",
- commit_message="Add model",
- use_temp_dir=True,
-)
-```
-
-Vale la pena spendere un po' di tempo per creare una model card ad-hoc per ogni checkpoint. Le model cards dovrebbero
-suggerire le caratteristiche specifiche del checkpoint, *per esempio* su che dataset il checkpoint Ă© stato pretrained o fine-tuned.
-O che su che genere di task il modello lavoro? E anche buona pratica includere del codice su come usare il modello correttamente.
-
-
-**13. (Opzionale) Aggiungere un notebook**
-
-Ă molto utile aggiungere un notebook, che dimostri in dettaglio come *brand_new_bert* si utilizzi per fare inferenza e/o
-fine-tuned su specifiche task. Non Ă© una cosa obbligatoria da avere nella vostra PR, ma Ă© molto utile per la community.
-
-**14. Sottomettere la PR**
-
-L'ultimissimo step! Ovvero il merge della PR nel main. Di solito il team Hugging face a questo punto vi avrĂ gia aiutato,
-ma Ă© ok prendere un po' di tempo per pulire la descirzione e commenti nel codice.
-
-
-### Condividete il vostro lavoro!!
-
-Ă ora tempo di prendere un po' di credito dalla communitĂ per il vostro lavoro! Caricare e implementare un nuovo modello
-Ă© un grandissimo contributo per Transformers e l'intera community NLP. Il codice e la conversione dei modelli pre-trained sara
-sicuramente utilizzato da centinaia o migliaia di sviluppatori e ricercatori. Siate fieri e orgogliosi di condividere il vostro
-traguardo con l'intera community :)
-
-** Avete create un altro modello che Ă© super facile da usare per tutti quanti nella community! đ€Ż**
diff --git a/docs/source/it/add_new_pipeline.md b/docs/source/it/add_new_pipeline.md
new file mode 100644
index 000000000000..adc1c3651a2c
--- /dev/null
+++ b/docs/source/it/add_new_pipeline.md
@@ -0,0 +1,250 @@
+
+
+# Come creare una pipeline personalizzata?
+
+In questa guida, scopriremo come creare una pipeline personalizzata e condividerla sull' [Hub](hf.co/models) o aggiungerla nella libreria
+Transformers.
+
+Innanzitutto, Ăš necessario decidere gli input grezzi che la pipeline sarĂ in grado di accettare. Possono essere strings, raw bytes,
+dictionaries o qualsiasi cosa sia l'input desiderato piĂč probabile. Cerca di mantenere questi input il piĂč possibile in Python
+in quanto facilita la compatibilitĂ (anche con altri linguaggi tramite JSON). Questi saranno gli `inputs` della
+pipeline (`preprocess`).
+
+Poi definire gli `outputs`. Stessa strategia degli `inputs`. PiĂč Ăš seplice e meglio Ăš. Questi saranno gli output del metodo
+`postprocess`.
+
+Si parte ereditando la classe base `Pipeline`. con i 4 metodi che bisogna implementare `preprocess`,
+`_forward`, `postprocess` e `_sanitize_parameters`.
+
+
+```python
+from transformers import Pipeline
+
+
+class MyPipeline(Pipeline):
+ def _sanitize_parameters(self, **kwargs):
+ preprocess_kwargs = {}
+ if "maybe_arg" in kwargs:
+ preprocess_kwargs["maybe_arg"] = kwargs["maybe_arg"]
+ return preprocess_kwargs, {}, {}
+
+ def preprocess(self, inputs, maybe_arg=2):
+ model_input = Tensor(inputs["input_ids"])
+ return {"model_input": model_input}
+
+ def _forward(self, model_inputs):
+ # model_inputs == {"model_input": model_input}
+ outputs = self.model(**model_inputs)
+ # Maybe {"logits": Tensor(...)}
+ return outputs
+
+ def postprocess(self, model_outputs):
+ best_class = model_outputs["logits"].softmax(-1)
+ return best_class
+```
+
+La struttura di questa suddivisione consiste nel supportare in modo relativamente continuo CPU/GPU, supportando allo stesso tempo l'esecuzione di
+pre/postelaborazione sulla CPU su thread diversi.
+
+`preprocess` prenderĂ gli input originariamente definiti e li trasformerĂ in qualcosa di alimentabile dal modello. Potrebbe
+contenere piĂč informazioni e di solito Ăš un `Dict`.
+
+`_forward` Ăš il dettaglio dell'implementazione e non Ăš destinato a essere chiamato direttamente. `forward` Ăš il metodo preferito per assicurarsi che tutto funzioni correttamente perchĂš contiene delle slavaguardie. Se qualcosa Ăš
+Ăš collegato a un modello reale, appartiene al metodo `_forward`, tutto il resto Ăš nel preprocess/postprocess.
+
+`postprocess` prende l'otput di `_forward` e lo trasforma nell'output finale che era stato deciso in precedenza.
+
+`_sanitize_parameters` esiste per consentire agli utenti di passare i parametri ogni volta che desiderano sia a inizialization time `pipeline(...., maybe_arg=4)` che al call time `pipe = pipeline(...); output = pipe(...., maybe_arg=4)`.
+
+`_sanitize_parameters` ritorna 3 dicts di kwargs che vengono passati direttamente a `preprocess`,
+`_forward` e `postprocess`. Non riempire nulla se il chiamante non ha chiamato con alcun parametro aggiuntivo. Questo
+consente di mantenere gli argomenti predefiniti nella definizione della funzione, che Ăš sempre piĂč "naturale".
+
+Un esempio classico potrebbe essere l'argomento `top_k` nel post processing dei classification tasks.
+
+```python
+>>> pipe = pipeline("my-new-task")
+>>> pipe("This is a test")
+[{"label": "1-star", "score": 0.8}, {"label": "2-star", "score": 0.1}, {"label": "3-star", "score": 0.05}
+{"label": "4-star", "score": 0.025}, {"label": "5-star", "score": 0.025}]
+
+>>> pipe("This is a test", top_k=2)
+[{"label": "1-star", "score": 0.8}, {"label": "2-star", "score": 0.1}]
+```
+
+In order to achieve that, we'll update our `postprocess` method with a default parameter to `5`. and edit
+`_sanitize_parameters` to allow this new parameter.
+
+
+```python
+def postprocess(self, model_outputs, top_k=5):
+ best_class = model_outputs["logits"].softmax(-1)
+ # Add logic to handle top_k
+ return best_class
+
+
+def _sanitize_parameters(self, **kwargs):
+ preprocess_kwargs = {}
+ if "maybe_arg" in kwargs:
+ preprocess_kwargs["maybe_arg"] = kwargs["maybe_arg"]
+
+ postprocess_kwargs = {}
+ if "top_k" in kwargs:
+ postprocess_kwargs["top_k"] = kwargs["top_k"]
+ return preprocess_kwargs, {}, postprocess_kwargs
+```
+
+Cercare di mantenere gli input/output molto semplici e idealmente serializzabili in JSON, in quanto ciĂČ rende l'uso della pipeline molto facile
+senza richiedere agli utenti di comprendere nuovi tipi di oggetti. Ă anche relativamente comune supportare molti tipi di argomenti
+per facilitarne l'uso (ad esempio file audio, possono essere nomi di file, URL o byte puri).
+
+## Aggiungilo alla lista dei tasks supportati
+
+Per registrar il tuo `new-task` alla lista dei tasks supportati, devi aggiungerlo al `PIPELINE_REGISTRY`:
+
+```python
+from transformers.pipelines import PIPELINE_REGISTRY
+
+PIPELINE_REGISTRY.register_pipeline(
+ "new-task",
+ pipeline_class=MyPipeline,
+ pt_model=AutoModelForSequenceClassification,
+)
+```
+
+Puoi specificare il modello di default che desideri, in questo caso dovrebbe essere accompagnato da una revisione specifica (che puĂČ essere il nome di un branch o l'hash di un commit, in questo caso abbiamo preso `"abcdef"`) e anche dal type:
+
+```python
+PIPELINE_REGISTRY.register_pipeline(
+ "new-task",
+ pipeline_class=MyPipeline,
+ pt_model=AutoModelForSequenceClassification,
+ default={"pt": ("user/awesome_model", "abcdef")},
+ type="text", # current support type: text, audio, image, multimodal
+)
+```
+
+## Condividi la tua pipeline sull'Hub
+
+Per condividere la tua pipeline personalizzata sull'Hub, devi solo salvare il codice della tua sottoclasse `Pipeline` in un file
+python. Per esempio, supponiamo di voler utilizzare una pipeline personalizzata per la classificazione delle coppie di frasi come la seguente:
+
+```py
+import numpy as np
+
+from transformers import Pipeline
+
+
+def softmax(outputs):
+ maxes = np.max(outputs, axis=-1, keepdims=True)
+ shifted_exp = np.exp(outputs - maxes)
+ return shifted_exp / shifted_exp.sum(axis=-1, keepdims=True)
+
+
+class PairClassificationPipeline(Pipeline):
+ def _sanitize_parameters(self, **kwargs):
+ preprocess_kwargs = {}
+ if "second_text" in kwargs:
+ preprocess_kwargs["second_text"] = kwargs["second_text"]
+ return preprocess_kwargs, {}, {}
+
+ def preprocess(self, text, second_text=None):
+ return self.tokenizer(text, text_pair=second_text, return_tensors=self.framework)
+
+ def _forward(self, model_inputs):
+ return self.model(**model_inputs)
+
+ def postprocess(self, model_outputs):
+ logits = model_outputs.logits[0].numpy()
+ probabilities = softmax(logits)
+
+ best_class = np.argmax(probabilities)
+ label = self.model.config.id2label[best_class]
+ score = probabilities[best_class].item()
+ logits = logits.tolist()
+ return {"label": label, "score": score, "logits": logits}
+```
+
+L'implementazione Ăš agnostica al framework, e lavorerĂ sia con modelli PyTorch che con TensorFlow. Se l'abbiamo salvato in un file chiamato `pair_classification.py`, puĂČ essere successivamente importato e registrato in questo modo:
+
+```py
+from pair_classification import PairClassificationPipeline
+from transformers.pipelines import PIPELINE_REGISTRY
+from transformers import AutoModelForSequenceClassification, TFAutoModelForSequenceClassification
+
+PIPELINE_REGISTRY.register_pipeline(
+ "pair-classification",
+ pipeline_class=PairClassificationPipeline,
+ pt_model=AutoModelForSequenceClassification,
+ tf_model=TFAutoModelForSequenceClassification,
+)
+```
+
+Una volta fatto, possiamo usarla con un modello pretrained. L'istanza `sgugger/finetuned-bert-mrpc` Ăš stata
+fine-tuned sul dataset MRPC, che classifica le coppie di frasi come parafrasi o no.
+
+```py
+from transformers import pipeline
+
+classifier = pipeline("pair-classification", model="sgugger/finetuned-bert-mrpc")
+```
+
+Successivamente possiamo condividerlo sull'Hub usando il metodo `save_pretrained` in un `Repository`:
+
+```py
+from huggingface_hub import Repository
+
+repo = Repository("test-dynamic-pipeline", clone_from="{your_username}/test-dynamic-pipeline")
+classifier.save_pretrained("test-dynamic-pipeline")
+repo.push_to_hub()
+```
+
+Questo codice copierĂ il file dove Ăš stato definitp `PairClassificationPipeline` all'interno della cartella `"test-dynamic-pipeline"`,
+insieme al salvataggio del modello e del tokenizer della pipeline, prima di pushare il tutto nel repository
+`{your_username}/test-dynamic-pipeline`. Dopodiché chiunque potrà utilizzarlo, purché fornisca l'opzione
+`trust_remote_code=True`:
+
+```py
+from transformers import pipeline
+
+classifier = pipeline(model="{your_username}/test-dynamic-pipeline", trust_remote_code=True)
+```
+
+## Aggiungere la pipeline a Transformers
+
+Se vuoi contribuire con la tua pipeline a Transformers, dovrai aggiungere un modulo nel sottomodulo `pipelines`
+con il codice della tua pipeline, quindi aggiungilo all'elenco dei tasks definiti in `pipelines/__init__.py`.
+
+Poi hai bisogno di aggiungere i test. Crea un nuovo file `tests/test_pipelines_MY_PIPELINE.py` con esempi ed altri test.
+
+La funzione `run_pipeline_test` sarĂ molto generica e su piccoli modelli casuali su ogni possibile
+architettura, come definito da `model_mapping` e `tf_model_mapping`.
+
+Questo Ăš molto importante per testare la compatibilitĂ futura, nel senso che se qualcuno aggiunge un nuovo modello di
+`XXXForQuestionAnswering` allora il test della pipeline tenterà di essere eseguito su di esso. Poiché i modelli sono casuali, Ú
+Ăš impossibile controllare i valori effettivi, per questo esiste un aiuto `ANY` che tenterĂ solamente di far corrispondere l'output della pipeline TYPE.
+
+Hai anche *bisogno* di implementare 2 (idealmente 4) test.
+
+- `test_small_model_pt` : Definire 1 piccolo modello per questa pipeline (non importa se i risultati non hanno senso)
+ e testare i risultati della pipeline. I risultati dovrebbero essere gli stessi di `test_small_model_tf`.
+- `test_small_model_tf` : Definire 1 piccolo modello per questa pipeline (non importa se i risultati non hanno senso)
+ e testare i risultati della pipeline. I risultati dovrebbero essere gli stessi di `test_small_model_pt`.
+- `test_large_model_pt` (`optional`): Testare la pipeline su una pipeline reale in cui i risultati dovrebbero avere
+ senso. Questi test sono lenti e dovrebbero essere contrassegnati come tali. In questo caso l'obiettivo Ăš mostrare la pipeline e assicurarsi che non ci siano derive nelle versioni future
+- `test_large_model_tf` (`optional`): Testare la pipeline su una pipeline reale in cui i risultati dovrebbero avere
+ senso. Questi test sono lenti e dovrebbero essere contrassegnati come tali. In questo caso l'obiettivo Ăš mostrare la pipeline e assicurarsi
+ che non ci siano derive nelle versioni future
\ No newline at end of file
diff --git a/docs/source/it/add_new_pipeline.mdx b/docs/source/it/add_new_pipeline.mdx
deleted file mode 100644
index cf9acd2902fc..000000000000
--- a/docs/source/it/add_new_pipeline.mdx
+++ /dev/null
@@ -1,246 +0,0 @@
-
-
-# Come creare una pipeline personalizzata?
-
-In questa guida, scopriremo come creare una pipeline personalizzata e condividerla sull' [Hub](hf.co/models) o aggiungerla nella libreria
-Transformers.
-
-Innanzitutto, Ăš necessario decidere gli input grezzi che la pipeline sarĂ in grado di accettare. Possono essere strings, raw bytes,
-dictionaries o qualsiasi cosa sia l'input desiderato piĂč probabile. Cerca di mantenere questi input il piĂč possibile in Python
-in quanto facilita la compatibilitĂ (anche con altri linguaggi tramite JSON). Questi saranno gli `inputs` della
-pipeline (`preprocess`).
-
-Poi definire gli `outputs`. Stessa strategia degli `inputs`. PiĂč Ăš seplice e meglio Ăš. Questi saranno gli output del metodo
-`postprocess`.
-
-Si parte ereditando la classe base `Pipeline`. con i 4 metodi che bisogna implementare `preprocess`,
-`_forward`, `postprocess` e `_sanitize_parameters`.
-
-
-```python
-from transformers import Pipeline
-
-
-class MyPipeline(Pipeline):
- def _sanitize_parameters(self, **kwargs):
- preprocess_kwargs = {}
- if "maybe_arg" in kwargs:
- preprocess_kwargs["maybe_arg"] = kwargs["maybe_arg"]
- return preprocess_kwargs, {}, {}
-
- def preprocess(self, inputs, maybe_arg=2):
- model_input = Tensor(inputs["input_ids"])
- return {"model_input": model_input}
-
- def _forward(self, model_inputs):
- # model_inputs == {"model_input": model_input}
- outputs = self.model(**model_inputs)
- # Maybe {"logits": Tensor(...)}
- return outputs
-
- def postprocess(self, model_outputs):
- best_class = model_outputs["logits"].softmax(-1)
- return best_class
-```
-
-La struttura di questa suddivisione consiste nel supportare in modo relativamente continuo CPU/GPU, supportando allo stesso tempo l'esecuzione di
-pre/postelaborazione sulla CPU su thread diversi.
-
-`preprocess` prenderĂ gli input originariamente definiti e li trasformerĂ in qualcosa di alimentabile dal modello. Potrebbe
-contenere piĂč informazioni e di solito Ăš un `Dict`.
-
-`_forward` Ăš il dettaglio dell'implementazione e non Ăš destinato a essere chiamato direttamente. `forward` Ăš il metodo preferito per assicurarsi che tutto funzioni correttamente perchĂš contiene delle slavaguardie. Se qualcosa Ăš
-Ăš collegato a un modello reale, appartiene al metodo `_forward`, tutto il resto Ăš nel preprocess/postprocess.
-
-`postprocess` prende l'otput di `_forward` e lo trasforma nell'output finale che era stato deciso in precedenza.
-
-`_sanitize_parameters` esiste per consentire agli utenti di passare i parametri ogni volta che desiderano sia a inizialization time `pipeline(...., maybe_arg=4)` che al call time `pipe = pipeline(...); output = pipe(...., maybe_arg=4)`.
-
-`_sanitize_parameters` ritorna 3 dicts di kwargs che vengono passati direttamente a `preprocess`,
-`_forward` e `postprocess`. Non riempire nulla se il chiamante non ha chiamato con alcun parametro aggiuntivo. Questo
-consente di mantenere gli argomenti predefiniti nella definizione della funzione, che Ăš sempre piĂč "naturale".
-
-Un esempio classico potrebbe essere l'argomento `top_k` nel post processing dei classification tasks.
-
-```python
->>> pipe = pipeline("my-new-task")
->>> pipe("This is a test")
-[{"label": "1-star", "score": 0.8}, {"label": "2-star", "score": 0.1}, {"label": "3-star", "score": 0.05}
-{"label": "4-star", "score": 0.025}, {"label": "5-star", "score": 0.025}]
-
->>> pipe("This is a test", top_k=2)
-[{"label": "1-star", "score": 0.8}, {"label": "2-star", "score": 0.1}]
-```
-
-In order to achieve that, we'll update our `postprocess` method with a default parameter to `5`. and edit
-`_sanitize_parameters` to allow this new parameter.
-
-
-```python
-def postprocess(self, model_outputs, top_k=5):
- best_class = model_outputs["logits"].softmax(-1)
- # Add logic to handle top_k
- return best_class
-
-
-def _sanitize_parameters(self, **kwargs):
- preprocess_kwargs = {}
- if "maybe_arg" in kwargs:
- preprocess_kwargs["maybe_arg"] = kwargs["maybe_arg"]
-
- postprocess_kwargs = {}
- if "top_k" in kwargs:
- postprocess_kwargs["top_k"] = kwargs["top_k"]
- return preprocess_kwargs, {}, postprocess_kwargs
-```
-
-Cercare di mantenere gli input/output molto semplici e idealmente serializzabili in JSON, in quanto ciĂČ rende l'uso della pipeline molto facile
-senza richiedere agli utenti di comprendere nuovi tipi di oggetti. Ă anche relativamente comune supportare molti tipi di argomenti
-per facilitarne l'uso (ad esempio file audio, possono essere nomi di file, URL o byte puri).
-
-## Aggiungilo alla lista dei tasks supportati
-
-Per registrar il tuo `new-task` alla lista dei tasks supportati, devi aggiungerlo al `PIPELINE_REGISTRY`:
-
-```python
-from transformers.pipelines import PIPELINE_REGISTRY
-
-PIPELINE_REGISTRY.register_pipeline(
- "new-task",
- pipeline_class=MyPipeline,
- pt_model=AutoModelForSequenceClassification,
-)
-```
-
-Puoi specificare il modello di default che desideri, in questo caso dovrebbe essere accompagnato da una revisione specifica (che puĂČ essere il nome di un branch o l'hash di un commit, in questo caso abbiamo preso `"abcdef"`) e anche dal type:
-
-```python
-PIPELINE_REGISTRY.register_pipeline(
- "new-task",
- pipeline_class=MyPipeline,
- pt_model=AutoModelForSequenceClassification,
- default={"pt": ("user/awesome_model", "abcdef")},
- type="text", # current support type: text, audio, image, multimodal
-)
-```
-
-## Condividi la tua pipeline sull'Hub
-
-Per condividere la tua pipeline personalizzata sull'Hub, devi solo salvare il codice della tua sottoclasse `Pipeline` in un file
-python. Per esempio, supponiamo di voler utilizzare una pipeline personalizzata per la classificazione delle coppie di frasi come la seguente:
-
-```py
-import numpy as np
-
-from transformers import Pipeline
-
-
-def softmax(outputs):
- maxes = np.max(outputs, axis=-1, keepdims=True)
- shifted_exp = np.exp(outputs - maxes)
- return shifted_exp / shifted_exp.sum(axis=-1, keepdims=True)
-
-
-class PairClassificationPipeline(Pipeline):
- def _sanitize_parameters(self, **kwargs):
- preprocess_kwargs = {}
- if "second_text" in kwargs:
- preprocess_kwargs["second_text"] = kwargs["second_text"]
- return preprocess_kwargs, {}, {}
-
- def preprocess(self, text, second_text=None):
- return self.tokenizer(text, text_pair=second_text, return_tensors=self.framework)
-
- def _forward(self, model_inputs):
- return self.model(**model_inputs)
-
- def postprocess(self, model_outputs):
- logits = model_outputs.logits[0].numpy()
- probabilities = softmax(logits)
-
- best_class = np.argmax(probabilities)
- label = self.model.config.id2label[best_class]
- score = probabilities[best_class].item()
- logits = logits.tolist()
- return {"label": label, "score": score, "logits": logits}
-```
-
-L'implementazione Ăš agnostica al framework, e lavorerĂ sia con modelli PyTorch che con TensorFlow. Se l'abbiamo salvato in un file chiamato `pair_classification.py`, puĂČ essere successivamente importato e registrato in questo modo:
-
-```py
-from pair_classification import PairClassificationPipeline
-from transformers.pipelines import PIPELINE_REGISTRY
-from transformers import AutoModelForSequenceClassification, TFAutoModelForSequenceClassification
-
-PIPELINE_REGISTRY.register_pipeline(
- "pair-classification",
- pipeline_class=PairClassificationPipeline,
- pt_model=AutoModelForSequenceClassification,
- tf_model=TFAutoModelForSequenceClassification,
-)
-```
-
-Una volta fatto, possiamo usarla con un modello pretrained. L'istanza `sgugger/finetuned-bert-mrpc` Ăš stata
-fine-tuned sul dataset MRPC, che classifica le coppie di frasi come parafrasi o no.
-
-```py
-from transformers import pipeline
-
-classifier = pipeline("pair-classification", model="sgugger/finetuned-bert-mrpc")
-```
-
-Successivamente possiamo condividerlo sull'Hub usando il metodo `save_pretrained` in un `Repository`:
-
-```py
-from huggingface_hub import Repository
-
-repo = Repository("test-dynamic-pipeline", clone_from="{your_username}/test-dynamic-pipeline")
-classifier.save_pretrained("test-dynamic-pipeline")
-repo.push_to_hub()
-```
-
-Questo codice copierĂ il file dove Ăš stato definitp `PairClassificationPipeline` all'interno della cartella `"test-dynamic-pipeline"`,
-insieme al salvataggio del modello e del tokenizer della pipeline, prima di pushare il tutto nel repository
-`{your_username}/test-dynamic-pipeline`. Dopodiché chiunque potrà utilizzarlo, purché fornisca l'opzione
-`trust_remote_code=True`:
-
-```py
-from transformers import pipeline
-
-classifier = pipeline(model="{your_username}/test-dynamic-pipeline", trust_remote_code=True)
-```
-
-## Aggiungere la pipeline a Transformers
-
-Se vuoi contribuire con la tua pipeline a Transformers, dovrai aggiungere un modulo nel sottomodulo `pipelines`
-con il codice della tua pipeline, quindi aggiungilo all'elenco dei tasks definiti in `pipelines/__init__.py`.
-
-Poi hai bisogno di aggiungere i test. Crea un nuovo file `tests/test_pipelines_MY_PIPELINE.py` con esempi ed altri test.
-
-La funzione `run_pipeline_test` sarĂ molto generica e su piccoli modelli casuali su ogni possibile
-architettura, come definito da `model_mapping` e `tf_model_mapping`.
-
-Questo Ăš molto importante per testare la compatibilitĂ futura, nel senso che se qualcuno aggiunge un nuovo modello di
-`XXXForQuestionAnswering` allora il test della pipeline tenterà di essere eseguito su di esso. Poiché i modelli sono casuali, Ú
-Ăš impossibile controllare i valori effettivi, per questo esiste un aiuto `ANY` che tenterĂ solamente di far corrispondere l'output della pipeline TYPE.
-
-Hai anche *bisogno* di implementare 2 (idealmente 4) test.
-
-- `test_small_model_pt` : Definire 1 piccolo modello per questa pipeline (non importa se i risultati non hanno senso)
- e testare i risultati della pipeline. I risultati dovrebbero essere gli stessi di `test_small_model_tf`.
-- `test_small_model_tf` : Definire 1 piccolo modello per questa pipeline (non importa se i risultati non hanno senso)
- e testare i risultati della pipeline. I risultati dovrebbero essere gli stessi di `test_small_model_pt`.
-- `test_large_model_pt` (`optional`): Testare la pipeline su una pipeline reale in cui i risultati dovrebbero avere
- senso. Questi test sono lenti e dovrebbero essere contrassegnati come tali. In questo caso l'obiettivo Ăš mostrare la pipeline e assicurarsi che non ci siano derive nelle versioni future
-- `test_large_model_tf` (`optional`): Testare la pipeline su una pipeline reale in cui i risultati dovrebbero avere
- senso. Questi test sono lenti e dovrebbero essere contrassegnati come tali. In questo caso l'obiettivo Ăš mostrare la pipeline e assicurarsi
- che non ci siano derive nelle versioni future
\ No newline at end of file
diff --git a/docs/source/it/autoclass_tutorial.md b/docs/source/it/autoclass_tutorial.md
new file mode 100644
index 000000000000..51621d098302
--- /dev/null
+++ b/docs/source/it/autoclass_tutorial.md
@@ -0,0 +1,123 @@
+
+
+# Carica istanze pre-allenate con AutoClass
+
+Con cosĂŹ tante architetture Transformer differenti, puĂČ essere sfidante crearne una per il tuo checkpoint. Come parte della filosofia centrale di đ€ Transformers per rendere la libreria facile, semplice e flessibile da utilizzare, una `AutoClass` inferisce e carica automaticamente l'architettura corretta da un dato checkpoint. Il metodo `from_pretrained` ti permette di caricare velocemente un modello pre-allenato per qualsiasi architettura, cosĂŹ non devi utilizzare tempo e risorse per allenare un modello da zero. Produrre questo codice agnostico ai checkpoint significa che se il tuo codice funziona per un checkpoint, funzionerĂ anche per un altro checkpoint, purchĂ© sia stato allenato per un compito simile, anche se l'architettura Ăš differente.
+
+
+
+Ricorda, con architettura ci si riferisce allo scheletro del modello e con checkpoint ai pesi di una determinata architettura. Per esempio, [BERT](https://huggingface.co/bert-base-uncased) Ăš un'architettura, mentre `bert-base-uncased` Ăš un checkpoint. Modello Ăš un termine generale che puĂČ significare sia architettura che checkpoint.
+
+
+
+In questo tutorial, imparerai a:
+
+* Caricare un tokenizer pre-allenato.
+* Caricare un estrattore di caratteristiche (feature extractor, in inglese) pre-allenato.
+* Caricare un processore pre-allenato.
+* Caricare un modello pre-allenato.
+
+## AutoTokenizer
+
+Quasi tutti i compiti di NLP iniziano con un tokenizer. Un tokenizer converte il tuo input in un formato che possa essere elaborato dal modello.
+
+Carica un tokenizer con [`AutoTokenizer.from_pretrained`]:
+
+```py
+>>> from transformers import AutoTokenizer
+
+>>> tokenizer = AutoTokenizer.from_pretrained("xlm-roberta-base")
+```
+
+Poi tokenizza il tuo input come mostrato in seguito:
+
+```py
+>>> sequenza = "In un buco nel terreno viveva uno Hobbit."
+>>> print(tokenizer(sequenza))
+{'input_ids': [0, 360, 51, 373, 587, 1718, 54644, 22597, 330, 3269, 2291, 22155, 18, 5, 2],
+ 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}
+```
+
+## AutoFeatureExtractor
+
+Per compiti inerenti a audio e video, un feature extractor processa il segnale audio o l'immagine nel formato di input corretto.
+
+Carica un feature extractor con [`AutoFeatureExtractor.from_pretrained`]:
+
+```py
+>>> from transformers import AutoFeatureExtractor
+
+>>> feature_extractor = AutoFeatureExtractor.from_pretrained(
+... "ehcalabres/wav2vec2-lg-xlsr-en-speech-emotion-recognition"
+... )
+```
+
+## AutoProcessor
+
+Compiti multimodali richiedono un processore che combini i due tipi di strumenti di elaborazione. Per esempio, il modello [LayoutLMV2](model_doc/layoutlmv2) richiede un feature extractor per gestire le immagine e un tokenizer per gestire il testo; un processore li combina entrambi.
+
+Carica un processore con [`AutoProcessor.from_pretrained`]:
+
+```py
+>>> from transformers import AutoProcessor
+
+>>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv2-base-uncased")
+```
+
+## AutoModel
+
+
+
+Infine, le classi `AutoModelFor` ti permettono di caricare un modello pre-allenato per un determinato compito (guarda [qui](model_doc/auto) per una lista completa di compiti presenti). Per esempio, carica un modello per la classificazione di sequenze con [`AutoModelForSequenceClassification.from_pretrained`]:
+
+```py
+>>> from transformers import AutoModelForSequenceClassification
+
+>>> model = AutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased")
+```
+
+Semplicemente utilizza lo stesso checkpoint per caricare un'architettura per un task differente:
+
+```py
+>>> from transformers import AutoModelForTokenClassification
+
+>>> model = AutoModelForTokenClassification.from_pretrained("distilbert-base-uncased")
+```
+
+Generalmente, raccomandiamo di utilizzare la classe `AutoTokenizer` e la classe `AutoModelFor` per caricare istanze pre-allenate dei modelli. Questo ti assicurerĂ di aver caricato la corretta architettura ogni volta. Nel prossimo [tutorial](preprocessing), imparerai come utilizzare il tokenizer, il feature extractor e il processore per elaborare un dataset per il fine-tuning.
+
+
+
+Infine, le classi `TFAutoModelFor` ti permettono di caricare un modello pre-allenato per un determinato compito (guarda [qui](model_doc/auto) per una lista completa di compiti presenti). Per esempio, carica un modello per la classificazione di sequenze con [`TFAutoModelForSequenceClassification.from_pretrained`]:
+
+```py
+>>> from transformers import TFAutoModelForSequenceClassification
+
+>>> model = TFAutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased")
+```
+
+Semplicemente utilizza lo stesso checkpoint per caricare un'architettura per un task differente:
+
+```py
+>>> from transformers import TFAutoModelForTokenClassification
+
+>>> model = TFAutoModelForTokenClassification.from_pretrained("distilbert-base-uncased")
+```
+
+Generalmente, raccomandiamo di utilizzare la classe `AutoTokenizer` e la classe `TFAutoModelFor` per caricare istanze pre-allenate dei modelli. Questo ti assicurerĂ di aver caricato la corretta architettura ogni volta. Nel prossimo [tutorial](preprocessing), imparerai come utilizzare il tokenizer, il feature extractor e il processore per elaborare un dataset per il fine-tuning.
+
+
diff --git a/docs/source/it/autoclass_tutorial.mdx b/docs/source/it/autoclass_tutorial.mdx
deleted file mode 100644
index 88dd6cad6c42..000000000000
--- a/docs/source/it/autoclass_tutorial.mdx
+++ /dev/null
@@ -1,119 +0,0 @@
-
-
-# Carica istanze pre-allenate con AutoClass
-
-Con cosĂŹ tante architetture Transformer differenti, puĂČ essere sfidante crearne una per il tuo checkpoint. Come parte della filosofia centrale di đ€ Transformers per rendere la libreria facile, semplice e flessibile da utilizzare, una `AutoClass` inferisce e carica automaticamente l'architettura corretta da un dato checkpoint. Il metodo `from_pretrained` ti permette di caricare velocemente un modello pre-allenato per qualsiasi architettura, cosĂŹ non devi utilizzare tempo e risorse per allenare un modello da zero. Produrre questo codice agnostico ai checkpoint significa che se il tuo codice funziona per un checkpoint, funzionerĂ anche per un altro checkpoint, purchĂ© sia stato allenato per un compito simile, anche se l'architettura Ăš differente.
-
-
-
-Ricorda, con architettura ci si riferisce allo scheletro del modello e con checkpoint ai pesi di una determinata architettura. Per esempio, [BERT](https://huggingface.co/bert-base-uncased) Ăš un'architettura, mentre `bert-base-uncased` Ăš un checkpoint. Modello Ăš un termine generale che puĂČ significare sia architettura che checkpoint.
-
-
-
-In questo tutorial, imparerai a:
-
-* Caricare un tokenizer pre-allenato.
-* Caricare un estrattore di caratteristiche (feature extractor, in inglese) pre-allenato.
-* Caricare un processore pre-allenato.
-* Caricare un modello pre-allenato.
-
-## AutoTokenizer
-
-Quasi tutti i compiti di NLP iniziano con un tokenizer. Un tokenizer converte il tuo input in un formato che possa essere elaborato dal modello.
-
-Carica un tokenizer con [`AutoTokenizer.from_pretrained`]:
-
-```py
->>> from transformers import AutoTokenizer
-
->>> tokenizer = AutoTokenizer.from_pretrained("xlm-roberta-base")
-```
-
-Poi tokenizza il tuo input come mostrato in seguito:
-
-```py
->>> sequenza = "In un buco nel terreno viveva uno Hobbit."
->>> print(tokenizer(sequenza))
-{'input_ids': [0, 360, 51, 373, 587, 1718, 54644, 22597, 330, 3269, 2291, 22155, 18, 5, 2],
- 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}
-```
-
-## AutoFeatureExtractor
-
-Per compiti inerenti a audio e video, un feature extractor processa il segnale audio o l'immagine nel formato di input corretto.
-
-Carica un feature extractor con [`AutoFeatureExtractor.from_pretrained`]:
-
-```py
->>> from transformers import AutoFeatureExtractor
-
->>> feature_extractor = AutoFeatureExtractor.from_pretrained(
-... "ehcalabres/wav2vec2-lg-xlsr-en-speech-emotion-recognition"
-... )
-```
-
-## AutoProcessor
-
-Compiti multimodali richiedono un processore che combini i due tipi di strumenti di elaborazione. Per esempio, il modello [LayoutLMV2](model_doc/layoutlmv2) richiede un feature extractor per gestire le immagine e un tokenizer per gestire il testo; un processore li combina entrambi.
-
-Carica un processore con [`AutoProcessor.from_pretrained`]:
-
-```py
->>> from transformers import AutoProcessor
-
->>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv2-base-uncased")
-```
-
-## AutoModel
-
-
-
-Infine, le classi `AutoModelFor` ti permettono di caricare un modello pre-allenato per un determinato compito (guarda [qui](model_doc/auto) per una lista completa di compiti presenti). Per esempio, carica un modello per la classificazione di sequenze con [`AutoModelForSequenceClassification.from_pretrained`]:
-
-```py
->>> from transformers import AutoModelForSequenceClassification
-
->>> model = AutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased")
-```
-
-Semplicemente utilizza lo stesso checkpoint per caricare un'architettura per un task differente:
-
-```py
->>> from transformers import AutoModelForTokenClassification
-
->>> model = AutoModelForTokenClassification.from_pretrained("distilbert-base-uncased")
-```
-
-Generalmente, raccomandiamo di utilizzare la classe `AutoTokenizer` e la classe `AutoModelFor` per caricare istanze pre-allenate dei modelli. Questo ti assicurerĂ di aver caricato la corretta architettura ogni volta. Nel prossimo [tutorial](preprocessing), imparerai come utilizzare il tokenizer, il feature extractor e il processore per elaborare un dataset per il fine-tuning.
-
-
-
-Infine, le classi `TFAutoModelFor` ti permettono di caricare un modello pre-allenato per un determinato compito (guarda [qui](model_doc/auto) per una lista completa di compiti presenti). Per esempio, carica un modello per la classificazione di sequenze con [`TFAutoModelForSequenceClassification.from_pretrained`]:
-
-```py
->>> from transformers import TFAutoModelForSequenceClassification
-
->>> model = TFAutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased")
-```
-
-Semplicemente utilizza lo stesso checkpoint per caricare un'architettura per un task differente:
-
-```py
->>> from transformers import TFAutoModelForTokenClassification
-
->>> model = TFAutoModelForTokenClassification.from_pretrained("distilbert-base-uncased")
-```
-
-Generalmente, raccomandiamo di utilizzare la classe `AutoTokenizer` e la classe `TFAutoModelFor` per caricare istanze pre-allenate dei modelli. Questo ti assicurerĂ di aver caricato la corretta architettura ogni volta. Nel prossimo [tutorial](preprocessing), imparerai come utilizzare il tokenizer, il feature extractor e il processore per elaborare un dataset per il fine-tuning.
-
-
diff --git a/docs/source/it/big_models.md b/docs/source/it/big_models.md
new file mode 100644
index 000000000000..cd0fd9017d9d
--- /dev/null
+++ b/docs/source/it/big_models.md
@@ -0,0 +1,123 @@
+
+
+# Istanziare un big model
+
+Quando vuoi utilizzare un modello preaddestrato (pretrained) molto grande, una sfida Ăš minimizzare l'uso della RAM. Il workflow classico
+in PyTorch Ăš:
+
+1. Crea il tuo modello con pesi casuali (random weights).
+2. Carica i tuoi pesi preaddestrati.
+3. Inserisci i pesi preaddestrati nel tuo modello casuale.
+
+I passi 1 e 2 una versione completa del modello in memoria, in molti casi non Ăš un problema, ma se il modello inizia a pesare diversi GigaBytes, queste due copie possono sturare la nostra RAM. Ancora peggio, se stai usando `torch.distributed` per seguire l'addestramento (training) in distribuito, ogni processo caricherĂ il modello preaddestrato e memorizzerĂ queste due copie nella RAM.
+
+
+
+Nota che il modello creato casualmente Ăš inizializzato con tensori "vuoti", che occupano spazio in memoria ma senza riempirlo (quindi i valori casuali sono quelli che si trovavano in questa porzione di memoria in un determinato momento). L'inizializzazione casuale che segue la distribuzione appropriata per il tipo di modello/parametri istanziato (come la distribuzione normale per le istanze) Ăš eseguito solo dopo il passaggio 3 sui pesi non inizializzati, per essere piĂč rapido possibile!
+
+
+
+In questa guida, esploreremo le soluzioni che Transformers offre per affrontare questo problema. C'Ăš da tenere in conto che questa Ăš un'area in cui si sta attualmente sviluppando, quindi le API spiegate qui possono variare velocemente in futuro.
+
+## Checkpoints condivisi
+
+Dalla versione 4.18.0, i checkpoints dei modelli che occupano piĂč di 10GB di spazio vengono automaticamente frammentati in piĂč parti. Per quanto riguarda la possibilitĂ di avere un unico checkpoint quando si utilizza `model.save_pretrained(save_dir)`, si hanno diversi checkpoint parziali (ognuno con dimensione < 10GB) e un indice che mappa i nomi dei parametri ai file in cui sono memorizzati.
+
+Puoi controllare la dimensione massima dopo la frammentazione con il parametro `max_shard_size`, nel prossimo esempio, useremo modelli di dimensioni normali con frammenti di piccoli dimensioni: prendiamo un modello BERT classico.
+
+```py
+from transformers import AutoModel
+
+model = AutoModel.from_pretrained("bert-base-cased")
+```
+
+Se tu salvi usando [`~PreTrainedModel.save_pretrained`], avrai una nuova cartella con due file: il config del modello e i suoi pesi:
+
+```py
+>>> import os
+>>> import tempfile
+
+>>> with tempfile.TemporaryDirectory() as tmp_dir:
+... model.save_pretrained(tmp_dir)
+... print(sorted(os.listdir(tmp_dir)))
+['config.json', 'pytorch_model.bin']
+```
+
+Adesso usiamo una dimensione massima di frammentazione di 200MB:
+
+```py
+>>> with tempfile.TemporaryDirectory() as tmp_dir:
+... model.save_pretrained(tmp_dir, max_shard_size="200MB")
+... print(sorted(os.listdir(tmp_dir)))
+['config.json', 'pytorch_model-00001-of-00003.bin', 'pytorch_model-00002-of-00003.bin', 'pytorch_model-00003-of-00003.bin', 'pytorch_model.bin.index.json']
+```
+
+In aggiunta alla configurazione del modello, vediamo tre differenti file dei pesi, e un file `index.json` che Ăš il nostro indice. Un checkpoint puĂČ essere ricaricato totalmente usando il metodo [`~PreTrainedModel.from_pretrained`]:
+
+```py
+>>> with tempfile.TemporaryDirectory() as tmp_dir:
+... model.save_pretrained(tmp_dir, max_shard_size="200MB")
+... new_model = AutoModel.from_pretrained(tmp_dir)
+```
+
+Il vantaggio principale di applicare questo metodo per modelli grandi Ăš che durante il passo 2 del workflow illustrato in precedenza, ogni frammento del checkpoint viene caricato dopo il precedente, limitando l'utilizzo della RAM alla dimensione del modello piĂč la dimensione del frammento piĂč grande.
+
+Dietro le quinte, il file indice Ăš utilizzato per determinare quali chiavi sono nel checkpoint, e dove i corrispondenti pesi sono memorizzati. Possiamo caricare l'indice come un qualsiasi json e ottenere un dizionario:
+
+```py
+>>> import json
+
+>>> with tempfile.TemporaryDirectory() as tmp_dir:
+... model.save_pretrained(tmp_dir, max_shard_size="200MB")
+... with open(os.path.join(tmp_dir, "pytorch_model.bin.index.json"), "r") as f:
+... index = json.load(f)
+
+>>> print(index.keys())
+dict_keys(['metadata', 'weight_map'])
+```
+
+I metadati consistono solo nella dimensione totale del modello per ora. Abbiamo in programma di aggiungere altre informazioni in futuro:
+
+```py
+>>> index["metadata"]
+{'total_size': 433245184}
+```
+
+La mappa dei pesi Ăš la parte principale di questo indice, che mappa ogni nome dei parametri (si trova solitamente nei modelli PyTorch come `state_dict`) al file in cui Ăš memorizzato:
+
+```py
+>>> index["weight_map"]
+{'embeddings.LayerNorm.bias': 'pytorch_model-00001-of-00003.bin',
+ 'embeddings.LayerNorm.weight': 'pytorch_model-00001-of-00003.bin',
+ ...
+```
+
+Se vuoi caricare direttamente un checkpoint frammentato in un modello senza usare [`~PreTrainedModel.from_pretrained`] (come si farebbe con `model.load_state_dict()` per un checkpoint completo) devi usare [`~modeling_utils.load_sharded_checkpoint`]:
+
+```py
+>>> from transformers.modeling_utils import load_sharded_checkpoint
+
+>>> with tempfile.TemporaryDirectory() as tmp_dir:
+... model.save_pretrained(tmp_dir, max_shard_size="200MB")
+... load_sharded_checkpoint(model, tmp_dir)
+```
+
+## Caricamento low memory
+
+Frammentare i checkpoint l'utilizzo di memoria al passo 2 del workflow citato in precedenza, ma per utilizzare questo modello in un ambiente con poca memoria, consigliamo di utilizzare i nostri strumenti basati sulla libreria Accelerate.
+
+Per ulteriori informazioni, leggere la seguente guida: [Large model loading using Accelerate](./main_classes/model#large-model-loading)
\ No newline at end of file
diff --git a/docs/source/it/big_models.mdx b/docs/source/it/big_models.mdx
deleted file mode 100644
index 56a0fa6fea4a..000000000000
--- a/docs/source/it/big_models.mdx
+++ /dev/null
@@ -1,119 +0,0 @@
-
-
-# Istanziare un big model
-
-Quando vuoi utilizzare un modello preaddestrato (pretrained) molto grande, una sfida Ăš minimizzare l'uso della RAM. Il workflow classico
-in PyTorch Ăš:
-
-1. Crea il tuo modello con pesi casuali (random weights).
-2. Carica i tuoi pesi preaddestrati.
-3. Inserisci i pesi preaddestrati nel tuo modello casuale.
-
-I passi 1 e 2 una versione completa del modello in memoria, in molti casi non Ăš un problema, ma se il modello inizia a pesare diversi GigaBytes, queste due copie possono sturare la nostra RAM. Ancora peggio, se stai usando `torch.distributed` per seguire l'addestramento (training) in distribuito, ogni processo caricherĂ il modello preaddestrato e memorizzerĂ queste due copie nella RAM.
-
-
-
-Nota che il modello creato casualmente Ăš inizializzato con tensori "vuoti", che occupano spazio in memoria ma senza riempirlo (quindi i valori casuali sono quelli che si trovavano in questa porzione di memoria in un determinato momento). L'inizializzazione casuale che segue la distribuzione appropriata per il tipo di modello/parametri istanziato (come la distribuzione normale per le istanze) Ăš eseguito solo dopo il passaggio 3 sui pesi non inizializzati, per essere piĂč rapido possibile!
-
-
-
-In questa guida, esploreremo le soluzioni che Transformers offre per affrontare questo problema. C'Ăš da tenere in conto che questa Ăš un'area in cui si sta attualmente sviluppando, quindi le API spiegate qui possono variare velocemente in futuro.
-
-## Checkpoints condivisi
-
-Dalla versione 4.18.0, i checkpoints dei modelli che occupano piĂč di 10GB di spazio vengono automaticamente frammentati in piĂč parti. Per quanto riguarda la possibilitĂ di avere un unico checkpoint quando si utilizza `model.save_pretrained(save_dir)`, si hanno diversi checkpoint parziali (ognuno con dimensione < 10GB) e un indice che mappa i nomi dei parametri ai file in cui sono memorizzati.
-
-Puoi controllare la dimensione massima dopo la frammentazione con il parametro `max_shard_size`, nel prossimo esempio, useremo modelli di dimensioni normali con frammenti di piccoli dimensioni: prendiamo un modello BERT classico.
-
-```py
-from transformers import AutoModel
-
-model = AutoModel.from_pretrained("bert-base-cased")
-```
-
-Se tu salvi usando [`~PreTrainedModel.save_pretrained`], avrai una nuova cartella con due file: il config del modello e i suoi pesi:
-
-```py
->>> import os
->>> import tempfile
-
->>> with tempfile.TemporaryDirectory() as tmp_dir:
-... model.save_pretrained(tmp_dir)
-... print(sorted(os.listdir(tmp_dir)))
-['config.json', 'pytorch_model.bin']
-```
-
-Adesso usiamo una dimensione massima di frammentazione di 200MB:
-
-```py
->>> with tempfile.TemporaryDirectory() as tmp_dir:
-... model.save_pretrained(tmp_dir, max_shard_size="200MB")
-... print(sorted(os.listdir(tmp_dir)))
-['config.json', 'pytorch_model-00001-of-00003.bin', 'pytorch_model-00002-of-00003.bin', 'pytorch_model-00003-of-00003.bin', 'pytorch_model.bin.index.json']
-```
-
-In aggiunta alla configurazione del modello, vediamo tre differenti file dei pesi, e un file `index.json` che Ăš il nostro indice. Un checkpoint puĂČ essere ricaricato totalmente usando il metodo [`~PreTrainedModel.from_pretrained`]:
-
-```py
->>> with tempfile.TemporaryDirectory() as tmp_dir:
-... model.save_pretrained(tmp_dir, max_shard_size="200MB")
-... new_model = AutoModel.from_pretrained(tmp_dir)
-```
-
-Il vantaggio principale di applicare questo metodo per modelli grandi Ăš che durante il passo 2 del workflow illustrato in precedenza, ogni frammento del checkpoint viene caricato dopo il precedente, limitando l'utilizzo della RAM alla dimensione del modello piĂč la dimensione del frammento piĂč grande.
-
-Dietro le quinte, il file indice Ăš utilizzato per determinare quali chiavi sono nel checkpoint, e dove i corrispondenti pesi sono memorizzati. Possiamo caricare l'indice come un qualsiasi json e ottenere un dizionario:
-
-```py
->>> import json
-
->>> with tempfile.TemporaryDirectory() as tmp_dir:
-... model.save_pretrained(tmp_dir, max_shard_size="200MB")
-... with open(os.path.join(tmp_dir, "pytorch_model.bin.index.json"), "r") as f:
-... index = json.load(f)
-
->>> print(index.keys())
-dict_keys(['metadata', 'weight_map'])
-```
-
-I metadati consistono solo nella dimensione totale del modello per ora. Abbiamo in programma di aggiungere altre informazioni in futuro:
-
-```py
->>> index["metadata"]
-{'total_size': 433245184}
-```
-
-La mappa dei pesi Ăš la parte principale di questo indice, che mappa ogni nome dei parametri (si trova solitamente nei modelli PyTorch come `state_dict`) al file in cui Ăš memorizzato:
-
-```py
->>> index["weight_map"]
-{'embeddings.LayerNorm.bias': 'pytorch_model-00001-of-00003.bin',
- 'embeddings.LayerNorm.weight': 'pytorch_model-00001-of-00003.bin',
- ...
-```
-
-Se vuoi caricare direttamente un checkpoint frammentato in un modello senza usare [`~PreTrainedModel.from_pretrained`] (come si farebbe con `model.load_state_dict()` per un checkpoint completo) devi usare [`~modeling_utils.load_sharded_checkpoint`]:
-
-```py
->>> from transformers.modeling_utils import load_sharded_checkpoint
-
->>> with tempfile.TemporaryDirectory() as tmp_dir:
-... model.save_pretrained(tmp_dir, max_shard_size="200MB")
-... load_sharded_checkpoint(model, tmp_dir)
-```
-
-## Caricamento low memory
-
-Frammentare i checkpoint l'utilizzo di memoria al passo 2 del workflow citato in precedenza, ma per utilizzare questo modello in un ambiente con poca memoria, consigliamo di utilizzare i nostri strumenti basati sulla libreria Accelerate.
-
-Per ulteriori informazioni, leggere la seguente guida: [Large model loading using Accelerate](./main_classes/model#large-model-loading)
\ No newline at end of file
diff --git a/docs/source/it/community.md b/docs/source/it/community.md
new file mode 100644
index 000000000000..2f3c0c8a82b4
--- /dev/null
+++ b/docs/source/it/community.md
@@ -0,0 +1,68 @@
+
+
+# ComunitĂ
+
+Questa pagina raggruppa le risorse sviluppate dalla comunitĂ riguardo đ€ Transformers.
+
+## Risorse della comunitĂ :
+
+| Risorsa | Descrizione | Autore |
+|:----------|:-------------|------:|
+| [Glossario delle Flashcards di Transformers](https://www.darigovresearch.com/huggingface-transformers-glossary-flashcards) | Un insieme di flashcards basate sul [glossario della documentazione di Transformers](glossary), creato in un formato tale da permettere un facile apprendimento e revisione usando [Anki](https://apps.ankiweb.net/), un'applicazione open-source e multi-piattaforma, specificatamente progettata per ricordare informazioni nel lungo termine. Guarda questo [video introduttivo su come usare le flashcards](https://www.youtube.com/watch?v=Dji_h7PILrw). | [Darigov Research](https://www.darigovresearch.com/) |
+
+## Notebook della comunitĂ :
+
+| Notebook | Descrizione | Autore | |
+|:----------|:-------------|:-------------|------:|
+| [Fine-tuning di un Transformer pre-addestrato, al fine di generare testi di canzoni](https://github.com/AlekseyKorshuk/huggingartists) | Come generare testi di canzoni nello stile del vostro artista preferito attraverso il fine-tuning di un modello GPT-2. | [Aleksey Korshuk](https://github.com/AlekseyKorshuk) | [](https://colab.research.google.com/github/AlekseyKorshuk/huggingartists/blob/master/huggingartists-demo.ipynb) |
+| [Addestramento di T5 in Tensorflow 2 ](https://github.com/snapthat/TF-T5-text-to-text) | Come addestrare T5 per qualsiasi attivitĂ usando Tensorflow 2. Questo notebook mostra come risolvere l'attivitĂ di "Question Answering" usando Tensorflow 2 e SQUAD. | [Muhammad Harris](https://github.com/HarrisDePerceptron) |[](https://colab.research.google.com/github/snapthat/TF-T5-text-to-text/blob/master/snapthatT5/notebooks/TF-T5-Datasets%20Training.ipynb) |
+| [Addestramento di T5 con TPU](https://github.com/patil-suraj/exploring-T5/blob/master/T5_on_TPU.ipynb) | Come addestrare T5 su SQUAD con Transformers e NLP. | [Suraj Patil](https://github.com/patil-suraj) |[](https://colab.research.google.com/github/patil-suraj/exploring-T5/blob/master/T5_on_TPU.ipynb#scrollTo=QLGiFCDqvuil) |
+| [Fine-tuning di T5 per la classificazione e scelta multipla](https://github.com/patil-suraj/exploring-T5/blob/master/t5_fine_tuning.ipynb) | Come effettuare il fine-tuning di T5 per le attivitĂ di classificazione a scelta multipla - usando un formato testo-a-testo - con PyTorch Lightning. | [Suraj Patil](https://github.com/patil-suraj) | [](https://colab.research.google.com/github/patil-suraj/exploring-T5/blob/master/t5_fine_tuning.ipynb) |
+| [Fine-tuning di DialoGPT su nuovi dataset e lingue](https://github.com/ncoop57/i-am-a-nerd/blob/master/_notebooks/2020-05-12-chatbot-part-1.ipynb) | Come effettuare il fine-tuning di un modello DialoGPT su un nuovo dataset per chatbots conversazionali open-dialog. | [Nathan Cooper](https://github.com/ncoop57) | [](https://colab.research.google.com/github/ncoop57/i-am-a-nerd/blob/master/_notebooks/2020-05-12-chatbot-part-1.ipynb) |
+| [Modellamento di una lunga sequenza con Reformer](https://github.com/patrickvonplaten/notebooks/blob/master/PyTorch_Reformer.ipynb) | Come addestrare su sequenze di lunghezza fino a 500 mila token con Reformer. | [Patrick von Platen](https://github.com/patrickvonplaten) | [](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/PyTorch_Reformer.ipynb) |
+| [Fine-tuning di BART per riassumere testi](https://github.com/ohmeow/ohmeow_website/blob/master/_notebooks/2020-05-23-text-generation-with-blurr.ipynb) | Come effettuare il fine-tuning di BART per riassumere testi con fastai usando blurr. | [Wayde Gilliam](https://ohmeow.com/) | [](https://colab.research.google.com/github/ohmeow/ohmeow_website/blob/master/_notebooks/2020-05-23-text-generation-with-blurr.ipynb) |
+| [Fine-tuning di un Transformer pre-addestrato su tweet](https://colab.research.google.com/github/borisdayma/huggingtweets/blob/master/huggingtweets-demo.ipynb) | Come generare tweet nello stile del tuo account Twitter preferito attraverso il fine-tuning di un modello GPT-2. | [Boris Dayma](https://github.com/borisdayma) | [](https://colab.research.google.com/github/borisdayma/huggingtweets/blob/master/huggingtweets-demo.ipynb) |
+| [Ottimizzazione di modelli đ€ Hugging Face con Weights & Biases](https://colab.research.google.com/github/wandb/examples/blob/master/colabs/huggingface/Optimize_Hugging_Face_models_with_Weights_%26_Biases.ipynb) | Un tutorial completo che mostra l'integrazione di W&B con Hugging Face. | [Boris Dayma](https://github.com/borisdayma) | [](https://colab.research.google.com/github/wandb/examples/blob/master/colabs/huggingface/Optimize_Hugging_Face_models_with_Weights_%26_Biases.ipynb) |
+| [Longformer pre-addestrato](https://github.com/allenai/longformer/blob/master/scripts/convert_model_to_long.ipynb) | Come costruire una versione "long" degli esistenti modelli pre-addestrati. | [Iz Beltagy](https://beltagy.net) | [](https://colab.research.google.com/github/allenai/longformer/blob/master/scripts/convert_model_to_long.ipynb) |
+| [Fine-tuning di Longformer per QA](https://github.com/patil-suraj/Notebooks/blob/master/longformer_qa_training.ipynb) | Come effettuare il fine-tuning di un modello longformer per un task di QA.| [Suraj Patil](https://github.com/patil-suraj) | [](https://colab.research.google.com/github/patil-suraj/Notebooks/blob/master/longformer_qa_training.ipynb) |
+| [Valutazione di modelli con đ€NLP](https://github.com/patrickvonplaten/notebooks/blob/master/How_to_evaluate_Longformer_on_TriviaQA_using_NLP.ipynb) | Come valutare longformer su TriviaQA con `NLP`. | [Patrick von Platen](https://github.com/patrickvonplaten) | [](https://colab.research.google.com/drive/1m7eTGlPmLRgoPkkA7rkhQdZ9ydpmsdLE?usp=sharing) |
+| [Fine-tuning di T5 per Sentiment Span Extraction](https://github.com/enzoampil/t5-intro/blob/master/t5_qa_training_pytorch_span_extraction.ipynb) | Come effettuare il fine-tuning di T5 per la sentiment span extraction - usando un formato testo-a-testo - con PyTorch Lightning. | [Lorenzo Ampil](https://github.com/enzoampil) | [](https://colab.research.google.com/github/enzoampil/t5-intro/blob/master/t5_qa_training_pytorch_span_extraction.ipynb) |
+| [Fine-tuning di DistilBert per la classificazione multi-classe](https://github.com/abhimishra91/transformers-tutorials/blob/master/transformers_multiclass_classification.ipynb) | Come effettuare il fine-tuning di DistilBert per la classificazione multi-classe con PyTorch. | [Abhishek Kumar Mishra](https://github.com/abhimishra91) | [](https://colab.research.google.com/github/abhimishra91/transformers-tutorials/blob/master/transformers_multiclass_classification.ipynb)|
+|[Fine-tuning di BERT per la classificazione multi-etichetta](https://github.com/abhimishra91/transformers-tutorials/blob/master/transformers_multi_label_classification.ipynb)|Come effettuare il fine-tuning di BERT per la classificazione multi-etichetta con PyTorch. |[Abhishek Kumar Mishra](https://github.com/abhimishra91) |[](https://colab.research.google.com/github/abhimishra91/transformers-tutorials/blob/master/transformers_multi_label_classification.ipynb)|
+|[Accelerazione del fine-tuning con il Dynamic Padding / Bucketing](https://github.com/ELS-RD/transformers-notebook/blob/master/Divide_Hugging_Face_Transformers_training_time_by_2_or_more.ipynb)| Come velocizzare il fine-tuning di un fattore 2X usando il dynamic padding / bucketing. |[Michael Benesty](https://github.com/pommedeterresautee) |[](https://colab.research.google.com/drive/1CBfRU1zbfu7-ijiOqAAQUA-RJaxfcJoO?usp=sharing)|
+|[Pre-addestramento di Reformer per Masked Language Modeling](https://github.com/patrickvonplaten/notebooks/blob/master/Reformer_For_Masked_LM.ipynb)| Come addestrare un modello Reformer usando livelli di self-attention bi-direzionali.| [Patrick von Platen](https://github.com/patrickvonplaten) | [](https://colab.research.google.com/drive/1tzzh0i8PgDQGV3SMFUGxM7_gGae3K-uW?usp=sharing)|
+|[Espansione e fine-tuning di Sci-BERT](https://github.com/lordtt13/word-embeddings/blob/master/COVID-19%20Research%20Data/COVID-SciBERT.ipynb)| Come incrementare il vocabolario di un modello SciBERT - pre-addestrato da AllenAI sul dataset CORD - e crearne una pipeline. | [Tanmay Thakur](https://github.com/lordtt13) | [](https://colab.research.google.com/drive/1rqAR40goxbAfez1xvF3hBJphSCsvXmh8)|
+|[Fine-tuning di BlenderBotSmall per riassumere testi usando Trainer API](https://github.com/lordtt13/transformers-experiments/blob/master/Custom%20Tasks/fine-tune-blenderbot_small-for-summarization.ipynb)| Come effettuare il fine-tuning di BlenderBotSmall per riassumere testi su un dataset personalizzato, usando Trainer API. | [Tanmay Thakur](https://github.com/lordtt13) | [](https://colab.research.google.com/drive/19Wmupuls7mykSGyRN_Qo6lPQhgp56ymq?usp=sharing)|
+|[Fine-tuning di Electra e interpretazione con Integrated Gradients](https://github.com/elsanns/xai-nlp-notebooks/blob/master/electra_fine_tune_interpret_captum_ig.ipynb) | Come effettuare il fine-tuning di Electra per l'analisi dei sentimenti e intepretare le predizioni con Captum Integrated Gradients. | [Eliza Szczechla](https://elsanns.github.io) | [](https://colab.research.google.com/github/elsanns/xai-nlp-notebooks/blob/master/electra_fine_tune_interpret_captum_ig.ipynb)|
+|[Fine-tuning di un modello GPT-2 non inglese con la classe Trainer](https://github.com/philschmid/fine-tune-GPT-2/blob/master/Fine_tune_a_non_English_GPT_2_Model_with_Huggingface.ipynb) | Come effettuare il fine-tuning di un modello GPT-2 non inglese con la classe Trainer. | [Philipp Schmid](https://www.philschmid.de) | [](https://colab.research.google.com/github/philschmid/fine-tune-GPT-2/blob/master/Fine_tune_a_non_English_GPT_2_Model_with_Huggingface.ipynb)|
+|[Fine-tuning di un modello DistilBERT per la classficazione multi-etichetta](https://github.com/DhavalTaunk08/Transformers_scripts/blob/master/Transformers_multilabel_distilbert.ipynb) | Come effettuare il fine-tuning di un modello DistilBERT per l'attivitĂ di classificazione multi-etichetta. | [Dhaval Taunk](https://github.com/DhavalTaunk08) | [](https://colab.research.google.com/github/DhavalTaunk08/Transformers_scripts/blob/master/Transformers_multilabel_distilbert.ipynb)|
+|[Fine-tuning di ALBERT per la classifcazione di coppie di frasi](https://github.com/NadirEM/nlp-notebooks/blob/master/Fine_tune_ALBERT_sentence_pair_classification.ipynb) | Come effettuare il fine-tuning di un modello ALBERT - o un altro modello BERT-based - per l'attivitĂ di classificazione di coppie di frasi. | [Nadir El Manouzi](https://github.com/NadirEM) | [](https://colab.research.google.com/github/NadirEM/nlp-notebooks/blob/master/Fine_tune_ALBERT_sentence_pair_classification.ipynb)|
+|[Fine-tuning di Roberta per l'analisi di sentimenti](https://github.com/DhavalTaunk08/NLP_scripts/blob/master/sentiment_analysis_using_roberta.ipynb) | Come effettuare il fine-tuning di un modello Roberta per l'analisi di sentimenti. | [Dhaval Taunk](https://github.com/DhavalTaunk08) | [](https://colab.research.google.com/github/DhavalTaunk08/NLP_scripts/blob/master/sentiment_analysis_using_roberta.ipynb)|
+|[Valutazione di modelli che generano domande](https://github.com/flexudy-pipe/qugeev) | Quanto sono accurante le risposte alle domande generate dal tuo modello transformer seq2seq? | [Pascal Zoleko](https://github.com/zolekode) | [](https://colab.research.google.com/drive/1bpsSqCQU-iw_5nNoRm_crPq6FRuJthq_?usp=sharing)|
+|[Classificazione di testo con DistilBERT e Tensorflow](https://github.com/peterbayerle/huggingface_notebook/blob/main/distilbert_tf.ipynb) | Come effettuare il fine-tuning di DistilBERT per la classificazione di testo in TensorFlow. | [Peter Bayerle](https://github.com/peterbayerle) | [](https://colab.research.google.com/github/peterbayerle/huggingface_notebook/blob/main/distilbert_tf.ipynb)|
+|[Utilizzo di BERT per riassumere testi con un modello Encoder-Decoder su CNN/Dailymail](https://github.com/patrickvonplaten/notebooks/blob/master/BERT2BERT_for_CNN_Dailymail.ipynb) | Come avviare "a caldo" un *EncoderDecoderModel* attraverso l'utilizzo di un checkpoint *bert-base-uncased* per riassumere testi su CNN/Dailymail. | [Patrick von Platen](https://github.com/patrickvonplaten) | [](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/BERT2BERT_for_CNN_Dailymail.ipynb)|
+|[Utilizzo di RoBERTa per riassumere testi con un modello Encoder-Decoder su BBC XSum](https://github.com/patrickvonplaten/notebooks/blob/master/RoBERTaShared_for_BBC_XSum.ipynb) | Come avviare "a caldo" un *EncoderDecoderModel* (condiviso) attraverso l'utilizzo di un checkpoint *roberta-base* per riassumere testi su BBC/XSum. | [Patrick von Platen](https://github.com/patrickvonplaten) | [](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/RoBERTaShared_for_BBC_XSum.ipynb)|
+|[Fine-tuning di TAPAS su Sequential Question Answering (SQA)](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/TAPAS/Fine_tuning_TapasForQuestionAnswering_on_SQA.ipynb) | Come effettuare il fine-tuning di un modello *TapasForQuestionAnswering* attraverso l'utilizzo di un checkpoint *tapas-base* sul dataset Sequential Question Answering (SQA). | [Niels Rogge](https://github.com/nielsrogge) | [](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/TAPAS/Fine_tuning_TapasForQuestionAnswering_on_SQA.ipynb)|
+|[Valutazione di TAPAS su Table Fact Checking (TabFact)](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/TAPAS/Evaluating_TAPAS_on_the_Tabfact_test_set.ipynb) | Come valutare un modello *TapasForSequenceClassification* - fine-tuned con un checkpoint *tapas-base-finetuned-tabfact* - usando una combinazione delle librerie đ€ datasets e đ€ transformers. | [Niels Rogge](https://github.com/nielsrogge) | [](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/TAPAS/Evaluating_TAPAS_on_the_Tabfact_test_set.ipynb)|
+|[Fine-tuning di mBART per la traduzione](https://colab.research.google.com/github/vasudevgupta7/huggingface-tutorials/blob/main/translation_training.ipynb) | Come effettuare il fine-tuning di mBART usando Seq2SeqTrainer per la traduzione da hindi a inglese.| [Vasudev Gupta](https://github.com/vasudevgupta7) | [](https://colab.research.google.com/github/vasudevgupta7/huggingface-tutorials/blob/main/translation_training.ipynb)|
+|[Fine-tuning di LayoutLM su FUNSD (un dataset per la comprensione della forma)](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/LayoutLM/Fine_tuning_LayoutLMForTokenClassification_on_FUNSD.ipynb) | Come effettuare il fine-tuning di un modello *LayoutLMForTokenClassification* sul dataset FUNSD per l'estrazione di informazioni da documenti scannerizzati.| [Niels Rogge](https://github.com/nielsrogge) | [](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/LayoutLM/Fine_tuning_LayoutLMForTokenClassification_on_FUNSD.ipynb)|
+|[Fine-tuning di DistilGPT2 e generazione di testo](https://colab.research.google.com/github/tripathiaakash/DistilGPT2-Tutorial/blob/main/distilgpt2_fine_tuning.ipynb) | Come effettuare il fine-tuning di DistilGPT2 e generare testo. | [Aakash Tripathi](https://github.com/tripathiaakash) | [](https://colab.research.google.com/github/tripathiaakash/DistilGPT2-Tutorial/blob/main/distilgpt2_fine_tuning.ipynb)|
+|[Fine-tuning di LED fino a 8 mila token](https://github.com/patrickvonplaten/notebooks/blob/master/Fine_tune_Longformer_Encoder_Decoder_(LED)_for_Summarization_on_pubmed.ipynb) | Come effettuare il fine-tuning di LED su PubMed per riassumere "lunghi" testi. | [Patrick von Platen](https://github.com/patrickvonplaten) | [](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/Fine_tune_Longformer_Encoder_Decoder_(LED)_for_Summarization_on_pubmed.ipynb)|
+|[Valutazione di LED su Arxiv](https://github.com/patrickvonplaten/notebooks/blob/master/LED_on_Arxiv.ipynb) | Come valutare efficacemente LED sull'attivitĂ di riassumere "lunghi" testi. | [Patrick von Platen](https://github.com/patrickvonplaten) | [](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/LED_on_Arxiv.ipynb)|
+|[Fine-tuning di LayoutLM su RVL-CDIP, un dataset per la classificazione di documenti (immagini)](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/LayoutLM/Fine_tuning_LayoutLMForSequenceClassification_on_RVL_CDIP.ipynb) | Come effettuare il fine-tuning di un modello *LayoutLMForSequenceClassification* sul dataset RVL-CDIP per la classificazione di documenti scannerizzati. | [Niels Rogge](https://github.com/nielsrogge) | [](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/LayoutLM/Fine_tuning_LayoutLMForSequenceClassification_on_RVL_CDIP.ipynb)|
+|[Decodifica Wav2Vec2 CTC con variazioni di GPT2](https://github.com/voidful/huggingface_notebook/blob/main/xlsr_gpt.ipynb) | Come decodificare sequenze CTC, variate da modelli di linguaggio. | [Eric Lam](https://github.com/voidful) | [](https://colab.research.google.com/drive/1e_z5jQHYbO2YKEaUgzb1ww1WwiAyydAj?usp=sharing)
+|[Fine-tuning di BART per riassumere testi in due lingue con la classe Trainer](https://github.com/elsanns/xai-nlp-notebooks/blob/master/fine_tune_bart_summarization_two_langs.ipynb) | Come effettuare il fine-tuning di BART per riassumere testi in due lingue usando la classe Trainer. | [Eliza Szczechla](https://github.com/elsanns) | [](https://colab.research.google.com/github/elsanns/xai-nlp-notebooks/blob/master/fine_tune_bart_summarization_two_langs.ipynb)|
+|[Valutazione di Big Bird su Trivia QA](https://github.com/patrickvonplaten/notebooks/blob/master/Evaluating_Big_Bird_on_TriviaQA.ipynb) | Come valutare BigBird su question answering di "lunghi" documenti attraverso Trivia QA. | [Patrick von Platen](https://github.com/patrickvonplaten) | [](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/Evaluating_Big_Bird_on_TriviaQA.ipynb)|
+| [Creazione di sottotitoli per video usando Wav2Vec2](https://github.com/Muennighoff/ytclipcc/blob/main/wav2vec_youtube_captions.ipynb) | Come creare sottotitoli per qualsiasi video di YouTube trascrivendo l'audio con Wav2Vec. | [Niklas Muennighoff](https://github.com/Muennighoff) |[](https://colab.research.google.com/github/Muennighoff/ytclipcc/blob/main/wav2vec_youtube_captions.ipynb) |
+| [Fine-tuning di Vision Transformer su CIFAR-10 usando PyTorch Lightning](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/VisionTransformer/Fine_tuning_the_Vision_Transformer_on_CIFAR_10_with_PyTorch_Lightning.ipynb) | Come effettuare il fine-tuning di Vision Transformer (ViT) su CIFAR-10 usando HuggingFace Transformers, Datasets e PyTorch Lightning.| [Niels Rogge](https://github.com/nielsrogge) |[](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/VisionTransformer/Fine_tuning_the_Vision_Transformer_on_CIFAR_10_with_PyTorch_Lightning.ipynb) |
+| [Fine-tuning di Vision Transformer su CIFAR-10 usando đ€ Trainer](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/VisionTransformer/Fine_tuning_the_Vision_Transformer_on_CIFAR_10_with_the_%F0%9F%A4%97_Trainer.ipynb) | Come effettuare il fine-tuning di Vision Transformer (ViT) su CIFAR-10 usando HuggingFace Transformers, Datasets e đ€ Trainer. | [Niels Rogge](https://github.com/nielsrogge) |[](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/VisionTransformer/Fine_tuning_the_Vision_Transformer_on_CIFAR_10_with_the_%F0%9F%A4%97_Trainer.ipynb) |
+| [Valutazione di LUKE su Open Entity, un dataset di entity typing](https://github.com/studio-ousia/luke/blob/master/notebooks/huggingface_open_entity.ipynb) | Come valutare un modello *LukeForEntityClassification* sul dataset Open Entity. | [Ikuya Yamada](https://github.com/ikuyamada) |[](https://colab.research.google.com/github/studio-ousia/luke/blob/master/notebooks/huggingface_open_entity.ipynb) |
+| [Valutazione di LUKE su TACRED, un dataset per l'estrazione di relazioni](https://github.com/studio-ousia/luke/blob/master/notebooks/huggingface_tacred.ipynb) | Come valutare un modello *LukeForEntityPairClassification* sul dataset TACRED. | [Ikuya Yamada](https://github.com/ikuyamada) |[](https://colab.research.google.com/github/studio-ousia/luke/blob/master/notebooks/huggingface_tacred.ipynb) |
+| [Valutazione di LUKE su CoNLL-2003, un importante benchmark NER](https://github.com/studio-ousia/luke/blob/master/notebooks/huggingface_conll_2003.ipynb) | Come valutare un modello *LukeForEntitySpanClassification* sul dataset CoNLL-2003. | [Ikuya Yamada](https://github.com/ikuyamada) |[](https://colab.research.google.com/github/studio-ousia/luke/blob/master/notebooks/huggingface_conll_2003.ipynb) |
+| [Valutazione di BigBird-Pegasus su dataset PubMed](https://github.com/vasudevgupta7/bigbird/blob/main/notebooks/bigbird_pegasus_evaluation.ipynb) | Come valutare un modello *BigBirdPegasusForConditionalGeneration* su dataset PubMed. | [Vasudev Gupta](https://github.com/vasudevgupta7) | [](https://colab.research.google.com/github/vasudevgupta7/bigbird/blob/main/notebooks/bigbird_pegasus_evaluation.ipynb) |
+| [Classificazione di emozioni dal discorso con Wav2Vec2](https://github/m3hrdadfi/soxan/blob/main/notebooks/Emotion_recognition_in_Greek_speech_using_Wav2Vec2.ipynb) | Come utilizzare un modello pre-addestrato Wav2Vec2 per la classificazione di emozioni sul dataset MEGA. | [Mehrdad Farahani](https://github.com/m3hrdadfi) | [](https://colab.research.google.com/github/m3hrdadfi/soxan/blob/main/notebooks/Emotion_recognition_in_Greek_speech_using_Wav2Vec2.ipynb) |
+| [Rilevamento oggetti in un'immagine con DETR](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/DETR/DETR_minimal_example_(with_DetrFeatureExtractor).ipynb) | Come usare un modello addestrato *DetrForObjectDetection* per rilevare oggetti in un'immagine e visualizzare l'attention. | [Niels Rogge](https://github.com/NielsRogge) | [](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/DETR/DETR_minimal_example_(with_DetrFeatureExtractor).ipynb) |
+| [Fine-tuning di DETR su un dataset personalizzato per rilevare oggetti](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/DETR/Fine_tuning_DetrForObjectDetection_on_custom_dataset_(balloon).ipynb) | Come effettuare fine-tuning di un modello *DetrForObjectDetection* su un dataset personalizzato per rilevare oggetti. | [Niels Rogge](https://github.com/NielsRogge) | [](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/DETR/Fine_tuning_DetrForObjectDetection_on_custom_dataset_(balloon).ipynb) |
+| [Fine-tuning di T5 per Named Entity Recognition](https://github.com/ToluClassics/Notebooks/blob/main/T5_Ner_Finetuning.ipynb) | Come effettuare fine-tunining di *T5* per un'attivitĂ di Named Entity Recognition. | [Ogundepo Odunayo](https://github.com/ToluClassics) | [](https://colab.research.google.com/drive/1obr78FY_cBmWY5ODViCmzdY6O1KB65Vc?usp=sharing) |
diff --git a/docs/source/it/community.mdx b/docs/source/it/community.mdx
deleted file mode 100644
index 530e132014c7..000000000000
--- a/docs/source/it/community.mdx
+++ /dev/null
@@ -1,64 +0,0 @@
-ï»ż# ComunitĂ
-
-Questa pagina raggruppa le risorse sviluppate dalla comunitĂ riguardo đ€ Transformers.
-
-## Risorse della comunitĂ :
-
-| Risorsa | Descrizione | Autore |
-|:----------|:-------------|------:|
-| [Glossario delle Flashcards di Transformers](https://www.darigovresearch.com/huggingface-transformers-glossary-flashcards) | Un insieme di flashcards basate sul [glossario della documentazione di Transformers](glossary), creato in un formato tale da permettere un facile apprendimento e revisione usando [Anki](https://apps.ankiweb.net/), un'applicazione open-source e multi-piattaforma, specificatamente progettata per ricordare informazioni nel lungo termine. Guarda questo [video introduttivo su come usare le flashcards](https://www.youtube.com/watch?v=Dji_h7PILrw). | [Darigov Research](https://www.darigovresearch.com/) |
-
-## Notebook della comunitĂ :
-
-| Notebook | Descrizione | Autore | |
-|:----------|:-------------|:-------------|------:|
-| [Fine-tuning di un Transformer pre-addestrato, al fine di generare testi di canzoni](https://github.com/AlekseyKorshuk/huggingartists) | Come generare testi di canzoni nello stile del vostro artista preferito attraverso il fine-tuning di un modello GPT-2. | [Aleksey Korshuk](https://github.com/AlekseyKorshuk) | [](https://colab.research.google.com/github/AlekseyKorshuk/huggingartists/blob/master/huggingartists-demo.ipynb) |
-| [Addestramento di T5 in Tensorflow 2 ](https://github.com/snapthat/TF-T5-text-to-text) | Come addestrare T5 per qualsiasi attivitĂ usando Tensorflow 2. Questo notebook mostra come risolvere l'attivitĂ di "Question Answering" usando Tensorflow 2 e SQUAD. | [Muhammad Harris](https://github.com/HarrisDePerceptron) |[](https://colab.research.google.com/github/snapthat/TF-T5-text-to-text/blob/master/snapthatT5/notebooks/TF-T5-Datasets%20Training.ipynb) |
-| [Addestramento di T5 con TPU](https://github.com/patil-suraj/exploring-T5/blob/master/T5_on_TPU.ipynb) | Come addestrare T5 su SQUAD con Transformers e NLP. | [Suraj Patil](https://github.com/patil-suraj) |[](https://colab.research.google.com/github/patil-suraj/exploring-T5/blob/master/T5_on_TPU.ipynb#scrollTo=QLGiFCDqvuil) |
-| [Fine-tuning di T5 per la classificazione e scelta multipla](https://github.com/patil-suraj/exploring-T5/blob/master/t5_fine_tuning.ipynb) | Come effettuare il fine-tuning di T5 per le attivitĂ di classificazione a scelta multipla - usando un formato testo-a-testo - con PyTorch Lightning. | [Suraj Patil](https://github.com/patil-suraj) | [](https://colab.research.google.com/github/patil-suraj/exploring-T5/blob/master/t5_fine_tuning.ipynb) |
-| [Fine-tuning di DialoGPT su nuovi dataset e lingue](https://github.com/ncoop57/i-am-a-nerd/blob/master/_notebooks/2020-05-12-chatbot-part-1.ipynb) | Come effettuare il fine-tuning di un modello DialoGPT su un nuovo dataset per chatbots conversazionali open-dialog. | [Nathan Cooper](https://github.com/ncoop57) | [](https://colab.research.google.com/github/ncoop57/i-am-a-nerd/blob/master/_notebooks/2020-05-12-chatbot-part-1.ipynb) |
-| [Modellamento di una lunga sequenza con Reformer](https://github.com/patrickvonplaten/notebooks/blob/master/PyTorch_Reformer.ipynb) | Come addestrare su sequenze di lunghezza fino a 500 mila token con Reformer. | [Patrick von Platen](https://github.com/patrickvonplaten) | [](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/PyTorch_Reformer.ipynb) |
-| [Fine-tuning di BART per riassumere testi](https://github.com/ohmeow/ohmeow_website/blob/master/_notebooks/2020-05-23-text-generation-with-blurr.ipynb) | Come effettuare il fine-tuning di BART per riassumere testi con fastai usando blurr. | [Wayde Gilliam](https://ohmeow.com/) | [](https://colab.research.google.com/github/ohmeow/ohmeow_website/blob/master/_notebooks/2020-05-23-text-generation-with-blurr.ipynb) |
-| [Fine-tuning di un Transformer pre-addestrato su tweet](https://colab.research.google.com/github/borisdayma/huggingtweets/blob/master/huggingtweets-demo.ipynb) | Come generare tweet nello stile del tuo account Twitter preferito attraverso il fine-tuning di un modello GPT-2. | [Boris Dayma](https://github.com/borisdayma) | [](https://colab.research.google.com/github/borisdayma/huggingtweets/blob/master/huggingtweets-demo.ipynb) |
-| [Ottimizzazione di modelli đ€ Hugging Face con Weights & Biases](https://colab.research.google.com/github/wandb/examples/blob/master/colabs/huggingface/Optimize_Hugging_Face_models_with_Weights_%26_Biases.ipynb) | Un tutorial completo che mostra l'integrazione di W&B con Hugging Face. | [Boris Dayma](https://github.com/borisdayma) | [](https://colab.research.google.com/github/wandb/examples/blob/master/colabs/huggingface/Optimize_Hugging_Face_models_with_Weights_%26_Biases.ipynb) |
-| [Longformer pre-addestrato](https://github.com/allenai/longformer/blob/master/scripts/convert_model_to_long.ipynb) | Come costruire una versione "long" degli esistenti modelli pre-addestrati. | [Iz Beltagy](https://beltagy.net) | [](https://colab.research.google.com/github/allenai/longformer/blob/master/scripts/convert_model_to_long.ipynb) |
-| [Fine-tuning di Longformer per QA](https://github.com/patil-suraj/Notebooks/blob/master/longformer_qa_training.ipynb) | Come effettuare il fine-tuning di un modello longformer per un task di QA.| [Suraj Patil](https://github.com/patil-suraj) | [](https://colab.research.google.com/github/patil-suraj/Notebooks/blob/master/longformer_qa_training.ipynb) |
-| [Valutazione di modelli con đ€NLP](https://github.com/patrickvonplaten/notebooks/blob/master/How_to_evaluate_Longformer_on_TriviaQA_using_NLP.ipynb) | Come valutare longformer su TriviaQA con `NLP`. | [Patrick von Platen](https://github.com/patrickvonplaten) | [](https://colab.research.google.com/drive/1m7eTGlPmLRgoPkkA7rkhQdZ9ydpmsdLE?usp=sharing) |
-| [Fine-tuning di T5 per Sentiment Span Extraction](https://github.com/enzoampil/t5-intro/blob/master/t5_qa_training_pytorch_span_extraction.ipynb) | Come effettuare il fine-tuning di T5 per la sentiment span extraction - usando un formato testo-a-testo - con PyTorch Lightning. | [Lorenzo Ampil](https://github.com/enzoampil) | [](https://colab.research.google.com/github/enzoampil/t5-intro/blob/master/t5_qa_training_pytorch_span_extraction.ipynb) |
-| [Fine-tuning di DistilBert per la classificazione multi-classe](https://github.com/abhimishra91/transformers-tutorials/blob/master/transformers_multiclass_classification.ipynb) | Come effettuare il fine-tuning di DistilBert per la classificazione multi-classe con PyTorch. | [Abhishek Kumar Mishra](https://github.com/abhimishra91) | [](https://colab.research.google.com/github/abhimishra91/transformers-tutorials/blob/master/transformers_multiclass_classification.ipynb)|
-|[Fine-tuning di BERT per la classificazione multi-etichetta](https://github.com/abhimishra91/transformers-tutorials/blob/master/transformers_multi_label_classification.ipynb)|Come effettuare il fine-tuning di BERT per la classificazione multi-etichetta con PyTorch. |[Abhishek Kumar Mishra](https://github.com/abhimishra91) |[](https://colab.research.google.com/github/abhimishra91/transformers-tutorials/blob/master/transformers_multi_label_classification.ipynb)|
-|[Accelerazione del fine-tuning con il Dynamic Padding / Bucketing](https://github.com/ELS-RD/transformers-notebook/blob/master/Divide_Hugging_Face_Transformers_training_time_by_2_or_more.ipynb)| Come velocizzare il fine-tuning di un fattore 2X usando il dynamic padding / bucketing. |[Michael Benesty](https://github.com/pommedeterresautee) |[](https://colab.research.google.com/drive/1CBfRU1zbfu7-ijiOqAAQUA-RJaxfcJoO?usp=sharing)|
-|[Pre-addestramento di Reformer per Masked Language Modeling](https://github.com/patrickvonplaten/notebooks/blob/master/Reformer_For_Masked_LM.ipynb)| Come addestrare un modello Reformer usando livelli di self-attention bi-direzionali.| [Patrick von Platen](https://github.com/patrickvonplaten) | [](https://colab.research.google.com/drive/1tzzh0i8PgDQGV3SMFUGxM7_gGae3K-uW?usp=sharing)|
-|[Espansione e fine-tuning di Sci-BERT](https://github.com/lordtt13/word-embeddings/blob/master/COVID-19%20Research%20Data/COVID-SciBERT.ipynb)| Come incrementare il vocabolario di un modello SciBERT - pre-addestrato da AllenAI sul dataset CORD - e crearne una pipeline. | [Tanmay Thakur](https://github.com/lordtt13) | [](https://colab.research.google.com/drive/1rqAR40goxbAfez1xvF3hBJphSCsvXmh8)|
-|[Fine-tuning di BlenderBotSmall per riassumere testi usando Trainer API](https://github.com/lordtt13/transformers-experiments/blob/master/Custom%20Tasks/fine-tune-blenderbot_small-for-summarization.ipynb)| Come effettuare il fine-tuning di BlenderBotSmall per riassumere testi su un dataset personalizzato, usando Trainer API. | [Tanmay Thakur](https://github.com/lordtt13) | [](https://colab.research.google.com/drive/19Wmupuls7mykSGyRN_Qo6lPQhgp56ymq?usp=sharing)|
-|[Fine-tuning di Electra e interpretazione con Integrated Gradients](https://github.com/elsanns/xai-nlp-notebooks/blob/master/electra_fine_tune_interpret_captum_ig.ipynb) | Come effettuare il fine-tuning di Electra per l'analisi dei sentimenti e intepretare le predizioni con Captum Integrated Gradients. | [Eliza Szczechla](https://elsanns.github.io) | [](https://colab.research.google.com/github/elsanns/xai-nlp-notebooks/blob/master/electra_fine_tune_interpret_captum_ig.ipynb)|
-|[Fine-tuning di un modello GPT-2 non inglese con la classe Trainer](https://github.com/philschmid/fine-tune-GPT-2/blob/master/Fine_tune_a_non_English_GPT_2_Model_with_Huggingface.ipynb) | Come effettuare il fine-tuning di un modello GPT-2 non inglese con la classe Trainer. | [Philipp Schmid](https://www.philschmid.de) | [](https://colab.research.google.com/github/philschmid/fine-tune-GPT-2/blob/master/Fine_tune_a_non_English_GPT_2_Model_with_Huggingface.ipynb)|
-|[Fine-tuning di un modello DistilBERT per la classficazione multi-etichetta](https://github.com/DhavalTaunk08/Transformers_scripts/blob/master/Transformers_multilabel_distilbert.ipynb) | Come effettuare il fine-tuning di un modello DistilBERT per l'attivitĂ di classificazione multi-etichetta. | [Dhaval Taunk](https://github.com/DhavalTaunk08) | [](https://colab.research.google.com/github/DhavalTaunk08/Transformers_scripts/blob/master/Transformers_multilabel_distilbert.ipynb)|
-|[Fine-tuning di ALBERT per la classifcazione di coppie di frasi](https://github.com/NadirEM/nlp-notebooks/blob/master/Fine_tune_ALBERT_sentence_pair_classification.ipynb) | Come effettuare il fine-tuning di un modello ALBERT - o un altro modello BERT-based - per l'attivitĂ di classificazione di coppie di frasi. | [Nadir El Manouzi](https://github.com/NadirEM) | [](https://colab.research.google.com/github/NadirEM/nlp-notebooks/blob/master/Fine_tune_ALBERT_sentence_pair_classification.ipynb)|
-|[Fine-tuning di Roberta per l'analisi di sentimenti](https://github.com/DhavalTaunk08/NLP_scripts/blob/master/sentiment_analysis_using_roberta.ipynb) | Come effettuare il fine-tuning di un modello Roberta per l'analisi di sentimenti. | [Dhaval Taunk](https://github.com/DhavalTaunk08) | [](https://colab.research.google.com/github/DhavalTaunk08/NLP_scripts/blob/master/sentiment_analysis_using_roberta.ipynb)|
-|[Valutazione di modelli che generano domande](https://github.com/flexudy-pipe/qugeev) | Quanto sono accurante le risposte alle domande generate dal tuo modello transformer seq2seq? | [Pascal Zoleko](https://github.com/zolekode) | [](https://colab.research.google.com/drive/1bpsSqCQU-iw_5nNoRm_crPq6FRuJthq_?usp=sharing)|
-|[Classificazione di testo con DistilBERT e Tensorflow](https://github.com/peterbayerle/huggingface_notebook/blob/main/distilbert_tf.ipynb) | Come effettuare il fine-tuning di DistilBERT per la classificazione di testo in TensorFlow. | [Peter Bayerle](https://github.com/peterbayerle) | [](https://colab.research.google.com/github/peterbayerle/huggingface_notebook/blob/main/distilbert_tf.ipynb)|
-|[Utilizzo di BERT per riassumere testi con un modello Encoder-Decoder su CNN/Dailymail](https://github.com/patrickvonplaten/notebooks/blob/master/BERT2BERT_for_CNN_Dailymail.ipynb) | Come avviare "a caldo" un *EncoderDecoderModel* attraverso l'utilizzo di un checkpoint *bert-base-uncased* per riassumere testi su CNN/Dailymail. | [Patrick von Platen](https://github.com/patrickvonplaten) | [](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/BERT2BERT_for_CNN_Dailymail.ipynb)|
-|[Utilizzo di RoBERTa per riassumere testi con un modello Encoder-Decoder su BBC XSum](https://github.com/patrickvonplaten/notebooks/blob/master/RoBERTaShared_for_BBC_XSum.ipynb) | Come avviare "a caldo" un *EncoderDecoderModel* (condiviso) attraverso l'utilizzo di un checkpoint *roberta-base* per riassumere testi su BBC/XSum. | [Patrick von Platen](https://github.com/patrickvonplaten) | [](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/RoBERTaShared_for_BBC_XSum.ipynb)|
-|[Fine-tuning di TAPAS su Sequential Question Answering (SQA)](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/TAPAS/Fine_tuning_TapasForQuestionAnswering_on_SQA.ipynb) | Come effettuare il fine-tuning di un modello *TapasForQuestionAnswering* attraverso l'utilizzo di un checkpoint *tapas-base* sul dataset Sequential Question Answering (SQA). | [Niels Rogge](https://github.com/nielsrogge) | [](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/TAPAS/Fine_tuning_TapasForQuestionAnswering_on_SQA.ipynb)|
-|[Valutazione di TAPAS su Table Fact Checking (TabFact)](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/TAPAS/Evaluating_TAPAS_on_the_Tabfact_test_set.ipynb) | Come valutare un modello *TapasForSequenceClassification* - fine-tuned con un checkpoint *tapas-base-finetuned-tabfact* - usando una combinazione delle librerie đ€ datasets e đ€ transformers. | [Niels Rogge](https://github.com/nielsrogge) | [](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/TAPAS/Evaluating_TAPAS_on_the_Tabfact_test_set.ipynb)|
-|[Fine-tuning di mBART per la traduzione](https://colab.research.google.com/github/vasudevgupta7/huggingface-tutorials/blob/main/translation_training.ipynb) | Come effettuare il fine-tuning di mBART usando Seq2SeqTrainer per la traduzione da hindi a inglese.| [Vasudev Gupta](https://github.com/vasudevgupta7) | [](https://colab.research.google.com/github/vasudevgupta7/huggingface-tutorials/blob/main/translation_training.ipynb)|
-|[Fine-tuning di LayoutLM su FUNSD (un dataset per la comprensione della forma)](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/LayoutLM/Fine_tuning_LayoutLMForTokenClassification_on_FUNSD.ipynb) | Come effettuare il fine-tuning di un modello *LayoutLMForTokenClassification* sul dataset FUNSD per l'estrazione di informazioni da documenti scannerizzati.| [Niels Rogge](https://github.com/nielsrogge) | [](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/LayoutLM/Fine_tuning_LayoutLMForTokenClassification_on_FUNSD.ipynb)|
-|[Fine-tuning di DistilGPT2 e generazione di testo](https://colab.research.google.com/github/tripathiaakash/DistilGPT2-Tutorial/blob/main/distilgpt2_fine_tuning.ipynb) | Come effettuare il fine-tuning di DistilGPT2 e generare testo. | [Aakash Tripathi](https://github.com/tripathiaakash) | [](https://colab.research.google.com/github/tripathiaakash/DistilGPT2-Tutorial/blob/main/distilgpt2_fine_tuning.ipynb)|
-|[Fine-tuning di LED fino a 8 mila token](https://github.com/patrickvonplaten/notebooks/blob/master/Fine_tune_Longformer_Encoder_Decoder_(LED)_for_Summarization_on_pubmed.ipynb) | Come effettuare il fine-tuning di LED su PubMed per riassumere "lunghi" testi. | [Patrick von Platen](https://github.com/patrickvonplaten) | [](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/Fine_tune_Longformer_Encoder_Decoder_(LED)_for_Summarization_on_pubmed.ipynb)|
-|[Valutazione di LED su Arxiv](https://github.com/patrickvonplaten/notebooks/blob/master/LED_on_Arxiv.ipynb) | Come valutare efficacemente LED sull'attivitĂ di riassumere "lunghi" testi. | [Patrick von Platen](https://github.com/patrickvonplaten) | [](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/LED_on_Arxiv.ipynb)|
-|[Fine-tuning di LayoutLM su RVL-CDIP, un dataset per la classificazione di documenti (immagini)](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/LayoutLM/Fine_tuning_LayoutLMForSequenceClassification_on_RVL_CDIP.ipynb) | Come effettuare il fine-tuning di un modello *LayoutLMForSequenceClassification* sul dataset RVL-CDIP per la classificazione di documenti scannerizzati. | [Niels Rogge](https://github.com/nielsrogge) | [](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/LayoutLM/Fine_tuning_LayoutLMForSequenceClassification_on_RVL_CDIP.ipynb)|
-|[Decodifica Wav2Vec2 CTC con variazioni di GPT2](https://github.com/voidful/huggingface_notebook/blob/main/xlsr_gpt.ipynb) | Come decodificare sequenze CTC, variate da modelli di linguaggio. | [Eric Lam](https://github.com/voidful) | [](https://colab.research.google.com/drive/1e_z5jQHYbO2YKEaUgzb1ww1WwiAyydAj?usp=sharing)
-|[Fine-tuning di BART per riassumere testi in due lingue con la classe Trainer](https://github.com/elsanns/xai-nlp-notebooks/blob/master/fine_tune_bart_summarization_two_langs.ipynb) | Come effettuare il fine-tuning di BART per riassumere testi in due lingue usando la classe Trainer. | [Eliza Szczechla](https://github.com/elsanns) | [](https://colab.research.google.com/github/elsanns/xai-nlp-notebooks/blob/master/fine_tune_bart_summarization_two_langs.ipynb)|
-|[Valutazione di Big Bird su Trivia QA](https://github.com/patrickvonplaten/notebooks/blob/master/Evaluating_Big_Bird_on_TriviaQA.ipynb) | Come valutare BigBird su question answering di "lunghi" documenti attraverso Trivia QA. | [Patrick von Platen](https://github.com/patrickvonplaten) | [](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/Evaluating_Big_Bird_on_TriviaQA.ipynb)|
-| [Creazione di sottotitoli per video usando Wav2Vec2](https://github.com/Muennighoff/ytclipcc/blob/main/wav2vec_youtube_captions.ipynb) | Come creare sottotitoli per qualsiasi video di YouTube trascrivendo l'audio con Wav2Vec. | [Niklas Muennighoff](https://github.com/Muennighoff) |[](https://colab.research.google.com/github/Muennighoff/ytclipcc/blob/main/wav2vec_youtube_captions.ipynb) |
-| [Fine-tuning di Vision Transformer su CIFAR-10 usando PyTorch Lightning](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/VisionTransformer/Fine_tuning_the_Vision_Transformer_on_CIFAR_10_with_PyTorch_Lightning.ipynb) | Come effettuare il fine-tuning di Vision Transformer (ViT) su CIFAR-10 usando HuggingFace Transformers, Datasets e PyTorch Lightning.| [Niels Rogge](https://github.com/nielsrogge) |[](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/VisionTransformer/Fine_tuning_the_Vision_Transformer_on_CIFAR_10_with_PyTorch_Lightning.ipynb) |
-| [Fine-tuning di Vision Transformer su CIFAR-10 usando đ€ Trainer](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/VisionTransformer/Fine_tuning_the_Vision_Transformer_on_CIFAR_10_with_the_%F0%9F%A4%97_Trainer.ipynb) | Come effettuare il fine-tuning di Vision Transformer (ViT) su CIFAR-10 usando HuggingFace Transformers, Datasets e đ€ Trainer. | [Niels Rogge](https://github.com/nielsrogge) |[](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/VisionTransformer/Fine_tuning_the_Vision_Transformer_on_CIFAR_10_with_the_%F0%9F%A4%97_Trainer.ipynb) |
-| [Valutazione di LUKE su Open Entity, un dataset di entity typing](https://github.com/studio-ousia/luke/blob/master/notebooks/huggingface_open_entity.ipynb) | Come valutare un modello *LukeForEntityClassification* sul dataset Open Entity. | [Ikuya Yamada](https://github.com/ikuyamada) |[](https://colab.research.google.com/github/studio-ousia/luke/blob/master/notebooks/huggingface_open_entity.ipynb) |
-| [Valutazione di LUKE su TACRED, un dataset per l'estrazione di relazioni](https://github.com/studio-ousia/luke/blob/master/notebooks/huggingface_tacred.ipynb) | Come valutare un modello *LukeForEntityPairClassification* sul dataset TACRED. | [Ikuya Yamada](https://github.com/ikuyamada) |[](https://colab.research.google.com/github/studio-ousia/luke/blob/master/notebooks/huggingface_tacred.ipynb) |
-| [Valutazione di LUKE su CoNLL-2003, un importante benchmark NER](https://github.com/studio-ousia/luke/blob/master/notebooks/huggingface_conll_2003.ipynb) | Come valutare un modello *LukeForEntitySpanClassification* sul dataset CoNLL-2003. | [Ikuya Yamada](https://github.com/ikuyamada) |[](https://colab.research.google.com/github/studio-ousia/luke/blob/master/notebooks/huggingface_conll_2003.ipynb) |
-| [Valutazione di BigBird-Pegasus su dataset PubMed](https://github.com/vasudevgupta7/bigbird/blob/main/notebooks/bigbird_pegasus_evaluation.ipynb) | Come valutare un modello *BigBirdPegasusForConditionalGeneration* su dataset PubMed. | [Vasudev Gupta](https://github.com/vasudevgupta7) | [](https://colab.research.google.com/github/vasudevgupta7/bigbird/blob/main/notebooks/bigbird_pegasus_evaluation.ipynb) |
-| [Classificazione di emozioni dal discorso con Wav2Vec2](https://github/m3hrdadfi/soxan/blob/main/notebooks/Emotion_recognition_in_Greek_speech_using_Wav2Vec2.ipynb) | Come utilizzare un modello pre-addestrato Wav2Vec2 per la classificazione di emozioni sul dataset MEGA. | [Mehrdad Farahani](https://github.com/m3hrdadfi) | [](https://colab.research.google.com/github/m3hrdadfi/soxan/blob/main/notebooks/Emotion_recognition_in_Greek_speech_using_Wav2Vec2.ipynb) |
-| [Rilevamento oggetti in un'immagine con DETR](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/DETR/DETR_minimal_example_(with_DetrFeatureExtractor).ipynb) | Come usare un modello addestrato *DetrForObjectDetection* per rilevare oggetti in un'immagine e visualizzare l'attention. | [Niels Rogge](https://github.com/NielsRogge) | [](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/DETR/DETR_minimal_example_(with_DetrFeatureExtractor).ipynb) |
-| [Fine-tuning di DETR su un dataset personalizzato per rilevare oggetti](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/DETR/Fine_tuning_DetrForObjectDetection_on_custom_dataset_(balloon).ipynb) | Come effettuare fine-tuning di un modello *DetrForObjectDetection* su un dataset personalizzato per rilevare oggetti. | [Niels Rogge](https://github.com/NielsRogge) | [](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/DETR/Fine_tuning_DetrForObjectDetection_on_custom_dataset_(balloon).ipynb) |
-| [Fine-tuning di T5 per Named Entity Recognition](https://github.com/ToluClassics/Notebooks/blob/main/T5_Ner_Finetuning.ipynb) | Come effettuare fine-tunining di *T5* per un'attivitĂ di Named Entity Recognition. | [Ogundepo Odunayo](https://github.com/ToluClassics) | [](https://colab.research.google.com/drive/1obr78FY_cBmWY5ODViCmzdY6O1KB65Vc?usp=sharing) |
diff --git a/docs/source/it/converting_tensorflow_models.md b/docs/source/it/converting_tensorflow_models.md
new file mode 100644
index 000000000000..04398636359c
--- /dev/null
+++ b/docs/source/it/converting_tensorflow_models.md
@@ -0,0 +1,159 @@
+
+
+# Convertire checkpoint di Tensorflow
+
+Ă disponibile un'interfaccia a linea di comando per convertire gli originali checkpoint di Bert/GPT/GPT-2/Transformer-XL/XLNet/XLM
+in modelli che possono essere caricati utilizzando i metodi `from_pretrained` della libreria.
+
+
+
+A partire dalla versione 2.3.0 lo script di conversione Ăš parte di transformers CLI (**transformers-cli**), disponibile in ogni installazione
+di transformers >=2.3.0.
+
+La seguente documentazione riflette il formato dei comandi di **transformers-cli convert**.
+
+
+
+## BERT
+
+Puoi convertire qualunque checkpoint Tensorflow di BERT (in particolare
+[i modeli pre-allenati rilasciati da Google](https://github.com/google-research/bert#pre-trained-models))
+in un file di salvataggio Pytorch utilizzando lo script
+[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).
+
+Questo CLI prende come input un checkpoint di Tensorflow (tre files che iniziano con `bert_model.ckpt`) ed il relativo
+file di configurazione (`bert_config.json`), crea un modello Pytorch per questa configurazione, carica i pesi dal
+checkpoint di Tensorflow nel modello di Pytorch e salva il modello che ne risulta in un file di salvataggio standard di Pytorch che
+puĂČ essere importato utilizzando `from_pretrained()` (vedi l'esempio nel
+[quicktour](quicktour) , [run_glue.py](https://github.com/huggingface/transformers/tree/main/examples/pytorch/text-classification/run_glue.py) ).
+
+Devi soltanto lanciare questo script di conversione **una volta** per ottenere un modello Pytorch. DopodichĂš, potrai tralasciare
+il checkpoint di Tensorflow (i tre files che iniziano con `bert_model.ckpt`), ma assicurati di tenere il file di configurazione
+(`bert_config.json`) ed il file di vocabolario (`vocab.txt`) in quanto queste componenti sono necessarie anche per il modello di Pytorch.
+
+Per lanciare questo specifico script di conversione avrai bisogno di un'installazione di Tensorflow e di Pytorch
+(`pip install tensorflow`). Il resto della repository richiede soltanto Pytorch.
+
+Questo Ăš un esempio del processo di conversione per un modello `BERT-Base Uncased` pre-allenato:
+
+```bash
+export BERT_BASE_DIR=/path/to/bert/uncased_L-12_H-768_A-12
+transformers-cli convert --model_type bert \
+ --tf_checkpoint $BERT_BASE_DIR/bert_model.ckpt \
+ --config $BERT_BASE_DIR/bert_config.json \
+ --pytorch_dump_output $BERT_BASE_DIR/pytorch_model.bin
+```
+
+Puoi scaricare i modelli pre-allenati di Google per la conversione [qua](https://github.com/google-research/bert#pre-trained-models).
+
+## ALBERT
+
+Per il modello ALBERT, converti checkpoint di Tensoflow in Pytorch utilizzando lo script
+[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).
+
+Il CLI prende come input un checkpoint di Tensorflow (tre files che iniziano con `model.ckpt-best`) e i relativi file di
+configurazione (`albert_config.json`), dopodichĂš crea e salva un modello Pytorch. Per lanciare questa conversione
+avrai bisogno di un'installazione di Tensorflow e di Pytorch.
+
+Ecco un esempio del procedimento di conversione di un modello `ALBERT Base` pre-allenato:
+
+```bash
+export ALBERT_BASE_DIR=/path/to/albert/albert_base
+transformers-cli convert --model_type albert \
+ --tf_checkpoint $ALBERT_BASE_DIR/model.ckpt-best \
+ --config $ALBERT_BASE_DIR/albert_config.json \
+ --pytorch_dump_output $ALBERT_BASE_DIR/pytorch_model.bin
+```
+
+Puoi scaricare i modelli pre-allenati di Google per la conversione [qui](https://github.com/google-research/albert#pre-trained-models).
+
+## OpenAI GPT
+
+Ecco un esempio del processo di conversione di un modello OpenAI GPT pre-allenato, assumendo che il tuo checkpoint di NumPy
+sia salvato nello stesso formato dei modelli pre-allenati OpenAI (vedi [qui](https://github.com/openai/finetune-transformer-lm)):
+```bash
+export OPENAI_GPT_CHECKPOINT_FOLDER_PATH=/path/to/openai/pretrained/numpy/weights
+transformers-cli convert --model_type gpt \
+ --tf_checkpoint $OPENAI_GPT_CHECKPOINT_FOLDER_PATH \
+ --pytorch_dump_output $PYTORCH_DUMP_OUTPUT \
+ [--config OPENAI_GPT_CONFIG] \
+ [--finetuning_task_name OPENAI_GPT_FINETUNED_TASK] \
+```
+
+## OpenAI GPT-2
+
+Ecco un esempio del processo di conversione di un modello OpenAI GPT-2 pre-allenato (vedi [qui](https://github.com/openai/gpt-2)):
+
+```bash
+export OPENAI_GPT2_CHECKPOINT_PATH=/path/to/gpt2/pretrained/weights
+transformers-cli convert --model_type gpt2 \
+ --tf_checkpoint $OPENAI_GPT2_CHECKPOINT_PATH \
+ --pytorch_dump_output $PYTORCH_DUMP_OUTPUT \
+ [--config OPENAI_GPT2_CONFIG] \
+ [--finetuning_task_name OPENAI_GPT2_FINETUNED_TASK]
+```
+
+## Transformer-XL
+
+
+Ecco un esempio del processo di conversione di un modello Transformer-XL pre-allenato
+(vedi [qui](https://github.com/kimiyoung/transformer-xl/tree/master/tf#obtain-and-evaluate-pretrained-sota-models)):
+
+```bash
+export TRANSFO_XL_CHECKPOINT_FOLDER_PATH=/path/to/transfo/xl/checkpoint
+transformers-cli convert --model_type transfo_xl \
+ --tf_checkpoint $TRANSFO_XL_CHECKPOINT_FOLDER_PATH \
+ --pytorch_dump_output $PYTORCH_DUMP_OUTPUT \
+ [--config TRANSFO_XL_CONFIG] \
+ [--finetuning_task_name TRANSFO_XL_FINETUNED_TASK]
+```
+
+## XLNet
+
+Ecco un esempio del processo di conversione di un modello XLNet pre-allenato:
+
+```bash
+export TRANSFO_XL_CHECKPOINT_PATH=/path/to/xlnet/checkpoint
+export TRANSFO_XL_CONFIG_PATH=/path/to/xlnet/config
+transformers-cli convert --model_type xlnet \
+ --tf_checkpoint $TRANSFO_XL_CHECKPOINT_PATH \
+ --config $TRANSFO_XL_CONFIG_PATH \
+ --pytorch_dump_output $PYTORCH_DUMP_OUTPUT \
+ [--finetuning_task_name XLNET_FINETUNED_TASK] \
+```
+
+## XLM
+
+Ecco un esempio del processo di conversione di un modello XLM pre-allenato:
+
+```bash
+export XLM_CHECKPOINT_PATH=/path/to/xlm/checkpoint
+transformers-cli convert --model_type xlm \
+ --tf_checkpoint $XLM_CHECKPOINT_PATH \
+ --pytorch_dump_output $PYTORCH_DUMP_OUTPUT
+ [--config XML_CONFIG] \
+ [--finetuning_task_name XML_FINETUNED_TASK]
+```
+
+## T5
+
+Ecco un esempio del processo di conversione di un modello T5 pre-allenato:
+
+```bash
+export T5=/path/to/t5/uncased_L-12_H-768_A-12
+transformers-cli convert --model_type t5 \
+ --tf_checkpoint $T5/t5_model.ckpt \
+ --config $T5/t5_config.json \
+ --pytorch_dump_output $T5/pytorch_model.bin
+```
diff --git a/docs/source/it/converting_tensorflow_models.mdx b/docs/source/it/converting_tensorflow_models.mdx
deleted file mode 100644
index b9b30a315c6a..000000000000
--- a/docs/source/it/converting_tensorflow_models.mdx
+++ /dev/null
@@ -1,155 +0,0 @@
-
-
-# Convertire checkpoint di Tensorflow
-
-Ă disponibile un'interfaccia a linea di comando per convertire gli originali checkpoint di Bert/GPT/GPT-2/Transformer-XL/XLNet/XLM
-in modelli che possono essere caricati utilizzando i metodi `from_pretrained` della libreria.
-
-
-
-A partire dalla versione 2.3.0 lo script di conversione Ăš parte di transformers CLI (**transformers-cli**), disponibile in ogni installazione
-di transformers >=2.3.0.
-
-La seguente documentazione riflette il formato dei comandi di **transformers-cli convert**.
-
-
-
-## BERT
-
-Puoi convertire qualunque checkpoint Tensorflow di BERT (in particolare
-[i modeli pre-allenati rilasciati da Google](https://github.com/google-research/bert#pre-trained-models))
-in un file di salvataggio Pytorch utilizzando lo script
-[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).
-
-Questo CLI prende come input un checkpoint di Tensorflow (tre files che iniziano con `bert_model.ckpt`) ed il relativo
-file di configurazione (`bert_config.json`), crea un modello Pytorch per questa configurazione, carica i pesi dal
-checkpoint di Tensorflow nel modello di Pytorch e salva il modello che ne risulta in un file di salvataggio standard di Pytorch che
-puĂČ essere importato utilizzando `from_pretrained()` (vedi l'esempio nel
-[quicktour](quicktour) , [run_glue.py](https://github.com/huggingface/transformers/tree/main/examples/pytorch/text-classification/run_glue.py) ).
-
-Devi soltanto lanciare questo script di conversione **una volta** per ottenere un modello Pytorch. DopodichĂš, potrai tralasciare
-il checkpoint di Tensorflow (i tre files che iniziano con `bert_model.ckpt`), ma assicurati di tenere il file di configurazione
-(`bert_config.json`) ed il file di vocabolario (`vocab.txt`) in quanto queste componenti sono necessarie anche per il modello di Pytorch.
-
-Per lanciare questo specifico script di conversione avrai bisogno di un'installazione di Tensorflow e di Pytorch
-(`pip install tensorflow`). Il resto della repository richiede soltanto Pytorch.
-
-Questo Ăš un esempio del processo di conversione per un modello `BERT-Base Uncased` pre-allenato:
-
-```bash
-export BERT_BASE_DIR=/path/to/bert/uncased_L-12_H-768_A-12
-transformers-cli convert --model_type bert \
- --tf_checkpoint $BERT_BASE_DIR/bert_model.ckpt \
- --config $BERT_BASE_DIR/bert_config.json \
- --pytorch_dump_output $BERT_BASE_DIR/pytorch_model.bin
-```
-
-Puoi scaricare i modelli pre-allenati di Google per la conversione [qua](https://github.com/google-research/bert#pre-trained-models).
-
-## ALBERT
-
-Per il modello ALBERT, converti checkpoint di Tensoflow in Pytorch utilizzando lo script
-[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).
-
-Il CLI prende come input un checkpoint di Tensorflow (tre files che iniziano con `model.ckpt-best`) e i relativi file di
-configurazione (`albert_config.json`), dopodichĂš crea e salva un modello Pytorch. Per lanciare questa conversione
-avrai bisogno di un'installazione di Tensorflow e di Pytorch.
-
-Ecco un esempio del procedimento di conversione di un modello `ALBERT Base` pre-allenato:
-
-```bash
-export ALBERT_BASE_DIR=/path/to/albert/albert_base
-transformers-cli convert --model_type albert \
- --tf_checkpoint $ALBERT_BASE_DIR/model.ckpt-best \
- --config $ALBERT_BASE_DIR/albert_config.json \
- --pytorch_dump_output $ALBERT_BASE_DIR/pytorch_model.bin
-```
-
-Puoi scaricare i modelli pre-allenati di Google per la conversione [qui](https://github.com/google-research/albert#pre-trained-models).
-
-## OpenAI GPT
-
-Ecco un esempio del processo di conversione di un modello OpenAI GPT pre-allenato, assumendo che il tuo checkpoint di NumPy
-sia salvato nello stesso formato dei modelli pre-allenati OpenAI (vedi [qui](https://github.com/openai/finetune-transformer-lm)):
-```bash
-export OPENAI_GPT_CHECKPOINT_FOLDER_PATH=/path/to/openai/pretrained/numpy/weights
-transformers-cli convert --model_type gpt \
- --tf_checkpoint $OPENAI_GPT_CHECKPOINT_FOLDER_PATH \
- --pytorch_dump_output $PYTORCH_DUMP_OUTPUT \
- [--config OPENAI_GPT_CONFIG] \
- [--finetuning_task_name OPENAI_GPT_FINETUNED_TASK] \
-```
-
-## OpenAI GPT-2
-
-Ecco un esempio del processo di conversione di un modello OpenAI GPT-2 pre-allenato (vedi [qui](https://github.com/openai/gpt-2)):
-
-```bash
-export OPENAI_GPT2_CHECKPOINT_PATH=/path/to/gpt2/pretrained/weights
-transformers-cli convert --model_type gpt2 \
- --tf_checkpoint $OPENAI_GPT2_CHECKPOINT_PATH \
- --pytorch_dump_output $PYTORCH_DUMP_OUTPUT \
- [--config OPENAI_GPT2_CONFIG] \
- [--finetuning_task_name OPENAI_GPT2_FINETUNED_TASK]
-```
-
-## Transformer-XL
-
-
-Ecco un esempio del processo di conversione di un modello Transformer-XL pre-allenato
-(vedi [qui](https://github.com/kimiyoung/transformer-xl/tree/master/tf#obtain-and-evaluate-pretrained-sota-models)):
-
-```bash
-export TRANSFO_XL_CHECKPOINT_FOLDER_PATH=/path/to/transfo/xl/checkpoint
-transformers-cli convert --model_type transfo_xl \
- --tf_checkpoint $TRANSFO_XL_CHECKPOINT_FOLDER_PATH \
- --pytorch_dump_output $PYTORCH_DUMP_OUTPUT \
- [--config TRANSFO_XL_CONFIG] \
- [--finetuning_task_name TRANSFO_XL_FINETUNED_TASK]
-```
-
-## XLNet
-
-Ecco un esempio del processo di conversione di un modello XLNet pre-allenato:
-
-```bash
-export TRANSFO_XL_CHECKPOINT_PATH=/path/to/xlnet/checkpoint
-export TRANSFO_XL_CONFIG_PATH=/path/to/xlnet/config
-transformers-cli convert --model_type xlnet \
- --tf_checkpoint $TRANSFO_XL_CHECKPOINT_PATH \
- --config $TRANSFO_XL_CONFIG_PATH \
- --pytorch_dump_output $PYTORCH_DUMP_OUTPUT \
- [--finetuning_task_name XLNET_FINETUNED_TASK] \
-```
-
-## XLM
-
-Ecco un esempio del processo di conversione di un modello XLM pre-allenato:
-
-```bash
-export XLM_CHECKPOINT_PATH=/path/to/xlm/checkpoint
-transformers-cli convert --model_type xlm \
- --tf_checkpoint $XLM_CHECKPOINT_PATH \
- --pytorch_dump_output $PYTORCH_DUMP_OUTPUT
- [--config XML_CONFIG] \
- [--finetuning_task_name XML_FINETUNED_TASK]
-```
-
-## T5
-
-Ecco un esempio del processo di conversione di un modello T5 pre-allenato:
-
-```bash
-export T5=/path/to/t5/uncased_L-12_H-768_A-12
-transformers-cli convert --model_type t5 \
- --tf_checkpoint $T5/t5_model.ckpt \
- --config $T5/t5_config.json \
- --pytorch_dump_output $T5/pytorch_model.bin
-```
diff --git a/docs/source/it/create_a_model.md b/docs/source/it/create_a_model.md
new file mode 100644
index 000000000000..c32040d7d389
--- /dev/null
+++ b/docs/source/it/create_a_model.md
@@ -0,0 +1,361 @@
+
+
+# Crea un'architettura personalizzata
+
+Una [`AutoClass`](model_doc/auto) deduce automaticamente il modello dell'architettura e scarica la configurazione e i pesi pre-allenati. Generalmente, noi consigliamo di usare un `AutoClass` per produrre un codice indipendente dal checkpoint. Ma gli utenti che desiderano un controllo maggiore su parametri specifici del modello possono creare un modello đ€ Transformers personalizzato da poche classi base. Questo potrebbe essere particolarmente utile per qualunque persona sia interessata nel studiare, allenare o sperimentare con un modello đ€ Transformers. In questa guida, approfondisci la creazione di un modello personalizzato senza `AutoClass`. Impara come:
+
+- Caricare e personalizzare una configurazione del modello.
+- Creare un'architettura modello.
+- Creare un tokenizer lento e veloce per il testo.
+- Creare un estrattore di caratteristiche per attivitĂ riguardanti audio o immagini.
+- Creare un processore per attivitĂ multimodali.
+
+## Configurazione
+
+Una [configurazione](main_classes/configuration) si riferisce agli attributi specifici di un modello. Ogni configurazione del modello ha attributi diversi; per esempio, tutti i modelli npl hanno questi attributi in comune `hidden_size`, `num_attention_heads`, `num_hidden_layers` e `vocab_size`. Questi attributi specificano il numero di attention heads o strati nascosti con cui costruire un modello.
+
+Dai un'occhiata piĂč da vicino a [DistilBERT](model_doc/distilbert) accedendo a [`DistilBertConfig`] per ispezionare i suoi attributi:
+
+```py
+>>> from transformers import DistilBertConfig
+
+>>> config = DistilBertConfig()
+>>> print(config)
+DistilBertConfig {
+ "activation": "gelu",
+ "attention_dropout": 0.1,
+ "dim": 768,
+ "dropout": 0.1,
+ "hidden_dim": 3072,
+ "initializer_range": 0.02,
+ "max_position_embeddings": 512,
+ "model_type": "distilbert",
+ "n_heads": 12,
+ "n_layers": 6,
+ "pad_token_id": 0,
+ "qa_dropout": 0.1,
+ "seq_classif_dropout": 0.2,
+ "sinusoidal_pos_embds": false,
+ "transformers_version": "4.16.2",
+ "vocab_size": 30522
+}
+```
+
+[`DistilBertConfig`] mostra tutti gli attributi predefiniti usati per costruire una base [`DistilBertModel`]. Tutti gli attributi sono personalizzabili, creando uno spazio per sperimentare. Per esempio, puoi configurare un modello predefinito per:
+
+- Provare un funzione di attivazione diversa con il parametro `activation`.
+- Utilizzare tasso di drop out piĂč elevato per le probalitĂ di attention con il parametro `attention_dropout`.
+
+```py
+>>> my_config = DistilBertConfig(activation="relu", attention_dropout=0.4)
+>>> print(my_config)
+DistilBertConfig {
+ "activation": "relu",
+ "attention_dropout": 0.4,
+ "dim": 768,
+ "dropout": 0.1,
+ "hidden_dim": 3072,
+ "initializer_range": 0.02,
+ "max_position_embeddings": 512,
+ "model_type": "distilbert",
+ "n_heads": 12,
+ "n_layers": 6,
+ "pad_token_id": 0,
+ "qa_dropout": 0.1,
+ "seq_classif_dropout": 0.2,
+ "sinusoidal_pos_embds": false,
+ "transformers_version": "4.16.2",
+ "vocab_size": 30522
+}
+```
+
+Nella funzione [`~PretrainedConfig.from_pretrained`] possono essere modificati gli attributi del modello pre-allenato:
+
+```py
+>>> my_config = DistilBertConfig.from_pretrained("distilbert-base-uncased", activation="relu", attention_dropout=0.4)
+```
+
+Quando la configurazione del modello ti soddisfa, la puoi salvare con [`~PretrainedConfig.save_pretrained`]. Il file della tua configurazione Ăš memorizzato come file JSON nella save directory specificata:
+
+```py
+>>> my_config.save_pretrained(save_directory="./your_model_save_path")
+```
+
+Per riutilizzare la configurazione del file, caricalo con [`~PretrainedConfig.from_pretrained`]:
+
+```py
+>>> my_config = DistilBertConfig.from_pretrained("./your_model_save_path/my_config.json")
+```
+
+
+
+Puoi anche salvare il file di configurazione come dizionario oppure come la differenza tra gli attributi della tua configurazione personalizzata e gli attributi della configurazione predefinita! Guarda la documentazione [configuration](main_classes/configuration) per piĂč dettagli.
+
+
+
+## Modello
+
+Il prossimo passo e di creare [modello](main_classes/models). Il modello - vagamente riferito anche come architettura - definisce cosa ogni strato deve fare e quali operazioni stanno succedendo. Attributi come `num_hidden_layers` provenienti dalla configurazione sono usati per definire l'architettura. Ogni modello condivide la classe base [`PreTrainedModel`] e alcuni metodi comuni come il ridimensionamento degli input embeddings e la soppressione delle self-attention heads . Inoltre, tutti i modelli sono la sottoclasse di [`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) o [`flax.linen.Module`](https://flax.readthedocs.io/en/latest/flax.linen.html#module). Cio significa che i modelli sono compatibili con l'uso di ciascun di framework.
+
+
+
+Carica gli attributi della tua configurazione personalizzata nel modello:
+
+```py
+>>> from transformers import DistilBertModel
+
+>>> my_config = DistilBertConfig.from_pretrained("./your_model_save_path/my_config.json")
+>>> model = DistilBertModel(my_config)
+```
+
+Questo crea modelli con valori casuali invece di pesi pre-allenati. Non sarai in grado di usare questo modello per niente di utile finché non lo alleni. L'allenamento Ú un processo costoso e che richiede tempo . Generalmente Ú meglio usare un modello pre-allenato per ottenere risultati migliori velocemente, utilizzando solo una frazione delle risorse neccesarie per l'allenamento.
+
+Crea un modello pre-allenato con [`~PreTrainedModel.from_pretrained`]:
+
+```py
+>>> model = DistilBertModel.from_pretrained("distilbert-base-uncased")
+```
+
+Quando carichi pesi pre-allenati, la configurazione del modello predefinito Ăš automaticamente caricata se il modello Ăš fornito da đ€ Transformers. Tuttavia, puoi ancora sostituire gli attributi - alcuni o tutti - di configurazione del modello predefinito con i tuoi se lo desideri:
+
+```py
+>>> model = DistilBertModel.from_pretrained("distilbert-base-uncased", config=my_config)
+```
+
+
+Carica gli attributi di configurazione personalizzati nel modello:
+
+```py
+>>> from transformers import TFDistilBertModel
+
+>>> my_config = DistilBertConfig.from_pretrained("./your_model_save_path/my_config.json")
+>>> tf_model = TFDistilBertModel(my_config)
+```
+
+
+Questo crea modelli con valori casuali invece di pesi pre-allenati. Non sarai in grado di usare questo modello per niente di utile finché non lo alleni. L'allenamento Ú un processo costoso e che richiede tempo . Generalmente Ú meglio usare un modello pre-allenato per ottenere risultati migliori velocemente, utilizzando solo una frazione delle risorse neccesarie per l'allenamento.
+
+Crea un modello pre-allenoto con [`~TFPreTrainedModel.from_pretrained`]:
+
+```py
+>>> tf_model = TFDistilBertModel.from_pretrained("distilbert-base-uncased")
+```
+
+Quando carichi pesi pre-allenati, la configurazione del modello predefinito Ăš automaticamente caricato se il modello Ăš fornito da đ€ Transformers. Tuttavia, puoi ancora sostituire gli attributi - alcuni o tutti - di configurazione del modello predefinito con i tuoi se lo desideri:
+
+```py
+>>> tf_model = TFDistilBertModel.from_pretrained("distilbert-base-uncased", config=my_config)
+```
+
+
+
+
+### Model head
+
+A questo punto, hai un modello DistilBERT base i cui output sono gli *hidden states* (in italiano stati nascosti). Gli stati nascosti sono passati come input a un model head per produrre l'output finale. đ€ Transformers fornisce un model head diverso per ogni attivitĂ fintanto che il modello supporta l'attivitĂ (i.e., non puoi usare DistilBERT per un attivitĂ sequence-to-sequence come la traduzione).
+
+
+
+Per esempio, [`DistilBertForSequenceClassification`] Ăš un modello DistilBERT base con una testa di classificazione per sequenze. La sequenza di classificazione head Ăš uno strato lineare sopra gli output ragruppati.
+
+```py
+>>> from transformers import DistilBertForSequenceClassification
+
+>>> model = DistilBertForSequenceClassification.from_pretrained("distilbert-base-uncased")
+```
+
+Riutilizza facilmente questo checkpoint per un'altra attivitĂ passando ad un model head differente. Per un attivitĂ di risposta alle domande, utilizzerai il model head [`DistilBertForQuestionAnswering`]. La head per compiti di question answering Ăš simile alla classificazione di sequenza head tranne per il fatto che Ăš uno strato lineare sopra l'output degli stati nascosti (hidden states in inglese)
+
+```py
+>>> from transformers import DistilBertForQuestionAnswering
+
+>>> model = DistilBertForQuestionAnswering.from_pretrained("distilbert-base-uncased")
+```
+
+
+Per esempio, [`TFDistilBertForSequenceClassification`] Ăš un modello DistilBERT base con classificazione di sequenza head. La classificazione di sequenza head Ăš uno strato lineare sopra gli output raggruppati.
+
+```py
+>>> from transformers import TFDistilBertForSequenceClassification
+
+>>> tf_model = TFDistilBertForSequenceClassification.from_pretrained("distilbert-base-uncased")
+```
+
+Riutilizza facilmente questo checkpoint per un altra attivitĂ passando ad un modello head diverso. Per un attivitĂ di risposta alle domande, utilizzerai il model head [`TFDistilBertForQuestionAnswering`]. Il head di risposta alle domande Ăš simile alla sequenza di classificazione head tranne per il fatto che Ăš uno strato lineare sopra l'output degli stati nascosti (hidden states in inglese)
+
+```py
+>>> from transformers import TFDistilBertForQuestionAnswering
+
+>>> tf_model = TFDistilBertForQuestionAnswering.from_pretrained("distilbert-base-uncased")
+```
+
+
+
+## Tokenizer
+
+L'ultima classe base di cui hai bisogno prima di utilizzare un modello per i dati testuali Ăš un [tokenizer](main_classes/tokenizer) per convertire il testo grezzo in tensori. Ci sono due tipi di tokenizer che puoi usare con đ€ Transformers:
+
+- [`PreTrainedTokenizer`]: un'implementazione Python di un tokenizer.
+- [`PreTrainedTokenizerFast`]: un tokenizer dalla nostra libreria [đ€ Tokenizer](https://huggingface.co/docs/tokenizers/python/latest/) basata su Rust. Questo tipo di tokenizer Ăš significativamente piĂč veloce, specialmente durante la batch tokenization, grazie alla sua implementazione Rust. Il tokenizer veloce offre anche metodi aggiuntivi come *offset mapping* che associa i token alle loro parole o caratteri originali.
+
+Entrambi i tokenizer supportano metodi comuni come la codifica e la decodifica, l'aggiunta di nuovi token e la gestione di token speciali.
+
+
+
+Non tutti i modelli supportano un tokenizer veloce. Dai un'occhiata a questo [tabella](index#supported-frameworks) per verificare se un modello ha il supporto per tokenizer veloce.
+
+
+
+Se hai addestrato il tuo tokenizer, puoi crearne uno dal tuo file *vocabolario*:
+
+```py
+>>> from transformers import DistilBertTokenizer
+
+>>> my_tokenizer = DistilBertTokenizer(vocab_file="my_vocab_file.txt", do_lower_case=False, padding_side="left")
+```
+
+Ă importante ricordare che il vocabolario di un tokenizer personalizzato sarĂ diverso dal vocabolario generato dal tokenizer di un modello preallenato. Ă necessario utilizzare il vocabolario di un modello preallenato se si utilizza un modello preallenato, altrimenti gli input non avranno senso. Crea un tokenizer con il vocabolario di un modello preallenato con la classe [`DistilBertTokenizer`]:
+
+```py
+>>> from transformers import DistilBertTokenizer
+
+>>> slow_tokenizer = DistilBertTokenizer.from_pretrained("distilbert-base-uncased")
+```
+
+Crea un tokenizer veloce con la classe [`DistilBertTokenizerFast`]:
+
+```py
+>>> from transformers import DistilBertTokenizerFast
+
+>>> fast_tokenizer = DistilBertTokenizerFast.from_pretrained("distilbert-base-uncased")
+```
+
+
+
+Per l'impostazione predefinita, [`AutoTokenizer`] proverĂ a caricare un tokenizer veloce. Puoi disabilitare questo comportamento impostando `use_fast=False` in `from_pretrained`.
+
+
+
+## Estrattore Di Feature
+
+Un estrattore di caratteristiche (feature in inglese) elabora input audio o immagini. Eredita dalla classe [`~feature_extraction_utils.FeatureExtractionMixin`] base e puĂČ anche ereditare dalla classe [`ImageFeatureExtractionMixin`] per l'elaborazione delle caratteristiche dell'immagine o dalla classe [`SequenceFeatureExtractor`] per l'elaborazione degli input audio.
+
+A seconda che tu stia lavorando a un'attivitĂ audio o visiva, crea un estrattore di caratteristiche associato al modello che stai utilizzando. Ad esempio, crea un [`ViTFeatureExtractor`] predefinito se stai usando [ViT](model_doc/vit) per la classificazione delle immagini:
+
+```py
+>>> from transformers import ViTFeatureExtractor
+
+>>> vit_extractor = ViTFeatureExtractor()
+>>> print(vit_extractor)
+ViTFeatureExtractor {
+ "do_normalize": true,
+ "do_resize": true,
+ "feature_extractor_type": "ViTFeatureExtractor",
+ "image_mean": [
+ 0.5,
+ 0.5,
+ 0.5
+ ],
+ "image_std": [
+ 0.5,
+ 0.5,
+ 0.5
+ ],
+ "resample": 2,
+ "size": 224
+}
+```
+
+
+
+Se non stai cercando alcuna personalizzazione, usa il metodo `from_pretrained` per caricare i parametri di default dell'estrattore di caratteristiche di un modello.
+
+
+
+Modifica uno qualsiasi dei parametri [`ViTFeatureExtractor`] per creare il tuo estrattore di caratteristiche personalizzato:
+
+```py
+>>> from transformers import ViTFeatureExtractor
+
+>>> my_vit_extractor = ViTFeatureExtractor(resample="PIL.Image.BOX", do_normalize=False, image_mean=[0.3, 0.3, 0.3])
+>>> print(my_vit_extractor)
+ViTFeatureExtractor {
+ "do_normalize": false,
+ "do_resize": true,
+ "feature_extractor_type": "ViTFeatureExtractor",
+ "image_mean": [
+ 0.3,
+ 0.3,
+ 0.3
+ ],
+ "image_std": [
+ 0.5,
+ 0.5,
+ 0.5
+ ],
+ "resample": "PIL.Image.BOX",
+ "size": 224
+}
+```
+
+Per gli input audio, puoi creare un [`Wav2Vec2FeatureExtractor`] e personalizzare i parametri in modo simile:
+
+```py
+>>> from transformers import Wav2Vec2FeatureExtractor
+
+>>> w2v2_extractor = Wav2Vec2FeatureExtractor()
+>>> print(w2v2_extractor)
+Wav2Vec2FeatureExtractor {
+ "do_normalize": true,
+ "feature_extractor_type": "Wav2Vec2FeatureExtractor",
+ "feature_size": 1,
+ "padding_side": "right",
+ "padding_value": 0.0,
+ "return_attention_mask": false,
+ "sampling_rate": 16000
+}
+```
+
+## Processore
+
+Per modelli che supportano attivitĂ multimodali, đ€ Transformers offre una classe di processore che racchiude comodamente un estrattore di caratteristiche e un tokenizer in un unico oggetto. Ad esempio, utilizziamo [`Wav2Vec2Processor`] per un'attivitĂ di riconoscimento vocale automatico (ASR). ASR trascrive l'audio in testo, quindi avrai bisogno di un estrattore di caratteristiche e di un tokenizer.
+
+Crea un estrattore di feature per gestire gli input audio:
+
+```py
+>>> from transformers import Wav2Vec2FeatureExtractor
+
+>>> feature_extractor = Wav2Vec2FeatureExtractor(padding_value=1.0, do_normalize=True)
+```
+
+Crea un tokenizer per gestire gli input di testo:
+
+```py
+>>> from transformers import Wav2Vec2CTCTokenizer
+
+>>> tokenizer = Wav2Vec2CTCTokenizer(vocab_file="my_vocab_file.txt")
+```
+
+Combinare l'estrattore di caratteristiche e il tokenizer in [`Wav2Vec2Processor`]:
+
+```py
+>>> from transformers import Wav2Vec2Processor
+
+>>> processor = Wav2Vec2Processor(feature_extractor=feature_extractor, tokenizer=tokenizer)
+```
+
+Con due classi di base - configurazione e modello - e una classe di preelaborazione aggiuntiva (tokenizer, estrattore di caratteristiche o processore), puoi creare qualsiasi modello supportato da đ€ Transformers. Ognuna di queste classi base Ăš configurabile, consentendoti di utilizzare gli attributi specifici che desideri. Ă possibile impostare facilmente un modello per l'addestramento o modificare un modello preallenato esistente per la messa a punto.
\ No newline at end of file
diff --git a/docs/source/it/create_a_model.mdx b/docs/source/it/create_a_model.mdx
deleted file mode 100644
index 6e11f3f1d029..000000000000
--- a/docs/source/it/create_a_model.mdx
+++ /dev/null
@@ -1,357 +0,0 @@
-
-
-# Crea un'architettura personalizzata
-
-Una [`AutoClass`](model_doc/auto) deduce automaticamente il modello dell'architettura e scarica la configurazione e i pesi pre-allenati. Generalmente, noi consigliamo di usare un `AutoClass` per produrre un codice indipendente dal checkpoint. Ma gli utenti che desiderano un controllo maggiore su parametri specifici del modello possono creare un modello đ€ Transformers personalizzato da poche classi base. Questo potrebbe essere particolarmente utile per qualunque persona sia interessata nel studiare, allenare o sperimentare con un modello đ€ Transformers. In questa guida, approfondisci la creazione di un modello personalizzato senza `AutoClass`. Impara come:
-
-- Caricare e personalizzare una configurazione del modello.
-- Creare un'architettura modello.
-- Creare un tokenizer lento e veloce per il testo.
-- Creare un estrattore di caratteristiche per attivitĂ riguardanti audio o immagini.
-- Creare un processore per attivitĂ multimodali.
-
-## Configurazione
-
-Una [configurazione](main_classes/configuration) si riferisce agli attributi specifici di un modello. Ogni configurazione del modello ha attributi diversi; per esempio, tutti i modelli npl hanno questi attributi in comune `hidden_size`, `num_attention_heads`, `num_hidden_layers` e `vocab_size`. Questi attributi specificano il numero di attention heads o strati nascosti con cui costruire un modello.
-
-Dai un'occhiata piĂč da vicino a [DistilBERT](model_doc/distilbert) accedendo a [`DistilBertConfig`] per ispezionare i suoi attributi:
-
-```py
->>> from transformers import DistilBertConfig
-
->>> config = DistilBertConfig()
->>> print(config)
-DistilBertConfig {
- "activation": "gelu",
- "attention_dropout": 0.1,
- "dim": 768,
- "dropout": 0.1,
- "hidden_dim": 3072,
- "initializer_range": 0.02,
- "max_position_embeddings": 512,
- "model_type": "distilbert",
- "n_heads": 12,
- "n_layers": 6,
- "pad_token_id": 0,
- "qa_dropout": 0.1,
- "seq_classif_dropout": 0.2,
- "sinusoidal_pos_embds": false,
- "transformers_version": "4.16.2",
- "vocab_size": 30522
-}
-```
-
-[`DistilBertConfig`] mostra tutti gli attributi predefiniti usati per costruire una base [`DistilBertModel`]. Tutti gli attributi sono personalizzabili, creando uno spazio per sperimentare. Per esempio, puoi configurare un modello predefinito per:
-
-- Provare un funzione di attivazione diversa con il parametro `activation`.
-- Utilizzare tasso di drop out piĂč elevato per le probalitĂ di attention con il parametro `attention_dropout`.
-
-```py
->>> my_config = DistilBertConfig(activation="relu", attention_dropout=0.4)
->>> print(my_config)
-DistilBertConfig {
- "activation": "relu",
- "attention_dropout": 0.4,
- "dim": 768,
- "dropout": 0.1,
- "hidden_dim": 3072,
- "initializer_range": 0.02,
- "max_position_embeddings": 512,
- "model_type": "distilbert",
- "n_heads": 12,
- "n_layers": 6,
- "pad_token_id": 0,
- "qa_dropout": 0.1,
- "seq_classif_dropout": 0.2,
- "sinusoidal_pos_embds": false,
- "transformers_version": "4.16.2",
- "vocab_size": 30522
-}
-```
-
-Nella funzione [`~PretrainedConfig.from_pretrained`] possono essere modificati gli attributi del modello pre-allenato:
-
-```py
->>> my_config = DistilBertConfig.from_pretrained("distilbert-base-uncased", activation="relu", attention_dropout=0.4)
-```
-
-Quando la configurazione del modello ti soddisfa, la puoi salvare con [`~PretrainedConfig.save_pretrained`]. Il file della tua configurazione Ăš memorizzato come file JSON nella save directory specificata:
-
-```py
->>> my_config.save_pretrained(save_directory="./your_model_save_path")
-```
-
-Per riutilizzare la configurazione del file, caricalo con [`~PretrainedConfig.from_pretrained`]:
-
-```py
->>> my_config = DistilBertConfig.from_pretrained("./your_model_save_path/my_config.json")
-```
-
-
-
-Puoi anche salvare il file di configurazione come dizionario oppure come la differenza tra gli attributi della tua configurazione personalizzata e gli attributi della configurazione predefinita! Guarda la documentazione [configuration](main_classes/configuration) per piĂč dettagli.
-
-
-
-## Modello
-
-Il prossimo passo e di creare [modello](main_classes/models). Il modello - vagamente riferito anche come architettura - definisce cosa ogni strato deve fare e quali operazioni stanno succedendo. Attributi come `num_hidden_layers` provenienti dalla configurazione sono usati per definire l'architettura. Ogni modello condivide la classe base [`PreTrainedModel`] e alcuni metodi comuni come il ridimensionamento degli input embeddings e la soppressione delle self-attention heads . Inoltre, tutti i modelli sono la sottoclasse di [`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) o [`flax.linen.Module`](https://flax.readthedocs.io/en/latest/flax.linen.html#module). Cio significa che i modelli sono compatibili con l'uso di ciascun di framework.
-
-
-
-Carica gli attributi della tua configurazione personalizzata nel modello:
-
-```py
->>> from transformers import DistilBertModel
-
->>> my_config = DistilBertConfig.from_pretrained("./your_model_save_path/my_config.json")
->>> model = DistilBertModel(my_config)
-```
-
-Questo crea modelli con valori casuali invece di pesi pre-allenati. Non sarai in grado di usare questo modello per niente di utile finché non lo alleni. L'allenamento Ú un processo costoso e che richiede tempo . Generalmente Ú meglio usare un modello pre-allenato per ottenere risultati migliori velocemente, utilizzando solo una frazione delle risorse neccesarie per l'allenamento.
-
-Crea un modello pre-allenato con [`~PreTrainedModel.from_pretrained`]:
-
-```py
->>> model = DistilBertModel.from_pretrained("distilbert-base-uncased")
-```
-
-Quando carichi pesi pre-allenati, la configurazione del modello predefinito Ăš automaticamente caricata se il modello Ăš fornito da đ€ Transformers. Tuttavia, puoi ancora sostituire gli attributi - alcuni o tutti - di configurazione del modello predefinito con i tuoi se lo desideri:
-
-```py
->>> model = DistilBertModel.from_pretrained("distilbert-base-uncased", config=my_config)
-```
-
-
-Carica gli attributi di configurazione personalizzati nel modello:
-
-```py
->>> from transformers import TFDistilBertModel
-
->>> my_config = DistilBertConfig.from_pretrained("./your_model_save_path/my_config.json")
->>> tf_model = TFDistilBertModel(my_config)
-```
-
-
-Questo crea modelli con valori casuali invece di pesi pre-allenati. Non sarai in grado di usare questo modello per niente di utile finché non lo alleni. L'allenamento Ú un processo costoso e che richiede tempo . Generalmente Ú meglio usare un modello pre-allenato per ottenere risultati migliori velocemente, utilizzando solo una frazione delle risorse neccesarie per l'allenamento.
-
-Crea un modello pre-allenoto con [`~TFPreTrainedModel.from_pretrained`]:
-
-```py
->>> tf_model = TFDistilBertModel.from_pretrained("distilbert-base-uncased")
-```
-
-Quando carichi pesi pre-allenati, la configurazione del modello predefinito Ăš automaticamente caricato se il modello Ăš fornito da đ€ Transformers. Tuttavia, puoi ancora sostituire gli attributi - alcuni o tutti - di configurazione del modello predefinito con i tuoi se lo desideri:
-
-```py
->>> tf_model = TFDistilBertModel.from_pretrained("distilbert-base-uncased", config=my_config)
-```
-
-
-
-
-### Model head
-
-A questo punto, hai un modello DistilBERT base i cui output sono gli *hidden states* (in italiano stati nascosti). Gli stati nascosti sono passati come input a un model head per produrre l'output finale. đ€ Transformers fornisce un model head diverso per ogni attivitĂ fintanto che il modello supporta l'attivitĂ (i.e., non puoi usare DistilBERT per un attivitĂ sequence-to-sequence come la traduzione).
-
-
-
-Per esempio, [`DistilBertForSequenceClassification`] Ăš un modello DistilBERT base con una testa di classificazione per sequenze. La sequenza di classificazione head Ăš uno strato lineare sopra gli output ragruppati.
-
-```py
->>> from transformers import DistilBertForSequenceClassification
-
->>> model = DistilBertForSequenceClassification.from_pretrained("distilbert-base-uncased")
-```
-
-Riutilizza facilmente questo checkpoint per un'altra attivitĂ passando ad un model head differente. Per un attivitĂ di risposta alle domande, utilizzerai il model head [`DistilBertForQuestionAnswering`]. La head per compiti di question answering Ăš simile alla classificazione di sequenza head tranne per il fatto che Ăš uno strato lineare sopra l'output degli stati nascosti (hidden states in inglese)
-
-```py
->>> from transformers import DistilBertForQuestionAnswering
-
->>> model = DistilBertForQuestionAnswering.from_pretrained("distilbert-base-uncased")
-```
-
-
-Per esempio, [`TFDistilBertForSequenceClassification`] Ăš un modello DistilBERT base con classificazione di sequenza head. La classificazione di sequenza head Ăš uno strato lineare sopra gli output raggruppati.
-
-```py
->>> from transformers import TFDistilBertForSequenceClassification
-
->>> tf_model = TFDistilBertForSequenceClassification.from_pretrained("distilbert-base-uncased")
-```
-
-Riutilizza facilmente questo checkpoint per un altra attivitĂ passando ad un modello head diverso. Per un attivitĂ di risposta alle domande, utilizzerai il model head [`TFDistilBertForQuestionAnswering`]. Il head di risposta alle domande Ăš simile alla sequenza di classificazione head tranne per il fatto che Ăš uno strato lineare sopra l'output degli stati nascosti (hidden states in inglese)
-
-```py
->>> from transformers import TFDistilBertForQuestionAnswering
-
->>> tf_model = TFDistilBertForQuestionAnswering.from_pretrained("distilbert-base-uncased")
-```
-
-
-
-## Tokenizer
-
-L'ultima classe base di cui hai bisogno prima di utilizzare un modello per i dati testuali Ăš un [tokenizer](main_classes/tokenizer) per convertire il testo grezzo in tensori. Ci sono due tipi di tokenizer che puoi usare con đ€ Transformers:
-
-- [`PreTrainedTokenizer`]: un'implementazione Python di un tokenizer.
-- [`PreTrainedTokenizerFast`]: un tokenizer dalla nostra libreria [đ€ Tokenizer](https://huggingface.co/docs/tokenizers/python/latest/) basata su Rust. Questo tipo di tokenizer Ăš significativamente piĂč veloce, specialmente durante la batch tokenization, grazie alla sua implementazione Rust. Il tokenizer veloce offre anche metodi aggiuntivi come *offset mapping* che associa i token alle loro parole o caratteri originali.
-
-Entrambi i tokenizer supportano metodi comuni come la codifica e la decodifica, l'aggiunta di nuovi token e la gestione di token speciali.
-
-
-
-Non tutti i modelli supportano un tokenizer veloce. Dai un'occhiata a questo [tabella](index#supported-frameworks) per verificare se un modello ha il supporto per tokenizer veloce.
-
-
-
-Se hai addestrato il tuo tokenizer, puoi crearne uno dal tuo file *vocabolario*:
-
-```py
->>> from transformers import DistilBertTokenizer
-
->>> my_tokenizer = DistilBertTokenizer(vocab_file="my_vocab_file.txt", do_lower_case=False, padding_side="left")
-```
-
-Ă importante ricordare che il vocabolario di un tokenizer personalizzato sarĂ diverso dal vocabolario generato dal tokenizer di un modello preallenato. Ă necessario utilizzare il vocabolario di un modello preallenato se si utilizza un modello preallenato, altrimenti gli input non avranno senso. Crea un tokenizer con il vocabolario di un modello preallenato con la classe [`DistilBertTokenizer`]:
-
-```py
->>> from transformers import DistilBertTokenizer
-
->>> slow_tokenizer = DistilBertTokenizer.from_pretrained("distilbert-base-uncased")
-```
-
-Crea un tokenizer veloce con la classe [`DistilBertTokenizerFast`]:
-
-```py
->>> from transformers import DistilBertTokenizerFast
-
->>> fast_tokenizer = DistilBertTokenizerFast.from_pretrained("distilbert-base-uncased")
-```
-
-
-
-Per l'impostazione predefinita, [`AutoTokenizer`] proverĂ a caricare un tokenizer veloce. Puoi disabilitare questo comportamento impostando `use_fast=False` in `from_pretrained`.
-
-
-
-## Estrattore Di Feature
-
-Un estrattore di caratteristiche (feature in inglese) elabora input audio o immagini. Eredita dalla classe [`~feature_extraction_utils.FeatureExtractionMixin`] base e puĂČ anche ereditare dalla classe [`ImageFeatureExtractionMixin`] per l'elaborazione delle caratteristiche dell'immagine o dalla classe [`SequenceFeatureExtractor`] per l'elaborazione degli input audio.
-
-A seconda che tu stia lavorando a un'attivitĂ audio o visiva, crea un estrattore di caratteristiche associato al modello che stai utilizzando. Ad esempio, crea un [`ViTFeatureExtractor`] predefinito se stai usando [ViT](model_doc/vit) per la classificazione delle immagini:
-
-```py
->>> from transformers import ViTFeatureExtractor
-
->>> vit_extractor = ViTFeatureExtractor()
->>> print(vit_extractor)
-ViTFeatureExtractor {
- "do_normalize": true,
- "do_resize": true,
- "feature_extractor_type": "ViTFeatureExtractor",
- "image_mean": [
- 0.5,
- 0.5,
- 0.5
- ],
- "image_std": [
- 0.5,
- 0.5,
- 0.5
- ],
- "resample": 2,
- "size": 224
-}
-```
-
-
-
-Se non stai cercando alcuna personalizzazione, usa il metodo `from_pretrained` per caricare i parametri di default dell'estrattore di caratteristiche di un modello.
-
-
-
-Modifica uno qualsiasi dei parametri [`ViTFeatureExtractor`] per creare il tuo estrattore di caratteristiche personalizzato:
-
-```py
->>> from transformers import ViTFeatureExtractor
-
->>> my_vit_extractor = ViTFeatureExtractor(resample="PIL.Image.BOX", do_normalize=False, image_mean=[0.3, 0.3, 0.3])
->>> print(my_vit_extractor)
-ViTFeatureExtractor {
- "do_normalize": false,
- "do_resize": true,
- "feature_extractor_type": "ViTFeatureExtractor",
- "image_mean": [
- 0.3,
- 0.3,
- 0.3
- ],
- "image_std": [
- 0.5,
- 0.5,
- 0.5
- ],
- "resample": "PIL.Image.BOX",
- "size": 224
-}
-```
-
-Per gli input audio, puoi creare un [`Wav2Vec2FeatureExtractor`] e personalizzare i parametri in modo simile:
-
-```py
->>> from transformers import Wav2Vec2FeatureExtractor
-
->>> w2v2_extractor = Wav2Vec2FeatureExtractor()
->>> print(w2v2_extractor)
-Wav2Vec2FeatureExtractor {
- "do_normalize": true,
- "feature_extractor_type": "Wav2Vec2FeatureExtractor",
- "feature_size": 1,
- "padding_side": "right",
- "padding_value": 0.0,
- "return_attention_mask": false,
- "sampling_rate": 16000
-}
-```
-
-## Processore
-
-Per modelli che supportano attivitĂ multimodali, đ€ Transformers offre una classe di processore che racchiude comodamente un estrattore di caratteristiche e un tokenizer in un unico oggetto. Ad esempio, utilizziamo [`Wav2Vec2Processor`] per un'attivitĂ di riconoscimento vocale automatico (ASR). ASR trascrive l'audio in testo, quindi avrai bisogno di un estrattore di caratteristiche e di un tokenizer.
-
-Crea un estrattore di feature per gestire gli input audio:
-
-```py
->>> from transformers import Wav2Vec2FeatureExtractor
-
->>> feature_extractor = Wav2Vec2FeatureExtractor(padding_value=1.0, do_normalize=True)
-```
-
-Crea un tokenizer per gestire gli input di testo:
-
-```py
->>> from transformers import Wav2Vec2CTCTokenizer
-
->>> tokenizer = Wav2Vec2CTCTokenizer(vocab_file="my_vocab_file.txt")
-```
-
-Combinare l'estrattore di caratteristiche e il tokenizer in [`Wav2Vec2Processor`]:
-
-```py
->>> from transformers import Wav2Vec2Processor
-
->>> processor = Wav2Vec2Processor(feature_extractor=feature_extractor, tokenizer=tokenizer)
-```
-
-Con due classi di base - configurazione e modello - e una classe di preelaborazione aggiuntiva (tokenizer, estrattore di caratteristiche o processore), puoi creare qualsiasi modello supportato da đ€ Transformers. Ognuna di queste classi base Ăš configurabile, consentendoti di utilizzare gli attributi specifici che desideri. Ă possibile impostare facilmente un modello per l'addestramento o modificare un modello preallenato esistente per la messa a punto.
\ No newline at end of file
diff --git a/docs/source/it/custom_models.md b/docs/source/it/custom_models.md
new file mode 100644
index 000000000000..b0cdf4cd7bf0
--- /dev/null
+++ b/docs/source/it/custom_models.md
@@ -0,0 +1,359 @@
+
+
+# Condividere modelli personalizzati
+La libreria đ€ Transformers Ăš studiata per essere facilmente estendibile. Il codice di ogni modello Ăš interamente
+situato in una sottocartella del repository senza alcuna astrazione, perciĂČ puoi facilmente copiare il file di un
+modello e modificarlo in base ai tuoi bisogni.
+
+Se stai scrivendo un nuovo modello, potrebbe essere piĂč semplice iniziare da zero. In questo tutorial, ti mostreremo
+come scrivere un modello personalizzato e la sua configurazione in modo che possa essere utilizzato allâinterno di
+Transformers, e come condividerlo con la community (assieme al relativo codice) cosĂŹ che tutte le persone possano usarlo, anche
+se non presente nella libreria đ€ Transformers.
+
+Illustriamo tutto questo su un modello ResNet, avvolgendo la classe ResNet della
+[libreria timm](https://github.com/rwightman/pytorch-image-models) in un [`PreTrainedModel`].
+
+## Scrivere una configurazione personalizzata
+Prima di iniziare a lavorare al modello, scriviamone la configurazione. La configurazione di un modello Ăš un oggetto
+che contiene tutte le informazioni necessarie per la build del modello. Come vedremo nella prossima sezione, il
+modello puĂČ soltanto essere inizializzato tramite `config`, per cui dovremo rendere tale oggetto piĂč completo possibile.
+
+Nel nostro esempio, prenderemo un paio di argomenti della classe ResNet che potremmo voler modificare.
+Configurazioni differenti ci daranno quindi i differenti possibili tipi di ResNet. Salveremo poi questi argomenti,
+dopo averne controllato la validitĂ .
+
+```python
+from transformers import PretrainedConfig
+from typing import List
+
+
+class ResnetConfig(PretrainedConfig):
+ model_type = "resnet"
+
+ def __init__(
+ self,
+ block_type="bottleneck",
+ layers: List[int] = [3, 4, 6, 3],
+ num_classes: int = 1000,
+ input_channels: int = 3,
+ cardinality: int = 1,
+ base_width: int = 64,
+ stem_width: int = 64,
+ stem_type: str = "",
+ avg_down: bool = False,
+ **kwargs,
+ ):
+ if block_type not in ["basic", "bottleneck"]:
+ raise ValueError(f"`block_type` must be 'basic' or bottleneck', got {block_type}.")
+ if stem_type not in ["", "deep", "deep-tiered"]:
+ raise ValueError(f"`stem_type` must be '', 'deep' or 'deep-tiered', got {stem_type}.")
+
+ self.block_type = block_type
+ self.layers = layers
+ self.num_classes = num_classes
+ self.input_channels = input_channels
+ self.cardinality = cardinality
+ self.base_width = base_width
+ self.stem_width = stem_width
+ self.stem_type = stem_type
+ self.avg_down = avg_down
+ super().__init__(**kwargs)
+```
+
+Le tre cose piĂč importanti da ricordare quando scrivi le tue configurazioni sono le seguenti:
+- Devi ereditare da `Pretrainedconfig`,
+- Il metodo `__init__` del tuo `Pretrainedconfig` deve accettare i kwargs,
+- I `kwargs` devono essere passati alla superclass `__init__`
+
+LâereditĂ Ăš importante per assicurarsi di ottenere tutte le funzionalitĂ della libreria đ€ transformers,
+mentre gli altri due vincoli derivano dal fatto che un `Pretrainedconfig` ha piĂč campi di quelli che stai settando.
+Quando ricarichi una config da un metodo `from_pretrained`, questi campi devono essere accettati dalla tua config e
+poi inviati alla superclasse.
+
+Definire un `model_type` per la tua configurazione (qua `model_type = âresnetâ`) non Ăš obbligatorio, a meno che tu
+non voglia registrare il modello con le classi Auto (vedi l'ultima sezione).
+
+Una volta completato, puoi facilmente creare e salvare la tua configurazione come faresti con ogni altra configurazione
+di modelli della libreria. Ecco come possiamo creare la config di un resnet50d e salvarlo:
+
+```py
+resnet50d_config = ResnetConfig(block_type="bottleneck", stem_width=32, stem_type="deep", avg_down=True)
+resnet50d_config.save_pretrained("custom-resnet")
+```
+
+Questo salverĂ un file chiamato `config.json` all'interno della cartella `custom-resnet`. Potrai poi ricaricare la tua
+config con il metodo `from_pretrained`.
+
+```py
+resnet50d_config = ResnetConfig.from_pretrained("custom-resnet")
+```
+
+Puoi anche usare qualunque altro metodo della classe [`PretrainedConfig`], come [`~PretrainedConfig.push_to_hub`]
+per caricare direttamente la tua configurazione nell'hub.
+
+## Scrivere un modello personalizzato
+
+Ora che abbiamo la nostra configurazione ResNet, possiamo continuare a scrivere il modello. In realtĂ , ne scriveremo
+due: uno che estrae le features nascoste da una batch di immagini (come [`BertModel`]) e uno che Ăš utilizzabile per
+la classificazione di immagini (come [`BertModelForSequenceClassification`]).
+
+Come abbiamo menzionato in precedenza, scriveremo soltanto un wrapper del modello, per mantenerlo semplice ai fini di
+questo esempio. L'unica cosa che dobbiamo fare prima di scrivere questa classe Ăš una mappatura fra i tipi di blocco e
+le vere classi dei blocchi. Successivamente il modello Ăš definito tramite la configurazione, passando tutto quanto alla
+classe `ResNet`.
+
+```py
+from transformers import PreTrainedModel
+from timm.models.resnet import BasicBlock, Bottleneck, ResNet
+from .configuration_resnet import ResnetConfig
+
+
+BLOCK_MAPPING = {"basic": BasicBlock, "bottleneck": Bottleneck}
+
+
+class ResnetModel(PreTrainedModel):
+ config_class = ResnetConfig
+
+ def __init__(self, config):
+ super().__init__(config)
+ block_layer = BLOCK_MAPPING[config.block_type]
+ self.model = ResNet(
+ block_layer,
+ config.layers,
+ num_classes=config.num_classes,
+ in_chans=config.input_channels,
+ cardinality=config.cardinality,
+ base_width=config.base_width,
+ stem_width=config.stem_width,
+ stem_type=config.stem_type,
+ avg_down=config.avg_down,
+ )
+
+ def forward(self, tensor):
+ return self.model.forward_features(tensor)
+```
+
+Per il modello che classificherĂ le immagini, cambiamo soltanto il metodo forward:
+
+```py
+import torch
+
+
+class ResnetModelForImageClassification(PreTrainedModel):
+ config_class = ResnetConfig
+
+ def __init__(self, config):
+ super().__init__(config)
+ block_layer = BLOCK_MAPPING[config.block_type]
+ self.model = ResNet(
+ block_layer,
+ config.layers,
+ num_classes=config.num_classes,
+ in_chans=config.input_channels,
+ cardinality=config.cardinality,
+ base_width=config.base_width,
+ stem_width=config.stem_width,
+ stem_type=config.stem_type,
+ avg_down=config.avg_down,
+ )
+
+ def forward(self, tensor, labels=None):
+ logits = self.model(tensor)
+ if labels is not None:
+ loss = torch.nn.cross_entropy(logits, labels)
+ return {"loss": loss, "logits": logits}
+ return {"logits": logits}
+```
+
+Nota come, in entrambi i casi, ereditiamo da `PreTrainedModel` e chiamiamo l'inizializzazione della superclasse
+con il metodo `config` (un po' come quando scrivi un normale `torch.nn.Module`). La riga che imposta la `config_class`
+non Ăš obbligatoria, a meno che tu non voglia registrare il modello con le classi Auto (vedi l'ultima sezione).
+
+
+
+Se il tuo modello Ăš molto simile a un modello all'interno della libreria, puoi ri-usare la stessa configurazione di quel modello.
+
+
+
+Puoi fare in modo che il tuo modello restituisca in output qualunque cosa tu voglia, ma far restituire un dizionario
+come abbiamo fatto per `ResnetModelForImageClassification`, con la funzione di perdita inclusa quando vengono passate le labels,
+renderĂ il tuo modello direttamente utilizzabile all'interno della classe [`Trainer`]. Utilizzare altri formati di output va bene
+se hai in progetto di utilizzare un tuo loop di allenamento, o se utilizzerai un'altra libreria per l'addestramento.
+
+Ora che abbiamo la classe del nostro modello, creiamone uno:
+
+```py
+resnet50d = ResnetModelForImageClassification(resnet50d_config)
+```
+
+Ribadiamo, puoi usare qualunque metodo dei [`PreTrainedModel`], come [`~PreTrainedModel.save_pretrained`] o
+[`~PreTrainedModel.push_to_hub`]. Utilizzeremo quest'ultimo nella prossima sezione, e vedremo come caricare i pesi del
+modello assieme al codice del modello stesso. Ma prima, carichiamo alcuni pesi pre-allenati all'interno del nostro modello.
+
+Nel tuo caso specifico, probabilmente allenerai il tuo modello sui tuoi dati. Per velocizzare in questo tutorial,
+utilizzeremo la versione pre-allenata del resnet50d. Dato che il nostro modello Ăš soltanto un wrapper attorno a quel modello,
+sarĂ facile trasferirne i pesi:
+
+```py
+import timm
+
+pretrained_model = timm.create_model("resnet50d", pretrained=True)
+resnet50d.model.load_state_dict(pretrained_model.state_dict())
+```
+
+Vediamo adesso come assicurarci che quando facciamo [`~PreTrainedModel.save_pretrained`] o [`~PreTrainedModel.push_to_hub`],
+il codice del modello venga salvato.
+
+## Inviare il codice all'Hub
+
+
+
+Questa API Ăš sperimentale e potrebbe avere alcuni cambiamenti nei prossimi rilasci.
+
+
+
+Innanzitutto, assicurati che il tuo modello sia completamente definito in un file `.py`. PuĂČ sfruttare import relativi
+ad altri file, purchĂš questi siano nella stessa directory (non supportiamo ancora sotto-moduli per questa funzionalitĂ ).
+Per questo esempio, definiremo un file `modeling_resnet.py` e un file `configuration_resnet.py` in una cartella dell'attuale
+working directory chiamata `resnet_model`. Il file configuration contiene il codice per `ResnetConfig` e il file modeling
+contiene il codice di `ResnetModel` e `ResnetModelForImageClassification`.
+
+```
+.
+âââ resnet_model
+ âââ __init__.py
+ âââ configuration_resnet.py
+ âââ modeling_resnet.py
+```
+
+Il file `__init__.py` puĂČ essere vuoto, serve solo perchĂš Python capisca che `resnet_model` puĂČ essere utilizzato come un modulo.
+
+
+
+Se stai copiando i file relativi alla modellazione della libreria, dovrai sostituire tutti gli import relativi in cima al file con import del
+ pacchetto `transformers`.
+
+
+
+Nota che puoi ri-utilizzare (o usare come sottoclassi) un modello/configurazione esistente.
+
+Per condividere il tuo modello con la community, segui questi passi: prima importa il modello ResNet e la sua configurazione
+dai nuovi file creati:
+
+```py
+from resnet_model.configuration_resnet import ResnetConfig
+from resnet_model.modeling_resnet import ResnetModel, ResnetModelForImageClassification
+```
+
+DopodichĂš dovrai dire alla libreria che vuoi copiare i file con il codice di quegli oggetti quando utilizzi il metodo
+`save_pretrained` e registrarli in modo corretto con una Auto classe (specialmente per i modelli). Utilizza semplicemente:
+
+```py
+ResnetConfig.register_for_auto_class()
+ResnetModel.register_for_auto_class("AutoModel")
+ResnetModelForImageClassification.register_for_auto_class("AutoModelForImageClassification")
+```
+
+Nota che non c'Ăš bisogno di specificare una Auto classe per la configurazione (c'Ăš solo una Auto classe per le configurazioni,
+[`AutoConfig`], ma Ăš diversa per i modelli). Il tuo modello personalizato potrebbe essere utilizzato per diverse tasks,
+per cui devi specificare quale delle classi Auto Ăš quella corretta per il tuo modello.
+
+Successivamente, creiamo i modelli e la config come abbiamo fatto in precedenza:
+
+```py
+resnet50d_config = ResnetConfig(block_type="bottleneck", stem_width=32, stem_type="deep", avg_down=True)
+resnet50d = ResnetModelForImageClassification(resnet50d_config)
+
+pretrained_model = timm.create_model("resnet50d", pretrained=True)
+resnet50d.model.load_state_dict(pretrained_model.state_dict())
+```
+
+Adesso, per inviare il modello all'Hub, assicurati di aver effettuato l'accesso. Lancia dal tuo terminale:
+
+```bash
+huggingface-cli login
+```
+
+O da un notebook:
+
+```py
+from huggingface_hub import notebook_login
+
+notebook_login()
+```
+
+Potrai poi inviare il tutto sul tuo profilo (o di un'organizzazione di cui fai parte) in questo modo:
+
+```py
+resnet50d.push_to_hub("custom-resnet50d")
+```
+
+Oltre ai pesi del modello e alla configurazione in formato json, questo ha anche copiato i file `.py` modeling e
+configuration all'interno della cartella `custom-resnet50d` e ha caricato i risultati sull'Hub. Puoi controllare
+i risultati in questa [model repo](https://huggingface.co/sgugger/custom-resnet50d).
+
+Puoi controllare il tutorial di condivisione [tutorial di condivisione](model_sharing) per piĂč informazioni sul
+metodo con cui inviare all'Hub.
+
+## Usare un modello con codice personalizzato
+
+Puoi usare ogni configurazione, modello o tokenizer con file di codice personalizzati nella sua repository
+con le classi Auto e il metodo `from_pretrained`. Tutti i files e il codice caricati sull'Hub sono scansionati da malware
+(fai riferimento alla documentazione [Hub security](https://huggingface.co/docs/hub/security#malware-scanning) per piĂč informazioni),
+ma dovresti comunque assicurarti dell'affidabilitĂ del codice e dell'autore per evitare di eseguire codice dannoso sulla tua macchina.
+Imposta `trust_remote_code=True` per usare un modello con codice personalizzato:
+
+```py
+from transformers import AutoModelForImageClassification
+
+model = AutoModelForImageClassification.from_pretrained("sgugger/custom-resnet50d", trust_remote_code=True)
+```
+
+Inoltre, raccomandiamo fortemente di passare un hash del commit come `revision` per assicurarti che le autrici o gli autori del modello
+non abbiano modificato il codice con alcune nuove righe dannose (a meno che non ti fidi completamente della fonte):
+
+```py
+commit_hash = "ed94a7c6247d8aedce4647f00f20de6875b5b292"
+model = AutoModelForImageClassification.from_pretrained(
+ "sgugger/custom-resnet50d", trust_remote_code=True, revision=commit_hash
+)
+```
+
+Nota che quando cerchi la storia dei commit della repo del modello sull'Hub, c'Ăš un bottone con cui facilmente copiare il
+commit hash di ciascun commit.
+
+## Registrare un modello con codice personalizzato nelle classi Auto
+
+Se stai scrivendo una libreria che estende đ€ Transformers, potresti voler estendere le classi Auto per includere il tuo modello.
+Questo Ăš diverso dall'inviare codice nell'Hub: gli utenti dovranno importare la tua libreria per ottenere il modello personalizzato
+(anzichĂš scaricare automaticamente il modello dall'Hub).
+
+FinchĂš il tuo file di configurazione ha un attributo `model_type` diverso dai model types esistenti, e finchĂš le tue
+classi modello hanno i corretti attributi `config_class`, potrai semplicemente aggiungerli alle classi Auto come segue:
+
+```py
+from transformers import AutoConfig, AutoModel, AutoModelForImageClassification
+
+AutoConfig.register("resnet", ResnetConfig)
+AutoModel.register(ResnetConfig, ResnetModel)
+AutoModelForImageClassification.register(ResnetConfig, ResnetModelForImageClassification)
+```
+
+Nota che il primo argomento utilizzato quando registri la configurazione di un modello personalizzato con [`AutoConfig`]
+deve corrispondere al `model_type` della tua configurazione personalizzata, ed il primo argomento utilizzato quando
+registri i tuoi modelli personalizzati in una qualunque classe Auto del modello deve corrispondere alla `config_class`
+di quei modelli.
diff --git a/docs/source/it/custom_models.mdx b/docs/source/it/custom_models.mdx
deleted file mode 100644
index b4b0302e29e3..000000000000
--- a/docs/source/it/custom_models.mdx
+++ /dev/null
@@ -1,355 +0,0 @@
-
-
-# Condividere modelli personalizzati
-La libreria đ€ Transformers Ăš studiata per essere facilmente estendibile. Il codice di ogni modello Ăš interamente
-situato in una sottocartella del repository senza alcuna astrazione, perciĂČ puoi facilmente copiare il file di un
-modello e modificarlo in base ai tuoi bisogni.
-
-Se stai scrivendo un nuovo modello, potrebbe essere piĂč semplice iniziare da zero. In questo tutorial, ti mostreremo
-come scrivere un modello personalizzato e la sua configurazione in modo che possa essere utilizzato allâinterno di
-Transformers, e come condividerlo con la community (assieme al relativo codice) cosĂŹ che tutte le persone possano usarlo, anche
-se non presente nella libreria đ€ Transformers.
-
-Illustriamo tutto questo su un modello ResNet, avvolgendo la classe ResNet della
-[libreria timm](https://github.com/rwightman/pytorch-image-models) in un [`PreTrainedModel`].
-
-## Scrivere una configurazione personalizzata
-Prima di iniziare a lavorare al modello, scriviamone la configurazione. La configurazione di un modello Ăš un oggetto
-che contiene tutte le informazioni necessarie per la build del modello. Come vedremo nella prossima sezione, il
-modello puĂČ soltanto essere inizializzato tramite `config`, per cui dovremo rendere tale oggetto piĂč completo possibile.
-
-Nel nostro esempio, prenderemo un paio di argomenti della classe ResNet che potremmo voler modificare.
-Configurazioni differenti ci daranno quindi i differenti possibili tipi di ResNet. Salveremo poi questi argomenti,
-dopo averne controllato la validitĂ .
-
-```python
-from transformers import PretrainedConfig
-from typing import List
-
-
-class ResnetConfig(PretrainedConfig):
- model_type = "resnet"
-
- def __init__(
- self,
- block_type="bottleneck",
- layers: List[int] = [3, 4, 6, 3],
- num_classes: int = 1000,
- input_channels: int = 3,
- cardinality: int = 1,
- base_width: int = 64,
- stem_width: int = 64,
- stem_type: str = "",
- avg_down: bool = False,
- **kwargs,
- ):
- if block_type not in ["basic", "bottleneck"]:
- raise ValueError(f"`block_type` must be 'basic' or bottleneck', got {block_type}.")
- if stem_type not in ["", "deep", "deep-tiered"]:
- raise ValueError(f"`stem_type` must be '', 'deep' or 'deep-tiered', got {stem_type}.")
-
- self.block_type = block_type
- self.layers = layers
- self.num_classes = num_classes
- self.input_channels = input_channels
- self.cardinality = cardinality
- self.base_width = base_width
- self.stem_width = stem_width
- self.stem_type = stem_type
- self.avg_down = avg_down
- super().__init__(**kwargs)
-```
-
-Le tre cose piĂč importanti da ricordare quando scrivi le tue configurazioni sono le seguenti:
-- Devi ereditare da `Pretrainedconfig`,
-- Il metodo `__init__` del tuo `Pretrainedconfig` deve accettare i kwargs,
-- I `kwargs` devono essere passati alla superclass `__init__`
-
-LâereditĂ Ăš importante per assicurarsi di ottenere tutte le funzionalitĂ della libreria đ€ transformers,
-mentre gli altri due vincoli derivano dal fatto che un `Pretrainedconfig` ha piĂč campi di quelli che stai settando.
-Quando ricarichi una config da un metodo `from_pretrained`, questi campi devono essere accettati dalla tua config e
-poi inviati alla superclasse.
-
-Definire un `model_type` per la tua configurazione (qua `model_type = âresnetâ`) non Ăš obbligatorio, a meno che tu
-non voglia registrare il modello con le classi Auto (vedi l'ultima sezione).
-
-Una volta completato, puoi facilmente creare e salvare la tua configurazione come faresti con ogni altra configurazione
-di modelli della libreria. Ecco come possiamo creare la config di un resnet50d e salvarlo:
-
-```py
-resnet50d_config = ResnetConfig(block_type="bottleneck", stem_width=32, stem_type="deep", avg_down=True)
-resnet50d_config.save_pretrained("custom-resnet")
-```
-
-Questo salverĂ un file chiamato `config.json` all'interno della cartella `custom-resnet`. Potrai poi ricaricare la tua
-config con il metodo `from_pretrained`.
-
-```py
-resnet50d_config = ResnetConfig.from_pretrained("custom-resnet")
-```
-
-Puoi anche usare qualunque altro metodo della classe [`PretrainedConfig`], come [`~PretrainedConfig.push_to_hub`]
-per caricare direttamente la tua configurazione nell'hub.
-
-## Scrivere un modello personalizzato
-
-Ora che abbiamo la nostra configurazione ResNet, possiamo continuare a scrivere il modello. In realtĂ , ne scriveremo
-due: uno che estrae le features nascoste da una batch di immagini (come [`BertModel`]) e uno che Ăš utilizzabile per
-la classificazione di immagini (come [`BertModelForSequenceClassification`]).
-
-Come abbiamo menzionato in precedenza, scriveremo soltanto un wrapper del modello, per mantenerlo semplice ai fini di
-questo esempio. L'unica cosa che dobbiamo fare prima di scrivere questa classe Ăš una mappatura fra i tipi di blocco e
-le vere classi dei blocchi. Successivamente il modello Ăš definito tramite la configurazione, passando tutto quanto alla
-classe `ResNet`.
-
-```py
-from transformers import PreTrainedModel
-from timm.models.resnet import BasicBlock, Bottleneck, ResNet
-from .configuration_resnet import ResnetConfig
-
-
-BLOCK_MAPPING = {"basic": BasicBlock, "bottleneck": Bottleneck}
-
-
-class ResnetModel(PreTrainedModel):
- config_class = ResnetConfig
-
- def __init__(self, config):
- super().__init__(config)
- block_layer = BLOCK_MAPPING[config.block_type]
- self.model = ResNet(
- block_layer,
- config.layers,
- num_classes=config.num_classes,
- in_chans=config.input_channels,
- cardinality=config.cardinality,
- base_width=config.base_width,
- stem_width=config.stem_width,
- stem_type=config.stem_type,
- avg_down=config.avg_down,
- )
-
- def forward(self, tensor):
- return self.model.forward_features(tensor)
-```
-
-Per il modello che classificherĂ le immagini, cambiamo soltanto il metodo forward:
-
-```py
-import torch
-
-
-class ResnetModelForImageClassification(PreTrainedModel):
- config_class = ResnetConfig
-
- def __init__(self, config):
- super().__init__(config)
- block_layer = BLOCK_MAPPING[config.block_type]
- self.model = ResNet(
- block_layer,
- config.layers,
- num_classes=config.num_classes,
- in_chans=config.input_channels,
- cardinality=config.cardinality,
- base_width=config.base_width,
- stem_width=config.stem_width,
- stem_type=config.stem_type,
- avg_down=config.avg_down,
- )
-
- def forward(self, tensor, labels=None):
- logits = self.model(tensor)
- if labels is not None:
- loss = torch.nn.cross_entropy(logits, labels)
- return {"loss": loss, "logits": logits}
- return {"logits": logits}
-```
-
-Nota come, in entrambi i casi, ereditiamo da `PreTrainedModel` e chiamiamo l'inizializzazione della superclasse
-con il metodo `config` (un po' come quando scrivi un normale `torch.nn.Module`). La riga che imposta la `config_class`
-non Ăš obbligatoria, a meno che tu non voglia registrare il modello con le classi Auto (vedi l'ultima sezione).
-
-
-
-Se il tuo modello Ăš molto simile a un modello all'interno della libreria, puoi ri-usare la stessa configurazione di quel modello.
-
-
-
-Puoi fare in modo che il tuo modello restituisca in output qualunque cosa tu voglia, ma far restituire un dizionario
-come abbiamo fatto per `ResnetModelForImageClassification`, con la funzione di perdita inclusa quando vengono passate le labels,
-renderĂ il tuo modello direttamente utilizzabile all'interno della classe [`Trainer`]. Utilizzare altri formati di output va bene
-se hai in progetto di utilizzare un tuo loop di allenamento, o se utilizzerai un'altra libreria per l'addestramento.
-
-Ora che abbiamo la classe del nostro modello, creiamone uno:
-
-```py
-resnet50d = ResnetModelForImageClassification(resnet50d_config)
-```
-
-Ribadiamo, puoi usare qualunque metodo dei [`PreTrainedModel`], come [`~PreTrainedModel.save_pretrained`] o
-[`~PreTrainedModel.push_to_hub`]. Utilizzeremo quest'ultimo nella prossima sezione, e vedremo come caricare i pesi del
-modello assieme al codice del modello stesso. Ma prima, carichiamo alcuni pesi pre-allenati all'interno del nostro modello.
-
-Nel tuo caso specifico, probabilmente allenerai il tuo modello sui tuoi dati. Per velocizzare in questo tutorial,
-utilizzeremo la versione pre-allenata del resnet50d. Dato che il nostro modello Ăš soltanto un wrapper attorno a quel modello,
-sarĂ facile trasferirne i pesi:
-
-```py
-import timm
-
-pretrained_model = timm.create_model("resnet50d", pretrained=True)
-resnet50d.model.load_state_dict(pretrained_model.state_dict())
-```
-
-Vediamo adesso come assicurarci che quando facciamo [`~PreTrainedModel.save_pretrained`] o [`~PreTrainedModel.push_to_hub`],
-il codice del modello venga salvato.
-
-## Inviare il codice all'Hub
-
-
-
-Questa API Ăš sperimentale e potrebbe avere alcuni cambiamenti nei prossimi rilasci.
-
-
-
-Innanzitutto, assicurati che il tuo modello sia completamente definito in un file `.py`. PuĂČ sfruttare import relativi
-ad altri file, purchĂš questi siano nella stessa directory (non supportiamo ancora sotto-moduli per questa funzionalitĂ ).
-Per questo esempio, definiremo un file `modeling_resnet.py` e un file `configuration_resnet.py` in una cartella dell'attuale
-working directory chiamata `resnet_model`. Il file configuration contiene il codice per `ResnetConfig` e il file modeling
-contiene il codice di `ResnetModel` e `ResnetModelForImageClassification`.
-
-```
-.
-âââ resnet_model
- âââ __init__.py
- âââ configuration_resnet.py
- âââ modeling_resnet.py
-```
-
-Il file `__init__.py` puĂČ essere vuoto, serve solo perchĂš Python capisca che `resnet_model` puĂČ essere utilizzato come un modulo.
-
-
-
-Se stai copiando i file relativi alla modellazione della libreria, dovrai sostituire tutti gli import relativi in cima al file con import del
- pacchetto `transformers`.
-
-
-
-Nota che puoi ri-utilizzare (o usare come sottoclassi) un modello/configurazione esistente.
-
-Per condividere il tuo modello con la community, segui questi passi: prima importa il modello ResNet e la sua configurazione
-dai nuovi file creati:
-
-```py
-from resnet_model.configuration_resnet import ResnetConfig
-from resnet_model.modeling_resnet import ResnetModel, ResnetModelForImageClassification
-```
-
-DopodichĂš dovrai dire alla libreria che vuoi copiare i file con il codice di quegli oggetti quando utilizzi il metodo
-`save_pretrained` e registrarli in modo corretto con una Auto classe (specialmente per i modelli). Utilizza semplicemente:
-
-```py
-ResnetConfig.register_for_auto_class()
-ResnetModel.register_for_auto_class("AutoModel")
-ResnetModelForImageClassification.register_for_auto_class("AutoModelForImageClassification")
-```
-
-Nota che non c'Ăš bisogno di specificare una Auto classe per la configurazione (c'Ăš solo una Auto classe per le configurazioni,
-[`AutoConfig`], ma Ăš diversa per i modelli). Il tuo modello personalizato potrebbe essere utilizzato per diverse tasks,
-per cui devi specificare quale delle classi Auto Ăš quella corretta per il tuo modello.
-
-Successivamente, creiamo i modelli e la config come abbiamo fatto in precedenza:
-
-```py
-resnet50d_config = ResnetConfig(block_type="bottleneck", stem_width=32, stem_type="deep", avg_down=True)
-resnet50d = ResnetModelForImageClassification(resnet50d_config)
-
-pretrained_model = timm.create_model("resnet50d", pretrained=True)
-resnet50d.model.load_state_dict(pretrained_model.state_dict())
-```
-
-Adesso, per inviare il modello all'Hub, assicurati di aver effettuato l'accesso. Lancia dal tuo terminale:
-
-```bash
-huggingface-cli login
-```
-
-O da un notebook:
-
-```py
-from huggingface_hub import notebook_login
-
-notebook_login()
-```
-
-Potrai poi inviare il tutto sul tuo profilo (o di un'organizzazione di cui fai parte) in questo modo:
-
-```py
-resnet50d.push_to_hub("custom-resnet50d")
-```
-
-Oltre ai pesi del modello e alla configurazione in formato json, questo ha anche copiato i file `.py` modeling e
-configuration all'interno della cartella `custom-resnet50d` e ha caricato i risultati sull'Hub. Puoi controllare
-i risultati in questa [model repo](https://huggingface.co/sgugger/custom-resnet50d).
-
-Puoi controllare il tutorial di condivisione [tutorial di condivisione](model_sharing) per piĂč informazioni sul
-metodo con cui inviare all'Hub.
-
-## Usare un modello con codice personalizzato
-
-Puoi usare ogni configurazione, modello o tokenizer con file di codice personalizzati nella sua repository
-con le classi Auto e il metodo `from_pretrained`. Tutti i files e il codice caricati sull'Hub sono scansionati da malware
-(fai riferimento alla documentazione [Hub security](https://huggingface.co/docs/hub/security#malware-scanning) per piĂč informazioni),
-ma dovresti comunque assicurarti dell'affidabilitĂ del codice e dell'autore per evitare di eseguire codice dannoso sulla tua macchina.
-Imposta `trust_remote_code=True` per usare un modello con codice personalizzato:
-
-```py
-from transformers import AutoModelForImageClassification
-
-model = AutoModelForImageClassification.from_pretrained("sgugger/custom-resnet50d", trust_remote_code=True)
-```
-
-Inoltre, raccomandiamo fortemente di passare un hash del commit come `revision` per assicurarti che le autrici o gli autori del modello
-non abbiano modificato il codice con alcune nuove righe dannose (a meno che non ti fidi completamente della fonte):
-
-```py
-commit_hash = "ed94a7c6247d8aedce4647f00f20de6875b5b292"
-model = AutoModelForImageClassification.from_pretrained(
- "sgugger/custom-resnet50d", trust_remote_code=True, revision=commit_hash
-)
-```
-
-Nota che quando cerchi la storia dei commit della repo del modello sull'Hub, c'Ăš un bottone con cui facilmente copiare il
-commit hash di ciascun commit.
-
-## Registrare un modello con codice personalizzato nelle classi Auto
-
-Se stai scrivendo una libreria che estende đ€ Transformers, potresti voler estendere le classi Auto per includere il tuo modello.
-Questo Ăš diverso dall'inviare codice nell'Hub: gli utenti dovranno importare la tua libreria per ottenere il modello personalizzato
-(anzichĂš scaricare automaticamente il modello dall'Hub).
-
-FinchĂš il tuo file di configurazione ha un attributo `model_type` diverso dai model types esistenti, e finchĂš le tue
-classi modello hanno i corretti attributi `config_class`, potrai semplicemente aggiungerli alle classi Auto come segue:
-
-```py
-from transformers import AutoConfig, AutoModel, AutoModelForImageClassification
-
-AutoConfig.register("resnet", ResnetConfig)
-AutoModel.register(ResnetConfig, ResnetModel)
-AutoModelForImageClassification.register(ResnetConfig, ResnetModelForImageClassification)
-```
-
-Nota che il primo argomento utilizzato quando registri la configurazione di un modello personalizzato con [`AutoConfig`]
-deve corrispondere al `model_type` della tua configurazione personalizzata, ed il primo argomento utilizzato quando
-registri i tuoi modelli personalizzati in una qualunque classe Auto del modello deve corrispondere alla `config_class`
-di quei modelli.
diff --git a/docs/source/it/debugging.md b/docs/source/it/debugging.md
new file mode 100644
index 000000000000..5c1dab51bd11
--- /dev/null
+++ b/docs/source/it/debugging.md
@@ -0,0 +1,318 @@
+
+
+# Debugging
+
+## Debug dei problemi di rete multi-GPU
+
+Quando addestri o fai inferenza con `DistributedDataParallel` e GPU multiple, se si verificano problemi di intercomunicazione tra processi e/o nodi, puoi utilizzare il seguente script per diagnosticare i problemi della rete.
+
+```bash
+wget https://raw.githubusercontent.com/huggingface/transformers/main/scripts/distributed/torch-distributed-gpu-test.py
+```
+
+Per esempio per testare come 2 GPU interagiscono fai:
+
+```bash
+python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py
+```
+
+Se entrambi i processi sono in grado di comunicare tra loro e di allocare la memoria della GPU, ciascuno di essi stamperĂ lo stato OK.
+
+Per piĂč GPU o nodi adatta gli argumenti nello script.
+
+All'interno dello script di diagnostica troverai molti altri dettagli e anche una guida per eseguirlo in ambiente SLURM.
+
+Un livello di debug superiore Ăš aggiungere la variabile d'ambiente `NCCL_DEBUG=INFO` come di seguito:
+
+```bash
+NCCL_DEBUG=INFO python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py
+```
+
+In questo modo si scaricano molte informazioni di debug relative a NCCL, che puoi cercare online in caso di problemi. Oppure, se non hai la sicurezza di come interpretare l'output, puoi condividere il file di log in una Issue.
+
+## Rilevamento di Underflow e Overflow
+
+
+
+Questa funzionalitĂ al momento Ăš disponibile solo per PyTorch.
+
+
+
+
+
+Per addestramento multi-GPU richiede DDP (`torch.distributed.launch`).
+
+
+
+
+
+Questa funzionalitĂ puĂČ essere usata con modelli basati su `nn.Module`.
+
+
+
+Se inizi a ottenere `loss=NaN` o il modello presenta qualche altro comportamento anomalo a causa di valori `inf` o `nan` in
+attivazioni o nei pesi, Ăš necessario scoprire dove si verifica il primo underflow o overflow e cosa lo ha determinato. Fortunatamente
+Ăš possibile farlo facilmente attivando un modulo speciale che effettuerĂ il rilevamento automaticamente.
+
+Se stai usando [`Trainer`], hai bisogno di aggiungere solo:
+
+```bash
+--debug underflow_overflow
+```
+
+ai normali argomenti della riga di comando, o passa `debug="underflow_overflow"` quando viene creato l'oggetto
+[`TrainingArguments`].
+
+Se stai usando il tuo ciclo di allenamento o un altro trainer, puoi ottenere lo stesso risultato con:
+
+```python
+from .debug_utils import DebugUnderflowOverflow
+
+debug_overflow = DebugUnderflowOverflow(model)
+```
+
+[`~debug_utils.DebugUnderflowOverflow`] inserisce dei ganci nel modello che dopo ogni chiamata
+testeranno le variabili di ingresso e di uscita e anche i pesi del modulo corrispondente. Non appena viene rilevato `inf` o
+o `nan` in almeno un elemento delle attivazioni o dei pesi, il programma lo notifica e stampa un rapporto come il seguente (questo Ăš stato rilevato con `google/mt5-small` sotto fp16 mixed precision):
+
+```
+Detected inf/nan during batch_number=0
+Last 21 forward frames:
+abs min abs max metadata
+ encoder.block.1.layer.1.DenseReluDense.dropout Dropout
+0.00e+00 2.57e+02 input[0]
+0.00e+00 2.85e+02 output
+[...]
+ encoder.block.2.layer.0 T5LayerSelfAttention
+6.78e-04 3.15e+03 input[0]
+2.65e-04 3.42e+03 output[0]
+ None output[1]
+2.25e-01 1.00e+04 output[2]
+ encoder.block.2.layer.1.layer_norm T5LayerNorm
+8.69e-02 4.18e-01 weight
+2.65e-04 3.42e+03 input[0]
+1.79e-06 4.65e+00 output
+ encoder.block.2.layer.1.DenseReluDense.wi_0 Linear
+2.17e-07 4.50e+00 weight
+1.79e-06 4.65e+00 input[0]
+2.68e-06 3.70e+01 output
+ encoder.block.2.layer.1.DenseReluDense.wi_1 Linear
+8.08e-07 2.66e+01 weight
+1.79e-06 4.65e+00 input[0]
+1.27e-04 2.37e+02 output
+ encoder.block.2.layer.1.DenseReluDense.dropout Dropout
+0.00e+00 8.76e+03 input[0]
+0.00e+00 9.74e+03 output
+ encoder.block.2.layer.1.DenseReluDense.wo Linear
+1.01e-06 6.44e+00 weight
+0.00e+00 9.74e+03 input[0]
+3.18e-04 6.27e+04 output
+ encoder.block.2.layer.1.DenseReluDense T5DenseGatedGeluDense
+1.79e-06 4.65e+00 input[0]
+3.18e-04 6.27e+04 output
+ encoder.block.2.layer.1.dropout Dropout
+3.18e-04 6.27e+04 input[0]
+0.00e+00 inf output
+```
+
+L'output di esempio Ăš stato tagliato al centro per brevitĂ .
+
+La seconda colonna mostra il valore dell'elemento piĂč grande in assoluto,cosĂŹ se osserviamo da vicino gli ultimi istanti,
+input e output sono nel range di `1e4`. Questo addestramento Ăš stato eseguito con una mixed precision fp16 e l'ultimo passo usciva fuori (sotto `fp16` il valore piĂč grande prima di `inf` Ăš `64e3`). Per evitare overflows sotto `fp16` le attivazionioni devono rimanere molto al di sotto di `1e4`, perchĂ© `1e4 * 1e4 = 1e8` quindi qualsiasi moltiplicazione di matrice con grandi attivazioni porterĂ a una condizione di overflow numerico.
+
+All'inizio della traccia Ăš possibile scoprire a quale lotto si Ăš verificato il problema (questo `Detected inf/nan during batch_number=0` significa che il problema si Ăš verificato nel primo lotto).
+
+Ogni frame segnalato inizia dichiarando la voce completamente qualificata per il modulo corrispondente per il quale il frame Ăš stato segnalato.
+Se osserviamo il seguente frame:
+
+```
+ encoder.block.2.layer.1.layer_norm T5LayerNorm
+8.69e-02 4.18e-01 weight
+2.65e-04 3.42e+03 input[0]
+1.79e-06 4.65e+00 output
+```
+
+Questo, `encoder.block.2.layer.1.layer_norm` indica che si tratta di un layer norm nel primo layer, del secondo blocco dell'encoder. E le chiamata specifica di `forward` Ăš `T5LayerNorm`.
+
+Osserviamo gli ultimi frame del report:
+
+```
+Detected inf/nan during batch_number=0
+Last 21 forward frames:
+abs min abs max metadata
+[...]
+ encoder.block.2.layer.1.DenseReluDense.wi_0 Linear
+2.17e-07 4.50e+00 weight
+1.79e-06 4.65e+00 input[0]
+2.68e-06 3.70e+01 output
+ encoder.block.2.layer.1.DenseReluDense.wi_1 Linear
+8.08e-07 2.66e+01 weight
+1.79e-06 4.65e+00 input[0]
+1.27e-04 2.37e+02 output
+ encoder.block.2.layer.1.DenseReluDense.wo Linear
+1.01e-06 6.44e+00 weight
+0.00e+00 9.74e+03 input[0]
+3.18e-04 6.27e+04 output
+ encoder.block.2.layer.1.DenseReluDense T5DenseGatedGeluDense
+1.79e-06 4.65e+00 input[0]
+3.18e-04 6.27e+04 output
+ encoder.block.2.layer.1.dropout Dropout
+3.18e-04 6.27e+04 input[0]
+0.00e+00 inf output
+```
+
+L'ultimo frame report per la funzione `Dropout.forward` con la prima voce per l'unico input e la seconda per l'unico output. Si puĂČ notare che Ăš stato richiamato da un attibuto `dropout` dentro la classe `DenseReluDense`. Si puĂČ notare che ciĂČ Ăš avvenuto durante il primo strato, del 2° blocco, durante il primissimo lotto. Infine, gli elementi di input piĂč grandi in assoluto sono stati `6.27e+04` e l'equivalente per l'output era `inf`.
+
+Puoi vedere qui, che `T5DenseGatedGeluDense.forward` risulta in output activations, il cui valore massimo assoluto era circa 62,7K, che Ăš molto vicino al limite massimo di 64K di fp16. Nel prossimo frame abbiamo `Dropout` che rinormalizza i pesi, dopo aver azzerato alcuni elementi, il che spinge il valore massimo assoluto a piĂč di 64K e si verifica un overflow.(`inf`).
+
+Come puoi notare, Ăš nei frames precedenti che occorre esaminare quando i numeri iniziano a diventare molto grandi per i valori fp16.
+
+Confrontiamo il report al codice `models/t5/modeling_t5.py`:
+
+```python
+class T5DenseGatedGeluDense(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.wi_0 = nn.Linear(config.d_model, config.d_ff, bias=False)
+ self.wi_1 = nn.Linear(config.d_model, config.d_ff, bias=False)
+ self.wo = nn.Linear(config.d_ff, config.d_model, bias=False)
+ self.dropout = nn.Dropout(config.dropout_rate)
+ self.gelu_act = ACT2FN["gelu_new"]
+
+ def forward(self, hidden_states):
+ hidden_gelu = self.gelu_act(self.wi_0(hidden_states))
+ hidden_linear = self.wi_1(hidden_states)
+ hidden_states = hidden_gelu * hidden_linear
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.wo(hidden_states)
+ return hidden_states
+```
+
+Ora Ăš facile vedere la chiamata `dropout`, e tutte le chiamate precedenti.
+
+Poiché il rilevamento avviene in un avanzamento (forward hook in eng.), i rapporti vengono creati immeditamente dopo ogni rientro da `forward` (forward returns in eng.).
+
+Tornando al rapporto completo, per agire e risolvere il problema, dobbiamo andare qualche frame piĂč in alto, dove i numeri hanno iniziato a salire, e probabilmente passare alla modalitĂ `fp32`, in modo che i numeri non trabocchino quando vengono moltiplicati o sommati. Naturalmente, potrebbero esserci altre soluzioni. Per esempio, potremmo spegnere temporanemante `amp` se Ăš abilitato, successivamente spostare `forward` in un helper wrapper, come:
+
+```python
+def _forward(self, hidden_states):
+ hidden_gelu = self.gelu_act(self.wi_0(hidden_states))
+ hidden_linear = self.wi_1(hidden_states)
+ hidden_states = hidden_gelu * hidden_linear
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.wo(hidden_states)
+ return hidden_states
+
+
+import torch
+
+
+def forward(self, hidden_states):
+ if torch.is_autocast_enabled():
+ with torch.cuda.amp.autocast(enabled=False):
+ return self._forward(hidden_states)
+ else:
+ return self._forward(hidden_states)
+```
+
+PoichĂ© il rilevatore automatico riporta solo gli ingressi e le uscite di fotogrammi completi, una volta che si sa dove cercare, si puĂČ
+analizzare anche le fasi intermedie di una specifica funzione `forward`. In alcuni casi puoi usare la funzione di supporto `detect_overflow` per indirizzare il rilevatore dove preferisci, ad esempio:
+
+```python
+from debug_utils import detect_overflow
+
+
+class T5LayerFF(nn.Module):
+ [...]
+
+ def forward(self, hidden_states):
+ forwarded_states = self.layer_norm(hidden_states)
+ detect_overflow(forwarded_states, "after layer_norm")
+ forwarded_states = self.DenseReluDense(forwarded_states)
+ detect_overflow(forwarded_states, "after DenseReluDense")
+ return hidden_states + self.dropout(forwarded_states)
+```
+
+Si puĂČ vedere che abbiamo aggiunto 2 di questi e ora teniamo traccia se `inf` o `nan` per `forwarded_states` Ăš stato rilevato
+da qualche parte.
+
+In realtà , il rilevatore li riporta già , perché ciascuna delle chiamate nell'esempio precedente Ú un `nn.Module`, ma
+diciamo che se avessimo dei calcoli diretti locali, questo Ăš il modo in cui lo faremmo.
+
+Inoltre, se si istanzia il debugger nel proprio codice, Ăš possibile modificare il numero di fotogrammi stampati rispetto a
+predefinito, ad esempio.:
+
+```python
+from .debug_utils import DebugUnderflowOverflow
+
+debug_overflow = DebugUnderflowOverflow(model, max_frames_to_save=100)
+```
+
+### Tracciamento della mistura assoluta del lotto specifico e del valore massimo
+
+La stessa classe di debug puĂČ essere utilizzata per il tracciamento per-batch con la funzione di rilevamento di underflow/overflow disattivata.
+
+Supponiamo di voler osservare i valori minimi e massimi assoluti per tutti gli ingredienti di ogni chiamata `forward` di un dato lotto.
+lotto, e che lo si voglia fare solo per i lotti 1 e 3. Si istanzia questa classe come:
+
+```python
+debug_overflow = DebugUnderflowOverflow(model, trace_batch_nums=[1, 3])
+```
+
+Ora i batch completi 1 e 3 saranno tracciati utilizzando lo stesso formato del rilevatore di underflow/overflow.
+
+I batches sono 0-indexed.
+
+Questo Ăš utile se si sa che il programma inizia a comportarsi male dopo un certo numero di batch, in modo da poter avanzare velocemente fino a quell'area.
+direttamente a quell'area. Ecco un esempio di output troncato per questa configurazione:
+
+```
+ *** Starting batch number=1 ***
+abs min abs max metadata
+ shared Embedding
+1.01e-06 7.92e+02 weight
+0.00e+00 2.47e+04 input[0]
+5.36e-05 7.92e+02 output
+[...]
+ decoder.dropout Dropout
+1.60e-07 2.27e+01 input[0]
+0.00e+00 2.52e+01 output
+ decoder T5Stack
+ not a tensor output
+ lm_head Linear
+1.01e-06 7.92e+02 weight
+0.00e+00 1.11e+00 input[0]
+6.06e-02 8.39e+01 output
+ T5ForConditionalGeneration
+ not a tensor output
+
+ *** Starting batch number=3 ***
+abs min abs max metadata
+ shared Embedding
+1.01e-06 7.92e+02 weight
+0.00e+00 2.78e+04 input[0]
+5.36e-05 7.92e+02 output
+[...]
+```
+
+Qui verrĂ scaricato un numero enorme di fotogrammi, tanti quanti sono le chiamate in avanti nel modello, quindi puĂČ essere o non essere quello che volete, ma a volte puĂČ essere piĂč utile usarlo di un classico debugger. Per esempio, se il problema inizia a verificarsi a partire dal lotto numero 150. Quindi Ăš possibile scaricare le tracce dei lotti 149 e 150 e confrontare i punti in cui i numeri hanno iniziato a divergere.
+
+Ă inoltre possibile specificare il numero di batch dopo il quale interrompere l'addestramento, con:
+
+```python
+debug_overflow = DebugUnderflowOverflow(model, trace_batch_nums=[1, 3], abort_after_batch_num=3)
+```
diff --git a/docs/source/it/debugging.mdx b/docs/source/it/debugging.mdx
deleted file mode 100644
index 5b392489eab9..000000000000
--- a/docs/source/it/debugging.mdx
+++ /dev/null
@@ -1,314 +0,0 @@
-
-
-# Debugging
-
-## Debug dei problemi di rete multi-GPU
-
-Quando addestri o fai inferenza con `DistributedDataParallel` e GPU multiple, se si verificano problemi di intercomunicazione tra processi e/o nodi, puoi utilizzare il seguente script per diagnosticare i problemi della rete.
-
-```bash
-wget https://raw.githubusercontent.com/huggingface/transformers/main/scripts/distributed/torch-distributed-gpu-test.py
-```
-
-Per esempio per testare come 2 GPU interagiscono fai:
-
-```bash
-python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py
-```
-
-Se entrambi i processi sono in grado di comunicare tra loro e di allocare la memoria della GPU, ciascuno di essi stamperĂ lo stato OK.
-
-Per piĂč GPU o nodi adatta gli argumenti nello script.
-
-All'interno dello script di diagnostica troverai molti altri dettagli e anche una guida per eseguirlo in ambiente SLURM.
-
-Un livello di debug superiore Ăš aggiungere la variabile d'ambiente `NCCL_DEBUG=INFO` come di seguito:
-
-```bash
-NCCL_DEBUG=INFO python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py
-```
-
-In questo modo si scaricano molte informazioni di debug relative a NCCL, che puoi cercare online in caso di problemi. Oppure, se non hai la sicurezza di come interpretare l'output, puoi condividere il file di log in una Issue.
-
-## Rilevamento di Underflow e Overflow
-
-
-
-Questa funzionalitĂ al momento Ăš disponibile solo per PyTorch.
-
-
-
-
-
-Per addestramento multi-GPU richiede DDP (`torch.distributed.launch`).
-
-
-
-
-
-Questa funzionalitĂ puĂČ essere usata con modelli basati su `nn.Module`.
-
-
-
-Se inizi a ottenere `loss=NaN` o il modello presenta qualche altro comportamento anomalo a causa di valori `inf` o `nan` in
-attivazioni o nei pesi, Ăš necessario scoprire dove si verifica il primo underflow o overflow e cosa lo ha determinato. Fortunatamente
-Ăš possibile farlo facilmente attivando un modulo speciale che effettuerĂ il rilevamento automaticamente.
-
-Se stai usando [`Trainer`], hai bisogno di aggiungere solo:
-
-```bash
---debug underflow_overflow
-```
-
-ai normali argomenti della riga di comando, o passa `debug="underflow_overflow"` quando viene creato l'oggetto
-[`TrainingArguments`].
-
-Se stai usando il tuo ciclo di allenamento o un altro trainer, puoi ottenere lo stesso risultato con:
-
-```python
-from .debug_utils import DebugUnderflowOverflow
-
-debug_overflow = DebugUnderflowOverflow(model)
-```
-
-[`~debug_utils.DebugUnderflowOverflow`] inserisce dei ganci nel modello che dopo ogni chiamata
-testeranno le variabili di ingresso e di uscita e anche i pesi del modulo corrispondente. Non appena viene rilevato `inf` o
-o `nan` in almeno un elemento delle attivazioni o dei pesi, il programma lo notifica e stampa un rapporto come il seguente (questo Ăš stato rilevato con `google/mt5-small` sotto fp16 mixed precision):
-
-```
-Detected inf/nan during batch_number=0
-Last 21 forward frames:
-abs min abs max metadata
- encoder.block.1.layer.1.DenseReluDense.dropout Dropout
-0.00e+00 2.57e+02 input[0]
-0.00e+00 2.85e+02 output
-[...]
- encoder.block.2.layer.0 T5LayerSelfAttention
-6.78e-04 3.15e+03 input[0]
-2.65e-04 3.42e+03 output[0]
- None output[1]
-2.25e-01 1.00e+04 output[2]
- encoder.block.2.layer.1.layer_norm T5LayerNorm
-8.69e-02 4.18e-01 weight
-2.65e-04 3.42e+03 input[0]
-1.79e-06 4.65e+00 output
- encoder.block.2.layer.1.DenseReluDense.wi_0 Linear
-2.17e-07 4.50e+00 weight
-1.79e-06 4.65e+00 input[0]
-2.68e-06 3.70e+01 output
- encoder.block.2.layer.1.DenseReluDense.wi_1 Linear
-8.08e-07 2.66e+01 weight
-1.79e-06 4.65e+00 input[0]
-1.27e-04 2.37e+02 output
- encoder.block.2.layer.1.DenseReluDense.dropout Dropout
-0.00e+00 8.76e+03 input[0]
-0.00e+00 9.74e+03 output
- encoder.block.2.layer.1.DenseReluDense.wo Linear
-1.01e-06 6.44e+00 weight
-0.00e+00 9.74e+03 input[0]
-3.18e-04 6.27e+04 output
- encoder.block.2.layer.1.DenseReluDense T5DenseGatedGeluDense
-1.79e-06 4.65e+00 input[0]
-3.18e-04 6.27e+04 output
- encoder.block.2.layer.1.dropout Dropout
-3.18e-04 6.27e+04 input[0]
-0.00e+00 inf output
-```
-
-L'output di esempio Ăš stato tagliato al centro per brevitĂ .
-
-La seconda colonna mostra il valore dell'elemento piĂč grande in assoluto,cosĂŹ se osserviamo da vicino gli ultimi istanti,
-input e output sono nel range di `1e4`. Questo addestramento Ăš stato eseguito con una mixed precision fp16 e l'ultimo passo usciva fuori (sotto `fp16` il valore piĂč grande prima di `inf` Ăš `64e3`). Per evitare overflows sotto `fp16` le attivazionioni devono rimanere molto al di sotto di `1e4`, perchĂ© `1e4 * 1e4 = 1e8` quindi qualsiasi moltiplicazione di matrice con grandi attivazioni porterĂ a una condizione di overflow numerico.
-
-All'inizio della traccia Ăš possibile scoprire a quale lotto si Ăš verificato il problema (questo `Detected inf/nan during batch_number=0` significa che il problema si Ăš verificato nel primo lotto).
-
-Ogni frame segnalato inizia dichiarando la voce completamente qualificata per il modulo corrispondente per il quale il frame Ăš stato segnalato.
-Se osserviamo il seguente frame:
-
-```
- encoder.block.2.layer.1.layer_norm T5LayerNorm
-8.69e-02 4.18e-01 weight
-2.65e-04 3.42e+03 input[0]
-1.79e-06 4.65e+00 output
-```
-
-Questo, `encoder.block.2.layer.1.layer_norm` indica che si tratta di un layer norm nel primo layer, del secondo blocco dell'encoder. E le chiamata specifica di `forward` Ăš `T5LayerNorm`.
-
-Osserviamo gli ultimi frame del report:
-
-```
-Detected inf/nan during batch_number=0
-Last 21 forward frames:
-abs min abs max metadata
-[...]
- encoder.block.2.layer.1.DenseReluDense.wi_0 Linear
-2.17e-07 4.50e+00 weight
-1.79e-06 4.65e+00 input[0]
-2.68e-06 3.70e+01 output
- encoder.block.2.layer.1.DenseReluDense.wi_1 Linear
-8.08e-07 2.66e+01 weight
-1.79e-06 4.65e+00 input[0]
-1.27e-04 2.37e+02 output
- encoder.block.2.layer.1.DenseReluDense.wo Linear
-1.01e-06 6.44e+00 weight
-0.00e+00 9.74e+03 input[0]
-3.18e-04 6.27e+04 output
- encoder.block.2.layer.1.DenseReluDense T5DenseGatedGeluDense
-1.79e-06 4.65e+00 input[0]
-3.18e-04 6.27e+04 output
- encoder.block.2.layer.1.dropout Dropout
-3.18e-04 6.27e+04 input[0]
-0.00e+00 inf output
-```
-
-L'ultimo frame report per la funzione `Dropout.forward` con la prima voce per l'unico input e la seconda per l'unico output. Si puĂČ notare che Ăš stato richiamato da un attibuto `dropout` dentro la classe `DenseReluDense`. Si puĂČ notare che ciĂČ Ăš avvenuto durante il primo strato, del 2° blocco, durante il primissimo lotto. Infine, gli elementi di input piĂč grandi in assoluto sono stati `6.27e+04` e l'equivalente per l'output era `inf`.
-
-Puoi vedere qui, che `T5DenseGatedGeluDense.forward` risulta in output activations, il cui valore massimo assoluto era circa 62,7K, che Ăš molto vicino al limite massimo di 64K di fp16. Nel prossimo frame abbiamo `Dropout` che rinormalizza i pesi, dopo aver azzerato alcuni elementi, il che spinge il valore massimo assoluto a piĂč di 64K e si verifica un overflow.(`inf`).
-
-Come puoi notare, Ăš nei frames precedenti che occorre esaminare quando i numeri iniziano a diventare molto grandi per i valori fp16.
-
-Confrontiamo il report al codice `models/t5/modeling_t5.py`:
-
-```python
-class T5DenseGatedGeluDense(nn.Module):
- def __init__(self, config):
- super().__init__()
- self.wi_0 = nn.Linear(config.d_model, config.d_ff, bias=False)
- self.wi_1 = nn.Linear(config.d_model, config.d_ff, bias=False)
- self.wo = nn.Linear(config.d_ff, config.d_model, bias=False)
- self.dropout = nn.Dropout(config.dropout_rate)
- self.gelu_act = ACT2FN["gelu_new"]
-
- def forward(self, hidden_states):
- hidden_gelu = self.gelu_act(self.wi_0(hidden_states))
- hidden_linear = self.wi_1(hidden_states)
- hidden_states = hidden_gelu * hidden_linear
- hidden_states = self.dropout(hidden_states)
- hidden_states = self.wo(hidden_states)
- return hidden_states
-```
-
-Ora Ăš facile vedere la chiamata `dropout`, e tutte le chiamate precedenti.
-
-Poiché il rilevamento avviene in un avanzamento (forward hook in eng.), i rapporti vengono creati immeditamente dopo ogni rientro da `forward` (forward returns in eng.).
-
-Tornando al rapporto completo, per agire e risolvere il problema, dobbiamo andare qualche frame piĂč in alto, dove i numeri hanno iniziato a salire, e probabilmente passare alla modalitĂ `fp32`, in modo che i numeri non trabocchino quando vengono moltiplicati o sommati. Naturalmente, potrebbero esserci altre soluzioni. Per esempio, potremmo spegnere temporanemante `amp` se Ăš abilitato, successivamente spostare `forward` in un helper wrapper, come:
-
-```python
-def _forward(self, hidden_states):
- hidden_gelu = self.gelu_act(self.wi_0(hidden_states))
- hidden_linear = self.wi_1(hidden_states)
- hidden_states = hidden_gelu * hidden_linear
- hidden_states = self.dropout(hidden_states)
- hidden_states = self.wo(hidden_states)
- return hidden_states
-
-
-import torch
-
-
-def forward(self, hidden_states):
- if torch.is_autocast_enabled():
- with torch.cuda.amp.autocast(enabled=False):
- return self._forward(hidden_states)
- else:
- return self._forward(hidden_states)
-```
-
-PoichĂ© il rilevatore automatico riporta solo gli ingressi e le uscite di fotogrammi completi, una volta che si sa dove cercare, si puĂČ
-analizzare anche le fasi intermedie di una specifica funzione `forward`. In alcuni casi puoi usare la funzione di supporto `detect_overflow` per indirizzare il rilevatore dove preferisci, ad esempio:
-
-```python
-from debug_utils import detect_overflow
-
-
-class T5LayerFF(nn.Module):
- [...]
-
- def forward(self, hidden_states):
- forwarded_states = self.layer_norm(hidden_states)
- detect_overflow(forwarded_states, "after layer_norm")
- forwarded_states = self.DenseReluDense(forwarded_states)
- detect_overflow(forwarded_states, "after DenseReluDense")
- return hidden_states + self.dropout(forwarded_states)
-```
-
-Si puĂČ vedere che abbiamo aggiunto 2 di questi e ora teniamo traccia se `inf` o `nan` per `forwarded_states` Ăš stato rilevato
-da qualche parte.
-
-In realtà , il rilevatore li riporta già , perché ciascuna delle chiamate nell'esempio precedente Ú un `nn.Module`, ma
-diciamo che se avessimo dei calcoli diretti locali, questo Ăš il modo in cui lo faremmo.
-
-Inoltre, se si istanzia il debugger nel proprio codice, Ăš possibile modificare il numero di fotogrammi stampati rispetto a
-predefinito, ad esempio.:
-
-```python
-from .debug_utils import DebugUnderflowOverflow
-
-debug_overflow = DebugUnderflowOverflow(model, max_frames_to_save=100)
-```
-
-### Tracciamento della mistura assoluta del lotto specifico e del valore massimo
-
-La stessa classe di debug puĂČ essere utilizzata per il tracciamento per-batch con la funzione di rilevamento di underflow/overflow disattivata.
-
-Supponiamo di voler osservare i valori minimi e massimi assoluti per tutti gli ingredienti di ogni chiamata `forward` di un dato lotto.
-lotto, e che lo si voglia fare solo per i lotti 1 e 3. Si istanzia questa classe come:
-
-```python
-debug_overflow = DebugUnderflowOverflow(model, trace_batch_nums=[1, 3])
-```
-
-Ora i batch completi 1 e 3 saranno tracciati utilizzando lo stesso formato del rilevatore di underflow/overflow.
-
-I batches sono 0-indexed.
-
-Questo Ăš utile se si sa che il programma inizia a comportarsi male dopo un certo numero di batch, in modo da poter avanzare velocemente fino a quell'area.
-direttamente a quell'area. Ecco un esempio di output troncato per questa configurazione:
-
-```
- *** Starting batch number=1 ***
-abs min abs max metadata
- shared Embedding
-1.01e-06 7.92e+02 weight
-0.00e+00 2.47e+04 input[0]
-5.36e-05 7.92e+02 output
-[...]
- decoder.dropout Dropout
-1.60e-07 2.27e+01 input[0]
-0.00e+00 2.52e+01 output
- decoder T5Stack
- not a tensor output
- lm_head Linear
-1.01e-06 7.92e+02 weight
-0.00e+00 1.11e+00 input[0]
-6.06e-02 8.39e+01 output
- T5ForConditionalGeneration
- not a tensor output
-
- *** Starting batch number=3 ***
-abs min abs max metadata
- shared Embedding
-1.01e-06 7.92e+02 weight
-0.00e+00 2.78e+04 input[0]
-5.36e-05 7.92e+02 output
-[...]
-```
-
-Qui verrĂ scaricato un numero enorme di fotogrammi, tanti quanti sono le chiamate in avanti nel modello, quindi puĂČ essere o non essere quello che volete, ma a volte puĂČ essere piĂč utile usarlo di un classico debugger. Per esempio, se il problema inizia a verificarsi a partire dal lotto numero 150. Quindi Ăš possibile scaricare le tracce dei lotti 149 e 150 e confrontare i punti in cui i numeri hanno iniziato a divergere.
-
-Ă inoltre possibile specificare il numero di batch dopo il quale interrompere l'addestramento, con:
-
-```python
-debug_overflow = DebugUnderflowOverflow(model, trace_batch_nums=[1, 3], abort_after_batch_num=3)
-```
diff --git a/docs/source/it/index.md b/docs/source/it/index.md
new file mode 100644
index 000000000000..5c7d22c1e6b1
--- /dev/null
+++ b/docs/source/it/index.md
@@ -0,0 +1,300 @@
+
+
+# đ€ Transformers
+
+Machine Learning allo stato dell'arte per PyTorch, TensorFlow e JAX.
+
+đ€ Transformers fornisce delle API per scaricare in modo semplice e allenare modelli pre-allenati allo stato dell'arte. L'utilizzo di modelli pre-allenati puĂČ ridurre i tuoi costi computazionali, l'impatto ambientale, e farti risparmiare il tempo che utilizzeresti per allenare un modello da zero. I modelli possono essere utilizzati in diverse modalitĂ come ad esempio:
+
+* đ Testo: classificazione del testo, estrazione delle informazioni, rispondere a domande, riassumere, traduzione e generazione del testo in piĂč di 100 lingue.
+* đŒïž Immagini: classificazione di immagini, rilevazione di oggetti e segmentazione.
+* đŁïž Audio: riconoscimento vocale e classificazione dell'audio.
+* đ Multimodale: rispondere a domande inerenti dati tabulari, riconoscimento ottico dei caratteri, estrazione di informazioni a partire da documenti scannerizzati, classificazione di video e risposta visuale a domande.
+
+La nostra libreria supporta un'integrazione perfetta tra tre delle librerie per il deep learning piĂč popolari: [PyTorch](https://pytorch.org/), [TensorFlow](https://www.tensorflow.org/) e [JAX](https://jax.readthedocs.io/en/latest/). Allena il tuo modello in tre righe di codice in un framework, e caricalo per l'inferenza in un altro.
+
+Ogni architettura di đ€ Transformers Ăš definita in un modulo Python indipendente cosĂŹ da poter essere personalizzata in modo semplice per la ricerca e gli esperimenti.
+
+## Se stai cercando supporto personalizzato dal team di Hugging Face
+
+
+
+
+
+## Contenuti
+
+La documentazione Ăš organizzata in cinque parti:
+
+- **INIZIARE** contiene un tour rapido e le istruzioni di installazione per cominciare ad utilizzare đ€ Transformers.
+- **TUTORIALS** Ăš un buon posto da cui iniziare se per te la nostra libreria Ăš nuova. Questa sezione ti aiuterĂ ad acquisire le competenze basilari di cui hai bisogno per iniziare ad utilizzare đ€ Transformers.
+- **GUIDE PRATICHE** ti mostrerĂ come raggiungere obiettivi specifici come fare fine-tuning di un modello pre-allenato per la modellizzazione del linguaggio o come creare una testa per un modello personalizzato.
+- **GUIDE CONCETTUALI** fornisce discussioni e spiegazioni dei concetti sottostanti alle idee dietro ai modelli, compiti, e la filosofia di progettazione di đ€ Transformers.
+- **API** descrive ogni classe e funzione, raggruppate in:
+ - **CLASSI PRINCIPALI** per le classi principali che espongono le API importanti della libreria.
+ - **MODELLI** per le classi e le funzioni relative ad ogni modello implementato all'interno della libreria.
+ - **HELPERS INTERNI** per le classi e le funzioni che utilizziamo internamente.
+
+La libreria attualmente contiene implementazioni in JAX, PyTorch e TensorFlow, pesi di modelli pre-allenati, script di utilizzo e strumenti di conversione per i seguenti modelli.
+
+### Modelli supportati
+
+
+
+1. **[ALBERT](model_doc/albert)** (da Google Research e l'Istituto Tecnologico di Chicago) rilasciato con il paper [ALBERT: A Lite BERT for Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), da Zhenzhong Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.
+1. **[ALIGN](model_doc/align)** (from Google Research) rilasciato con il paper [Scaling Up Visual and Vision-Language Representation Learning With Noisy Text Supervision](https://arxiv.org/abs/2102.05918) da Chao Jia, Yinfei Yang, Ye Xia, Yi-Ting Chen, Zarana Parekh, Hieu Pham, Quoc V. Le, Yunhsuan Sung, Zhen Li, Tom Duerig.
+1. **[BART](model_doc/bart)** (da Facebook) rilasciato con il paper [BART: Denoising Sequence-to-Sequence Pre-training for Natural Language Generation, Translation, and Comprehension](https://arxiv.org/abs/1910.13461) da Mike Lewis, Yinhan Liu, Naman Goyal, Marjan Ghazvininejad, Abdelrahman Mohamed, Omer Levy, Ves Stoyanov e Luke Zettlemoyer.
+1. **[BARThez](model_doc/barthez)** (da politecnico di Ăcole) rilasciato con il paper [BARThez: a Skilled Pretrained French Sequence-to-Sequence Model](https://arxiv.org/abs/2010.12321) da Moussa Kamal Eddine, Antoine J.-P. Tixier, Michalis Vazirgiannis.
+1. **[BARTpho](model_doc/bartpho)** (da VinAI Research) rilasciato con il paper [BARTpho: Pre-trained Sequence-to-Sequence Models for Vietnamese](https://arxiv.org/abs/2109.09701) da Nguyen Luong Tran, Duong Minh Le e Dat Quoc Nguyen.
+1. **[BEiT](model_doc/beit)** (da Microsoft) rilasciato con il paper [BEiT: BERT Pre-Training of Image Transformers](https://arxiv.org/abs/2106.08254) da Hangbo Bao, Li Dong, Furu Wei.
+1. **[BERT](model_doc/bert)** (da Google) rilasciato con il paper [BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding](https://arxiv.org/abs/1810.04805) da Jacob Devlin, Ming-Wei Chang, Kenton Lee e Kristina Toutanova.
+1. **[BERTweet](model_doc/bertweet)** (da VinAI Research) rilasciato con il paper [BERTweet: A pre-trained language model for English Tweets](https://aclanthology.org/2020.emnlp-demos.2/) da Dat Quoc Nguyen, Thanh Vu e Anh Tuan Nguyen.
+1. **[BERT For Sequence Generation](model_doc/bert-generation)** (da Google) rilasciato con il paper [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://arxiv.org/abs/1907.12461) da Sascha Rothe, Shashi Narayan, Aliaksei Severyn.
+1. **[BigBird-RoBERTa](model_doc/big_bird)** (da Google Research) rilasciato con il paper [Big Bird: Transformers for Longer Sequences](https://arxiv.org/abs/2007.14062) da Manzil Zaheer, Guru Guruganesh, Avinava Dubey, Joshua Ainslie, Chris Alberti, Santiago Ontanon, Philip Pham, Anirudh Ravula, Qifan Wang, Li Yang, Amr Ahmed.
+1. **[BigBird-Pegasus](model_doc/bigbird_pegasus)** (v Google Research) rilasciato con il paper [Big Bird: Transformers for Longer Sequences](https://arxiv.org/abs/2007.14062) da Manzil Zaheer, Guru Guruganesh, Avinava Dubey, Joshua Ainslie, Chris Alberti, Santiago Ontanon, Philip Pham, Anirudh Ravula, Qifan Wang, Li Yang, Amr Ahmed.
+1. **[Blenderbot](model_doc/blenderbot)** (da Facebook) rilasciato con il paper [Recipes for building an open-domain chatbot](https://arxiv.org/abs/2004.13637) da 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.
+1. **[BlenderbotSmall](model_doc/blenderbot-small)** (da Facebook) rilasciato con il paper [Recipes for building an open-domain chatbot](https://arxiv.org/abs/2004.13637) da 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.
+1. **[BORT](model_doc/bort)** (da Alexa) rilasciato con il paper [Optimal Subarchitecture Extraction For BERT](https://arxiv.org/abs/2010.10499) da Adrian de Wynter e Daniel J. Perry.
+1. **[ByT5](model_doc/byt5)** (da Google Research) rilasciato con il paper [ByT5: Towards a token-free future with pre-trained byte-to-byte models](https://arxiv.org/abs/2105.13626) da Linting Xue, Aditya Barua, Noah Constant, Rami Al-Rfou, Sharan Narang, Mihir Kale, Adam Roberts, Colin Raffel.
+1. **[CamemBERT](model_doc/camembert)** (da Inria/Facebook/Sorbonne) rilasciato con il paper [CamemBERT: a Tasty French Language Model](https://arxiv.org/abs/1911.03894) da Louis Martin*, Benjamin Muller*, Pedro Javier Ortiz SuĂĄrez*, Yoann Dupont, Laurent Romary, Ăric Villemonte de la Clergerie, DjamĂ© Seddah e BenoĂźt Sagot.
+1. **[CANINE](model_doc/canine)** (da Google Research) rilasciato con il paper [CANINE: Pre-training an Efficient Tokenization-Free Encoder for Language Representation](https://arxiv.org/abs/2103.06874) da Jonathan H. Clark, Dan Garrette, Iulia Turc, John Wieting.
+1. **[ConvNeXT](model_doc/convnext)** (da Facebook AI) rilasciato con il paper [A ConvNet for the 2020s](https://arxiv.org/abs/2201.03545) da Zhuang Liu, Hanzi Mao, Chao-Yuan Wu, Christoph Feichtenhofer, Trevor Darrell, Saining Xie.
+1. **[ConvNeXTV2](model_doc/convnextv2)** (da Facebook AI) rilasciato con il paper [ConvNeXt V2: Co-designing and Scaling ConvNets with Masked Autoencoders](https://arxiv.org/abs/2301.00808) da Sanghyun Woo, Shoubhik Debnath, Ronghang Hu, Xinlei Chen, Zhuang Liu, In So Kweon, Saining Xie.
+1. **[CLIP](model_doc/clip)** (da OpenAI) rilasciato con il paper [Learning Transferable Visual Models From Natural Language Supervision](https://arxiv.org/abs/2103.00020) da 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.
+1. **[ConvBERT](model_doc/convbert)** (da YituTech) rilasciato con il paper [ConvBERT: Improving BERT with Span-based Dynamic Convolution](https://arxiv.org/abs/2008.02496) da Zihang Jiang, Weihao Yu, Daquan Zhou, Yunpeng Chen, Jiashi Feng, Shuicheng Yan.
+1. **[CPM](model_doc/cpm)** (dalla UniversitĂ di Tsinghua) rilasciato con il paper [CPM: A Large-scale Generative Chinese Pre-trained Language Model](https://arxiv.org/abs/2012.00413) da 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.
+1. **[CTRL](model_doc/ctrl)** (da Salesforce) rilasciato con il paper [CTRL: A Conditional Transformer Language Model for Controllable Generation](https://arxiv.org/abs/1909.05858) da Nitish Shirish Keskar*, Bryan McCann*, Lav R. Varshney, Caiming Xiong e Richard Socher.
+1. **[CvT](model_doc/cvt)** (da Microsoft) rilasciato con il paper [CvT: Introducing Convolutions to Vision Transformers](https://arxiv.org/abs/2103.15808) da Haiping Wu, Bin Xiao, Noel Codella, Mengchen Liu, Xiyang Dai, Lu Yuan, Lei Zhang.
+1. **[Data2Vec](model_doc/data2vec)** (da Facebook) rilasciato con il paper [Data2Vec: A General Framework for Self-supervised Learning in Speech, Vision and Language](https://arxiv.org/abs/2202.03555) da Alexei Baevski, Wei-Ning Hsu, Qiantong Xu, Arun Babu, Jiatao Gu, Michael Auli.
+1. **[DeBERTa](model_doc/deberta)** (da Microsoft) rilasciato con il paper [DeBERTa: Decoding-enhanced BERT with Disentangled Attention](https://arxiv.org/abs/2006.03654) da Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen.
+1. **[DeBERTa-v2](model_doc/deberta-v2)** (da Microsoft) rilasciato con il paper [DeBERTa: Decoding-enhanced BERT with Disentangled Attention](https://arxiv.org/abs/2006.03654) da Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen.
+1. **[Decision Transformer](model_doc/decision_transformer)** (da Berkeley/Facebook/Google) rilasciato con il paper [Decision Transformer: Reinforcement Learning via Sequence Modeling](https://arxiv.org/abs/2106.01345) da Lili Chen, Kevin Lu, Aravind Rajeswaran, Kimin Lee, Aditya Grover, Michael Laskin, Pieter Abbeel, Aravind Srinivas, Igor Mordatch.
+1. **[DiT](model_doc/dit)** (da Microsoft Research) rilasciato con il paper [DiT: Self-supervised Pre-training for Document Image Transformer](https://arxiv.org/abs/2203.02378) da Junlong Li, Yiheng Xu, Tengchao Lv, Lei Cui, Cha Zhang, Furu Wei.
+1. **[DeiT](model_doc/deit)** (da Facebook) rilasciato con il paper [Training data-efficient image transformers & distillation through attention](https://arxiv.org/abs/2012.12877) da Hugo Touvron, Matthieu Cord, Matthijs Douze, Francisco Massa, Alexandre Sablayrolles, Hervé Jégou.
+1. **[DETR](model_doc/detr)** (da Facebook) rilasciato con il paper [End-to-End Object Detection with Transformers](https://arxiv.org/abs/2005.12872) da Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov, Sergey Zagoruyko.
+1. **[DialoGPT](model_doc/dialogpt)** (da Microsoft Research) rilasciato con il paper [DialoGPT: Large-Scale Generative Pre-training for Conversational Response Generation](https://arxiv.org/abs/1911.00536) da Yizhe Zhang, Siqi Sun, Michel Galley, Yen-Chun Chen, Chris Brockett, Xiang Gao, Jianfeng Gao, Jingjing Liu, Bill Dolan.
+1. **[DistilBERT](model_doc/distilbert)** (da HuggingFace), rilasciato assieme al paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter](https://arxiv.org/abs/1910.01108) da Victor Sanh, Lysandre Debut e Thomas Wolf. La stessa tecnica Ăš stata applicata per comprimere GPT2 in [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/research_projects/distillation), RoBERTa in [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/research_projects/distillation), Multilingual BERT in [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/research_projects/distillation) and a German version of DistilBERT.
+1. **[DPR](model_doc/dpr)** (da Facebook) rilasciato con il paper [Dense Passage Retrieval for Open-Domain Question Answering](https://arxiv.org/abs/2004.04906) da Vladimir Karpukhin, Barlas OÄuz, Sewon Min, Patrick Lewis, Ledell Wu, Sergey Edunov, Danqi Chen, e Wen-tau Yih.
+1. **[DPT](master/model_doc/dpt)** (da Intel Labs) rilasciato con il paper [Vision Transformers for Dense Prediction](https://arxiv.org/abs/2103.13413) da René Ranftl, Alexey Bochkovskiy, Vladlen Koltun.
+1. **[EfficientNet](model_doc/efficientnet)** (from Google Research) released with the paper [EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks](https://arxiv.org/abs/1905.11946) by Mingxing Tan and Quoc V. Le.
+1. **[EncoderDecoder](model_doc/encoder-decoder)** (da Google Research) rilasciato con il paper [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://arxiv.org/abs/1907.12461) da Sascha Rothe, Shashi Narayan, Aliaksei Severyn.
+1. **[ELECTRA](model_doc/electra)** (da Google Research/Stanford University) rilasciato con il paper [ELECTRA: Pre-training text encoders as discriminators rather than generators](https://arxiv.org/abs/2003.10555) da Kevin Clark, Minh-Thang Luong, Quoc V. Le, Christopher D. Manning.
+1. **[FlauBERT](model_doc/flaubert)** (da CNRS) rilasciato con il paper [FlauBERT: Unsupervised Language Model Pre-training for French](https://arxiv.org/abs/1912.05372) da Hang Le, Loïc Vial, Jibril Frej, Vincent Segonne, Maximin Coavoux, Benjamin Lecouteux, Alexandre Allauzen, Benoßt Crabbé, Laurent Besacier, Didier Schwab.
+1. **[FLAVA](model_doc/flava)** (da Facebook AI) rilasciato con il paper [FLAVA: A Foundational Language And Vision Alignment Model](https://arxiv.org/abs/2112.04482) da Amanpreet Singh, Ronghang Hu, Vedanuj Goswami, Guillaume Couairon, Wojciech Galuba, Marcus Rohrbach, e Douwe Kiela.
+1. **[FNet](model_doc/fnet)** (da Google Research) rilasciato con il paper [FNet: Mixing Tokens with Fourier Transforms](https://arxiv.org/abs/2105.03824) da James Lee-Thorp, Joshua Ainslie, Ilya Eckstein, Santiago Ontanon.
+1. **[Funnel Transformer](model_doc/funnel)** (da CMU/Google Brain) rilasciato con il paper [Funnel-Transformer: Filtering out Sequential Redundancy for Efficient Language Processing](https://arxiv.org/abs/2006.03236) da Zihang Dai, Guokun Lai, Yiming Yang, Quoc V. Le.
+1. **[GLPN](model_doc/glpn)** (da KAIST) rilasciato con il paper [Global-Local Path Networks for Monocular Depth Estimation with Vertical CutDepth](https://arxiv.org/abs/2201.07436) da Doyeon Kim, Woonghyun Ga, Pyungwhan Ahn, Donggyu Joo, Sehwan Chun, Junmo Kim.
+1. **[GPT](model_doc/openai-gpt)** (da OpenAI) rilasciato con il paper [Improving Language Understanding by Generative Pre-Training](https://blog.openai.com/language-unsupervised/) da Alec Radford, Karthik Narasimhan, Tim Salimans e Ilya Sutskever.
+1. **[GPT-2](model_doc/gpt2)** (da OpenAI) rilasciato con il paper [Language Models are Unsupervised Multitask Learners](https://blog.openai.com/better-language-models/) da Alec Radford*, Jeffrey Wu*, Rewon Child, David Luan, Dario Amodei** e Ilya Sutskever**.
+1. **[GPT-J](model_doc/gptj)** (da EleutherAI) rilasciato nel repository [kingoflolz/mesh-transformer-jax](https://github.com/kingoflolz/mesh-transformer-jax/) da Ben Wang e Aran Komatsuzaki.
+1. **[GPT Neo](model_doc/gpt_neo)** (da EleutherAI) rilasciato nel repository [EleutherAI/gpt-neo](https://github.com/EleutherAI/gpt-neo) da Sid Black, Stella Biderman, Leo Gao, Phil Wang e Connor Leahy.
+1. **[GPT NeoX](model_doc/gpt_neox)** (da EleutherAI) rilasciato con il paper [GPT-NeoX-20B: An Open-Source Autoregressive Language Model](https://arxiv.org/abs/2204.06745) da 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
+1. **[Hubert](model_doc/hubert)** (da Facebook) rilasciato con il paper [HuBERT: Self-Supervised Speech Representation Learning by Masked Prediction of Hidden Units](https://arxiv.org/abs/2106.07447) da Wei-Ning Hsu, Benjamin Bolte, Yao-Hung Hubert Tsai, Kushal Lakhotia, Ruslan Salakhutdinov, Abdelrahman Mohamed.
+1. **[I-BERT](model_doc/ibert)** (da Berkeley) rilasciato con il paper [I-BERT: Integer-only BERT Quantization](https://arxiv.org/abs/2101.01321) da Sehoon Kim, Amir Gholami, Zhewei Yao, Michael W. Mahoney, Kurt Keutzer.
+1. **[ImageGPT](model_doc/imagegpt)** (da OpenAI) rilasciato con il paper [Generative Pretraining from Pixels](https://openai.com/blog/image-gpt/) da Mark Chen, Alec Radford, Rewon Child, Jeffrey Wu, Heewoo Jun, David Luan, Ilya Sutskever.
+1. **[LayoutLM](model_doc/layoutlm)** (da Microsoft Research Asia) rilasciato con il paper [LayoutLM: Pre-training of Text and Layout for Document Image Understanding](https://arxiv.org/abs/1912.13318) da Yiheng Xu, Minghao Li, Lei Cui, Shaohan Huang, Furu Wei, Ming Zhou.
+1. **[LayoutLMv2](model_doc/layoutlmv2)** (da Microsoft Research Asia) rilasciato con il paper [LayoutLMv2: Multi-modal Pre-training for Visually-Rich Document Understanding](https://arxiv.org/abs/2012.14740) da Yang Xu, Yiheng Xu, Tengchao Lv, Lei Cui, Furu Wei, Guoxin Wang, Yijuan Lu, Dinei Florencio, Cha Zhang, Wanxiang Che, Min Zhang, Lidong Zhou.
+1. **[LayoutLMv3](model_doc/layoutlmv3)** (da Microsoft Research Asia) rilasciato con il paper [LayoutLMv3: Pre-training for Document AI with Unified Text and Image Masking](https://arxiv.org/abs/2204.08387) da Yupan Huang, Tengchao Lv, Lei Cui, Yutong Lu, Furu Wei.
+1. **[LayoutXLM](model_doc/layoutlxlm)** (da Microsoft Research Asia) rilasciato con il paper [LayoutXLM: Multimodal Pre-training for Multilingual Visually-rich Document Understanding](https://arxiv.org/abs/2104.08836) da Yiheng Xu, Tengchao Lv, Lei Cui, Guoxin Wang, Yijuan Lu, Dinei Florencio, Cha Zhang, Furu Wei.
+1. **[LED](model_doc/led)** (da AllenAI) rilasciato con il paper [Longformer: The Long-Document Transformer](https://arxiv.org/abs/2004.05150) da Iz Beltagy, Matthew E. Peters, Arman Cohan.
+1. **[Longformer](model_doc/longformer)** (da AllenAI) rilasciato con il paper [Longformer: The Long-Document Transformer](https://arxiv.org/abs/2004.05150) da Iz Beltagy, Matthew E. Peters, Arman Cohan.
+1. **[LUKE](model_doc/luke)** (da Studio Ousia) rilasciato con il paper [LUKE: Deep Contextualized Entity Representations with Entity-aware Self-attention](https://arxiv.org/abs/2010.01057) da Ikuya Yamada, Akari Asai, Hiroyuki Shindo, Hideaki Takeda, Yuji Matsumoto.
+1. **[mLUKE](model_doc/mluke)** (da Studio Ousia) rilasciato con il paper [mLUKE: The Power of Entity Representations in Multilingual Pretrained Language Models](https://arxiv.org/abs/2110.08151) da Ryokan Ri, Ikuya Yamada, e Yoshimasa Tsuruoka.
+1. **[LXMERT](model_doc/lxmert)** (da UNC Chapel Hill) rilasciato con il paper [LXMERT: Learning Cross-Modality Encoder Representations from Transformers for Open-Domain Question Answering](https://arxiv.org/abs/1908.07490) da Hao Tan e Mohit Bansal.
+1. **[M2M100](model_doc/m2m_100)** (da Facebook) rilasciato con il paper [Beyond English-Centric Multilingual Machine Translation](https://arxiv.org/abs/2010.11125) da 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.
+1. **[MarianMT](model_doc/marian)** Modello di machine learning per le traduzioni allenato utilizzando i dati [OPUS](http://opus.nlpl.eu/) di Jörg Tiedemann. Il [Framework Marian](https://marian-nmt.github.io/) Ú stato sviluppato dal Microsoft Translator Team.
+1. **[Mask2Former](model_doc/mask2former)** (da FAIR e UIUC) rilasciato con il paper [Masked-attention Mask Transformer for Universal Image Segmentation](https://arxiv.org/abs/2112.01527) da Bowen Cheng, Ishan Misra, Alexander G. Schwing, Alexander Kirillov, Rohit Girdhar.
+1. **[MaskFormer](model_doc/maskformer)** (da Meta e UIUC) rilasciato con il paper [Per-Pixel Classification is Not All You Need for Semantic Segmentation](https://arxiv.org/abs/2107.06278) da Bowen Cheng, Alexander G. Schwing, Alexander Kirillov.
+1. **[MBart](model_doc/mbart)** (da Facebook) rilasciato con il paper [Multilingual Denoising Pre-training for Neural Machine Translation](https://arxiv.org/abs/2001.08210) da Yinhan Liu, Jiatao Gu, Naman Goyal, Xian Li, Sergey Edunov, Marjan Ghazvininejad, Mike Lewis, Luke Zettlemoyer.
+1. **[MBart-50](model_doc/mbart)** (da Facebook) rilasciato con il paper [Multilingual Translation with Extensible Multilingual Pretraining and Finetuning](https://arxiv.org/abs/2008.00401) da Yuqing Tang, Chau Tran, Xian Li, Peng-Jen Chen, Naman Goyal, Vishrav Chaudhary, Jiatao Gu, Angela Fan.
+1. **[Megatron-BERT](model_doc/megatron-bert)** (da NVIDIA) rilasciato con il paper [Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism](https://arxiv.org/abs/1909.08053) da Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper e Bryan Catanzaro.
+1. **[Megatron-GPT2](model_doc/megatron_gpt2)** (da NVIDIA) rilasciato con il paper [Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism](https://arxiv.org/abs/1909.08053) da Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper e Bryan Catanzaro.
+1. **[MPNet](model_doc/mpnet)** (da Microsoft Research) rilasciato con il paper [MPNet: Masked and Permuted Pre-training for Language Understanding](https://arxiv.org/abs/2004.09297) da Kaitao Song, Xu Tan, Tao Qin, Jianfeng Lu, Tie-Yan Liu.
+1. **[MT5](model_doc/mt5)** (da Google AI) rilasciato con il paper [mT5: A massively multilingual pre-trained text-to-text transformer](https://arxiv.org/abs/2010.11934) da Linting Xue, Noah Constant, Adam Roberts, Mihir Kale, Rami Al-Rfou, Aditya Siddhant, Aditya Barua, Colin Raffel.
+1. **[Nyströmformer](model_doc/nystromformer)** (dalla Università del Wisconsin - Madison) rilasciato con il paper [Nyströmformer: A Nyström-Based Algorithm for Approximating Self-Attention](https://arxiv.org/abs/2102.03902) da Yunyang Xiong, Zhanpeng Zeng, Rudrasis Chakraborty, Mingxing Tan, Glenn Fung, Yin Li, Vikas Singh.
+1. **[OneFormer](model_doc/oneformer)** (da SHI Labs) rilasciato con il paper [OneFormer: One Transformer to Rule Universal Image Segmentation](https://arxiv.org/abs/2211.06220) da Jitesh Jain, Jiachen Li, MangTik Chiu, Ali Hassani, Nikita Orlov, Humphrey Shi.
+1. **[OPT](master/model_doc/opt)** (da Meta AI) rilasciato con il paper [OPT: Open Pre-trained Transformer Language Models](https://arxiv.org/abs/2205.01068) da Susan Zhang, Stephen Roller, Naman Goyal, Mikel Artetxe, Moya Chen, Shuohui Chen et al.
+1. **[Pegasus](model_doc/pegasus)** (da Google) rilasciato con il paper [PEGASUS: Pre-training with Extracted Gap-sentences for Abstractive Summarization](https://arxiv.org/abs/1912.08777) da Jingqing Zhang, Yao Zhao, Mohammad Saleh e Peter J. Liu.
+1. **[Perceiver IO](model_doc/perceiver)** (da Deepmind) rilasciato con il paper [Perceiver IO: A General Architecture for Structured Inputs & Outputs](https://arxiv.org/abs/2107.14795) da 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.
+1. **[PhoBERT](model_doc/phobert)** (da VinAI Research) rilasciato con il paper [PhoBERT: Pre-trained language models for Vietnamese](https://www.aclweb.org/anthology/2020.findings-emnlp.92/) da Dat Quoc Nguyen e Anh Tuan Nguyen.
+1. **[PLBart](model_doc/plbart)** (da UCLA NLP) rilasciato con il paper [Unified Pre-training for Program Understanding and Generation](https://arxiv.org/abs/2103.06333) da Wasi Uddin Ahmad, Saikat Chakraborty, Baishakhi Ray, Kai-Wei Chang.
+1. **[PoolFormer](model_doc/poolformer)** (da Sea AI Labs) rilasciato con il paper [MetaFormer is Actually What You Need for Vision](https://arxiv.org/abs/2111.11418) da Yu, Weihao e Luo, Mi e Zhou, Pan e Si, Chenyang e Zhou, Yichen e Wang, Xinchao e Feng, Jiashi e Yan, Shuicheng.
+1. **[ProphetNet](model_doc/prophetnet)** (da Microsoft Research) rilasciato con il paper [ProphetNet: Predicting Future N-gram for Sequence-to-Sequence Pre-training](https://arxiv.org/abs/2001.04063) da Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang e Ming Zhou.
+1. **[QDQBert](model_doc/qdqbert)** (da NVIDIA) rilasciato con il paper [Integer Quantization for Deep Learning Inference: Principles and Empirical Evaluation](https://arxiv.org/abs/2004.09602) da Hao Wu, Patrick Judd, Xiaojie Zhang, Mikhail Isaev e Paulius Micikevicius.
+1. **[REALM](model_doc/realm.html)** (da Google Research) rilasciato con il paper [REALM: Retrieval-Augmented Language Model Pre-Training](https://arxiv.org/abs/2002.08909) da Kelvin Guu, Kenton Lee, Zora Tung, Panupong Pasupat e Ming-Wei Chang.
+1. **[Reformer](model_doc/reformer)** (da Google Research) rilasciato con il paper [Reformer: The Efficient Transformer](https://arxiv.org/abs/2001.04451) da Nikita Kitaev, Ćukasz Kaiser, Anselm Levskaya.
+1. **[RemBERT](model_doc/rembert)** (da Google Research) rilasciato con il paper [Rethinking embedding coupling in pre-trained language models](https://arxiv.org/abs/2010.12821) da Hyung Won Chung, Thibault Févry, Henry Tsai, M. Johnson, Sebastian Ruder.
+1. **[RegNet](model_doc/regnet)** (da META Platforms) rilasciato con il paper [Designing Network Design Space](https://arxiv.org/abs/2003.13678) da Ilija Radosavovic, Raj Prateek Kosaraju, Ross Girshick, Kaiming He, Piotr DollĂĄr.
+1. **[ResNet](model_doc/resnet)** (da Microsoft Research) rilasciato con il paper [Deep Residual Learning for Image Recognition](https://arxiv.org/abs/1512.03385) da Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun.
+1. **[RoBERTa](model_doc/roberta)** (da Facebook), rilasciato assieme al paper [RoBERTa: A Robustly Optimized BERT Pretraining Approach](https://arxiv.org/abs/1907.11692) da Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Mandar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, Veselin Stoyanov.
+1. **[RoFormer](model_doc/roformer)** (da ZhuiyiTechnology), rilasciato assieme al paper [RoFormer: Enhanced Transformer with Rotary Position Embedding](https://arxiv.org/abs/2104.09864) da Jianlin Su e Yu Lu e Shengfeng Pan e Bo Wen e Yunfeng Liu.
+1. **[SegFormer](model_doc/segformer)** (da NVIDIA) rilasciato con il paper [SegFormer: Simple and Efficient Design for Semantic Segmentation with Transformers](https://arxiv.org/abs/2105.15203) da Enze Xie, Wenhai Wang, Zhiding Yu, Anima Anandkumar, Jose M. Alvarez, Ping Luo.
+1. **[SEW](model_doc/sew)** (da ASAPP) rilasciato con il paper [Performance-Efficiency Trade-offs in Unsupervised Pre-training for Speech Recognition](https://arxiv.org/abs/2109.06870) da Felix Wu, Kwangyoun Kim, Jing Pan, Kyu Han, Kilian Q. Weinberger, Yoav Artzi.
+1. **[SEW-D](model_doc/sew_d)** (da ASAPP) rilasciato con il paper [Performance-Efficiency Trade-offs in Unsupervised Pre-training for Speech Recognition](https://arxiv.org/abs/2109.06870) da Felix Wu, Kwangyoun Kim, Jing Pan, Kyu Han, Kilian Q. Weinberger, Yoav Artzi.
+1. **[SpeechToTextTransformer](model_doc/speech_to_text)** (da Facebook), rilasciato assieme al paper [fairseq S2T: Fast Speech-to-Text Modeling with fairseq](https://arxiv.org/abs/2010.05171) da Changhan Wang, Yun Tang, Xutai Ma, Anne Wu, Dmytro Okhonko, Juan Pino.
+1. **[SpeechToTextTransformer2](model_doc/speech_to_text_2)** (da Facebook), rilasciato assieme al paper [Large-Scale Self- and Semi-Supervised Learning for Speech Translation](https://arxiv.org/abs/2104.06678) da Changhan Wang, Anne Wu, Juan Pino, Alexei Baevski, Michael Auli, Alexis Conneau.
+1. **[Splinter](model_doc/splinter)** (dalla UniversitĂ di Tel Aviv), rilasciato assieme al paper [Few-Shot Question Answering by Pretraining Span Selection](https://arxiv.org/abs/2101.00438) da Ori Ram, Yuval Kirstain, Jonathan Berant, Amir Globerson, Omer Levy.
+1. **[SqueezeBert](model_doc/squeezebert)** (da Berkeley) rilasciato con il paper [SqueezeBERT: What can computer vision teach NLP about efficient neural networks?](https://arxiv.org/abs/2006.11316) da Forrest N. Iandola, Albert E. Shaw, Ravi Krishna, e Kurt W. Keutzer.
+1. **[Swin Transformer](model_doc/swin)** (da Microsoft) rilasciato con il paper [Swin Transformer: Hierarchical Vision Transformer using Shifted Windows](https://arxiv.org/abs/2103.14030) da Ze Liu, Yutong Lin, Yue Cao, Han Hu, Yixuan Wei, Zheng Zhang, Stephen Lin, Baining Guo.
+1. **[T5](model_doc/t5)** (da Google AI) rilasciato con il paper [Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer](https://arxiv.org/abs/1910.10683) da Colin Raffel e Noam Shazeer e Adam Roberts e Katherine Lee e Sharan Narang e Michael Matena e Yanqi Zhou e Wei Li e Peter J. Liu.
+1. **[T5v1.1](model_doc/t5v1.1)** (da Google AI) rilasciato nel repository [google-research/text-to-text-transfer-transformer](https://github.com/google-research/text-to-text-transfer-transformer/blob/main/released_checkpoints.md#t511) da Colin Raffel e Noam Shazeer e Adam Roberts e Katherine Lee e Sharan Narang e Michael Matena e Yanqi Zhou e Wei Li e Peter J. Liu.
+1. **[TAPAS](model_doc/tapas)** (da Google AI) rilasciato con il paper [TAPAS: Weakly Supervised Table Parsing via Pre-training](https://arxiv.org/abs/2004.02349) da Jonathan Herzig, PaweĆ Krzysztof Nowak, Thomas MĂŒller, Francesco Piccinno e Julian Martin Eisenschlos.
+1. **[TAPEX](model_doc/tapex)** (da Microsoft Research) rilasciato con il paper [TAPEX: Table Pre-training via Learning a Neural SQL Executor](https://arxiv.org/abs/2107.07653) da Qian Liu, Bei Chen, Jiaqi Guo, Morteza Ziyadi, Zeqi Lin, Weizhu Chen, Jian-Guang Lou.
+1. **[Trajectory Transformer](model_doc/trajectory_transformers)** (dall'UniversitĂ della California a Berkeley) rilasciato con il paper [Offline Reinforcement Learning as One Big Sequence Modeling Problem](https://arxiv.org/abs/2106.02039) da Michael Janner, Qiyang Li, Sergey Levine
+1. **[Transformer-XL](model_doc/transfo-xl)** (da Google/CMU) rilasciato con il paper [Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context](https://arxiv.org/abs/1901.02860) da Zihang Dai*, Zhilin Yang*, Yiming Yang, Jaime Carbonell, Quoc V. Le, Ruslan Salakhutdinov.
+1. **[TrOCR](model_doc/trocr)** (da Microsoft), rilasciato assieme al paper [TrOCR: Transformer-based Optical Character Recognition with Pre-trained Models](https://arxiv.org/abs/2109.10282) da Minghao Li, Tengchao Lv, Lei Cui, Yijuan Lu, Dinei Florencio, Cha Zhang, Zhoujun Li, Furu Wei.
+1. **[UniSpeech](model_doc/unispeech)** (da Microsoft Research) rilasciato con il paper [UniSpeech: Unified Speech Representation Learning with Labeled and Unlabeled Data](https://arxiv.org/abs/2101.07597) da Chengyi Wang, Yu Wu, Yao Qian, Kenichi Kumatani, Shujie Liu, Furu Wei, Michael Zeng, Xuedong Huang.
+1. **[UniSpeechSat](model_doc/unispeech-sat)** (da Microsoft Research) rilasciato con il paper [UNISPEECH-SAT: UNIVERSAL SPEECH REPRESENTATION LEARNING WITH SPEAKER AWARE PRE-TRAINING](https://arxiv.org/abs/2110.05752) da Sanyuan Chen, Yu Wu, Chengyi Wang, Zhengyang Chen, Zhuo Chen, Shujie Liu, Jian Wu, Yao Qian, Furu Wei, Jinyu Li, Xiangzhan Yu.
+1. **[VAN](model_doc/van)** (dalle UniversitĂ di Tsinghua e Nankai) rilasciato con il paper [Visual Attention Network](https://arxiv.org/abs/2202.09741) da Meng-Hao Guo, Cheng-Ze Lu, Zheng-Ning Liu, Ming-Ming Cheng, Shi-Min Hu.
+1. **[ViLT](model_doc/vilt)** (da NAVER AI Lab/Kakao Enterprise/Kakao Brain) rilasciato con il paper [ViLT: Vision-and-Language Transformer Without Convolution or Region Supervision](https://arxiv.org/abs/2102.03334) da Wonjae Kim, Bokyung Son, Ildoo Kim.
+1. **[Vision Transformer (ViT)](model_doc/vit)** (da Google AI) rilasciato con il paper [An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale](https://arxiv.org/abs/2010.11929) da Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xiaohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg Heigold, Sylvain Gelly, Jakob Uszkoreit, Neil Houlsby.
+1. **[ViTMAE](model_doc/vit_mae)** (da Meta AI) rilasciato con il paper [Masked Autoencoders Are Scalable Vision Learners](https://arxiv.org/abs/2111.06377) da Kaiming He, Xinlei Chen, Saining Xie, Yanghao Li, Piotr DollĂĄr, Ross Girshick.
+1. **[VisualBERT](model_doc/visual_bert)** (da UCLA NLP) rilasciato con il paper [VisualBERT: A Simple and Performant Baseline for Vision and Language](https://arxiv.org/pdf/1908.03557) da Liunian Harold Li, Mark Yatskar, Da Yin, Cho-Jui Hsieh, Kai-Wei Chang.
+1. **[WavLM](model_doc/wavlm)** (da Microsoft Research) rilasciato con il paper [WavLM: Large-Scale Self-Supervised Pre-Training for Full Stack Speech Processing](https://arxiv.org/abs/2110.13900) da 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.
+1. **[Wav2Vec2](model_doc/wav2vec2)** (da Facebook AI) rilasciato con il paper [wav2vec 2.0: A Framework for Self-Supervised Learning of Speech Representations](https://arxiv.org/abs/2006.11477) da Alexei Baevski, Henry Zhou, Abdelrahman Mohamed, Michael Auli.
+1. **[Wav2Vec2Phoneme](model_doc/wav2vec2_phoneme)** (da Facebook AI) rilasciato con il paper [Simple and Effective Zero-shot Cross-lingual Phoneme Recognition](https://arxiv.org/abs/2109.11680) da Qiantong Xu, Alexei Baevski, Michael Auli.
+1. **[XGLM](model_doc/xglm)** (da Facebook AI) rilasciato con il paper [Few-shot Learning with Multilingual Language Models](https://arxiv.org/abs/2112.10668) da 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.
+1. **[XLM](model_doc/xlm)** (v Facebook) rilasciato assieme al paper [Cross-lingual Language Model Pretraining](https://arxiv.org/abs/1901.07291) da Guillaume Lample e Alexis Conneau.
+1. **[XLM-ProphetNet](model_doc/xlm-prophetnet)** (da Microsoft Research) rilasciato con il paper [ProphetNet: Predicting Future N-gram for Sequence-to-Sequence Pre-training](https://arxiv.org/abs/2001.04063) da Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang e Ming Zhou.
+1. **[XLM-RoBERTa](model_doc/xlm-roberta)** (da Facebook AI), rilasciato assieme al paper [Unsupervised Cross-lingual Representation Learning at Scale](https://arxiv.org/abs/1911.02116) da Alexis Conneau*, Kartikay Khandelwal*, Naman Goyal, Vishrav Chaudhary, Guillaume Wenzek, Francisco GuzmĂĄn, Edouard Grave, Myle Ott, Luke Zettlemoyer e Veselin Stoyanov.
+1. **[XLM-RoBERTa-XL](model_doc/xlm-roberta-xl)** (da Facebook AI), rilasciato assieme al paper [Larger-Scale Transformers for Multilingual Masked Language Modeling](https://arxiv.org/abs/2105.00572) da Naman Goyal, Jingfei Du, Myle Ott, Giri Anantharaman, Alexis Conneau.
+1. **[XLNet](model_doc/xlnet)** (da Google/CMU) rilasciato con il paper [âXLNet: Generalized Autoregressive Pretraining for Language Understanding](https://arxiv.org/abs/1906.08237) da Zhilin Yang*, Zihang Dai*, Yiming Yang, Jaime Carbonell, Ruslan Salakhutdinov, Quoc V. Le.
+1. **[XLSR-Wav2Vec2](model_doc/xlsr_wav2vec2)** (da Facebook AI) rilasciato con il paper [Unsupervised Cross-Lingual Representation Learning For Speech Recognition](https://arxiv.org/abs/2006.13979) da Alexis Conneau, Alexei Baevski, Ronan Collobert, Abdelrahman Mohamed, Michael Auli.
+1. **[XLS-R](model_doc/xls_r)** (da Facebook AI) rilasciato con il paper [XLS-R: Self-supervised Cross-lingual Speech Representation Learning at Scale](https://arxiv.org/abs/2111.09296) da 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.
+1. **[YOLOS](model_doc/yolos)** (dalla UniversitĂ della scienza e tecnologia di Huazhong) rilasciato con il paper [You Only Look at One Sequence: Rethinking Transformer in Vision through Object Detection](https://arxiv.org/abs/2106.00666) da Yuxin Fang, Bencheng Liao, Xinggang Wang, Jiemin Fang, Jiyang Qi, Rui Wu, Jianwei Niu, Wenyu Liu.
+1. **[YOSO](model_doc/yoso)** (dall'UniversitĂ del Wisconsin - Madison) rilasciato con il paper [You Only Sample (Almost) Once: Linear Cost Self-Attention Via Bernoulli Sampling](https://arxiv.org/abs/2111.09714) da Zhanpeng Zeng, Yunyang Xiong, Sathya N. Ravi, Shailesh Acharya, Glenn Fung, Vikas Singh.
+
+
+### Framework supportati
+
+La tabella seguente rappresenta il supporto attuale nella libreria per ognuno di questi modelli, si puĂČ identificare se questi hanno un Python
+tokenizer (chiamato "slow"). Un tokenizer "fast" supportato dalla libreria đ€ Tokenizers, e se hanno supporto in Jax (via Flax), PyTorch, e/o TensorFlow.
+
+
+
+| Model | Tokenizer slow | Tokenizer fast | PyTorch support | TensorFlow support | Flax Support |
+|:---------------------------:|:--------------:|:--------------:|:---------------:|:------------------:|:------------:|
+| ALBERT | â
| â
| â
| â
| â
|
+| BART | â
| â
| â
| â
| â
|
+| BEiT | â | â | â
| â | â
|
+| BERT | â
| â
| â
| â
| â
|
+| Bert Generation | â
| â | â
| â | â |
+| BigBird | â
| â
| â
| â | â
|
+| BigBirdPegasus | â | â | â
| â | â |
+| Blenderbot | â
| â
| â
| â
| â
|
+| BlenderbotSmall | â
| â
| â
| â
| â
|
+| CamemBERT | â
| â
| â
| â
| â |
+| Canine | â
| â | â
| â | â |
+| CLIP | â
| â
| â
| â
| â
|
+| ConvBERT | â
| â
| â
| â
| â |
+| ConvNext | â | â | â
| â
| â |
+| CTRL | â
| â | â
| â
| â |
+| CvT | â | â | â
| â | â |
+| Data2VecAudio | â | â | â
| â | â |
+| Data2VecText | â | â | â
| â | â |
+| Data2VecVision | â | â | â
| â
| â |
+| DeBERTa | â
| â
| â
| â
| â |
+| DeBERTa-v2 | â
| â
| â
| â
| â |
+| Decision Transformer | â | â | â
| â | â |
+| DeiT | â | â | â
| â | â |
+| DETR | â | â | â
| â | â |
+| DistilBERT | â
| â
| â
| â
| â
|
+| DPR | â
| â
| â
| â
| â |
+| DPT | â | â | â
| â | â |
+| ELECTRA | â
| â
| â
| â
| â
|
+| Encoder decoder | â | â | â
| â
| â
|
+| FairSeq Machine-Translation | â
| â | â
| â | â |
+| FlauBERT | â
| â | â
| â
| â |
+| Flava | â | â | â
| â | â |
+| FNet | â
| â
| â
| â | â |
+| Funnel Transformer | â
| â
| â
| â
| â |
+| GLPN | â | â | â
| â | â |
+| GPT Neo | â | â | â
| â | â
|
+| GPT NeoX | â | â
| â
| â | â |
+| GPT-J | â | â | â
| â
| â
|
+| Hubert | â | â | â
| â
| â |
+| I-BERT | â | â | â
| â | â |
+| ImageGPT | â | â | â
| â | â |
+| LayoutLM | â
| â
| â
| â
| â |
+| LayoutLMv2 | â
| â
| â
| â | â |
+| LayoutLMv3 | â
| â
| â
| â
| â |
+| LED | â
| â
| â
| â
| â |
+| Longformer | â
| â
| â
| â
| â |
+| LUKE | â
| â | â
| â | â |
+| LXMERT | â
| â
| â
| â
| â |
+| M2M100 | â
| â | â
| â | â |
+| Marian | â
| â | â
| â
| â
|
+| MaskFormer | â | â | â
| â | â |
+| mBART | â
| â
| â
| â
| â
|
+| MegatronBert | â | â | â
| â | â |
+| MobileBERT | â
| â
| â
| â
| â |
+| MPNet | â
| â
| â
| â
| â |
+| mT5 | â
| â
| â
| â
| â
|
+| Nystromformer | â | â | â
| â | â |
+| OpenAI GPT | â
| â
| â
| â
| â |
+| OpenAI GPT-2 | â
| â
| â
| â
| â
|
+| OPT | â | â | â
| â | â |
+| Pegasus | â
| â
| â
| â
| â
|
+| Perceiver | â
| â | â
| â | â |
+| PLBart | â
| â | â
| â | â |
+| PoolFormer | â | â | â
| â | â |
+| ProphetNet | â
| â | â
| â | â |
+| QDQBert | â | â | â
| â | â |
+| RAG | â
| â | â
| â
| â |
+| Realm | â
| â
| â
| â | â |
+| Reformer | â
| â
| â
| â | â |
+| RegNet | â | â | â
| â
| â
|
+| RemBERT | â
| â
| â
| â
| â |
+| ResNet | â | â | â
| â
| â
|
+| RetriBERT | â
| â
| â
| â | â |
+| RoBERTa | â
| â
| â
| â
| â
|
+| RoFormer | â
| â
| â
| â
| â
|
+| SegFormer | â | â | â
| â | â |
+| SEW | â | â | â
| â | â |
+| SEW-D | â | â | â
| â | â |
+| Speech Encoder decoder | â | â | â
| â | â
|
+| Speech2Text | â
| â | â
| â
| â |
+| Speech2Text2 | â
| â | â | â | â |
+| Splinter | â
| â
| â
| â | â |
+| SqueezeBERT | â
| â
| â
| â | â |
+| Swin | â | â | â
| â
| â |
+| T5 | â
| â
| â
| â
| â
|
+| TAPAS | â
| â | â
| â
| â |
+| Trajectory Transformer | â | â | â
| â | â |
+| Transformer-XL | â
| â | â
| â
| â |
+| TrOCR | â | â | â
| â | â |
+| UniSpeech | â | â | â
| â | â |
+| UniSpeechSat | â | â | â
| â | â |
+| VAN | â | â | â
| â | â |
+| ViLT | â | â | â
| â | â |
+| Vision Encoder decoder | â | â | â
| â
| â
|
+| VisionTextDualEncoder | â | â | â
| â | â
|
+| VisualBert | â | â | â
| â | â |
+| ViT | â | â | â
| â
| â
|
+| ViTMAE | â | â | â
| â
| â |
+| Wav2Vec2 | â
| â | â
| â
| â
|
+| Wav2Vec2-Conformer | â | â | â
| â | â |
+| WavLM | â | â | â
| â | â |
+| XGLM | â
| â
| â
| â | â
|
+| XLM | â
| â | â
| â
| â |
+| XLM-RoBERTa | â
| â
| â
| â
| â
|
+| XLM-RoBERTa-XL | â | â | â
| â | â |
+| XLMProphetNet | â
| â | â
| â | â |
+| XLNet | â
| â
| â
| â
| â |
+| YOLOS | â | â | â
| â | â |
+| YOSO | â | â | â
| â | â |
+
+
diff --git a/docs/source/it/index.mdx b/docs/source/it/index.mdx
deleted file mode 100644
index 4c050bfe5224..000000000000
--- a/docs/source/it/index.mdx
+++ /dev/null
@@ -1,296 +0,0 @@
-
-
-# đ€ Transformers
-
-Machine Learning allo stato dell'arte per PyTorch, TensorFlow e JAX.
-
-đ€ Transformers fornisce delle API per scaricare in modo semplice e allenare modelli pre-allenati allo stato dell'arte. L'utilizzo di modelli pre-allenati puĂČ ridurre i tuoi costi computazionali, l'impatto ambientale, e farti risparmiare il tempo che utilizzeresti per allenare un modello da zero. I modelli possono essere utilizzati in diverse modalitĂ come ad esempio:
-
-* đ Testo: classificazione del testo, estrazione delle informazioni, rispondere a domande, riassumere, traduzione e generazione del testo in piĂč di 100 lingue.
-* đŒïž Immagini: classificazione di immagini, rilevazione di oggetti e segmentazione.
-* đŁïž Audio: riconoscimento vocale e classificazione dell'audio.
-* đ Multimodale: rispondere a domande inerenti dati tabulari, riconoscimento ottico dei caratteri, estrazione di informazioni a partire da documenti scannerizzati, classificazione di video e risposta visuale a domande.
-
-La nostra libreria supporta un'integrazione perfetta tra tre delle librerie per il deep learning piĂč popolari: [PyTorch](https://pytorch.org/), [TensorFlow](https://www.tensorflow.org/) e [JAX](https://jax.readthedocs.io/en/latest/). Allena il tuo modello in tre righe di codice in un framework, e caricalo per l'inferenza in un altro.
-
-Ogni architettura di đ€ Transformers Ăš definita in un modulo Python indipendente cosĂŹ da poter essere personalizzata in modo semplice per la ricerca e gli esperimenti.
-
-## Se stai cercando supporto personalizzato dal team di Hugging Face
-
-
-
-
-
-## Contenuti
-
-La documentazione Ăš organizzata in cinque parti:
-
-- **INIZIARE** contiene un tour rapido e le istruzioni di installazione per cominciare ad utilizzare đ€ Transformers.
-- **TUTORIALS** Ăš un buon posto da cui iniziare se per te la nostra libreria Ăš nuova. Questa sezione ti aiuterĂ ad acquisire le competenze basilari di cui hai bisogno per iniziare ad utilizzare đ€ Transformers.
-- **GUIDE PRATICHE** ti mostrerĂ come raggiungere obiettivi specifici come fare fine-tuning di un modello pre-allenato per la modellizzazione del linguaggio o come creare una testa per un modello personalizzato.
-- **GUIDE CONCETTUALI** fornisce discussioni e spiegazioni dei concetti sottostanti alle idee dietro ai modelli, compiti, e la filosofia di progettazione di đ€ Transformers.
-- **API** descrive ogni classe e funzione, raggruppate in:
- - **CLASSI PRINCIPALI** per le classi principali che espongono le API importanti della libreria.
- - **MODELLI** per le classi e le funzioni relative ad ogni modello implementato all'interno della libreria.
- - **HELPERS INTERNI** per le classi e le funzioni che utilizziamo internamente.
-
-La libreria attualmente contiene implementazioni in JAX, PyTorch e TensorFlow, pesi di modelli pre-allenati, script di utilizzo e strumenti di conversione per i seguenti modelli.
-
-### Modelli supportati
-
-
-
-1. **[ALBERT](model_doc/albert)** (da Google Research e l'Istituto Tecnologico di Chicago) rilasciato con il paper [ALBERT: A Lite BERT for Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), da Zhenzhong Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.
-1. **[ALIGN](model_doc/align)** (from Google Research) rilasciato con il paper [Scaling Up Visual and Vision-Language Representation Learning With Noisy Text Supervision](https://arxiv.org/abs/2102.05918) da Chao Jia, Yinfei Yang, Ye Xia, Yi-Ting Chen, Zarana Parekh, Hieu Pham, Quoc V. Le, Yunhsuan Sung, Zhen Li, Tom Duerig.
-1. **[BART](model_doc/bart)** (da Facebook) rilasciato con il paper [BART: Denoising Sequence-to-Sequence Pre-training for Natural Language Generation, Translation, and Comprehension](https://arxiv.org/abs/1910.13461) da Mike Lewis, Yinhan Liu, Naman Goyal, Marjan Ghazvininejad, Abdelrahman Mohamed, Omer Levy, Ves Stoyanov e Luke Zettlemoyer.
-1. **[BARThez](model_doc/barthez)** (da politecnico di Ăcole) rilasciato con il paper [BARThez: a Skilled Pretrained French Sequence-to-Sequence Model](https://arxiv.org/abs/2010.12321) da Moussa Kamal Eddine, Antoine J.-P. Tixier, Michalis Vazirgiannis.
-1. **[BARTpho](model_doc/bartpho)** (da VinAI Research) rilasciato con il paper [BARTpho: Pre-trained Sequence-to-Sequence Models for Vietnamese](https://arxiv.org/abs/2109.09701) da Nguyen Luong Tran, Duong Minh Le e Dat Quoc Nguyen.
-1. **[BEiT](model_doc/beit)** (da Microsoft) rilasciato con il paper [BEiT: BERT Pre-Training of Image Transformers](https://arxiv.org/abs/2106.08254) da Hangbo Bao, Li Dong, Furu Wei.
-1. **[BERT](model_doc/bert)** (da Google) rilasciato con il paper [BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding](https://arxiv.org/abs/1810.04805) da Jacob Devlin, Ming-Wei Chang, Kenton Lee e Kristina Toutanova.
-1. **[BERTweet](model_doc/bertweet)** (da VinAI Research) rilasciato con il paper [BERTweet: A pre-trained language model for English Tweets](https://aclanthology.org/2020.emnlp-demos.2/) da Dat Quoc Nguyen, Thanh Vu e Anh Tuan Nguyen.
-1. **[BERT For Sequence Generation](model_doc/bert-generation)** (da Google) rilasciato con il paper [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://arxiv.org/abs/1907.12461) da Sascha Rothe, Shashi Narayan, Aliaksei Severyn.
-1. **[BigBird-RoBERTa](model_doc/big_bird)** (da Google Research) rilasciato con il paper [Big Bird: Transformers for Longer Sequences](https://arxiv.org/abs/2007.14062) da Manzil Zaheer, Guru Guruganesh, Avinava Dubey, Joshua Ainslie, Chris Alberti, Santiago Ontanon, Philip Pham, Anirudh Ravula, Qifan Wang, Li Yang, Amr Ahmed.
-1. **[BigBird-Pegasus](model_doc/bigbird_pegasus)** (v Google Research) rilasciato con il paper [Big Bird: Transformers for Longer Sequences](https://arxiv.org/abs/2007.14062) da Manzil Zaheer, Guru Guruganesh, Avinava Dubey, Joshua Ainslie, Chris Alberti, Santiago Ontanon, Philip Pham, Anirudh Ravula, Qifan Wang, Li Yang, Amr Ahmed.
-1. **[Blenderbot](model_doc/blenderbot)** (da Facebook) rilasciato con il paper [Recipes for building an open-domain chatbot](https://arxiv.org/abs/2004.13637) da 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.
-1. **[BlenderbotSmall](model_doc/blenderbot-small)** (da Facebook) rilasciato con il paper [Recipes for building an open-domain chatbot](https://arxiv.org/abs/2004.13637) da 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.
-1. **[BORT](model_doc/bort)** (da Alexa) rilasciato con il paper [Optimal Subarchitecture Extraction For BERT](https://arxiv.org/abs/2010.10499) da Adrian de Wynter e Daniel J. Perry.
-1. **[ByT5](model_doc/byt5)** (da Google Research) rilasciato con il paper [ByT5: Towards a token-free future with pre-trained byte-to-byte models](https://arxiv.org/abs/2105.13626) da Linting Xue, Aditya Barua, Noah Constant, Rami Al-Rfou, Sharan Narang, Mihir Kale, Adam Roberts, Colin Raffel.
-1. **[CamemBERT](model_doc/camembert)** (da Inria/Facebook/Sorbonne) rilasciato con il paper [CamemBERT: a Tasty French Language Model](https://arxiv.org/abs/1911.03894) da Louis Martin*, Benjamin Muller*, Pedro Javier Ortiz SuĂĄrez*, Yoann Dupont, Laurent Romary, Ăric Villemonte de la Clergerie, DjamĂ© Seddah e BenoĂźt Sagot.
-1. **[CANINE](model_doc/canine)** (da Google Research) rilasciato con il paper [CANINE: Pre-training an Efficient Tokenization-Free Encoder for Language Representation](https://arxiv.org/abs/2103.06874) da Jonathan H. Clark, Dan Garrette, Iulia Turc, John Wieting.
-1. **[ConvNeXT](model_doc/convnext)** (da Facebook AI) rilasciato con il paper [A ConvNet for the 2020s](https://arxiv.org/abs/2201.03545) da Zhuang Liu, Hanzi Mao, Chao-Yuan Wu, Christoph Feichtenhofer, Trevor Darrell, Saining Xie.
-1. **[ConvNeXTV2](model_doc/convnextv2)** (da Facebook AI) rilasciato con il paper [ConvNeXt V2: Co-designing and Scaling ConvNets with Masked Autoencoders](https://arxiv.org/abs/2301.00808) da Sanghyun Woo, Shoubhik Debnath, Ronghang Hu, Xinlei Chen, Zhuang Liu, In So Kweon, Saining Xie.
-1. **[CLIP](model_doc/clip)** (da OpenAI) rilasciato con il paper [Learning Transferable Visual Models From Natural Language Supervision](https://arxiv.org/abs/2103.00020) da 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.
-1. **[ConvBERT](model_doc/convbert)** (da YituTech) rilasciato con il paper [ConvBERT: Improving BERT with Span-based Dynamic Convolution](https://arxiv.org/abs/2008.02496) da Zihang Jiang, Weihao Yu, Daquan Zhou, Yunpeng Chen, Jiashi Feng, Shuicheng Yan.
-1. **[CPM](model_doc/cpm)** (dalla UniversitĂ di Tsinghua) rilasciato con il paper [CPM: A Large-scale Generative Chinese Pre-trained Language Model](https://arxiv.org/abs/2012.00413) da 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.
-1. **[CTRL](model_doc/ctrl)** (da Salesforce) rilasciato con il paper [CTRL: A Conditional Transformer Language Model for Controllable Generation](https://arxiv.org/abs/1909.05858) da Nitish Shirish Keskar*, Bryan McCann*, Lav R. Varshney, Caiming Xiong e Richard Socher.
-1. **[CvT](model_doc/cvt)** (da Microsoft) rilasciato con il paper [CvT: Introducing Convolutions to Vision Transformers](https://arxiv.org/abs/2103.15808) da Haiping Wu, Bin Xiao, Noel Codella, Mengchen Liu, Xiyang Dai, Lu Yuan, Lei Zhang.
-1. **[Data2Vec](model_doc/data2vec)** (da Facebook) rilasciato con il paper [Data2Vec: A General Framework for Self-supervised Learning in Speech, Vision and Language](https://arxiv.org/abs/2202.03555) da Alexei Baevski, Wei-Ning Hsu, Qiantong Xu, Arun Babu, Jiatao Gu, Michael Auli.
-1. **[DeBERTa](model_doc/deberta)** (da Microsoft) rilasciato con il paper [DeBERTa: Decoding-enhanced BERT with Disentangled Attention](https://arxiv.org/abs/2006.03654) da Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen.
-1. **[DeBERTa-v2](model_doc/deberta-v2)** (da Microsoft) rilasciato con il paper [DeBERTa: Decoding-enhanced BERT with Disentangled Attention](https://arxiv.org/abs/2006.03654) da Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen.
-1. **[Decision Transformer](model_doc/decision_transformer)** (da Berkeley/Facebook/Google) rilasciato con il paper [Decision Transformer: Reinforcement Learning via Sequence Modeling](https://arxiv.org/abs/2106.01345) da Lili Chen, Kevin Lu, Aravind Rajeswaran, Kimin Lee, Aditya Grover, Michael Laskin, Pieter Abbeel, Aravind Srinivas, Igor Mordatch.
-1. **[DiT](model_doc/dit)** (da Microsoft Research) rilasciato con il paper [DiT: Self-supervised Pre-training for Document Image Transformer](https://arxiv.org/abs/2203.02378) da Junlong Li, Yiheng Xu, Tengchao Lv, Lei Cui, Cha Zhang, Furu Wei.
-1. **[DeiT](model_doc/deit)** (da Facebook) rilasciato con il paper [Training data-efficient image transformers & distillation through attention](https://arxiv.org/abs/2012.12877) da Hugo Touvron, Matthieu Cord, Matthijs Douze, Francisco Massa, Alexandre Sablayrolles, Hervé Jégou.
-1. **[DETR](model_doc/detr)** (da Facebook) rilasciato con il paper [End-to-End Object Detection with Transformers](https://arxiv.org/abs/2005.12872) da Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov, Sergey Zagoruyko.
-1. **[DialoGPT](model_doc/dialogpt)** (da Microsoft Research) rilasciato con il paper [DialoGPT: Large-Scale Generative Pre-training for Conversational Response Generation](https://arxiv.org/abs/1911.00536) da Yizhe Zhang, Siqi Sun, Michel Galley, Yen-Chun Chen, Chris Brockett, Xiang Gao, Jianfeng Gao, Jingjing Liu, Bill Dolan.
-1. **[DistilBERT](model_doc/distilbert)** (da HuggingFace), rilasciato assieme al paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter](https://arxiv.org/abs/1910.01108) da Victor Sanh, Lysandre Debut e Thomas Wolf. La stessa tecnica Ăš stata applicata per comprimere GPT2 in [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/research_projects/distillation), RoBERTa in [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/research_projects/distillation), Multilingual BERT in [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/research_projects/distillation) and a German version of DistilBERT.
-1. **[DPR](model_doc/dpr)** (da Facebook) rilasciato con il paper [Dense Passage Retrieval for Open-Domain Question Answering](https://arxiv.org/abs/2004.04906) da Vladimir Karpukhin, Barlas OÄuz, Sewon Min, Patrick Lewis, Ledell Wu, Sergey Edunov, Danqi Chen, e Wen-tau Yih.
-1. **[DPT](master/model_doc/dpt)** (da Intel Labs) rilasciato con il paper [Vision Transformers for Dense Prediction](https://arxiv.org/abs/2103.13413) da René Ranftl, Alexey Bochkovskiy, Vladlen Koltun.
-1. **[EfficientNet](model_doc/efficientnet)** (from Google Research) released with the paper [EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks](https://arxiv.org/abs/1905.11946) by Mingxing Tan and Quoc V. Le.
-1. **[EncoderDecoder](model_doc/encoder-decoder)** (da Google Research) rilasciato con il paper [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://arxiv.org/abs/1907.12461) da Sascha Rothe, Shashi Narayan, Aliaksei Severyn.
-1. **[ELECTRA](model_doc/electra)** (da Google Research/Stanford University) rilasciato con il paper [ELECTRA: Pre-training text encoders as discriminators rather than generators](https://arxiv.org/abs/2003.10555) da Kevin Clark, Minh-Thang Luong, Quoc V. Le, Christopher D. Manning.
-1. **[FlauBERT](model_doc/flaubert)** (da CNRS) rilasciato con il paper [FlauBERT: Unsupervised Language Model Pre-training for French](https://arxiv.org/abs/1912.05372) da Hang Le, Loïc Vial, Jibril Frej, Vincent Segonne, Maximin Coavoux, Benjamin Lecouteux, Alexandre Allauzen, Benoßt Crabbé, Laurent Besacier, Didier Schwab.
-1. **[FLAVA](model_doc/flava)** (da Facebook AI) rilasciato con il paper [FLAVA: A Foundational Language And Vision Alignment Model](https://arxiv.org/abs/2112.04482) da Amanpreet Singh, Ronghang Hu, Vedanuj Goswami, Guillaume Couairon, Wojciech Galuba, Marcus Rohrbach, e Douwe Kiela.
-1. **[FNet](model_doc/fnet)** (da Google Research) rilasciato con il paper [FNet: Mixing Tokens with Fourier Transforms](https://arxiv.org/abs/2105.03824) da James Lee-Thorp, Joshua Ainslie, Ilya Eckstein, Santiago Ontanon.
-1. **[Funnel Transformer](model_doc/funnel)** (da CMU/Google Brain) rilasciato con il paper [Funnel-Transformer: Filtering out Sequential Redundancy for Efficient Language Processing](https://arxiv.org/abs/2006.03236) da Zihang Dai, Guokun Lai, Yiming Yang, Quoc V. Le.
-1. **[GLPN](model_doc/glpn)** (da KAIST) rilasciato con il paper [Global-Local Path Networks for Monocular Depth Estimation with Vertical CutDepth](https://arxiv.org/abs/2201.07436) da Doyeon Kim, Woonghyun Ga, Pyungwhan Ahn, Donggyu Joo, Sehwan Chun, Junmo Kim.
-1. **[GPT](model_doc/openai-gpt)** (da OpenAI) rilasciato con il paper [Improving Language Understanding by Generative Pre-Training](https://blog.openai.com/language-unsupervised/) da Alec Radford, Karthik Narasimhan, Tim Salimans e Ilya Sutskever.
-1. **[GPT-2](model_doc/gpt2)** (da OpenAI) rilasciato con il paper [Language Models are Unsupervised Multitask Learners](https://blog.openai.com/better-language-models/) da Alec Radford*, Jeffrey Wu*, Rewon Child, David Luan, Dario Amodei** e Ilya Sutskever**.
-1. **[GPT-J](model_doc/gptj)** (da EleutherAI) rilasciato nel repository [kingoflolz/mesh-transformer-jax](https://github.com/kingoflolz/mesh-transformer-jax/) da Ben Wang e Aran Komatsuzaki.
-1. **[GPT Neo](model_doc/gpt_neo)** (da EleutherAI) rilasciato nel repository [EleutherAI/gpt-neo](https://github.com/EleutherAI/gpt-neo) da Sid Black, Stella Biderman, Leo Gao, Phil Wang e Connor Leahy.
-1. **[GPT NeoX](model_doc/gpt_neox)** (da EleutherAI) rilasciato con il paper [GPT-NeoX-20B: An Open-Source Autoregressive Language Model](https://arxiv.org/abs/2204.06745) da 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
-1. **[Hubert](model_doc/hubert)** (da Facebook) rilasciato con il paper [HuBERT: Self-Supervised Speech Representation Learning by Masked Prediction of Hidden Units](https://arxiv.org/abs/2106.07447) da Wei-Ning Hsu, Benjamin Bolte, Yao-Hung Hubert Tsai, Kushal Lakhotia, Ruslan Salakhutdinov, Abdelrahman Mohamed.
-1. **[I-BERT](model_doc/ibert)** (da Berkeley) rilasciato con il paper [I-BERT: Integer-only BERT Quantization](https://arxiv.org/abs/2101.01321) da Sehoon Kim, Amir Gholami, Zhewei Yao, Michael W. Mahoney, Kurt Keutzer.
-1. **[ImageGPT](model_doc/imagegpt)** (da OpenAI) rilasciato con il paper [Generative Pretraining from Pixels](https://openai.com/blog/image-gpt/) da Mark Chen, Alec Radford, Rewon Child, Jeffrey Wu, Heewoo Jun, David Luan, Ilya Sutskever.
-1. **[LayoutLM](model_doc/layoutlm)** (da Microsoft Research Asia) rilasciato con il paper [LayoutLM: Pre-training of Text and Layout for Document Image Understanding](https://arxiv.org/abs/1912.13318) da Yiheng Xu, Minghao Li, Lei Cui, Shaohan Huang, Furu Wei, Ming Zhou.
-1. **[LayoutLMv2](model_doc/layoutlmv2)** (da Microsoft Research Asia) rilasciato con il paper [LayoutLMv2: Multi-modal Pre-training for Visually-Rich Document Understanding](https://arxiv.org/abs/2012.14740) da Yang Xu, Yiheng Xu, Tengchao Lv, Lei Cui, Furu Wei, Guoxin Wang, Yijuan Lu, Dinei Florencio, Cha Zhang, Wanxiang Che, Min Zhang, Lidong Zhou.
-1. **[LayoutLMv3](model_doc/layoutlmv3)** (da Microsoft Research Asia) rilasciato con il paper [LayoutLMv3: Pre-training for Document AI with Unified Text and Image Masking](https://arxiv.org/abs/2204.08387) da Yupan Huang, Tengchao Lv, Lei Cui, Yutong Lu, Furu Wei.
-1. **[LayoutXLM](model_doc/layoutlxlm)** (da Microsoft Research Asia) rilasciato con il paper [LayoutXLM: Multimodal Pre-training for Multilingual Visually-rich Document Understanding](https://arxiv.org/abs/2104.08836) da Yiheng Xu, Tengchao Lv, Lei Cui, Guoxin Wang, Yijuan Lu, Dinei Florencio, Cha Zhang, Furu Wei.
-1. **[LED](model_doc/led)** (da AllenAI) rilasciato con il paper [Longformer: The Long-Document Transformer](https://arxiv.org/abs/2004.05150) da Iz Beltagy, Matthew E. Peters, Arman Cohan.
-1. **[Longformer](model_doc/longformer)** (da AllenAI) rilasciato con il paper [Longformer: The Long-Document Transformer](https://arxiv.org/abs/2004.05150) da Iz Beltagy, Matthew E. Peters, Arman Cohan.
-1. **[LUKE](model_doc/luke)** (da Studio Ousia) rilasciato con il paper [LUKE: Deep Contextualized Entity Representations with Entity-aware Self-attention](https://arxiv.org/abs/2010.01057) da Ikuya Yamada, Akari Asai, Hiroyuki Shindo, Hideaki Takeda, Yuji Matsumoto.
-1. **[mLUKE](model_doc/mluke)** (da Studio Ousia) rilasciato con il paper [mLUKE: The Power of Entity Representations in Multilingual Pretrained Language Models](https://arxiv.org/abs/2110.08151) da Ryokan Ri, Ikuya Yamada, e Yoshimasa Tsuruoka.
-1. **[LXMERT](model_doc/lxmert)** (da UNC Chapel Hill) rilasciato con il paper [LXMERT: Learning Cross-Modality Encoder Representations from Transformers for Open-Domain Question Answering](https://arxiv.org/abs/1908.07490) da Hao Tan e Mohit Bansal.
-1. **[M2M100](model_doc/m2m_100)** (da Facebook) rilasciato con il paper [Beyond English-Centric Multilingual Machine Translation](https://arxiv.org/abs/2010.11125) da 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.
-1. **[MarianMT](model_doc/marian)** Modello di machine learning per le traduzioni allenato utilizzando i dati [OPUS](http://opus.nlpl.eu/) di Jörg Tiedemann. Il [Framework Marian](https://marian-nmt.github.io/) Ú stato sviluppato dal Microsoft Translator Team.
-1. **[Mask2Former](model_doc/mask2former)** (da FAIR e UIUC) rilasciato con il paper [Masked-attention Mask Transformer for Universal Image Segmentation](https://arxiv.org/abs/2112.01527) da Bowen Cheng, Ishan Misra, Alexander G. Schwing, Alexander Kirillov, Rohit Girdhar.
-1. **[MaskFormer](model_doc/maskformer)** (da Meta e UIUC) rilasciato con il paper [Per-Pixel Classification is Not All You Need for Semantic Segmentation](https://arxiv.org/abs/2107.06278) da Bowen Cheng, Alexander G. Schwing, Alexander Kirillov.
-1. **[MBart](model_doc/mbart)** (da Facebook) rilasciato con il paper [Multilingual Denoising Pre-training for Neural Machine Translation](https://arxiv.org/abs/2001.08210) da Yinhan Liu, Jiatao Gu, Naman Goyal, Xian Li, Sergey Edunov, Marjan Ghazvininejad, Mike Lewis, Luke Zettlemoyer.
-1. **[MBart-50](model_doc/mbart)** (da Facebook) rilasciato con il paper [Multilingual Translation with Extensible Multilingual Pretraining and Finetuning](https://arxiv.org/abs/2008.00401) da Yuqing Tang, Chau Tran, Xian Li, Peng-Jen Chen, Naman Goyal, Vishrav Chaudhary, Jiatao Gu, Angela Fan.
-1. **[Megatron-BERT](model_doc/megatron-bert)** (da NVIDIA) rilasciato con il paper [Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism](https://arxiv.org/abs/1909.08053) da Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper e Bryan Catanzaro.
-1. **[Megatron-GPT2](model_doc/megatron_gpt2)** (da NVIDIA) rilasciato con il paper [Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism](https://arxiv.org/abs/1909.08053) da Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper e Bryan Catanzaro.
-1. **[MPNet](model_doc/mpnet)** (da Microsoft Research) rilasciato con il paper [MPNet: Masked and Permuted Pre-training for Language Understanding](https://arxiv.org/abs/2004.09297) da Kaitao Song, Xu Tan, Tao Qin, Jianfeng Lu, Tie-Yan Liu.
-1. **[MT5](model_doc/mt5)** (da Google AI) rilasciato con il paper [mT5: A massively multilingual pre-trained text-to-text transformer](https://arxiv.org/abs/2010.11934) da Linting Xue, Noah Constant, Adam Roberts, Mihir Kale, Rami Al-Rfou, Aditya Siddhant, Aditya Barua, Colin Raffel.
-1. **[Nyströmformer](model_doc/nystromformer)** (dalla Università del Wisconsin - Madison) rilasciato con il paper [Nyströmformer: A Nyström-Based Algorithm for Approximating Self-Attention](https://arxiv.org/abs/2102.03902) da Yunyang Xiong, Zhanpeng Zeng, Rudrasis Chakraborty, Mingxing Tan, Glenn Fung, Yin Li, Vikas Singh.
-1. **[OneFormer](model_doc/oneformer)** (da SHI Labs) rilasciato con il paper [OneFormer: One Transformer to Rule Universal Image Segmentation](https://arxiv.org/abs/2211.06220) da Jitesh Jain, Jiachen Li, MangTik Chiu, Ali Hassani, Nikita Orlov, Humphrey Shi.
-1. **[OPT](master/model_doc/opt)** (da Meta AI) rilasciato con il paper [OPT: Open Pre-trained Transformer Language Models](https://arxiv.org/abs/2205.01068) da Susan Zhang, Stephen Roller, Naman Goyal, Mikel Artetxe, Moya Chen, Shuohui Chen et al.
-1. **[Pegasus](model_doc/pegasus)** (da Google) rilasciato con il paper [PEGASUS: Pre-training with Extracted Gap-sentences for Abstractive Summarization](https://arxiv.org/abs/1912.08777) da Jingqing Zhang, Yao Zhao, Mohammad Saleh e Peter J. Liu.
-1. **[Perceiver IO](model_doc/perceiver)** (da Deepmind) rilasciato con il paper [Perceiver IO: A General Architecture for Structured Inputs & Outputs](https://arxiv.org/abs/2107.14795) da 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.
-1. **[PhoBERT](model_doc/phobert)** (da VinAI Research) rilasciato con il paper [PhoBERT: Pre-trained language models for Vietnamese](https://www.aclweb.org/anthology/2020.findings-emnlp.92/) da Dat Quoc Nguyen e Anh Tuan Nguyen.
-1. **[PLBart](model_doc/plbart)** (da UCLA NLP) rilasciato con il paper [Unified Pre-training for Program Understanding and Generation](https://arxiv.org/abs/2103.06333) da Wasi Uddin Ahmad, Saikat Chakraborty, Baishakhi Ray, Kai-Wei Chang.
-1. **[PoolFormer](model_doc/poolformer)** (da Sea AI Labs) rilasciato con il paper [MetaFormer is Actually What You Need for Vision](https://arxiv.org/abs/2111.11418) da Yu, Weihao e Luo, Mi e Zhou, Pan e Si, Chenyang e Zhou, Yichen e Wang, Xinchao e Feng, Jiashi e Yan, Shuicheng.
-1. **[ProphetNet](model_doc/prophetnet)** (da Microsoft Research) rilasciato con il paper [ProphetNet: Predicting Future N-gram for Sequence-to-Sequence Pre-training](https://arxiv.org/abs/2001.04063) da Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang e Ming Zhou.
-1. **[QDQBert](model_doc/qdqbert)** (da NVIDIA) rilasciato con il paper [Integer Quantization for Deep Learning Inference: Principles and Empirical Evaluation](https://arxiv.org/abs/2004.09602) da Hao Wu, Patrick Judd, Xiaojie Zhang, Mikhail Isaev e Paulius Micikevicius.
-1. **[REALM](model_doc/realm.html)** (da Google Research) rilasciato con il paper [REALM: Retrieval-Augmented Language Model Pre-Training](https://arxiv.org/abs/2002.08909) da Kelvin Guu, Kenton Lee, Zora Tung, Panupong Pasupat e Ming-Wei Chang.
-1. **[Reformer](model_doc/reformer)** (da Google Research) rilasciato con il paper [Reformer: The Efficient Transformer](https://arxiv.org/abs/2001.04451) da Nikita Kitaev, Ćukasz Kaiser, Anselm Levskaya.
-1. **[RemBERT](model_doc/rembert)** (da Google Research) rilasciato con il paper [Rethinking embedding coupling in pre-trained language models](https://arxiv.org/abs/2010.12821) da Hyung Won Chung, Thibault Févry, Henry Tsai, M. Johnson, Sebastian Ruder.
-1. **[RegNet](model_doc/regnet)** (da META Platforms) rilasciato con il paper [Designing Network Design Space](https://arxiv.org/abs/2003.13678) da Ilija Radosavovic, Raj Prateek Kosaraju, Ross Girshick, Kaiming He, Piotr DollĂĄr.
-1. **[ResNet](model_doc/resnet)** (da Microsoft Research) rilasciato con il paper [Deep Residual Learning for Image Recognition](https://arxiv.org/abs/1512.03385) da Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun.
-1. **[RoBERTa](model_doc/roberta)** (da Facebook), rilasciato assieme al paper [RoBERTa: A Robustly Optimized BERT Pretraining Approach](https://arxiv.org/abs/1907.11692) da Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Mandar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, Veselin Stoyanov.
-1. **[RoFormer](model_doc/roformer)** (da ZhuiyiTechnology), rilasciato assieme al paper [RoFormer: Enhanced Transformer with Rotary Position Embedding](https://arxiv.org/abs/2104.09864) da Jianlin Su e Yu Lu e Shengfeng Pan e Bo Wen e Yunfeng Liu.
-1. **[SegFormer](model_doc/segformer)** (da NVIDIA) rilasciato con il paper [SegFormer: Simple and Efficient Design for Semantic Segmentation with Transformers](https://arxiv.org/abs/2105.15203) da Enze Xie, Wenhai Wang, Zhiding Yu, Anima Anandkumar, Jose M. Alvarez, Ping Luo.
-1. **[SEW](model_doc/sew)** (da ASAPP) rilasciato con il paper [Performance-Efficiency Trade-offs in Unsupervised Pre-training for Speech Recognition](https://arxiv.org/abs/2109.06870) da Felix Wu, Kwangyoun Kim, Jing Pan, Kyu Han, Kilian Q. Weinberger, Yoav Artzi.
-1. **[SEW-D](model_doc/sew_d)** (da ASAPP) rilasciato con il paper [Performance-Efficiency Trade-offs in Unsupervised Pre-training for Speech Recognition](https://arxiv.org/abs/2109.06870) da Felix Wu, Kwangyoun Kim, Jing Pan, Kyu Han, Kilian Q. Weinberger, Yoav Artzi.
-1. **[SpeechToTextTransformer](model_doc/speech_to_text)** (da Facebook), rilasciato assieme al paper [fairseq S2T: Fast Speech-to-Text Modeling with fairseq](https://arxiv.org/abs/2010.05171) da Changhan Wang, Yun Tang, Xutai Ma, Anne Wu, Dmytro Okhonko, Juan Pino.
-1. **[SpeechToTextTransformer2](model_doc/speech_to_text_2)** (da Facebook), rilasciato assieme al paper [Large-Scale Self- and Semi-Supervised Learning for Speech Translation](https://arxiv.org/abs/2104.06678) da Changhan Wang, Anne Wu, Juan Pino, Alexei Baevski, Michael Auli, Alexis Conneau.
-1. **[Splinter](model_doc/splinter)** (dalla UniversitĂ di Tel Aviv), rilasciato assieme al paper [Few-Shot Question Answering by Pretraining Span Selection](https://arxiv.org/abs/2101.00438) da Ori Ram, Yuval Kirstain, Jonathan Berant, Amir Globerson, Omer Levy.
-1. **[SqueezeBert](model_doc/squeezebert)** (da Berkeley) rilasciato con il paper [SqueezeBERT: What can computer vision teach NLP about efficient neural networks?](https://arxiv.org/abs/2006.11316) da Forrest N. Iandola, Albert E. Shaw, Ravi Krishna, e Kurt W. Keutzer.
-1. **[Swin Transformer](model_doc/swin)** (da Microsoft) rilasciato con il paper [Swin Transformer: Hierarchical Vision Transformer using Shifted Windows](https://arxiv.org/abs/2103.14030) da Ze Liu, Yutong Lin, Yue Cao, Han Hu, Yixuan Wei, Zheng Zhang, Stephen Lin, Baining Guo.
-1. **[T5](model_doc/t5)** (da Google AI) rilasciato con il paper [Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer](https://arxiv.org/abs/1910.10683) da Colin Raffel e Noam Shazeer e Adam Roberts e Katherine Lee e Sharan Narang e Michael Matena e Yanqi Zhou e Wei Li e Peter J. Liu.
-1. **[T5v1.1](model_doc/t5v1.1)** (da Google AI) rilasciato nel repository [google-research/text-to-text-transfer-transformer](https://github.com/google-research/text-to-text-transfer-transformer/blob/main/released_checkpoints.md#t511) da Colin Raffel e Noam Shazeer e Adam Roberts e Katherine Lee e Sharan Narang e Michael Matena e Yanqi Zhou e Wei Li e Peter J. Liu.
-1. **[TAPAS](model_doc/tapas)** (da Google AI) rilasciato con il paper [TAPAS: Weakly Supervised Table Parsing via Pre-training](https://arxiv.org/abs/2004.02349) da Jonathan Herzig, PaweĆ Krzysztof Nowak, Thomas MĂŒller, Francesco Piccinno e Julian Martin Eisenschlos.
-1. **[TAPEX](model_doc/tapex)** (da Microsoft Research) rilasciato con il paper [TAPEX: Table Pre-training via Learning a Neural SQL Executor](https://arxiv.org/abs/2107.07653) da Qian Liu, Bei Chen, Jiaqi Guo, Morteza Ziyadi, Zeqi Lin, Weizhu Chen, Jian-Guang Lou.
-1. **[Trajectory Transformer](model_doc/trajectory_transformers)** (dall'UniversitĂ della California a Berkeley) rilasciato con il paper [Offline Reinforcement Learning as One Big Sequence Modeling Problem](https://arxiv.org/abs/2106.02039) da Michael Janner, Qiyang Li, Sergey Levine
-1. **[Transformer-XL](model_doc/transfo-xl)** (da Google/CMU) rilasciato con il paper [Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context](https://arxiv.org/abs/1901.02860) da Zihang Dai*, Zhilin Yang*, Yiming Yang, Jaime Carbonell, Quoc V. Le, Ruslan Salakhutdinov.
-1. **[TrOCR](model_doc/trocr)** (da Microsoft), rilasciato assieme al paper [TrOCR: Transformer-based Optical Character Recognition with Pre-trained Models](https://arxiv.org/abs/2109.10282) da Minghao Li, Tengchao Lv, Lei Cui, Yijuan Lu, Dinei Florencio, Cha Zhang, Zhoujun Li, Furu Wei.
-1. **[UniSpeech](model_doc/unispeech)** (da Microsoft Research) rilasciato con il paper [UniSpeech: Unified Speech Representation Learning with Labeled and Unlabeled Data](https://arxiv.org/abs/2101.07597) da Chengyi Wang, Yu Wu, Yao Qian, Kenichi Kumatani, Shujie Liu, Furu Wei, Michael Zeng, Xuedong Huang.
-1. **[UniSpeechSat](model_doc/unispeech-sat)** (da Microsoft Research) rilasciato con il paper [UNISPEECH-SAT: UNIVERSAL SPEECH REPRESENTATION LEARNING WITH SPEAKER AWARE PRE-TRAINING](https://arxiv.org/abs/2110.05752) da Sanyuan Chen, Yu Wu, Chengyi Wang, Zhengyang Chen, Zhuo Chen, Shujie Liu, Jian Wu, Yao Qian, Furu Wei, Jinyu Li, Xiangzhan Yu.
-1. **[VAN](model_doc/van)** (dalle UniversitĂ di Tsinghua e Nankai) rilasciato con il paper [Visual Attention Network](https://arxiv.org/abs/2202.09741) da Meng-Hao Guo, Cheng-Ze Lu, Zheng-Ning Liu, Ming-Ming Cheng, Shi-Min Hu.
-1. **[ViLT](model_doc/vilt)** (da NAVER AI Lab/Kakao Enterprise/Kakao Brain) rilasciato con il paper [ViLT: Vision-and-Language Transformer Without Convolution or Region Supervision](https://arxiv.org/abs/2102.03334) da Wonjae Kim, Bokyung Son, Ildoo Kim.
-1. **[Vision Transformer (ViT)](model_doc/vit)** (da Google AI) rilasciato con il paper [An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale](https://arxiv.org/abs/2010.11929) da Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xiaohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg Heigold, Sylvain Gelly, Jakob Uszkoreit, Neil Houlsby.
-1. **[ViTMAE](model_doc/vit_mae)** (da Meta AI) rilasciato con il paper [Masked Autoencoders Are Scalable Vision Learners](https://arxiv.org/abs/2111.06377) da Kaiming He, Xinlei Chen, Saining Xie, Yanghao Li, Piotr DollĂĄr, Ross Girshick.
-1. **[VisualBERT](model_doc/visual_bert)** (da UCLA NLP) rilasciato con il paper [VisualBERT: A Simple and Performant Baseline for Vision and Language](https://arxiv.org/pdf/1908.03557) da Liunian Harold Li, Mark Yatskar, Da Yin, Cho-Jui Hsieh, Kai-Wei Chang.
-1. **[WavLM](model_doc/wavlm)** (da Microsoft Research) rilasciato con il paper [WavLM: Large-Scale Self-Supervised Pre-Training for Full Stack Speech Processing](https://arxiv.org/abs/2110.13900) da 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.
-1. **[Wav2Vec2](model_doc/wav2vec2)** (da Facebook AI) rilasciato con il paper [wav2vec 2.0: A Framework for Self-Supervised Learning of Speech Representations](https://arxiv.org/abs/2006.11477) da Alexei Baevski, Henry Zhou, Abdelrahman Mohamed, Michael Auli.
-1. **[Wav2Vec2Phoneme](model_doc/wav2vec2_phoneme)** (da Facebook AI) rilasciato con il paper [Simple and Effective Zero-shot Cross-lingual Phoneme Recognition](https://arxiv.org/abs/2109.11680) da Qiantong Xu, Alexei Baevski, Michael Auli.
-1. **[XGLM](model_doc/xglm)** (da Facebook AI) rilasciato con il paper [Few-shot Learning with Multilingual Language Models](https://arxiv.org/abs/2112.10668) da 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.
-1. **[XLM](model_doc/xlm)** (v Facebook) rilasciato assieme al paper [Cross-lingual Language Model Pretraining](https://arxiv.org/abs/1901.07291) da Guillaume Lample e Alexis Conneau.
-1. **[XLM-ProphetNet](model_doc/xlm-prophetnet)** (da Microsoft Research) rilasciato con il paper [ProphetNet: Predicting Future N-gram for Sequence-to-Sequence Pre-training](https://arxiv.org/abs/2001.04063) da Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang e Ming Zhou.
-1. **[XLM-RoBERTa](model_doc/xlm-roberta)** (da Facebook AI), rilasciato assieme al paper [Unsupervised Cross-lingual Representation Learning at Scale](https://arxiv.org/abs/1911.02116) da Alexis Conneau*, Kartikay Khandelwal*, Naman Goyal, Vishrav Chaudhary, Guillaume Wenzek, Francisco GuzmĂĄn, Edouard Grave, Myle Ott, Luke Zettlemoyer e Veselin Stoyanov.
-1. **[XLM-RoBERTa-XL](model_doc/xlm-roberta-xl)** (da Facebook AI), rilasciato assieme al paper [Larger-Scale Transformers for Multilingual Masked Language Modeling](https://arxiv.org/abs/2105.00572) da Naman Goyal, Jingfei Du, Myle Ott, Giri Anantharaman, Alexis Conneau.
-1. **[XLNet](model_doc/xlnet)** (da Google/CMU) rilasciato con il paper [âXLNet: Generalized Autoregressive Pretraining for Language Understanding](https://arxiv.org/abs/1906.08237) da Zhilin Yang*, Zihang Dai*, Yiming Yang, Jaime Carbonell, Ruslan Salakhutdinov, Quoc V. Le.
-1. **[XLSR-Wav2Vec2](model_doc/xlsr_wav2vec2)** (da Facebook AI) rilasciato con il paper [Unsupervised Cross-Lingual Representation Learning For Speech Recognition](https://arxiv.org/abs/2006.13979) da Alexis Conneau, Alexei Baevski, Ronan Collobert, Abdelrahman Mohamed, Michael Auli.
-1. **[XLS-R](model_doc/xls_r)** (da Facebook AI) rilasciato con il paper [XLS-R: Self-supervised Cross-lingual Speech Representation Learning at Scale](https://arxiv.org/abs/2111.09296) da 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.
-1. **[YOLOS](model_doc/yolos)** (dalla UniversitĂ della scienza e tecnologia di Huazhong) rilasciato con il paper [You Only Look at One Sequence: Rethinking Transformer in Vision through Object Detection](https://arxiv.org/abs/2106.00666) da Yuxin Fang, Bencheng Liao, Xinggang Wang, Jiemin Fang, Jiyang Qi, Rui Wu, Jianwei Niu, Wenyu Liu.
-1. **[YOSO](model_doc/yoso)** (dall'UniversitĂ del Wisconsin - Madison) rilasciato con il paper [You Only Sample (Almost) Once: Linear Cost Self-Attention Via Bernoulli Sampling](https://arxiv.org/abs/2111.09714) da Zhanpeng Zeng, Yunyang Xiong, Sathya N. Ravi, Shailesh Acharya, Glenn Fung, Vikas Singh.
-
-
-### Framework supportati
-
-La tabella seguente rappresenta il supporto attuale nella libreria per ognuno di questi modelli, si puĂČ identificare se questi hanno un Python
-tokenizer (chiamato "slow"). Un tokenizer "fast" supportato dalla libreria đ€ Tokenizers, e se hanno supporto in Jax (via Flax), PyTorch, e/o TensorFlow.
-
-
-
-| Model | Tokenizer slow | Tokenizer fast | PyTorch support | TensorFlow support | Flax Support |
-|:---------------------------:|:--------------:|:--------------:|:---------------:|:------------------:|:------------:|
-| ALBERT | â
| â
| â
| â
| â
|
-| BART | â
| â
| â
| â
| â
|
-| BEiT | â | â | â
| â | â
|
-| BERT | â
| â
| â
| â
| â
|
-| Bert Generation | â
| â | â
| â | â |
-| BigBird | â
| â
| â
| â | â
|
-| BigBirdPegasus | â | â | â
| â | â |
-| Blenderbot | â
| â
| â
| â
| â
|
-| BlenderbotSmall | â
| â
| â
| â
| â
|
-| CamemBERT | â
| â
| â
| â
| â |
-| Canine | â
| â | â
| â | â |
-| CLIP | â
| â
| â
| â
| â
|
-| ConvBERT | â
| â
| â
| â
| â |
-| ConvNext | â | â | â
| â
| â |
-| CTRL | â
| â | â
| â
| â |
-| CvT | â | â | â
| â | â |
-| Data2VecAudio | â | â | â
| â | â |
-| Data2VecText | â | â | â
| â | â |
-| Data2VecVision | â | â | â
| â
| â |
-| DeBERTa | â
| â
| â
| â
| â |
-| DeBERTa-v2 | â
| â
| â
| â
| â |
-| Decision Transformer | â | â | â
| â | â |
-| DeiT | â | â | â
| â | â |
-| DETR | â | â | â
| â | â |
-| DistilBERT | â
| â
| â
| â
| â
|
-| DPR | â
| â
| â
| â
| â |
-| DPT | â | â | â
| â | â |
-| ELECTRA | â
| â
| â
| â
| â
|
-| Encoder decoder | â | â | â
| â
| â
|
-| FairSeq Machine-Translation | â
| â | â
| â | â |
-| FlauBERT | â
| â | â
| â
| â |
-| Flava | â | â | â
| â | â |
-| FNet | â
| â
| â
| â | â |
-| Funnel Transformer | â
| â
| â
| â
| â |
-| GLPN | â | â | â
| â | â |
-| GPT Neo | â | â | â
| â | â
|
-| GPT NeoX | â | â
| â
| â | â |
-| GPT-J | â | â | â
| â
| â
|
-| Hubert | â | â | â
| â
| â |
-| I-BERT | â | â | â
| â | â |
-| ImageGPT | â | â | â
| â | â |
-| LayoutLM | â
| â
| â
| â
| â |
-| LayoutLMv2 | â
| â
| â
| â | â |
-| LayoutLMv3 | â
| â
| â
| â
| â |
-| LED | â
| â
| â
| â
| â |
-| Longformer | â
| â
| â
| â
| â |
-| LUKE | â
| â | â
| â | â |
-| LXMERT | â
| â
| â
| â
| â |
-| M2M100 | â
| â | â
| â | â |
-| Marian | â
| â | â
| â
| â
|
-| MaskFormer | â | â | â
| â | â |
-| mBART | â
| â
| â
| â
| â
|
-| MegatronBert | â | â | â
| â | â |
-| MobileBERT | â
| â
| â
| â
| â |
-| MPNet | â
| â
| â
| â
| â |
-| mT5 | â
| â
| â
| â
| â
|
-| Nystromformer | â | â | â
| â | â |
-| OpenAI GPT | â
| â
| â
| â
| â |
-| OpenAI GPT-2 | â
| â
| â
| â
| â
|
-| OPT | â | â | â
| â | â |
-| Pegasus | â
| â
| â
| â
| â
|
-| Perceiver | â
| â | â
| â | â |
-| PLBart | â
| â | â
| â | â |
-| PoolFormer | â | â | â
| â | â |
-| ProphetNet | â
| â | â
| â | â |
-| QDQBert | â | â | â
| â | â |
-| RAG | â
| â | â
| â
| â |
-| Realm | â
| â
| â
| â | â |
-| Reformer | â
| â
| â
| â | â |
-| RegNet | â | â | â
| â
| â
|
-| RemBERT | â
| â
| â
| â
| â |
-| ResNet | â | â | â
| â
| â
|
-| RetriBERT | â
| â
| â
| â | â |
-| RoBERTa | â
| â
| â
| â
| â
|
-| RoFormer | â
| â
| â
| â
| â
|
-| SegFormer | â | â | â
| â | â |
-| SEW | â | â | â
| â | â |
-| SEW-D | â | â | â
| â | â |
-| Speech Encoder decoder | â | â | â
| â | â
|
-| Speech2Text | â
| â | â
| â
| â |
-| Speech2Text2 | â
| â | â | â | â |
-| Splinter | â
| â
| â
| â | â |
-| SqueezeBERT | â
| â
| â
| â | â |
-| Swin | â | â | â
| â
| â |
-| T5 | â
| â
| â
| â
| â
|
-| TAPAS | â
| â | â
| â
| â |
-| Trajectory Transformer | â | â | â
| â | â |
-| Transformer-XL | â
| â | â
| â
| â |
-| TrOCR | â | â | â
| â | â |
-| UniSpeech | â | â | â
| â | â |
-| UniSpeechSat | â | â | â
| â | â |
-| VAN | â | â | â
| â | â |
-| ViLT | â | â | â
| â | â |
-| Vision Encoder decoder | â | â | â
| â
| â
|
-| VisionTextDualEncoder | â | â | â
| â | â
|
-| VisualBert | â | â | â
| â | â |
-| ViT | â | â | â
| â
| â
|
-| ViTMAE | â | â | â
| â
| â |
-| Wav2Vec2 | â
| â | â
| â
| â
|
-| Wav2Vec2-Conformer | â | â | â
| â | â |
-| WavLM | â | â | â
| â | â |
-| XGLM | â
| â
| â
| â | â
|
-| XLM | â
| â | â
| â
| â |
-| XLM-RoBERTa | â
| â
| â
| â
| â
|
-| XLM-RoBERTa-XL | â | â | â
| â | â |
-| XLMProphetNet | â
| â | â
| â | â |
-| XLNet | â
| â
| â
| â
| â |
-| YOLOS | â | â | â
| â | â |
-| YOSO | â | â | â
| â | â |
-
-
diff --git a/docs/source/it/installation.md b/docs/source/it/installation.md
new file mode 100644
index 000000000000..4f884f80d936
--- /dev/null
+++ b/docs/source/it/installation.md
@@ -0,0 +1,239 @@
+
+
+# Installazione
+
+Installa đ€ Transformers per qualsiasi libreria di deep learning con cui stai lavorando, imposta la tua cache, e opzionalmente configura đ€ Transformers per l'esecuzione offline.
+
+đ€ Transformers Ăš testato su Python 3.6+, PyTorch 1.1.0+, TensorFlow 2.0+, e Flax. Segui le istruzioni di installazione seguenti per la libreria di deep learning che stai utilizzando:
+
+* [PyTorch](https://pytorch.org/get-started/locally/) istruzioni di installazione.
+* [TensorFlow 2.0](https://www.tensorflow.org/install/pip) istruzioni di installazione.
+* [Flax](https://flax.readthedocs.io/en/latest/) istruzioni di installazione.
+
+## Installazione con pip
+
+Puoi installare đ€ Transformers in un [ambiente virtuale](https://docs.python.org/3/library/venv.html). Se non sei familiare con gli ambienti virtuali in Python, dai un'occhiata a questa [guida](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/). Un ambiente virtuale rende piĂč semplice la gestione di progetti differenti, evitando problemi di compatibilitĂ tra dipendenze.
+
+Inizia creando un ambiente virtuale nella directory del tuo progetto:
+
+```bash
+python -m venv .env
+```
+
+Attiva l'ambiente virtuale:
+
+```bash
+source .env/bin/activate
+```
+
+Ora puoi procedere con l'installazione di đ€ Transformers eseguendo il comando seguente:
+
+```bash
+pip install transformers
+```
+
+Per il solo supporto della CPU, puoi installare facilmente đ€ Transformers e una libreria di deep learning in solo una riga. Ad esempio, installiamo đ€ Transformers e PyTorch con:
+
+```bash
+pip install transformers[torch]
+```
+
+đ€ Transformers e TensorFlow 2.0:
+
+```bash
+pip install transformers[tf-cpu]
+```
+
+đ€ Transformers e Flax:
+
+```bash
+pip install transformers[flax]
+```
+
+Infine, verifica se đ€ Transformers Ăš stato installato in modo appropriato eseguendo il seguente comando. Questo scaricherĂ un modello pre-allenato:
+
+```bash
+python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('we love you'))"
+```
+
+Dopodiché stampa l'etichetta e il punteggio:
+
+```bash
+[{'label': 'POSITIVE', 'score': 0.9998704791069031}]
+```
+
+## Installazione dalla fonte
+
+Installa đ€ Transformers dalla fonte con il seguente comando:
+
+```bash
+pip install git+https://github.com/huggingface/transformers
+```
+
+Questo comando installa la versione `main` piĂč attuale invece dell'ultima versione stabile. Questo Ăš utile per stare al passo con gli ultimi sviluppi. Ad esempio, se un bug Ăš stato sistemato da quando Ăš uscita l'ultima versione ufficiale ma non Ăš stata ancora rilasciata una nuova versione. Tuttavia, questo significa che questa versione `main` puĂČ non essere sempre stabile. Ci sforziamo per mantenere la versione `main` operativa, e la maggior parte dei problemi viene risolta in poche ore o in un giorno. Se riscontri un problema, per favore apri una [Issue](https://github.com/huggingface/transformers/issues) cosĂŹ possiamo sistemarlo ancora piĂč velocemente!
+
+Controlla se đ€ Transformers Ăš stata installata in modo appropriato con il seguente comando:
+
+```bash
+python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('I love you'))"
+```
+
+## Installazione modificabile
+
+Hai bisogno di un'installazione modificabile se vuoi:
+
+* Usare la versione `main` del codice dalla fonte.
+* Contribuire a đ€ Transformers e hai bisogno di testare i cambiamenti nel codice.
+
+Clona il repository e installa đ€ Transformers con i seguenti comandi:
+
+```bash
+git clone https://github.com/huggingface/transformers.git
+cd transformers
+pip install -e .
+```
+
+Questi comandi collegheranno la cartella in cui Ăš stato clonato il repository e i path delle librerie Python. Python guarderĂ ora all'interno della cartella clonata, oltre ai normali path delle librerie. Per esempio, se i tuoi pacchetti Python sono installati tipicamente in `~/anaconda3/envs/main/lib/python3.7/site-packages/`, Python cercherĂ anche nella cartella clonata: `~/transformers/`.
+
+
+
+Devi tenere la cartella `transformers` se vuoi continuare ad utilizzare la libreria.
+
+
+
+Ora puoi facilmente aggiornare il tuo clone all'ultima versione di đ€ Transformers con il seguente comando:
+
+```bash
+cd ~/transformers/
+git pull
+```
+
+Il tuo ambiente Python troverĂ la versione `main` di đ€ Transformers alla prossima esecuzione.
+
+## Installazione con conda
+
+Installazione dal canale conda `huggingface`:
+
+```bash
+conda install -c huggingface transformers
+```
+
+## Impostazione della cache
+
+I modelli pre-allenati sono scaricati e memorizzati localmente nella cache in: `~/.cache/huggingface/transformers/`. Questa Ăš la directory di default data dalla variabile d'ambiente della shell `TRANSFORMERS_CACHE`. Su Windows, la directory di default Ăš data da `C:\Users\username\.cache\huggingface\transformers`. Puoi cambiare le variabili d'ambiente della shell indicate in seguito, in ordine di prioritĂ , per specificare una directory differente per la cache:
+
+1. Variabile d'ambiente della shell (default): `TRANSFORMERS_CACHE`.
+2. Variabile d'ambiente della shell: `HF_HOME` + `transformers/`.
+3. Variabile d'ambiente della shell: `XDG_CACHE_HOME` + `/huggingface/transformers`.
+
+
+
+đ€ Transformers utilizzerĂ le variabili d'ambiente della shell `PYTORCH_TRANSFORMERS_CACHE` o `PYTORCH_PRETRAINED_BERT_CACHE` se si proviene da un'iterazione precedente di questa libreria e sono state impostate queste variabili d'ambiente, a meno che non si specifichi la variabile d'ambiente della shell `TRANSFORMERS_CACHE`.
+
+
+
+## ModalitĂ Offline
+
+đ€ Transformers puĂČ essere eseguita in un ambiente firewalled o offline utilizzando solo file locali. Imposta la variabile d'ambiente `TRANSFORMERS_OFFLINE=1` per abilitare questo comportamento.
+
+
+
+Aggiungi [đ€ Datasets](https://huggingface.co/docs/datasets/) al tuo flusso di lavoro offline di training impostando la variabile d'ambiente `HF_DATASETS_OFFLINE=1`.
+
+
+
+Ad esempio, in genere si esegue un programma su una rete normale, protetta da firewall per le istanze esterne, con il seguente comando:
+
+```bash
+python examples/pytorch/translation/run_translation.py --model_name_or_path t5-small --dataset_name wmt16 --dataset_config ro-en ...
+```
+
+Esegui lo stesso programma in un'istanza offline con:
+
+```bash
+HF_DATASETS_OFFLINE=1 TRANSFORMERS_OFFLINE=1 \
+python examples/pytorch/translation/run_translation.py --model_name_or_path t5-small --dataset_name wmt16 --dataset_config ro-en ...
+```
+
+Lo script viene ora eseguito senza bloccarsi o attendere il timeout, perché sa di dover cercare solo file locali.
+
+### Ottenere modelli e tokenizer per l'uso offline
+
+Un'altra opzione per utilizzare offline đ€ Transformers Ăš scaricare i file in anticipo, e poi puntare al loro path locale quando hai la necessitĂ di utilizzarli offline. Ci sono tre modi per fare questo:
+
+* Scarica un file tramite l'interfaccia utente sul [Model Hub](https://huggingface.co/models) premendo sull'icona â.
+
+ 
+
+* Utilizza il flusso [`PreTrainedModel.from_pretrained`] e [`PreTrainedModel.save_pretrained`]:
+
+ 1. Scarica i tuoi file in anticipo con [`PreTrainedModel.from_pretrained`]:
+
+ ```py
+ >>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("bigscience/T0_3B")
+ >>> model = AutoModelForSeq2SeqLM.from_pretrained("bigscience/T0_3B")
+ ```
+
+ 2. Salva i tuoi file in una directory specificata con [`PreTrainedModel.save_pretrained`]:
+
+ ```py
+ >>> tokenizer.save_pretrained("./il/tuo/path/bigscience_t0")
+ >>> model.save_pretrained("./il/tuo/path/bigscience_t0")
+ ```
+
+ 3. Ora quando sei offline, carica i tuoi file con [`PreTrainedModel.from_pretrained`] dalla directory specificata:
+
+ ```py
+ >>> tokenizer = AutoTokenizer.from_pretrained("./il/tuo/path/bigscience_t0")
+ >>> model = AutoModel.from_pretrained("./il/tuo/path/bigscience_t0")
+ ```
+
+* Scarica in maniera programmatica i file con la libreria [huggingface_hub](https://github.com/huggingface/huggingface_hub/tree/main/src/huggingface_hub):
+
+ 1. Installa la libreria `huggingface_hub` nel tuo ambiente virtuale:
+
+ ```bash
+ python -m pip install huggingface_hub
+ ```
+
+ 2. Utilizza la funzione [`hf_hub_download`](https://huggingface.co/docs/hub/adding-a-library#download-files-from-the-hub) per scaricare un file in un path specifico. Per esempio, il seguente comando scarica il file `config.json` dal modello [T0](https://huggingface.co/bigscience/T0_3B) nel path che desideri:
+
+ ```py
+ >>> from huggingface_hub import hf_hub_download
+
+ >>> hf_hub_download(repo_id="bigscience/T0_3B", filename="config.json", cache_dir="./il/tuo/path/bigscience_t0")
+ ```
+
+Una volta che il tuo file Ăš scaricato e salvato in cache localmente, specifica il suo path locale per caricarlo e utilizzarlo:
+
+```py
+>>> from transformers import AutoConfig
+
+>>> config = AutoConfig.from_pretrained("./il/tuo/path/bigscience_t0/config.json")
+```
+
+
+
+Fai riferimento alla sezione [How to download files from the Hub](https://huggingface.co/docs/hub/how-to-downstream) per avere maggiori dettagli su come scaricare modelli presenti sull Hub.
+
+
\ No newline at end of file
diff --git a/docs/source/it/installation.mdx b/docs/source/it/installation.mdx
deleted file mode 100644
index 1ff47c110cff..000000000000
--- a/docs/source/it/installation.mdx
+++ /dev/null
@@ -1,235 +0,0 @@
-
-
-# Installazione
-
-Installa đ€ Transformers per qualsiasi libreria di deep learning con cui stai lavorando, imposta la tua cache, e opzionalmente configura đ€ Transformers per l'esecuzione offline.
-
-đ€ Transformers Ăš testato su Python 3.6+, PyTorch 1.1.0+, TensorFlow 2.0+, e Flax. Segui le istruzioni di installazione seguenti per la libreria di deep learning che stai utilizzando:
-
-* [PyTorch](https://pytorch.org/get-started/locally/) istruzioni di installazione.
-* [TensorFlow 2.0](https://www.tensorflow.org/install/pip) istruzioni di installazione.
-* [Flax](https://flax.readthedocs.io/en/latest/) istruzioni di installazione.
-
-## Installazione con pip
-
-Puoi installare đ€ Transformers in un [ambiente virtuale](https://docs.python.org/3/library/venv.html). Se non sei familiare con gli ambienti virtuali in Python, dai un'occhiata a questa [guida](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/). Un ambiente virtuale rende piĂč semplice la gestione di progetti differenti, evitando problemi di compatibilitĂ tra dipendenze.
-
-Inizia creando un ambiente virtuale nella directory del tuo progetto:
-
-```bash
-python -m venv .env
-```
-
-Attiva l'ambiente virtuale:
-
-```bash
-source .env/bin/activate
-```
-
-Ora puoi procedere con l'installazione di đ€ Transformers eseguendo il comando seguente:
-
-```bash
-pip install transformers
-```
-
-Per il solo supporto della CPU, puoi installare facilmente đ€ Transformers e una libreria di deep learning in solo una riga. Ad esempio, installiamo đ€ Transformers e PyTorch con:
-
-```bash
-pip install transformers[torch]
-```
-
-đ€ Transformers e TensorFlow 2.0:
-
-```bash
-pip install transformers[tf-cpu]
-```
-
-đ€ Transformers e Flax:
-
-```bash
-pip install transformers[flax]
-```
-
-Infine, verifica se đ€ Transformers Ăš stato installato in modo appropriato eseguendo il seguente comando. Questo scaricherĂ un modello pre-allenato:
-
-```bash
-python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('we love you'))"
-```
-
-Dopodiché stampa l'etichetta e il punteggio:
-
-```bash
-[{'label': 'POSITIVE', 'score': 0.9998704791069031}]
-```
-
-## Installazione dalla fonte
-
-Installa đ€ Transformers dalla fonte con il seguente comando:
-
-```bash
-pip install git+https://github.com/huggingface/transformers
-```
-
-Questo comando installa la versione `main` piĂč attuale invece dell'ultima versione stabile. Questo Ăš utile per stare al passo con gli ultimi sviluppi. Ad esempio, se un bug Ăš stato sistemato da quando Ăš uscita l'ultima versione ufficiale ma non Ăš stata ancora rilasciata una nuova versione. Tuttavia, questo significa che questa versione `main` puĂČ non essere sempre stabile. Ci sforziamo per mantenere la versione `main` operativa, e la maggior parte dei problemi viene risolta in poche ore o in un giorno. Se riscontri un problema, per favore apri una [Issue](https://github.com/huggingface/transformers/issues) cosĂŹ possiamo sistemarlo ancora piĂč velocemente!
-
-Controlla se đ€ Transformers Ăš stata installata in modo appropriato con il seguente comando:
-
-```bash
-python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('I love you'))"
-```
-
-## Installazione modificabile
-
-Hai bisogno di un'installazione modificabile se vuoi:
-
-* Usare la versione `main` del codice dalla fonte.
-* Contribuire a đ€ Transformers e hai bisogno di testare i cambiamenti nel codice.
-
-Clona il repository e installa đ€ Transformers con i seguenti comandi:
-
-```bash
-git clone https://github.com/huggingface/transformers.git
-cd transformers
-pip install -e .
-```
-
-Questi comandi collegheranno la cartella in cui Ăš stato clonato il repository e i path delle librerie Python. Python guarderĂ ora all'interno della cartella clonata, oltre ai normali path delle librerie. Per esempio, se i tuoi pacchetti Python sono installati tipicamente in `~/anaconda3/envs/main/lib/python3.7/site-packages/`, Python cercherĂ anche nella cartella clonata: `~/transformers/`.
-
-
-
-Devi tenere la cartella `transformers` se vuoi continuare ad utilizzare la libreria.
-
-
-
-Ora puoi facilmente aggiornare il tuo clone all'ultima versione di đ€ Transformers con il seguente comando:
-
-```bash
-cd ~/transformers/
-git pull
-```
-
-Il tuo ambiente Python troverĂ la versione `main` di đ€ Transformers alla prossima esecuzione.
-
-## Installazione con conda
-
-Installazione dal canale conda `huggingface`:
-
-```bash
-conda install -c huggingface transformers
-```
-
-## Impostazione della cache
-
-I modelli pre-allenati sono scaricati e memorizzati localmente nella cache in: `~/.cache/huggingface/transformers/`. Questa Ăš la directory di default data dalla variabile d'ambiente della shell `TRANSFORMERS_CACHE`. Su Windows, la directory di default Ăš data da `C:\Users\username\.cache\huggingface\transformers`. Puoi cambiare le variabili d'ambiente della shell indicate in seguito, in ordine di prioritĂ , per specificare una directory differente per la cache:
-
-1. Variabile d'ambiente della shell (default): `TRANSFORMERS_CACHE`.
-2. Variabile d'ambiente della shell: `HF_HOME` + `transformers/`.
-3. Variabile d'ambiente della shell: `XDG_CACHE_HOME` + `/huggingface/transformers`.
-
-
-
-đ€ Transformers utilizzerĂ le variabili d'ambiente della shell `PYTORCH_TRANSFORMERS_CACHE` o `PYTORCH_PRETRAINED_BERT_CACHE` se si proviene da un'iterazione precedente di questa libreria e sono state impostate queste variabili d'ambiente, a meno che non si specifichi la variabile d'ambiente della shell `TRANSFORMERS_CACHE`.
-
-
-
-## ModalitĂ Offline
-
-đ€ Transformers puĂČ essere eseguita in un ambiente firewalled o offline utilizzando solo file locali. Imposta la variabile d'ambiente `TRANSFORMERS_OFFLINE=1` per abilitare questo comportamento.
-
-
-
-Aggiungi [đ€ Datasets](https://huggingface.co/docs/datasets/) al tuo flusso di lavoro offline di training impostando la variabile d'ambiente `HF_DATASETS_OFFLINE=1`.
-
-
-
-Ad esempio, in genere si esegue un programma su una rete normale, protetta da firewall per le istanze esterne, con il seguente comando:
-
-```bash
-python examples/pytorch/translation/run_translation.py --model_name_or_path t5-small --dataset_name wmt16 --dataset_config ro-en ...
-```
-
-Esegui lo stesso programma in un'istanza offline con:
-
-```bash
-HF_DATASETS_OFFLINE=1 TRANSFORMERS_OFFLINE=1 \
-python examples/pytorch/translation/run_translation.py --model_name_or_path t5-small --dataset_name wmt16 --dataset_config ro-en ...
-```
-
-Lo script viene ora eseguito senza bloccarsi o attendere il timeout, perché sa di dover cercare solo file locali.
-
-### Ottenere modelli e tokenizer per l'uso offline
-
-Un'altra opzione per utilizzare offline đ€ Transformers Ăš scaricare i file in anticipo, e poi puntare al loro path locale quando hai la necessitĂ di utilizzarli offline. Ci sono tre modi per fare questo:
-
-* Scarica un file tramite l'interfaccia utente sul [Model Hub](https://huggingface.co/models) premendo sull'icona â.
-
- 
-
-* Utilizza il flusso [`PreTrainedModel.from_pretrained`] e [`PreTrainedModel.save_pretrained`]:
-
- 1. Scarica i tuoi file in anticipo con [`PreTrainedModel.from_pretrained`]:
-
- ```py
- >>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
-
- >>> tokenizer = AutoTokenizer.from_pretrained("bigscience/T0_3B")
- >>> model = AutoModelForSeq2SeqLM.from_pretrained("bigscience/T0_3B")
- ```
-
- 2. Salva i tuoi file in una directory specificata con [`PreTrainedModel.save_pretrained`]:
-
- ```py
- >>> tokenizer.save_pretrained("./il/tuo/path/bigscience_t0")
- >>> model.save_pretrained("./il/tuo/path/bigscience_t0")
- ```
-
- 3. Ora quando sei offline, carica i tuoi file con [`PreTrainedModel.from_pretrained`] dalla directory specificata:
-
- ```py
- >>> tokenizer = AutoTokenizer.from_pretrained("./il/tuo/path/bigscience_t0")
- >>> model = AutoModel.from_pretrained("./il/tuo/path/bigscience_t0")
- ```
-
-* Scarica in maniera programmatica i file con la libreria [huggingface_hub](https://github.com/huggingface/huggingface_hub/tree/main/src/huggingface_hub):
-
- 1. Installa la libreria `huggingface_hub` nel tuo ambiente virtuale:
-
- ```bash
- python -m pip install huggingface_hub
- ```
-
- 2. Utilizza la funzione [`hf_hub_download`](https://huggingface.co/docs/hub/adding-a-library#download-files-from-the-hub) per scaricare un file in un path specifico. Per esempio, il seguente comando scarica il file `config.json` dal modello [T0](https://huggingface.co/bigscience/T0_3B) nel path che desideri:
-
- ```py
- >>> from huggingface_hub import hf_hub_download
-
- >>> hf_hub_download(repo_id="bigscience/T0_3B", filename="config.json", cache_dir="./il/tuo/path/bigscience_t0")
- ```
-
-Una volta che il tuo file Ăš scaricato e salvato in cache localmente, specifica il suo path locale per caricarlo e utilizzarlo:
-
-```py
->>> from transformers import AutoConfig
-
->>> config = AutoConfig.from_pretrained("./il/tuo/path/bigscience_t0/config.json")
-```
-
-
-
-Fai riferimento alla sezione [How to download files from the Hub](https://huggingface.co/docs/hub/how-to-downstream) per avere maggiori dettagli su come scaricare modelli presenti sull Hub.
-
-
\ No newline at end of file
diff --git a/docs/source/it/migration.md b/docs/source/it/migration.md
new file mode 100644
index 000000000000..3b3b71da4d49
--- /dev/null
+++ b/docs/source/it/migration.md
@@ -0,0 +1,320 @@
+
+
+# Migrazione da pacchetti precedenti
+
+## Migrazione da transformers `v3.x` a `v4.x`
+
+Un paio di modifiche sono state introdotte nel passaggio dalla versione 3 alla versione 4. Di seguito Ăš riportato un riepilogo delle
+modifiche previste:
+
+#### 1. AutoTokenizer e pipeline ora utilizzano tokenizer veloci (rust) per impostazione predefinita.
+
+I tokenizer python e rust hanno all'incirca le stesse API, ma i tokenizer rust hanno un set di funzionalitĂ piĂč completo.
+
+CiĂČ introduce due modifiche sostanziali:
+- La gestione dei token in overflow tra i tokenizer Python e Rust Ăš diversa.
+- I tokenizers di rust non accettano numeri interi nei metodi di codifica.
+
+##### Come ottenere lo stesso comportamento di v3.x in v4.x
+
+- Le pipeline ora contengono funzionalitĂ aggiuntive pronte all'uso. Vedi la [pipeline di classificazione dei token con il flag `grouped_entities`](main_classes/pipelines#transformers.TokenClassificationPipeline).
+- Gli auto-tokenizer ora restituiscono tokenizer rust. Per ottenere invece i tokenizer python, l'utente deve usare il flag `use_fast` impostandolo `False`:
+
+Nella versione `v3.x`:
+```py
+from transformers import AutoTokenizer
+
+tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
+```
+per ottenere lo stesso nella versione `v4.x`:
+```py
+from transformers import AutoTokenizer
+
+tokenizer = AutoTokenizer.from_pretrained("bert-base-cased", use_fast=False)
+```
+
+#### 2. SentencePiece Ăš stato rimosso dalle dipendenze richieste
+
+Il requisito sulla dipendenza SentencePiece Ăš stato rimosso da `setup.py`. Ă stato fatto per avere un canale su anaconda cloud senza basarsi su `conda-forge`. CiĂČ significa che i tokenizer che dipendono dalla libreria SentencePiece non saranno disponibili con un'installazione standard di `transformers`.
+
+CiĂČ include le versioni **lente** di:
+- `XLNetTokenizer`
+- `AlbertTokenizer`
+- `CamembertTokenizer`
+- `MBartTokenizer`
+- `PegasusTokenizer`
+- `T5Tokenizer`
+- `ReformerTokenizer`
+- `XLMRobertaTokenizer`
+
+##### Come ottenere lo stesso comportamento della v3.x nella v4.x
+
+Per ottenere lo stesso comportamento della versione `v3.x`, devi installare anche `sentencepiece`:
+
+Nella versione `v3.x`:
+```bash
+pip install transformers
+```
+per ottenere lo stesso nella versione `v4.x`:
+```bash
+pip install transformers[sentencepiece]
+```
+o
+```bash
+pip install transformers stentencepiece
+```
+#### 3. L'architettura delle repo Ăš stato aggiornata in modo che ogni modello abbia la propria cartella
+
+Con lâaggiunta di nuovi modelli, il numero di file nella cartella `src/transformers` continua a crescere e diventa piĂč difficile navigare e capire. Abbiamo fatto la scelta di inserire ogni modello e i file che lo accompagnano nelle proprie sottocartelle.
+
+Si tratta di una modifica sostanziale in quanto l'importazione di layer intermedi utilizzando direttamente il modulo di un modello deve essere eseguita tramite un percorso diverso.
+
+##### Come ottenere lo stesso comportamento della v3.x nella v4.x
+
+Per ottenere lo stesso comportamento della versione `v3.x`, devi aggiornare il percorso utilizzato per accedere ai layer.
+
+Nella versione `v3.x`:
+```bash
+from transformers.modeling_bert import BertLayer
+```
+per ottenere lo stesso nella versione `v4.x`:
+```bash
+from transformers.models.bert.modeling_bert import BertLayer
+```
+
+#### 4. Impostare l'argomento `return_dict` su `True` per impostazione predefinita
+
+L'[argomento `return_dict`](main_classes/output) abilita la restituzione di oggetti python dict-like contenenti gli output del modello, invece delle tuple standard. Questo oggetto Ú self-documented poiché le chiavi possono essere utilizzate per recuperare valori, comportandosi anche come una tupla e gli utenti possono recuperare oggetti per indexing o slicing.
+
+Questa Ăš una modifica sostanziale poichĂ© la tupla non puĂČ essere decompressa: `value0, value1 = outputs` non funzionerĂ .
+
+##### Come ottenere lo stesso comportamento della v3.x nella v4.x
+
+Per ottenere lo stesso comportamento della versione `v3.x`, specifica l'argomento `return_dict` come `False`, sia nella configurazione del modello che nel passaggio successivo.
+
+Nella versione `v3.x`:
+```bash
+model = BertModel.from_pretrained("bert-base-cased")
+outputs = model(**inputs)
+```
+per ottenere lo stesso nella versione `v4.x`:
+```bash
+model = BertModel.from_pretrained("bert-base-cased")
+outputs = model(**inputs, return_dict=False)
+```
+o
+```bash
+model = BertModel.from_pretrained("bert-base-cased", return_dict=False)
+outputs = model(**inputs)
+```
+
+#### 5. Rimozione di alcuni attributi deprecati
+
+Gli attributi sono stati rimossi se deprecati da almeno un mese. L'elenco completo degli attributi obsoleti Ăš disponibile in [#8604](https://github.com/huggingface/transformers/pull/8604).
+
+Ecco un elenco di questi attributi/metodi/argomenti e quali dovrebbero essere le loro sostituzioni:
+
+In diversi modelli, le etichette diventano coerenti con gli altri modelli:
+- `masked_lm_labels` diventa `labels` in `AlbertForMaskedLM` e `AlbertForPreTraining`.
+- `masked_lm_labels` diventa `labels` in `BertForMaskedLM` e `BertForPreTraining`.
+- `masked_lm_labels` diventa `labels` in `DistilBertForMaskedLM`.
+- `masked_lm_labels` diventa `labels` in `ElectraForMaskedLM`.
+- `masked_lm_labels` diventa `labels` in `LongformerForMaskedLM`.
+- `masked_lm_labels` diventa `labels` in `MobileBertForMaskedLM`.
+- `masked_lm_labels` diventa `labels` in `RobertaForMaskedLM`.
+- `lm_labels` diventa `labels` in `BartForConditionalGeneration`.
+- `lm_labels` diventa `labels` in `GPT2DoubleHeadsModel`.
+- `lm_labels` diventa `labels` in `OpenAIGPTDoubleHeadsModel`.
+- `lm_labels` diventa `labels` in `T5ForConditionalGeneration`.
+
+In diversi modelli, il meccanismo di memorizzazione nella cache diventa coerente con gli altri:
+- `decoder_cached_states` diventa `past_key_values` in tutti i modelli BART-like, FSMT e T5.
+- `decoder_past_key_values` diventa `past_key_values` in tutti i modelli BART-like, FSMT e T5.
+- `past` diventa `past_key_values` in tutti i modelli CTRL.
+- `past` diventa `past_key_values` in tutti i modelli GPT-2.
+
+Per quanto riguarda le classi tokenizer:
+- L'attributo tokenizer `max_len` diventa `model_max_length`.
+- L'attributo tokenizer `return_lengths` diventa `return_length`.
+- L'argomento di codifica del tokenizer `is_pretokenized` diventa `is_split_into_words`.
+
+Per quanto riguarda la classe `Trainer`:
+- L'argomento `tb_writer` di `Trainer` Ăš stato rimosso in favore della funzione richiamabile `TensorBoardCallback(tb_writer=...)`.
+- L'argomento `prediction_loss_only` di `Trainer` Ăš stato rimosso in favore dell'argomento di classe `args.prediction_loss_only`.
+- L'attributo `data_collator` di `Trainer` sarĂ richiamabile.
+- Il metodo `_log` di `Trainer` Ăš deprecato a favore di `log`.
+- Il metodo `_training_step` di `Trainer` Ăš deprecato a favore di `training_step`.
+- Il metodo `_prediction_loop` di `Trainer` Ăš deprecato a favore di `prediction_loop`.
+- Il metodo `is_local_master` di `Trainer` Ăš deprecato a favore di `is_local_process_zero`.
+- Il metodo `is_world_master` di `Trainer` Ăš deprecato a favore di `is_world_process_zero`.
+
+Per quanto riguarda la classe `TFTrainer`:
+- L'argomento `prediction_loss_only` di `TFTrainer` Ăš stato rimosso a favore dell'argomento di classe `args.prediction_loss_only`.
+- Il metodo `_log` di `Trainer` Ăš deprecato a favore di `log`.
+- Il metodo `_prediction_loop` di `TFTrainer` Ăš deprecato a favore di `prediction_loop`.
+- Il metodo `_setup_wandb` di `TFTrainer` Ăš deprecato a favore di `setup_wandb`.
+- Il metodo `_run_model` di `TFTrainer` Ăš deprecato a favore di `run_model`.
+
+Per quanto riguarda la classe `TrainingArguments`:
+- L'argomento `evaluate_during_training` di `TrainingArguments` Ăš deprecato a favore di `evaluation_strategy`.
+
+Per quanto riguarda il modello Transfo-XL:
+- L'attributo di configurazione `tie_weight` di Transfo-XL diventa `tie_words_embeddings`.
+- Il metodo di modellazione `reset_length` di Transfo-XL diventa `reset_memory_length`.
+
+Per quanto riguarda le pipeline:
+- L'argomento `topk` di `FillMaskPipeline` diventa `top_k`.
+
+
+
+## Passaggio da pytorch-transformers a đ€ Transformers
+
+Ecco un breve riepilogo di ciĂČ a cui prestare attenzione durante il passaggio da `pytorch-transformers` a đ€ Transformers.
+
+### Lâordine posizionale di alcune parole chiave di input dei modelli (`attention_mask`, `token_type_ids`...) Ăš cambiato
+
+Per usare Torchscript (vedi #1010, #1204 e #1195) l'ordine specifico delle **parole chiave di input** di alcuni modelli (`attention_mask`, `token_type_ids`...) Ăš stato modificato.
+
+Se inizializzavi i modelli usando parole chiave per gli argomenti, ad esempio `model(inputs_ids, attention_mask=attention_mask, token_type_ids=token_type_ids)`, questo non dovrebbe causare alcun cambiamento.
+
+Se inizializzavi i modelli con input posizionali per gli argomenti, ad esempio `model(inputs_ids, attention_mask, token_type_ids)`, potrebbe essere necessario ricontrollare l'ordine esatto degli argomenti di input.
+
+## Migrazione da pytorch-pretrained-bert
+
+Ecco un breve riepilogo di ciĂČ a cui prestare attenzione durante la migrazione da `pytorch-pretrained-bert` a đ€ Transformers
+
+### I modelli restituiscono sempre `tuple`
+
+La principale modifica di rilievo durante la migrazione da `pytorch-pretrained-bert` a đ€ Transformers Ăš che il metodo dei modelli di previsione dĂ sempre una `tupla` con vari elementi a seconda del modello e dei parametri di configurazione.
+
+Il contenuto esatto delle tuple per ciascun modello Ăš mostrato in dettaglio nelle docstring dei modelli e nella [documentazione](https://huggingface.co/transformers/).
+
+In quasi tutti i casi, andrĂ bene prendendo il primo elemento dell'output come quello che avresti precedentemente utilizzato in `pytorch-pretrained-bert`.
+
+Ecco un esempio di conversione da `pytorch-pretrained-bert`
+ a đ€ Transformers per un modello di classificazione `BertForSequenceClassification`:
+
+```python
+# Carichiamo il nostro modello
+model = BertForSequenceClassification.from_pretrained("bert-base-uncased")
+
+# Se usavi questa riga in pytorch-pretrained-bert :
+loss = model(input_ids, labels=labels)
+
+# Ora usa questa riga in đ€ Transformers per estrarre la perdita dalla tupla di output:
+outputs = model(input_ids, labels=labels)
+loss = outputs[0]
+
+# In đ€ Transformers puoi anche avere accesso ai logit:
+loss, logits = outputs[:2]
+
+# Ed anche agli attention weight se configuri il modello per restituirli (e anche altri output, vedi le docstring e la documentazione)
+model = BertForSequenceClassification.from_pretrained(" bert-base-uncased", output_attentions=True)
+outputs = model(input_ids, labels=labels)
+loss, logits, attentions = outputs
+```
+
+### Serializzazione
+
+Modifica sostanziale nel metodo `from_pretrained()`:
+
+1. I modelli sono ora impostati in modalitĂ di valutazione in maniera predefinita quando usi il metodo `from_pretrained()`. Per addestrarli non dimenticare di riportarli in modalitĂ di addestramento (`model.train()`) per attivare i moduli di dropout.
+
+2. Gli argomenti aggiuntivi `*inputs` e `**kwargs` forniti al metodo `from_pretrained()` venivano passati direttamente al metodo `__init__()` della classe sottostante del modello. Ora sono usati per aggiornare prima l'attributo di configurazione del modello, che puĂČ non funzionare con le classi del modello derivate costruite basandosi sui precedenti esempi di `BertForSequenceClassification`. PiĂč precisamente, gli argomenti posizionali `*inputs` forniti a `from_pretrained()` vengono inoltrati direttamente al metodo `__init__()` del modello mentre gli argomenti keyword `**kwargs` (i) che corrispondono agli attributi della classe di configurazione, vengono utilizzati per aggiornare tali attributi (ii) che non corrispondono ad alcun attributo della classe di configurazione, vengono inoltrati al metodo `__init__()`.
+
+Inoltre, sebbene non si tratti di una modifica sostanziale, i metodi di serializzazione sono stati standardizzati e probabilmente dovresti passare al nuovo metodo `save_pretrained(save_directory)` se prima usavi qualsiasi altro metodo di serializzazione.
+
+Ecco un esempio:
+
+```python
+### Carichiamo un modello e un tokenizer
+model = BertForSequenceClassification.from_pretrained("bert-base-uncased")
+tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
+
+### Facciamo fare alcune cose al nostro modello e tokenizer
+# Es: aggiungiamo nuovi token al vocabolario e agli embending del nostro modello
+tokenizer.add_tokens(["[SPECIAL_TOKEN_1]", "[SPECIAL_TOKEN_2]"])
+model.resize_token_embeddings(len(tokenizer))
+# Alleniamo il nostro modello
+train(model)
+
+### Ora salviamo il nostro modello e il tokenizer in una cartella
+model.save_pretrained("./my_saved_model_directory/")
+tokenizer.save_pretrained("./my_saved_model_directory/")
+
+### Ricarichiamo il modello e il tokenizer
+model = BertForSequenceClassification.from_pretrained("./my_saved_model_directory/")
+tokenizer = BertTokenizer.from_pretrained("./my_saved_model_directory/")
+```
+
+### Ottimizzatori: BertAdam e OpenAIAdam ora sono AdamW, lo scheduling Ăš quello standard PyTorch
+
+I due ottimizzatori precedenti inclusi, `BertAdam` e `OpenAIAdam`, sono stati sostituiti da un singolo `AdamW` che presenta alcune differenze:
+
+- implementa solo la correzione del weights decay,
+- lo scheduling ora Ăš esterno (vedi sotto),
+- anche il gradient clipping ora Ăš esterno (vedi sotto).
+
+Il nuovo ottimizzatore `AdamW` corrisponde alle API di `Adam` di PyTorch e ti consente di utilizzare metodi PyTorch o apex per lo scheduling e il clipping.
+
+Lo scheduling Ăš ora standard [PyTorch learning rate schedulers](https://pytorch.org/docs/stable/optim.html#how-to-adjust-learning-rate) e non fanno piĂč parte dell'ottimizzatore.
+
+Ecco un esempio di linear warmup e decay con `BertAdam` e con `AdamW`:
+
+```python
+# Parametri:
+lr = 1e-3
+max_grad_norm = 1.0
+num_training_steps = 1000
+num_warmup_steps = 100
+warmup_proportion = float( num_warmup_steps) / float(num_training_steps) # 0.1
+
+### In precedenza l'ottimizzatore BertAdam veniva istanziato in questo modo:
+optimizer = BertAdam(
+ model.parameters(),
+ lr=lr,
+ schedule="warmup_linear",
+ warmup=warmup_proportion,
+ num_training_steps=num_training_steps,
+)
+### e usato in questo modo:
+for batch in train_data:
+ loss = model(batch)
+ loss.backward()
+ optimizer.step()
+
+### In đ€ Transformers, ottimizzatore e schedule sono divisi e usati in questo modo:
+optimizer = AdamW(
+ model.parameters(), lr=lr, correct_bias=False
+) # Per riprodurre il comportamento specifico di BertAdam impostare correct_bias=False
+scheduler = get_linear_schedule_with_warmup(
+ optimizer, num_warmup_steps=num_warmup_steps, num_training_steps=num_training_steps
+) # PyTorch scheduler
+### e va usato cosĂŹ:
+for batch in train_data:
+ loss = model(batch)
+ loss.backward()
+ torch.nn.utils.clip_grad_norm_(
+ model.parameters(), max_grad_norm
+ ) # Gradient clipping non Ăš piĂč in AdamW (quindi puoi usare amp senza problemi)
+ optimizer.step()
+ scheduler.step()
+```
diff --git a/docs/source/it/migration.mdx b/docs/source/it/migration.mdx
deleted file mode 100644
index 92622787c6e9..000000000000
--- a/docs/source/it/migration.mdx
+++ /dev/null
@@ -1,316 +0,0 @@
-
-
-# Migrazione da pacchetti precedenti
-
-## Migrazione da transformers `v3.x` a `v4.x`
-
-Un paio di modifiche sono state introdotte nel passaggio dalla versione 3 alla versione 4. Di seguito Ăš riportato un riepilogo delle
-modifiche previste:
-
-#### 1. AutoTokenizer e pipeline ora utilizzano tokenizer veloci (rust) per impostazione predefinita.
-
-I tokenizer python e rust hanno all'incirca le stesse API, ma i tokenizer rust hanno un set di funzionalitĂ piĂč completo.
-
-CiĂČ introduce due modifiche sostanziali:
-- La gestione dei token in overflow tra i tokenizer Python e Rust Ăš diversa.
-- I tokenizers di rust non accettano numeri interi nei metodi di codifica.
-
-##### Come ottenere lo stesso comportamento di v3.x in v4.x
-
-- Le pipeline ora contengono funzionalitĂ aggiuntive pronte all'uso. Vedi la [pipeline di classificazione dei token con il flag `grouped_entities`](main_classes/pipelines#transformers.TokenClassificationPipeline).
-- Gli auto-tokenizer ora restituiscono tokenizer rust. Per ottenere invece i tokenizer python, l'utente deve usare il flag `use_fast` impostandolo `False`:
-
-Nella versione `v3.x`:
-```py
-from transformers import AutoTokenizer
-
-tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
-```
-per ottenere lo stesso nella versione `v4.x`:
-```py
-from transformers import AutoTokenizer
-
-tokenizer = AutoTokenizer.from_pretrained("bert-base-cased", use_fast=False)
-```
-
-#### 2. SentencePiece Ăš stato rimosso dalle dipendenze richieste
-
-Il requisito sulla dipendenza SentencePiece Ăš stato rimosso da `setup.py`. Ă stato fatto per avere un canale su anaconda cloud senza basarsi su `conda-forge`. CiĂČ significa che i tokenizer che dipendono dalla libreria SentencePiece non saranno disponibili con un'installazione standard di `transformers`.
-
-CiĂČ include le versioni **lente** di:
-- `XLNetTokenizer`
-- `AlbertTokenizer`
-- `CamembertTokenizer`
-- `MBartTokenizer`
-- `PegasusTokenizer`
-- `T5Tokenizer`
-- `ReformerTokenizer`
-- `XLMRobertaTokenizer`
-
-##### Come ottenere lo stesso comportamento della v3.x nella v4.x
-
-Per ottenere lo stesso comportamento della versione `v3.x`, devi installare anche `sentencepiece`:
-
-Nella versione `v3.x`:
-```bash
-pip install transformers
-```
-per ottenere lo stesso nella versione `v4.x`:
-```bash
-pip install transformers[sentencepiece]
-```
-o
-```bash
-pip install transformers stentencepiece
-```
-#### 3. L'architettura delle repo Ăš stato aggiornata in modo che ogni modello abbia la propria cartella
-
-Con lâaggiunta di nuovi modelli, il numero di file nella cartella `src/transformers` continua a crescere e diventa piĂč difficile navigare e capire. Abbiamo fatto la scelta di inserire ogni modello e i file che lo accompagnano nelle proprie sottocartelle.
-
-Si tratta di una modifica sostanziale in quanto l'importazione di layer intermedi utilizzando direttamente il modulo di un modello deve essere eseguita tramite un percorso diverso.
-
-##### Come ottenere lo stesso comportamento della v3.x nella v4.x
-
-Per ottenere lo stesso comportamento della versione `v3.x`, devi aggiornare il percorso utilizzato per accedere ai layer.
-
-Nella versione `v3.x`:
-```bash
-from transformers.modeling_bert import BertLayer
-```
-per ottenere lo stesso nella versione `v4.x`:
-```bash
-from transformers.models.bert.modeling_bert import BertLayer
-```
-
-#### 4. Impostare l'argomento `return_dict` su `True` per impostazione predefinita
-
-L'[argomento `return_dict`](main_classes/output) abilita la restituzione di oggetti python dict-like contenenti gli output del modello, invece delle tuple standard. Questo oggetto Ú self-documented poiché le chiavi possono essere utilizzate per recuperare valori, comportandosi anche come una tupla e gli utenti possono recuperare oggetti per indexing o slicing.
-
-Questa Ăš una modifica sostanziale poichĂ© la tupla non puĂČ essere decompressa: `value0, value1 = outputs` non funzionerĂ .
-
-##### Come ottenere lo stesso comportamento della v3.x nella v4.x
-
-Per ottenere lo stesso comportamento della versione `v3.x`, specifica l'argomento `return_dict` come `False`, sia nella configurazione del modello che nel passaggio successivo.
-
-Nella versione `v3.x`:
-```bash
-model = BertModel.from_pretrained("bert-base-cased")
-outputs = model(**inputs)
-```
-per ottenere lo stesso nella versione `v4.x`:
-```bash
-model = BertModel.from_pretrained("bert-base-cased")
-outputs = model(**inputs, return_dict=False)
-```
-o
-```bash
-model = BertModel.from_pretrained("bert-base-cased", return_dict=False)
-outputs = model(**inputs)
-```
-
-#### 5. Rimozione di alcuni attributi deprecati
-
-Gli attributi sono stati rimossi se deprecati da almeno un mese. L'elenco completo degli attributi obsoleti Ăš disponibile in [#8604](https://github.com/huggingface/transformers/pull/8604).
-
-Ecco un elenco di questi attributi/metodi/argomenti e quali dovrebbero essere le loro sostituzioni:
-
-In diversi modelli, le etichette diventano coerenti con gli altri modelli:
-- `masked_lm_labels` diventa `labels` in `AlbertForMaskedLM` e `AlbertForPreTraining`.
-- `masked_lm_labels` diventa `labels` in `BertForMaskedLM` e `BertForPreTraining`.
-- `masked_lm_labels` diventa `labels` in `DistilBertForMaskedLM`.
-- `masked_lm_labels` diventa `labels` in `ElectraForMaskedLM`.
-- `masked_lm_labels` diventa `labels` in `LongformerForMaskedLM`.
-- `masked_lm_labels` diventa `labels` in `MobileBertForMaskedLM`.
-- `masked_lm_labels` diventa `labels` in `RobertaForMaskedLM`.
-- `lm_labels` diventa `labels` in `BartForConditionalGeneration`.
-- `lm_labels` diventa `labels` in `GPT2DoubleHeadsModel`.
-- `lm_labels` diventa `labels` in `OpenAIGPTDoubleHeadsModel`.
-- `lm_labels` diventa `labels` in `T5ForConditionalGeneration`.
-
-In diversi modelli, il meccanismo di memorizzazione nella cache diventa coerente con gli altri:
-- `decoder_cached_states` diventa `past_key_values` in tutti i modelli BART-like, FSMT e T5.
-- `decoder_past_key_values` diventa `past_key_values` in tutti i modelli BART-like, FSMT e T5.
-- `past` diventa `past_key_values` in tutti i modelli CTRL.
-- `past` diventa `past_key_values` in tutti i modelli GPT-2.
-
-Per quanto riguarda le classi tokenizer:
-- L'attributo tokenizer `max_len` diventa `model_max_length`.
-- L'attributo tokenizer `return_lengths` diventa `return_length`.
-- L'argomento di codifica del tokenizer `is_pretokenized` diventa `is_split_into_words`.
-
-Per quanto riguarda la classe `Trainer`:
-- L'argomento `tb_writer` di `Trainer` Ăš stato rimosso in favore della funzione richiamabile `TensorBoardCallback(tb_writer=...)`.
-- L'argomento `prediction_loss_only` di `Trainer` Ăš stato rimosso in favore dell'argomento di classe `args.prediction_loss_only`.
-- L'attributo `data_collator` di `Trainer` sarĂ richiamabile.
-- Il metodo `_log` di `Trainer` Ăš deprecato a favore di `log`.
-- Il metodo `_training_step` di `Trainer` Ăš deprecato a favore di `training_step`.
-- Il metodo `_prediction_loop` di `Trainer` Ăš deprecato a favore di `prediction_loop`.
-- Il metodo `is_local_master` di `Trainer` Ăš deprecato a favore di `is_local_process_zero`.
-- Il metodo `is_world_master` di `Trainer` Ăš deprecato a favore di `is_world_process_zero`.
-
-Per quanto riguarda la classe `TFTrainer`:
-- L'argomento `prediction_loss_only` di `TFTrainer` Ăš stato rimosso a favore dell'argomento di classe `args.prediction_loss_only`.
-- Il metodo `_log` di `Trainer` Ăš deprecato a favore di `log`.
-- Il metodo `_prediction_loop` di `TFTrainer` Ăš deprecato a favore di `prediction_loop`.
-- Il metodo `_setup_wandb` di `TFTrainer` Ăš deprecato a favore di `setup_wandb`.
-- Il metodo `_run_model` di `TFTrainer` Ăš deprecato a favore di `run_model`.
-
-Per quanto riguarda la classe `TrainingArguments`:
-- L'argomento `evaluate_during_training` di `TrainingArguments` Ăš deprecato a favore di `evaluation_strategy`.
-
-Per quanto riguarda il modello Transfo-XL:
-- L'attributo di configurazione `tie_weight` di Transfo-XL diventa `tie_words_embeddings`.
-- Il metodo di modellazione `reset_length` di Transfo-XL diventa `reset_memory_length`.
-
-Per quanto riguarda le pipeline:
-- L'argomento `topk` di `FillMaskPipeline` diventa `top_k`.
-
-
-
-## Passaggio da pytorch-transformers a đ€ Transformers
-
-Ecco un breve riepilogo di ciĂČ a cui prestare attenzione durante il passaggio da `pytorch-transformers` a đ€ Transformers.
-
-### Lâordine posizionale di alcune parole chiave di input dei modelli (`attention_mask`, `token_type_ids`...) Ăš cambiato
-
-Per usare Torchscript (vedi #1010, #1204 e #1195) l'ordine specifico delle **parole chiave di input** di alcuni modelli (`attention_mask`, `token_type_ids`...) Ăš stato modificato.
-
-Se inizializzavi i modelli usando parole chiave per gli argomenti, ad esempio `model(inputs_ids, attention_mask=attention_mask, token_type_ids=token_type_ids)`, questo non dovrebbe causare alcun cambiamento.
-
-Se inizializzavi i modelli con input posizionali per gli argomenti, ad esempio `model(inputs_ids, attention_mask, token_type_ids)`, potrebbe essere necessario ricontrollare l'ordine esatto degli argomenti di input.
-
-## Migrazione da pytorch-pretrained-bert
-
-Ecco un breve riepilogo di ciĂČ a cui prestare attenzione durante la migrazione da `pytorch-pretrained-bert` a đ€ Transformers
-
-### I modelli restituiscono sempre `tuple`
-
-La principale modifica di rilievo durante la migrazione da `pytorch-pretrained-bert` a đ€ Transformers Ăš che il metodo dei modelli di previsione dĂ sempre una `tupla` con vari elementi a seconda del modello e dei parametri di configurazione.
-
-Il contenuto esatto delle tuple per ciascun modello Ăš mostrato in dettaglio nelle docstring dei modelli e nella [documentazione](https://huggingface.co/transformers/).
-
-In quasi tutti i casi, andrĂ bene prendendo il primo elemento dell'output come quello che avresti precedentemente utilizzato in `pytorch-pretrained-bert`.
-
-Ecco un esempio di conversione da `pytorch-pretrained-bert`
- a đ€ Transformers per un modello di classificazione `BertForSequenceClassification`:
-
-```python
-# Carichiamo il nostro modello
-model = BertForSequenceClassification.from_pretrained("bert-base-uncased")
-
-# Se usavi questa riga in pytorch-pretrained-bert :
-loss = model(input_ids, labels=labels)
-
-# Ora usa questa riga in đ€ Transformers per estrarre la perdita dalla tupla di output:
-outputs = model(input_ids, labels=labels)
-loss = outputs[0]
-
-# In đ€ Transformers puoi anche avere accesso ai logit:
-loss, logits = outputs[:2]
-
-# Ed anche agli attention weight se configuri il modello per restituirli (e anche altri output, vedi le docstring e la documentazione)
-model = BertForSequenceClassification.from_pretrained(" bert-base-uncased", output_attentions=True)
-outputs = model(input_ids, labels=labels)
-loss, logits, attentions = outputs
-```
-
-### Serializzazione
-
-Modifica sostanziale nel metodo `from_pretrained()`:
-
-1. I modelli sono ora impostati in modalitĂ di valutazione in maniera predefinita quando usi il metodo `from_pretrained()`. Per addestrarli non dimenticare di riportarli in modalitĂ di addestramento (`model.train()`) per attivare i moduli di dropout.
-
-2. Gli argomenti aggiuntivi `*inputs` e `**kwargs` forniti al metodo `from_pretrained()` venivano passati direttamente al metodo `__init__()` della classe sottostante del modello. Ora sono usati per aggiornare prima l'attributo di configurazione del modello, che puĂČ non funzionare con le classi del modello derivate costruite basandosi sui precedenti esempi di `BertForSequenceClassification`. PiĂč precisamente, gli argomenti posizionali `*inputs` forniti a `from_pretrained()` vengono inoltrati direttamente al metodo `__init__()` del modello mentre gli argomenti keyword `**kwargs` (i) che corrispondono agli attributi della classe di configurazione, vengono utilizzati per aggiornare tali attributi (ii) che non corrispondono ad alcun attributo della classe di configurazione, vengono inoltrati al metodo `__init__()`.
-
-Inoltre, sebbene non si tratti di una modifica sostanziale, i metodi di serializzazione sono stati standardizzati e probabilmente dovresti passare al nuovo metodo `save_pretrained(save_directory)` se prima usavi qualsiasi altro metodo di serializzazione.
-
-Ecco un esempio:
-
-```python
-### Carichiamo un modello e un tokenizer
-model = BertForSequenceClassification.from_pretrained("bert-base-uncased")
-tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
-
-### Facciamo fare alcune cose al nostro modello e tokenizer
-# Es: aggiungiamo nuovi token al vocabolario e agli embending del nostro modello
-tokenizer.add_tokens(["[SPECIAL_TOKEN_1]", "[SPECIAL_TOKEN_2]"])
-model.resize_token_embeddings(len(tokenizer))
-# Alleniamo il nostro modello
-train(model)
-
-### Ora salviamo il nostro modello e il tokenizer in una cartella
-model.save_pretrained("./my_saved_model_directory/")
-tokenizer.save_pretrained("./my_saved_model_directory/")
-
-### Ricarichiamo il modello e il tokenizer
-model = BertForSequenceClassification.from_pretrained("./my_saved_model_directory/")
-tokenizer = BertTokenizer.from_pretrained("./my_saved_model_directory/")
-```
-
-### Ottimizzatori: BertAdam e OpenAIAdam ora sono AdamW, lo scheduling Ăš quello standard PyTorch
-
-I due ottimizzatori precedenti inclusi, `BertAdam` e `OpenAIAdam`, sono stati sostituiti da un singolo `AdamW` che presenta alcune differenze:
-
-- implementa solo la correzione del weights decay,
-- lo scheduling ora Ăš esterno (vedi sotto),
-- anche il gradient clipping ora Ăš esterno (vedi sotto).
-
-Il nuovo ottimizzatore `AdamW` corrisponde alle API di `Adam` di PyTorch e ti consente di utilizzare metodi PyTorch o apex per lo scheduling e il clipping.
-
-Lo scheduling Ăš ora standard [PyTorch learning rate schedulers](https://pytorch.org/docs/stable/optim.html#how-to-adjust-learning-rate) e non fanno piĂč parte dell'ottimizzatore.
-
-Ecco un esempio di linear warmup e decay con `BertAdam` e con `AdamW`:
-
-```python
-# Parametri:
-lr = 1e-3
-max_grad_norm = 1.0
-num_training_steps = 1000
-num_warmup_steps = 100
-warmup_proportion = float( num_warmup_steps) / float(num_training_steps) # 0.1
-
-### In precedenza l'ottimizzatore BertAdam veniva istanziato in questo modo:
-optimizer = BertAdam(
- model.parameters(),
- lr=lr,
- schedule="warmup_linear",
- warmup=warmup_proportion,
- num_training_steps=num_training_steps,
-)
-### e usato in questo modo:
-for batch in train_data:
- loss = model(batch)
- loss.backward()
- optimizer.step()
-
-### In đ€ Transformers, ottimizzatore e schedule sono divisi e usati in questo modo:
-optimizer = AdamW(
- model.parameters(), lr=lr, correct_bias=False
-) # Per riprodurre il comportamento specifico di BertAdam impostare correct_bias=False
-scheduler = get_linear_schedule_with_warmup(
- optimizer, num_warmup_steps=num_warmup_steps, num_training_steps=num_training_steps
-) # PyTorch scheduler
-### e va usato cosĂŹ:
-for batch in train_data:
- loss = model(batch)
- loss.backward()
- torch.nn.utils.clip_grad_norm_(
- model.parameters(), max_grad_norm
- ) # Gradient clipping non Ăš piĂč in AdamW (quindi puoi usare amp senza problemi)
- optimizer.step()
- scheduler.step()
-```
diff --git a/docs/source/it/model_sharing.md b/docs/source/it/model_sharing.md
new file mode 100644
index 000000000000..351cf57bf96b
--- /dev/null
+++ b/docs/source/it/model_sharing.md
@@ -0,0 +1,238 @@
+
+
+# Condividi un modello
+
+Gli ultimi due tutorial ti hanno mostrato come puoi fare fine-tuning di un modello con PyTorch, Keras e đ€ Accelerate per configurazioni distribuite. Il prossimo passo Ăš quello di condividere il tuo modello con la community! In Hugging Face, crediamo nella condivisione della conoscenza e delle risorse in modo da democratizzare l'intelligenza artificiale per chiunque. Ti incoraggiamo a considerare di condividere il tuo modello con la community per aiutare altre persone a risparmiare tempo e risorse.
+
+In questo tutorial, imparerai due metodi per la condivisione di un modello trained o fine-tuned nel [Model Hub](https://huggingface.co/models):
+
+- Condividi in modo programmatico i tuoi file nell'Hub.
+- Trascina i tuoi file nell'Hub mediante interfaccia grafica.
+
+VIDEO
+
+
+
+Per condividere un modello con la community, hai bisogno di un account su [huggingface.co](https://huggingface.co/join). Puoi anche unirti ad un'organizzazione esistente o crearne una nuova.
+
+
+
+## Caratteristiche dei repository
+
+Ogni repository nel Model Hub si comporta come un tipico repository di GitHub. I nostri repository offrono il versionamento, la cronologia dei commit, e la possibilitĂ di visualizzare le differenze.
+
+Il versionamento all'interno del Model Hub Ăš basato su git e [git-lfs](https://git-lfs.github.com/). In altre parole, puoi trattare un modello come un unico repository, consentendo un maggiore controllo degli accessi e maggiore scalabilitĂ . Il controllo delle versioni consente *revisions*, un metodo per appuntare una versione specifica di un modello con un hash di commit, un tag o un branch.
+
+Come risultato, puoi caricare una specifica versione di un modello con il parametro `revision`:
+
+```py
+>>> model = AutoModel.from_pretrained(
+... "julien-c/EsperBERTo-small", revision="v2.0.1" # nome di un tag, di un branch, o commit hash
+... )
+```
+
+Anche i file possono essere modificati facilmente in un repository ed Ăš possibile visualizzare la cronologia dei commit e le differenze:
+
+
+
+## Configurazione
+
+Prima di condividere un modello nell'Hub, hai bisogno delle tue credenziali di Hugging Face. Se hai accesso ad un terminale, esegui il seguente comando nell'ambiente virtuale in cui Ăš installata la libreria đ€ Transformers. Questo memorizzerĂ il tuo token di accesso nella cartella cache di Hugging Face (di default `~/.cache/`):
+
+```bash
+huggingface-cli login
+```
+
+Se stai usando un notebook come Jupyter o Colaboratory, assicurati di avere la libreria [`huggingface_hub`](https://huggingface.co/docs/hub/adding-a-library) installata. Questa libreria ti permette di interagire in maniera programmatica con l'Hub.
+
+```bash
+pip install huggingface_hub
+```
+
+Utilizza `notebook_login` per accedere all'Hub, e segui il link [qui](https://huggingface.co/settings/token) per generare un token con cui effettuare il login:
+
+```py
+>>> from huggingface_hub import notebook_login
+
+>>> notebook_login()
+```
+
+## Converti un modello per tutti i framework
+
+Per assicurarti che il tuo modello possa essere utilizzato da persone che lavorano con un framework differente, ti raccomandiamo di convertire e caricare il tuo modello sia con i checkpoint di PyTorch che con quelli di TensorFlow. Anche se Ăš possibile caricare il modello da un framework diverso, se si salta questo passaggio, il caricamento sarĂ piĂč lento perchĂ© đ€ Transformers ha bisogno di convertire i checkpoint al momento.
+
+Convertire un checkpoint per un altro framework Ăš semplice. Assicurati di avere PyTorch e TensorFlow installati (vedi [qui](installation) per le istruzioni d'installazione), e poi trova il modello specifico per il tuo compito nell'altro framework.
+
+
+
+Specifica `from_tf=True` per convertire un checkpoint da TensorFlow a PyTorch:
+
+```py
+>>> pt_model = DistilBertForSequenceClassification.from_pretrained(
+... "path/verso/il-nome-magnifico-che-hai-scelto", from_tf=True
+... )
+>>> pt_model.save_pretrained("path/verso/il-nome-magnifico-che-hai-scelto")
+```
+
+
+Specifica `from_pt=True` per convertire un checkpoint da PyTorch a TensorFlow:
+
+```py
+>>> tf_model = TFDistilBertForSequenceClassification.from_pretrained(
+... "path/verso/il-nome-magnifico-che-hai-scelto", from_pt=True
+... )
+```
+
+Poi puoi salvare il tuo nuovo modello in TensorFlow con il suo nuovo checkpoint:
+
+```py
+>>> tf_model.save_pretrained("path/verso/il-nome-magnifico-che-hai-scelto")
+```
+
+
+Se un modello Ăš disponibile in Flax, puoi anche convertire un checkpoint da PyTorch a Flax:
+
+```py
+>>> flax_model = FlaxDistilBertForSequenceClassification.from_pretrained(
+... "path/verso/il-nome-magnifico-che-hai-scelto", from_pt=True
+... )
+```
+
+
+
+## Condividi un modello durante il training
+
+
+
+
+
+Condividere un modello nell'Hub Ăš tanto semplice quanto aggiungere un parametro extra o un callback. Ricorda dal [tutorial sul fine-tuning](training), la classe [`TrainingArguments`] Ăš dove specifichi gli iperparametri e le opzioni addizionali per l'allenamento. Una di queste opzioni di training include l'abilitĂ di condividere direttamente un modello nell'Hub. Imposta `push_to_hub=True` in [`TrainingArguments`]:
+
+```py
+>>> training_args = TrainingArguments(output_dir="il-mio-bellissimo-modello", push_to_hub=True)
+```
+
+Passa gli argomenti per il training come di consueto al [`Trainer`]:
+
+```py
+>>> trainer = Trainer(
+... model=model,
+... args=training_args,
+... train_dataset=small_train_dataset,
+... eval_dataset=small_eval_dataset,
+... compute_metrics=compute_metrics,
+... )
+```
+
+Dopo aver effettuato il fine-tuning del tuo modello, chiama [`~transformers.Trainer.push_to_hub`] sul [`Trainer`] per condividere il modello allenato nell'Hub. đ€ Transformers aggiungerĂ in modo automatico persino gli iperparametri, i risultati del training e le versioni del framework alla scheda del tuo modello (model card, in inglese)!
+
+```py
+>>> trainer.push_to_hub()
+```
+
+
+Condividi un modello nell'Hub con [`PushToHubCallback`]. Nella funzione [`PushToHubCallback`], aggiungi:
+
+- Una directory di output per il tuo modello.
+- Un tokenizer.
+- L'`hub_model_id`, che Ăš il tuo username sull'Hub e il nome del modello.
+
+```py
+>>> from transformers import PushToHubCallback
+
+>>> push_to_hub_callback = PushToHubCallback(
+... output_dir="./il_path_dove_salvare_il_tuo_modello",
+... tokenizer=tokenizer,
+... hub_model_id="il-tuo-username/il-mio-bellissimo-modello",
+... )
+```
+
+Aggiungi il callback a [`fit`](https://keras.io/api/models/model_training_apis/), e đ€ Transformers caricherĂ il modello allenato nell'Hub:
+
+```py
+>>> model.fit(tf_train_dataset, validation_data=tf_validation_dataset, epochs=3, callbacks=push_to_hub_callback)
+```
+
+
+
+## Utilizzare la funzione `push_to_hub`
+
+Puoi anche chiamare `push_to_hub` direttamente sul tuo modello per caricarlo nell'Hub.
+
+Specifica il nome del tuo modello in `push_to_hub`:
+
+```py
+>>> pt_model.push_to_hub("il-mio-bellissimo-modello")
+```
+
+Questo crea un repository sotto il proprio username con il nome del modello `il-mio-bellissimo-modello`. Ora chiunque puĂČ caricare il tuo modello con la funzione `from_pretrained`:
+
+```py
+>>> from transformers import AutoModel
+
+>>> model = AutoModel.from_pretrained("il-tuo-username/il-mio-bellissimo-modello")
+```
+
+Se fai parte di un'organizzazione e vuoi invece condividere un modello sotto il nome dell'organizzazione, aggiungi il parametro `organization`:
+
+```py
+>>> pt_model.push_to_hub("il-mio-bellissimo-modello", organization="la-mia-fantastica-org")
+```
+
+La funzione `push_to_hub` puĂČ essere anche utilizzata per aggiungere altri file al repository del modello. Per esempio, aggiungi un tokenizer ad un repository di un modello:
+
+```py
+>>> tokenizer.push_to_hub("il-mio-bellissimo-modello")
+```
+
+O magari potresti voler aggiungere la versione di TensorFlow del tuo modello PyTorch a cui hai fatto fine-tuning:
+
+```py
+>>> tf_model.push_to_hub("il-mio-bellissimo-modello")
+```
+
+Ora quando navighi nel tuo profilo Hugging Face, dovresti vedere il tuo repository del modello appena creato. Premendo sulla scheda **Files** vengono visualizzati tutti i file caricati nel repository.
+
+Per maggiori dettagli su come creare e caricare file ad un repository, fai riferimento alla documentazione [qui](https://huggingface.co/docs/hub/how-to-upstream).
+
+## Carica un modello utilizzando l'interfaccia web
+
+Chi preferisce un approccio senza codice puĂČ caricare un modello tramite l'interfaccia web dell'hub. Visita [huggingface.co/new](https://huggingface.co/new) per creare un nuovo repository:
+
+
+
+Da qui, aggiungi alcune informazioni sul tuo modello:
+
+- Seleziona il/la **owner** del repository. Puoi essere te o qualunque organizzazione di cui fai parte.
+- Scegli un nome per il tuo modello, il quale sarĂ anche il nome del repository.
+- Scegli se il tuo modello Ăš pubblico o privato.
+- Specifica la licenza utilizzata per il tuo modello.
+
+Ora premi sulla scheda **Files** e premi sul pulsante **Add file** per caricare un nuovo file al tuo repository. Trascina poi un file per caricarlo e aggiungere un messaggio di commit.
+
+
+
+## Aggiungi una scheda del modello
+
+Per assicurarti che chiunque possa comprendere le abilitĂ , limitazioni, i potenziali bias e le considerazioni etiche del tuo modello, per favore aggiungi una scheda del modello (model card, in inglese) al tuo repository. La scheda del modello Ăš definita nel file `README.md`. Puoi aggiungere una scheda del modello:
+
+* Creando manualmente e caricando un file `README.md`.
+* Premendo sul pulsante **Edit model card** nel repository del tuo modello.
+
+Dai un'occhiata alla [scheda del modello](https://huggingface.co/distilbert-base-uncased) di DistilBert per avere un buon esempio del tipo di informazioni che una scheda di un modello deve includere. Per maggiori dettagli legati ad altre opzioni che puoi controllare nel file `README.md`, come l'impatto ambientale o widget di esempio, fai riferimento alla documentazione [qui](https://huggingface.co/docs/hub/models-cards).
diff --git a/docs/source/it/model_sharing.mdx b/docs/source/it/model_sharing.mdx
deleted file mode 100644
index 9e1ca9588a10..000000000000
--- a/docs/source/it/model_sharing.mdx
+++ /dev/null
@@ -1,234 +0,0 @@
-
-
-# Condividi un modello
-
-Gli ultimi due tutorial ti hanno mostrato come puoi fare fine-tuning di un modello con PyTorch, Keras e đ€ Accelerate per configurazioni distribuite. Il prossimo passo Ăš quello di condividere il tuo modello con la community! In Hugging Face, crediamo nella condivisione della conoscenza e delle risorse in modo da democratizzare l'intelligenza artificiale per chiunque. Ti incoraggiamo a considerare di condividere il tuo modello con la community per aiutare altre persone a risparmiare tempo e risorse.
-
-In questo tutorial, imparerai due metodi per la condivisione di un modello trained o fine-tuned nel [Model Hub](https://huggingface.co/models):
-
-- Condividi in modo programmatico i tuoi file nell'Hub.
-- Trascina i tuoi file nell'Hub mediante interfaccia grafica.
-
-VIDEO
-
-
-
-Per condividere un modello con la community, hai bisogno di un account su [huggingface.co](https://huggingface.co/join). Puoi anche unirti ad un'organizzazione esistente o crearne una nuova.
-
-
-
-## Caratteristiche dei repository
-
-Ogni repository nel Model Hub si comporta come un tipico repository di GitHub. I nostri repository offrono il versionamento, la cronologia dei commit, e la possibilitĂ di visualizzare le differenze.
-
-Il versionamento all'interno del Model Hub Ăš basato su git e [git-lfs](https://git-lfs.github.com/). In altre parole, puoi trattare un modello come un unico repository, consentendo un maggiore controllo degli accessi e maggiore scalabilitĂ . Il controllo delle versioni consente *revisions*, un metodo per appuntare una versione specifica di un modello con un hash di commit, un tag o un branch.
-
-Come risultato, puoi caricare una specifica versione di un modello con il parametro `revision`:
-
-```py
->>> model = AutoModel.from_pretrained(
-... "julien-c/EsperBERTo-small", revision="v2.0.1" # nome di un tag, di un branch, o commit hash
-... )
-```
-
-Anche i file possono essere modificati facilmente in un repository ed Ăš possibile visualizzare la cronologia dei commit e le differenze:
-
-
-
-## Configurazione
-
-Prima di condividere un modello nell'Hub, hai bisogno delle tue credenziali di Hugging Face. Se hai accesso ad un terminale, esegui il seguente comando nell'ambiente virtuale in cui Ăš installata la libreria đ€ Transformers. Questo memorizzerĂ il tuo token di accesso nella cartella cache di Hugging Face (di default `~/.cache/`):
-
-```bash
-huggingface-cli login
-```
-
-Se stai usando un notebook come Jupyter o Colaboratory, assicurati di avere la libreria [`huggingface_hub`](https://huggingface.co/docs/hub/adding-a-library) installata. Questa libreria ti permette di interagire in maniera programmatica con l'Hub.
-
-```bash
-pip install huggingface_hub
-```
-
-Utilizza `notebook_login` per accedere all'Hub, e segui il link [qui](https://huggingface.co/settings/token) per generare un token con cui effettuare il login:
-
-```py
->>> from huggingface_hub import notebook_login
-
->>> notebook_login()
-```
-
-## Converti un modello per tutti i framework
-
-Per assicurarti che il tuo modello possa essere utilizzato da persone che lavorano con un framework differente, ti raccomandiamo di convertire e caricare il tuo modello sia con i checkpoint di PyTorch che con quelli di TensorFlow. Anche se Ăš possibile caricare il modello da un framework diverso, se si salta questo passaggio, il caricamento sarĂ piĂč lento perchĂ© đ€ Transformers ha bisogno di convertire i checkpoint al momento.
-
-Convertire un checkpoint per un altro framework Ăš semplice. Assicurati di avere PyTorch e TensorFlow installati (vedi [qui](installation) per le istruzioni d'installazione), e poi trova il modello specifico per il tuo compito nell'altro framework.
-
-
-
-Specifica `from_tf=True` per convertire un checkpoint da TensorFlow a PyTorch:
-
-```py
->>> pt_model = DistilBertForSequenceClassification.from_pretrained(
-... "path/verso/il-nome-magnifico-che-hai-scelto", from_tf=True
-... )
->>> pt_model.save_pretrained("path/verso/il-nome-magnifico-che-hai-scelto")
-```
-
-
-Specifica `from_pt=True` per convertire un checkpoint da PyTorch a TensorFlow:
-
-```py
->>> tf_model = TFDistilBertForSequenceClassification.from_pretrained(
-... "path/verso/il-nome-magnifico-che-hai-scelto", from_pt=True
-... )
-```
-
-Poi puoi salvare il tuo nuovo modello in TensorFlow con il suo nuovo checkpoint:
-
-```py
->>> tf_model.save_pretrained("path/verso/il-nome-magnifico-che-hai-scelto")
-```
-
-
-Se un modello Ăš disponibile in Flax, puoi anche convertire un checkpoint da PyTorch a Flax:
-
-```py
->>> flax_model = FlaxDistilBertForSequenceClassification.from_pretrained(
-... "path/verso/il-nome-magnifico-che-hai-scelto", from_pt=True
-... )
-```
-
-
-
-## Condividi un modello durante il training
-
-
-
-
-
-Condividere un modello nell'Hub Ăš tanto semplice quanto aggiungere un parametro extra o un callback. Ricorda dal [tutorial sul fine-tuning](training), la classe [`TrainingArguments`] Ăš dove specifichi gli iperparametri e le opzioni addizionali per l'allenamento. Una di queste opzioni di training include l'abilitĂ di condividere direttamente un modello nell'Hub. Imposta `push_to_hub=True` in [`TrainingArguments`]:
-
-```py
->>> training_args = TrainingArguments(output_dir="il-mio-bellissimo-modello", push_to_hub=True)
-```
-
-Passa gli argomenti per il training come di consueto al [`Trainer`]:
-
-```py
->>> trainer = Trainer(
-... model=model,
-... args=training_args,
-... train_dataset=small_train_dataset,
-... eval_dataset=small_eval_dataset,
-... compute_metrics=compute_metrics,
-... )
-```
-
-Dopo aver effettuato il fine-tuning del tuo modello, chiama [`~transformers.Trainer.push_to_hub`] sul [`Trainer`] per condividere il modello allenato nell'Hub. đ€ Transformers aggiungerĂ in modo automatico persino gli iperparametri, i risultati del training e le versioni del framework alla scheda del tuo modello (model card, in inglese)!
-
-```py
->>> trainer.push_to_hub()
-```
-
-
-Condividi un modello nell'Hub con [`PushToHubCallback`]. Nella funzione [`PushToHubCallback`], aggiungi:
-
-- Una directory di output per il tuo modello.
-- Un tokenizer.
-- L'`hub_model_id`, che Ăš il tuo username sull'Hub e il nome del modello.
-
-```py
->>> from transformers import PushToHubCallback
-
->>> push_to_hub_callback = PushToHubCallback(
-... output_dir="./il_path_dove_salvare_il_tuo_modello",
-... tokenizer=tokenizer,
-... hub_model_id="il-tuo-username/il-mio-bellissimo-modello",
-... )
-```
-
-Aggiungi il callback a [`fit`](https://keras.io/api/models/model_training_apis/), e đ€ Transformers caricherĂ il modello allenato nell'Hub:
-
-```py
->>> model.fit(tf_train_dataset, validation_data=tf_validation_dataset, epochs=3, callbacks=push_to_hub_callback)
-```
-
-
-
-## Utilizzare la funzione `push_to_hub`
-
-Puoi anche chiamare `push_to_hub` direttamente sul tuo modello per caricarlo nell'Hub.
-
-Specifica il nome del tuo modello in `push_to_hub`:
-
-```py
->>> pt_model.push_to_hub("il-mio-bellissimo-modello")
-```
-
-Questo crea un repository sotto il proprio username con il nome del modello `il-mio-bellissimo-modello`. Ora chiunque puĂČ caricare il tuo modello con la funzione `from_pretrained`:
-
-```py
->>> from transformers import AutoModel
-
->>> model = AutoModel.from_pretrained("il-tuo-username/il-mio-bellissimo-modello")
-```
-
-Se fai parte di un'organizzazione e vuoi invece condividere un modello sotto il nome dell'organizzazione, aggiungi il parametro `organization`:
-
-```py
->>> pt_model.push_to_hub("il-mio-bellissimo-modello", organization="la-mia-fantastica-org")
-```
-
-La funzione `push_to_hub` puĂČ essere anche utilizzata per aggiungere altri file al repository del modello. Per esempio, aggiungi un tokenizer ad un repository di un modello:
-
-```py
->>> tokenizer.push_to_hub("il-mio-bellissimo-modello")
-```
-
-O magari potresti voler aggiungere la versione di TensorFlow del tuo modello PyTorch a cui hai fatto fine-tuning:
-
-```py
->>> tf_model.push_to_hub("il-mio-bellissimo-modello")
-```
-
-Ora quando navighi nel tuo profilo Hugging Face, dovresti vedere il tuo repository del modello appena creato. Premendo sulla scheda **Files** vengono visualizzati tutti i file caricati nel repository.
-
-Per maggiori dettagli su come creare e caricare file ad un repository, fai riferimento alla documentazione [qui](https://huggingface.co/docs/hub/how-to-upstream).
-
-## Carica un modello utilizzando l'interfaccia web
-
-Chi preferisce un approccio senza codice puĂČ caricare un modello tramite l'interfaccia web dell'hub. Visita [huggingface.co/new](https://huggingface.co/new) per creare un nuovo repository:
-
-
-
-Da qui, aggiungi alcune informazioni sul tuo modello:
-
-- Seleziona il/la **owner** del repository. Puoi essere te o qualunque organizzazione di cui fai parte.
-- Scegli un nome per il tuo modello, il quale sarĂ anche il nome del repository.
-- Scegli se il tuo modello Ăš pubblico o privato.
-- Specifica la licenza utilizzata per il tuo modello.
-
-Ora premi sulla scheda **Files** e premi sul pulsante **Add file** per caricare un nuovo file al tuo repository. Trascina poi un file per caricarlo e aggiungere un messaggio di commit.
-
-
-
-## Aggiungi una scheda del modello
-
-Per assicurarti che chiunque possa comprendere le abilitĂ , limitazioni, i potenziali bias e le considerazioni etiche del tuo modello, per favore aggiungi una scheda del modello (model card, in inglese) al tuo repository. La scheda del modello Ăš definita nel file `README.md`. Puoi aggiungere una scheda del modello:
-
-* Creando manualmente e caricando un file `README.md`.
-* Premendo sul pulsante **Edit model card** nel repository del tuo modello.
-
-Dai un'occhiata alla [scheda del modello](https://huggingface.co/distilbert-base-uncased) di DistilBert per avere un buon esempio del tipo di informazioni che una scheda di un modello deve includere. Per maggiori dettagli legati ad altre opzioni che puoi controllare nel file `README.md`, come l'impatto ambientale o widget di esempio, fai riferimento alla documentazione [qui](https://huggingface.co/docs/hub/models-cards).
diff --git a/docs/source/it/multilingual.md b/docs/source/it/multilingual.md
new file mode 100644
index 000000000000..889c620ab29d
--- /dev/null
+++ b/docs/source/it/multilingual.md
@@ -0,0 +1,178 @@
+
+
+# Modelli multilingue per l'inferenza
+
+[[open-in-colab]]
+
+Ci sono diversi modelli multilingue in đ€ Transformers, e il loro utilizzo per l'inferenza differisce da quello dei modelli monolingua. Non *tutti* gli utilizzi dei modelli multilingue sono perĂČ diversi. Alcuni modelli, come [bert-base-multilingual-uncased](https://huggingface.co/bert-base-multilingual-uncased), possono essere usati come un modello monolingua. Questa guida ti mostrerĂ come utilizzare modelli multilingue che utilizzano un modo diverso per fare l'inferenza.
+
+## XLM
+
+XLM ha dieci diversi checkpoint, di cui solo uno Ăš monolingua. I nove checkpoint rimanenti possono essere suddivisi in due categorie: i checkpoint che utilizzano i language embeddings e quelli che non li utilizzano.
+
+### XLM con language embeddings
+
+I seguenti modelli XLM utilizzano gli embeddings linguistici per specificare la lingua utilizzata per l'inferenza:
+
+- `xlm-mlm-ende-1024` (Modellazione mascherata del linguaggio (Masked language modeling, in inglese), Inglese-Tedesco)
+- `xlm-mlm-enfr-1024` (Modellazione mascherata del linguaggio, Inglese-Francese)
+- `xlm-mlm-enro-1024` (Modellazione mascherata del linguaggio, Inglese-Rumeno)
+- `xlm-mlm-xnli15-1024` (Modellazione mascherata del linguaggio, lingue XNLI)
+- `xlm-mlm-tlm-xnli15-1024` (Modellazione mascherata del linguaggio + traduzione, lingue XNLI)
+- `xlm-clm-enfr-1024` (Modellazione causale del linguaggio, Inglese-Francese)
+- `xlm-clm-ende-1024` (Modellazione causale del linguaggio, Inglese-Tedesco)
+
+Gli embeddings linguistici sono rappresentati come un tensore delle stesse dimensioni dell' `input_ids` passato al modello. I valori in questi tensori dipendono dal linguaggio usato e sono identificati dagli attributi `lang2id` e `id2lang` del tokenizer.
+
+In questo esempio, carica il checkpoint `xlm-clm-enfr-1024` (Modellazione causale del linguaggio, Inglese-Francese):
+
+```py
+>>> import torch
+>>> from transformers import XLMTokenizer, XLMWithLMHeadModel
+
+>>> tokenizer = XLMTokenizer.from_pretrained("xlm-clm-enfr-1024")
+>>> model = XLMWithLMHeadModel.from_pretrained("xlm-clm-enfr-1024")
+```
+
+L'attributo `lang2id` del tokenizer mostra il linguaggio del modello e il suo ids:
+
+```py
+>>> print(tokenizer.lang2id)
+{'en': 0, 'fr': 1}
+```
+
+Poi, crea un esempio di input:
+
+```py
+>>> input_ids = torch.tensor([tokenizer.encode("Wikipedia was used to")]) # batch size of 1
+```
+
+Imposta l'id del linguaggio a `"en"` e usalo per definire il language embedding. Il language embedding Ú un tensore riempito con `0` perché questo Ú il language id per l'inglese. Questo tensore dovrebbe avere la stessa dimensione di `input_ids`.
+
+```py
+>>> language_id = tokenizer.lang2id["en"] # 0
+>>> langs = torch.tensor([language_id] * input_ids.shape[1]) # torch.tensor([0, 0, 0, ..., 0])
+
+>>> # We reshape it to be of size (batch_size, sequence_length)
+>>> langs = langs.view(1, -1) # is now of shape [1, sequence_length] (we have a batch size of 1)
+```
+
+Adesso puoi inserire `input_ids` e language embedding nel modello:
+
+```py
+>>> outputs = model(input_ids, langs=langs)
+```
+
+Lo script [run_generation.py](https://github.com/huggingface/transformers/tree/main/examples/pytorch/text-generation/run_generation.py) puĂČ generare testo tramite i language embeddings usando i checkpoints `xlm-clm`.
+
+### XLM senza language embeddings
+
+I seguenti modelli XLM non richiedono l'utilizzo dei language embeddings per fare inferenza:
+
+- `xlm-mlm-17-1280` (Modellazione mascherata del linguaggio, 17 lingue)
+- `xlm-mlm-100-1280` (Modellazione mascherata del linguaggio, 100 lingue)
+
+Questi modelli sono utilizzati per rappresentazioni generiche di frasi, a differenza dei precedenti checkpoints XML.
+
+## BERT
+
+Il seguente modello BERT puĂČ essere usato per compiti multilingue:
+
+- `bert-base-multilingual-uncased` (Modellazione mascherata del linguaggio + Previsione della prossima frase, 102 lingue)
+- `bert-base-multilingual-cased` (Modellazione mascherata del linguaggio + Previsione della prossima frase, 104 lingue)
+
+Questi modelli non richiedono language embeddings per fare inferenza. Riescono ad identificare il linguaggio dal contesto e inferire di conseguenza.
+
+## XLM-RoBERTa
+
+Il seguente modello XLM-RoBERTa puĂČ essere usato per compiti multilingue:
+
+- `xlm-roberta-base` (Modellazione mascherata del linguaggio, 100 lingue)
+- `xlm-roberta-large` (Modellazione mascherata del linguaggio, 100 lingue)
+
+XLM-RoBERTa Ăš stato addestrato su 2.5TB di dati CommonCrawl appena creati e puliti in 100 lingue. Offre notevoli vantaggi rispetto ai modelli multilingue rilasciati in precedenza, come mBERT o XLM, in compiti come la classificazione, l'etichettatura delle sequenze e la risposta alle domande.
+
+## M2M100
+
+Il seguente modello M2M100 puĂČ essere usato per compiti multilingue:
+
+- `facebook/m2m100_418M` (Traduzione)
+- `facebook/m2m100_1.2B` (Traduzione)
+
+In questo esempio, carica il checkpoint `facebook/m2m100_418M` per tradurre dal cinese all'inglese. Puoi impostare la lingua di partenza nel tokenizer:
+
+```py
+>>> from transformers import M2M100ForConditionalGeneration, M2M100Tokenizer
+
+>>> en_text = "Do not meddle in the affairs of wizards, for they are subtle and quick to anger."
+>>> chinese_text = "äžèŠææć·«ćž«çäșć, ć çșä»ćæŻćŸźćŠç, ćŸćż«ć°±æçŒæ."
+
+>>> tokenizer = M2M100Tokenizer.from_pretrained("facebook/m2m100_418M", src_lang="zh")
+>>> model = M2M100ForConditionalGeneration.from_pretrained("facebook/m2m100_418M")
+```
+
+Applica il tokenizer al testo:
+
+```py
+>>> encoded_zh = tokenizer(chinese_text, return_tensors="pt")
+```
+
+M2M100 forza l'id della lingua obiettivo come primo token generato per tradurre nella lingua obiettivo. Imposta il parametro `forced_bos_token_id` a `en` nel metodo `generate` per tradurre in inglese:
+
+```py
+>>> generated_tokens = model.generate(**encoded_zh, forced_bos_token_id=tokenizer.get_lang_id("en"))
+>>> tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)
+'Do not interfere with the matters of the witches, because they are delicate and will soon be angry.'
+```
+
+## MBart
+
+Il seguente modello MBart puĂČ essere usato per compiti multilingue:
+
+- `facebook/mbart-large-50-one-to-many-mmt` (Traduzione automatica multilingue uno-a-molti, 50 lingue)
+- `facebook/mbart-large-50-many-to-many-mmt` (Traduzione automatica multilingue molti-a-molti, 50 lingue)
+- `facebook/mbart-large-50-many-to-one-mmt` (Traduzione automatica multilingue molti-a-uno, 50 lingue)
+- `facebook/mbart-large-50` (Traduzione multilingue, 50 lingue)
+- `facebook/mbart-large-cc25`
+
+In questo esempio, carica il checkpoint `facebook/mbart-large-50-many-to-many-mmt` per tradurre dal finlandese all'inglese. Puoi impostare la lingua di partenza nel tokenizer:
+
+```py
+>>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
+
+>>> en_text = "Do not meddle in the affairs of wizards, for they are subtle and quick to anger."
+>>> fi_text = "ĂlĂ€ sekaannu velhojen asioihin, sillĂ€ ne ovat hienovaraisia ja nopeasti vihaisia."
+
+>>> tokenizer = AutoTokenizer.from_pretrained("facebook/mbart-large-50-many-to-many-mmt", src_lang="fi_FI")
+>>> model = AutoModelForSeq2SeqLM.from_pretrained("facebook/mbart-large-50-many-to-many-mmt")
+```
+
+Applica il tokenizer sul testo:
+
+```py
+>>> encoded_en = tokenizer(en_text, return_tensors="pt")
+```
+
+MBart forza l'id della lingua obiettivo come primo token generato per tradurre nella lingua obiettivo. Imposta il parametro `forced_bos_token_id` a `en` nel metodo `generate` per tradurre in inglese:
+
+```py
+>>> generated_tokens = model.generate(**encoded_en, forced_bos_token_id=tokenizer.lang_code_to_id("en_XX"))
+>>> tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)
+"Don't interfere with the wizard's affairs, because they are subtle, will soon get angry."
+```
+
+Se stai usando il checkpoint `facebook/mbart-large-50-many-to-one-mmt`, non hai bisogno di forzare l'id della lingua obiettivo come primo token generato altrimenti l'uso Ăš lo stesso.
\ No newline at end of file
diff --git a/docs/source/it/multilingual.mdx b/docs/source/it/multilingual.mdx
deleted file mode 100644
index a8ccec97d0a7..000000000000
--- a/docs/source/it/multilingual.mdx
+++ /dev/null
@@ -1,174 +0,0 @@
-
-
-# Modelli multilingue per l'inferenza
-
-[[open-in-colab]]
-
-Ci sono diversi modelli multilingue in đ€ Transformers, e il loro utilizzo per l'inferenza differisce da quello dei modelli monolingua. Non *tutti* gli utilizzi dei modelli multilingue sono perĂČ diversi. Alcuni modelli, come [bert-base-multilingual-uncased](https://huggingface.co/bert-base-multilingual-uncased), possono essere usati come un modello monolingua. Questa guida ti mostrerĂ come utilizzare modelli multilingue che utilizzano un modo diverso per fare l'inferenza.
-
-## XLM
-
-XLM ha dieci diversi checkpoint, di cui solo uno Ăš monolingua. I nove checkpoint rimanenti possono essere suddivisi in due categorie: i checkpoint che utilizzano i language embeddings e quelli che non li utilizzano.
-
-### XLM con language embeddings
-
-I seguenti modelli XLM utilizzano gli embeddings linguistici per specificare la lingua utilizzata per l'inferenza:
-
-- `xlm-mlm-ende-1024` (Modellazione mascherata del linguaggio (Masked language modeling, in inglese), Inglese-Tedesco)
-- `xlm-mlm-enfr-1024` (Modellazione mascherata del linguaggio, Inglese-Francese)
-- `xlm-mlm-enro-1024` (Modellazione mascherata del linguaggio, Inglese-Rumeno)
-- `xlm-mlm-xnli15-1024` (Modellazione mascherata del linguaggio, lingue XNLI)
-- `xlm-mlm-tlm-xnli15-1024` (Modellazione mascherata del linguaggio + traduzione, lingue XNLI)
-- `xlm-clm-enfr-1024` (Modellazione causale del linguaggio, Inglese-Francese)
-- `xlm-clm-ende-1024` (Modellazione causale del linguaggio, Inglese-Tedesco)
-
-Gli embeddings linguistici sono rappresentati come un tensore delle stesse dimensioni dell' `input_ids` passato al modello. I valori in questi tensori dipendono dal linguaggio usato e sono identificati dagli attributi `lang2id` e `id2lang` del tokenizer.
-
-In questo esempio, carica il checkpoint `xlm-clm-enfr-1024` (Modellazione causale del linguaggio, Inglese-Francese):
-
-```py
->>> import torch
->>> from transformers import XLMTokenizer, XLMWithLMHeadModel
-
->>> tokenizer = XLMTokenizer.from_pretrained("xlm-clm-enfr-1024")
->>> model = XLMWithLMHeadModel.from_pretrained("xlm-clm-enfr-1024")
-```
-
-L'attributo `lang2id` del tokenizer mostra il linguaggio del modello e il suo ids:
-
-```py
->>> print(tokenizer.lang2id)
-{'en': 0, 'fr': 1}
-```
-
-Poi, crea un esempio di input:
-
-```py
->>> input_ids = torch.tensor([tokenizer.encode("Wikipedia was used to")]) # batch size of 1
-```
-
-Imposta l'id del linguaggio a `"en"` e usalo per definire il language embedding. Il language embedding Ú un tensore riempito con `0` perché questo Ú il language id per l'inglese. Questo tensore dovrebbe avere la stessa dimensione di `input_ids`.
-
-```py
->>> language_id = tokenizer.lang2id["en"] # 0
->>> langs = torch.tensor([language_id] * input_ids.shape[1]) # torch.tensor([0, 0, 0, ..., 0])
-
->>> # We reshape it to be of size (batch_size, sequence_length)
->>> langs = langs.view(1, -1) # is now of shape [1, sequence_length] (we have a batch size of 1)
-```
-
-Adesso puoi inserire `input_ids` e language embedding nel modello:
-
-```py
->>> outputs = model(input_ids, langs=langs)
-```
-
-Lo script [run_generation.py](https://github.com/huggingface/transformers/tree/main/examples/pytorch/text-generation/run_generation.py) puĂČ generare testo tramite i language embeddings usando i checkpoints `xlm-clm`.
-
-### XLM senza language embeddings
-
-I seguenti modelli XLM non richiedono l'utilizzo dei language embeddings per fare inferenza:
-
-- `xlm-mlm-17-1280` (Modellazione mascherata del linguaggio, 17 lingue)
-- `xlm-mlm-100-1280` (Modellazione mascherata del linguaggio, 100 lingue)
-
-Questi modelli sono utilizzati per rappresentazioni generiche di frasi, a differenza dei precedenti checkpoints XML.
-
-## BERT
-
-Il seguente modello BERT puĂČ essere usato per compiti multilingue:
-
-- `bert-base-multilingual-uncased` (Modellazione mascherata del linguaggio + Previsione della prossima frase, 102 lingue)
-- `bert-base-multilingual-cased` (Modellazione mascherata del linguaggio + Previsione della prossima frase, 104 lingue)
-
-Questi modelli non richiedono language embeddings per fare inferenza. Riescono ad identificare il linguaggio dal contesto e inferire di conseguenza.
-
-## XLM-RoBERTa
-
-Il seguente modello XLM-RoBERTa puĂČ essere usato per compiti multilingue:
-
-- `xlm-roberta-base` (Modellazione mascherata del linguaggio, 100 lingue)
-- `xlm-roberta-large` (Modellazione mascherata del linguaggio, 100 lingue)
-
-XLM-RoBERTa Ăš stato addestrato su 2.5TB di dati CommonCrawl appena creati e puliti in 100 lingue. Offre notevoli vantaggi rispetto ai modelli multilingue rilasciati in precedenza, come mBERT o XLM, in compiti come la classificazione, l'etichettatura delle sequenze e la risposta alle domande.
-
-## M2M100
-
-Il seguente modello M2M100 puĂČ essere usato per compiti multilingue:
-
-- `facebook/m2m100_418M` (Traduzione)
-- `facebook/m2m100_1.2B` (Traduzione)
-
-In questo esempio, carica il checkpoint `facebook/m2m100_418M` per tradurre dal cinese all'inglese. Puoi impostare la lingua di partenza nel tokenizer:
-
-```py
->>> from transformers import M2M100ForConditionalGeneration, M2M100Tokenizer
-
->>> en_text = "Do not meddle in the affairs of wizards, for they are subtle and quick to anger."
->>> chinese_text = "äžèŠææć·«ćž«çäșć, ć çșä»ćæŻćŸźćŠç, ćŸćż«ć°±æçŒæ."
-
->>> tokenizer = M2M100Tokenizer.from_pretrained("facebook/m2m100_418M", src_lang="zh")
->>> model = M2M100ForConditionalGeneration.from_pretrained("facebook/m2m100_418M")
-```
-
-Applica il tokenizer al testo:
-
-```py
->>> encoded_zh = tokenizer(chinese_text, return_tensors="pt")
-```
-
-M2M100 forza l'id della lingua obiettivo come primo token generato per tradurre nella lingua obiettivo. Imposta il parametro `forced_bos_token_id` a `en` nel metodo `generate` per tradurre in inglese:
-
-```py
->>> generated_tokens = model.generate(**encoded_zh, forced_bos_token_id=tokenizer.get_lang_id("en"))
->>> tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)
-'Do not interfere with the matters of the witches, because they are delicate and will soon be angry.'
-```
-
-## MBart
-
-Il seguente modello MBart puĂČ essere usato per compiti multilingue:
-
-- `facebook/mbart-large-50-one-to-many-mmt` (Traduzione automatica multilingue uno-a-molti, 50 lingue)
-- `facebook/mbart-large-50-many-to-many-mmt` (Traduzione automatica multilingue molti-a-molti, 50 lingue)
-- `facebook/mbart-large-50-many-to-one-mmt` (Traduzione automatica multilingue molti-a-uno, 50 lingue)
-- `facebook/mbart-large-50` (Traduzione multilingue, 50 lingue)
-- `facebook/mbart-large-cc25`
-
-In questo esempio, carica il checkpoint `facebook/mbart-large-50-many-to-many-mmt` per tradurre dal finlandese all'inglese. Puoi impostare la lingua di partenza nel tokenizer:
-
-```py
->>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
-
->>> en_text = "Do not meddle in the affairs of wizards, for they are subtle and quick to anger."
->>> fi_text = "ĂlĂ€ sekaannu velhojen asioihin, sillĂ€ ne ovat hienovaraisia ja nopeasti vihaisia."
-
->>> tokenizer = AutoTokenizer.from_pretrained("facebook/mbart-large-50-many-to-many-mmt", src_lang="fi_FI")
->>> model = AutoModelForSeq2SeqLM.from_pretrained("facebook/mbart-large-50-many-to-many-mmt")
-```
-
-Applica il tokenizer sul testo:
-
-```py
->>> encoded_en = tokenizer(en_text, return_tensors="pt")
-```
-
-MBart forza l'id della lingua obiettivo come primo token generato per tradurre nella lingua obiettivo. Imposta il parametro `forced_bos_token_id` a `en` nel metodo `generate` per tradurre in inglese:
-
-```py
->>> generated_tokens = model.generate(**encoded_en, forced_bos_token_id=tokenizer.lang_code_to_id("en_XX"))
->>> tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)
-"Don't interfere with the wizard's affairs, because they are subtle, will soon get angry."
-```
-
-Se stai usando il checkpoint `facebook/mbart-large-50-many-to-one-mmt`, non hai bisogno di forzare l'id della lingua obiettivo come primo token generato altrimenti l'uso Ăš lo stesso.
\ No newline at end of file
diff --git a/docs/source/it/perf_hardware.md b/docs/source/it/perf_hardware.md
new file mode 100644
index 000000000000..a579362e2b1b
--- /dev/null
+++ b/docs/source/it/perf_hardware.md
@@ -0,0 +1,155 @@
+
+
+
+# Hardware ottimizzato per l'addestramento
+
+L'hardware utilizzato per eseguire l'addestramento del modello e l'inferenza puĂČ avere un grande effetto sulle prestazioni. Per un analisi approfondita delle GPUs, assicurati di dare un'occhiata all'eccellente [blog post](https://timdettmers.com/2020/09/07/which-gpu-for-deep-learning/) di Tim Dettmer.
+
+Diamo un'occhiata ad alcuni consigli pratici per la configurazione della GPU.
+
+## GPU
+Quando si addestrano modelli piĂč grandi ci sono essenzialmente tre opzioni:
+- GPUs piu' grandi
+- Piu' GPUs
+- Piu' CPU e piu' NVMe (scaricato da [DeepSpeed-Infinity](main_classes/deepspeed#nvme-support))
+
+Iniziamo dal caso in cui ci sia una singola GPU.
+
+### Potenza e Raffreddamento
+
+Se hai acquistato una costosa GPU di fascia alta, assicurati di darle la potenza corretta e un raffreddamento sufficiente.
+
+**Potenza**:
+
+Alcune schede GPU consumer di fascia alta hanno 2 e talvolta 3 prese di alimentazione PCI-E a 8 pin. Assicurati di avere tanti cavi PCI-E a 8 pin indipendenti da 12 V collegati alla scheda quante sono le prese. Non utilizzare le 2 fessure a un'estremitĂ dello stesso cavo (noto anche come cavo a spirale). CioĂš se hai 2 prese sulla GPU, vuoi 2 cavi PCI-E a 8 pin che vanno dall'alimentatore alla scheda e non uno che abbia 2 connettori PCI-E a 8 pin alla fine! In caso contrario, non otterrai tutte le prestazioni ufficiali.
+
+Ciascun cavo di alimentazione PCI-E a 8 pin deve essere collegato a una guida da 12 V sul lato dell'alimentatore e puĂČ fornire fino a 150 W di potenza.
+
+Alcune altre schede possono utilizzare connettori PCI-E a 12 pin e questi possono fornire fino a 500-600 W di potenza.
+
+Le schede di fascia bassa possono utilizzare connettori a 6 pin, che forniscono fino a 75 W di potenza.
+
+Inoltre vuoi un alimentatore (PSU) di fascia alta che abbia una tensione stabile. Alcuni PSU di qualitĂ inferiore potrebbero non fornire alla scheda la tensione stabile di cui ha bisogno per funzionare al massimo.
+
+E ovviamente l'alimentatore deve avere abbastanza Watt inutilizzati per alimentare la scheda.
+
+**Raffreddamento**:
+
+Quando una GPU si surriscalda, inizierĂ a rallentare e non fornirĂ le prestazioni mssimali e potrebbe persino spegnersi se diventasse troppo calda.
+
+Ă difficile dire l'esatta temperatura migliore a cui aspirare quando una GPU Ăš molto caricata, ma probabilmente qualsiasi cosa al di sotto di +80°C va bene, ma piĂč bassa Ăš meglio - forse 70-75°C Ăš un intervallo eccellente in cui trovarsi. Ă probabile che il rallentamento inizi a circa 84-90°C. Ma oltre alla limitazione delle prestazioni, una temperatura molto elevata prolungata Ăš probabile che riduca la durata di una GPU.
+
+Diamo quindi un'occhiata a uno degli aspetti piĂč importanti quando si hanno piĂč GPU: la connettivitĂ .
+
+### ConnettivitĂ multi-GPU
+
+Se utilizzi piĂč GPU, il modo in cui le schede sono interconnesse puĂČ avere un enorme impatto sul tempo totale di allenamento. Se le GPU si trovano sullo stesso nodo fisico, puoi eseguire:
+
+```
+nvidia-smi topo -m
+```
+
+e ti dirĂ come sono interconnesse le GPU. Su una macchina con doppia GPU e collegata a NVLink, molto probabilmente vedrai qualcosa del tipo:
+
+```
+ GPU0 GPU1 CPU Affinity NUMA Affinity
+GPU0 X NV2 0-23 N/A
+GPU1 NV2 X 0-23 N/A
+```
+
+su una macchina diversa senza NVLink potremmo vedere:
+
+```
+ GPU0 GPU1 CPU Affinity NUMA Affinity
+GPU0 X PHB 0-11 N/A
+GPU1 PHB X 0-11 N/A
+```
+
+Il rapporto include questa legenda:
+
+```
+ X = Self
+ SYS = Connection traversing PCIe as well as the SMP interconnect between NUMA nodes (e.g., QPI/UPI)
+ NODE = Connection traversing PCIe as well as the interconnect between PCIe Host Bridges within a NUMA node
+ PHB = Connection traversing PCIe as well as a PCIe Host Bridge (typically the CPU)
+ PXB = Connection traversing multiple PCIe bridges (without traversing the PCIe Host Bridge)
+ PIX = Connection traversing at most a single PCIe bridge
+ NV# = Connection traversing a bonded set of # NVLinks
+```
+
+Quindi il primo rapporto `NV2` ci dice che le GPU sono interconnesse con 2 NVLinks e nel secondo report `PHB` abbiamo una tipica configurazione PCIe+Bridge a livello di consumatore.
+
+Controlla che tipo di connettivitĂ hai sulla tua configurazione. Alcuni di questi renderanno la comunicazione tra le carte piĂč veloce (es. NVLink), altri piĂč lenta (es. PHB).
+
+A seconda del tipo di soluzione di scalabilitĂ utilizzata, la velocitĂ di connettivitĂ potrebbe avere un impatto maggiore o minore. Se le GPU devono sincronizzarsi raramente, come in DDP, l'impatto di una connessione piĂč lenta sarĂ meno significativo. Se le GPU devono scambiarsi messaggi spesso, come in ZeRO-DP, una connettivitĂ piĂč veloce diventa estremamente importante per ottenere un addestramento piĂč veloce.
+
+#### NVlink
+
+[NVLink](https://en.wikipedia.org/wiki/NVLink) Ăš un collegamento di comunicazione a corto raggio multilinea seriale basato su cavo sviluppato da Nvidia.
+
+Ogni nuova generazione fornisce una larghezza di banda piĂč veloce, ad es. ecco una citazione da [Nvidia Ampere GA102 GPU Architecture](https://www.nvidia.com/content/dam/en-zz/Solutions/geforce/ampere/pdf/NVIDIA-ampere-GA102-GPU-Architecture-Whitepaper-V1.pdf):
+
+> Third-Generation NVLinkÂź
+> GA102 GPUs utilize NVIDIAâs third-generation NVLink interface, which includes four x4 links,
+> with each link providing 14.0625 GB/sec bandwidth in each direction between two GPUs. Four
+> links provide 56.25 GB/sec bandwidth in each direction, and 112.5 GB/sec total bandwidth
+> between two GPUs. Two RTX 3090 GPUs can be connected together for SLI using NVLink.
+> (Note that 3-Way and 4-Way SLI configurations are not supported.)
+
+Quindi piĂč `X` si ottiene nel rapporto di `NVX` nell'output di `nvidia-smi topo -m`, meglio Ăš. La generazione dipenderĂ dall'architettura della tua GPU.
+
+Confrontiamo l'esecuzione di un training del modello di linguaggio gpt2 su un piccolo campione di wikitext
+
+I risultati sono:
+
+
+| NVlink | Time |
+| ----- | ---: |
+| Y | 101s |
+| N | 131s |
+
+
+Puoi vedere che NVLink completa l'addestramento circa il 23% piĂč velocemente. Nel secondo benchmark utilizziamo `NCCL_P2P_DISABLE=1` per dire alle GPU di non utilizzare NVLink.
+
+Ecco il codice benchmark completo e gli output:
+
+```bash
+# DDP w/ NVLink
+
+rm -r /tmp/test-clm; CUDA_VISIBLE_DEVICES=0,1 python -m torch.distributed.launch \
+--nproc_per_node 2 examples/pytorch/language-modeling/run_clm.py --model_name_or_path gpt2 \
+--dataset_name wikitext --dataset_config_name wikitext-2-raw-v1 --do_train \
+--output_dir /tmp/test-clm --per_device_train_batch_size 4 --max_steps 200
+
+{'train_runtime': 101.9003, 'train_samples_per_second': 1.963, 'epoch': 0.69}
+
+# DDP w/o NVLink
+
+rm -r /tmp/test-clm; CUDA_VISIBLE_DEVICES=0,1 NCCL_P2P_DISABLE=1 python -m torch.distributed.launch \
+--nproc_per_node 2 examples/pytorch/language-modeling/run_clm.py --model_name_or_path gpt2 \
+--dataset_name wikitext --dataset_config_name wikitext-2-raw-v1 --do_train
+--output_dir /tmp/test-clm --per_device_train_batch_size 4 --max_steps 200
+
+{'train_runtime': 131.4367, 'train_samples_per_second': 1.522, 'epoch': 0.69}
+```
+
+Hardware: 2x TITAN RTX 24GB each + NVlink with 2 NVLinks (`NV2` in `nvidia-smi topo -m`)
+Software: `pytorch-1.8-to-be` + `cuda-11.0` / `transformers==4.3.0.dev0`
\ No newline at end of file
diff --git a/docs/source/it/perf_hardware.mdx b/docs/source/it/perf_hardware.mdx
deleted file mode 100644
index 0bfdbc8fe686..000000000000
--- a/docs/source/it/perf_hardware.mdx
+++ /dev/null
@@ -1,151 +0,0 @@
-
-
-
-# Hardware ottimizzato per l'addestramento
-
-L'hardware utilizzato per eseguire l'addestramento del modello e l'inferenza puĂČ avere un grande effetto sulle prestazioni. Per un analisi approfondita delle GPUs, assicurati di dare un'occhiata all'eccellente [blog post](https://timdettmers.com/2020/09/07/which-gpu-for-deep-learning/) di Tim Dettmer.
-
-Diamo un'occhiata ad alcuni consigli pratici per la configurazione della GPU.
-
-## GPU
-Quando si addestrano modelli piĂč grandi ci sono essenzialmente tre opzioni:
-- GPUs piu' grandi
-- Piu' GPUs
-- Piu' CPU e piu' NVMe (scaricato da [DeepSpeed-Infinity](main_classes/deepspeed#nvme-support))
-
-Iniziamo dal caso in cui ci sia una singola GPU.
-
-### Potenza e Raffreddamento
-
-Se hai acquistato una costosa GPU di fascia alta, assicurati di darle la potenza corretta e un raffreddamento sufficiente.
-
-**Potenza**:
-
-Alcune schede GPU consumer di fascia alta hanno 2 e talvolta 3 prese di alimentazione PCI-E a 8 pin. Assicurati di avere tanti cavi PCI-E a 8 pin indipendenti da 12 V collegati alla scheda quante sono le prese. Non utilizzare le 2 fessure a un'estremitĂ dello stesso cavo (noto anche come cavo a spirale). CioĂš se hai 2 prese sulla GPU, vuoi 2 cavi PCI-E a 8 pin che vanno dall'alimentatore alla scheda e non uno che abbia 2 connettori PCI-E a 8 pin alla fine! In caso contrario, non otterrai tutte le prestazioni ufficiali.
-
-Ciascun cavo di alimentazione PCI-E a 8 pin deve essere collegato a una guida da 12 V sul lato dell'alimentatore e puĂČ fornire fino a 150 W di potenza.
-
-Alcune altre schede possono utilizzare connettori PCI-E a 12 pin e questi possono fornire fino a 500-600 W di potenza.
-
-Le schede di fascia bassa possono utilizzare connettori a 6 pin, che forniscono fino a 75 W di potenza.
-
-Inoltre vuoi un alimentatore (PSU) di fascia alta che abbia una tensione stabile. Alcuni PSU di qualitĂ inferiore potrebbero non fornire alla scheda la tensione stabile di cui ha bisogno per funzionare al massimo.
-
-E ovviamente l'alimentatore deve avere abbastanza Watt inutilizzati per alimentare la scheda.
-
-**Raffreddamento**:
-
-Quando una GPU si surriscalda, inizierĂ a rallentare e non fornirĂ le prestazioni mssimali e potrebbe persino spegnersi se diventasse troppo calda.
-
-Ă difficile dire l'esatta temperatura migliore a cui aspirare quando una GPU Ăš molto caricata, ma probabilmente qualsiasi cosa al di sotto di +80°C va bene, ma piĂč bassa Ăš meglio - forse 70-75°C Ăš un intervallo eccellente in cui trovarsi. Ă probabile che il rallentamento inizi a circa 84-90°C. Ma oltre alla limitazione delle prestazioni, una temperatura molto elevata prolungata Ăš probabile che riduca la durata di una GPU.
-
-Diamo quindi un'occhiata a uno degli aspetti piĂč importanti quando si hanno piĂč GPU: la connettivitĂ .
-
-### ConnettivitĂ multi-GPU
-
-Se utilizzi piĂč GPU, il modo in cui le schede sono interconnesse puĂČ avere un enorme impatto sul tempo totale di allenamento. Se le GPU si trovano sullo stesso nodo fisico, puoi eseguire:
-
-```
-nvidia-smi topo -m
-```
-
-e ti dirĂ come sono interconnesse le GPU. Su una macchina con doppia GPU e collegata a NVLink, molto probabilmente vedrai qualcosa del tipo:
-
-```
- GPU0 GPU1 CPU Affinity NUMA Affinity
-GPU0 X NV2 0-23 N/A
-GPU1 NV2 X 0-23 N/A
-```
-
-su una macchina diversa senza NVLink potremmo vedere:
-
-```
- GPU0 GPU1 CPU Affinity NUMA Affinity
-GPU0 X PHB 0-11 N/A
-GPU1 PHB X 0-11 N/A
-```
-
-Il rapporto include questa legenda:
-
-```
- X = Self
- SYS = Connection traversing PCIe as well as the SMP interconnect between NUMA nodes (e.g., QPI/UPI)
- NODE = Connection traversing PCIe as well as the interconnect between PCIe Host Bridges within a NUMA node
- PHB = Connection traversing PCIe as well as a PCIe Host Bridge (typically the CPU)
- PXB = Connection traversing multiple PCIe bridges (without traversing the PCIe Host Bridge)
- PIX = Connection traversing at most a single PCIe bridge
- NV# = Connection traversing a bonded set of # NVLinks
-```
-
-Quindi il primo rapporto `NV2` ci dice che le GPU sono interconnesse con 2 NVLinks e nel secondo report `PHB` abbiamo una tipica configurazione PCIe+Bridge a livello di consumatore.
-
-Controlla che tipo di connettivitĂ hai sulla tua configurazione. Alcuni di questi renderanno la comunicazione tra le carte piĂč veloce (es. NVLink), altri piĂč lenta (es. PHB).
-
-A seconda del tipo di soluzione di scalabilitĂ utilizzata, la velocitĂ di connettivitĂ potrebbe avere un impatto maggiore o minore. Se le GPU devono sincronizzarsi raramente, come in DDP, l'impatto di una connessione piĂč lenta sarĂ meno significativo. Se le GPU devono scambiarsi messaggi spesso, come in ZeRO-DP, una connettivitĂ piĂč veloce diventa estremamente importante per ottenere un addestramento piĂč veloce.
-
-#### NVlink
-
-[NVLink](https://en.wikipedia.org/wiki/NVLink) Ăš un collegamento di comunicazione a corto raggio multilinea seriale basato su cavo sviluppato da Nvidia.
-
-Ogni nuova generazione fornisce una larghezza di banda piĂč veloce, ad es. ecco una citazione da [Nvidia Ampere GA102 GPU Architecture](https://www.nvidia.com/content/dam/en-zz/Solutions/geforce/ampere/pdf/NVIDIA-ampere-GA102-GPU-Architecture-Whitepaper-V1.pdf):
-
-> Third-Generation NVLinkÂź
-> GA102 GPUs utilize NVIDIAâs third-generation NVLink interface, which includes four x4 links,
-> with each link providing 14.0625 GB/sec bandwidth in each direction between two GPUs. Four
-> links provide 56.25 GB/sec bandwidth in each direction, and 112.5 GB/sec total bandwidth
-> between two GPUs. Two RTX 3090 GPUs can be connected together for SLI using NVLink.
-> (Note that 3-Way and 4-Way SLI configurations are not supported.)
-
-Quindi piĂč `X` si ottiene nel rapporto di `NVX` nell'output di `nvidia-smi topo -m`, meglio Ăš. La generazione dipenderĂ dall'architettura della tua GPU.
-
-Confrontiamo l'esecuzione di un training del modello di linguaggio gpt2 su un piccolo campione di wikitext
-
-I risultati sono:
-
-
-| NVlink | Time |
-| ----- | ---: |
-| Y | 101s |
-| N | 131s |
-
-
-Puoi vedere che NVLink completa l'addestramento circa il 23% piĂč velocemente. Nel secondo benchmark utilizziamo `NCCL_P2P_DISABLE=1` per dire alle GPU di non utilizzare NVLink.
-
-Ecco il codice benchmark completo e gli output:
-
-```bash
-# DDP w/ NVLink
-
-rm -r /tmp/test-clm; CUDA_VISIBLE_DEVICES=0,1 python -m torch.distributed.launch \
---nproc_per_node 2 examples/pytorch/language-modeling/run_clm.py --model_name_or_path gpt2 \
---dataset_name wikitext --dataset_config_name wikitext-2-raw-v1 --do_train \
---output_dir /tmp/test-clm --per_device_train_batch_size 4 --max_steps 200
-
-{'train_runtime': 101.9003, 'train_samples_per_second': 1.963, 'epoch': 0.69}
-
-# DDP w/o NVLink
-
-rm -r /tmp/test-clm; CUDA_VISIBLE_DEVICES=0,1 NCCL_P2P_DISABLE=1 python -m torch.distributed.launch \
---nproc_per_node 2 examples/pytorch/language-modeling/run_clm.py --model_name_or_path gpt2 \
---dataset_name wikitext --dataset_config_name wikitext-2-raw-v1 --do_train
---output_dir /tmp/test-clm --per_device_train_batch_size 4 --max_steps 200
-
-{'train_runtime': 131.4367, 'train_samples_per_second': 1.522, 'epoch': 0.69}
-```
-
-Hardware: 2x TITAN RTX 24GB each + NVlink with 2 NVLinks (`NV2` in `nvidia-smi topo -m`)
-Software: `pytorch-1.8-to-be` + `cuda-11.0` / `transformers==4.3.0.dev0`
\ No newline at end of file
diff --git a/docs/source/it/perf_infer_cpu.md b/docs/source/it/perf_infer_cpu.md
new file mode 100644
index 000000000000..baae51a5a978
--- /dev/null
+++ b/docs/source/it/perf_infer_cpu.md
@@ -0,0 +1,79 @@
+
+
+# Inferenza Efficiente su CPU
+
+Questa guida si concentra sull'inferenza di modelli di grandi dimensioni in modo efficiente sulla CPU.
+
+## `BetterTransformer` per inferenza piĂč rapida
+
+Abbiamo integrato di recente `BetterTransformer` per fare inferenza piĂč rapidamente con modelli per testi, immagini e audio. Visualizza la documentazione sull'integrazione [qui](https://huggingface.co/docs/optimum/bettertransformer/overview) per maggiori dettagli.
+
+## PyTorch JIT-mode (TorchScript)
+
+TorchScript Ăš un modo di creare modelli serializzabili e ottimizzabili da codice PyTorch. Ogni programmma TorchScript puĂČ esere salvato da un processo Python e caricato in un processo dove non ci sono dipendenze Python.
+Comparandolo con l'eager mode di default, jit mode in PyTorch normalmente fornisce prestazioni migliori per l'inferenza del modello da parte di metodologie di ottimizzazione come la operator fusion.
+
+Per una prima introduzione a TorchScript, vedi la Introduction to [PyTorch TorchScript tutorial](https://pytorch.org/tutorials/beginner/Intro_to_TorchScript_tutorial.html#tracing-modules).
+
+### IPEX Graph Optimization con JIT-mode
+
+IntelÂź Extension per PyTorch fornnisce ulteriori ottimizzazioni in jit mode per i modelli della serie Transformers. Consigliamo vivamente agli utenti di usufruire dei vantaggi di IntelÂź Extension per PyTorch con jit mode. Alcuni operator patterns usati fequentemente dai modelli Transformers models sono giĂ supportati in IntelÂź Extension per PyTorch con jit mode fusions. Questi fusion patterns come Multi-head-attention fusion, Concat Linear, Linear+Add, Linear+Gelu, Add+LayerNorm fusion and etc. sono abilitati e hanno buone performance. I benefici della fusion Ăš fornito agli utenti in modo trasparente. In base alle analisi, il ~70% dei problemi piĂč popolari in NLP question-answering, text-classification, and token-classification possono avere benefici sulle performance grazie ai fusion patterns sia per Float32 precision che per BFloat16 Mixed precision.
+
+Vedi maggiori informazioni per [IPEX Graph Optimization](https://intel.github.io/intel-extension-for-pytorch/cpu/latest/tutorials/features/graph_optimization.html).
+
+#### Installazione di IPEX
+
+I rilasci di IPEX seguono PyTorch, verifica i vari approcci per [IPEX installation](https://intel.github.io/intel-extension-for-pytorch/).
+
+### Utilizzo del JIT-mode
+
+Per abilitare JIT-mode in Trainer per evaluation e prediction, devi aggiungere `jit_mode_eval` negli argomenti di Trainer.
+
+
+
+per PyTorch >= 1.14.0. JIT-mode potrebe giovare a qualsiasi modello di prediction e evaluaion visto che il dict input Ăš supportato in jit.trace
+
+per PyTorch < 1.14.0. JIT-mode potrebbe giovare ai modelli il cui ordine dei parametri corrisponde all'ordine delle tuple in ingresso in jit.trace, come i modelli per question-answering.
+Nel caso in cui l'ordine dei parametri seguenti non corrisponda all'ordine delle tuple in ingresso in jit.trace, come nei modelli di text-classification, jit.trace fallirĂ e lo cattureremo con una eccezione al fine di renderlo un fallback. Il logging Ăš usato per notificare gli utenti.
+
+
+
+Trovi un esempo con caso d'uso in [Transformers question-answering](https://github.com/huggingface/transformers/tree/main/examples/pytorch/question-answering)
+
+- Inference using jit mode on CPU:
+
+python run_qa.py \
+--model_name_or_path csarron/bert-base-uncased-squad-v1 \
+--dataset_name squad \
+--do_eval \
+--max_seq_length 384 \
+--doc_stride 128 \
+--output_dir /tmp/ \
+--no_cuda \
+--jit_mode_eval
+
+- Inference with IPEX using jit mode on CPU:
+
+python run_qa.py \
+--model_name_or_path csarron/bert-base-uncased-squad-v1 \
+--dataset_name squad \
+--do_eval \
+--max_seq_length 384 \
+--doc_stride 128 \
+--output_dir /tmp/ \
+--no_cuda \
+--use_ipex \
+--jit_mode_eval
diff --git a/docs/source/it/perf_infer_cpu.mdx b/docs/source/it/perf_infer_cpu.mdx
deleted file mode 100644
index 1423b8f0552c..000000000000
--- a/docs/source/it/perf_infer_cpu.mdx
+++ /dev/null
@@ -1,75 +0,0 @@
-
-
-# Inferenza Efficiente su CPU
-
-Questa guida si concentra sull'inferenza di modelli di grandi dimensioni in modo efficiente sulla CPU.
-
-## `BetterTransformer` per inferenza piĂč rapida
-
-Abbiamo integrato di recente `BetterTransformer` per fare inferenza piĂč rapidamente con modelli per testi, immagini e audio. Visualizza la documentazione sull'integrazione [qui](https://huggingface.co/docs/optimum/bettertransformer/overview) per maggiori dettagli.
-
-## PyTorch JIT-mode (TorchScript)
-
-TorchScript Ăš un modo di creare modelli serializzabili e ottimizzabili da codice PyTorch. Ogni programmma TorchScript puĂČ esere salvato da un processo Python e caricato in un processo dove non ci sono dipendenze Python.
-Comparandolo con l'eager mode di default, jit mode in PyTorch normalmente fornisce prestazioni migliori per l'inferenza del modello da parte di metodologie di ottimizzazione come la operator fusion.
-
-Per una prima introduzione a TorchScript, vedi la Introduction to [PyTorch TorchScript tutorial](https://pytorch.org/tutorials/beginner/Intro_to_TorchScript_tutorial.html#tracing-modules).
-
-### IPEX Graph Optimization con JIT-mode
-
-IntelÂź Extension per PyTorch fornnisce ulteriori ottimizzazioni in jit mode per i modelli della serie Transformers. Consigliamo vivamente agli utenti di usufruire dei vantaggi di IntelÂź Extension per PyTorch con jit mode. Alcuni operator patterns usati fequentemente dai modelli Transformers models sono giĂ supportati in IntelÂź Extension per PyTorch con jit mode fusions. Questi fusion patterns come Multi-head-attention fusion, Concat Linear, Linear+Add, Linear+Gelu, Add+LayerNorm fusion and etc. sono abilitati e hanno buone performance. I benefici della fusion Ăš fornito agli utenti in modo trasparente. In base alle analisi, il ~70% dei problemi piĂč popolari in NLP question-answering, text-classification, and token-classification possono avere benefici sulle performance grazie ai fusion patterns sia per Float32 precision che per BFloat16 Mixed precision.
-
-Vedi maggiori informazioni per [IPEX Graph Optimization](https://intel.github.io/intel-extension-for-pytorch/cpu/latest/tutorials/features/graph_optimization.html).
-
-#### Installazione di IPEX
-
-I rilasci di IPEX seguono PyTorch, verifica i vari approcci per [IPEX installation](https://intel.github.io/intel-extension-for-pytorch/).
-
-### Utilizzo del JIT-mode
-
-Per abilitare JIT-mode in Trainer per evaluation e prediction, devi aggiungere `jit_mode_eval` negli argomenti di Trainer.
-
-
-
-per PyTorch >= 1.14.0. JIT-mode potrebe giovare a qualsiasi modello di prediction e evaluaion visto che il dict input Ăš supportato in jit.trace
-
-per PyTorch < 1.14.0. JIT-mode potrebbe giovare ai modelli il cui ordine dei parametri corrisponde all'ordine delle tuple in ingresso in jit.trace, come i modelli per question-answering.
-Nel caso in cui l'ordine dei parametri seguenti non corrisponda all'ordine delle tuple in ingresso in jit.trace, come nei modelli di text-classification, jit.trace fallirĂ e lo cattureremo con una eccezione al fine di renderlo un fallback. Il logging Ăš usato per notificare gli utenti.
-
-
-
-Trovi un esempo con caso d'uso in [Transformers question-answering](https://github.com/huggingface/transformers/tree/main/examples/pytorch/question-answering)
-
-- Inference using jit mode on CPU:
-
-python run_qa.py \
---model_name_or_path csarron/bert-base-uncased-squad-v1 \
---dataset_name squad \
---do_eval \
---max_seq_length 384 \
---doc_stride 128 \
---output_dir /tmp/ \
---no_cuda \
---jit_mode_eval
-
-- Inference with IPEX using jit mode on CPU:
-
-python run_qa.py \
---model_name_or_path csarron/bert-base-uncased-squad-v1 \
---dataset_name squad \
---do_eval \
---max_seq_length 384 \
---doc_stride 128 \
---output_dir /tmp/ \
---no_cuda \
---use_ipex \
---jit_mode_eval
diff --git a/docs/source/it/perf_infer_gpu_many.md b/docs/source/it/perf_infer_gpu_many.md
new file mode 100644
index 000000000000..b78cb34e1d6d
--- /dev/null
+++ b/docs/source/it/perf_infer_gpu_many.md
@@ -0,0 +1,28 @@
+
+
+# Inferenza Efficiente su GPU Multiple
+
+Questo documento contiene informazioni su come fare inferenza in maniera efficiente su GPU multiple.
+
+
+
+Nota: Un setup con GPU multiple puĂČ utilizzare la maggior parte delle strategie descritte nella [sezione con GPU singola](./perf_infer_gpu_one). Tuttavia, Ăš necessario conoscere delle tecniche semplici che possono essere utilizzate per un risultato migliore.
+
+
+
+## `BetterTransformer` per inferenza piĂč rapida
+
+Abbiamo recentemente integrato `BetterTransformer` per inferenza piĂč rapida su multi-GPU per modelli su testo, immagini e audio. Controlla il documento con queste integrazioni [qui](https://huggingface.co/docs/optimum/bettertransformer/overview) per maggiori dettagli.
diff --git a/docs/source/it/perf_infer_gpu_many.mdx b/docs/source/it/perf_infer_gpu_many.mdx
deleted file mode 100644
index 5eeefa907dd6..000000000000
--- a/docs/source/it/perf_infer_gpu_many.mdx
+++ /dev/null
@@ -1,24 +0,0 @@
-
-
-# Inferenza Efficiente su GPU Multiple
-
-Questo documento contiene informazioni su come fare inferenza in maniera efficiente su GPU multiple.
-
-
-
-Nota: Un setup con GPU multiple puĂČ utilizzare la maggior parte delle strategie descritte nella [sezione con GPU singola](./perf_infer_gpu_one). Tuttavia, Ăš necessario conoscere delle tecniche semplici che possono essere utilizzate per un risultato migliore.
-
-
-
-## `BetterTransformer` per inferenza piĂč rapida
-
-Abbiamo recentemente integrato `BetterTransformer` per inferenza piĂč rapida su multi-GPU per modelli su testo, immagini e audio. Controlla il documento con queste integrazioni [qui](https://huggingface.co/docs/optimum/bettertransformer/overview) per maggiori dettagli.
diff --git a/docs/source/it/perf_infer_gpu_one.md b/docs/source/it/perf_infer_gpu_one.md
new file mode 100644
index 000000000000..9acbed1d0f27
--- /dev/null
+++ b/docs/source/it/perf_infer_gpu_one.md
@@ -0,0 +1,112 @@
+
+
+# Inferenza efficiente su GPU singola
+
+Questo documento sarĂ presto completato con informazioni su come effetture l'inferenza su una singola GPU. Nel frattempo Ăš possibile consultare [la guida per l'addestramento su una singola GPU](perf_train_gpu_one) e [la guida per l'inferenza su CPU](perf_infer_cpu).
+
+## `BetterTransformer` per l'inferenza piĂč veloce
+
+Abbiamo recentemente integrato `BetterTransformer` per velocizzare l'inferenza su GPU per modelli di testo, immagini e audio. Per maggiori dettagli, consultare la documentazione su questa integrazione [qui](https://huggingface.co/docs/optimum/bettertransformer/overview).
+
+## Integrazione di `bitsandbytes` per Int8 mixed-precision matrix decomposition
+
+
+
+Nota che questa funzione puĂČ essere utilizzata anche nelle configurazioni multi GPU.
+
+
+
+Dal paper [`LLM.int8() : 8-bit Matrix Multiplication for Transformers at Scale`](https://arxiv.org/abs/2208.07339), noi supportiamo l'integrazione di Hugging Face per tutti i modelli dell'Hub con poche righe di codice.
+Il metodo `nn.Linear` riduce la dimensione di 2 per i pesi `float16` e `bfloat16` e di 4 per i pesi `float32`, con un impatto quasi nullo sulla qualitĂ , operando sugli outlier in half-precision.
+
+
+
+Il metodo Int8 mixed-precision matrix decomposition funziona separando la moltiplicazione tra matrici in due flussi: (1) una matrice di flusso di outlier di caratteristiche sistematiche moltiplicata in fp16, (2) in flusso regolare di moltiplicazione di matrici int8 (99,9%). Con questo metodo, Ăš possibile effettutare inferenza int8 per modelli molto grandi senza degrado predittivo.
+Per maggiori dettagli sul metodo, consultare il [paper](https://arxiv.org/abs/2208.07339) o il nostro [blogpost sull'integrazione](https://huggingface.co/blog/hf-bitsandbytes-integration).
+
+
+
+Nota che Ú necessaria una GPU per eseguire modelli di tipo mixed-8bit, poiché i kernel sono stati compilati solo per le GPU. Prima di utilizzare questa funzione, assicurarsi di disporre di memoria sufficiente sulla GPU per memorizzare un quarto del modello (o la metà se i pesi del modello sono in mezza precisione).
+Di seguito sono riportate alcune note per aiutarvi a utilizzare questo modulo, oppure seguite le dimostrazioni su [Google colab](#colab-demos).
+
+### Requisiti
+
+- Se si dispone di `bitsandbytes<0.37.0`, assicurarsi di eseguire su GPU NVIDIA che supportano tensor cores a 8 bit (Turing, Ampere o architetture piĂč recenti - ad esempio T4, RTX20s RTX30s, A40-A100). Per `bitsandbytes>=0.37.0`, tutte le GPU dovrebbero essere supportate.
+- Installare la versione corretta di `bitsandbytes` eseguendo:
+`pip install bitsandbytes>=0.31.5`.
+- Installare `accelerate`
+`pip install accelerate>=0.12.0`
+
+### Esecuzione di modelli mixed-Int8 - configurazione per singola GPU
+
+Dopo aver installato le librerie necessarie, per caricare il tuo modello mixed 8-bit Ăš il seguente:
+
+```py
+from transformers import AutoModelForCausalLM
+
+model_name = "bigscience/bloom-2b5"
+model_8bit = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto", load_in_8bit=True)
+```
+
+Per la generazione di testo, si consiglia di:
+
+* utilizzare il metodo `generate()` del modello invece della funzione `pipeline()`. Sebbene l'inferenza sia possibile con la funzione `pipeline()`, essa non Ăš ottimizzata per i modelli mixed-8bit e sarĂ piĂč lenta rispetto all'uso del metodo `generate()`. Inoltre, alcune strategie di campionamento, come il campionamento nucleaus, non sono supportate dalla funzione `pipeline()` per i modelli mixed-8bit.
+* collocare tutti gli ingressi sullo stesso dispositivo del modello.
+
+Ecco un semplice esempio:
+
+```py
+from transformers import AutoModelForCausalLM, AutoTokenizer
+
+model_name = "bigscience/bloom-2b5"
+tokenizer = AutoTokenizer.from_pretrained(model_name)
+model_8bit = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto", load_in_8bit=True)
+
+text = "Hello, my llama is cute"
+inputs = tokenizer(prompt, return_tensors="pt").to("cuda")
+generated_ids = model.generate(**inputs)
+outputs = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
+```
+
+
+### Esecuzione di modelli mixed-8bit - configurazione multi GPU
+
+Usare il seguente modo caricare il modello mixed-8bit su piĂč GPU (stesso comando della configurazione a GPU singola):
+```py
+model_name = "bigscience/bloom-2b5"
+model_8bit = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto", load_in_8bit=True)
+```
+Puoi controllare la RAM della GPU che si vuole allocare su ogni GPU usando `accelerate`. Utilizzare l'argomento `max_memory` come segue:
+
+```py
+max_memory_mapping = {0: "1GB", 1: "2GB"}
+model_name = "bigscience/bloom-3b"
+model_8bit = AutoModelForCausalLM.from_pretrained(
+ model_name, device_map="auto", load_in_8bit=True, max_memory=max_memory_mapping
+)
+```
+In questo esempio, la prima GPU utilizzerĂ 1 GB di memoria e la seconda 2 GB.
+
+### Colab demos
+
+Con questo metodo Ăš possibile inferire modelli che prima non era possibile inferire su Google Colab.
+Guardate la demo per l'esecuzione di T5-11b (42GB in fp32)! Utilizzo la quantizzazione a 8 bit su Google Colab:
+
+[](https://colab.research.google.com/drive/1YORPWx4okIHXnjW7MSAidXN29mPVNT7F?usp=sharing)
+
+Oppure questa demo di BLOOM-3B:
+
+[](https://colab.research.google.com/drive/1qOjXfQIAULfKvZqwCen8-MoWKGdSatZ4?usp=sharing)
\ No newline at end of file
diff --git a/docs/source/it/perf_infer_gpu_one.mdx b/docs/source/it/perf_infer_gpu_one.mdx
deleted file mode 100644
index 60df05515351..000000000000
--- a/docs/source/it/perf_infer_gpu_one.mdx
+++ /dev/null
@@ -1,108 +0,0 @@
-
-
-# Inferenza efficiente su GPU singola
-
-Questo documento sarĂ presto completato con informazioni su come effetture l'inferenza su una singola GPU. Nel frattempo Ăš possibile consultare [la guida per l'addestramento su una singola GPU](perf_train_gpu_one) e [la guida per l'inferenza su CPU](perf_infer_cpu).
-
-## `BetterTransformer` per l'inferenza piĂč veloce
-
-Abbiamo recentemente integrato `BetterTransformer` per velocizzare l'inferenza su GPU per modelli di testo, immagini e audio. Per maggiori dettagli, consultare la documentazione su questa integrazione [qui](https://huggingface.co/docs/optimum/bettertransformer/overview).
-
-## Integrazione di `bitsandbytes` per Int8 mixed-precision matrix decomposition
-
-
-
-Nota che questa funzione puĂČ essere utilizzata anche nelle configurazioni multi GPU.
-
-
-
-Dal paper [`LLM.int8() : 8-bit Matrix Multiplication for Transformers at Scale`](https://arxiv.org/abs/2208.07339), noi supportiamo l'integrazione di Hugging Face per tutti i modelli dell'Hub con poche righe di codice.
-Il metodo `nn.Linear` riduce la dimensione di 2 per i pesi `float16` e `bfloat16` e di 4 per i pesi `float32`, con un impatto quasi nullo sulla qualitĂ , operando sugli outlier in half-precision.
-
-
-
-Il metodo Int8 mixed-precision matrix decomposition funziona separando la moltiplicazione tra matrici in due flussi: (1) una matrice di flusso di outlier di caratteristiche sistematiche moltiplicata in fp16, (2) in flusso regolare di moltiplicazione di matrici int8 (99,9%). Con questo metodo, Ăš possibile effettutare inferenza int8 per modelli molto grandi senza degrado predittivo.
-Per maggiori dettagli sul metodo, consultare il [paper](https://arxiv.org/abs/2208.07339) o il nostro [blogpost sull'integrazione](https://huggingface.co/blog/hf-bitsandbytes-integration).
-
-
-
-Nota che Ú necessaria una GPU per eseguire modelli di tipo mixed-8bit, poiché i kernel sono stati compilati solo per le GPU. Prima di utilizzare questa funzione, assicurarsi di disporre di memoria sufficiente sulla GPU per memorizzare un quarto del modello (o la metà se i pesi del modello sono in mezza precisione).
-Di seguito sono riportate alcune note per aiutarvi a utilizzare questo modulo, oppure seguite le dimostrazioni su [Google colab](#colab-demos).
-
-### Requisiti
-
-- Se si dispone di `bitsandbytes<0.37.0`, assicurarsi di eseguire su GPU NVIDIA che supportano tensor cores a 8 bit (Turing, Ampere o architetture piĂč recenti - ad esempio T4, RTX20s RTX30s, A40-A100). Per `bitsandbytes>=0.37.0`, tutte le GPU dovrebbero essere supportate.
-- Installare la versione corretta di `bitsandbytes` eseguendo:
-`pip install bitsandbytes>=0.31.5`.
-- Installare `accelerate`
-`pip install accelerate>=0.12.0`
-
-### Esecuzione di modelli mixed-Int8 - configurazione per singola GPU
-
-Dopo aver installato le librerie necessarie, per caricare il tuo modello mixed 8-bit Ăš il seguente:
-
-```py
-from transformers import AutoModelForCausalLM
-
-model_name = "bigscience/bloom-2b5"
-model_8bit = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto", load_in_8bit=True)
-```
-
-Per la generazione di testo, si consiglia di:
-
-* utilizzare il metodo `generate()` del modello invece della funzione `pipeline()`. Sebbene l'inferenza sia possibile con la funzione `pipeline()`, essa non Ăš ottimizzata per i modelli mixed-8bit e sarĂ piĂč lenta rispetto all'uso del metodo `generate()`. Inoltre, alcune strategie di campionamento, come il campionamento nucleaus, non sono supportate dalla funzione `pipeline()` per i modelli mixed-8bit.
-* collocare tutti gli ingressi sullo stesso dispositivo del modello.
-
-Ecco un semplice esempio:
-
-```py
-from transformers import AutoModelForCausalLM, AutoTokenizer
-
-model_name = "bigscience/bloom-2b5"
-tokenizer = AutoTokenizer.from_pretrained(model_name)
-model_8bit = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto", load_in_8bit=True)
-
-text = "Hello, my llama is cute"
-inputs = tokenizer(prompt, return_tensors="pt").to("cuda")
-generated_ids = model.generate(**inputs)
-outputs = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
-```
-
-
-### Esecuzione di modelli mixed-8bit - configurazione multi GPU
-
-Usare il seguente modo caricare il modello mixed-8bit su piĂč GPU (stesso comando della configurazione a GPU singola):
-```py
-model_name = "bigscience/bloom-2b5"
-model_8bit = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto", load_in_8bit=True)
-```
-Puoi controllare la RAM della GPU che si vuole allocare su ogni GPU usando `accelerate`. Utilizzare l'argomento `max_memory` come segue:
-
-```py
-max_memory_mapping = {0: "1GB", 1: "2GB"}
-model_name = "bigscience/bloom-3b"
-model_8bit = AutoModelForCausalLM.from_pretrained(
- model_name, device_map="auto", load_in_8bit=True, max_memory=max_memory_mapping
-)
-```
-In questo esempio, la prima GPU utilizzerĂ 1 GB di memoria e la seconda 2 GB.
-
-### Colab demos
-
-Con questo metodo Ăš possibile inferire modelli che prima non era possibile inferire su Google Colab.
-Guardate la demo per l'esecuzione di T5-11b (42GB in fp32)! Utilizzo la quantizzazione a 8 bit su Google Colab:
-
-[](https://colab.research.google.com/drive/1YORPWx4okIHXnjW7MSAidXN29mPVNT7F?usp=sharing)
-
-Oppure questa demo di BLOOM-3B:
-
-[](https://colab.research.google.com/drive/1qOjXfQIAULfKvZqwCen8-MoWKGdSatZ4?usp=sharing)
\ No newline at end of file
diff --git a/docs/source/it/perf_infer_special.md b/docs/source/it/perf_infer_special.md
new file mode 100644
index 000000000000..3e2c0a5c288e
--- /dev/null
+++ b/docs/source/it/perf_infer_special.md
@@ -0,0 +1,18 @@
+
+
+# Inferenza su Hardware Specializzato
+
+Questo documento sarĂ completato a breve con la documentazione per l'inferenza su hardware specializzato. Nel frattempo puoi controllare [la guida per fare inferenza sulle CPU](perf_infer_cpu).
\ No newline at end of file
diff --git a/docs/source/it/perf_infer_special.mdx b/docs/source/it/perf_infer_special.mdx
deleted file mode 100644
index 1e92190d192c..000000000000
--- a/docs/source/it/perf_infer_special.mdx
+++ /dev/null
@@ -1,14 +0,0 @@
-
-
-# Inferenza su Hardware Specializzato
-
-Questo documento sarĂ completato a breve con la documentazione per l'inferenza su hardware specializzato. Nel frattempo puoi controllare [la guida per fare inferenza sulle CPU](perf_infer_cpu).
\ No newline at end of file
diff --git a/docs/source/it/perf_train_cpu.md b/docs/source/it/perf_train_cpu.md
new file mode 100644
index 000000000000..c91baeec8800
--- /dev/null
+++ b/docs/source/it/perf_train_cpu.md
@@ -0,0 +1,69 @@
+
+
+# Addestramento efficiente su CPU
+
+Questa guida si concentra su come addestrare in maniera efficiente grandi modelli su CPU.
+
+## Mixed precision con IPEX
+
+IPEX Ăš ottimizzato per CPU con AVX-512 o superiore, e funziona per le CPU con solo AVX2. Pertanto, si prevede che le prestazioni saranno piĂč vantaggiose per le le CPU Intel con AVX-512 o superiori, mentre le CPU con solo AVX2 (ad esempio, le CPU AMD o le CPU Intel piĂč vecchie) potrebbero ottenere prestazioni migliori con IPEX, ma non sono garantite. IPEX offre ottimizzazioni delle prestazioni per l'addestramento della CPU sia con Float32 che con BFloat16. L'uso di BFloat16 Ăš l'argomento principale delle seguenti sezioni.
+
+Il tipo di dati a bassa precisione BFloat16 Ăš stato supportato in modo nativo su 3rd Generation XeonÂź Scalable Processors (aka Cooper Lake) con AVX512 e sarĂ supportata dalla prossima generazione di IntelÂź XeonÂź Scalable Processors con IntelÂź Advanced Matrix Extensions (IntelÂź AMX) instruction set con prestazioni ulteriormente migliorate. L'Auto Mixed Precision per il backende della CPU Ăš stato abilitato da PyTorch-1.10. allo stesso tempo, il supporto di Auto Mixed Precision con BFloat16 per CPU e l'ottimizzazione degli operatori BFloat16 Ăš stata abilitata in modo massiccio in IntelÂź Extension per PyTorch, and parzialmente aggiornato al branch master di PyTorch. Gli utenti possono ottenere prestazioni migliori ed users experience con IPEX Auto Mixed Precision..
+
+Vedi informazioni piĂč dettagliate su [Auto Mixed Precision](https://intel.github.io/intel-extension-for-pytorch/cpu/latest/tutorials/features/amp.html).
+
+### Installazione di IPEX:
+
+Il rilascio di IPEX segue quello di PyTorch, da installare via pip:
+
+| PyTorch Version | IPEX version |
+| :---------------: | :----------: |
+| 1.13 | 1.13.0+cpu |
+| 1.12 | 1.12.300+cpu |
+| 1.11 | 1.11.200+cpu |
+| 1.10 | 1.10.100+cpu |
+
+```bash
+pip install intel_extension_for_pytorch== -f https://developer.intel.com/ipex-whl-stable-cpu
+```
+
+Vedi altri approcci per [IPEX installation](https://intel.github.io/intel-extension-for-pytorch/cpu/latest/tutorials/installation.html).
+
+### Utilizzo nel Trainer
+
+Per abilitare la auto mixed precision con IPEX in Trainer, l'utende dovrebbe aggiungere `use_ipex`, `bf16` e `no_cuda` negli argomenti del comando di addestramento.
+
+Vedi un sempio di un caso d'uso [Transformers question-answering](https://github.com/huggingface/transformers/tree/main/examples/pytorch/question-answering)
+
+- Training with IPEX using BF16 auto mixed precision on CPU:
+
+ python run_qa.py \
+--model_name_or_path bert-base-uncased \
+--dataset_name squad \
+--do_train \
+--do_eval \
+--per_device_train_batch_size 12 \
+--learning_rate 3e-5 \
+--num_train_epochs 2 \
+--max_seq_length 384 \
+--doc_stride 128 \
+--output_dir /tmp/debug_squad/ \
+--use_ipex \
+--bf16 --no_cuda
+
+### Esempi pratici
+
+Blog: [Accelerating PyTorch Transformers with Intel Sapphire Rapids](https://huggingface.co/blog/intel-sapphire-rapids)
diff --git a/docs/source/it/perf_train_cpu.mdx b/docs/source/it/perf_train_cpu.mdx
deleted file mode 100644
index bf9b265ba301..000000000000
--- a/docs/source/it/perf_train_cpu.mdx
+++ /dev/null
@@ -1,65 +0,0 @@
-
-
-# Addestramento efficiente su CPU
-
-Questa guida si concentra su come addestrare in maniera efficiente grandi modelli su CPU.
-
-## Mixed precision con IPEX
-
-IPEX Ăš ottimizzato per CPU con AVX-512 o superiore, e funziona per le CPU con solo AVX2. Pertanto, si prevede che le prestazioni saranno piĂč vantaggiose per le le CPU Intel con AVX-512 o superiori, mentre le CPU con solo AVX2 (ad esempio, le CPU AMD o le CPU Intel piĂč vecchie) potrebbero ottenere prestazioni migliori con IPEX, ma non sono garantite. IPEX offre ottimizzazioni delle prestazioni per l'addestramento della CPU sia con Float32 che con BFloat16. L'uso di BFloat16 Ăš l'argomento principale delle seguenti sezioni.
-
-Il tipo di dati a bassa precisione BFloat16 Ăš stato supportato in modo nativo su 3rd Generation XeonÂź Scalable Processors (aka Cooper Lake) con AVX512 e sarĂ supportata dalla prossima generazione di IntelÂź XeonÂź Scalable Processors con IntelÂź Advanced Matrix Extensions (IntelÂź AMX) instruction set con prestazioni ulteriormente migliorate. L'Auto Mixed Precision per il backende della CPU Ăš stato abilitato da PyTorch-1.10. allo stesso tempo, il supporto di Auto Mixed Precision con BFloat16 per CPU e l'ottimizzazione degli operatori BFloat16 Ăš stata abilitata in modo massiccio in IntelÂź Extension per PyTorch, and parzialmente aggiornato al branch master di PyTorch. Gli utenti possono ottenere prestazioni migliori ed users experience con IPEX Auto Mixed Precision..
-
-Vedi informazioni piĂč dettagliate su [Auto Mixed Precision](https://intel.github.io/intel-extension-for-pytorch/cpu/latest/tutorials/features/amp.html).
-
-### Installazione di IPEX:
-
-Il rilascio di IPEX segue quello di PyTorch, da installare via pip:
-
-| PyTorch Version | IPEX version |
-| :---------------: | :----------: |
-| 1.13 | 1.13.0+cpu |
-| 1.12 | 1.12.300+cpu |
-| 1.11 | 1.11.200+cpu |
-| 1.10 | 1.10.100+cpu |
-
-```bash
-pip install intel_extension_for_pytorch== -f https://developer.intel.com/ipex-whl-stable-cpu
-```
-
-Vedi altri approcci per [IPEX installation](https://intel.github.io/intel-extension-for-pytorch/cpu/latest/tutorials/installation.html).
-
-### Utilizzo nel Trainer
-
-Per abilitare la auto mixed precision con IPEX in Trainer, l'utende dovrebbe aggiungere `use_ipex`, `bf16` e `no_cuda` negli argomenti del comando di addestramento.
-
-Vedi un sempio di un caso d'uso [Transformers question-answering](https://github.com/huggingface/transformers/tree/main/examples/pytorch/question-answering)
-
-- Training with IPEX using BF16 auto mixed precision on CPU:
-
- python run_qa.py \
---model_name_or_path bert-base-uncased \
---dataset_name squad \
---do_train \
---do_eval \
---per_device_train_batch_size 12 \
---learning_rate 3e-5 \
---num_train_epochs 2 \
---max_seq_length 384 \
---doc_stride 128 \
---output_dir /tmp/debug_squad/ \
---use_ipex \
---bf16 --no_cuda
-
-### Esempi pratici
-
-Blog: [Accelerating PyTorch Transformers with Intel Sapphire Rapids](https://huggingface.co/blog/intel-sapphire-rapids)
diff --git a/docs/source/it/perf_train_cpu_many.md b/docs/source/it/perf_train_cpu_many.md
new file mode 100644
index 000000000000..2fb10ee4ba49
--- /dev/null
+++ b/docs/source/it/perf_train_cpu_many.md
@@ -0,0 +1,141 @@
+
+
+# Addestramento effciente su multiple CPU
+
+Quando l'addestramento su una singola CPU Ăš troppo lento, possiamo usare CPU multiple. Quasta guida si concentra su DDP basato su PyTorch abilitando l'addetramento distribuito su CPU in maniera efficiente.
+
+## IntelÂź oneCCL Bindings per PyTorch
+
+[IntelÂź oneCCL](https://github.com/oneapi-src/oneCCL) (collective communications library) Ăš una libreria per l'addestramento efficiente del deep learning in distribuito e implementa collettivi come allreduce, allgather, alltoall. Per maggiori informazioni su oneCCL, fai riferimento a [oneCCL documentation](https://spec.oneapi.com/versions/latest/elements/oneCCL/source/index.html) e [oneCCL specification](https://spec.oneapi.com/versions/latest/elements/oneCCL/source/index.html).
+
+Il modulo `oneccl_bindings_for_pytorch` (`torch_ccl` precedentemente alla versione 1.12) implementa PyTorch C10D ProcessGroup API e puĂČ essere caricato dinamicamente com external ProcessGroup e funziona solo su piattaforma Linux al momento.
+
+Qui trovi informazioni piĂč dettagliate per [oneccl_bind_pt](https://github.com/intel/torch-ccl).
+
+### IntelÂź oneCCL Bindings per l'installazione PyTorch:
+
+I file wheel sono disponibili per le seguenti versioni di Python:
+
+| Extension Version | Python 3.6 | Python 3.7 | Python 3.8 | Python 3.9 | Python 3.10 |
+| :---------------: | :--------: | :--------: | :--------: | :--------: | :---------: |
+| 1.13.0 | | â | â | â | â |
+| 1.12.100 | | â | â | â | â |
+| 1.12.0 | | â | â | â | â |
+| 1.11.0 | | â | â | â | â |
+| 1.10.0 | â | â | â | â | |
+
+```bash
+pip install oneccl_bind_pt=={pytorch_version} -f https://developer.intel.com/ipex-whl-stable-cpu
+```
+
+dove `{pytorch_version}` deve essere la tua versione di PyTorch, per l'stanza 1.13.0.
+Verifica altri approcci per [oneccl_bind_pt installation](https://github.com/intel/torch-ccl).
+Le versioni di oneCCL e PyTorch devono combaciare.
+
+
+
+oneccl_bindings_for_pytorch 1.12.0 prebuilt wheel does not work with PyTorch 1.12.1 (it is for PyTorch 1.12.0)
+PyTorch 1.12.1 should work with oneccl_bindings_for_pytorch 1.12.100
+
+
+
+## IntelÂź MPI library
+
+Usa questa implementazione basata su standard MPI per fornire una architettura flessibile, efficiente, scalabile su cluster per IntelÂź. Questo componente Ăš parte di IntelÂź oneAPI HPC Toolkit.
+
+oneccl_bindings_for_pytorch Ăš installato insieme al set di strumenti MPI. NecessitĂ di reperire l'ambiente prima di utilizzarlo.
+
+per IntelÂź oneCCL >= 1.12.0
+
+```bash
+oneccl_bindings_for_pytorch_path=$(python -c "from oneccl_bindings_for_pytorch import cwd; print(cwd)")
+source $oneccl_bindings_for_pytorch_path/env/setvars.sh
+```
+
+per IntelÂź oneCCL con versione < 1.12.0
+
+```bash
+torch_ccl_path=$(python -c "import torch; import torch_ccl; import os; print(os.path.abspath(os.path.dirname(torch_ccl.__file__)))")
+source $torch_ccl_path/env/setvars.sh
+```
+
+#### Installazione IPEX:
+
+IPEX fornisce ottimizzazioni delle prestazioni per l'addestramento della CPU sia con Float32 che con BFloat16; puoi fare riferimento a [single CPU section](./perf_train_cpu).
+
+Il seguente "Utilizzo in Trainer" prende come esempio mpirun nella libreria IntelÂź MPI.
+
+## Utilizzo in Trainer
+
+Per abilitare l'addestramento distribuito multi CPU nel Trainer con il ccl backend, gli utenti devono aggiungere **`--ddp_backend ccl`** negli argomenti del comando.
+
+Vediamo un esempio per il [question-answering example](https://github.com/huggingface/transformers/tree/main/examples/pytorch/question-answering)
+
+Il seguente comando abilita due processi sul nodo Xeon, con un processo in esecuzione per ogni socket. Le variabili OMP_NUM_THREADS/CCL_WORKER_COUNT possono essere impostate per una prestazione ottimale.
+
+```shell script
+ export CCL_WORKER_COUNT=1
+ export MASTER_ADDR=127.0.0.1
+ mpirun -n 2 -genv OMP_NUM_THREADS=23 \
+ python3 run_qa.py \
+ --model_name_or_path bert-large-uncased \
+ --dataset_name squad \
+ --do_train \
+ --do_eval \
+ --per_device_train_batch_size 12 \
+ --learning_rate 3e-5 \
+ --num_train_epochs 2 \
+ --max_seq_length 384 \
+ --doc_stride 128 \
+ --output_dir /tmp/debug_squad/ \
+ --no_cuda \
+ --ddp_backend ccl \
+ --use_ipex
+```
+
+Il seguente comando abilita l'addestramento per un totale di quattro processi su due Xeon (node0 e node1, prendendo node0 come processo principale), ppn (processes per node) Ăš impostato a 2, on un processo in esecuzione per ogni socket. Le variabili OMP_NUM_THREADS/CCL_WORKER_COUNT possono essere impostate per una prestazione ottimale.
+
+In node0, Ăš necessario creare un file di configurazione che contenga gli indirizzi IP di ciascun nodo (per esempio hostfile) e passare il percorso del file di configurazione come parametro.
+
+```shell script
+ cat hostfile
+ xxx.xxx.xxx.xxx #node0 ip
+ xxx.xxx.xxx.xxx #node1 ip
+```
+
+A questo punto, esegui il seguente comando nel nodo0 e **4DDP** sarĂ abilitato in node0 e node1 con BF16 auto mixed precision:
+
+```shell script
+ export CCL_WORKER_COUNT=1
+ export MASTER_ADDR=xxx.xxx.xxx.xxx #node0 ip
+ mpirun -f hostfile -n 4 -ppn 2 \
+ -genv OMP_NUM_THREADS=23 \
+ python3 run_qa.py \
+ --model_name_or_path bert-large-uncased \
+ --dataset_name squad \
+ --do_train \
+ --do_eval \
+ --per_device_train_batch_size 12 \
+ --learning_rate 3e-5 \
+ --num_train_epochs 2 \
+ --max_seq_length 384 \
+ --doc_stride 128 \
+ --output_dir /tmp/debug_squad/ \
+ --no_cuda \
+ --ddp_backend ccl \
+ --use_ipex \
+ --bf16
+```
diff --git a/docs/source/it/perf_train_cpu_many.mdx b/docs/source/it/perf_train_cpu_many.mdx
deleted file mode 100644
index abe99b27f8df..000000000000
--- a/docs/source/it/perf_train_cpu_many.mdx
+++ /dev/null
@@ -1,137 +0,0 @@
-
-
-# Addestramento effciente su multiple CPU
-
-Quando l'addestramento su una singola CPU Ăš troppo lento, possiamo usare CPU multiple. Quasta guida si concentra su DDP basato su PyTorch abilitando l'addetramento distribuito su CPU in maniera efficiente.
-
-## IntelÂź oneCCL Bindings per PyTorch
-
-[IntelÂź oneCCL](https://github.com/oneapi-src/oneCCL) (collective communications library) Ăš una libreria per l'addestramento efficiente del deep learning in distribuito e implementa collettivi come allreduce, allgather, alltoall. Per maggiori informazioni su oneCCL, fai riferimento a [oneCCL documentation](https://spec.oneapi.com/versions/latest/elements/oneCCL/source/index.html) e [oneCCL specification](https://spec.oneapi.com/versions/latest/elements/oneCCL/source/index.html).
-
-Il modulo `oneccl_bindings_for_pytorch` (`torch_ccl` precedentemente alla versione 1.12) implementa PyTorch C10D ProcessGroup API e puĂČ essere caricato dinamicamente com external ProcessGroup e funziona solo su piattaforma Linux al momento.
-
-Qui trovi informazioni piĂč dettagliate per [oneccl_bind_pt](https://github.com/intel/torch-ccl).
-
-### IntelÂź oneCCL Bindings per l'installazione PyTorch:
-
-I file wheel sono disponibili per le seguenti versioni di Python:
-
-| Extension Version | Python 3.6 | Python 3.7 | Python 3.8 | Python 3.9 | Python 3.10 |
-| :---------------: | :--------: | :--------: | :--------: | :--------: | :---------: |
-| 1.13.0 | | â | â | â | â |
-| 1.12.100 | | â | â | â | â |
-| 1.12.0 | | â | â | â | â |
-| 1.11.0 | | â | â | â | â |
-| 1.10.0 | â | â | â | â | |
-
-```bash
-pip install oneccl_bind_pt=={pytorch_version} -f https://developer.intel.com/ipex-whl-stable-cpu
-```
-
-dove `{pytorch_version}` deve essere la tua versione di PyTorch, per l'stanza 1.13.0.
-Verifica altri approcci per [oneccl_bind_pt installation](https://github.com/intel/torch-ccl).
-Le versioni di oneCCL e PyTorch devono combaciare.
-
-
-
-oneccl_bindings_for_pytorch 1.12.0 prebuilt wheel does not work with PyTorch 1.12.1 (it is for PyTorch 1.12.0)
-PyTorch 1.12.1 should work with oneccl_bindings_for_pytorch 1.12.100
-
-
-
-## IntelÂź MPI library
-
-Usa questa implementazione basata su standard MPI per fornire una architettura flessibile, efficiente, scalabile su cluster per IntelÂź. Questo componente Ăš parte di IntelÂź oneAPI HPC Toolkit.
-
-oneccl_bindings_for_pytorch Ăš installato insieme al set di strumenti MPI. NecessitĂ di reperire l'ambiente prima di utilizzarlo.
-
-per IntelÂź oneCCL >= 1.12.0
-
-```bash
-oneccl_bindings_for_pytorch_path=$(python -c "from oneccl_bindings_for_pytorch import cwd; print(cwd)")
-source $oneccl_bindings_for_pytorch_path/env/setvars.sh
-```
-
-per IntelÂź oneCCL con versione < 1.12.0
-
-```bash
-torch_ccl_path=$(python -c "import torch; import torch_ccl; import os; print(os.path.abspath(os.path.dirname(torch_ccl.__file__)))")
-source $torch_ccl_path/env/setvars.sh
-```
-
-#### Installazione IPEX:
-
-IPEX fornisce ottimizzazioni delle prestazioni per l'addestramento della CPU sia con Float32 che con BFloat16; puoi fare riferimento a [single CPU section](./perf_train_cpu).
-
-Il seguente "Utilizzo in Trainer" prende come esempio mpirun nella libreria IntelÂź MPI.
-
-## Utilizzo in Trainer
-
-Per abilitare l'addestramento distribuito multi CPU nel Trainer con il ccl backend, gli utenti devono aggiungere **`--ddp_backend ccl`** negli argomenti del comando.
-
-Vediamo un esempio per il [question-answering example](https://github.com/huggingface/transformers/tree/main/examples/pytorch/question-answering)
-
-Il seguente comando abilita due processi sul nodo Xeon, con un processo in esecuzione per ogni socket. Le variabili OMP_NUM_THREADS/CCL_WORKER_COUNT possono essere impostate per una prestazione ottimale.
-
-```shell script
- export CCL_WORKER_COUNT=1
- export MASTER_ADDR=127.0.0.1
- mpirun -n 2 -genv OMP_NUM_THREADS=23 \
- python3 run_qa.py \
- --model_name_or_path bert-large-uncased \
- --dataset_name squad \
- --do_train \
- --do_eval \
- --per_device_train_batch_size 12 \
- --learning_rate 3e-5 \
- --num_train_epochs 2 \
- --max_seq_length 384 \
- --doc_stride 128 \
- --output_dir /tmp/debug_squad/ \
- --no_cuda \
- --ddp_backend ccl \
- --use_ipex
-```
-
-Il seguente comando abilita l'addestramento per un totale di quattro processi su due Xeon (node0 e node1, prendendo node0 come processo principale), ppn (processes per node) Ăš impostato a 2, on un processo in esecuzione per ogni socket. Le variabili OMP_NUM_THREADS/CCL_WORKER_COUNT possono essere impostate per una prestazione ottimale.
-
-In node0, Ăš necessario creare un file di configurazione che contenga gli indirizzi IP di ciascun nodo (per esempio hostfile) e passare il percorso del file di configurazione come parametro.
-
-```shell script
- cat hostfile
- xxx.xxx.xxx.xxx #node0 ip
- xxx.xxx.xxx.xxx #node1 ip
-```
-
-A questo punto, esegui il seguente comando nel nodo0 e **4DDP** sarĂ abilitato in node0 e node1 con BF16 auto mixed precision:
-
-```shell script
- export CCL_WORKER_COUNT=1
- export MASTER_ADDR=xxx.xxx.xxx.xxx #node0 ip
- mpirun -f hostfile -n 4 -ppn 2 \
- -genv OMP_NUM_THREADS=23 \
- python3 run_qa.py \
- --model_name_or_path bert-large-uncased \
- --dataset_name squad \
- --do_train \
- --do_eval \
- --per_device_train_batch_size 12 \
- --learning_rate 3e-5 \
- --num_train_epochs 2 \
- --max_seq_length 384 \
- --doc_stride 128 \
- --output_dir /tmp/debug_squad/ \
- --no_cuda \
- --ddp_backend ccl \
- --use_ipex \
- --bf16
-```
diff --git a/docs/source/it/perf_train_special.md b/docs/source/it/perf_train_special.md
new file mode 100644
index 000000000000..afe05d801d66
--- /dev/null
+++ b/docs/source/it/perf_train_special.md
@@ -0,0 +1,24 @@
+
+
+# Addestramento su Hardware Specializzato
+
+
+
+ Nota: Molte delle strategie introdotte nella [sezione sulla GPU singola](perf_train_gpu_one) (come mixed precision training o gradient accumulation) e [sezione multi-GPU](perf_train_gpu_many) sono generiche e applicabili all'addestramento di modelli in generale quindi assicurati di dargli un'occhiata prima di immergerti in questa sezione.
+
+
+
+Questo documento sarĂ presto completato con informazioni su come effettuare la formazione su hardware specializzato.
diff --git a/docs/source/it/perf_train_special.mdx b/docs/source/it/perf_train_special.mdx
deleted file mode 100644
index 22ea6d73e3d6..000000000000
--- a/docs/source/it/perf_train_special.mdx
+++ /dev/null
@@ -1,20 +0,0 @@
-
-
-# Addestramento su Hardware Specializzato
-
-
-
- Nota: Molte delle strategie introdotte nella [sezione sulla GPU singola](perf_train_gpu_one) (come mixed precision training o gradient accumulation) e [sezione multi-GPU](perf_train_gpu_many) sono generiche e applicabili all'addestramento di modelli in generale quindi assicurati di dargli un'occhiata prima di immergerti in questa sezione.
-
-
-
-Questo documento sarĂ presto completato con informazioni su come effettuare la formazione su hardware specializzato.
diff --git a/docs/source/it/perf_train_tpu.md b/docs/source/it/perf_train_tpu.md
new file mode 100644
index 000000000000..663f83c499cb
--- /dev/null
+++ b/docs/source/it/perf_train_tpu.md
@@ -0,0 +1,24 @@
+
+
+# Addestramento su TPU
+
+
+
+ Nota: Molte delle strategie introdotte nella [sezione sulla GPU singola](perf_train_gpu_one) (come mixed precision training o gradient accumulation) e [sezione multi-GPU](perf_train_gpu_many) sono generiche e applicabili all'addestramento di modelli in generale quindi assicurati di dargli un'occhiata prima di immergerti in questa sezione.
+
+
+
+Questo documento sarĂ presto completato con informazioni su come effettuare la formazione su TPU.
diff --git a/docs/source/it/perf_train_tpu.mdx b/docs/source/it/perf_train_tpu.mdx
deleted file mode 100644
index 395caebcd066..000000000000
--- a/docs/source/it/perf_train_tpu.mdx
+++ /dev/null
@@ -1,20 +0,0 @@
-
-
-# Addestramento su TPU
-
-
-
- Nota: Molte delle strategie introdotte nella [sezione sulla GPU singola](perf_train_gpu_one) (come mixed precision training o gradient accumulation) e [sezione multi-GPU](perf_train_gpu_many) sono generiche e applicabili all'addestramento di modelli in generale quindi assicurati di dargli un'occhiata prima di immergerti in questa sezione.
-
-
-
-Questo documento sarĂ presto completato con informazioni su come effettuare la formazione su TPU.
diff --git a/docs/source/it/pipeline_tutorial.md b/docs/source/it/pipeline_tutorial.md
new file mode 100644
index 000000000000..056282b164ed
--- /dev/null
+++ b/docs/source/it/pipeline_tutorial.md
@@ -0,0 +1,152 @@
+
+
+# Pipeline per l'inferenza
+
+La [`pipeline`] rende semplice usare qualsiasi modello dal [Model Hub](https://huggingface.co/models) per fare inferenza su diversi compiti come generazione del testo, segmentazione di immagini e classificazione di audio. Anche se non hai esperienza con una modalitĂ specifica o non comprendi bene il codice che alimenta i modelli, Ăš comunque possibile utilizzarli con l'opzione [`pipeline`]! Questa esercitazione ti insegnerĂ a:
+
+* Usare una [`pipeline`] per fare inferenza.
+* Usare uno specifico tokenizer o modello.
+* Usare una [`pipeline`] per compiti che riguardano audio e video.
+
+
+
+Dai un'occhiata alla documentazione di [`pipeline`] per una lista completa dei compiti supportati.
+
+
+
+## Utilizzo della Pipeline
+
+Nonostante ogni compito abbia una [`pipeline`] associata, Ăš piĂč semplice utilizzare l'astrazione generica della [`pipeline`] che contiene tutte quelle specifiche per ogni mansione. La [`pipeline`] carica automaticamente un modello predefinito e un tokenizer in grado di fare inferenza per il tuo compito.
+
+1. Inizia creando una [`pipeline`] e specificando il compito su cui fare inferenza:
+
+```py
+>>> from transformers import pipeline
+
+>>> generator = pipeline(task="text-generation")
+```
+
+2. Inserisci il testo in input nella [`pipeline`]:
+
+```py
+>>> generator(
+... "Three Rings for the Elven-kings under the sky, Seven for the Dwarf-lords in their halls of stone"
+... ) # doctest: +SKIP
+[{'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'}]
+```
+
+Se hai piĂč di un input, inseriscilo in una lista:
+
+```py
+>>> generator(
+... [
+... "Three Rings for the Elven-kings under the sky, Seven for the Dwarf-lords in their halls of stone",
+... "Nine for Mortal Men, doomed to die, One for the Dark Lord on his dark throne",
+... ]
+... ) # doctest: +SKIP
+```
+
+Qualsiasi parametro addizionale per il tuo compito puĂČ essere incluso nella [`pipeline`]. La mansione `text-generation` ha un metodo [`~generation.GenerationMixin.generate`] con diversi parametri per controllare l'output. Ad esempio, se desideri generare piĂč di un output, utilizza il parametro `num_return_sequences`:
+
+```py
+>>> generator(
+... "Three Rings for the Elven-kings under the sky, Seven for the Dwarf-lords in their halls of stone",
+... num_return_sequences=2,
+... ) # doctest: +SKIP
+```
+
+### Scegliere modello e tokenizer
+
+La [`pipeline`] accetta qualsiasi modello dal [Model Hub](https://huggingface.co/models). Ci sono tag nel Model Hub che consentono di filtrare i modelli per attivitĂ . Una volta che avrai scelto il modello appropriato, caricalo usando la corrispondente classe `AutoModelFor` e [`AutoTokenizer`]. Ad esempio, carica la classe [`AutoModelForCausalLM`] per un compito di causal language modeling:
+
+```py
+>>> from transformers import AutoTokenizer, AutoModelForCausalLM
+
+>>> tokenizer = AutoTokenizer.from_pretrained("distilgpt2")
+>>> model = AutoModelForCausalLM.from_pretrained("distilgpt2")
+```
+
+Crea una [`pipeline`] per il tuo compito, specificando il modello e il tokenizer che hai caricato:
+
+```py
+>>> from transformers import pipeline
+
+>>> generator = pipeline(task="text-generation", model=model, tokenizer=tokenizer)
+```
+
+Inserisci il testo di input nella [`pipeline`] per generare del testo:
+
+```py
+>>> generator(
+... "Three Rings for the Elven-kings under the sky, Seven for the Dwarf-lords in their halls of stone"
+... ) # doctest: +SKIP
+[{'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'}]
+```
+
+## Audio pipeline
+
+La flessibilitĂ della [`pipeline`] fa si che possa essere estesa ad attivitĂ sugli audio.
+
+Per esempio, classifichiamo le emozioni in questo clip audio:
+
+```py
+>>> from datasets import load_dataset
+>>> import torch
+
+>>> torch.manual_seed(42) # doctest: +IGNORE_RESULT
+>>> ds = load_dataset("hf-internal-testing/librispeech_asr_demo", "clean", split="validation")
+>>> audio_file = ds[0]["audio"]["path"]
+```
+
+Trova un modello per la [classificazione audio](https://huggingface.co/models?pipeline_tag=audio-classification) sul Model Hub per eseguire un compito di riconoscimento automatico delle emozioni e caricalo nella [`pipeline`]:
+
+```py
+>>> from transformers import pipeline
+
+>>> audio_classifier = pipeline(
+... task="audio-classification", model="ehcalabres/wav2vec2-lg-xlsr-en-speech-emotion-recognition"
+... )
+```
+
+Inserisci il file audio nella [`pipeline`]:
+
+```py
+>>> preds = audio_classifier(audio_file)
+>>> preds = [{"score": round(pred["score"], 4), "label": pred["label"]} for pred in preds]
+>>> preds
+[{'score': 0.1315, 'label': 'calm'}, {'score': 0.1307, 'label': 'neutral'}, {'score': 0.1274, 'label': 'sad'}, {'score': 0.1261, 'label': 'fearful'}, {'score': 0.1242, 'label': 'happy'}]
+```
+
+## Vision pipeline
+
+Infine, usare la [`pipeline`] per le attivitĂ sulle immagini Ăš praticamente la stessa cosa.
+
+Specifica la tua attivitĂ e inserisci l'immagine nel classificatore. L'immagine puĂČ essere sia un link che un percorso sul tuo pc in locale. Per esempio, quale specie di gatto Ăš raffigurata qui sotto?
+
+
+
+```py
+>>> from transformers import pipeline
+
+>>> vision_classifier = pipeline(task="image-classification")
+>>> preds = vision_classifier(
+... images="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
+... )
+>>> preds = [{"score": round(pred["score"], 4), "label": pred["label"]} for pred in preds]
+>>> preds
+[{'score': 0.4335, 'label': 'lynx, catamount'}, {'score': 0.0348, 'label': 'cougar, puma, catamount, mountain lion, painter, panther, Felis concolor'}, {'score': 0.0324, 'label': 'snow leopard, ounce, Panthera uncia'}, {'score': 0.0239, 'label': 'Egyptian cat'}, {'score': 0.0229, 'label': 'tiger cat'}]
+```
diff --git a/docs/source/it/pipeline_tutorial.mdx b/docs/source/it/pipeline_tutorial.mdx
deleted file mode 100644
index 64347164505f..000000000000
--- a/docs/source/it/pipeline_tutorial.mdx
+++ /dev/null
@@ -1,148 +0,0 @@
-
-
-# Pipeline per l'inferenza
-
-La [`pipeline`] rende semplice usare qualsiasi modello dal [Model Hub](https://huggingface.co/models) per fare inferenza su diversi compiti come generazione del testo, segmentazione di immagini e classificazione di audio. Anche se non hai esperienza con una modalitĂ specifica o non comprendi bene il codice che alimenta i modelli, Ăš comunque possibile utilizzarli con l'opzione [`pipeline`]! Questa esercitazione ti insegnerĂ a:
-
-* Usare una [`pipeline`] per fare inferenza.
-* Usare uno specifico tokenizer o modello.
-* Usare una [`pipeline`] per compiti che riguardano audio e video.
-
-
-
-Dai un'occhiata alla documentazione di [`pipeline`] per una lista completa dei compiti supportati.
-
-
-
-## Utilizzo della Pipeline
-
-Nonostante ogni compito abbia una [`pipeline`] associata, Ăš piĂč semplice utilizzare l'astrazione generica della [`pipeline`] che contiene tutte quelle specifiche per ogni mansione. La [`pipeline`] carica automaticamente un modello predefinito e un tokenizer in grado di fare inferenza per il tuo compito.
-
-1. Inizia creando una [`pipeline`] e specificando il compito su cui fare inferenza:
-
-```py
->>> from transformers import pipeline
-
->>> generator = pipeline(task="text-generation")
-```
-
-2. Inserisci il testo in input nella [`pipeline`]:
-
-```py
->>> generator(
-... "Three Rings for the Elven-kings under the sky, Seven for the Dwarf-lords in their halls of stone"
-... ) # doctest: +SKIP
-[{'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'}]
-```
-
-Se hai piĂč di un input, inseriscilo in una lista:
-
-```py
->>> generator(
-... [
-... "Three Rings for the Elven-kings under the sky, Seven for the Dwarf-lords in their halls of stone",
-... "Nine for Mortal Men, doomed to die, One for the Dark Lord on his dark throne",
-... ]
-... ) # doctest: +SKIP
-```
-
-Qualsiasi parametro addizionale per il tuo compito puĂČ essere incluso nella [`pipeline`]. La mansione `text-generation` ha un metodo [`~generation.GenerationMixin.generate`] con diversi parametri per controllare l'output. Ad esempio, se desideri generare piĂč di un output, utilizza il parametro `num_return_sequences`:
-
-```py
->>> generator(
-... "Three Rings for the Elven-kings under the sky, Seven for the Dwarf-lords in their halls of stone",
-... num_return_sequences=2,
-... ) # doctest: +SKIP
-```
-
-### Scegliere modello e tokenizer
-
-La [`pipeline`] accetta qualsiasi modello dal [Model Hub](https://huggingface.co/models). Ci sono tag nel Model Hub che consentono di filtrare i modelli per attivitĂ . Una volta che avrai scelto il modello appropriato, caricalo usando la corrispondente classe `AutoModelFor` e [`AutoTokenizer`]. Ad esempio, carica la classe [`AutoModelForCausalLM`] per un compito di causal language modeling:
-
-```py
->>> from transformers import AutoTokenizer, AutoModelForCausalLM
-
->>> tokenizer = AutoTokenizer.from_pretrained("distilgpt2")
->>> model = AutoModelForCausalLM.from_pretrained("distilgpt2")
-```
-
-Crea una [`pipeline`] per il tuo compito, specificando il modello e il tokenizer che hai caricato:
-
-```py
->>> from transformers import pipeline
-
->>> generator = pipeline(task="text-generation", model=model, tokenizer=tokenizer)
-```
-
-Inserisci il testo di input nella [`pipeline`] per generare del testo:
-
-```py
->>> generator(
-... "Three Rings for the Elven-kings under the sky, Seven for the Dwarf-lords in their halls of stone"
-... ) # doctest: +SKIP
-[{'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'}]
-```
-
-## Audio pipeline
-
-La flessibilitĂ della [`pipeline`] fa si che possa essere estesa ad attivitĂ sugli audio.
-
-Per esempio, classifichiamo le emozioni in questo clip audio:
-
-```py
->>> from datasets import load_dataset
->>> import torch
-
->>> torch.manual_seed(42) # doctest: +IGNORE_RESULT
->>> ds = load_dataset("hf-internal-testing/librispeech_asr_demo", "clean", split="validation")
->>> audio_file = ds[0]["audio"]["path"]
-```
-
-Trova un modello per la [classificazione audio](https://huggingface.co/models?pipeline_tag=audio-classification) sul Model Hub per eseguire un compito di riconoscimento automatico delle emozioni e caricalo nella [`pipeline`]:
-
-```py
->>> from transformers import pipeline
-
->>> audio_classifier = pipeline(
-... task="audio-classification", model="ehcalabres/wav2vec2-lg-xlsr-en-speech-emotion-recognition"
-... )
-```
-
-Inserisci il file audio nella [`pipeline`]:
-
-```py
->>> preds = audio_classifier(audio_file)
->>> preds = [{"score": round(pred["score"], 4), "label": pred["label"]} for pred in preds]
->>> preds
-[{'score': 0.1315, 'label': 'calm'}, {'score': 0.1307, 'label': 'neutral'}, {'score': 0.1274, 'label': 'sad'}, {'score': 0.1261, 'label': 'fearful'}, {'score': 0.1242, 'label': 'happy'}]
-```
-
-## Vision pipeline
-
-Infine, usare la [`pipeline`] per le attivitĂ sulle immagini Ăš praticamente la stessa cosa.
-
-Specifica la tua attivitĂ e inserisci l'immagine nel classificatore. L'immagine puĂČ essere sia un link che un percorso sul tuo pc in locale. Per esempio, quale specie di gatto Ăš raffigurata qui sotto?
-
-
-
-```py
->>> from transformers import pipeline
-
->>> vision_classifier = pipeline(task="image-classification")
->>> preds = vision_classifier(
-... images="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
-... )
->>> preds = [{"score": round(pred["score"], 4), "label": pred["label"]} for pred in preds]
->>> preds
-[{'score': 0.4335, 'label': 'lynx, catamount'}, {'score': 0.0348, 'label': 'cougar, puma, catamount, mountain lion, painter, panther, Felis concolor'}, {'score': 0.0324, 'label': 'snow leopard, ounce, Panthera uncia'}, {'score': 0.0239, 'label': 'Egyptian cat'}, {'score': 0.0229, 'label': 'tiger cat'}]
-```
diff --git a/docs/source/it/pr_checks.md b/docs/source/it/pr_checks.md
new file mode 100644
index 000000000000..caa5fe32965b
--- /dev/null
+++ b/docs/source/it/pr_checks.md
@@ -0,0 +1,135 @@
+
+
+# Controlli su una Pull Request
+
+Quando apri una pull request sui đ€ Transformers, vengono eseguiti un discreto numero di controlli per assicurarsi che la patch che stai aggiungendo non stia rompendo qualcosa di esistente. Questi controlli sono di quattro tipi:
+- test regolari
+- costruzione della documentazione
+- stile del codice e della documentazione
+- coerenza generale del repository
+
+In questo documento, cercheremo di spiegare quali sono i vari controlli e le loro ragioni, oltre a spiegare come eseguire il debug locale se uno di essi fallisce sulla tua PR.
+
+Nota che tutti richiedono un'installazione dev:
+
+```bash
+pip install transformers[dev]
+```
+
+o un'installazione modificabile:
+
+```bash
+pip install -e .[dev]
+```
+
+all'interno del repo Transformers.
+
+## Tests
+
+Tutti i job che iniziano con `ci/circleci: run_tests_` eseguono parti della suite di test dei Transformers. Ognuno di questi job si concentra su una parte della libreria in un determinato ambiente: per esempio `ci/circleci: run_tests_pipelines_tf` esegue il test delle pipeline in un ambiente in cui Ăš installato solo TensorFlow.
+
+Nota che per evitare di eseguire i test quando non ci sono cambiamenti reali nei moduli che si stanno testando, ogni volta viene eseguita solo una parte della suite di test: viene eseguita una utility per determinare le differenze nella libreria tra prima e dopo la PR (ciĂČ che GitHub mostra nella scheda "Files changes") e sceglie i test che sono stati impattati dalla diff. Questa utility puĂČ essere eseguita localmente con:
+
+```bash
+python utils/tests_fetcher.py
+```
+
+dalla root del repo Transformers. Di seguito ciĂČ che farĂ :
+
+1. Controlla per ogni file nel diff se le modifiche sono nel codice o solo nei commenti o nelle docstrings. Vengono mantenuti solo i file con modifiche reali al codice.
+2. Costruisce una mappa interna che fornisce per ogni file del codice sorgente della libreria tutti i file su cui ha un impatto ricorsivo. Si dice che il modulo A ha un impatto sul modulo B se il modulo B importa il modulo A. Per l'impatto ricorsivo, abbiamo bisogno di una catena di moduli che va dal modulo A al modulo B in cui ogni modulo importa il precedente.
+3. Applica questa mappa ai file raccolti nel passaggio 1, si ottiene l'elenco dei file del modello interessati dalla PR.
+4. Mappa ciascuno di questi file con i corrispondenti file di test e ottiene l'elenco dei test da eseguire.
+
+Quando esegui lo script in locale, dovresti ottenere la stampa dei risultati dei passi 1, 3 e 4 e quindi sapere quali test sono stati eseguiti. Lo script creerĂ anche un file chiamato `test_list.txt` che contiene l'elenco dei test da eseguire e che puoi eseguire localmente con il seguente comando:
+
+```bash
+python -m pytest -n 8 --dist=loadfile -rA -s $(cat test_list.txt)
+```
+
+Nel caso in cui qualcosa sia sfuggito, l'intera suite di test viene eseguita quotidianamente.
+
+## Build della documentazione
+
+Il job `ci/circleci: build_doc` esegue una build della documentazione per assicurarsi che tutto sia a posto una volta che la PR Ăš stata unita. Se questo passaggio fallisce, puoi controllare localmente entrando nella cartella `docs` del repo Transformers e digitare
+
+```bash
+make html
+```
+
+Sphinx non Ăš noto per i suoi messaggi di errore chiari, quindi potrebbe essere necessario che provi alcune cose per trovare davvero la fonte dell'errore.
+
+## Stile del codice e della documentazione
+
+La formattazione del codice viene applicata a tutti i file sorgenti, agli esempi e ai test usando `black` e `isort`. Abbiamo anche uno strumento personalizzato che si occupa della formattazione delle docstring e dei file `rst` (`utils/style_doc.py`), cosĂŹ come dell'ordine dei lazy imports eseguiti nei file `__init__.py` dei Transformers (`utils/custom_init_isort.py`). Tutto questo puĂČ essere lanciato eseguendo
+
+```bash
+make style
+```
+
+I controlli della CI sono applicati all'interno del controllo `ci/circleci: check_code_quality`. Esegue anche `flake8`, che dĂ un'occhiata di base al codice e si lamenta se trova una variabile non definita o non utilizzata. Per eseguire questo controllo localmente, usare
+
+```bash
+make quality
+```
+
+Questa operazione puĂČ richiedere molto tempo, quindi per eseguire la stessa operazione solo sui file modificati nel branch corrente, eseguire
+
+```bash
+make fixup
+```
+
+Quest'ultimo comando eseguirĂ anche tutti i controlli aggiuntivi per la consistenza del repository. Diamogli un'occhiata.
+
+## Coerenza del repository
+
+All'interno sono raggruppati tutti i test per assicurarsi che la tua PR lasci il repository in un buono stato ed Ăš eseguito dal controllo `ci/circleci: check_repository_consistency`. Puoi eseguire localmente questo controllo eseguendo quanto segue:
+
+```bash
+make repo-consistency
+```
+
+Questo verifica che:
+
+- Tutti gli oggetti aggiunti all'init sono documentati (eseguito da `utils/check_repo.py`)
+- Tutti i file `__init__.py` hanno lo stesso contenuto nelle loro due sezioni (eseguito da `utils/check_inits.py`)
+- Tutto il codice identificato come copia da un altro modulo Ăš coerente con l'originale (eseguito da `utils/check_copies.py`)
+- Le traduzioni dei README e l'indice della documentazione hanno lo stesso elenco di modelli del README principale (eseguito da `utils/check_copies.py`)
+- Le tabelle autogenerate nella documentazione sono aggiornate (eseguito da `utils/check_table.py`)
+- La libreria ha tutti gli oggetti disponibili anche se non tutte le dipendenze opzionali sono installate (eseguito da `utils/check_dummies.py`)
+
+Se questo controllo fallisce, le prime due voci richiedono una correzione manuale, mentre le ultime quattro possono essere corrette automaticamente per te eseguendo il comando
+
+```bash
+make fix-copies
+```
+
+Ulteriori controlli riguardano le PR che aggiungono nuovi modelli, principalmente che:
+
+- Tutti i modelli aggiunti sono in un Auto-mapping (eseguita da `utils/check_repo.py`)
+
+- Tutti i modelli sono testati correttamente (eseguito da `utils/check_repo.py`)
+
+
\ No newline at end of file
diff --git a/docs/source/it/pr_checks.mdx b/docs/source/it/pr_checks.mdx
deleted file mode 100644
index d7541d59f0ad..000000000000
--- a/docs/source/it/pr_checks.mdx
+++ /dev/null
@@ -1,131 +0,0 @@
-
-
-# Controlli su una Pull Request
-
-Quando apri una pull request sui đ€ Transformers, vengono eseguiti un discreto numero di controlli per assicurarsi che la patch che stai aggiungendo non stia rompendo qualcosa di esistente. Questi controlli sono di quattro tipi:
-- test regolari
-- costruzione della documentazione
-- stile del codice e della documentazione
-- coerenza generale del repository
-
-In questo documento, cercheremo di spiegare quali sono i vari controlli e le loro ragioni, oltre a spiegare come eseguire il debug locale se uno di essi fallisce sulla tua PR.
-
-Nota che tutti richiedono un'installazione dev:
-
-```bash
-pip install transformers[dev]
-```
-
-o un'installazione modificabile:
-
-```bash
-pip install -e .[dev]
-```
-
-all'interno del repo Transformers.
-
-## Tests
-
-Tutti i job che iniziano con `ci/circleci: run_tests_` eseguono parti della suite di test dei Transformers. Ognuno di questi job si concentra su una parte della libreria in un determinato ambiente: per esempio `ci/circleci: run_tests_pipelines_tf` esegue il test delle pipeline in un ambiente in cui Ăš installato solo TensorFlow.
-
-Nota che per evitare di eseguire i test quando non ci sono cambiamenti reali nei moduli che si stanno testando, ogni volta viene eseguita solo una parte della suite di test: viene eseguita una utility per determinare le differenze nella libreria tra prima e dopo la PR (ciĂČ che GitHub mostra nella scheda "Files changes") e sceglie i test che sono stati impattati dalla diff. Questa utility puĂČ essere eseguita localmente con:
-
-```bash
-python utils/tests_fetcher.py
-```
-
-dalla root del repo Transformers. Di seguito ciĂČ che farĂ :
-
-1. Controlla per ogni file nel diff se le modifiche sono nel codice o solo nei commenti o nelle docstrings. Vengono mantenuti solo i file con modifiche reali al codice.
-2. Costruisce una mappa interna che fornisce per ogni file del codice sorgente della libreria tutti i file su cui ha un impatto ricorsivo. Si dice che il modulo A ha un impatto sul modulo B se il modulo B importa il modulo A. Per l'impatto ricorsivo, abbiamo bisogno di una catena di moduli che va dal modulo A al modulo B in cui ogni modulo importa il precedente.
-3. Applica questa mappa ai file raccolti nel passaggio 1, si ottiene l'elenco dei file del modello interessati dalla PR.
-4. Mappa ciascuno di questi file con i corrispondenti file di test e ottiene l'elenco dei test da eseguire.
-
-Quando esegui lo script in locale, dovresti ottenere la stampa dei risultati dei passi 1, 3 e 4 e quindi sapere quali test sono stati eseguiti. Lo script creerĂ anche un file chiamato `test_list.txt` che contiene l'elenco dei test da eseguire e che puoi eseguire localmente con il seguente comando:
-
-```bash
-python -m pytest -n 8 --dist=loadfile -rA -s $(cat test_list.txt)
-```
-
-Nel caso in cui qualcosa sia sfuggito, l'intera suite di test viene eseguita quotidianamente.
-
-## Build della documentazione
-
-Il job `ci/circleci: build_doc` esegue una build della documentazione per assicurarsi che tutto sia a posto una volta che la PR Ăš stata unita. Se questo passaggio fallisce, puoi controllare localmente entrando nella cartella `docs` del repo Transformers e digitare
-
-```bash
-make html
-```
-
-Sphinx non Ăš noto per i suoi messaggi di errore chiari, quindi potrebbe essere necessario che provi alcune cose per trovare davvero la fonte dell'errore.
-
-## Stile del codice e della documentazione
-
-La formattazione del codice viene applicata a tutti i file sorgenti, agli esempi e ai test usando `black` e `isort`. Abbiamo anche uno strumento personalizzato che si occupa della formattazione delle docstring e dei file `rst` (`utils/style_doc.py`), cosĂŹ come dell'ordine dei lazy imports eseguiti nei file `__init__.py` dei Transformers (`utils/custom_init_isort.py`). Tutto questo puĂČ essere lanciato eseguendo
-
-```bash
-make style
-```
-
-I controlli della CI sono applicati all'interno del controllo `ci/circleci: check_code_quality`. Esegue anche `flake8`, che dĂ un'occhiata di base al codice e si lamenta se trova una variabile non definita o non utilizzata. Per eseguire questo controllo localmente, usare
-
-```bash
-make quality
-```
-
-Questa operazione puĂČ richiedere molto tempo, quindi per eseguire la stessa operazione solo sui file modificati nel branch corrente, eseguire
-
-```bash
-make fixup
-```
-
-Quest'ultimo comando eseguirĂ anche tutti i controlli aggiuntivi per la consistenza del repository. Diamogli un'occhiata.
-
-## Coerenza del repository
-
-All'interno sono raggruppati tutti i test per assicurarsi che la tua PR lasci il repository in un buono stato ed Ăš eseguito dal controllo `ci/circleci: check_repository_consistency`. Puoi eseguire localmente questo controllo eseguendo quanto segue:
-
-```bash
-make repo-consistency
-```
-
-Questo verifica che:
-
-- Tutti gli oggetti aggiunti all'init sono documentati (eseguito da `utils/check_repo.py`)
-- Tutti i file `__init__.py` hanno lo stesso contenuto nelle loro due sezioni (eseguito da `utils/check_inits.py`)
-- Tutto il codice identificato come copia da un altro modulo Ăš coerente con l'originale (eseguito da `utils/check_copies.py`)
-- Le traduzioni dei README e l'indice della documentazione hanno lo stesso elenco di modelli del README principale (eseguito da `utils/check_copies.py`)
-- Le tabelle autogenerate nella documentazione sono aggiornate (eseguito da `utils/check_table.py`)
-- La libreria ha tutti gli oggetti disponibili anche se non tutte le dipendenze opzionali sono installate (eseguito da `utils/check_dummies.py`)
-
-Se questo controllo fallisce, le prime due voci richiedono una correzione manuale, mentre le ultime quattro possono essere corrette automaticamente per te eseguendo il comando
-
-```bash
-make fix-copies
-```
-
-Ulteriori controlli riguardano le PR che aggiungono nuovi modelli, principalmente che:
-
-- Tutti i modelli aggiunti sono in un Auto-mapping (eseguita da `utils/check_repo.py`)
-
-- Tutti i modelli sono testati correttamente (eseguito da `utils/check_repo.py`)
-
-
\ No newline at end of file
diff --git a/docs/source/it/preprocessing.md b/docs/source/it/preprocessing.md
new file mode 100644
index 000000000000..94578dfe166b
--- /dev/null
+++ b/docs/source/it/preprocessing.md
@@ -0,0 +1,491 @@
+
+
+# Preprocess
+
+[[open-in-colab]]
+
+Prima di poter usare i dati in un modello, bisogna processarli in un formato accettabile per quest'ultimo. Un modello non comprende il testo grezzo, le immagini o l'audio. Bisogna convertire questi input in numeri e assemblarli all'interno di tensori. In questa esercitazione, tu potrai:
+
+* Preprocessare dati testuali con un tokenizer.
+* Preprocessare immagini o dati audio con un estrattore di caratteristiche.
+* Preprocessare dati per attivitĂ multimodali mediante un processore.
+
+## NLP
+
+
+
+Lo strumento principale per processare dati testuali Ăš un [tokenizer](main_classes/tokenizer). Un tokenizer inizia separando il testo in *tokens* secondo una serie di regole. I tokens sono convertiti in numeri, questi vengono utilizzati per costruire i tensori di input del modello. Anche altri input addizionali se richiesti dal modello vengono aggiunti dal tokenizer.
+
+
+
+Se stai pensando si utilizzare un modello preaddestrato, Ăš importante utilizzare il tokenizer preaddestrato associato. Questo assicura che il testo sia separato allo stesso modo che nel corpus usato per l'addestramento, e venga usata la stessa mappatura tokens-to-index (solitamente indicato come il *vocabolario*) come nel preaddestramento.
+
+
+
+Iniziamo subito caricando un tokenizer preaddestrato con la classe [`AutoTokenizer`]. Questo scarica il *vocabolario* usato quando il modello Ăš stato preaddestrato.
+
+### Tokenize
+
+Carica un tokenizer preaddestrato con [`AutoTokenizer.from_pretrained`]:
+
+```py
+>>> from transformers import AutoTokenizer
+
+>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
+```
+
+Poi inserisci le tue frasi nel tokenizer:
+
+```py
+>>> encoded_input = tokenizer("Do not meddle in the affairs of wizards, for they are subtle and quick to anger.")
+>>> print(encoded_input)
+{'input_ids': [101, 2079, 2025, 19960, 10362, 1999, 1996, 3821, 1997, 16657, 1010, 2005, 2027, 2024, 11259, 1998, 4248, 2000, 4963, 1012, 102],
+ 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}
+```
+
+Il tokenizer restituisce un dizionario contenente tre oggetti importanti:
+
+* [input_ids](glossary#input-ids) sono gli indici che corrispondono ad ogni token nella frase.
+* [attention_mask](glossary#attention-mask) indicata se un token deve essere elaborato o no.
+* [token_type_ids](glossary#token-type-ids) identifica a quale sequenza appartiene un token se Ăš presente piĂč di una sequenza.
+
+Si possono decodificare gli `input_ids` per farsi restituire l'input originale:
+
+```py
+>>> tokenizer.decode(encoded_input["input_ids"])
+'[CLS] Do not meddle in the affairs of wizards, for they are subtle and quick to anger. [SEP]'
+```
+
+Come si puĂČ vedere, il tokenizer aggiunge due token speciali - `CLS` e `SEP` (classificatore e separatore) - alla frase. Non tutti i modelli hanno bisogno dei token speciali, ma se servono, il tokenizer li aggiungerĂ automaticamente.
+
+Se ci sono piĂč frasi che vuoi processare, passale come una lista al tokenizer:
+
+```py
+>>> batch_sentences = [
+... "But what about second breakfast?",
+... "Don't think he knows about second breakfast, Pip.",
+... "What about elevensies?",
+... ]
+>>> encoded_inputs = tokenizer(batch_sentences)
+>>> print(encoded_inputs)
+{'input_ids': [[101, 1252, 1184, 1164, 1248, 6462, 136, 102],
+ [101, 1790, 112, 189, 1341, 1119, 3520, 1164, 1248, 6462, 117, 21902, 1643, 119, 102],
+ [101, 1327, 1164, 5450, 23434, 136, 102]],
+ 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]],
+ 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1],
+ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
+ [1, 1, 1, 1, 1, 1, 1]]}
+```
+
+### Pad
+
+Questo Ăš un argomento importante. Quando processi un insieme di frasi potrebbero non avere tutte la stessa lunghezza. Questo Ăš un problema perchĂš i tensori, in input del modello, devono avere dimensioni uniformi. Il padding Ăš una strategia per assicurarsi che i tensori siano rettangolari aggiungendo uno speciale *padding token* alle frasi piĂč corte.
+
+Imposta il parametro `padding` a `True` per imbottire le frasi piĂč corte nel gruppo in modo che combacino con la massima lunghezza presente:
+
+```py
+>>> batch_sentences = [
+... "But what about second breakfast?",
+... "Don't think he knows about second breakfast, Pip.",
+... "What about elevensies?",
+... ]
+>>> encoded_input = tokenizer(batch_sentences, padding=True)
+>>> print(encoded_input)
+{'input_ids': [[101, 1252, 1184, 1164, 1248, 6462, 136, 102, 0, 0, 0, 0, 0, 0, 0],
+ [101, 1790, 112, 189, 1341, 1119, 3520, 1164, 1248, 6462, 117, 21902, 1643, 119, 102],
+ [101, 1327, 1164, 5450, 23434, 136, 102, 0, 0, 0, 0, 0, 0, 0, 0]],
+ 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
+ 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0],
+ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
+ [1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]]}
+```
+
+Nota che il tokenizer aggiunge alle sequenze degli `0` perchĂš sono troppo corte!
+
+### Truncation
+
+L'altra faccia della medaglia Ăš che avolte le sequenze possono essere troppo lunghe per essere gestite dal modello. In questo caso, avrai bisogno di troncare la sequenza per avere una lunghezza minore.
+
+Imposta il parametro `truncation` a `True` per troncare una sequenza alla massima lunghezza accettata dal modello:
+
+```py
+>>> batch_sentences = [
+... "But what about second breakfast?",
+... "Don't think he knows about second breakfast, Pip.",
+... "What about elevensies?",
+... ]
+>>> encoded_input = tokenizer(batch_sentences, padding=True, truncation=True)
+>>> print(encoded_input)
+{'input_ids': [[101, 1252, 1184, 1164, 1248, 6462, 136, 102, 0, 0, 0, 0, 0, 0, 0],
+ [101, 1790, 112, 189, 1341, 1119, 3520, 1164, 1248, 6462, 117, 21902, 1643, 119, 102],
+ [101, 1327, 1164, 5450, 23434, 136, 102, 0, 0, 0, 0, 0, 0, 0, 0]],
+ 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
+ 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0],
+ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
+ [1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]]}
+```
+
+### Costruire i tensori
+
+Infine, vuoi che il tokenizer restituisca i tensori prodotti dal modello.
+
+Imposta il parametro `return_tensors` su `pt` per PyTorch, o `tf` per TensorFlow:
+
+```py
+>>> batch_sentences = [
+... "But what about second breakfast?",
+... "Don't think he knows about second breakfast, Pip.",
+... "What about elevensies?",
+... ]
+>>> encoded_input = tokenizer(batch, padding=True, truncation=True, return_tensors="pt")
+>>> print(encoded_input)
+{'input_ids': tensor([[ 101, 153, 7719, 21490, 1122, 1114, 9582, 1623, 102],
+ [ 101, 5226, 1122, 9649, 1199, 2610, 1236, 102, 0]]),
+ 'token_type_ids': tensor([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]]),
+ 'attention_mask': tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1],
+ [1, 1, 1, 1, 1, 1, 1, 1, 0]])}
+===PT-TF-SPLIT===
+>>> batch_sentences = [
+... "But what about second breakfast?",
+... "Don't think he knows about second breakfast, Pip.",
+... "What about elevensies?",
+... ]
+>>> encoded_input = tokenizer(batch, padding=True, truncation=True, return_tensors="tf")
+>>> print(encoded_input)
+{'input_ids': ,
+ 'token_type_ids': ,
+ 'attention_mask': }
+```
+
+## Audio
+
+Gli input audio sono processati in modo differente rispetto al testo, ma l'obiettivo rimane lo stesso: creare sequenze numeriche che il modello puĂČ capire. Un [estrattore di caratteristiche](main_classes/feature_extractor) Ăš progettato con lo scopo preciso di estrarre caratteristiche da immagini o dati audio grezzi e convertirli in tensori. Prima di iniziare, installa đ€ Datasets per caricare un dataset audio e sperimentare:
+
+```bash
+pip install datasets
+```
+
+Carica il dataset [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) (vedi il đ€ [Datasets tutorial](https://huggingface.co/docs/datasets/load_hub.html) per avere maggiori dettagli su come caricare un dataset):
+
+```py
+>>> from datasets import load_dataset, Audio
+
+>>> dataset = load_dataset("PolyAI/minds14", name="en-US", split="train")
+```
+
+Accedi al primo elemento della colonna `audio` per dare uno sguardo all'input. Richiamando la colonna `audio` sarĂ caricato automaticamente e ricampionato il file audio:
+
+```py
+>>> dataset[0]["audio"]
+{'array': array([ 0. , 0.00024414, -0.00024414, ..., -0.00024414,
+ 0. , 0. ], dtype=float32),
+ 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav',
+ 'sampling_rate': 8000}
+```
+
+Questo restituisce tre oggetti:
+
+* `array` Ăš il segnale vocale caricato - e potenzialmente ricampionato - come vettore 1D.
+* `path` il percorso del file audio.
+* `sampling_rate` si riferisce al numero di campioni del segnale vocale misurati al secondo.
+
+### Ricampionamento
+
+Per questo tutorial, puoi usare il modello [Wav2Vec2](https://huggingface.co/facebook/wav2vec2-base). Come puoi vedere dalla model card, il modello Wav2Vec2 Ăš preaddestrato su un campionamento vocale a 16kHz.Ă importante che la frequenza di campionamento dei tuoi dati audio combaci con la frequenza di campionamento del dataset usato per preaddestrare il modello. Se la frequenza di campionamento dei tuoi dati non Ăš uguale dovrai ricampionare i tuoi dati audio.
+
+Per esempio, il dataset [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) ha una frequenza di campionamento di 8000kHz. Utilizzando il modello Wav2Vec2 su questo dataset, alzala a 16kHz:
+
+```py
+>>> dataset = load_dataset("PolyAI/minds14", name="en-US", split="train")
+>>> dataset[0]["audio"]
+{'array': array([ 0. , 0.00024414, -0.00024414, ..., -0.00024414,
+ 0. , 0. ], dtype=float32),
+ 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav',
+ 'sampling_rate': 8000}
+```
+
+1. Usa il metodo di đ€ Datasets' [`cast_column`](https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.cast_column) per alzare la frequenza di campionamento a 16kHz:
+
+```py
+>>> dataset = dataset.cast_column("audio", Audio(sampling_rate=16_000))
+```
+
+2. Carica il file audio:
+
+```py
+>>> dataset[0]["audio"]
+{'array': array([ 2.3443763e-05, 2.1729663e-04, 2.2145823e-04, ...,
+ 3.8356509e-05, -7.3497440e-06, -2.1754686e-05], dtype=float32),
+ 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav',
+ 'sampling_rate': 16000}
+```
+
+Come puoi notare, la `sampling_rate` adesso Ăš 16kHz!
+
+### Feature extractor
+
+Il prossimo passo Ăš caricare un estrattore di caratteristiche per normalizzare e fare padding sull'input. Quando applichiamo il padding sui dati testuali, uno `0` Ăš aggiunto alle sequenze piĂč brevi. La stessa idea si applica ai dati audio, l'estrattore di caratteristiche per gli audio aggiungerĂ uno `0` - interpretato come silenzio - agli `array`.
+
+Carica l'estrattore delle caratteristiche con [`AutoFeatureExtractor.from_pretrained`]:
+
+```py
+>>> from transformers import AutoFeatureExtractor
+
+>>> feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base")
+```
+
+Inserisci l' `array` audio nell'estrattore delle caratteristiche. Noi raccomandiamo sempre di aggiungere il parametro `sampling_rate` nell'estrattore delle caratteristiche per correggere meglio qualche errore, dovuto ai silenzi, che potrebbe verificarsi.
+
+```py
+>>> audio_input = [dataset[0]["audio"]["array"]]
+>>> feature_extractor(audio_input, sampling_rate=16000)
+{'input_values': [array([ 3.8106556e-04, 2.7506407e-03, 2.8015103e-03, ...,
+ 5.6335266e-04, 4.6588284e-06, -1.7142107e-04], dtype=float32)]}
+```
+
+### Pad e truncate
+
+Come per il tokenizer, puoi applicare le operazioni padding o truncation per manipolare sequenze di variabili a lotti. Dai uno sguaro alla lunghezza delle sequenze di questi due campioni audio:
+
+```py
+>>> dataset[0]["audio"]["array"].shape
+(173398,)
+
+>>> dataset[1]["audio"]["array"].shape
+(106496,)
+```
+
+Come puoi vedere, il primo campione ha una sequenza piĂč lunga del secondo. Crea una funzione che preprocesserĂ il dataset. Specifica una lunghezza massima del campione, e l'estrattore di features si occuperĂ di riempire o troncare la sequenza per coincidervi:
+
+```py
+>>> def preprocess_function(examples):
+... audio_arrays = [x["array"] for x in examples["audio"]]
+... inputs = feature_extractor(
+... audio_arrays,
+... sampling_rate=16000,
+... padding=True,
+... max_length=100000,
+... truncation=True,
+... )
+... return inputs
+```
+
+Applica la funzione ai primi esempi nel dataset:
+
+```py
+>>> processed_dataset = preprocess_function(dataset[:5])
+```
+
+Adesso guarda la lunghezza dei campioni elaborati:
+
+```py
+>>> processed_dataset["input_values"][0].shape
+(100000,)
+
+>>> processed_dataset["input_values"][1].shape
+(100000,)
+```
+
+La lunghezza dei campioni adesso coincide con la massima lunghezza impostata nelle funzione.
+
+## Vision
+
+Un estrattore di caratteristiche si puĂČ usare anche per processare immagini e per compiti di visione. Ancora una volta, l'obiettivo Ăš convertire l'immagine grezza in un lotto di tensori come input.
+
+Carica il dataset [food101](https://huggingface.co/datasets/food101) per questa esercitazione. Usa il parametro `split` di đ€ Datasets per caricare solo un piccolo campione dal dataset di addestramento poichĂš il set di dati Ăš molto grande:
+
+```py
+>>> from datasets import load_dataset
+
+>>> dataset = load_dataset("food101", split="train[:100]")
+```
+
+Secondo passo, dai uno sguardo alle immagini usando la caratteristica [`Image`](https://huggingface.co/docs/datasets/package_reference/main_classes.html?highlight=image#datasets.Image) di đ€ Datasets:
+
+```py
+>>> dataset[0]["image"]
+```
+
+
+
+### Feature extractor
+
+Carica l'estrattore di caratteristiche [`AutoFeatureExtractor.from_pretrained`]:
+
+```py
+>>> from transformers import AutoFeatureExtractor
+
+>>> feature_extractor = AutoFeatureExtractor.from_pretrained("google/vit-base-patch16-224")
+```
+
+### Data augmentation
+
+Per le attivitĂ di visione, Ăš usuale aggiungere alcuni tipi di data augmentation alle immagini come parte del preprocessing. Puoi aggiungere augmentations con qualsiasi libreria che preferisci, ma in questa esercitazione, userai il modulo [`transforms`](https://pytorch.org/vision/stable/transforms.html) di torchvision.
+
+1. Normalizza l'immagine e usa [`Compose`](https://pytorch.org/vision/master/generated/torchvision.transforms.Compose.html) per concatenare alcune trasformazioni - [`RandomResizedCrop`](https://pytorch.org/vision/main/generated/torchvision.transforms.RandomResizedCrop.html) e [`ColorJitter`](https://pytorch.org/vision/main/generated/torchvision.transforms.ColorJitter.html) - insieme:
+
+```py
+>>> from torchvision.transforms import Compose, Normalize, RandomResizedCrop, ColorJitter, ToTensor
+
+>>> normalize = Normalize(mean=feature_extractor.image_mean, std=feature_extractor.image_std)
+>>> _transforms = Compose(
+... [RandomResizedCrop(feature_extractor.size), ColorJitter(brightness=0.5, hue=0.5), ToTensor(), normalize]
+... )
+```
+
+2. Il modello accetta [`pixel_values`](model_doc/visionencoderdecoder#transformers.VisionEncoderDecoderModel.forward.pixel_values) come input. Questo valore Ăš generato dall'estrattore di caratteristiche. Crea una funzione che genera `pixel_values` dai transforms:
+
+```py
+>>> def transforms(examples):
+... examples["pixel_values"] = [_transforms(image.convert("RGB")) for image in examples["image"]]
+... return examples
+```
+
+3. Poi utilizza đ€ Datasets [`set_transform`](https://huggingface.co/docs/datasets/process.html#format-transform)per applicare al volo la trasformazione:
+
+```py
+>>> dataset.set_transform(transforms)
+```
+
+4. Adesso quando accedi all'immagine, puoi notare che l'estrattore di caratteristiche ha aggiunto `pixel_values` allo schema di input:
+
+```py
+>>> dataset[0]["image"]
+{'image': ,
+ 'label': 6,
+ 'pixel_values': tensor([[[ 0.0353, 0.0745, 0.1216, ..., -0.9922, -0.9922, -0.9922],
+ [-0.0196, 0.0667, 0.1294, ..., -0.9765, -0.9843, -0.9922],
+ [ 0.0196, 0.0824, 0.1137, ..., -0.9765, -0.9686, -0.8667],
+ ...,
+ [ 0.0275, 0.0745, 0.0510, ..., -0.1137, -0.1216, -0.0824],
+ [ 0.0667, 0.0824, 0.0667, ..., -0.0588, -0.0745, -0.0980],
+ [ 0.0353, 0.0353, 0.0431, ..., -0.0039, -0.0039, -0.0588]],
+
+ [[ 0.2078, 0.2471, 0.2863, ..., -0.9451, -0.9373, -0.9451],
+ [ 0.1608, 0.2471, 0.3098, ..., -0.9373, -0.9451, -0.9373],
+ [ 0.2078, 0.2706, 0.3020, ..., -0.9608, -0.9373, -0.8275],
+ ...,
+ [-0.0353, 0.0118, -0.0039, ..., -0.2392, -0.2471, -0.2078],
+ [ 0.0196, 0.0353, 0.0196, ..., -0.1843, -0.2000, -0.2235],
+ [-0.0118, -0.0039, -0.0039, ..., -0.0980, -0.0980, -0.1529]],
+
+ [[ 0.3961, 0.4431, 0.4980, ..., -0.9216, -0.9137, -0.9216],
+ [ 0.3569, 0.4510, 0.5216, ..., -0.9059, -0.9137, -0.9137],
+ [ 0.4118, 0.4745, 0.5216, ..., -0.9137, -0.8902, -0.7804],
+ ...,
+ [-0.2314, -0.1922, -0.2078, ..., -0.4196, -0.4275, -0.3882],
+ [-0.1843, -0.1686, -0.2000, ..., -0.3647, -0.3804, -0.4039],
+ [-0.1922, -0.1922, -0.1922, ..., -0.2941, -0.2863, -0.3412]]])}
+```
+
+Di seguito come si vede l'immagine dopo la fase di preprocessing. Come ci si aspetterebbe dalle trasformazioni applicate, l'immagine Ăš stata ritagliata in modo casuale e le proprietĂ del colore sono diverse.
+
+```py
+>>> import numpy as np
+>>> import matplotlib.pyplot as plt
+
+>>> img = dataset[0]["pixel_values"]
+>>> plt.imshow(img.permute(1, 2, 0))
+```
+
+
+
+## Multimodal
+
+Per attivitĂ multimodali userai una combinazione di tutto quello che hai imparato poco fa e applicherai le tue competenze alla comprensione automatica del parlato (Automatic Speech Recognition - ASR). Questo significa che avrai bisogno di:
+
+* Un estrattore delle caratteristiche per processare i dati audio.
+* Il Tokenizer per processare i testi.
+
+Ritorna sul datasere [LJ Speech](https://huggingface.co/datasets/lj_speech):
+
+```py
+>>> from datasets import load_dataset
+
+>>> lj_speech = load_dataset("lj_speech", split="train")
+```
+
+Visto che sei interessato solo alle colonne `audio` e `text`, elimina tutte le altre:
+
+```py
+>>> lj_speech = lj_speech.map(remove_columns=["file", "id", "normalized_text"])
+```
+
+Adesso guarda le colonne `audio` e `text`:
+
+```py
+>>> lj_speech[0]["audio"]
+{'array': array([-7.3242188e-04, -7.6293945e-04, -6.4086914e-04, ...,
+ 7.3242188e-04, 2.1362305e-04, 6.1035156e-05], dtype=float32),
+ 'path': '/root/.cache/huggingface/datasets/downloads/extracted/917ece08c95cf0c4115e45294e3cd0dee724a1165b7fc11798369308a465bd26/LJSpeech-1.1/wavs/LJ001-0001.wav',
+ 'sampling_rate': 22050}
+
+>>> lj_speech[0]["text"]
+'Printing, in the only sense with which we are at present concerned, differs from most if not from all the arts and crafts represented in the Exhibition'
+```
+
+Ricorda dalla sezione precedente sull'elaborazione dei dati audio, tu dovresti sempre [ricampionare](preprocessing#audio) la frequenza di campionamento dei tuoi dati audio per farla coincidere con quella del dataset usato dal modello preaddestrato:
+
+```py
+>>> lj_speech = lj_speech.cast_column("audio", Audio(sampling_rate=16_000))
+```
+
+### Processor
+
+Un processor combina un estrattore di caratteristiche e un tokenizer. Carica un processor con [`AutoProcessor.from_pretrained]:
+
+```py
+>>> from transformers import AutoProcessor
+
+>>> processor = AutoProcessor.from_pretrained("facebook/wav2vec2-base-960h")
+```
+
+1. Crea una funzione che processi i dati audio in `input_values`, e tokenizza il testo in `labels`. Questi sono i tuoi input per il modello:
+
+```py
+>>> def prepare_dataset(example):
+... audio = example["audio"]
+
+... example.update(processor(audio=audio["array"], text=example["text"], sampling_rate=16000))
+
+... return example
+```
+
+2. Applica la funzione `prepare_dataset` ad un campione:
+
+```py
+>>> prepare_dataset(lj_speech[0])
+```
+
+Nota che il processor ha aggiunto `input_values` e `labels`. La frequenza di campionamento Ăš stata corretta riducendola a 16kHz.
+
+Fantastico, ora dovresti essere in grado di preelaborare i dati per qualsiasi modalitĂ e persino di combinare modalitĂ diverse! Nella prossima esercitazione, impareremo a mettere a punto un modello sui dati appena pre-elaborati.
\ No newline at end of file
diff --git a/docs/source/it/preprocessing.mdx b/docs/source/it/preprocessing.mdx
deleted file mode 100644
index a57ff9df9151..000000000000
--- a/docs/source/it/preprocessing.mdx
+++ /dev/null
@@ -1,487 +0,0 @@
-
-
-# Preprocess
-
-[[open-in-colab]]
-
-Prima di poter usare i dati in un modello, bisogna processarli in un formato accettabile per quest'ultimo. Un modello non comprende il testo grezzo, le immagini o l'audio. Bisogna convertire questi input in numeri e assemblarli all'interno di tensori. In questa esercitazione, tu potrai:
-
-* Preprocessare dati testuali con un tokenizer.
-* Preprocessare immagini o dati audio con un estrattore di caratteristiche.
-* Preprocessare dati per attivitĂ multimodali mediante un processore.
-
-## NLP
-
-
-
-Lo strumento principale per processare dati testuali Ăš un [tokenizer](main_classes/tokenizer). Un tokenizer inizia separando il testo in *tokens* secondo una serie di regole. I tokens sono convertiti in numeri, questi vengono utilizzati per costruire i tensori di input del modello. Anche altri input addizionali se richiesti dal modello vengono aggiunti dal tokenizer.
-
-
-
-Se stai pensando si utilizzare un modello preaddestrato, Ăš importante utilizzare il tokenizer preaddestrato associato. Questo assicura che il testo sia separato allo stesso modo che nel corpus usato per l'addestramento, e venga usata la stessa mappatura tokens-to-index (solitamente indicato come il *vocabolario*) come nel preaddestramento.
-
-
-
-Iniziamo subito caricando un tokenizer preaddestrato con la classe [`AutoTokenizer`]. Questo scarica il *vocabolario* usato quando il modello Ăš stato preaddestrato.
-
-### Tokenize
-
-Carica un tokenizer preaddestrato con [`AutoTokenizer.from_pretrained`]:
-
-```py
->>> from transformers import AutoTokenizer
-
->>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
-```
-
-Poi inserisci le tue frasi nel tokenizer:
-
-```py
->>> encoded_input = tokenizer("Do not meddle in the affairs of wizards, for they are subtle and quick to anger.")
->>> print(encoded_input)
-{'input_ids': [101, 2079, 2025, 19960, 10362, 1999, 1996, 3821, 1997, 16657, 1010, 2005, 2027, 2024, 11259, 1998, 4248, 2000, 4963, 1012, 102],
- 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
- 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}
-```
-
-Il tokenizer restituisce un dizionario contenente tre oggetti importanti:
-
-* [input_ids](glossary#input-ids) sono gli indici che corrispondono ad ogni token nella frase.
-* [attention_mask](glossary#attention-mask) indicata se un token deve essere elaborato o no.
-* [token_type_ids](glossary#token-type-ids) identifica a quale sequenza appartiene un token se Ăš presente piĂč di una sequenza.
-
-Si possono decodificare gli `input_ids` per farsi restituire l'input originale:
-
-```py
->>> tokenizer.decode(encoded_input["input_ids"])
-'[CLS] Do not meddle in the affairs of wizards, for they are subtle and quick to anger. [SEP]'
-```
-
-Come si puĂČ vedere, il tokenizer aggiunge due token speciali - `CLS` e `SEP` (classificatore e separatore) - alla frase. Non tutti i modelli hanno bisogno dei token speciali, ma se servono, il tokenizer li aggiungerĂ automaticamente.
-
-Se ci sono piĂč frasi che vuoi processare, passale come una lista al tokenizer:
-
-```py
->>> batch_sentences = [
-... "But what about second breakfast?",
-... "Don't think he knows about second breakfast, Pip.",
-... "What about elevensies?",
-... ]
->>> encoded_inputs = tokenizer(batch_sentences)
->>> print(encoded_inputs)
-{'input_ids': [[101, 1252, 1184, 1164, 1248, 6462, 136, 102],
- [101, 1790, 112, 189, 1341, 1119, 3520, 1164, 1248, 6462, 117, 21902, 1643, 119, 102],
- [101, 1327, 1164, 5450, 23434, 136, 102]],
- 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0],
- [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
- [0, 0, 0, 0, 0, 0, 0]],
- 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1],
- [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
- [1, 1, 1, 1, 1, 1, 1]]}
-```
-
-### Pad
-
-Questo Ăš un argomento importante. Quando processi un insieme di frasi potrebbero non avere tutte la stessa lunghezza. Questo Ăš un problema perchĂš i tensori, in input del modello, devono avere dimensioni uniformi. Il padding Ăš una strategia per assicurarsi che i tensori siano rettangolari aggiungendo uno speciale *padding token* alle frasi piĂč corte.
-
-Imposta il parametro `padding` a `True` per imbottire le frasi piĂč corte nel gruppo in modo che combacino con la massima lunghezza presente:
-
-```py
->>> batch_sentences = [
-... "But what about second breakfast?",
-... "Don't think he knows about second breakfast, Pip.",
-... "What about elevensies?",
-... ]
->>> encoded_input = tokenizer(batch_sentences, padding=True)
->>> print(encoded_input)
-{'input_ids': [[101, 1252, 1184, 1164, 1248, 6462, 136, 102, 0, 0, 0, 0, 0, 0, 0],
- [101, 1790, 112, 189, 1341, 1119, 3520, 1164, 1248, 6462, 117, 21902, 1643, 119, 102],
- [101, 1327, 1164, 5450, 23434, 136, 102, 0, 0, 0, 0, 0, 0, 0, 0]],
- 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
- [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
- [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
- 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0],
- [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
- [1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]]}
-```
-
-Nota che il tokenizer aggiunge alle sequenze degli `0` perchĂš sono troppo corte!
-
-### Truncation
-
-L'altra faccia della medaglia Ăš che avolte le sequenze possono essere troppo lunghe per essere gestite dal modello. In questo caso, avrai bisogno di troncare la sequenza per avere una lunghezza minore.
-
-Imposta il parametro `truncation` a `True` per troncare una sequenza alla massima lunghezza accettata dal modello:
-
-```py
->>> batch_sentences = [
-... "But what about second breakfast?",
-... "Don't think he knows about second breakfast, Pip.",
-... "What about elevensies?",
-... ]
->>> encoded_input = tokenizer(batch_sentences, padding=True, truncation=True)
->>> print(encoded_input)
-{'input_ids': [[101, 1252, 1184, 1164, 1248, 6462, 136, 102, 0, 0, 0, 0, 0, 0, 0],
- [101, 1790, 112, 189, 1341, 1119, 3520, 1164, 1248, 6462, 117, 21902, 1643, 119, 102],
- [101, 1327, 1164, 5450, 23434, 136, 102, 0, 0, 0, 0, 0, 0, 0, 0]],
- 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
- [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
- [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
- 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0],
- [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
- [1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]]}
-```
-
-### Costruire i tensori
-
-Infine, vuoi che il tokenizer restituisca i tensori prodotti dal modello.
-
-Imposta il parametro `return_tensors` su `pt` per PyTorch, o `tf` per TensorFlow:
-
-```py
->>> batch_sentences = [
-... "But what about second breakfast?",
-... "Don't think he knows about second breakfast, Pip.",
-... "What about elevensies?",
-... ]
->>> encoded_input = tokenizer(batch, padding=True, truncation=True, return_tensors="pt")
->>> print(encoded_input)
-{'input_ids': tensor([[ 101, 153, 7719, 21490, 1122, 1114, 9582, 1623, 102],
- [ 101, 5226, 1122, 9649, 1199, 2610, 1236, 102, 0]]),
- 'token_type_ids': tensor([[0, 0, 0, 0, 0, 0, 0, 0, 0],
- [0, 0, 0, 0, 0, 0, 0, 0, 0]]),
- 'attention_mask': tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1],
- [1, 1, 1, 1, 1, 1, 1, 1, 0]])}
-===PT-TF-SPLIT===
->>> batch_sentences = [
-... "But what about second breakfast?",
-... "Don't think he knows about second breakfast, Pip.",
-... "What about elevensies?",
-... ]
->>> encoded_input = tokenizer(batch, padding=True, truncation=True, return_tensors="tf")
->>> print(encoded_input)
-{'input_ids': ,
- 'token_type_ids': ,
- 'attention_mask': }
-```
-
-## Audio
-
-Gli input audio sono processati in modo differente rispetto al testo, ma l'obiettivo rimane lo stesso: creare sequenze numeriche che il modello puĂČ capire. Un [estrattore di caratteristiche](main_classes/feature_extractor) Ăš progettato con lo scopo preciso di estrarre caratteristiche da immagini o dati audio grezzi e convertirli in tensori. Prima di iniziare, installa đ€ Datasets per caricare un dataset audio e sperimentare:
-
-```bash
-pip install datasets
-```
-
-Carica il dataset [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) (vedi il đ€ [Datasets tutorial](https://huggingface.co/docs/datasets/load_hub.html) per avere maggiori dettagli su come caricare un dataset):
-
-```py
->>> from datasets import load_dataset, Audio
-
->>> dataset = load_dataset("PolyAI/minds14", name="en-US", split="train")
-```
-
-Accedi al primo elemento della colonna `audio` per dare uno sguardo all'input. Richiamando la colonna `audio` sarĂ caricato automaticamente e ricampionato il file audio:
-
-```py
->>> dataset[0]["audio"]
-{'array': array([ 0. , 0.00024414, -0.00024414, ..., -0.00024414,
- 0. , 0. ], dtype=float32),
- 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav',
- 'sampling_rate': 8000}
-```
-
-Questo restituisce tre oggetti:
-
-* `array` Ăš il segnale vocale caricato - e potenzialmente ricampionato - come vettore 1D.
-* `path` il percorso del file audio.
-* `sampling_rate` si riferisce al numero di campioni del segnale vocale misurati al secondo.
-
-### Ricampionamento
-
-Per questo tutorial, puoi usare il modello [Wav2Vec2](https://huggingface.co/facebook/wav2vec2-base). Come puoi vedere dalla model card, il modello Wav2Vec2 Ăš preaddestrato su un campionamento vocale a 16kHz.Ă importante che la frequenza di campionamento dei tuoi dati audio combaci con la frequenza di campionamento del dataset usato per preaddestrare il modello. Se la frequenza di campionamento dei tuoi dati non Ăš uguale dovrai ricampionare i tuoi dati audio.
-
-Per esempio, il dataset [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) ha una frequenza di campionamento di 8000kHz. Utilizzando il modello Wav2Vec2 su questo dataset, alzala a 16kHz:
-
-```py
->>> dataset = load_dataset("PolyAI/minds14", name="en-US", split="train")
->>> dataset[0]["audio"]
-{'array': array([ 0. , 0.00024414, -0.00024414, ..., -0.00024414,
- 0. , 0. ], dtype=float32),
- 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav',
- 'sampling_rate': 8000}
-```
-
-1. Usa il metodo di đ€ Datasets' [`cast_column`](https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.cast_column) per alzare la frequenza di campionamento a 16kHz:
-
-```py
->>> dataset = dataset.cast_column("audio", Audio(sampling_rate=16_000))
-```
-
-2. Carica il file audio:
-
-```py
->>> dataset[0]["audio"]
-{'array': array([ 2.3443763e-05, 2.1729663e-04, 2.2145823e-04, ...,
- 3.8356509e-05, -7.3497440e-06, -2.1754686e-05], dtype=float32),
- 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav',
- 'sampling_rate': 16000}
-```
-
-Come puoi notare, la `sampling_rate` adesso Ăš 16kHz!
-
-### Feature extractor
-
-Il prossimo passo Ăš caricare un estrattore di caratteristiche per normalizzare e fare padding sull'input. Quando applichiamo il padding sui dati testuali, uno `0` Ăš aggiunto alle sequenze piĂč brevi. La stessa idea si applica ai dati audio, l'estrattore di caratteristiche per gli audio aggiungerĂ uno `0` - interpretato come silenzio - agli `array`.
-
-Carica l'estrattore delle caratteristiche con [`AutoFeatureExtractor.from_pretrained`]:
-
-```py
->>> from transformers import AutoFeatureExtractor
-
->>> feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base")
-```
-
-Inserisci l' `array` audio nell'estrattore delle caratteristiche. Noi raccomandiamo sempre di aggiungere il parametro `sampling_rate` nell'estrattore delle caratteristiche per correggere meglio qualche errore, dovuto ai silenzi, che potrebbe verificarsi.
-
-```py
->>> audio_input = [dataset[0]["audio"]["array"]]
->>> feature_extractor(audio_input, sampling_rate=16000)
-{'input_values': [array([ 3.8106556e-04, 2.7506407e-03, 2.8015103e-03, ...,
- 5.6335266e-04, 4.6588284e-06, -1.7142107e-04], dtype=float32)]}
-```
-
-### Pad e truncate
-
-Come per il tokenizer, puoi applicare le operazioni padding o truncation per manipolare sequenze di variabili a lotti. Dai uno sguaro alla lunghezza delle sequenze di questi due campioni audio:
-
-```py
->>> dataset[0]["audio"]["array"].shape
-(173398,)
-
->>> dataset[1]["audio"]["array"].shape
-(106496,)
-```
-
-Come puoi vedere, il primo campione ha una sequenza piĂč lunga del secondo. Crea una funzione che preprocesserĂ il dataset. Specifica una lunghezza massima del campione, e l'estrattore di features si occuperĂ di riempire o troncare la sequenza per coincidervi:
-
-```py
->>> def preprocess_function(examples):
-... audio_arrays = [x["array"] for x in examples["audio"]]
-... inputs = feature_extractor(
-... audio_arrays,
-... sampling_rate=16000,
-... padding=True,
-... max_length=100000,
-... truncation=True,
-... )
-... return inputs
-```
-
-Applica la funzione ai primi esempi nel dataset:
-
-```py
->>> processed_dataset = preprocess_function(dataset[:5])
-```
-
-Adesso guarda la lunghezza dei campioni elaborati:
-
-```py
->>> processed_dataset["input_values"][0].shape
-(100000,)
-
->>> processed_dataset["input_values"][1].shape
-(100000,)
-```
-
-La lunghezza dei campioni adesso coincide con la massima lunghezza impostata nelle funzione.
-
-## Vision
-
-Un estrattore di caratteristiche si puĂČ usare anche per processare immagini e per compiti di visione. Ancora una volta, l'obiettivo Ăš convertire l'immagine grezza in un lotto di tensori come input.
-
-Carica il dataset [food101](https://huggingface.co/datasets/food101) per questa esercitazione. Usa il parametro `split` di đ€ Datasets per caricare solo un piccolo campione dal dataset di addestramento poichĂš il set di dati Ăš molto grande:
-
-```py
->>> from datasets import load_dataset
-
->>> dataset = load_dataset("food101", split="train[:100]")
-```
-
-Secondo passo, dai uno sguardo alle immagini usando la caratteristica [`Image`](https://huggingface.co/docs/datasets/package_reference/main_classes.html?highlight=image#datasets.Image) di đ€ Datasets:
-
-```py
->>> dataset[0]["image"]
-```
-
-
-
-### Feature extractor
-
-Carica l'estrattore di caratteristiche [`AutoFeatureExtractor.from_pretrained`]:
-
-```py
->>> from transformers import AutoFeatureExtractor
-
->>> feature_extractor = AutoFeatureExtractor.from_pretrained("google/vit-base-patch16-224")
-```
-
-### Data augmentation
-
-Per le attivitĂ di visione, Ăš usuale aggiungere alcuni tipi di data augmentation alle immagini come parte del preprocessing. Puoi aggiungere augmentations con qualsiasi libreria che preferisci, ma in questa esercitazione, userai il modulo [`transforms`](https://pytorch.org/vision/stable/transforms.html) di torchvision.
-
-1. Normalizza l'immagine e usa [`Compose`](https://pytorch.org/vision/master/generated/torchvision.transforms.Compose.html) per concatenare alcune trasformazioni - [`RandomResizedCrop`](https://pytorch.org/vision/main/generated/torchvision.transforms.RandomResizedCrop.html) e [`ColorJitter`](https://pytorch.org/vision/main/generated/torchvision.transforms.ColorJitter.html) - insieme:
-
-```py
->>> from torchvision.transforms import Compose, Normalize, RandomResizedCrop, ColorJitter, ToTensor
-
->>> normalize = Normalize(mean=feature_extractor.image_mean, std=feature_extractor.image_std)
->>> _transforms = Compose(
-... [RandomResizedCrop(feature_extractor.size), ColorJitter(brightness=0.5, hue=0.5), ToTensor(), normalize]
-... )
-```
-
-2. Il modello accetta [`pixel_values`](model_doc/visionencoderdecoder#transformers.VisionEncoderDecoderModel.forward.pixel_values) come input. Questo valore Ăš generato dall'estrattore di caratteristiche. Crea una funzione che genera `pixel_values` dai transforms:
-
-```py
->>> def transforms(examples):
-... examples["pixel_values"] = [_transforms(image.convert("RGB")) for image in examples["image"]]
-... return examples
-```
-
-3. Poi utilizza đ€ Datasets [`set_transform`](https://huggingface.co/docs/datasets/process.html#format-transform)per applicare al volo la trasformazione:
-
-```py
->>> dataset.set_transform(transforms)
-```
-
-4. Adesso quando accedi all'immagine, puoi notare che l'estrattore di caratteristiche ha aggiunto `pixel_values` allo schema di input:
-
-```py
->>> dataset[0]["image"]
-{'image': ,
- 'label': 6,
- 'pixel_values': tensor([[[ 0.0353, 0.0745, 0.1216, ..., -0.9922, -0.9922, -0.9922],
- [-0.0196, 0.0667, 0.1294, ..., -0.9765, -0.9843, -0.9922],
- [ 0.0196, 0.0824, 0.1137, ..., -0.9765, -0.9686, -0.8667],
- ...,
- [ 0.0275, 0.0745, 0.0510, ..., -0.1137, -0.1216, -0.0824],
- [ 0.0667, 0.0824, 0.0667, ..., -0.0588, -0.0745, -0.0980],
- [ 0.0353, 0.0353, 0.0431, ..., -0.0039, -0.0039, -0.0588]],
-
- [[ 0.2078, 0.2471, 0.2863, ..., -0.9451, -0.9373, -0.9451],
- [ 0.1608, 0.2471, 0.3098, ..., -0.9373, -0.9451, -0.9373],
- [ 0.2078, 0.2706, 0.3020, ..., -0.9608, -0.9373, -0.8275],
- ...,
- [-0.0353, 0.0118, -0.0039, ..., -0.2392, -0.2471, -0.2078],
- [ 0.0196, 0.0353, 0.0196, ..., -0.1843, -0.2000, -0.2235],
- [-0.0118, -0.0039, -0.0039, ..., -0.0980, -0.0980, -0.1529]],
-
- [[ 0.3961, 0.4431, 0.4980, ..., -0.9216, -0.9137, -0.9216],
- [ 0.3569, 0.4510, 0.5216, ..., -0.9059, -0.9137, -0.9137],
- [ 0.4118, 0.4745, 0.5216, ..., -0.9137, -0.8902, -0.7804],
- ...,
- [-0.2314, -0.1922, -0.2078, ..., -0.4196, -0.4275, -0.3882],
- [-0.1843, -0.1686, -0.2000, ..., -0.3647, -0.3804, -0.4039],
- [-0.1922, -0.1922, -0.1922, ..., -0.2941, -0.2863, -0.3412]]])}
-```
-
-Di seguito come si vede l'immagine dopo la fase di preprocessing. Come ci si aspetterebbe dalle trasformazioni applicate, l'immagine Ăš stata ritagliata in modo casuale e le proprietĂ del colore sono diverse.
-
-```py
->>> import numpy as np
->>> import matplotlib.pyplot as plt
-
->>> img = dataset[0]["pixel_values"]
->>> plt.imshow(img.permute(1, 2, 0))
-```
-
-
-
-## Multimodal
-
-Per attivitĂ multimodali userai una combinazione di tutto quello che hai imparato poco fa e applicherai le tue competenze alla comprensione automatica del parlato (Automatic Speech Recognition - ASR). Questo significa che avrai bisogno di:
-
-* Un estrattore delle caratteristiche per processare i dati audio.
-* Il Tokenizer per processare i testi.
-
-Ritorna sul datasere [LJ Speech](https://huggingface.co/datasets/lj_speech):
-
-```py
->>> from datasets import load_dataset
-
->>> lj_speech = load_dataset("lj_speech", split="train")
-```
-
-Visto che sei interessato solo alle colonne `audio` e `text`, elimina tutte le altre:
-
-```py
->>> lj_speech = lj_speech.map(remove_columns=["file", "id", "normalized_text"])
-```
-
-Adesso guarda le colonne `audio` e `text`:
-
-```py
->>> lj_speech[0]["audio"]
-{'array': array([-7.3242188e-04, -7.6293945e-04, -6.4086914e-04, ...,
- 7.3242188e-04, 2.1362305e-04, 6.1035156e-05], dtype=float32),
- 'path': '/root/.cache/huggingface/datasets/downloads/extracted/917ece08c95cf0c4115e45294e3cd0dee724a1165b7fc11798369308a465bd26/LJSpeech-1.1/wavs/LJ001-0001.wav',
- 'sampling_rate': 22050}
-
->>> lj_speech[0]["text"]
-'Printing, in the only sense with which we are at present concerned, differs from most if not from all the arts and crafts represented in the Exhibition'
-```
-
-Ricorda dalla sezione precedente sull'elaborazione dei dati audio, tu dovresti sempre [ricampionare](preprocessing#audio) la frequenza di campionamento dei tuoi dati audio per farla coincidere con quella del dataset usato dal modello preaddestrato:
-
-```py
->>> lj_speech = lj_speech.cast_column("audio", Audio(sampling_rate=16_000))
-```
-
-### Processor
-
-Un processor combina un estrattore di caratteristiche e un tokenizer. Carica un processor con [`AutoProcessor.from_pretrained]:
-
-```py
->>> from transformers import AutoProcessor
-
->>> processor = AutoProcessor.from_pretrained("facebook/wav2vec2-base-960h")
-```
-
-1. Crea una funzione che processi i dati audio in `input_values`, e tokenizza il testo in `labels`. Questi sono i tuoi input per il modello:
-
-```py
->>> def prepare_dataset(example):
-... audio = example["audio"]
-
-... example.update(processor(audio=audio["array"], text=example["text"], sampling_rate=16000))
-
-... return example
-```
-
-2. Applica la funzione `prepare_dataset` ad un campione:
-
-```py
->>> prepare_dataset(lj_speech[0])
-```
-
-Nota che il processor ha aggiunto `input_values` e `labels`. La frequenza di campionamento Ăš stata corretta riducendola a 16kHz.
-
-Fantastico, ora dovresti essere in grado di preelaborare i dati per qualsiasi modalitĂ e persino di combinare modalitĂ diverse! Nella prossima esercitazione, impareremo a mettere a punto un modello sui dati appena pre-elaborati.
\ No newline at end of file
diff --git a/docs/source/it/quicktour.md b/docs/source/it/quicktour.md
new file mode 100644
index 000000000000..2ec450e238f8
--- /dev/null
+++ b/docs/source/it/quicktour.md
@@ -0,0 +1,397 @@
+
+
+# Quick tour
+
+[[open-in-colab]]
+
+Entra in azione con đ€ Transformers! Inizia utilizzando [`pipeline`] per un'inferenza veloce, carica un modello pre-allenato e un tokenizer con una [AutoClass](./model_doc/auto) per risolvere i tuoi compiti legati a testo, immagini o audio.
+
+
+
+Tutti gli esempi di codice presenti in questa documentazione hanno un pulsante in alto a sinistra che permette di selezionare tra PyTorch e TensorFlow. Se
+questo non Ăš presente, ci si aspetta che il codice funzioni per entrambi i backend senza alcun cambiamento.
+
+
+
+## Pipeline
+
+[`pipeline`] Ăš il modo piĂč semplice per utilizzare un modello pre-allenato per un dato compito.
+
+
+
+La [`pipeline`] supporta molti compiti comuni:
+
+**Testo**:
+* Analisi del Sentimento (Sentiment Analysis, in inglese): classifica la polaritĂ di un testo dato.
+* Generazione del Testo (Text Generation, in inglese): genera del testo a partire da un dato input.
+* Riconoscimento di EntitĂ (Name Entity Recognition o NER, in inglese): etichetta ogni parola con l'entitĂ che questa rappresenta (persona, data, luogo, ecc.).
+* Rispondere a Domande (Question answering, in inglese): estrae la risposta da un contesto, dato del contesto e una domanda.
+* Riempimento di Maschere (Fill-mask, in inglese): riempie gli spazi mancanti in un testo che ha parole mascherate.
+* Riassumere (Summarization, in inglese): genera una sintesi di una lunga sequenza di testo o di un documento.
+* Traduzione (Translation, in inglese): traduce un testo in un'altra lingua.
+* Estrazione di Caratteristiche (Feature Extraction, in inglese): crea un tensore che rappresenta un testo.
+
+**Immagini**:
+* Classificazione di Immagini (Image Classification, in inglese): classifica un'immagine.
+* Segmentazione di Immagini (Image Segmentation, in inglese): classifica ogni pixel di un'immagine.
+* Rilevazione di Oggetti (Object Detection, in inglese): rileva oggetti all'interno di un'immagine.
+
+**Audio**:
+* Classificazione di Audio (Audio Classification, in inglese): assegna un'etichetta ad un segmento di audio dato.
+* Riconoscimento Vocale Automatico (Automatic Speech Recognition o ASR, in inglese): trascrive il contenuto di un audio dato in un testo.
+
+
+
+Per maggiori dettagli legati alla [`pipeline`] e ai compiti ad essa associati, fai riferimento alla documentazione [qui](./main_classes/pipelines).
+
+
+
+### Utilizzo della Pipeline
+
+Nel seguente esempio, utilizzerai la [`pipeline`] per l'analisi del sentimento.
+
+Installa le seguenti dipendenze se non lo hai giĂ fatto:
+
+
+
+```bash
+pip install torch
+```
+
+
+```bash
+pip install tensorflow
+```
+
+
+
+Importa [`pipeline`] e specifica il compito che vuoi completare:
+
+```py
+>>> from transformers import pipeline
+
+>>> classificatore = pipeline("sentiment-analysis", model="MilaNLProc/feel-it-italian-sentiment")
+```
+
+La pipeline scarica e salva il [modello pre-allenato](https://huggingface.co/MilaNLProc/feel-it-italian-sentiment) e il tokenizer per l'analisi del sentimento. Se non avessimo scelto un modello, la pipeline ne avrebbe scelto uno di default. Ora puoi utilizzare il `classifier` sul tuo testo obiettivo:
+
+```py
+>>> classificatore("Siamo molto felici di mostrarti la libreria đ€ Transformers.")
+[{'label': 'positive', 'score': 0.9997}]
+```
+
+Per piĂč di una frase, passa una lista di frasi alla [`pipeline`] la quale restituirĂ una lista di dizionari:
+
+```py
+>>> risultati = classificatore(
+... ["Siamo molto felici di mostrarti la libreria đ€ Transformers.", "Speriamo te non la odierai."]
+... )
+>>> for risultato in risultati:
+... print(f"etichetta: {risultato['label']}, con punteggio: {round(risultato['score'], 4)}")
+etichetta: positive, con punteggio: 0.9998
+etichetta: negative, con punteggio: 0.9998
+```
+
+La [`pipeline`] puĂČ anche iterare su un dataset intero. Inizia installando la libreria [đ€ Datasets](https://huggingface.co/docs/datasets/):
+
+```bash
+pip install datasets
+```
+
+Crea una [`pipeline`] con il compito che vuoi risolvere e con il modello che vuoi utilizzare.
+
+```py
+>>> import torch
+>>> from transformers import pipeline
+
+>>> riconoscitore_vocale = pipeline(
+... "automatic-speech-recognition", model="radiogroup-crits/wav2vec2-xls-r-1b-italian-doc4lm-5gram"
+... )
+```
+
+Poi, carica un dataset (vedi đ€ Datasets [Quick Start](https://huggingface.co/docs/datasets/quickstart.html) per maggiori dettagli) sul quale vuoi iterare. Per esempio, carichiamo il dataset [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14):
+
+```py
+>>> from datasets import load_dataset, Audio
+
+>>> dataset = load_dataset("PolyAI/minds14", name="it-IT", split="train") # doctest: +IGNORE_RESULT
+```
+
+Dobbiamo assicurarci che la frequenza di campionamento del set di dati corrisponda alla frequenza di campionamento con cui Ăš stato addestrato `radiogroup-crits/wav2vec2-xls-r-1b-italian-doc4lm-5gram`.
+
+```py
+>>> dataset = dataset.cast_column("audio", Audio(sampling_rate=riconoscitore_vocale.feature_extractor.sampling_rate))
+```
+
+I file audio vengono caricati automaticamente e ri-campionati quando chiamiamo la colonna "audio".
+Estraiamo i vettori delle forme d'onda grezze delle prime 4 osservazioni e passiamoli come lista alla pipeline:
+
+```py
+>>> risultato = riconoscitore_vocale(dataset[:4]["audio"])
+>>> print([d["text"] for d in risultato])
+['dovrei caricare dei soldi sul mio conto corrente', 'buongiorno e senza vorrei depositare denaro sul mio conto corrente come devo fare per cortesia', 'sĂŹ salve vorrei depositare del denaro sul mio conto', 'e buon pomeriggio vorrei depositare dei soldi sul mio conto bancario volleo sapere come posso fare se e posso farlo online ed un altro conto o andandoo tramite bancomut']
+```
+
+Per un dataset piĂč grande dove gli input sono di dimensione maggiore (come nel parlato/audio o nella visione), dovrai passare un generatore al posto di una lista che carica tutti gli input in memoria. Guarda la [documentazione della pipeline](./main_classes/pipelines) per maggiori informazioni.
+
+### Utilizzare un altro modello e tokenizer nella pipeline
+
+La [`pipeline`] puĂČ ospitare qualsiasi modello del [Model Hub](https://huggingface.co/models), rendendo semplice l'adattamento della [`pipeline`] per altri casi d'uso. Per esempio, se si vuole un modello capace di trattare testo in francese, usa i tag presenti nel Model Hub in modo da filtrare per ottenere un modello appropriato. Il miglior risultato filtrato restituisce un modello multi-lingua [BERT model](https://huggingface.co/nlptown/bert-base-multilingual-uncased-sentiment) fine-tuned per l'analisi del sentimento. Ottimo, utilizziamo questo modello!
+
+```py
+>>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
+```
+
+
+
+Usa [`AutoModelForSequenceClassification`] e [`AutoTokenizer`] per caricare il modello pre-allenato e il suo tokenizer associato (maggiori informazioni su una `AutoClass` in seguito):
+
+```py
+>>> from transformers import AutoTokenizer, AutoModelForSequenceClassification
+
+>>> model = AutoModelForSequenceClassification.from_pretrained(model_name)
+>>> tokenizer = AutoTokenizer.from_pretrained(model_name)
+```
+
+
+Usa [`TFAutoModelForSequenceClassification`] e [`AutoTokenizer`] per caricare il modello pre-allenato e il suo tokenizer associato (maggiori informazioni su una `TFAutoClass` in seguito):
+
+```py
+>>> from transformers import AutoTokenizer, TFAutoModelForSequenceClassification
+
+>>> model = TFAutoModelForSequenceClassification.from_pretrained(model_name)
+>>> tokenizer = AutoTokenizer.from_pretrained(model_name)
+```
+
+
+
+Poi puoi specificare il modello e il tokenizer nella [`pipeline`], e applicare il `classifier` sul tuo testo obiettivo:
+
+```py
+>>> classifier = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer)
+>>> classifier("Nous sommes trĂšs heureux de vous prĂ©senter la bibliothĂšque đ€ Transformers.")
+[{'label': '5 stars', 'score': 0.7273}]
+```
+
+Se non riesci a trovare un modello per il tuo caso d'uso, dovrai fare fine-tuning di un modello pre-allenato sui tuoi dati. Dai un'occhiata al nostro tutorial [fine-tuning tutorial](./training) per imparare come. Infine, dopo che hai completato il fine-tuning del tuo modello pre-allenato, considera per favore di condividerlo (vedi il tutorial [qui](./model_sharing)) con la comunitĂ sul Model Hub per democratizzare l'NLP! đ€
+
+## AutoClass
+
+
+
+Al suo interno, le classi [`AutoModelForSequenceClassification`] e [`AutoTokenizer`] lavorano assieme per dare potere alla [`pipeline`]. Una [AutoClass](./model_doc/auto) Ăš una scorciatoia che automaticamente recupera l'architettura di un modello pre-allenato a partire dal suo nome o path. Hai solo bisogno di selezionare la `AutoClass` appropriata per il tuo compito e il suo tokenizer associato con [`AutoTokenizer`].
+
+Ritorniamo al nostro esempio e vediamo come puoi utilizzare la `AutoClass` per replicare i risultati della [`pipeline`].
+
+### AutoTokenizer
+
+Un tokenizer Ăš responsabile dell'elaborazione del testo in modo da trasformarlo in un formato comprensibile dal modello. Per prima cosa, il tokenizer dividerĂ il testo in parole chiamate *token*. Ci sono diverse regole che governano il processo di tokenizzazione, tra cui come dividere una parola e a quale livello (impara di piĂč sulla tokenizzazione [qui](./tokenizer_summary)). La cosa piĂč importante da ricordare comunque Ăš che hai bisogno di inizializzare il tokenizer con lo stesso nome del modello in modo da assicurarti che stai utilizzando le stesse regole di tokenizzazione con cui il modello Ăš stato pre-allenato.
+
+Carica un tokenizer con [`AutoTokenizer`]:
+
+```py
+>>> from transformers import AutoTokenizer
+
+>>> nome_del_modello = "nlptown/bert-base-multilingual-uncased-sentiment"
+>>> tokenizer = AutoTokenizer.from_pretrained(nome_del_modello)
+```
+
+Dopodiché, il tokenizer converte i token in numeri in modo da costruire un tensore come input del modello. Questo Ú conosciuto come il *vocabolario* del modello.
+
+Passa il tuo testo al tokenizer:
+
+```py
+>>> encoding = tokenizer("Siamo molto felici di mostrarti la libreria đ€ Transformers.")
+>>> print(encoding)
+{'input_ids': [101, 56821, 10132, 14407, 13019, 13007, 10120, 47201, 10330, 10106, 91686, 100, 58263, 119, 102],
+'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}
+```
+
+Il tokenizer restituirĂ un dizionario contenente:
+
+* [input_ids](./glossary#input-ids): rappresentazioni numeriche dei tuoi token.
+* [attention_mask](.glossary#attention-mask): indica quali token devono essere presi in considerazione.
+
+Come con la [`pipeline`], il tokenizer accetterĂ una lista di input. In piĂč, il tokenizer puĂČ anche completare (pad, in inglese) e troncare il testo in modo da restituire un lotto (batch, in inglese) di lunghezza uniforme:
+
+
+
+```py
+>>> pt_batch = tokenizer(
+... ["Siamo molto felici di mostrarti la libreria đ€ Transformers.", "Speriamo te non la odierai."],
+... padding=True,
+... truncation=True,
+... max_length=512,
+... return_tensors="pt",
+... )
+```
+
+
+```py
+>>> tf_batch = tokenizer(
+... ["Siamo molto felici di mostrarti la libreria đ€ Transformers.", "Speriamo te non la odierai."],
+... padding=True,
+... truncation=True,
+... max_length=512,
+... return_tensors="tf",
+... )
+```
+
+
+
+Leggi il tutorial sul [preprocessing](./preprocessing) per maggiori dettagli sulla tokenizzazione.
+
+### AutoModel
+
+
+
+đ€ Transformers fornisce un metodo semplice e unificato per caricare istanze pre-allenate. Questo significa che puoi caricare un [`AutoModel`] come caricheresti un [`AutoTokenizer`]. L'unica differenza Ăš selezionare l'[`AutoModel`] corretto per il compito di interesse. Dato che stai facendo classificazione di testi, o sequenze, carica [`AutoModelForSequenceClassification`]:
+
+```py
+>>> from transformers import AutoModelForSequenceClassification
+
+>>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
+>>> pt_model = AutoModelForSequenceClassification.from_pretrained(model_name)
+```
+
+
+
+Guarda il [task summary](./task_summary) per sapere quale classe di [`AutoModel`] utilizzare per quale compito.
+
+
+
+Ora puoi passare il tuo lotto di input pre-processati direttamente al modello. Devi solo spacchettare il dizionario aggiungendo `**`:
+
+```py
+>>> pt_outputs = pt_model(**pt_batch)
+```
+
+Il modello produrrĂ le attivazioni finali nell'attributo `logits`. Applica la funzione softmax a `logits` per ottenere le probabilitĂ :
+
+```py
+>>> from torch import nn
+
+>>> pt_predictions = nn.functional.softmax(pt_outputs.logits, dim=-1)
+>>> print(pt_predictions)
+tensor([[0.0041, 0.0037, 0.0203, 0.2005, 0.7713],
+ [0.3766, 0.3292, 0.1832, 0.0558, 0.0552]], grad_fn=)
+```
+
+
+đ€ Transformers fornisce un metodo semplice e unificato per caricare istanze pre-allenate. Questo significa che puoi caricare un [`TFAutoModel`] come caricheresti un [`AutoTokenizer`]. L'unica differenza Ăš selezionare il [`TFAutoModel`] corretto per il compito di interesse. Dato che stai facendo classificazione di testi, o sequenze, carica [`TFAutoModelForSequenceClassification`]:
+
+```py
+>>> from transformers import TFAutoModelForSequenceClassification
+
+>>> nome_del_modello = "nlptown/bert-base-multilingual-uncased-sentiment"
+>>> tf_model = TFAutoModelForSequenceClassification.from_pretrained(nome_del_modello)
+```
+
+
+
+Guarda il [task summary](./task_summary) per sapere quale classe di [`AutoModel`] utilizzare per quale compito.
+
+
+
+Ora puoi passare il tuo lotto di input pre-processati direttamente al modello passando le chiavi del dizionario al tensore:
+
+```py
+>>> tf_outputs = tf_model(tf_batch)
+```
+
+Il modello produrrĂ le attivazioni finali nell'attributo `logits`. Applica la funzione softmax a `logits` per ottenere le probabilitĂ :
+```py
+>>> import tensorflow as tf
+
+>>> tf_predictions = tf.nn.softmax(tf_outputs.logits, axis=-1)
+>>> tf_predictions # doctest: +IGNORE_RESULT
+```
+
+
+
+
+
+Tutti i modelli di đ€ Transformers (PyTorch e TensorFlow) restituiscono i tensori *prima* della funzione finale
+di attivazione (come la softmax) perché la funzione di attivazione finale viene spesso unita a quella di perdita.
+
+
+
+I modelli sono [`torch.nn.Module`](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) o [`tf.keras.Model`](https://www.tensorflow.org/api_docs/python/tf/keras/Model) standard cosĂŹ puoi utilizzarli all'interno del tuo training loop usuale. Tuttavia, per rendere le cose piĂč semplici, đ€ Transformers fornisce una classe [`Trainer`] per PyTorch che aggiunge delle funzionalitĂ per l'allenamento distribuito, precisione mista, e altro ancora. Per TensorFlow, puoi utilizzare il metodo `fit` di [Keras](https://keras.io/). Fai riferimento al [tutorial per il training](./training) per maggiori dettagli.
+
+
+
+Gli output del modello di đ€ Transformers sono delle dataclasses speciali in modo che i loro attributi vengano auto-completati all'interno di un IDE.
+Gli output del modello si comportano anche come una tupla o un dizionario (ad esempio, puoi indicizzare con un intero, una slice o una stringa) nel qual caso gli attributi che sono `None` vengono ignorati.
+
+
+
+### Salva un modello
+
+
+
+Una volta completato il fine-tuning del tuo modello, puoi salvarlo con il suo tokenizer utilizzando [`PreTrainedModel.save_pretrained`]:
+
+```py
+>>> pt_save_directory = "./pt_save_pretrained"
+>>> tokenizer.save_pretrained(pt_save_directory) # doctest: +IGNORE_RESULT
+>>> pt_model.save_pretrained(pt_save_directory)
+```
+
+Quando desideri utilizzare il tuo modello nuovamente, puoi ri-caricarlo con [`PreTrainedModel.from_pretrained`]:
+
+```py
+>>> pt_model = AutoModelForSequenceClassification.from_pretrained("./pt_save_pretrained")
+```
+
+
+Una volta completato il fine-tuning del tuo modello, puoi salvarlo con il suo tokenizer utilizzando [`TFPreTrainedModel.save_pretrained`]:
+
+```py
+>>> tf_save_directory = "./tf_save_pretrained"
+>>> tokenizer.save_pretrained(tf_save_directory) # doctest: +IGNORE_RESULT
+>>> tf_model.save_pretrained(tf_save_directory)
+```
+
+Quando desideri utilizzare il tuo modello nuovamente, puoi ri-caricarlo con [`TFPreTrainedModel.from_pretrained`]:
+
+```py
+>>> tf_model = TFAutoModelForSequenceClassification.from_pretrained("./tf_save_pretrained")
+```
+
+
+
+Una caratteristica particolarmente interessante di đ€ Transformers Ăš la sua abilitĂ di salvare un modello e ri-caricarlo sia come modello di PyTorch che di TensorFlow. I parametri `from_pt` o `from_tf` possono convertire un modello da un framework all'altro:
+
+
+
+```py
+>>> from transformers import AutoModel
+
+>>> tokenizer = AutoTokenizer.from_pretrained(tf_save_directory)
+>>> pt_model = AutoModelForSequenceClassification.from_pretrained(tf_save_directory, from_tf=True)
+```
+
+
+```py
+>>> from transformers import TFAutoModel
+
+>>> tokenizer = AutoTokenizer.from_pretrained(pt_save_directory)
+>>> tf_model = TFAutoModelForSequenceClassification.from_pretrained(pt_save_directory, from_pt=True)
+```
+
+
diff --git a/docs/source/it/quicktour.mdx b/docs/source/it/quicktour.mdx
deleted file mode 100644
index 2378edd2c2a1..000000000000
--- a/docs/source/it/quicktour.mdx
+++ /dev/null
@@ -1,393 +0,0 @@
-
-
-# Quick tour
-
-[[open-in-colab]]
-
-Entra in azione con đ€ Transformers! Inizia utilizzando [`pipeline`] per un'inferenza veloce, carica un modello pre-allenato e un tokenizer con una [AutoClass](./model_doc/auto) per risolvere i tuoi compiti legati a testo, immagini o audio.
-
-
-
-Tutti gli esempi di codice presenti in questa documentazione hanno un pulsante in alto a sinistra che permette di selezionare tra PyTorch e TensorFlow. Se
-questo non Ăš presente, ci si aspetta che il codice funzioni per entrambi i backend senza alcun cambiamento.
-
-
-
-## Pipeline
-
-[`pipeline`] Ăš il modo piĂč semplice per utilizzare un modello pre-allenato per un dato compito.
-
-
-
-La [`pipeline`] supporta molti compiti comuni:
-
-**Testo**:
-* Analisi del Sentimento (Sentiment Analysis, in inglese): classifica la polaritĂ di un testo dato.
-* Generazione del Testo (Text Generation, in inglese): genera del testo a partire da un dato input.
-* Riconoscimento di EntitĂ (Name Entity Recognition o NER, in inglese): etichetta ogni parola con l'entitĂ che questa rappresenta (persona, data, luogo, ecc.).
-* Rispondere a Domande (Question answering, in inglese): estrae la risposta da un contesto, dato del contesto e una domanda.
-* Riempimento di Maschere (Fill-mask, in inglese): riempie gli spazi mancanti in un testo che ha parole mascherate.
-* Riassumere (Summarization, in inglese): genera una sintesi di una lunga sequenza di testo o di un documento.
-* Traduzione (Translation, in inglese): traduce un testo in un'altra lingua.
-* Estrazione di Caratteristiche (Feature Extraction, in inglese): crea un tensore che rappresenta un testo.
-
-**Immagini**:
-* Classificazione di Immagini (Image Classification, in inglese): classifica un'immagine.
-* Segmentazione di Immagini (Image Segmentation, in inglese): classifica ogni pixel di un'immagine.
-* Rilevazione di Oggetti (Object Detection, in inglese): rileva oggetti all'interno di un'immagine.
-
-**Audio**:
-* Classificazione di Audio (Audio Classification, in inglese): assegna un'etichetta ad un segmento di audio dato.
-* Riconoscimento Vocale Automatico (Automatic Speech Recognition o ASR, in inglese): trascrive il contenuto di un audio dato in un testo.
-
-
-
-Per maggiori dettagli legati alla [`pipeline`] e ai compiti ad essa associati, fai riferimento alla documentazione [qui](./main_classes/pipelines).
-
-
-
-### Utilizzo della Pipeline
-
-Nel seguente esempio, utilizzerai la [`pipeline`] per l'analisi del sentimento.
-
-Installa le seguenti dipendenze se non lo hai giĂ fatto:
-
-
-
-```bash
-pip install torch
-```
-
-
-```bash
-pip install tensorflow
-```
-
-
-
-Importa [`pipeline`] e specifica il compito che vuoi completare:
-
-```py
->>> from transformers import pipeline
-
->>> classificatore = pipeline("sentiment-analysis", model="MilaNLProc/feel-it-italian-sentiment")
-```
-
-La pipeline scarica e salva il [modello pre-allenato](https://huggingface.co/MilaNLProc/feel-it-italian-sentiment) e il tokenizer per l'analisi del sentimento. Se non avessimo scelto un modello, la pipeline ne avrebbe scelto uno di default. Ora puoi utilizzare il `classifier` sul tuo testo obiettivo:
-
-```py
->>> classificatore("Siamo molto felici di mostrarti la libreria đ€ Transformers.")
-[{'label': 'positive', 'score': 0.9997}]
-```
-
-Per piĂč di una frase, passa una lista di frasi alla [`pipeline`] la quale restituirĂ una lista di dizionari:
-
-```py
->>> risultati = classificatore(
-... ["Siamo molto felici di mostrarti la libreria đ€ Transformers.", "Speriamo te non la odierai."]
-... )
->>> for risultato in risultati:
-... print(f"etichetta: {risultato['label']}, con punteggio: {round(risultato['score'], 4)}")
-etichetta: positive, con punteggio: 0.9998
-etichetta: negative, con punteggio: 0.9998
-```
-
-La [`pipeline`] puĂČ anche iterare su un dataset intero. Inizia installando la libreria [đ€ Datasets](https://huggingface.co/docs/datasets/):
-
-```bash
-pip install datasets
-```
-
-Crea una [`pipeline`] con il compito che vuoi risolvere e con il modello che vuoi utilizzare.
-
-```py
->>> import torch
->>> from transformers import pipeline
-
->>> riconoscitore_vocale = pipeline(
-... "automatic-speech-recognition", model="radiogroup-crits/wav2vec2-xls-r-1b-italian-doc4lm-5gram"
-... )
-```
-
-Poi, carica un dataset (vedi đ€ Datasets [Quick Start](https://huggingface.co/docs/datasets/quickstart.html) per maggiori dettagli) sul quale vuoi iterare. Per esempio, carichiamo il dataset [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14):
-
-```py
->>> from datasets import load_dataset, Audio
-
->>> dataset = load_dataset("PolyAI/minds14", name="it-IT", split="train") # doctest: +IGNORE_RESULT
-```
-
-Dobbiamo assicurarci che la frequenza di campionamento del set di dati corrisponda alla frequenza di campionamento con cui Ăš stato addestrato `radiogroup-crits/wav2vec2-xls-r-1b-italian-doc4lm-5gram`.
-
-```py
->>> dataset = dataset.cast_column("audio", Audio(sampling_rate=riconoscitore_vocale.feature_extractor.sampling_rate))
-```
-
-I file audio vengono caricati automaticamente e ri-campionati quando chiamiamo la colonna "audio".
-Estraiamo i vettori delle forme d'onda grezze delle prime 4 osservazioni e passiamoli come lista alla pipeline:
-
-```py
->>> risultato = riconoscitore_vocale(dataset[:4]["audio"])
->>> print([d["text"] for d in risultato])
-['dovrei caricare dei soldi sul mio conto corrente', 'buongiorno e senza vorrei depositare denaro sul mio conto corrente come devo fare per cortesia', 'sĂŹ salve vorrei depositare del denaro sul mio conto', 'e buon pomeriggio vorrei depositare dei soldi sul mio conto bancario volleo sapere come posso fare se e posso farlo online ed un altro conto o andandoo tramite bancomut']
-```
-
-Per un dataset piĂč grande dove gli input sono di dimensione maggiore (come nel parlato/audio o nella visione), dovrai passare un generatore al posto di una lista che carica tutti gli input in memoria. Guarda la [documentazione della pipeline](./main_classes/pipelines) per maggiori informazioni.
-
-### Utilizzare un altro modello e tokenizer nella pipeline
-
-La [`pipeline`] puĂČ ospitare qualsiasi modello del [Model Hub](https://huggingface.co/models), rendendo semplice l'adattamento della [`pipeline`] per altri casi d'uso. Per esempio, se si vuole un modello capace di trattare testo in francese, usa i tag presenti nel Model Hub in modo da filtrare per ottenere un modello appropriato. Il miglior risultato filtrato restituisce un modello multi-lingua [BERT model](https://huggingface.co/nlptown/bert-base-multilingual-uncased-sentiment) fine-tuned per l'analisi del sentimento. Ottimo, utilizziamo questo modello!
-
-```py
->>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
-```
-
-
-
-Usa [`AutoModelForSequenceClassification`] e [`AutoTokenizer`] per caricare il modello pre-allenato e il suo tokenizer associato (maggiori informazioni su una `AutoClass` in seguito):
-
-```py
->>> from transformers import AutoTokenizer, AutoModelForSequenceClassification
-
->>> model = AutoModelForSequenceClassification.from_pretrained(model_name)
->>> tokenizer = AutoTokenizer.from_pretrained(model_name)
-```
-
-
-Usa [`TFAutoModelForSequenceClassification`] e [`AutoTokenizer`] per caricare il modello pre-allenato e il suo tokenizer associato (maggiori informazioni su una `TFAutoClass` in seguito):
-
-```py
->>> from transformers import AutoTokenizer, TFAutoModelForSequenceClassification
-
->>> model = TFAutoModelForSequenceClassification.from_pretrained(model_name)
->>> tokenizer = AutoTokenizer.from_pretrained(model_name)
-```
-
-
-
-Poi puoi specificare il modello e il tokenizer nella [`pipeline`], e applicare il `classifier` sul tuo testo obiettivo:
-
-```py
->>> classifier = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer)
->>> classifier("Nous sommes trĂšs heureux de vous prĂ©senter la bibliothĂšque đ€ Transformers.")
-[{'label': '5 stars', 'score': 0.7273}]
-```
-
-Se non riesci a trovare un modello per il tuo caso d'uso, dovrai fare fine-tuning di un modello pre-allenato sui tuoi dati. Dai un'occhiata al nostro tutorial [fine-tuning tutorial](./training) per imparare come. Infine, dopo che hai completato il fine-tuning del tuo modello pre-allenato, considera per favore di condividerlo (vedi il tutorial [qui](./model_sharing)) con la comunitĂ sul Model Hub per democratizzare l'NLP! đ€
-
-## AutoClass
-
-
-
-Al suo interno, le classi [`AutoModelForSequenceClassification`] e [`AutoTokenizer`] lavorano assieme per dare potere alla [`pipeline`]. Una [AutoClass](./model_doc/auto) Ăš una scorciatoia che automaticamente recupera l'architettura di un modello pre-allenato a partire dal suo nome o path. Hai solo bisogno di selezionare la `AutoClass` appropriata per il tuo compito e il suo tokenizer associato con [`AutoTokenizer`].
-
-Ritorniamo al nostro esempio e vediamo come puoi utilizzare la `AutoClass` per replicare i risultati della [`pipeline`].
-
-### AutoTokenizer
-
-Un tokenizer Ăš responsabile dell'elaborazione del testo in modo da trasformarlo in un formato comprensibile dal modello. Per prima cosa, il tokenizer dividerĂ il testo in parole chiamate *token*. Ci sono diverse regole che governano il processo di tokenizzazione, tra cui come dividere una parola e a quale livello (impara di piĂč sulla tokenizzazione [qui](./tokenizer_summary)). La cosa piĂč importante da ricordare comunque Ăš che hai bisogno di inizializzare il tokenizer con lo stesso nome del modello in modo da assicurarti che stai utilizzando le stesse regole di tokenizzazione con cui il modello Ăš stato pre-allenato.
-
-Carica un tokenizer con [`AutoTokenizer`]:
-
-```py
->>> from transformers import AutoTokenizer
-
->>> nome_del_modello = "nlptown/bert-base-multilingual-uncased-sentiment"
->>> tokenizer = AutoTokenizer.from_pretrained(nome_del_modello)
-```
-
-Dopodiché, il tokenizer converte i token in numeri in modo da costruire un tensore come input del modello. Questo Ú conosciuto come il *vocabolario* del modello.
-
-Passa il tuo testo al tokenizer:
-
-```py
->>> encoding = tokenizer("Siamo molto felici di mostrarti la libreria đ€ Transformers.")
->>> print(encoding)
-{'input_ids': [101, 56821, 10132, 14407, 13019, 13007, 10120, 47201, 10330, 10106, 91686, 100, 58263, 119, 102],
-'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
-'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}
-```
-
-Il tokenizer restituirĂ un dizionario contenente:
-
-* [input_ids](./glossary#input-ids): rappresentazioni numeriche dei tuoi token.
-* [attention_mask](.glossary#attention-mask): indica quali token devono essere presi in considerazione.
-
-Come con la [`pipeline`], il tokenizer accetterĂ una lista di input. In piĂč, il tokenizer puĂČ anche completare (pad, in inglese) e troncare il testo in modo da restituire un lotto (batch, in inglese) di lunghezza uniforme:
-
-
-
-```py
->>> pt_batch = tokenizer(
-... ["Siamo molto felici di mostrarti la libreria đ€ Transformers.", "Speriamo te non la odierai."],
-... padding=True,
-... truncation=True,
-... max_length=512,
-... return_tensors="pt",
-... )
-```
-
-
-```py
->>> tf_batch = tokenizer(
-... ["Siamo molto felici di mostrarti la libreria đ€ Transformers.", "Speriamo te non la odierai."],
-... padding=True,
-... truncation=True,
-... max_length=512,
-... return_tensors="tf",
-... )
-```
-
-
-
-Leggi il tutorial sul [preprocessing](./preprocessing) per maggiori dettagli sulla tokenizzazione.
-
-### AutoModel
-
-
-
-đ€ Transformers fornisce un metodo semplice e unificato per caricare istanze pre-allenate. Questo significa che puoi caricare un [`AutoModel`] come caricheresti un [`AutoTokenizer`]. L'unica differenza Ăš selezionare l'[`AutoModel`] corretto per il compito di interesse. Dato che stai facendo classificazione di testi, o sequenze, carica [`AutoModelForSequenceClassification`]:
-
-```py
->>> from transformers import AutoModelForSequenceClassification
-
->>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
->>> pt_model = AutoModelForSequenceClassification.from_pretrained(model_name)
-```
-
-
-
-Guarda il [task summary](./task_summary) per sapere quale classe di [`AutoModel`] utilizzare per quale compito.
-
-
-
-Ora puoi passare il tuo lotto di input pre-processati direttamente al modello. Devi solo spacchettare il dizionario aggiungendo `**`:
-
-```py
->>> pt_outputs = pt_model(**pt_batch)
-```
-
-Il modello produrrĂ le attivazioni finali nell'attributo `logits`. Applica la funzione softmax a `logits` per ottenere le probabilitĂ :
-
-```py
->>> from torch import nn
-
->>> pt_predictions = nn.functional.softmax(pt_outputs.logits, dim=-1)
->>> print(pt_predictions)
-tensor([[0.0041, 0.0037, 0.0203, 0.2005, 0.7713],
- [0.3766, 0.3292, 0.1832, 0.0558, 0.0552]], grad_fn=)
-```
-
-
-đ€ Transformers fornisce un metodo semplice e unificato per caricare istanze pre-allenate. Questo significa che puoi caricare un [`TFAutoModel`] come caricheresti un [`AutoTokenizer`]. L'unica differenza Ăš selezionare il [`TFAutoModel`] corretto per il compito di interesse. Dato che stai facendo classificazione di testi, o sequenze, carica [`TFAutoModelForSequenceClassification`]:
-
-```py
->>> from transformers import TFAutoModelForSequenceClassification
-
->>> nome_del_modello = "nlptown/bert-base-multilingual-uncased-sentiment"
->>> tf_model = TFAutoModelForSequenceClassification.from_pretrained(nome_del_modello)
-```
-
-
-
-Guarda il [task summary](./task_summary) per sapere quale classe di [`AutoModel`] utilizzare per quale compito.
-
-
-
-Ora puoi passare il tuo lotto di input pre-processati direttamente al modello passando le chiavi del dizionario al tensore:
-
-```py
->>> tf_outputs = tf_model(tf_batch)
-```
-
-Il modello produrrĂ le attivazioni finali nell'attributo `logits`. Applica la funzione softmax a `logits` per ottenere le probabilitĂ :
-```py
->>> import tensorflow as tf
-
->>> tf_predictions = tf.nn.softmax(tf_outputs.logits, axis=-1)
->>> tf_predictions # doctest: +IGNORE_RESULT
-```
-
-
-
-
-
-Tutti i modelli di đ€ Transformers (PyTorch e TensorFlow) restituiscono i tensori *prima* della funzione finale
-di attivazione (come la softmax) perché la funzione di attivazione finale viene spesso unita a quella di perdita.
-
-
-
-I modelli sono [`torch.nn.Module`](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) o [`tf.keras.Model`](https://www.tensorflow.org/api_docs/python/tf/keras/Model) standard cosĂŹ puoi utilizzarli all'interno del tuo training loop usuale. Tuttavia, per rendere le cose piĂč semplici, đ€ Transformers fornisce una classe [`Trainer`] per PyTorch che aggiunge delle funzionalitĂ per l'allenamento distribuito, precisione mista, e altro ancora. Per TensorFlow, puoi utilizzare il metodo `fit` di [Keras](https://keras.io/). Fai riferimento al [tutorial per il training](./training) per maggiori dettagli.
-
-
-
-Gli output del modello di đ€ Transformers sono delle dataclasses speciali in modo che i loro attributi vengano auto-completati all'interno di un IDE.
-Gli output del modello si comportano anche come una tupla o un dizionario (ad esempio, puoi indicizzare con un intero, una slice o una stringa) nel qual caso gli attributi che sono `None` vengono ignorati.
-
-
-
-### Salva un modello
-
-
-
-Una volta completato il fine-tuning del tuo modello, puoi salvarlo con il suo tokenizer utilizzando [`PreTrainedModel.save_pretrained`]:
-
-```py
->>> pt_save_directory = "./pt_save_pretrained"
->>> tokenizer.save_pretrained(pt_save_directory) # doctest: +IGNORE_RESULT
->>> pt_model.save_pretrained(pt_save_directory)
-```
-
-Quando desideri utilizzare il tuo modello nuovamente, puoi ri-caricarlo con [`PreTrainedModel.from_pretrained`]:
-
-```py
->>> pt_model = AutoModelForSequenceClassification.from_pretrained("./pt_save_pretrained")
-```
-
-
-Una volta completato il fine-tuning del tuo modello, puoi salvarlo con il suo tokenizer utilizzando [`TFPreTrainedModel.save_pretrained`]:
-
-```py
->>> tf_save_directory = "./tf_save_pretrained"
->>> tokenizer.save_pretrained(tf_save_directory) # doctest: +IGNORE_RESULT
->>> tf_model.save_pretrained(tf_save_directory)
-```
-
-Quando desideri utilizzare il tuo modello nuovamente, puoi ri-caricarlo con [`TFPreTrainedModel.from_pretrained`]:
-
-```py
->>> tf_model = TFAutoModelForSequenceClassification.from_pretrained("./tf_save_pretrained")
-```
-
-
-
-Una caratteristica particolarmente interessante di đ€ Transformers Ăš la sua abilitĂ di salvare un modello e ri-caricarlo sia come modello di PyTorch che di TensorFlow. I parametri `from_pt` o `from_tf` possono convertire un modello da un framework all'altro:
-
-
-
-```py
->>> from transformers import AutoModel
-
->>> tokenizer = AutoTokenizer.from_pretrained(tf_save_directory)
->>> pt_model = AutoModelForSequenceClassification.from_pretrained(tf_save_directory, from_tf=True)
-```
-
-
-```py
->>> from transformers import TFAutoModel
-
->>> tokenizer = AutoTokenizer.from_pretrained(pt_save_directory)
->>> tf_model = TFAutoModelForSequenceClassification.from_pretrained(pt_save_directory, from_pt=True)
-```
-
-
diff --git a/docs/source/it/run_scripts.md b/docs/source/it/run_scripts.md
new file mode 100644
index 000000000000..327eb9374d38
--- /dev/null
+++ b/docs/source/it/run_scripts.md
@@ -0,0 +1,351 @@
+
+
+# Addestramento con script
+
+Insieme ai [notebooks](./noteboks/README) đ€ Transformers, ci sono anche esempi di script che dimostrano come addestrare un modello per un task con [PyTorch](https://github.com/huggingface/transformers/tree/main/examples/pytorch), [TensorFlow](https://github.com/huggingface/transformers/tree/main/examples/tensorflow), o [JAX/Flax](https://github.com/huggingface/transformers/tree/main/examples/flax).
+
+Troverai anche script che abbiamo usato nei nostri [progetti di ricerca](https://github.com/huggingface/transformers/tree/main/examples/research_projects) e [precedenti esempi](https://github.com/huggingface/transformers/tree/main/examples/legacy) a cui contribuisce per lo piĂč la comunitĂ . Questi script non sono attivamente mantenuti e richiedono una specifica versione di đ€ Transformers che sarĂ molto probabilmente incompatibile con l'ultima versione della libreria.
+
+Non Ăš dato per scontato che gli script di esempio funzionino senza apportare modifiche per ogni problema, bensĂŹ potrebbe essere necessario adattare lo script al tuo caso specifico. Per aiutarti in ciĂČ, la maggioranza degli script espone le modalitĂ di pre-processamento dei dati, consentendoti di modificare lo script come preferisci.
+
+Per qualsiasi feature che vorresti implementare in uno script d'esempio, per favore discutine nel [forum](https://discuss.huggingface.co/) o in un'[issue](https://github.com/huggingface/transformers/issues) prima di inviare una Pull Request. Mentre accogliamo con piacere la correzione di bug, Ăš piĂč improbabile che faremo la stessa con una PR che aggiunge funzionalitĂ sacrificando la leggibilitĂ .
+
+Questa guida ti mostrerĂ come eseguire uno script di esempio relativo al task di summarization in [PyTorch](https://github.com/huggingface/transformers/tree/main/examples/pytorch/summarization) e [TensorFlow](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/summarization). Tutti gli esempi funzioneranno con entrambi i framework a meno che non sia specificato altrimenti.
+
+## Installazione
+
+Per eseguire con successo l'ultima versione degli script di esempio, devi **installare đ€ Transformers dalla fonte** in un nuovo ambiente virtuale:
+
+```bash
+git clone https://github.com/huggingface/transformers
+cd transformers
+pip install .
+```
+Per le precedenti versioni degli script di esempio, clicca sul pulsante di seguito:
+
+
+ Esempi per versioni precedenti di đ€ Transformers
+
+
+
+Successivamente, cambia la tua attuale copia di đ€ Transformers specificandone la versione, ad esempio v3.5.1:
+
+```bash
+git checkout tags/v3.5.1
+```
+
+ Dopo aver configurato correttamente la versione della libreria, naviga nella cartella degli esempi di tua scelta e installa i requisiti:
+
+```bash
+pip install -r requirements.txt
+```
+
+## Esegui uno script
+
+
+
+
+Lo script di esempio scarica e pre-processa un dataset dalla libreria đ€ [Datasets](https://huggingface.co/docs/datasets/). Successivamente, lo script esegue il fine-tuning su un dataset usando il [Trainer](https://huggingface.co/docs/transformers/main_classes/trainer) su un'architettura che supporta la summarization. Il seguente esempio mostra come eseguire il fine-tuning di [T5-small](https://huggingface.co/t5-small) sul dataset [CNN/DailyMail](https://huggingface.co/datasets/cnn_dailymail). Il modello T5 richiede un parametro addizionale `source_prefix` a causa del modo in cui Ăš stato addestrato. Questo prefisso permette a T5 di sapere che si tratta di un task di summarization.
+
+```bash
+python examples/pytorch/summarization/run_summarization.py \
+ --model_name_or_path t5-small \
+ --do_train \
+ --do_eval \
+ --dataset_name cnn_dailymail \
+ --dataset_config "3.0.0" \
+ --source_prefix "summarize: " \
+ --output_dir /tmp/tst-summarization \
+ --per_device_train_batch_size=4 \
+ --per_device_eval_batch_size=4 \
+ --overwrite_output_dir \
+ --predict_with_generate
+```
+
+
+Lo script di esempio scarica e pre-processa un dataset dalla libreria đ€ [Datasets](https://huggingface.co/docs/datasets/). Successivamente, lo script esegue il fine-tuning su un dataset usando Keras su un'architettura che supporta la summarization. Il seguente esempio mostra come eseguire il fine-tuning di [T5-small](https://huggingface.co/t5-small) sul dataset [CNN/DailyMail](https://huggingface.co/datasets/cnn_dailymail). Il modello T5 richiede un parametro addizionale `source_prefix` a causa del modo in cui Ăš stato addestrato. Questo prefisso permette a T5 di sapere che si tratta di un task di summarization.
+
+```bash
+python examples/tensorflow/summarization/run_summarization.py \
+ --model_name_or_path t5-small \
+ --dataset_name cnn_dailymail \
+ --dataset_config "3.0.0" \
+ --output_dir /tmp/tst-summarization \
+ --per_device_train_batch_size 8 \
+ --per_device_eval_batch_size 16 \
+ --num_train_epochs 3 \
+ --do_train \
+ --do_eval
+```
+
+
+
+## Addestramento distribuito e precisione mista
+
+Il [Trainer](https://huggingface.co/docs/transformers/main_classes/trainer) supporta l'addestramento distribuito e la precisione mista, che significa che puoi anche usarla in uno script. Per abilitare entrambe le funzionalitĂ :
+
+- Aggiunto l'argomento `fp16` per abilitare la precisione mista.
+- Imposta un numero di GPU da usare con l'argomento `nproc_per_node`.
+
+```bash
+python -m torch.distributed.launch \
+ --nproc_per_node 8 pytorch/summarization/run_summarization.py \
+ --fp16 \
+ --model_name_or_path t5-small \
+ --do_train \
+ --do_eval \
+ --dataset_name cnn_dailymail \
+ --dataset_config "3.0.0" \
+ --source_prefix "summarize: " \
+ --output_dir /tmp/tst-summarization \
+ --per_device_train_batch_size=4 \
+ --per_device_eval_batch_size=4 \
+ --overwrite_output_dir \
+ --predict_with_generate
+```
+
+Gli script TensorFlow utilizzano una [`MirroredStrategy`](https://www.tensorflow.org/guide/distributed_training#mirroredstrategy) per il training distribuito e non devi aggiungere alcun argomento addizionale allo script di training. Lo script TensorFlow userĂ multiple GPU in modo predefinito se quest'ultime sono disponibili:
+
+## Esegui uno script su TPU
+
+
+
+Le Tensor Processing Units (TPU) sono state progettate per migliorare le prestazioni. PyTorch supporta le TPU con il compilatore per deep learning [XLA](https://www.tensorflow.org/xla) (guarda [questo link](https://github.com/pytorch/xla/blob/master/README.md) per maggiori dettagli). Per usare una TPU, avvia lo script `xla_spawn.py` e usa l'argomento `num_cores` per impostare il numero di core TPU che intendi usare.
+
+```bash
+python xla_spawn.py --num_cores 8 \
+ summarization/run_summarization.py \
+ --model_name_or_path t5-small \
+ --do_train \
+ --do_eval \
+ --dataset_name cnn_dailymail \
+ --dataset_config "3.0.0" \
+ --source_prefix "summarize: " \
+ --output_dir /tmp/tst-summarization \
+ --per_device_train_batch_size=4 \
+ --per_device_eval_batch_size=4 \
+ --overwrite_output_dir \
+ --predict_with_generate
+```
+
+
+Le Tensor Processing Units (TPU) sono state progettate per migliorare le prestazioni. Gli script TensorFlow utilizzano una [`TPUStrategy`](https://www.tensorflow.org/guide/distributed_training#tpustrategy) per eseguire l'addestramento su TPU. Per usare una TPU, passa il nome della risorsa TPU all'argomento `tpu`.
+
+```bash
+python run_summarization.py \
+ --tpu name_of_tpu_resource \
+ --model_name_or_path t5-small \
+ --dataset_name cnn_dailymail \
+ --dataset_config "3.0.0" \
+ --output_dir /tmp/tst-summarization \
+ --per_device_train_batch_size 8 \
+ --per_device_eval_batch_size 16 \
+ --num_train_epochs 3 \
+ --do_train \
+ --do_eval
+```
+
+
+
+## Esegui uno script con đ€ Accelerate
+
+đ€ [Accelerate](https://huggingface.co/docs/accelerate) Ăš una libreria compatibile solo con PyTorch che offre un metodo unificato per addestrare modelli su diverse tipologie di configurazioni (CPU, multiple GPU, TPU) mantenendo una completa visibilitĂ rispetto al ciclo di training di PyTorch. Assicurati di aver effettuato l'installazione di đ€ Accelerate, nel caso non lo avessi fatto:
+
+> Nota: dato che Accelerate Ăš in rapido sviluppo, Ăš necessario installare la versione proveniente da git per eseguire gli script:
+```bash
+pip install git+https://github.com/huggingface/accelerate
+```
+
+Invece che usare lo script `run_summarization.py`, devi usare lo script `run_summarization_no_trainer.py`. Gli script supportati in đ€ Accelerate avranno un file chiamato `task_no_trainer.py` nella rispettiva cartella. Per iniziare, esegui il seguente comando per creare e salvare un file di configurazione:
+
+```bash
+accelerate config
+```
+
+Testa la tua configurazione per assicurarti della sua correttezza:
+
+```bash
+accelerate test
+```
+
+Ora sei pronto per avviare l'addestramento:
+
+```bash
+accelerate launch run_summarization_no_trainer.py \
+ --model_name_or_path t5-small \
+ --dataset_name cnn_dailymail \
+ --dataset_config "3.0.0" \
+ --source_prefix "summarize: " \
+ --output_dir ~/tmp/tst-summarization
+```
+
+## Uso di un dataset personalizzato
+
+Lo script di summarization supporta dataset personalizzati purché siano file CSV o JSON Line. Quando usi il tuo dataset, devi specificare diversi argomenti aggiuntivi:
+
+- `train_file` e `validation_file` specificano dove si trovano i file di addestramento e validazione.
+- `text_column` Ăš il file di input da riassumere.
+- `summary_column` Ăš il file di destinazione per l'output.
+
+Uno script di summarization usando un dataset personalizzato sarebbe simile a questo:
+
+```bash
+python examples/pytorch/summarization/run_summarization.py \
+ --model_name_or_path t5-small \
+ --do_train \
+ --do_eval \
+ --train_file path_to_csv_or_jsonlines_file \
+ --validation_file path_to_csv_or_jsonlines_file \
+ --text_column text_column_name \
+ --summary_column summary_column_name \
+ --source_prefix "summarize: " \
+ --output_dir /tmp/tst-summarization \
+ --overwrite_output_dir \
+ --per_device_train_batch_size=4 \
+ --per_device_eval_batch_size=4 \
+ --predict_with_generate
+```
+
+## Testare uno script
+
+Ă spesso una buona idea avviare il tuo script su un numero inferiore di esempi tratti dal dataset, per assicurarti che tutto funzioni come previsto prima di eseguire lo script sull'intero dataset, che potrebbe necessitare di ore. Usa i seguenti argomenti per limitare il dataset ad un massimo numero di esempi:
+
+- `max_train_samples`
+- `max_eval_samples`
+- `max_predict_samples`
+
+```bash
+python examples/pytorch/summarization/run_summarization.py \
+ --model_name_or_path t5-small \
+ --max_train_samples 50 \
+ --max_eval_samples 50 \
+ --max_predict_samples 50 \
+ --do_train \
+ --do_eval \
+ --dataset_name cnn_dailymail \
+ --dataset_config "3.0.0" \
+ --source_prefix "summarize: " \
+ --output_dir /tmp/tst-summarization \
+ --per_device_train_batch_size=4 \
+ --per_device_eval_batch_size=4 \
+ --overwrite_output_dir \
+ --predict_with_generate
+```
+
+Non tutti gli esempi di script supportano l'argomento `max_predict_samples`. Se non sei sicuro circa il supporto di questo argomento da parte del tuo script, aggiungi l'argomento `-h` per controllare:
+
+```bash
+examples/pytorch/summarization/run_summarization.py -h
+```
+
+## Riavviare addestramento da un checkpoint
+
+Un'altra utile opzione Ăš riavviare un addestramento da un checkpoint precedente. Questo garantirĂ che tu possa riprendere da dove hai interrotto senza ricominciare se l'addestramento viene interrotto. Ci sono due metodi per riavviare l'addestramento da un checkpoint:
+
+Il primo metodo usa l'argomento `output_dir previous_output_dir` per riavviare l'addestramento dall'ultima versione del checkpoint contenuto in `output_dir`. In questo caso, dovresti rimuovere `overwrite_output_dir`:
+
+```bash
+python examples/pytorch/summarization/run_summarization.py
+ --model_name_or_path t5-small \
+ --do_train \
+ --do_eval \
+ --dataset_name cnn_dailymail \
+ --dataset_config "3.0.0" \
+ --source_prefix "summarize: " \
+ --output_dir /tmp/tst-summarization \
+ --per_device_train_batch_size=4 \
+ --per_device_eval_batch_size=4 \
+ --output_dir previous_output_dir \
+ --predict_with_generate
+```
+
+Il secondo metodo usa l'argomento `resume_from_checkpoint path_to_specific_checkpoint` per riavviare un addestramento da una specifica cartella di checkpoint.
+
+```bash
+python examples/pytorch/summarization/run_summarization.py
+ --model_name_or_path t5-small \
+ --do_train \
+ --do_eval \
+ --dataset_name cnn_dailymail \
+ --dataset_config "3.0.0" \
+ --source_prefix "summarize: " \
+ --output_dir /tmp/tst-summarization \
+ --per_device_train_batch_size=4 \
+ --per_device_eval_batch_size=4 \
+ --overwrite_output_dir \
+ --resume_from_checkpoint path_to_specific_checkpoint \
+ --predict_with_generate
+```
+
+## Condividi il tuo modello
+
+Tutti gli script possono caricare il tuo modello finale al [Model Hub](https://huggingface.co/models). Prima di iniziare, assicurati di aver effettuato l'accesso su Hugging Face:
+
+```bash
+huggingface-cli login
+```
+
+Poi, aggiungi l'argomento `push_to_hub` allo script. Questo argomento consentirĂ di creare un repository con il tuo username Hugging Face e la cartella specificata in `output_dir`.
+
+Per dare uno specifico nome al repository, usa l'argomento `push_to_hub_model_id`. Il repository verrĂ automaticamente elencata sotto al tuo namespace.
+
+Il seguente esempio mostra come caricare un modello specificando il nome del repository:
+
+```bash
+python examples/pytorch/summarization/run_summarization.py
+ --model_name_or_path t5-small \
+ --do_train \
+ --do_eval \
+ --dataset_name cnn_dailymail \
+ --dataset_config "3.0.0" \
+ --source_prefix "summarize: " \
+ --push_to_hub \
+ --push_to_hub_model_id finetuned-t5-cnn_dailymail \
+ --output_dir /tmp/tst-summarization \
+ --per_device_train_batch_size=4 \
+ --per_device_eval_batch_size=4 \
+ --overwrite_output_dir \
+ --predict_with_generate
+```
diff --git a/docs/source/it/run_scripts.mdx b/docs/source/it/run_scripts.mdx
deleted file mode 100644
index 3ffd58a62830..000000000000
--- a/docs/source/it/run_scripts.mdx
+++ /dev/null
@@ -1,347 +0,0 @@
-
-
-# Addestramento con script
-
-Insieme ai [notebooks](./noteboks/README) đ€ Transformers, ci sono anche esempi di script che dimostrano come addestrare un modello per un task con [PyTorch](https://github.com/huggingface/transformers/tree/main/examples/pytorch), [TensorFlow](https://github.com/huggingface/transformers/tree/main/examples/tensorflow), o [JAX/Flax](https://github.com/huggingface/transformers/tree/main/examples/flax).
-
-Troverai anche script che abbiamo usato nei nostri [progetti di ricerca](https://github.com/huggingface/transformers/tree/main/examples/research_projects) e [precedenti esempi](https://github.com/huggingface/transformers/tree/main/examples/legacy) a cui contribuisce per lo piĂč la comunitĂ . Questi script non sono attivamente mantenuti e richiedono una specifica versione di đ€ Transformers che sarĂ molto probabilmente incompatibile con l'ultima versione della libreria.
-
-Non Ăš dato per scontato che gli script di esempio funzionino senza apportare modifiche per ogni problema, bensĂŹ potrebbe essere necessario adattare lo script al tuo caso specifico. Per aiutarti in ciĂČ, la maggioranza degli script espone le modalitĂ di pre-processamento dei dati, consentendoti di modificare lo script come preferisci.
-
-Per qualsiasi feature che vorresti implementare in uno script d'esempio, per favore discutine nel [forum](https://discuss.huggingface.co/) o in un'[issue](https://github.com/huggingface/transformers/issues) prima di inviare una Pull Request. Mentre accogliamo con piacere la correzione di bug, Ăš piĂč improbabile che faremo la stessa con una PR che aggiunge funzionalitĂ sacrificando la leggibilitĂ .
-
-Questa guida ti mostrerĂ come eseguire uno script di esempio relativo al task di summarization in [PyTorch](https://github.com/huggingface/transformers/tree/main/examples/pytorch/summarization) e [TensorFlow](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/summarization). Tutti gli esempi funzioneranno con entrambi i framework a meno che non sia specificato altrimenti.
-
-## Installazione
-
-Per eseguire con successo l'ultima versione degli script di esempio, devi **installare đ€ Transformers dalla fonte** in un nuovo ambiente virtuale:
-
-```bash
-git clone https://github.com/huggingface/transformers
-cd transformers
-pip install .
-```
-Per le precedenti versioni degli script di esempio, clicca sul pulsante di seguito:
-
-
- Esempi per versioni precedenti di đ€ Transformers
-
-
-
-Successivamente, cambia la tua attuale copia di đ€ Transformers specificandone la versione, ad esempio v3.5.1:
-
-```bash
-git checkout tags/v3.5.1
-```
-
- Dopo aver configurato correttamente la versione della libreria, naviga nella cartella degli esempi di tua scelta e installa i requisiti:
-
-```bash
-pip install -r requirements.txt
-```
-
-## Esegui uno script
-
-
-
-
-Lo script di esempio scarica e pre-processa un dataset dalla libreria đ€ [Datasets](https://huggingface.co/docs/datasets/). Successivamente, lo script esegue il fine-tuning su un dataset usando il [Trainer](https://huggingface.co/docs/transformers/main_classes/trainer) su un'architettura che supporta la summarization. Il seguente esempio mostra come eseguire il fine-tuning di [T5-small](https://huggingface.co/t5-small) sul dataset [CNN/DailyMail](https://huggingface.co/datasets/cnn_dailymail). Il modello T5 richiede un parametro addizionale `source_prefix` a causa del modo in cui Ăš stato addestrato. Questo prefisso permette a T5 di sapere che si tratta di un task di summarization.
-
-```bash
-python examples/pytorch/summarization/run_summarization.py \
- --model_name_or_path t5-small \
- --do_train \
- --do_eval \
- --dataset_name cnn_dailymail \
- --dataset_config "3.0.0" \
- --source_prefix "summarize: " \
- --output_dir /tmp/tst-summarization \
- --per_device_train_batch_size=4 \
- --per_device_eval_batch_size=4 \
- --overwrite_output_dir \
- --predict_with_generate
-```
-
-
-Lo script di esempio scarica e pre-processa un dataset dalla libreria đ€ [Datasets](https://huggingface.co/docs/datasets/). Successivamente, lo script esegue il fine-tuning su un dataset usando Keras su un'architettura che supporta la summarization. Il seguente esempio mostra come eseguire il fine-tuning di [T5-small](https://huggingface.co/t5-small) sul dataset [CNN/DailyMail](https://huggingface.co/datasets/cnn_dailymail). Il modello T5 richiede un parametro addizionale `source_prefix` a causa del modo in cui Ăš stato addestrato. Questo prefisso permette a T5 di sapere che si tratta di un task di summarization.
-
-```bash
-python examples/tensorflow/summarization/run_summarization.py \
- --model_name_or_path t5-small \
- --dataset_name cnn_dailymail \
- --dataset_config "3.0.0" \
- --output_dir /tmp/tst-summarization \
- --per_device_train_batch_size 8 \
- --per_device_eval_batch_size 16 \
- --num_train_epochs 3 \
- --do_train \
- --do_eval
-```
-
-
-
-## Addestramento distribuito e precisione mista
-
-Il [Trainer](https://huggingface.co/docs/transformers/main_classes/trainer) supporta l'addestramento distribuito e la precisione mista, che significa che puoi anche usarla in uno script. Per abilitare entrambe le funzionalitĂ :
-
-- Aggiunto l'argomento `fp16` per abilitare la precisione mista.
-- Imposta un numero di GPU da usare con l'argomento `nproc_per_node`.
-
-```bash
-python -m torch.distributed.launch \
- --nproc_per_node 8 pytorch/summarization/run_summarization.py \
- --fp16 \
- --model_name_or_path t5-small \
- --do_train \
- --do_eval \
- --dataset_name cnn_dailymail \
- --dataset_config "3.0.0" \
- --source_prefix "summarize: " \
- --output_dir /tmp/tst-summarization \
- --per_device_train_batch_size=4 \
- --per_device_eval_batch_size=4 \
- --overwrite_output_dir \
- --predict_with_generate
-```
-
-Gli script TensorFlow utilizzano una [`MirroredStrategy`](https://www.tensorflow.org/guide/distributed_training#mirroredstrategy) per il training distribuito e non devi aggiungere alcun argomento addizionale allo script di training. Lo script TensorFlow userĂ multiple GPU in modo predefinito se quest'ultime sono disponibili:
-
-## Esegui uno script su TPU
-
-
-
-Le Tensor Processing Units (TPU) sono state progettate per migliorare le prestazioni. PyTorch supporta le TPU con il compilatore per deep learning [XLA](https://www.tensorflow.org/xla) (guarda [questo link](https://github.com/pytorch/xla/blob/master/README.md) per maggiori dettagli). Per usare una TPU, avvia lo script `xla_spawn.py` e usa l'argomento `num_cores` per impostare il numero di core TPU che intendi usare.
-
-```bash
-python xla_spawn.py --num_cores 8 \
- summarization/run_summarization.py \
- --model_name_or_path t5-small \
- --do_train \
- --do_eval \
- --dataset_name cnn_dailymail \
- --dataset_config "3.0.0" \
- --source_prefix "summarize: " \
- --output_dir /tmp/tst-summarization \
- --per_device_train_batch_size=4 \
- --per_device_eval_batch_size=4 \
- --overwrite_output_dir \
- --predict_with_generate
-```
-
-
-Le Tensor Processing Units (TPU) sono state progettate per migliorare le prestazioni. Gli script TensorFlow utilizzano una [`TPUStrategy`](https://www.tensorflow.org/guide/distributed_training#tpustrategy) per eseguire l'addestramento su TPU. Per usare una TPU, passa il nome della risorsa TPU all'argomento `tpu`.
-
-```bash
-python run_summarization.py \
- --tpu name_of_tpu_resource \
- --model_name_or_path t5-small \
- --dataset_name cnn_dailymail \
- --dataset_config "3.0.0" \
- --output_dir /tmp/tst-summarization \
- --per_device_train_batch_size 8 \
- --per_device_eval_batch_size 16 \
- --num_train_epochs 3 \
- --do_train \
- --do_eval
-```
-
-
-
-## Esegui uno script con đ€ Accelerate
-
-đ€ [Accelerate](https://huggingface.co/docs/accelerate) Ăš una libreria compatibile solo con PyTorch che offre un metodo unificato per addestrare modelli su diverse tipologie di configurazioni (CPU, multiple GPU, TPU) mantenendo una completa visibilitĂ rispetto al ciclo di training di PyTorch. Assicurati di aver effettuato l'installazione di đ€ Accelerate, nel caso non lo avessi fatto:
-
-> Nota: dato che Accelerate Ăš in rapido sviluppo, Ăš necessario installare la versione proveniente da git per eseguire gli script:
-```bash
-pip install git+https://github.com/huggingface/accelerate
-```
-
-Invece che usare lo script `run_summarization.py`, devi usare lo script `run_summarization_no_trainer.py`. Gli script supportati in đ€ Accelerate avranno un file chiamato `task_no_trainer.py` nella rispettiva cartella. Per iniziare, esegui il seguente comando per creare e salvare un file di configurazione:
-
-```bash
-accelerate config
-```
-
-Testa la tua configurazione per assicurarti della sua correttezza:
-
-```bash
-accelerate test
-```
-
-Ora sei pronto per avviare l'addestramento:
-
-```bash
-accelerate launch run_summarization_no_trainer.py \
- --model_name_or_path t5-small \
- --dataset_name cnn_dailymail \
- --dataset_config "3.0.0" \
- --source_prefix "summarize: " \
- --output_dir ~/tmp/tst-summarization
-```
-
-## Uso di un dataset personalizzato
-
-Lo script di summarization supporta dataset personalizzati purché siano file CSV o JSON Line. Quando usi il tuo dataset, devi specificare diversi argomenti aggiuntivi:
-
-- `train_file` e `validation_file` specificano dove si trovano i file di addestramento e validazione.
-- `text_column` Ăš il file di input da riassumere.
-- `summary_column` Ăš il file di destinazione per l'output.
-
-Uno script di summarization usando un dataset personalizzato sarebbe simile a questo:
-
-```bash
-python examples/pytorch/summarization/run_summarization.py \
- --model_name_or_path t5-small \
- --do_train \
- --do_eval \
- --train_file path_to_csv_or_jsonlines_file \
- --validation_file path_to_csv_or_jsonlines_file \
- --text_column text_column_name \
- --summary_column summary_column_name \
- --source_prefix "summarize: " \
- --output_dir /tmp/tst-summarization \
- --overwrite_output_dir \
- --per_device_train_batch_size=4 \
- --per_device_eval_batch_size=4 \
- --predict_with_generate
-```
-
-## Testare uno script
-
-Ă spesso una buona idea avviare il tuo script su un numero inferiore di esempi tratti dal dataset, per assicurarti che tutto funzioni come previsto prima di eseguire lo script sull'intero dataset, che potrebbe necessitare di ore. Usa i seguenti argomenti per limitare il dataset ad un massimo numero di esempi:
-
-- `max_train_samples`
-- `max_eval_samples`
-- `max_predict_samples`
-
-```bash
-python examples/pytorch/summarization/run_summarization.py \
- --model_name_or_path t5-small \
- --max_train_samples 50 \
- --max_eval_samples 50 \
- --max_predict_samples 50 \
- --do_train \
- --do_eval \
- --dataset_name cnn_dailymail \
- --dataset_config "3.0.0" \
- --source_prefix "summarize: " \
- --output_dir /tmp/tst-summarization \
- --per_device_train_batch_size=4 \
- --per_device_eval_batch_size=4 \
- --overwrite_output_dir \
- --predict_with_generate
-```
-
-Non tutti gli esempi di script supportano l'argomento `max_predict_samples`. Se non sei sicuro circa il supporto di questo argomento da parte del tuo script, aggiungi l'argomento `-h` per controllare:
-
-```bash
-examples/pytorch/summarization/run_summarization.py -h
-```
-
-## Riavviare addestramento da un checkpoint
-
-Un'altra utile opzione Ăš riavviare un addestramento da un checkpoint precedente. Questo garantirĂ che tu possa riprendere da dove hai interrotto senza ricominciare se l'addestramento viene interrotto. Ci sono due metodi per riavviare l'addestramento da un checkpoint:
-
-Il primo metodo usa l'argomento `output_dir previous_output_dir` per riavviare l'addestramento dall'ultima versione del checkpoint contenuto in `output_dir`. In questo caso, dovresti rimuovere `overwrite_output_dir`:
-
-```bash
-python examples/pytorch/summarization/run_summarization.py
- --model_name_or_path t5-small \
- --do_train \
- --do_eval \
- --dataset_name cnn_dailymail \
- --dataset_config "3.0.0" \
- --source_prefix "summarize: " \
- --output_dir /tmp/tst-summarization \
- --per_device_train_batch_size=4 \
- --per_device_eval_batch_size=4 \
- --output_dir previous_output_dir \
- --predict_with_generate
-```
-
-Il secondo metodo usa l'argomento `resume_from_checkpoint path_to_specific_checkpoint` per riavviare un addestramento da una specifica cartella di checkpoint.
-
-```bash
-python examples/pytorch/summarization/run_summarization.py
- --model_name_or_path t5-small \
- --do_train \
- --do_eval \
- --dataset_name cnn_dailymail \
- --dataset_config "3.0.0" \
- --source_prefix "summarize: " \
- --output_dir /tmp/tst-summarization \
- --per_device_train_batch_size=4 \
- --per_device_eval_batch_size=4 \
- --overwrite_output_dir \
- --resume_from_checkpoint path_to_specific_checkpoint \
- --predict_with_generate
-```
-
-## Condividi il tuo modello
-
-Tutti gli script possono caricare il tuo modello finale al [Model Hub](https://huggingface.co/models). Prima di iniziare, assicurati di aver effettuato l'accesso su Hugging Face:
-
-```bash
-huggingface-cli login
-```
-
-Poi, aggiungi l'argomento `push_to_hub` allo script. Questo argomento consentirĂ di creare un repository con il tuo username Hugging Face e la cartella specificata in `output_dir`.
-
-Per dare uno specifico nome al repository, usa l'argomento `push_to_hub_model_id`. Il repository verrĂ automaticamente elencata sotto al tuo namespace.
-
-Il seguente esempio mostra come caricare un modello specificando il nome del repository:
-
-```bash
-python examples/pytorch/summarization/run_summarization.py
- --model_name_or_path t5-small \
- --do_train \
- --do_eval \
- --dataset_name cnn_dailymail \
- --dataset_config "3.0.0" \
- --source_prefix "summarize: " \
- --push_to_hub \
- --push_to_hub_model_id finetuned-t5-cnn_dailymail \
- --output_dir /tmp/tst-summarization \
- --per_device_train_batch_size=4 \
- --per_device_eval_batch_size=4 \
- --overwrite_output_dir \
- --predict_with_generate
-```
diff --git a/docs/source/it/serialization.md b/docs/source/it/serialization.md
new file mode 100644
index 000000000000..0067f1a3c52e
--- /dev/null
+++ b/docs/source/it/serialization.md
@@ -0,0 +1,677 @@
+
+
+# Esporta modelli đ€ Transformers
+
+Se devi implementare đ€ modelli Transformers in ambienti di produzione, noi
+consigliamo di esportarli in un formato serializzato che puĂČ essere caricato ed eseguito
+su runtime e hardware specializzati. In questa guida ti mostreremo come farlo
+esporta đ€ Modelli Transformers in due formati ampiamente utilizzati: ONNX e TorchScript.
+
+Una volta esportato, un modello puĂČ essere ottimizato per l'inferenza tramite tecniche come
+la quantizzazione e soppressione. Se sei interessato a ottimizzare i tuoi modelli per l'esecuzione
+con la massima efficienza, dai un'occhiata a [đ€ Optimum
+library](https://github.com/huggingface/optimum).
+
+## ONNX
+
+Il progetto [ONNX (Open Neural Network eXchange)](http://onnx.ai) Il progetto onnx Ăš un open
+standard che definisce un insieme comune di operatori e un formato di file comune a
+rappresentano modelli di deep learning in un'ampia varietĂ di framework, tra cui
+PyTorch e TensorFlow. Quando un modello viene esportato nel formato ONNX, questi
+operatori sono usati per costruire un grafico computazionale (often called an
+_intermediate representation_) che rappresenta il flusso di dati attraverso la
+rete neurale.
+
+Esponendo un grafico con operatori e tipi di dati standardizzati, ONNX rende
+piĂč facile passare da un framework all'altro. Ad esempio, un modello allenato in PyTorch puĂČ
+essere esportato in formato ONNX e quindi importato in TensorFlow (e viceversa).
+
+đ€ Transformers fornisce un pacchetto `transformers.onnx` che ti consente di
+convertire i checkpoint del modello in un grafico ONNX sfruttando gli oggetti di configurazione.
+Questi oggetti di configurazione sono giĂ pronti per una serie di architetture di modelli,
+e sono progettati per essere facilmente estensibili ad altre architetture.
+
+Le configurazioni pronte includono le seguenti architetture:
+
+
+
+- ALBERT
+- BART
+- BEiT
+- BERT
+- BigBird
+- BigBird-Pegasus
+- Blenderbot
+- BlenderbotSmall
+- CamemBERT
+- ConvBERT
+- Data2VecText
+- Data2VecVision
+- DeiT
+- DistilBERT
+- ELECTRA
+- FlauBERT
+- GPT Neo
+- GPT-J
+- I-BERT
+- LayoutLM
+- M2M100
+- Marian
+- mBART
+- MobileBERT
+- OpenAI GPT-2
+- Perceiver
+- PLBart
+- RoBERTa
+- RoFormer
+- SqueezeBERT
+- T5
+- ViT
+- XLM
+- XLM-RoBERTa
+- XLM-RoBERTa-XL
+
+Nelle prossime due sezioni, ti mostreremo come:
+
+* Esporta un modello supportato usando il pacchetto `transformers.onnx`.
+* Esporta un modello personalizzato per un'architettura non supportata.
+
+### Esportazione di un modello in ONNX
+
+Per esportare un modello đ€ Transformers in ONNX, dovrai prima installarne alcune
+dipendenze extra:
+
+```bash
+pip install transformers[onnx]
+```
+
+Il pacchetto `transformers.onnx` puĂČ essere usato come modulo Python:
+
+```bash
+python -m transformers.onnx --help
+
+usage: Hugging Face Transformers ONNX exporter [-h] -m MODEL [--feature {causal-lm, ...}] [--opset OPSET] [--atol ATOL] output
+
+positional arguments:
+ output Path indicating where to store generated ONNX model.
+
+optional arguments:
+ -h, --help show this help message and exit
+ -m MODEL, --model MODEL
+ Model ID on huggingface.co or path on disk to load model from.
+ --feature {causal-lm, ...}
+ The type of features to export the model with.
+ --opset OPSET ONNX opset version to export the model with.
+ --atol ATOL Absolute difference tolerance when validating the model.
+```
+
+L'esportazione di un checkpoint utilizzando una configurazione giĂ pronta puĂČ essere eseguita come segue:
+
+```bash
+python -m transformers.onnx --model=distilbert-base-uncased onnx/
+```
+
+che dovrebbe mostrare i seguenti log:
+
+```bash
+Validating ONNX model...
+ -[â] ONNX model output names match reference model ({'last_hidden_state'})
+ - Validating ONNX Model output "last_hidden_state":
+ -[â] (2, 8, 768) matches (2, 8, 768)
+ -[â] all values close (atol: 1e-05)
+All good, model saved at: onnx/model.onnx
+```
+
+Questo esporta un grafico ONNX del checkpoint definito dall'argomento `--model`.
+In questo esempio Ăš `distilbert-base-uncased`, ma puĂČ essere qualsiasi checkpoint
+Hugging Face Hub o uno memorizzato localmente.
+
+Il file risultante `model.onnx` puĂČ quindi essere eseguito su uno dei [tanti
+acceleratori](https://onnx.ai/supported-tools.html#deployModel) che supportano il
+lo standard ONNX. Ad esempio, possiamo caricare ed eseguire il modello con [ONNX
+Runtime](https://onnxruntime.ai/) come segue:
+
+```python
+>>> from transformers import AutoTokenizer
+>>> from onnxruntime import InferenceSession
+
+>>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
+>>> session = InferenceSession("onnx/model.onnx")
+>>> # ONNX Runtime expects NumPy arrays as input
+>>> inputs = tokenizer("Using DistilBERT with ONNX Runtime!", return_tensors="np")
+>>> outputs = session.run(output_names=["last_hidden_state"], input_feed=dict(inputs))
+```
+
+I nomi di output richiesti (cioĂš `["last_hidden_state"]`) possono essere ottenuti
+dando un'occhiata alla configurazione ONNX di ogni modello. Ad esempio, per
+DistilBERT abbiamo:
+
+```python
+>>> from transformers.models.distilbert import DistilBertConfig, DistilBertOnnxConfig
+
+>>> config = DistilBertConfig()
+>>> onnx_config = DistilBertOnnxConfig(config)
+>>> print(list(onnx_config.outputs.keys()))
+["last_hidden_state"]
+```
+
+Il processo Ăš identico per i checkpoint TensorFlow sull'hub. Ad esempio, noi
+possiamo esportare un checkpoint TensorFlow puro da [Keras
+organizzazione](https://huggingface.co/keras-io) come segue:
+
+```bash
+python -m transformers.onnx --model=keras-io/transformers-qa onnx/
+```
+
+Per esportare un modello memorizzato localmente, devi disporre dei pesi del modello
+e file tokenizer memorizzati in una directory. Ad esempio, possiamo caricare e salvare un
+checkpoint come segue:
+
+
+
+```python
+>>> from transformers import AutoTokenizer, AutoModelForSequenceClassification
+
+>>> # Load tokenizer and PyTorch weights form the Hub
+>>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
+>>> pt_model = AutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased")
+>>> # Save to disk
+>>> tokenizer.save_pretrained("local-pt-checkpoint")
+>>> pt_model.save_pretrained("local-pt-checkpoint")
+```
+
+Una volta salvato il checkpoint, possiamo esportarlo su ONNX puntando l'argomento `--model`
+del pacchetto `transformers.onnx` nella directory desiderata:
+
+```bash
+python -m transformers.onnx --model=local-pt-checkpoint onnx/
+```
+
+
+```python
+>>> from transformers import AutoTokenizer, TFAutoModelForSequenceClassification
+
+>>> # Load tokenizer and TensorFlow weights from the Hub
+>>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
+>>> tf_model = TFAutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased")
+>>> # Save to disk
+>>> tokenizer.save_pretrained("local-tf-checkpoint")
+>>> tf_model.save_pretrained("local-tf-checkpoint")
+```
+
+Once the checkpoint is saved, we can export it to ONNX by pointing the `--model`
+argument of the `transformers.onnx` package to the desired directory:
+
+```bash
+python -m transformers.onnx --model=local-tf-checkpoint onnx/
+```
+
+
+
+### Selezione delle caratteristiche per diverse topologie di modello
+
+Ogni configurazione giĂ pronta viene fornita con una serie di _caratteristiche_ che ti consentono di
+esportare modelli per diversi tipi di topologie o attivitĂ . Come mostrato nella tabella
+di seguito, ogni caratteristica Ăš associata a una diversa Auto Class:
+
+| Caratteristica | Auto Class |
+| ------------------------------------ | ------------------------------------ |
+| `causal-lm`, `causal-lm-with-past` | `AutoModelForCausalLM` |
+| `default`, `default-with-past` | `AutoModel` |
+| `masked-lm` | `AutoModelForMaskedLM` |
+| `question-answering` | `AutoModelForQuestionAnswering` |
+| `seq2seq-lm`, `seq2seq-lm-with-past` | `AutoModelForSeq2SeqLM` |
+| `sequence-classification` | `AutoModelForSequenceClassification` |
+| `token-classification` | `AutoModelForTokenClassification` |
+
+Per ciascuna configurazione, puoi trovare l'elenco delle funzionalitĂ supportate tramite il
+`FeaturesManager`. Ad esempio, per DistilBERT abbiamo:
+
+```python
+>>> from transformers.onnx.features import FeaturesManager
+
+>>> distilbert_features = list(FeaturesManager.get_supported_features_for_model_type("distilbert").keys())
+>>> print(distilbert_features)
+["default", "masked-lm", "causal-lm", "sequence-classification", "token-classification", "question-answering"]
+```
+
+Puoi quindi passare una di queste funzionalitĂ all'argomento `--feature` nel
+pacchetto `transformers.onnx`. Ad esempio, per esportare un modello di classificazione del testo
+possiamo scegliere un modello ottimizzato dall'Hub ed eseguire:
+
+```bash
+python -m transformers.onnx --model=distilbert-base-uncased-finetuned-sst-2-english \
+ --feature=sequence-classification onnx/
+```
+
+che visualizzerĂ i seguenti registri:
+
+```bash
+Validating ONNX model...
+ -[â] ONNX model output names match reference model ({'logits'})
+ - Validating ONNX Model output "logits":
+ -[â] (2, 2) matches (2, 2)
+ -[â] all values close (atol: 1e-05)
+All good, model saved at: onnx/model.onnx
+```
+
+Puoi notare che in questo caso, i nomi di output del modello ottimizzato sono
+`logits` invece di `last_hidden_state` che abbiamo visto con il
+checkpoint `distilbert-base-uncased` precedente. Questo Ăš previsto dal
+modello ottimizato visto che ha una testa di e.
+
+
+
+Le caratteristiche che hanno un suffisso `wtih-past` (ad es. `causal-lm-with-past`)
+corrispondono a topologie di modello con stati nascosti precalcolati (chiave e valori
+nei blocchi di attenzione) che possono essere utilizzati per la decodifica autoregressiva veloce.
+
+
+
+
+### Esportazione di un modello per un'architettura non supportata
+
+Se desideri esportare un modello la cui architettura non Ăš nativamente supportata dalla
+libreria, ci sono tre passaggi principali da seguire:
+
+1. Implementare una configurazione ONNX personalizzata.
+2. Esportare il modello in ONNX.
+3. Convalidare gli output di PyTorch e dei modelli esportati.
+
+In questa sezione, vedremo come DistilBERT Ăš stato implementato per mostrare cosa Ăš
+coinvolto in ogni passaggio.
+
+#### Implementazione di una configurazione ONNX personalizzata
+
+Iniziamo con l'oggetto di configurazione ONNX. Forniamo tre classi
+astratte da cui ereditare, a seconda del tipo di archittettura
+del modello che desideri esportare:
+
+* I modelli basati su encoder ereditano da [`~onnx.config.OnnxConfig`]
+* I modelli basati su decoder ereditano da [`~onnx.config.OnnxConfigWithPast`]
+* I modelli encoder-decoder ereditano da[`~onnx.config.OnnxSeq2SeqConfigWithPast`]
+
+
+
+Un buon modo per implementare una configurazione ONNX personalizzata Ăš guardare l'implementazione
+esistente nel file `configuration_.py` di un'architettura simile.
+
+
+
+Poiché DistilBERT Ú un modello basato su encoder, la sua configurazione eredita da
+`OnnxConfig`:
+
+```python
+>>> from typing import Mapping, OrderedDict
+>>> from transformers.onnx import OnnxConfig
+
+
+>>> class DistilBertOnnxConfig(OnnxConfig):
+... @property
+... def inputs(self) -> Mapping[str, Mapping[int, str]]:
+... return OrderedDict(
+... [
+... ("input_ids", {0: "batch", 1: "sequence"}),
+... ("attention_mask", {0: "batch", 1: "sequence"}),
+... ]
+... )
+```
+
+Ogni oggetto di configurazione deve implementare la proprietĂ `inputs` e restituire una
+mappatura, dove ogni chiave corrisponde a un input previsto e ogni valore
+indica l'asse di quell'input. Per DistilBERT, possiamo vedere che sono richiesti
+due input: `input_ids` e `attention_mask`. Questi inputs hanno la stessa forma di
+`(batch_size, sequence_length)` per questo motivo vediamo gli stessi assi usati nella
+configurazione.
+
+
+
+Puoi notare che la proprietĂ `inputs` per `DistilBertOnnxConfig` restituisce un
+`OrdinatoDict`. CiĂČ garantisce che gli input corrispondano alla loro posizione
+relativa all'interno del metodo `PreTrainedModel.forward()` durante il tracciamento del grafico.
+Raccomandiamo di usare un `OrderedDict` per le proprietĂ `inputs` e `outputs`
+quando si implementano configurazioni ONNX personalizzate.
+
+
+
+Dopo aver implementato una configurazione ONNX, Ăš possibile istanziarla
+fornendo alla configurazione del modello base come segue:
+
+```python
+>>> from transformers import AutoConfig
+
+>>> config = AutoConfig.from_pretrained("distilbert-base-uncased")
+>>> onnx_config = DistilBertOnnxConfig(config)
+```
+
+L'oggetto risultante ha diverse proprietĂ utili. Ad esempio Ăš possibile visualizzare il
+Set operatore ONNX che verrĂ utilizzato durante l'esportazione:
+
+```python
+>>> print(onnx_config.default_onnx_opset)
+11
+```
+
+Ă inoltre possibile visualizzare gli output associati al modello come segue:
+
+```python
+>>> print(onnx_config.outputs)
+OrderedDict([("last_hidden_state", {0: "batch", 1: "sequence"})])
+```
+
+Puoi notare che la proprietĂ degli output segue la stessa struttura degli input; esso
+restituisce un `OrderedDict` di output con nome e le loro forme. La struttura di output
+Ăš legato alla scelta della funzione con cui viene inizializzata la configurazione.
+Per impostazione predefinita, la configurazione ONNX viene inizializzata con la funzione 'predefinita'
+che corrisponde all'esportazione di un modello caricato con la classe `AutoModel`. Se tu
+desideri esportare una topologia di modello diversa, Ăš sufficiente fornire una funzionalitĂ diversa a
+l'argomento `task` quando inizializzi la configurazione ONNX. Ad esempio, se
+volevamo esportare DistilBERT con una testa di classificazione per sequenze, potremmo
+usare:
+
+```python
+>>> from transformers import AutoConfig
+
+>>> config = AutoConfig.from_pretrained("distilbert-base-uncased")
+>>> onnx_config_for_seq_clf = DistilBertOnnxConfig(config, task="sequence-classification")
+>>> print(onnx_config_for_seq_clf.outputs)
+OrderedDict([('logits', {0: 'batch'})])
+```
+
+
+
+Tutte le proprietĂ e i metodi di base associati a [`~onnx.config.OnnxConfig`] e le
+altre classi di configurazione possono essere sovrascritte se necessario. Guarda
+[`BartOnnxConfig`] per un esempio avanzato.
+
+
+
+#### Esportazione del modello
+
+Una volta implementata la configurazione ONNX, il passaggio successivo consiste nell'esportare il
+modello. Qui possiamo usare la funzione `export()` fornita dal
+pacchetto `transformers.onnx`. Questa funzione prevede la configurazione ONNX, insieme
+con il modello base e il tokenizer e il percorso per salvare il file esportato:
+
+```python
+>>> from pathlib import Path
+>>> from transformers.onnx import export
+>>> from transformers import AutoTokenizer, AutoModel
+
+>>> onnx_path = Path("model.onnx")
+>>> model_ckpt = "distilbert-base-uncased"
+>>> base_model = AutoModel.from_pretrained(model_ckpt)
+>>> tokenizer = AutoTokenizer.from_pretrained(model_ckpt)
+
+>>> onnx_inputs, onnx_outputs = export(tokenizer, base_model, onnx_config, onnx_config.default_onnx_opset, onnx_path)
+```
+
+Gli `onnx_inputs` e `onnx_outputs` restituiti dalla funzione `export()` sono
+liste di chiavi definite nelle proprietĂ di `input` e `output` della
+configurazione. Una volta esportato il modello, puoi verificare che il modello sia ben
+formato come segue:
+
+```python
+>>> import onnx
+
+>>> onnx_model = onnx.load("model.onnx")
+>>> onnx.checker.check_model(onnx_model)
+```
+
+
+
+Se il tuo modello Ăš piĂč largo di 2 GB, vedrai che molti file aggiuntivi sono
+creati durante l'esportazione. Questo Ú _previsto_ perché ONNX utilizza [Protocol
+Buffer](https://developers.google.com/protocol-buffers/) per memorizzare il modello e
+questi hanno un limite di dimensione 2 GB. Vedi la [Documentazione
+ONNX](https://github.com/onnx/onnx/blob/master/docs/ExternalData.md)
+per istruzioni su come caricare modelli con dati esterni.
+
+
+
+#### Convalida degli output del modello
+
+Il passaggio finale consiste nel convalidare gli output dal modello di base e quello esportato
+corrispondere entro una soglia di tolleranza assoluta. Qui possiamo usare la
+Funzione `validate_model_outputs()` fornita dal pacchetto `transformers.onnx`
+come segue:
+
+```python
+>>> from transformers.onnx import validate_model_outputs
+
+>>> validate_model_outputs(
+... onnx_config, tokenizer, base_model, onnx_path, onnx_outputs, onnx_config.atol_for_validation
+... )
+```
+
+Questa funzione usa il metodo `OnnxConfig.generate_dummy_inputs()` per generare
+input per il modello di base e quello esportato e la tolleranza assoluta puĂČ essere
+definita nella configurazione. Generalmente troviamo una corrispondenza numerica nell'intervallo da 1e-6
+a 1e-4, anche se Ăš probabile che qualsiasi cosa inferiore a 1e-3 vada bene.
+
+### Contribuire con una nuova configurazione a đ€ Transformers
+
+Stiamo cercando di espandere l'insieme di configurazioni giĂ pronte e di accettare
+contributi della community! Se vuoi contribuire con la tua aggiunta
+nella libreria, dovrai:
+
+* Implementare la configurazione ONNX nella corrispondente `configuration file
+_.py`
+* Includere l'architettura del modello e le funzioni corrispondenti in [`~onnx.features.FeatureManager`]
+* Aggiungere la tua architettura del modello ai test in `test_onnx_v2.py`
+
+Scopri come stato contribuito la configurazione per [IBERT]
+(https://github.com/huggingface/transformers/pull/14868/files) per
+avere un'idea di cosa Ăš coinvolto.
+
+## TorchScript
+
+
+
+Questo Ăš l'inizio dei nostri esperimenti con TorchScript e stiamo ancora esplorando le sue capacitĂ con
+modelli con variable-input-size. Ă una nostra prioritĂ e approfondiremo le nostre analisi nelle prossime versioni,
+con piĂč esempi di codici, un'implementazione piĂč flessibile e benchmark che confrontano i codici basati su Python con quelli compilati con
+TorchScript.
+
+
+
+Secondo la documentazione di Pytorch: "TorchScript Ăš un modo per creare modelli serializzabili e ottimizzabili da codice
+Pytorch". I due moduli di Pytorch [JIT e TRACE](https://pytorch.org/docs/stable/jit.html) consentono allo sviluppatore di esportare
+il loro modello da riutilizzare in altri programmi, come i programmi C++ orientati all'efficienza.
+
+Abbiamo fornito un'interfaccia che consente l'esportazione di modelli đ€ Transformers in TorchScript in modo che possano essere riutilizzati
+in un ambiente diverso rispetto a un programma Python basato su Pytorch. Qui spieghiamo come esportare e utilizzare i nostri modelli utilizzando
+TorchScript.
+
+Esportare un modello richiede due cose:
+
+- Un passaggio in avanti con input fittizzi.
+- Istanziazione del modello con flag `torchscript`.
+
+Queste necessitĂ implicano diverse cose a cui gli sviluppatori dovrebbero prestare attenzione. Questi dettagli mostrati sotto.
+
+### Flag TorchScript e pesi legati
+
+Questo flag Ú necessario perché la maggior parte dei modelli linguistici in questo repository hanno pesi legati tra il loro
+strato "Embedding" e lo strato "Decoding". TorchScript non consente l'esportazione di modelli che hanno pesi
+legati, quindi Ăš necessario prima slegare e clonare i pesi.
+
+CiĂČ implica che i modelli istanziati con il flag `torchscript` hanno il loro strato `Embedding` e strato `Decoding`
+separato, il che significa che non dovrebbero essere addestrati in futuro. L'allenamento de-sincronizza i due
+strati, portando a risultati inaspettati.
+
+Questo non Ú il caso per i modelli che non hanno una testa del modello linguistico, poiché quelli non hanno pesi legati. Questi modelli
+puĂČ essere esportato in sicurezza senza il flag `torchscript`.
+
+### Input fittizi e standard lengths
+
+Gli input fittizzi sono usati per fare un modello passaggio in avanti . Mentre i valori degli input si propagano attraverso i strati,
+Pytorch tiene traccia delle diverse operazioni eseguite su ciascun tensore. Queste operazioni registrate vengono quindi utilizzate per
+creare la "traccia" del modello.
+
+La traccia viene creata relativamente alle dimensioni degli input. Ă quindi vincolato dalle dimensioni dell'input
+fittizio e non funzionerĂ per altre lunghezze di sequenza o dimensioni batch. Quando si proverĂ con una dimensione diversa, ci sarĂ errore
+come:
+
+`La dimensione espansa del tensore (3) deve corrispondere alla dimensione esistente (7) nella dimensione non singleton 2`
+
+will be raised. Si consiglia pertanto di tracciare il modello con una dimensione di input fittizia grande almeno quanto il piĂč grande
+input che verrĂ fornito al modello durante l'inferenza. Ă possibile eseguire il padding per riempire i valori mancanti. Il modello
+sarĂ tracciato con una grande dimensione di input, tuttavia, anche le dimensioni della diverse matrici saranno grandi,
+risultando in piĂč calcoli.
+
+Si raccomanda di prestare attenzione al numero totale di operazioni eseguite su ciascun input e di seguire da vicino le prestazioni
+durante l'esportazione di modelli di sequenza-lunghezza variabili.
+
+### Usare TorchSscript in Python
+
+Di seguito Ăš riportato un esempio, che mostra come salvare, caricare modelli e come utilizzare la traccia per l'inferenza.
+
+#### Salvare un modello
+
+Questo frammento di codice mostra come usare TorchScript per esportare un `BertModel`. Qui il `BertModel` Ăš istanziato secondo
+una classe `BertConfig` e quindi salvato su disco con il nome del file `traced_bert.pt`
+
+```python
+from transformers import BertModel, BertTokenizer, BertConfig
+import torch
+
+enc = BertTokenizer.from_pretrained("bert-base-uncased")
+
+# Tokenizing input text
+text = "[CLS] Who was Jim Henson ? [SEP] Jim Henson was a puppeteer [SEP]"
+tokenized_text = enc.tokenize(text)
+
+# Masking one of the input tokens
+masked_index = 8
+tokenized_text[masked_index] = "[MASK]"
+indexed_tokens = enc.convert_tokens_to_ids(tokenized_text)
+segments_ids = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1]
+
+# Creating a dummy input
+tokens_tensor = torch.tensor([indexed_tokens])
+segments_tensors = torch.tensor([segments_ids])
+dummy_input = [tokens_tensor, segments_tensors]
+
+# Initializing the model with the torchscript flag
+# Flag set to True even though it is not necessary as this model does not have an LM Head.
+config = BertConfig(
+ vocab_size_or_config_json_file=32000,
+ hidden_size=768,
+ num_hidden_layers=12,
+ num_attention_heads=12,
+ intermediate_size=3072,
+ torchscript=True,
+)
+
+# Instantiating the model
+model = BertModel(config)
+
+# The model needs to be in evaluation mode
+model.eval()
+
+# If you are instantiating the model with *from_pretrained* you can also easily set the TorchScript flag
+model = BertModel.from_pretrained("bert-base-uncased", torchscript=True)
+
+# Creating the trace
+traced_model = torch.jit.trace(model, [tokens_tensor, segments_tensors])
+torch.jit.save(traced_model, "traced_bert.pt")
+```
+
+#### Caricare un modello
+
+Questo frammento di codice mostra come caricare il `BertModel` che era stato precedentemente salvato su disco con il nome `traced_bert.pt`.
+Stiamo riutilizzando il `dummy_input` precedentemente inizializzato.
+
+```python
+loaded_model = torch.jit.load("traced_bert.pt")
+loaded_model.eval()
+
+all_encoder_layers, pooled_output = loaded_model(*dummy_input)
+```
+
+#### Utilizzare un modello tracciato per l'inferenza
+
+Usare il modello tracciato per l'inferenza Ăš semplice come usare il suo metodo dunder `__call__`:
+
+```python
+traced_model(tokens_tensor, segments_tensors)
+```
+
+###Implementare modelli HuggingFace TorchScript su AWS utilizzando Neuron SDK
+
+AWS ha introdotto [Amazon EC2 Inf1](https://aws.amazon.com/ec2/instance-types/inf1/)
+famiglia di istanze per l'inferenza di machine learning a basso costo e ad alte prestazioni nel cloud.
+Le istanze Inf1 sono alimentate dal chip AWS Inferentia, un acceleratore hardware personalizzato,
+specializzato in carichi di lavoro di inferenza di deep learning.
+[AWS Neuron](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/#)
+Ăš l'SDK per Inferentia che supporta il tracciamento e l'ottimizzazione dei modelli transformers per
+distribuzione su Inf1. L'SDK Neuron fornisce:
+
+
+1. API di facile utilizzo con una riga di modifica del codice per tracciare e ottimizzare un modello TorchScript per l'inferenza nel cloud.
+2. Ottimizzazioni delle prestazioni pronte all'uso per [miglioramento dei costi-prestazioni](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/neuron-guide/benchmark/>)
+3. Supporto per i modelli di trasformatori HuggingFace costruiti con [PyTorch](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/src/examples/pytorch/bert_tutorial/tutorial_pretrained_bert.html)
+ o [TensorFlow](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/src/examples/tensorflow/huggingface_bert/huggingface_bert.html).
+
+#### Implicazioni
+
+Modelli Transformers basati su architettura [BERT (Bidirectional Encoder Representations from Transformers)](https://huggingface.co/docs/transformers/main/model_doc/bert),
+o sue varianti come [distilBERT](https://huggingface.co/docs/transformers/main/model_doc/distilbert)
+e [roBERTa](https://huggingface.co/docs/transformers/main/model_doc/roberta)
+funzioneranno meglio su Inf1 per attivitĂ non generative come la question answering estrattive,
+Classificazione della sequenza, Classificazione dei token. In alternativa, generazione di testo
+le attivitĂ possono essere adattate per essere eseguite su Inf1, secondo questo [tutorial AWS Neuron MarianMT](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/src/examples/pytorch/transformers-marianmt.html).
+Ulteriori informazioni sui modelli che possono essere convertiti fuori dagli schemi su Inferentia possono essere
+trovati nella [sezione Model Architecture Fit della documentazione Neuron](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/neuron-guide/models/models-inferentia.html#models-inferentia).
+
+#### Dipendenze
+
+L'utilizzo di AWS Neuron per convertire i modelli richiede le seguenti dipendenze e l'ambiente:
+
+* A [Neuron SDK environment](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/neuron-guide/neuron-frameworks/pytorch-neuron/index.html#installation-guide),
+ which comes pre-configured on [AWS Deep Learning AMI](https://docs.aws.amazon.com/dlami/latest/devguide/tutorial-inferentia-launching.html).
+
+#### Convertire un modello per AWS Neuron
+
+Usando lo stesso script come in [Usando TorchScipt in Python](https://huggingface.co/docs/transformers/main/en/serialization#using-torchscript-in-python)
+per tracciare un "BertModel", importi l'estensione del framework `torch.neuron` per accedere
+i componenti di Neuron SDK tramite un'API Python.
+
+```python
+from transformers import BertModel, BertTokenizer, BertConfig
+import torch
+import torch.neuron
+```
+E modificare solo la riga di codice di traccia
+
+Da:
+
+```python
+torch.jit.trace(model, [tokens_tensor, segments_tensors])
+```
+
+A:
+
+```python
+torch.neuron.trace(model, [token_tensor, segments_tensors])
+```
+
+Questa modifica consente a Neuron SDK di tracciare il modello e ottimizzarlo per l'esecuzione nelle istanze Inf1.
+
+Per ulteriori informazioni sulle funzionalitĂ , gli strumenti, i tutorial di esempi e gli ultimi aggiornamenti di AWS Neuron SDK,
+consultare la [documentazione AWS NeuronSDK](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/index.html).
\ No newline at end of file
diff --git a/docs/source/it/serialization.mdx b/docs/source/it/serialization.mdx
deleted file mode 100644
index 1dde00f429bd..000000000000
--- a/docs/source/it/serialization.mdx
+++ /dev/null
@@ -1,673 +0,0 @@
-
-
-# Esporta modelli đ€ Transformers
-
-Se devi implementare đ€ modelli Transformers in ambienti di produzione, noi
-consigliamo di esportarli in un formato serializzato che puĂČ essere caricato ed eseguito
-su runtime e hardware specializzati. In questa guida ti mostreremo come farlo
-esporta đ€ Modelli Transformers in due formati ampiamente utilizzati: ONNX e TorchScript.
-
-Una volta esportato, un modello puĂČ essere ottimizato per l'inferenza tramite tecniche come
-la quantizzazione e soppressione. Se sei interessato a ottimizzare i tuoi modelli per l'esecuzione
-con la massima efficienza, dai un'occhiata a [đ€ Optimum
-library](https://github.com/huggingface/optimum).
-
-## ONNX
-
-Il progetto [ONNX (Open Neural Network eXchange)](http://onnx.ai) Il progetto onnx Ăš un open
-standard che definisce un insieme comune di operatori e un formato di file comune a
-rappresentano modelli di deep learning in un'ampia varietĂ di framework, tra cui
-PyTorch e TensorFlow. Quando un modello viene esportato nel formato ONNX, questi
-operatori sono usati per costruire un grafico computazionale (often called an
-_intermediate representation_) che rappresenta il flusso di dati attraverso la
-rete neurale.
-
-Esponendo un grafico con operatori e tipi di dati standardizzati, ONNX rende
-piĂč facile passare da un framework all'altro. Ad esempio, un modello allenato in PyTorch puĂČ
-essere esportato in formato ONNX e quindi importato in TensorFlow (e viceversa).
-
-đ€ Transformers fornisce un pacchetto `transformers.onnx` che ti consente di
-convertire i checkpoint del modello in un grafico ONNX sfruttando gli oggetti di configurazione.
-Questi oggetti di configurazione sono giĂ pronti per una serie di architetture di modelli,
-e sono progettati per essere facilmente estensibili ad altre architetture.
-
-Le configurazioni pronte includono le seguenti architetture:
-
-
-
-- ALBERT
-- BART
-- BEiT
-- BERT
-- BigBird
-- BigBird-Pegasus
-- Blenderbot
-- BlenderbotSmall
-- CamemBERT
-- ConvBERT
-- Data2VecText
-- Data2VecVision
-- DeiT
-- DistilBERT
-- ELECTRA
-- FlauBERT
-- GPT Neo
-- GPT-J
-- I-BERT
-- LayoutLM
-- M2M100
-- Marian
-- mBART
-- MobileBERT
-- OpenAI GPT-2
-- Perceiver
-- PLBart
-- RoBERTa
-- RoFormer
-- SqueezeBERT
-- T5
-- ViT
-- XLM
-- XLM-RoBERTa
-- XLM-RoBERTa-XL
-
-Nelle prossime due sezioni, ti mostreremo come:
-
-* Esporta un modello supportato usando il pacchetto `transformers.onnx`.
-* Esporta un modello personalizzato per un'architettura non supportata.
-
-### Esportazione di un modello in ONNX
-
-Per esportare un modello đ€ Transformers in ONNX, dovrai prima installarne alcune
-dipendenze extra:
-
-```bash
-pip install transformers[onnx]
-```
-
-Il pacchetto `transformers.onnx` puĂČ essere usato come modulo Python:
-
-```bash
-python -m transformers.onnx --help
-
-usage: Hugging Face Transformers ONNX exporter [-h] -m MODEL [--feature {causal-lm, ...}] [--opset OPSET] [--atol ATOL] output
-
-positional arguments:
- output Path indicating where to store generated ONNX model.
-
-optional arguments:
- -h, --help show this help message and exit
- -m MODEL, --model MODEL
- Model ID on huggingface.co or path on disk to load model from.
- --feature {causal-lm, ...}
- The type of features to export the model with.
- --opset OPSET ONNX opset version to export the model with.
- --atol ATOL Absolute difference tolerance when validating the model.
-```
-
-L'esportazione di un checkpoint utilizzando una configurazione giĂ pronta puĂČ essere eseguita come segue:
-
-```bash
-python -m transformers.onnx --model=distilbert-base-uncased onnx/
-```
-
-che dovrebbe mostrare i seguenti log:
-
-```bash
-Validating ONNX model...
- -[â] ONNX model output names match reference model ({'last_hidden_state'})
- - Validating ONNX Model output "last_hidden_state":
- -[â] (2, 8, 768) matches (2, 8, 768)
- -[â] all values close (atol: 1e-05)
-All good, model saved at: onnx/model.onnx
-```
-
-Questo esporta un grafico ONNX del checkpoint definito dall'argomento `--model`.
-In questo esempio Ăš `distilbert-base-uncased`, ma puĂČ essere qualsiasi checkpoint
-Hugging Face Hub o uno memorizzato localmente.
-
-Il file risultante `model.onnx` puĂČ quindi essere eseguito su uno dei [tanti
-acceleratori](https://onnx.ai/supported-tools.html#deployModel) che supportano il
-lo standard ONNX. Ad esempio, possiamo caricare ed eseguire il modello con [ONNX
-Runtime](https://onnxruntime.ai/) come segue:
-
-```python
->>> from transformers import AutoTokenizer
->>> from onnxruntime import InferenceSession
-
->>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
->>> session = InferenceSession("onnx/model.onnx")
->>> # ONNX Runtime expects NumPy arrays as input
->>> inputs = tokenizer("Using DistilBERT with ONNX Runtime!", return_tensors="np")
->>> outputs = session.run(output_names=["last_hidden_state"], input_feed=dict(inputs))
-```
-
-I nomi di output richiesti (cioĂš `["last_hidden_state"]`) possono essere ottenuti
-dando un'occhiata alla configurazione ONNX di ogni modello. Ad esempio, per
-DistilBERT abbiamo:
-
-```python
->>> from transformers.models.distilbert import DistilBertConfig, DistilBertOnnxConfig
-
->>> config = DistilBertConfig()
->>> onnx_config = DistilBertOnnxConfig(config)
->>> print(list(onnx_config.outputs.keys()))
-["last_hidden_state"]
-```
-
-Il processo Ăš identico per i checkpoint TensorFlow sull'hub. Ad esempio, noi
-possiamo esportare un checkpoint TensorFlow puro da [Keras
-organizzazione](https://huggingface.co/keras-io) come segue:
-
-```bash
-python -m transformers.onnx --model=keras-io/transformers-qa onnx/
-```
-
-Per esportare un modello memorizzato localmente, devi disporre dei pesi del modello
-e file tokenizer memorizzati in una directory. Ad esempio, possiamo caricare e salvare un
-checkpoint come segue:
-
-
-
-```python
->>> from transformers import AutoTokenizer, AutoModelForSequenceClassification
-
->>> # Load tokenizer and PyTorch weights form the Hub
->>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
->>> pt_model = AutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased")
->>> # Save to disk
->>> tokenizer.save_pretrained("local-pt-checkpoint")
->>> pt_model.save_pretrained("local-pt-checkpoint")
-```
-
-Una volta salvato il checkpoint, possiamo esportarlo su ONNX puntando l'argomento `--model`
-del pacchetto `transformers.onnx` nella directory desiderata:
-
-```bash
-python -m transformers.onnx --model=local-pt-checkpoint onnx/
-```
-
-
-```python
->>> from transformers import AutoTokenizer, TFAutoModelForSequenceClassification
-
->>> # Load tokenizer and TensorFlow weights from the Hub
->>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
->>> tf_model = TFAutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased")
->>> # Save to disk
->>> tokenizer.save_pretrained("local-tf-checkpoint")
->>> tf_model.save_pretrained("local-tf-checkpoint")
-```
-
-Once the checkpoint is saved, we can export it to ONNX by pointing the `--model`
-argument of the `transformers.onnx` package to the desired directory:
-
-```bash
-python -m transformers.onnx --model=local-tf-checkpoint onnx/
-```
-
-
-
-### Selezione delle caratteristiche per diverse topologie di modello
-
-Ogni configurazione giĂ pronta viene fornita con una serie di _caratteristiche_ che ti consentono di
-esportare modelli per diversi tipi di topologie o attivitĂ . Come mostrato nella tabella
-di seguito, ogni caratteristica Ăš associata a una diversa Auto Class:
-
-| Caratteristica | Auto Class |
-| ------------------------------------ | ------------------------------------ |
-| `causal-lm`, `causal-lm-with-past` | `AutoModelForCausalLM` |
-| `default`, `default-with-past` | `AutoModel` |
-| `masked-lm` | `AutoModelForMaskedLM` |
-| `question-answering` | `AutoModelForQuestionAnswering` |
-| `seq2seq-lm`, `seq2seq-lm-with-past` | `AutoModelForSeq2SeqLM` |
-| `sequence-classification` | `AutoModelForSequenceClassification` |
-| `token-classification` | `AutoModelForTokenClassification` |
-
-Per ciascuna configurazione, puoi trovare l'elenco delle funzionalitĂ supportate tramite il
-`FeaturesManager`. Ad esempio, per DistilBERT abbiamo:
-
-```python
->>> from transformers.onnx.features import FeaturesManager
-
->>> distilbert_features = list(FeaturesManager.get_supported_features_for_model_type("distilbert").keys())
->>> print(distilbert_features)
-["default", "masked-lm", "causal-lm", "sequence-classification", "token-classification", "question-answering"]
-```
-
-Puoi quindi passare una di queste funzionalitĂ all'argomento `--feature` nel
-pacchetto `transformers.onnx`. Ad esempio, per esportare un modello di classificazione del testo
-possiamo scegliere un modello ottimizzato dall'Hub ed eseguire:
-
-```bash
-python -m transformers.onnx --model=distilbert-base-uncased-finetuned-sst-2-english \
- --feature=sequence-classification onnx/
-```
-
-che visualizzerĂ i seguenti registri:
-
-```bash
-Validating ONNX model...
- -[â] ONNX model output names match reference model ({'logits'})
- - Validating ONNX Model output "logits":
- -[â] (2, 2) matches (2, 2)
- -[â] all values close (atol: 1e-05)
-All good, model saved at: onnx/model.onnx
-```
-
-Puoi notare che in questo caso, i nomi di output del modello ottimizzato sono
-`logits` invece di `last_hidden_state` che abbiamo visto con il
-checkpoint `distilbert-base-uncased` precedente. Questo Ăš previsto dal
-modello ottimizato visto che ha una testa di e.
-
-
-
-Le caratteristiche che hanno un suffisso `wtih-past` (ad es. `causal-lm-with-past`)
-corrispondono a topologie di modello con stati nascosti precalcolati (chiave e valori
-nei blocchi di attenzione) che possono essere utilizzati per la decodifica autoregressiva veloce.
-
-
-
-
-### Esportazione di un modello per un'architettura non supportata
-
-Se desideri esportare un modello la cui architettura non Ăš nativamente supportata dalla
-libreria, ci sono tre passaggi principali da seguire:
-
-1. Implementare una configurazione ONNX personalizzata.
-2. Esportare il modello in ONNX.
-3. Convalidare gli output di PyTorch e dei modelli esportati.
-
-In questa sezione, vedremo come DistilBERT Ăš stato implementato per mostrare cosa Ăš
-coinvolto in ogni passaggio.
-
-#### Implementazione di una configurazione ONNX personalizzata
-
-Iniziamo con l'oggetto di configurazione ONNX. Forniamo tre classi
-astratte da cui ereditare, a seconda del tipo di archittettura
-del modello che desideri esportare:
-
-* I modelli basati su encoder ereditano da [`~onnx.config.OnnxConfig`]
-* I modelli basati su decoder ereditano da [`~onnx.config.OnnxConfigWithPast`]
-* I modelli encoder-decoder ereditano da[`~onnx.config.OnnxSeq2SeqConfigWithPast`]
-
-
-
-Un buon modo per implementare una configurazione ONNX personalizzata Ăš guardare l'implementazione
-esistente nel file `configuration_.py` di un'architettura simile.
-
-
-
-Poiché DistilBERT Ú un modello basato su encoder, la sua configurazione eredita da
-`OnnxConfig`:
-
-```python
->>> from typing import Mapping, OrderedDict
->>> from transformers.onnx import OnnxConfig
-
-
->>> class DistilBertOnnxConfig(OnnxConfig):
-... @property
-... def inputs(self) -> Mapping[str, Mapping[int, str]]:
-... return OrderedDict(
-... [
-... ("input_ids", {0: "batch", 1: "sequence"}),
-... ("attention_mask", {0: "batch", 1: "sequence"}),
-... ]
-... )
-```
-
-Ogni oggetto di configurazione deve implementare la proprietĂ `inputs` e restituire una
-mappatura, dove ogni chiave corrisponde a un input previsto e ogni valore
-indica l'asse di quell'input. Per DistilBERT, possiamo vedere che sono richiesti
-due input: `input_ids` e `attention_mask`. Questi inputs hanno la stessa forma di
-`(batch_size, sequence_length)` per questo motivo vediamo gli stessi assi usati nella
-configurazione.
-
-
-
-Puoi notare che la proprietĂ `inputs` per `DistilBertOnnxConfig` restituisce un
-`OrdinatoDict`. CiĂČ garantisce che gli input corrispondano alla loro posizione
-relativa all'interno del metodo `PreTrainedModel.forward()` durante il tracciamento del grafico.
-Raccomandiamo di usare un `OrderedDict` per le proprietĂ `inputs` e `outputs`
-quando si implementano configurazioni ONNX personalizzate.
-
-
-
-Dopo aver implementato una configurazione ONNX, Ăš possibile istanziarla
-fornendo alla configurazione del modello base come segue:
-
-```python
->>> from transformers import AutoConfig
-
->>> config = AutoConfig.from_pretrained("distilbert-base-uncased")
->>> onnx_config = DistilBertOnnxConfig(config)
-```
-
-L'oggetto risultante ha diverse proprietĂ utili. Ad esempio Ăš possibile visualizzare il
-Set operatore ONNX che verrĂ utilizzato durante l'esportazione:
-
-```python
->>> print(onnx_config.default_onnx_opset)
-11
-```
-
-Ă inoltre possibile visualizzare gli output associati al modello come segue:
-
-```python
->>> print(onnx_config.outputs)
-OrderedDict([("last_hidden_state", {0: "batch", 1: "sequence"})])
-```
-
-Puoi notare che la proprietĂ degli output segue la stessa struttura degli input; esso
-restituisce un `OrderedDict` di output con nome e le loro forme. La struttura di output
-Ăš legato alla scelta della funzione con cui viene inizializzata la configurazione.
-Per impostazione predefinita, la configurazione ONNX viene inizializzata con la funzione 'predefinita'
-che corrisponde all'esportazione di un modello caricato con la classe `AutoModel`. Se tu
-desideri esportare una topologia di modello diversa, Ăš sufficiente fornire una funzionalitĂ diversa a
-l'argomento `task` quando inizializzi la configurazione ONNX. Ad esempio, se
-volevamo esportare DistilBERT con una testa di classificazione per sequenze, potremmo
-usare:
-
-```python
->>> from transformers import AutoConfig
-
->>> config = AutoConfig.from_pretrained("distilbert-base-uncased")
->>> onnx_config_for_seq_clf = DistilBertOnnxConfig(config, task="sequence-classification")
->>> print(onnx_config_for_seq_clf.outputs)
-OrderedDict([('logits', {0: 'batch'})])
-```
-
-
-
-Tutte le proprietĂ e i metodi di base associati a [`~onnx.config.OnnxConfig`] e le
-altre classi di configurazione possono essere sovrascritte se necessario. Guarda
-[`BartOnnxConfig`] per un esempio avanzato.
-
-
-
-#### Esportazione del modello
-
-Una volta implementata la configurazione ONNX, il passaggio successivo consiste nell'esportare il
-modello. Qui possiamo usare la funzione `export()` fornita dal
-pacchetto `transformers.onnx`. Questa funzione prevede la configurazione ONNX, insieme
-con il modello base e il tokenizer e il percorso per salvare il file esportato:
-
-```python
->>> from pathlib import Path
->>> from transformers.onnx import export
->>> from transformers import AutoTokenizer, AutoModel
-
->>> onnx_path = Path("model.onnx")
->>> model_ckpt = "distilbert-base-uncased"
->>> base_model = AutoModel.from_pretrained(model_ckpt)
->>> tokenizer = AutoTokenizer.from_pretrained(model_ckpt)
-
->>> onnx_inputs, onnx_outputs = export(tokenizer, base_model, onnx_config, onnx_config.default_onnx_opset, onnx_path)
-```
-
-Gli `onnx_inputs` e `onnx_outputs` restituiti dalla funzione `export()` sono
-liste di chiavi definite nelle proprietĂ di `input` e `output` della
-configurazione. Una volta esportato il modello, puoi verificare che il modello sia ben
-formato come segue:
-
-```python
->>> import onnx
-
->>> onnx_model = onnx.load("model.onnx")
->>> onnx.checker.check_model(onnx_model)
-```
-
-
-
-Se il tuo modello Ăš piĂč largo di 2 GB, vedrai che molti file aggiuntivi sono
-creati durante l'esportazione. Questo Ú _previsto_ perché ONNX utilizza [Protocol
-Buffer](https://developers.google.com/protocol-buffers/) per memorizzare il modello e
-questi hanno un limite di dimensione 2 GB. Vedi la [Documentazione
-ONNX](https://github.com/onnx/onnx/blob/master/docs/ExternalData.md)
-per istruzioni su come caricare modelli con dati esterni.
-
-
-
-#### Convalida degli output del modello
-
-Il passaggio finale consiste nel convalidare gli output dal modello di base e quello esportato
-corrispondere entro una soglia di tolleranza assoluta. Qui possiamo usare la
-Funzione `validate_model_outputs()` fornita dal pacchetto `transformers.onnx`
-come segue:
-
-```python
->>> from transformers.onnx import validate_model_outputs
-
->>> validate_model_outputs(
-... onnx_config, tokenizer, base_model, onnx_path, onnx_outputs, onnx_config.atol_for_validation
-... )
-```
-
-Questa funzione usa il metodo `OnnxConfig.generate_dummy_inputs()` per generare
-input per il modello di base e quello esportato e la tolleranza assoluta puĂČ essere
-definita nella configurazione. Generalmente troviamo una corrispondenza numerica nell'intervallo da 1e-6
-a 1e-4, anche se Ăš probabile che qualsiasi cosa inferiore a 1e-3 vada bene.
-
-### Contribuire con una nuova configurazione a đ€ Transformers
-
-Stiamo cercando di espandere l'insieme di configurazioni giĂ pronte e di accettare
-contributi della community! Se vuoi contribuire con la tua aggiunta
-nella libreria, dovrai:
-
-* Implementare la configurazione ONNX nella corrispondente `configuration file
-_.py`
-* Includere l'architettura del modello e le funzioni corrispondenti in [`~onnx.features.FeatureManager`]
-* Aggiungere la tua architettura del modello ai test in `test_onnx_v2.py`
-
-Scopri come stato contribuito la configurazione per [IBERT]
-(https://github.com/huggingface/transformers/pull/14868/files) per
-avere un'idea di cosa Ăš coinvolto.
-
-## TorchScript
-
-
-
-Questo Ăš l'inizio dei nostri esperimenti con TorchScript e stiamo ancora esplorando le sue capacitĂ con
-modelli con variable-input-size. Ă una nostra prioritĂ e approfondiremo le nostre analisi nelle prossime versioni,
-con piĂč esempi di codici, un'implementazione piĂč flessibile e benchmark che confrontano i codici basati su Python con quelli compilati con
-TorchScript.
-
-
-
-Secondo la documentazione di Pytorch: "TorchScript Ăš un modo per creare modelli serializzabili e ottimizzabili da codice
-Pytorch". I due moduli di Pytorch [JIT e TRACE](https://pytorch.org/docs/stable/jit.html) consentono allo sviluppatore di esportare
-il loro modello da riutilizzare in altri programmi, come i programmi C++ orientati all'efficienza.
-
-Abbiamo fornito un'interfaccia che consente l'esportazione di modelli đ€ Transformers in TorchScript in modo che possano essere riutilizzati
-in un ambiente diverso rispetto a un programma Python basato su Pytorch. Qui spieghiamo come esportare e utilizzare i nostri modelli utilizzando
-TorchScript.
-
-Esportare un modello richiede due cose:
-
-- Un passaggio in avanti con input fittizzi.
-- Istanziazione del modello con flag `torchscript`.
-
-Queste necessitĂ implicano diverse cose a cui gli sviluppatori dovrebbero prestare attenzione. Questi dettagli mostrati sotto.
-
-### Flag TorchScript e pesi legati
-
-Questo flag Ú necessario perché la maggior parte dei modelli linguistici in questo repository hanno pesi legati tra il loro
-strato "Embedding" e lo strato "Decoding". TorchScript non consente l'esportazione di modelli che hanno pesi
-legati, quindi Ăš necessario prima slegare e clonare i pesi.
-
-CiĂČ implica che i modelli istanziati con il flag `torchscript` hanno il loro strato `Embedding` e strato `Decoding`
-separato, il che significa che non dovrebbero essere addestrati in futuro. L'allenamento de-sincronizza i due
-strati, portando a risultati inaspettati.
-
-Questo non Ú il caso per i modelli che non hanno una testa del modello linguistico, poiché quelli non hanno pesi legati. Questi modelli
-puĂČ essere esportato in sicurezza senza il flag `torchscript`.
-
-### Input fittizi e standard lengths
-
-Gli input fittizzi sono usati per fare un modello passaggio in avanti . Mentre i valori degli input si propagano attraverso i strati,
-Pytorch tiene traccia delle diverse operazioni eseguite su ciascun tensore. Queste operazioni registrate vengono quindi utilizzate per
-creare la "traccia" del modello.
-
-La traccia viene creata relativamente alle dimensioni degli input. Ă quindi vincolato dalle dimensioni dell'input
-fittizio e non funzionerĂ per altre lunghezze di sequenza o dimensioni batch. Quando si proverĂ con una dimensione diversa, ci sarĂ errore
-come:
-
-`La dimensione espansa del tensore (3) deve corrispondere alla dimensione esistente (7) nella dimensione non singleton 2`
-
-will be raised. Si consiglia pertanto di tracciare il modello con una dimensione di input fittizia grande almeno quanto il piĂč grande
-input che verrĂ fornito al modello durante l'inferenza. Ă possibile eseguire il padding per riempire i valori mancanti. Il modello
-sarĂ tracciato con una grande dimensione di input, tuttavia, anche le dimensioni della diverse matrici saranno grandi,
-risultando in piĂč calcoli.
-
-Si raccomanda di prestare attenzione al numero totale di operazioni eseguite su ciascun input e di seguire da vicino le prestazioni
-durante l'esportazione di modelli di sequenza-lunghezza variabili.
-
-### Usare TorchSscript in Python
-
-Di seguito Ăš riportato un esempio, che mostra come salvare, caricare modelli e come utilizzare la traccia per l'inferenza.
-
-#### Salvare un modello
-
-Questo frammento di codice mostra come usare TorchScript per esportare un `BertModel`. Qui il `BertModel` Ăš istanziato secondo
-una classe `BertConfig` e quindi salvato su disco con il nome del file `traced_bert.pt`
-
-```python
-from transformers import BertModel, BertTokenizer, BertConfig
-import torch
-
-enc = BertTokenizer.from_pretrained("bert-base-uncased")
-
-# Tokenizing input text
-text = "[CLS] Who was Jim Henson ? [SEP] Jim Henson was a puppeteer [SEP]"
-tokenized_text = enc.tokenize(text)
-
-# Masking one of the input tokens
-masked_index = 8
-tokenized_text[masked_index] = "[MASK]"
-indexed_tokens = enc.convert_tokens_to_ids(tokenized_text)
-segments_ids = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1]
-
-# Creating a dummy input
-tokens_tensor = torch.tensor([indexed_tokens])
-segments_tensors = torch.tensor([segments_ids])
-dummy_input = [tokens_tensor, segments_tensors]
-
-# Initializing the model with the torchscript flag
-# Flag set to True even though it is not necessary as this model does not have an LM Head.
-config = BertConfig(
- vocab_size_or_config_json_file=32000,
- hidden_size=768,
- num_hidden_layers=12,
- num_attention_heads=12,
- intermediate_size=3072,
- torchscript=True,
-)
-
-# Instantiating the model
-model = BertModel(config)
-
-# The model needs to be in evaluation mode
-model.eval()
-
-# If you are instantiating the model with *from_pretrained* you can also easily set the TorchScript flag
-model = BertModel.from_pretrained("bert-base-uncased", torchscript=True)
-
-# Creating the trace
-traced_model = torch.jit.trace(model, [tokens_tensor, segments_tensors])
-torch.jit.save(traced_model, "traced_bert.pt")
-```
-
-#### Caricare un modello
-
-Questo frammento di codice mostra come caricare il `BertModel` che era stato precedentemente salvato su disco con il nome `traced_bert.pt`.
-Stiamo riutilizzando il `dummy_input` precedentemente inizializzato.
-
-```python
-loaded_model = torch.jit.load("traced_bert.pt")
-loaded_model.eval()
-
-all_encoder_layers, pooled_output = loaded_model(*dummy_input)
-```
-
-#### Utilizzare un modello tracciato per l'inferenza
-
-Usare il modello tracciato per l'inferenza Ăš semplice come usare il suo metodo dunder `__call__`:
-
-```python
-traced_model(tokens_tensor, segments_tensors)
-```
-
-###Implementare modelli HuggingFace TorchScript su AWS utilizzando Neuron SDK
-
-AWS ha introdotto [Amazon EC2 Inf1](https://aws.amazon.com/ec2/instance-types/inf1/)
-famiglia di istanze per l'inferenza di machine learning a basso costo e ad alte prestazioni nel cloud.
-Le istanze Inf1 sono alimentate dal chip AWS Inferentia, un acceleratore hardware personalizzato,
-specializzato in carichi di lavoro di inferenza di deep learning.
-[AWS Neuron](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/#)
-Ăš l'SDK per Inferentia che supporta il tracciamento e l'ottimizzazione dei modelli transformers per
-distribuzione su Inf1. L'SDK Neuron fornisce:
-
-
-1. API di facile utilizzo con una riga di modifica del codice per tracciare e ottimizzare un modello TorchScript per l'inferenza nel cloud.
-2. Ottimizzazioni delle prestazioni pronte all'uso per [miglioramento dei costi-prestazioni](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/neuron-guide/benchmark/>)
-3. Supporto per i modelli di trasformatori HuggingFace costruiti con [PyTorch](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/src/examples/pytorch/bert_tutorial/tutorial_pretrained_bert.html)
- o [TensorFlow](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/src/examples/tensorflow/huggingface_bert/huggingface_bert.html).
-
-#### Implicazioni
-
-Modelli Transformers basati su architettura [BERT (Bidirectional Encoder Representations from Transformers)](https://huggingface.co/docs/transformers/main/model_doc/bert),
-o sue varianti come [distilBERT](https://huggingface.co/docs/transformers/main/model_doc/distilbert)
-e [roBERTa](https://huggingface.co/docs/transformers/main/model_doc/roberta)
-funzioneranno meglio su Inf1 per attivitĂ non generative come la question answering estrattive,
-Classificazione della sequenza, Classificazione dei token. In alternativa, generazione di testo
-le attivitĂ possono essere adattate per essere eseguite su Inf1, secondo questo [tutorial AWS Neuron MarianMT](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/src/examples/pytorch/transformers-marianmt.html).
-Ulteriori informazioni sui modelli che possono essere convertiti fuori dagli schemi su Inferentia possono essere
-trovati nella [sezione Model Architecture Fit della documentazione Neuron](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/neuron-guide/models/models-inferentia.html#models-inferentia).
-
-#### Dipendenze
-
-L'utilizzo di AWS Neuron per convertire i modelli richiede le seguenti dipendenze e l'ambiente:
-
-* A [Neuron SDK environment](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/neuron-guide/neuron-frameworks/pytorch-neuron/index.html#installation-guide),
- which comes pre-configured on [AWS Deep Learning AMI](https://docs.aws.amazon.com/dlami/latest/devguide/tutorial-inferentia-launching.html).
-
-#### Convertire un modello per AWS Neuron
-
-Usando lo stesso script come in [Usando TorchScipt in Python](https://huggingface.co/docs/transformers/main/en/serialization#using-torchscript-in-python)
-per tracciare un "BertModel", importi l'estensione del framework `torch.neuron` per accedere
-i componenti di Neuron SDK tramite un'API Python.
-
-```python
-from transformers import BertModel, BertTokenizer, BertConfig
-import torch
-import torch.neuron
-```
-E modificare solo la riga di codice di traccia
-
-Da:
-
-```python
-torch.jit.trace(model, [tokens_tensor, segments_tensors])
-```
-
-A:
-
-```python
-torch.neuron.trace(model, [token_tensor, segments_tensors])
-```
-
-Questa modifica consente a Neuron SDK di tracciare il modello e ottimizzarlo per l'esecuzione nelle istanze Inf1.
-
-Per ulteriori informazioni sulle funzionalitĂ , gli strumenti, i tutorial di esempi e gli ultimi aggiornamenti di AWS Neuron SDK,
-consultare la [documentazione AWS NeuronSDK](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/index.html).
\ No newline at end of file
diff --git a/docs/source/it/training.md b/docs/source/it/training.md
new file mode 100644
index 000000000000..be0883f07b77
--- /dev/null
+++ b/docs/source/it/training.md
@@ -0,0 +1,376 @@
+
+
+# Fine-tuning di un modello pre-addestrato
+
+[[open-in-colab]]
+
+Ci sono benefici significativi nell'usare un modello pre-addestrato. Si riducono i costi computazionali, l'impronta di carbonio e ti consente di usare modelli stato dell'arte senza doverli addestrare da zero. đ€ Transformers consente l'accesso a migliaia di modelli pre-addestrati per un'ampia gamma di compiti. Quando usi un modello pre-addestrato, lo alleni su un dataset specifico per il tuo compito. Questo Ăš conosciuto come fine-tuning, una tecnica di addestramento incredibilmente potente. In questa esercitazione, potrai fare il fine-tuning di un modello pre-addestrato, con un framework di deep learning a tua scelta:
+
+* Fine-tuning di un modello pre-addestrato con đ€ Transformers [`Trainer`].
+* Fine-tuning di un modello pre-addestrato in TensorFlow con Keras.
+* Fine-tuning di un modello pre-addestrato con PyTorch.
+
+
+
+## Preparare un dataset
+
+
+
+Prima di poter fare il fine-tuning di un modello pre-addestrato, scarica un dataset e preparalo per l'addestramento. La precedente esercitazione ti ha mostrato come processare i dati per l'addestramento e adesso hai l'opportunitĂ di metterti alla prova!
+
+Inizia caricando il dataset [Yelp Reviews](https://huggingface.co/datasets/yelp_review_full):
+
+```py
+>>> from datasets import load_dataset
+
+>>> dataset = load_dataset("yelp_review_full")
+>>> dataset["train"][100]
+{'label': 0,
+ '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!'}
+```
+
+Come giĂ sai, hai bisogno di un tokenizer per processare il testo e includere una strategia di padding e truncation per gestire sequenze di lunghezza variabile. Per processare il dataset in un unico passo, usa il metodo [`map`](https://huggingface.co/docs/datasets/process.html#map) di đ€ Datasets che applica la funzione di preprocessing all'intero dataset:
+
+```py
+>>> from transformers import AutoTokenizer
+
+>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
+
+
+>>> def tokenize_function(examples):
+... return tokenizer(examples["text"], padding="max_length", truncation=True)
+
+
+>>> tokenized_datasets = dataset.map(tokenize_function, batched=True)
+```
+
+Se vuoi, puoi creare un sottoinsieme piĂč piccolo del dataset per il fine-tuning cosĂŹ da ridurre il tempo necessario:
+
+```py
+>>> small_train_dataset = tokenized_datasets["train"].shuffle(seed=42).select(range(1000))
+>>> small_eval_dataset = tokenized_datasets["test"].shuffle(seed=42).select(range(1000))
+```
+
+
+
+## Addestramento
+
+
+
+
+
+đ€ Transformers mette a disposizione la classe [`Trainer`] ottimizzata per addestrare modelli đ€ Transformers, rendendo semplice iniziare l'addestramento senza scrivere manualmente il tuo ciclo di addestramento. L'API [`Trainer`] supporta un'ampia gamma di opzioni e funzionalitĂ di addestramento come logging, gradient accumulation e mixed precision.
+
+Inizia caricando il tuo modello e specificando il numero di etichette (labels) attese. Nel dataset Yelp Review [dataset card](https://huggingface.co/datasets/yelp_review_full#data-fields), sai che ci sono cinque etichette:
+
+```py
+>>> from transformers import AutoModelForSequenceClassification
+
+>>> model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=5)
+```
+
+
+
+Potresti vedere un warning dato che alcuni dei pesi pre-addestrati non sono stati utilizzati e altri pesi sono stati inizializzati casualmente. Non preoccuparti, Ăš completamente normale! L'head pre-addestrata del modello BERT viene scartata e rimpiazzata da una classification head inizializzata casualmente. Farai il fine-tuning di questa nuova head del modello sul tuo compito di classificazione, trasferendogli la conoscenza del modello pre-addestrato.
+
+
+
+### Iperparametri per il training
+
+Successivamente, crea una classe [`TrainingArguments`] contenente tutti gli iperparametri che si possono regore nonché le variabili per attivare le differenti opzioni di addestramento. Per questa esercitazione puoi iniziare con gli [iperparametri](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments) di ddestramento predefiniti, ma sentiti libero di sperimentare per trovare la configurazione ottimale per te.
+
+Specifica dove salvare i checkpoints del tuo addestramento:
+
+```py
+>>> from transformers import TrainingArguments
+
+>>> training_args = TrainingArguments(output_dir="test_trainer")
+```
+
+### Metriche
+
+[`Trainer`] non valuta automaticamente le performance del modello durante l'addestramento. Dovrai passare a [`Trainer`] una funzione che calcola e restituisce le metriche. La libreria đ€ Datasets mette a disposizione una semplice funzione [`accuracy`](https://huggingface.co/metrics/accuracy) che puoi caricare con la funzione `load_metric` (guarda questa [esercitazione](https://huggingface.co/docs/datasets/metrics.html) per maggiori informazioni):
+
+```py
+>>> import numpy as np
+>>> from datasets import load_metric
+
+>>> metric = load_metric("accuracy")
+```
+
+Richiama `compute` su `metric` per calcolare l'accuratezza delle tue previsioni. Prima di passare le tue previsioni a `compute`, hai bisogno di convertirle in logits (ricorda che tutti i modelli đ€ Transformers restituiscono logits):
+
+```py
+>>> def compute_metrics(eval_pred):
+... logits, labels = eval_pred
+... predictions = np.argmax(logits, axis=-1)
+... return metric.compute(predictions=predictions, references=labels)
+```
+
+Se preferisci monitorare le tue metriche di valutazione durante il fine-tuning, specifica il parametro `evaluation_strategy` nei tuoi training arguments per restituire le metriche di valutazione ad ogni epoca di addestramento:
+
+```py
+>>> from transformers import TrainingArguments, Trainer
+
+>>> training_args = TrainingArguments(output_dir="test_trainer", evaluation_strategy="epoch")
+```
+
+### Trainer
+
+Crea un oggetto [`Trainer`] col tuo modello, training arguments, dataset di training e test, e funzione di valutazione:
+
+```py
+>>> trainer = Trainer(
+... model=model,
+... args=training_args,
+... train_dataset=small_train_dataset,
+... eval_dataset=small_eval_dataset,
+... compute_metrics=compute_metrics,
+... )
+```
+
+Poi metti a punto il modello richiamando [`~transformers.Trainer.train`]:
+
+```py
+>>> trainer.train()
+```
+
+
+
+
+
+
+I modelli đ€ Transformers supportano anche l'addestramento in TensorFlow usando l'API di Keras.
+
+### Convertire dataset nel formato per TensorFlow
+
+Il [`DefaultDataCollator`] assembla tensori in lotti su cui il modello si addestrerĂ . Assicurati di specificare di restituire tensori per TensorFlow in `return_tensors`:
+
+```py
+>>> from transformers import DefaultDataCollator
+
+>>> data_collator = DefaultDataCollator(return_tensors="tf")
+```
+
+
+
+[`Trainer`] usa [`DataCollatorWithPadding`] in maniera predefinita in modo da non dover specificare esplicitamente un collettore di dati.
+
+
+
+Successivamente, converti i datasets tokenizzati in TensorFlow datasets con il metodo [`to_tf_dataset`](https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.to_tf_dataset). Specifica il tuo input in `columns` e le tue etichette in `label_cols`:
+
+```py
+>>> tf_train_dataset = small_train_dataset.to_tf_dataset(
+... columns=["attention_mask", "input_ids", "token_type_ids"],
+... label_cols=["labels"],
+... shuffle=True,
+... collate_fn=data_collator,
+... batch_size=8,
+... )
+
+>>> tf_validation_dataset = small_eval_dataset.to_tf_dataset(
+... columns=["attention_mask", "input_ids", "token_type_ids"],
+... label_cols=["labels"],
+... shuffle=False,
+... collate_fn=data_collator,
+... batch_size=8,
+... )
+```
+
+### Compilazione e addestramento
+
+Carica un modello TensorFlow col numero atteso di etichette:
+
+```py
+>>> import tensorflow as tf
+>>> from transformers import TFAutoModelForSequenceClassification
+
+>>> model = TFAutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=5)
+```
+
+Poi compila e fai il fine-tuning del tuo modello usando [`fit`](https://keras.io/api/models/model_training_apis/) come faresti con qualsiasi altro modello di Keras:
+
+```py
+>>> model.compile(
+... optimizer=tf.keras.optimizers.Adam(learning_rate=5e-5),
+... loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
+... metrics=tf.metrics.SparseCategoricalAccuracy(),
+... )
+
+>>> model.fit(tf_train_dataset, validation_data=tf_validation_dataset, epochs=3)
+```
+
+
+
+
+
+## Addestramento in PyTorch nativo
+
+
+
+
+
+[`Trainer`] si occupa del ciclo di addestramento e ti consente di mettere a punto un modello con una sola riga di codice. Per chi preferisse scrivere un proprio ciclo di addestramento personale, puoi anche fare il fine-tuning di un modello đ€ Transformers in PyTorch nativo.
+
+A questo punto, potresti avere bisogno di riavviare il tuo notebook o eseguire il seguente codice per liberare un po' di memoria:
+
+```py
+del model
+del pytorch_model
+del trainer
+torch.cuda.empty_cache()
+```
+
+Successivamente, postprocessa manualmente il `tokenized_dataset` per prepararlo ad essere allenato.
+
+1. Rimuovi la colonna `text` perché il modello non accetta testo grezzo come input:
+
+ ```py
+ >>> tokenized_datasets = tokenized_datasets.remove_columns(["text"])
+ ```
+
+2. Rinomina la colonna `label` in `labels` perché il modello si aspetta che questo argomento si chiami `labels`:
+
+ ```py
+ >>> tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
+ ```
+
+3. Imposta il formato del dataset per farti restituire tensori di PyTorch all'interno delle liste:
+
+ ```py
+ >>> tokenized_datasets.set_format("torch")
+ ```
+
+Poi crea un piccolo sottocampione del dataset come visto precedentemente per velocizzare il fine-tuning:
+
+```py
+>>> small_train_dataset = tokenized_datasets["train"].shuffle(seed=42).select(range(1000))
+>>> small_eval_dataset = tokenized_datasets["test"].shuffle(seed=42).select(range(1000))
+```
+
+### DataLoader
+
+Crea un `DataLoader` per i tuoi datasets di train e test cosĂŹ puoi iterare sui lotti di dati:
+
+```py
+>>> from torch.utils.data import DataLoader
+
+>>> train_dataloader = DataLoader(small_train_dataset, shuffle=True, batch_size=8)
+>>> eval_dataloader = DataLoader(small_eval_dataset, batch_size=8)
+```
+
+Carica il tuo modello con il numero atteso di etichette:
+
+```py
+>>> from transformers import AutoModelForSequenceClassification
+
+>>> model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=5)
+```
+
+### Ottimizzatore e learning rate scheduler
+
+Crea un ottimizzatore e il learning rate scheduler per fare il fine-tuning del modello. Usa l'ottimizzatore [`AdamW`](https://pytorch.org/docs/stable/generated/torch.optim.AdamW.html) di PyTorch:
+
+```py
+>>> from torch.optim import AdamW
+
+>>> optimizer = AdamW(model.parameters(), lr=5e-5)
+```
+
+Crea il learning rate scheduler predefinito da [`Trainer`]:
+
+```py
+>>> from transformers import get_scheduler
+
+>>> num_epochs = 3
+>>> num_training_steps = num_epochs * len(train_dataloader)
+>>> lr_scheduler = get_scheduler(
+... name="linear", optimizer=optimizer, num_warmup_steps=0, num_training_steps=num_training_steps
+... )
+```
+
+Infine specifica come `device` da usare una GPU se ne hai una. Altrimenti, l'addestramento su una CPU puĂČ richiedere diverse ore invece di un paio di minuti.
+
+```py
+>>> import torch
+
+>>> device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
+>>> model.to(device)
+```
+
+
+
+Ottieni l'accesso gratuito a una GPU sul cloud se non ne possiedi una usando un notebook sul web come [Colaboratory](https://colab.research.google.com/) o [SageMaker StudioLab](https://studiolab.sagemaker.aws/).
+
+
+
+Ottimo, adesso possiamo addestrare! đ„ł
+
+### Training loop
+
+Per tenere traccia dei tuoi progressi durante l'addestramento, usa la libreria [tqdm](https://tqdm.github.io/) per aggiungere una progress bar sopra il numero dei passi di addestramento:
+
+```py
+>>> from tqdm.auto import tqdm
+
+>>> progress_bar = tqdm(range(num_training_steps))
+
+>>> model.train()
+>>> for epoch in range(num_epochs):
+... for batch in train_dataloader:
+... batch = {k: v.to(device) for k, v in batch.items()}
+... outputs = model(**batch)
+... loss = outputs.loss
+... loss.backward()
+
+... optimizer.step()
+... lr_scheduler.step()
+... optimizer.zero_grad()
+... progress_bar.update(1)
+```
+
+### Metriche
+
+Proprio come Ăš necessario aggiungere una funzione di valutazione del [`Trainer`], Ăš necessario fare lo stesso quando si scrive il proprio ciclo di addestramento. Ma invece di calcolare e riportare la metrica alla fine di ogni epoca, questa volta accumulerai tutti i batch con [`add_batch`](https://huggingface.co/docs/datasets/package_reference/main_classes.html?highlight=add_batch#datasets.Metric.add_batch) e calcolerai la metrica alla fine.
+
+```py
+>>> metric = load_metric("accuracy")
+>>> model.eval()
+>>> for batch in eval_dataloader:
+... batch = {k: v.to(device) for k, v in batch.items()}
+... with torch.no_grad():
+... outputs = model(**batch)
+
+... logits = outputs.logits
+... predictions = torch.argmax(logits, dim=-1)
+... metric.add_batch(predictions=predictions, references=batch["labels"])
+
+>>> metric.compute()
+```
+
+
+
+
+
+## Altre risorse
+
+Per altri esempi sul fine-tuning, fai riferimento a:
+
+- [đ€ Transformers Examples](https://github.com/huggingface/transformers/tree/main/examples) include scripts per addestrare compiti comuni di NLP in PyTorch e TensorFlow.
+
+- [đ€ Transformers Notebooks](notebooks) contiene diversi notebooks su come mettere a punto un modello per compiti specifici in PyTorch e TensorFlow.
diff --git a/docs/source/it/training.mdx b/docs/source/it/training.mdx
deleted file mode 100644
index 68f6434bbb5a..000000000000
--- a/docs/source/it/training.mdx
+++ /dev/null
@@ -1,372 +0,0 @@
-
-
-# Fine-tuning di un modello pre-addestrato
-
-[[open-in-colab]]
-
-Ci sono benefici significativi nell'usare un modello pre-addestrato. Si riducono i costi computazionali, l'impronta di carbonio e ti consente di usare modelli stato dell'arte senza doverli addestrare da zero. đ€ Transformers consente l'accesso a migliaia di modelli pre-addestrati per un'ampia gamma di compiti. Quando usi un modello pre-addestrato, lo alleni su un dataset specifico per il tuo compito. Questo Ăš conosciuto come fine-tuning, una tecnica di addestramento incredibilmente potente. In questa esercitazione, potrai fare il fine-tuning di un modello pre-addestrato, con un framework di deep learning a tua scelta:
-
-* Fine-tuning di un modello pre-addestrato con đ€ Transformers [`Trainer`].
-* Fine-tuning di un modello pre-addestrato in TensorFlow con Keras.
-* Fine-tuning di un modello pre-addestrato con PyTorch.
-
-
-
-## Preparare un dataset
-
-
-
-Prima di poter fare il fine-tuning di un modello pre-addestrato, scarica un dataset e preparalo per l'addestramento. La precedente esercitazione ti ha mostrato come processare i dati per l'addestramento e adesso hai l'opportunitĂ di metterti alla prova!
-
-Inizia caricando il dataset [Yelp Reviews](https://huggingface.co/datasets/yelp_review_full):
-
-```py
->>> from datasets import load_dataset
-
->>> dataset = load_dataset("yelp_review_full")
->>> dataset["train"][100]
-{'label': 0,
- '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!'}
-```
-
-Come giĂ sai, hai bisogno di un tokenizer per processare il testo e includere una strategia di padding e truncation per gestire sequenze di lunghezza variabile. Per processare il dataset in un unico passo, usa il metodo [`map`](https://huggingface.co/docs/datasets/process.html#map) di đ€ Datasets che applica la funzione di preprocessing all'intero dataset:
-
-```py
->>> from transformers import AutoTokenizer
-
->>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
-
-
->>> def tokenize_function(examples):
-... return tokenizer(examples["text"], padding="max_length", truncation=True)
-
-
->>> tokenized_datasets = dataset.map(tokenize_function, batched=True)
-```
-
-Se vuoi, puoi creare un sottoinsieme piĂč piccolo del dataset per il fine-tuning cosĂŹ da ridurre il tempo necessario:
-
-```py
->>> small_train_dataset = tokenized_datasets["train"].shuffle(seed=42).select(range(1000))
->>> small_eval_dataset = tokenized_datasets["test"].shuffle(seed=42).select(range(1000))
-```
-
-
-
-## Addestramento
-
-
-
-
-
-đ€ Transformers mette a disposizione la classe [`Trainer`] ottimizzata per addestrare modelli đ€ Transformers, rendendo semplice iniziare l'addestramento senza scrivere manualmente il tuo ciclo di addestramento. L'API [`Trainer`] supporta un'ampia gamma di opzioni e funzionalitĂ di addestramento come logging, gradient accumulation e mixed precision.
-
-Inizia caricando il tuo modello e specificando il numero di etichette (labels) attese. Nel dataset Yelp Review [dataset card](https://huggingface.co/datasets/yelp_review_full#data-fields), sai che ci sono cinque etichette:
-
-```py
->>> from transformers import AutoModelForSequenceClassification
-
->>> model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=5)
-```
-
-
-
-Potresti vedere un warning dato che alcuni dei pesi pre-addestrati non sono stati utilizzati e altri pesi sono stati inizializzati casualmente. Non preoccuparti, Ăš completamente normale! L'head pre-addestrata del modello BERT viene scartata e rimpiazzata da una classification head inizializzata casualmente. Farai il fine-tuning di questa nuova head del modello sul tuo compito di classificazione, trasferendogli la conoscenza del modello pre-addestrato.
-
-
-
-### Iperparametri per il training
-
-Successivamente, crea una classe [`TrainingArguments`] contenente tutti gli iperparametri che si possono regore nonché le variabili per attivare le differenti opzioni di addestramento. Per questa esercitazione puoi iniziare con gli [iperparametri](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments) di ddestramento predefiniti, ma sentiti libero di sperimentare per trovare la configurazione ottimale per te.
-
-Specifica dove salvare i checkpoints del tuo addestramento:
-
-```py
->>> from transformers import TrainingArguments
-
->>> training_args = TrainingArguments(output_dir="test_trainer")
-```
-
-### Metriche
-
-[`Trainer`] non valuta automaticamente le performance del modello durante l'addestramento. Dovrai passare a [`Trainer`] una funzione che calcola e restituisce le metriche. La libreria đ€ Datasets mette a disposizione una semplice funzione [`accuracy`](https://huggingface.co/metrics/accuracy) che puoi caricare con la funzione `load_metric` (guarda questa [esercitazione](https://huggingface.co/docs/datasets/metrics.html) per maggiori informazioni):
-
-```py
->>> import numpy as np
->>> from datasets import load_metric
-
->>> metric = load_metric("accuracy")
-```
-
-Richiama `compute` su `metric` per calcolare l'accuratezza delle tue previsioni. Prima di passare le tue previsioni a `compute`, hai bisogno di convertirle in logits (ricorda che tutti i modelli đ€ Transformers restituiscono logits):
-
-```py
->>> def compute_metrics(eval_pred):
-... logits, labels = eval_pred
-... predictions = np.argmax(logits, axis=-1)
-... return metric.compute(predictions=predictions, references=labels)
-```
-
-Se preferisci monitorare le tue metriche di valutazione durante il fine-tuning, specifica il parametro `evaluation_strategy` nei tuoi training arguments per restituire le metriche di valutazione ad ogni epoca di addestramento:
-
-```py
->>> from transformers import TrainingArguments, Trainer
-
->>> training_args = TrainingArguments(output_dir="test_trainer", evaluation_strategy="epoch")
-```
-
-### Trainer
-
-Crea un oggetto [`Trainer`] col tuo modello, training arguments, dataset di training e test, e funzione di valutazione:
-
-```py
->>> trainer = Trainer(
-... model=model,
-... args=training_args,
-... train_dataset=small_train_dataset,
-... eval_dataset=small_eval_dataset,
-... compute_metrics=compute_metrics,
-... )
-```
-
-Poi metti a punto il modello richiamando [`~transformers.Trainer.train`]:
-
-```py
->>> trainer.train()
-```
-
-
-
-
-
-
-I modelli đ€ Transformers supportano anche l'addestramento in TensorFlow usando l'API di Keras.
-
-### Convertire dataset nel formato per TensorFlow
-
-Il [`DefaultDataCollator`] assembla tensori in lotti su cui il modello si addestrerĂ . Assicurati di specificare di restituire tensori per TensorFlow in `return_tensors`:
-
-```py
->>> from transformers import DefaultDataCollator
-
->>> data_collator = DefaultDataCollator(return_tensors="tf")
-```
-
-
-
-[`Trainer`] usa [`DataCollatorWithPadding`] in maniera predefinita in modo da non dover specificare esplicitamente un collettore di dati.
-
-
-
-Successivamente, converti i datasets tokenizzati in TensorFlow datasets con il metodo [`to_tf_dataset`](https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.to_tf_dataset). Specifica il tuo input in `columns` e le tue etichette in `label_cols`:
-
-```py
->>> tf_train_dataset = small_train_dataset.to_tf_dataset(
-... columns=["attention_mask", "input_ids", "token_type_ids"],
-... label_cols=["labels"],
-... shuffle=True,
-... collate_fn=data_collator,
-... batch_size=8,
-... )
-
->>> tf_validation_dataset = small_eval_dataset.to_tf_dataset(
-... columns=["attention_mask", "input_ids", "token_type_ids"],
-... label_cols=["labels"],
-... shuffle=False,
-... collate_fn=data_collator,
-... batch_size=8,
-... )
-```
-
-### Compilazione e addestramento
-
-Carica un modello TensorFlow col numero atteso di etichette:
-
-```py
->>> import tensorflow as tf
->>> from transformers import TFAutoModelForSequenceClassification
-
->>> model = TFAutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=5)
-```
-
-Poi compila e fai il fine-tuning del tuo modello usando [`fit`](https://keras.io/api/models/model_training_apis/) come faresti con qualsiasi altro modello di Keras:
-
-```py
->>> model.compile(
-... optimizer=tf.keras.optimizers.Adam(learning_rate=5e-5),
-... loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
-... metrics=tf.metrics.SparseCategoricalAccuracy(),
-... )
-
->>> model.fit(tf_train_dataset, validation_data=tf_validation_dataset, epochs=3)
-```
-
-
-
-
-
-## Addestramento in PyTorch nativo
-
-
-
-
-
-[`Trainer`] si occupa del ciclo di addestramento e ti consente di mettere a punto un modello con una sola riga di codice. Per chi preferisse scrivere un proprio ciclo di addestramento personale, puoi anche fare il fine-tuning di un modello đ€ Transformers in PyTorch nativo.
-
-A questo punto, potresti avere bisogno di riavviare il tuo notebook o eseguire il seguente codice per liberare un po' di memoria:
-
-```py
-del model
-del pytorch_model
-del trainer
-torch.cuda.empty_cache()
-```
-
-Successivamente, postprocessa manualmente il `tokenized_dataset` per prepararlo ad essere allenato.
-
-1. Rimuovi la colonna `text` perché il modello non accetta testo grezzo come input:
-
- ```py
- >>> tokenized_datasets = tokenized_datasets.remove_columns(["text"])
- ```
-
-2. Rinomina la colonna `label` in `labels` perché il modello si aspetta che questo argomento si chiami `labels`:
-
- ```py
- >>> tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
- ```
-
-3. Imposta il formato del dataset per farti restituire tensori di PyTorch all'interno delle liste:
-
- ```py
- >>> tokenized_datasets.set_format("torch")
- ```
-
-Poi crea un piccolo sottocampione del dataset come visto precedentemente per velocizzare il fine-tuning:
-
-```py
->>> small_train_dataset = tokenized_datasets["train"].shuffle(seed=42).select(range(1000))
->>> small_eval_dataset = tokenized_datasets["test"].shuffle(seed=42).select(range(1000))
-```
-
-### DataLoader
-
-Crea un `DataLoader` per i tuoi datasets di train e test cosĂŹ puoi iterare sui lotti di dati:
-
-```py
->>> from torch.utils.data import DataLoader
-
->>> train_dataloader = DataLoader(small_train_dataset, shuffle=True, batch_size=8)
->>> eval_dataloader = DataLoader(small_eval_dataset, batch_size=8)
-```
-
-Carica il tuo modello con il numero atteso di etichette:
-
-```py
->>> from transformers import AutoModelForSequenceClassification
-
->>> model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=5)
-```
-
-### Ottimizzatore e learning rate scheduler
-
-Crea un ottimizzatore e il learning rate scheduler per fare il fine-tuning del modello. Usa l'ottimizzatore [`AdamW`](https://pytorch.org/docs/stable/generated/torch.optim.AdamW.html) di PyTorch:
-
-```py
->>> from torch.optim import AdamW
-
->>> optimizer = AdamW(model.parameters(), lr=5e-5)
-```
-
-Crea il learning rate scheduler predefinito da [`Trainer`]:
-
-```py
->>> from transformers import get_scheduler
-
->>> num_epochs = 3
->>> num_training_steps = num_epochs * len(train_dataloader)
->>> lr_scheduler = get_scheduler(
-... name="linear", optimizer=optimizer, num_warmup_steps=0, num_training_steps=num_training_steps
-... )
-```
-
-Infine specifica come `device` da usare una GPU se ne hai una. Altrimenti, l'addestramento su una CPU puĂČ richiedere diverse ore invece di un paio di minuti.
-
-```py
->>> import torch
-
->>> device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
->>> model.to(device)
-```
-
-
-
-Ottieni l'accesso gratuito a una GPU sul cloud se non ne possiedi una usando un notebook sul web come [Colaboratory](https://colab.research.google.com/) o [SageMaker StudioLab](https://studiolab.sagemaker.aws/).
-
-
-
-Ottimo, adesso possiamo addestrare! đ„ł
-
-### Training loop
-
-Per tenere traccia dei tuoi progressi durante l'addestramento, usa la libreria [tqdm](https://tqdm.github.io/) per aggiungere una progress bar sopra il numero dei passi di addestramento:
-
-```py
->>> from tqdm.auto import tqdm
-
->>> progress_bar = tqdm(range(num_training_steps))
-
->>> model.train()
->>> for epoch in range(num_epochs):
-... for batch in train_dataloader:
-... batch = {k: v.to(device) for k, v in batch.items()}
-... outputs = model(**batch)
-... loss = outputs.loss
-... loss.backward()
-
-... optimizer.step()
-... lr_scheduler.step()
-... optimizer.zero_grad()
-... progress_bar.update(1)
-```
-
-### Metriche
-
-Proprio come Ăš necessario aggiungere una funzione di valutazione del [`Trainer`], Ăš necessario fare lo stesso quando si scrive il proprio ciclo di addestramento. Ma invece di calcolare e riportare la metrica alla fine di ogni epoca, questa volta accumulerai tutti i batch con [`add_batch`](https://huggingface.co/docs/datasets/package_reference/main_classes.html?highlight=add_batch#datasets.Metric.add_batch) e calcolerai la metrica alla fine.
-
-```py
->>> metric = load_metric("accuracy")
->>> model.eval()
->>> for batch in eval_dataloader:
-... batch = {k: v.to(device) for k, v in batch.items()}
-... with torch.no_grad():
-... outputs = model(**batch)
-
-... logits = outputs.logits
-... predictions = torch.argmax(logits, dim=-1)
-... metric.add_batch(predictions=predictions, references=batch["labels"])
-
->>> metric.compute()
-```
-
-
-
-
-
-## Altre risorse
-
-Per altri esempi sul fine-tuning, fai riferimento a:
-
-- [đ€ Transformers Examples](https://github.com/huggingface/transformers/tree/main/examples) include scripts per addestrare compiti comuni di NLP in PyTorch e TensorFlow.
-
-- [đ€ Transformers Notebooks](notebooks) contiene diversi notebooks su come mettere a punto un modello per compiti specifici in PyTorch e TensorFlow.
diff --git a/docs/source/ja/_toctree.yml b/docs/source/ja/_toctree.yml
index a85f0ee11dcf..8ac8b1e3183f 100644
--- a/docs/source/ja/_toctree.yml
+++ b/docs/source/ja/_toctree.yml
@@ -4,6 +4,10 @@
- local: installation
title: ă€ăłăčăăŒă«
title: ăŻăăă«
+- sections:
+ - local: accelerate
+ title: đ€ Accelerate ăçšăăćæŁćŠçż
+ title: ăă„ăŒăăȘăąă«
- sections:
- sections:
- local: multilingual
diff --git a/docs/source/ja/accelerate.md b/docs/source/ja/accelerate.md
new file mode 100644
index 000000000000..73e45b9cd3c5
--- /dev/null
+++ b/docs/source/ja/accelerate.md
@@ -0,0 +1,136 @@
+
+
+# đ€ Accelerate ăçšăăćæŁćŠçż
+
+ăąăă«ă性ăăăȘăă«ă€ăăŠăéăăăăăŒăăŠă§ăąă§ăă性ăăȘăąăă«ăèšç·Žăăèšç·ŽéćșŠă性ćč
ă«äžæăăăăăăźæčæłăšăăŠäžŠććŠçăæ”źäžăăŠăăŸăăă1ć°ăźăă·ăłă«è€æ°ăźGPUăăăŁăŠăăè€æ°ăźăă·ăłă«ăŸăăăè€æ°ăźGPUăăăŁăŠăăăăăăăżă€ăăźćæŁćŠçă»ăăăąăăäžă§ăŠăŒă¶ăŒăç°Ąćă« đ€ Transformers ăąăă«ăèšç·Žă§ăăăăă«ă Hugging Face ă§ăŻ [đ€ Accelerate](https://huggingface.co/docs/accelerate) ă©ă€ăă©ăȘăäœæăăŸăăăăăźăă„ăŒăăȘăąă«ă§ăŻăPyTorch ăźèšç·Žă«ăŒăăă«ăčăżăă€ășăăŠăćæŁćŠçç°ćąă§ăźèšç·ŽăćŻèœă«ăăæčæłă«ă€ăăŠćŠăłăŸăă
+
+## ă»ăăăąăă
+
+ăŻăăă« đ€ Accelerate ăă€ăłăčăăŒă«ăăŸăăă:
+
+```bash
+pip install accelerate
+```
+
+ăăăăă€ăłăăŒăă㊠[`~accelerate.Accelerator`] ăȘăăžă§ăŻăăäœæăăŸăăăă[`~accelerate.Accelerator`] ăŻćæŁćŠçă»ăăăąăăăèȘćçă«æ€ćșăăèšç·Žăźăăă«ćż
èŠăȘć
šăŠăźăłăłăăŒăăłăăćæćăăŸăăăąăă«ăăăă€ăčă«æç€șçă«é
çœźăăćż
èŠăŻăăăŸăăă
+
+```py
+>>> from accelerate import Accelerator
+
+>>> accelerator = Accelerator()
+```
+
+## Accelerate ăăæșćăăăŸăăă
+
+æŹĄă«ăéąéŁăăć
šăŠăźèšç·ŽăȘăăžă§ăŻăă [`~accelerate.Accelerator.prepare`] ăĄăœăăă«æžĄăăŸăăăăă«ăŻăèšç·Žăšè©äŸĄăăăăăźDataloaderăăąăă«ăoptimizer ăć«ăŸăăŸă:
+
+```py
+>>> train_dataloader, eval_dataloader, model, optimizer = accelerator.prepare(
+... train_dataloader, eval_dataloader, model, optimizer
+... )
+```
+
+## Backward
+
+æćŸă«èšç·Žă«ăŒăć
ăź `loss.backward()` ă đ€ Accelerate ăź [`~accelerate.Accelerator.backward`] ăĄăœăăă§çœźăæăăŸăïŒ
+
+```py
+>>> for epoch in range(num_epochs):
+... for batch in train_dataloader:
+... outputs = model(**batch)
+... loss = outputs.loss
+... accelerator.backward(loss)
+
+... optimizer.step()
+... lr_scheduler.step()
+... optimizer.zero_grad()
+... progress_bar.update(1)
+```
+
+仄äžăźăłăŒăă§çąșèȘă§ăăéăăèšç·Žă«ăŒăă«4èĄăźăłăŒăăèżœć ăăă ăă§ćæŁćŠçżăćŻèœă§ăïŒ
+
+```diff
++ from accelerate import Accelerator
+ from transformers import AdamW, AutoModelForSequenceClassification, get_scheduler
+
++ accelerator = Accelerator()
+
+ model = AutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=2)
+ optimizer = AdamW(model.parameters(), lr=3e-5)
+
+- device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
+- model.to(device)
+
++ train_dataloader, eval_dataloader, model, optimizer = accelerator.prepare(
++ train_dataloader, eval_dataloader, model, optimizer
++ )
+
+ num_epochs = 3
+ num_training_steps = num_epochs * len(train_dataloader)
+ lr_scheduler = get_scheduler(
+ "linear",
+ optimizer=optimizer,
+ num_warmup_steps=0,
+ num_training_steps=num_training_steps
+ )
+
+ progress_bar = tqdm(range(num_training_steps))
+
+ model.train()
+ for epoch in range(num_epochs):
+ for batch in train_dataloader:
+- batch = {k: v.to(device) for k, v in batch.items()}
+ outputs = model(**batch)
+ loss = outputs.loss
+- loss.backward()
++ accelerator.backward(loss)
+
+ optimizer.step()
+ lr_scheduler.step()
+ optimizer.zero_grad()
+ progress_bar.update(1)
+```
+
+## èšç·Žăă
+
+éąéŁăăăłăŒăăèżœć ăăăăăčăŻăȘăăăŸă㯠Colaboratory ăȘă©ăźăăŒăăăăŻă§èšç·Žăéć§ăăŸăă
+
+### ăčăŻăȘăăă§èšç·Žăă
+
+ăčăŻăȘăăăăèšç·ŽăăăŠăăć ŽćăŻăèšćźăăĄă€ă«ăäœæă»äżćăăăăă«ä»„äžăźăłăăłăăćźèĄăăŠăă ăă:
+
+```bash
+accelerate config
+```
+
+ăăăŠæŹĄăźăăă«ăăŠèšç·Žăéć§ăăŸă:
+
+```bash
+accelerate launch train.py
+```
+
+### ăăŒăăăăŻă§èšç·Žăă
+
+Colaboratory ăź TPU ăźć©çšăăèăăźć Žćăđ€ Accelerate ăŻăăŒăăăăŻäžă§ćźèĄăăăăšăă§ăăŸăăèšç·Žă«ćż
èŠăȘć
šăŠăźăłăŒăăéąæ°ă«ć«ăă[`~accelerate.notebook_launcher`] ă«æžĄăăŠăă ăă:
+
+```py
+>>> from accelerate import notebook_launcher
+
+>>> notebook_launcher(training_function)
+```
+
+đ€ Accelerate ăšè±ćŻăȘæ©èœă«ă€ăăŠăăŁăšç„ăăăæčăŻ[ăăă„ăĄăłă](https://huggingface.co/docs/accelerate)ăćç
§ăăŠăă ăăă
diff --git a/docs/source/ja/index.md b/docs/source/ja/index.md
new file mode 100644
index 000000000000..364a3b34caba
--- /dev/null
+++ b/docs/source/ja/index.md
@@ -0,0 +1,399 @@
+
+
+# đ€ Transformers
+
+[PyTorch](https://pytorch.org/), [TensorFlow](https://www.tensorflow.org/), [JAX](https://jax.readthedocs.io/en/latest/)ăźăăăźæć
ç«Żæ©æą°ćŠçżă
+
+đ€ Transformers ăŻæć
端ăźćŠçżæžăżăąăă«ăç°Ąćă«ăăŠăłăăŒăăăŠćŠçżăăAPIăšăăŒă«ăæäŸăăŸăăćŠçżæžăżăąăă«ăäœżçšăăăăšă§èšçźăłăčăăšäșé
žćççŽ ăźæćșéăćæžă§ăăăŸăăŒăăăăąăă«ăćŠçżăăăăă«èŠæ±ăăăæéăšăȘăœăŒăčăçŻçŽăăăăšăă§ăăŸăă ăăăăźăąăă«ăŻä»„äžăźăăăȘç°ăȘăăąăăȘăăŁă«ăăăäžèŹçăȘăżăčăŻăă”ăăŒăăăŸă:
+
+đ **èȘç¶èšèȘćŠç**: ăăăčăćéĄă ćșæèĄšçŸæœćșă èłȘććżçă èšèȘăąăăȘăłă°ă æç« èŠçŽă æ©æą°çż»èšłă è€æ°éžæăăăăčăçæă
+đŒïž **ăłăłăă„ăŒăżăăžă§ăł**: ç»ććéĄă ç©äœæ€ćșă ă»ă°ăĄăłăăŒă·ă§ăłă
+đŁïž **éłćٰ**: èȘćéłćٰèȘèăéłćٰćéĄă
+đ **ăă«ăăąăŒăă«**: ăăŒăă«èłȘććżçă ć
ćŠæćèȘè(OCR)ă ăčăăŁăłăăăăăă„ăĄăłăăăăźæ
ć ±æœćșă ćç»ćéĄă visual question answering(èŠèŠçèłȘććżç)ă
+
+đ€ Transformers ăŻPyTorch, TensorFlow, JAXéăźăăŹăŒă ăŻăŒăŻçžäșéçšæ§ăă”ăăŒăăăŠăăŸăă ăăăŻăąăă«ăźćæź”éă§ç°ăȘăăăŹăŒă ăŻăŒăŻăäœżăăăăźæè»æ§ăæäŸăăŸăăăăăăŹăŒă ăŻăŒăŻă§3èĄăźăłăŒăă§ăąăă«ăćŠçżăăć„ăźăăŹăŒă ăŻăŒăŻă§æšè«ăźăăă«ăąăă«ăăăŒăăăăăšăćŻèœă§ăăăŸăăæŹçȘç°ćąăźăăăă€ăźăăă«ăąăă«ăONNXăTorchScriptăźăăăȘćœąćŒă§ăšăŻăčăăŒăăăăăšăćŻèœă§ăă
+
+[Hub](https://huggingface.co/models), [forum](https://discuss.huggingface.co/), [Discord](https://discord.com/invite/JfAtkvEtRb)ă§æé·äžăźăłăă„ăăăŁă«ä»æ„ćć ăăŸăăăïŒ
+
+## Hugging FaceăăŒă ă«ăăă«ăčăżă ă”ăăŒăăăćžæăźć Žć
+
+
+
+
+
+## çźæŹĄ
+
+ăăă„ăĄăłăăŻä»„äžăź5ă€ăźă»ăŻă·ă§ăłă§æ§æăăăŠăăŸă:
+
+- **ăŻăăă«** ăŻăă©ă€ăă©ăȘăźăŻă€ăăŻăăąăŒăšă©ă€ăă©ăȘăäœżăć§ăăăăăźă€ăłăčăăŒă«æé ăæäŸăăŠăăŸăă
+- **ăă„ăŒăăȘăąă«** ăŻăććżè
ăć§ăăăźă«æé©ăȘć Žæă§ăăăăźă»ăŻă·ă§ăłă§ăŻăă©ă€ăă©ăȘăäœżăć§ăăăăă«ćż
èŠăȘćșæŹçăȘăčăă«ăçżćŸă§ăăŸăă
+- **HOW-TOăŹă€ă** ăŻăèšèȘăąăăȘăłă°ăźăăă«ćŠçżæžăżăąăă«ăfinetuningăăăăšăă«ăčăżă ăąăă«ăźäœæăšć
±æăźæčæłăȘă©ăšăăŁăçčćźăźçźæšăéæăăăăăźæčæłăç€șăăŠăăŸăă
+- **ăłăłă»ăăăŹă€ă** ăŻăăąăă«ăăżăčăŻăăă㊠đ€ TransformersăźèšèšææłăźèæŻă«ăăćșæŹçă«ăłăłă»ăăăèăæčă«ă€ăăŠăăæ·±ăèćŻăè§ŁèȘŹăăŠăăŸăă
+- **API** ć
šăŠăźăŻă©ăčăšéąæ°ăèȘŹæăăŸă:
+
+ - **MAIN CLASSES** ăŻăconfiguration, model, tokenizer, pipelineăšăăŁăæăéèŠăȘăŻă©ăčă«ă€ăăŠè©łçްă«èȘŹæăăŠăăŸăă
+ - **MODELS** ăŻăă©ă€ăă©ăȘă§ćźèŁ
ăăăŠăăăăăăăźăąăă«ă«éąéŁăăăŻă©ăčăšéąæ°ăè©łçŽ°ă«èȘŹæăăŠăăŸăă
+ - **INTERNAL HELPERS** ăŻăć
éšă§äœżçšăăăŠăăăŠăŒăăŁăȘăăŁăŻă©ăčăéąæ°ăè©łçŽ°ă«èȘŹæăăŠăăŸăă
+
+### ă”ăăŒăăăăŠăăăąăă«
+
+
+
+1. **[ALBERT](https://huggingface.co/docs/transformers/model_doc/albert)** (Google Research and the Toyota Technological Institute at Chicago ăă) Zhenzhong Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut ăăć
Źéăăăç ç©¶è«æ: [ALBERT: A Lite BERT for Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942)
+1. **[AltCLIP](https://huggingface.co/docs/transformers/main/model_doc/altclip)** (BAAI ăă) Chen, Zhongzhi and Liu, Guang and Zhang, Bo-Wen and Ye, Fulong and Yang, Qinghong and Wu, Ledell ăăć
Źéăăăç ç©¶è«æ: [AltCLIP: Altering the Language Encoder in CLIP for Extended Language Capabilities](https://arxiv.org/abs/2211.06679)
+1. **[Audio Spectrogram Transformer](https://huggingface.co/docs/transformers/model_doc/audio-spectrogram-transformer)** (MIT ăă) Yuan Gong, Yu-An Chung, James Glass ăăć
Źéăăăç ç©¶è«æ: [AST: Audio Spectrogram Transformer](https://arxiv.org/abs/2104.01778)
+1. **[BART](https://huggingface.co/docs/transformers/model_doc/bart)** (Facebook ăă) Mike Lewis, Yinhan Liu, Naman Goyal, Marjan Ghazvininejad, Abdelrahman Mohamed, Omer Levy, Ves Stoyanov and Luke Zettlemoyer ăăć
Źéăăăç ç©¶è«æ: [BART: Denoising Sequence-to-Sequence Pre-training for Natural Language Generation, Translation, and Comprehension](https://arxiv.org/abs/1910.13461)
+1. **[BARThez](https://huggingface.co/docs/transformers/model_doc/barthez)** (Ăcole polytechnique ăă) Moussa Kamal Eddine, Antoine J.-P. Tixier, Michalis Vazirgiannis ăăć
Źéăăăç ç©¶è«æ: [BARThez: a Skilled Pretrained French Sequence-to-Sequence Model](https://arxiv.org/abs/2010.12321)
+1. **[BARTpho](https://huggingface.co/docs/transformers/model_doc/bartpho)** (VinAI Research ăă) Nguyen Luong Tran, Duong Minh Le and Dat Quoc Nguyen ăăć
Źéăăăç ç©¶è«æ: [BARTpho: Pre-trained Sequence-to-Sequence Models for Vietnamese](https://arxiv.org/abs/2109.09701)
+1. **[BEiT](https://huggingface.co/docs/transformers/model_doc/beit)** (Microsoft ăă) Hangbo Bao, Li Dong, Furu Wei ăăć
Źéăăăç ç©¶è«æ: [BEiT: BERT Pre-Training of Image Transformers](https://arxiv.org/abs/2106.08254)
+1. **[BERT](https://huggingface.co/docs/transformers/model_doc/bert)** (Google ăă) Jacob Devlin, Ming-Wei Chang, Kenton Lee and Kristina Toutanova ăăć
Źéăăăç ç©¶è«æ: [BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding](https://arxiv.org/abs/1810.04805)
+1. **[BERT For Sequence Generation](https://huggingface.co/docs/transformers/model_doc/bert-generation)** (Google ăă) Sascha Rothe, Shashi Narayan, Aliaksei Severyn ăăć
Źéăăăç ç©¶è«æ: [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://arxiv.org/abs/1907.12461)
+1. **[BERTweet](https://huggingface.co/docs/transformers/model_doc/bertweet)** (VinAI Research ăă) Dat Quoc Nguyen, Thanh Vu and Anh Tuan Nguyen ăăć
Źéăăăç ç©¶è«æ: [BERTweet: A pre-trained language model for English Tweets](https://aclanthology.org/2020.emnlp-demos.2/)
+1. **[BigBird-Pegasus](https://huggingface.co/docs/transformers/model_doc/bigbird_pegasus)** (Google Research ăă) Manzil Zaheer, Guru Guruganesh, Avinava Dubey, Joshua Ainslie, Chris Alberti, Santiago Ontanon, Philip Pham, Anirudh Ravula, Qifan Wang, Li Yang, Amr Ahmed ăăć
Źéăăăç ç©¶è«æ: [Big Bird: Transformers for Longer Sequences](https://arxiv.org/abs/2007.14062)
+1. **[BigBird-RoBERTa](https://huggingface.co/docs/transformers/model_doc/big_bird)** (Google Research ăă) Manzil Zaheer, Guru Guruganesh, Avinava Dubey, Joshua Ainslie, Chris Alberti, Santiago Ontanon, Philip Pham, Anirudh Ravula, Qifan Wang, Li Yang, Amr Ahmed ăăć
Źéăăăç ç©¶è«æ: [Big Bird: Transformers for Longer Sequences](https://arxiv.org/abs/2007.14062)
+1. **[BioGpt](https://huggingface.co/docs/transformers/main/model_doc/biogpt)** (Microsoft Research AI4Science ăă) Renqian Luo, Liai Sun, Yingce Xia, Tao Qin, Sheng Zhang, Hoifung Poon and Tie-Yan Liu ăăć
Źéăăăç ç©¶è«æ: [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)
+1. **[BiT](https://huggingface.co/docs/transformers/main/model_doc/bit)** (Google AI ăă) Alexander Kolesnikov, Lucas Beyer, Xiaohua Zhai, Joan Puigcerver, Jessica Yung, Sylvain Gelly, Neil ăăć
Źéăăăç ç©¶è«æ: [Big Transfer (BiT)](https://arxiv.org/abs/1912.11370)Houlsby.
+1. **[Blenderbot](https://huggingface.co/docs/transformers/model_doc/blenderbot)** (Facebook ăă) 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 ăăć
Źéăăăç ç©¶è«æ: [Recipes for building an open-domain chatbot](https://arxiv.org/abs/2004.13637)
+1. **[BlenderbotSmall](https://huggingface.co/docs/transformers/model_doc/blenderbot-small)** (Facebook ăă) 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 ăăć
Źéăăăç ç©¶è«æ: [Recipes for building an open-domain chatbot](https://arxiv.org/abs/2004.13637)
+1. **[BLIP](https://huggingface.co/docs/transformers/main/model_doc/blip)** (Salesforce ăă) Junnan Li, Dongxu Li, Caiming Xiong, Steven Hoi ăăć
Źéăăăç ç©¶è«æ: [BLIP: Bootstrapping Language-Image Pre-training for Unified Vision-Language Understanding and Generation](https://arxiv.org/abs/2201.12086)
+1. **[BLOOM](https://huggingface.co/docs/transformers/model_doc/bloom)** (BigScience workshop ăă) [BigScience Workshop](https://bigscience.huggingface.co/) ăăć
ŹéăăăŸăă.
+1. **[BORT](https://huggingface.co/docs/transformers/model_doc/bort)** (Alexa ăă) Adrian de Wynter and Daniel J. Perry ăăć
Źéăăăç ç©¶è«æ: [Optimal Subarchitecture Extraction For BERT](https://arxiv.org/abs/2010.10499)
+1. **[ByT5](https://huggingface.co/docs/transformers/model_doc/byt5)** (Google Research ăă) Linting Xue, Aditya Barua, Noah Constant, Rami Al-Rfou, Sharan Narang, Mihir Kale, Adam Roberts, Colin Raffel ăăć
Źéăăăç ç©¶è«æ: [ByT5: Towards a token-free future with pre-trained byte-to-byte models](https://arxiv.org/abs/2105.13626)
+1. **[CamemBERT](https://huggingface.co/docs/transformers/model_doc/camembert)** (Inria/Facebook/Sorbonne ăă) Louis Martin*, Benjamin Muller*, Pedro Javier Ortiz SuĂĄrez*, Yoann Dupont, Laurent Romary, Ăric Villemonte de la Clergerie, DjamĂ© Seddah and BenoĂźt Sagot ăăć
Źéăăăç ç©¶è«æ: [CamemBERT: a Tasty French Language Model](https://arxiv.org/abs/1911.03894)
+1. **[CANINE](https://huggingface.co/docs/transformers/model_doc/canine)** (Google Research ăă) Jonathan H. Clark, Dan Garrette, Iulia Turc, John Wieting ăăć
Źéăăăç ç©¶è«æ: [CANINE: Pre-training an Efficient Tokenization-Free Encoder for Language Representation](https://arxiv.org/abs/2103.06874)
+1. **[Chinese-CLIP](https://huggingface.co/docs/transformers/model_doc/chinese_clip)** (OFA-Sys ăă) An Yang, Junshu Pan, Junyang Lin, Rui Men, Yichang Zhang, Jingren Zhou, Chang Zhou ăăć
Źéăăăç ç©¶è«æ: [Chinese CLIP: Contrastive Vision-Language Pretraining in Chinese](https://arxiv.org/abs/2211.01335)
+1. **[CLIP](https://huggingface.co/docs/transformers/model_doc/clip)** (OpenAI ăă) 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 ăăć
Źéăăăç ç©¶è«æ: [Learning Transferable Visual Models From Natural Language Supervision](https://arxiv.org/abs/2103.00020)
+1. **[CLIPSeg](https://huggingface.co/docs/transformers/model_doc/clipseg)** (University of Göttingen ăă) Timo LĂŒddecke and Alexander Ecker ăăć
Źéăăăç ç©¶è«æ: [Image Segmentation Using Text and Image Prompts](https://arxiv.org/abs/2112.10003)
+1. **[CodeGen](https://huggingface.co/docs/transformers/model_doc/codegen)** (Salesforce ăă) Erik Nijkamp, Bo Pang, Hiroaki Hayashi, Lifu Tu, Huan Wang, Yingbo Zhou, Silvio Savarese, Caiming Xiong ăăć
Źéăăăç ç©¶è«æ: [A Conversational Paradigm for Program Synthesis](https://arxiv.org/abs/2203.13474)
+1. **[Conditional DETR](https://huggingface.co/docs/transformers/model_doc/conditional_detr)** (Microsoft Research Asia ăă) Depu Meng, Xiaokang Chen, Zejia Fan, Gang Zeng, Houqiang Li, Yuhui Yuan, Lei Sun, Jingdong Wang ăăć
Źéăăăç ç©¶è«æ: [Conditional DETR for Fast Training Convergence](https://arxiv.org/abs/2108.06152)
+1. **[ConvBERT](https://huggingface.co/docs/transformers/model_doc/convbert)** (YituTech ăă) Zihang Jiang, Weihao Yu, Daquan Zhou, Yunpeng Chen, Jiashi Feng, Shuicheng Yan ăăć
Źéăăăç ç©¶è«æ: [ConvBERT: Improving BERT with Span-based Dynamic Convolution](https://arxiv.org/abs/2008.02496)
+1. **[ConvNeXT](https://huggingface.co/docs/transformers/model_doc/convnext)** (Facebook AI ăă) Zhuang Liu, Hanzi Mao, Chao-Yuan Wu, Christoph Feichtenhofer, Trevor Darrell, Saining Xie ăăć
Źéăăăç ç©¶è«æ: [A ConvNet for the 2020s](https://arxiv.org/abs/2201.03545)
+1. **[ConvNeXTV2](model_doc/convnextv2)** (from Facebook AI) released with the paper [ConvNeXt V2: Co-designing and Scaling ConvNets with Masked Autoencoders](https://arxiv.org/abs/2301.00808) by Sanghyun Woo, Shoubhik Debnath, Ronghang Hu, Xinlei Chen, Zhuang Liu, In So Kweon, Saining Xie.
+1. **[CPM](https://huggingface.co/docs/transformers/model_doc/cpm)** (Tsinghua University ăă) 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 ăăć
Źéăăăç ç©¶è«æ: [CPM: A Large-scale Generative Chinese Pre-trained Language Model](https://arxiv.org/abs/2012.00413)
+1. **[CTRL](https://huggingface.co/docs/transformers/model_doc/ctrl)** (Salesforce ăă) Nitish Shirish Keskar*, Bryan McCann*, Lav R. Varshney, Caiming Xiong and Richard Socher ăăć
Źéăăăç ç©¶è«æ: [CTRL: A Conditional Transformer Language Model for Controllable Generation](https://arxiv.org/abs/1909.05858)
+1. **[CvT](https://huggingface.co/docs/transformers/model_doc/cvt)** (Microsoft ăă) Haiping Wu, Bin Xiao, Noel Codella, Mengchen Liu, Xiyang Dai, Lu Yuan, Lei Zhang ăăć
Źéăăăç ç©¶è«æ: [CvT: Introducing Convolutions to Vision Transformers](https://arxiv.org/abs/2103.15808)
+1. **[Data2Vec](https://huggingface.co/docs/transformers/model_doc/data2vec)** (Facebook ăă) Alexei Baevski, Wei-Ning Hsu, Qiantong Xu, Arun Babu, Jiatao Gu, Michael Auli ăăć
Źéăăăç ç©¶è«æ: [Data2Vec: A General Framework for Self-supervised Learning in Speech, Vision and Language](https://arxiv.org/abs/2202.03555)
+1. **[DeBERTa](https://huggingface.co/docs/transformers/model_doc/deberta)** (Microsoft ăă) Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen ăăć
Źéăăăç ç©¶è«æ: [DeBERTa: Decoding-enhanced BERT with Disentangled Attention](https://arxiv.org/abs/2006.03654)
+1. **[DeBERTa-v2](https://huggingface.co/docs/transformers/model_doc/deberta-v2)** (Microsoft ăă) Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen ăăć
Źéăăăç ç©¶è«æ: [DeBERTa: Decoding-enhanced BERT with Disentangled Attention](https://arxiv.org/abs/2006.03654)
+1. **[Decision Transformer](https://huggingface.co/docs/transformers/model_doc/decision_transformer)** (Berkeley/Facebook/Google ăă) Lili Chen, Kevin Lu, Aravind Rajeswaran, Kimin Lee, Aditya Grover, Michael Laskin, Pieter Abbeel, Aravind Srinivas, Igor Mordatch ăăć
Źéăăăç ç©¶è«æ: [Decision Transformer: Reinforcement Learning via Sequence Modeling](https://arxiv.org/abs/2106.01345)
+1. **[Deformable DETR](https://huggingface.co/docs/transformers/model_doc/deformable_detr)** (SenseTime Research ăă) Xizhou Zhu, Weijie Su, Lewei Lu, Bin Li, Xiaogang Wang, Jifeng Dai ăăć
Źéăăăç ç©¶è«æ: [Deformable DETR: Deformable Transformers for End-to-End Object Detection](https://arxiv.org/abs/2010.04159)
+1. **[DeiT](https://huggingface.co/docs/transformers/model_doc/deit)** (Facebook ăă) Hugo Touvron, Matthieu Cord, Matthijs Douze, Francisco Massa, Alexandre Sablayrolles, HervĂ© JĂ©gou ăăć
Źéăăăç ç©¶è«æ: [Training data-efficient image transformers & distillation through attention](https://arxiv.org/abs/2012.12877)
+1. **[DETR](https://huggingface.co/docs/transformers/model_doc/detr)** (Facebook ăă) Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov, Sergey Zagoruyko ăăć
Źéăăăç ç©¶è«æ: [End-to-End Object Detection with Transformers](https://arxiv.org/abs/2005.12872)
+1. **[DialoGPT](https://huggingface.co/docs/transformers/model_doc/dialogpt)** (Microsoft Research ăă) Yizhe Zhang, Siqi Sun, Michel Galley, Yen-Chun Chen, Chris Brockett, Xiang Gao, Jianfeng Gao, Jingjing Liu, Bill Dolan ăăć
Źéăăăç ç©¶è«æ: [DialoGPT: Large-Scale Generative Pre-training for Conversational Response Generation](https://arxiv.org/abs/1911.00536)
+1. **[DiNAT](https://huggingface.co/docs/transformers/model_doc/dinat)** (SHI Labs ăă) Ali Hassani and Humphrey Shi ăăć
Źéăăăç ç©¶è«æ: [Dilated Neighborhood Attention Transformer](https://arxiv.org/abs/2209.15001)
+1. **[DistilBERT](https://huggingface.co/docs/transformers/model_doc/distilbert)** (HuggingFace ăă), Victor Sanh, Lysandre Debut and Thomas Wolf. ćăææłă§ GPT2, RoBERTa ăš Multilingual BERT ăźć§çžźăèĄăăŸăă.ć§çžźăăăăąăă«ăŻăăăă [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/research_projects/distillation)ă[DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/research_projects/distillation)ă[DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/research_projects/distillation) ăšćä»ăăăăŸăă. ć
Źéăăăç ç©¶è«æ: [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter](https://arxiv.org/abs/1910.01108)
+1. **[DiT](https://huggingface.co/docs/transformers/model_doc/dit)** (Microsoft Research ăă) Junlong Li, Yiheng Xu, Tengchao Lv, Lei Cui, Cha Zhang, Furu Wei ăăć
Źéăăăç ç©¶è«æ: [DiT: Self-supervised Pre-training for Document Image Transformer](https://arxiv.org/abs/2203.02378)
+1. **[Donut](https://huggingface.co/docs/transformers/model_doc/donut)** (NAVER ăă), Geewook Kim, Teakgyu Hong, Moonbin Yim, Jeongyeon Nam, Jinyoung Park, Jinyeong Yim, Wonseok Hwang, Sangdoo Yun, Dongyoon Han, Seunghyun Park ăăć
Źéăăăç ç©¶è«æ: [OCR-free Document Understanding Transformer](https://arxiv.org/abs/2111.15664)
+1. **[DPR](https://huggingface.co/docs/transformers/model_doc/dpr)** (Facebook ăă) Vladimir Karpukhin, Barlas OÄuz, Sewon Min, Patrick Lewis, Ledell Wu, Sergey Edunov, Danqi Chen, and Wen-tau Yih ăăć
Źéăăăç ç©¶è«æ: [Dense Passage Retrieval for Open-Domain Question Answering](https://arxiv.org/abs/2004.04906)
+1. **[DPT](https://huggingface.co/docs/transformers/master/model_doc/dpt)** (Intel Labs ăă) RenĂ© Ranftl, Alexey Bochkovskiy, Vladlen Koltun ăăć
Źéăăăç ç©¶è«æ: [Vision Transformers for Dense Prediction](https://arxiv.org/abs/2103.13413)
+1. **[EfficientNet](https://huggingface.co/docs/transformers/model_doc/efficientnet)** (from Google Research) released with the paper [EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks](https://arxiv.org/abs/1905.11946) by Mingxing Tan and Quoc V. Le.
+1. **[ELECTRA](https://huggingface.co/docs/transformers/model_doc/electra)** (Google Research/Stanford University ăă) Kevin Clark, Minh-Thang Luong, Quoc V. Le, Christopher D. Manning ăăć
Źéăăăç ç©¶è«æ: [ELECTRA: Pre-training text encoders as discriminators rather than generators](https://arxiv.org/abs/2003.10555)
+1. **[EncoderDecoder](https://huggingface.co/docs/transformers/model_doc/encoder-decoder)** (Google Research ăă) Sascha Rothe, Shashi Narayan, Aliaksei Severyn ăăć
Źéăăăç ç©¶è«æ: [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://arxiv.org/abs/1907.12461)
+1. **[ERNIE](https://huggingface.co/docs/transformers/model_doc/ernie)** (Baidu ăă) Yu Sun, Shuohuan Wang, Yukun Li, Shikun Feng, Xuyi Chen, Han Zhang, Xin Tian, Danxiang Zhu, Hao Tian, Hua Wu ăăć
Źéăăăç ç©¶è«æ: [ERNIE: Enhanced Representation through Knowledge Integration](https://arxiv.org/abs/1904.09223)
+1. **[ESM](https://huggingface.co/docs/transformers/model_doc/esm)** (Meta AI ăă) ăŻăă©ăłăčăă©ăŒăăŒăăăă€ăłèšèȘăąăă«ă§ă. **ESM-1b** 㯠Alexander Rives, Joshua Meier, Tom Sercu, Siddharth Goyal, Zeming Lin, Jason Liu, Demi Guo, Myle Ott, C. Lawrence Zitnick, Jerry Ma, and Rob Fergus ăăć
Źéăăăç ç©¶è«æ: [Biological structure and function emerge from scaling unsupervised learning to 250 million protein sequences](https://www.pnas.org/content/118/15/e2016239118). **ESM-1v** 㯠Joshua Meier, Roshan Rao, Robert Verkuil, Jason Liu, Tom Sercu and Alexander Rivesăăăć
Źéăăăç ç©¶è«æ: [Language models enable zero-shot prediction of the effects of mutations on protein function](https://doi.org/10.1101/2021.07.09.450648). **ESM-2** ăšă**ESMFold** 㯠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 ăăć
Źéăăăç ç©¶è«æ: [Language models of protein sequences at the scale of evolution enable accurate structure prediction](https://doi.org/10.1101/2022.07.20.500902)
+1. **[FLAN-T5](https://huggingface.co/docs/transformers/model_doc/flan-t5)** (Google AI ăă) 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 ăăć
ŹéăăăăŹăăžăăȘăŒ [google-research/t5x](https://github.com/google-research/t5x/blob/main/docs/models.md#flan-t5-checkpoints) Le, and Jason Wei
+1. **[FlauBERT](https://huggingface.co/docs/transformers/model_doc/flaubert)** (CNRS ăă) Hang Le, LoĂŻc Vial, Jibril Frej, Vincent Segonne, Maximin Coavoux, Benjamin Lecouteux, Alexandre Allauzen, BenoĂźt CrabbĂ©, Laurent Besacier, Didier Schwab ăăć
Źéăăăç ç©¶è«æ: [FlauBERT: Unsupervised Language Model Pre-training for French](https://arxiv.org/abs/1912.05372)
+1. **[FLAVA](https://huggingface.co/docs/transformers/model_doc/flava)** (Facebook AI ăă) Amanpreet Singh, Ronghang Hu, Vedanuj Goswami, Guillaume Couairon, Wojciech Galuba, Marcus Rohrbach, and Douwe Kiela ăăć
Źéăăăç ç©¶è«æ: [FLAVA: A Foundational Language And Vision Alignment Model](https://arxiv.org/abs/2112.04482)
+1. **[FNet](https://huggingface.co/docs/transformers/model_doc/fnet)** (Google Research ăă) James Lee-Thorp, Joshua Ainslie, Ilya Eckstein, Santiago Ontanon ăăć
Źéăăăç ç©¶è«æ: [FNet: Mixing Tokens with Fourier Transforms](https://arxiv.org/abs/2105.03824)
+1. **[Funnel Transformer](https://huggingface.co/docs/transformers/model_doc/funnel)** (CMU/Google Brain ăă) Zihang Dai, Guokun Lai, Yiming Yang, Quoc V. Le ăăć
Źéăăăç ç©¶è«æ: [Funnel-Transformer: Filtering out Sequential Redundancy for Efficient Language Processing](https://arxiv.org/abs/2006.03236)
+1. **[GIT](https://huggingface.co/docs/transformers/main/model_doc/git)** (Microsoft Research ăă) Jianfeng Wang, Zhengyuan Yang, Xiaowei Hu, Linjie Li, Kevin Lin, Zhe Gan, Zicheng Liu, Ce Liu, Lijuan Wang. ăăć
Źéăăăç ç©¶è«æ [GIT: A Generative Image-to-text Transformer for Vision and Language](https://arxiv.org/abs/2205.14100)
+1. **[GLPN](https://huggingface.co/docs/transformers/model_doc/glpn)** (KAIST ăă) Doyeon Kim, Woonghyun Ga, Pyungwhan Ahn, Donggyu Joo, Sehwan Chun, Junmo Kim ăăć
Źéăăăç ç©¶è«æ: [Global-Local Path Networks for Monocular Depth Estimation with Vertical CutDepth](https://arxiv.org/abs/2201.07436)
+1. **[GPT](https://huggingface.co/docs/transformers/model_doc/openai-gpt)** (OpenAI ăă) Alec Radford, Karthik Narasimhan, Tim Salimans and Ilya Sutskever ăăć
Źéăăăç ç©¶è«æ: [Improving Language Understanding by Generative Pre-Training](https://blog.openai.com/language-unsupervised/)
+1. **[GPT Neo](https://huggingface.co/docs/transformers/model_doc/gpt_neo)** (EleutherAI ăă) Sid Black, Stella Biderman, Leo Gao, Phil Wang and Connor Leahy ăăć
ŹéăăăăŹăăžăăȘăŒ : [EleutherAI/gpt-neo](https://github.com/EleutherAI/gpt-neo)
+1. **[GPT NeoX](https://huggingface.co/docs/transformers/model_doc/gpt_neox)** (EleutherAI ăă) 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 ăăć
Źéăăăç ç©¶è«æ: [GPT-NeoX-20B: An Open-Source Autoregressive Language Model](https://arxiv.org/abs/2204.06745)
+1. **[GPT NeoX Japanese](https://huggingface.co/docs/transformers/model_doc/gpt_neox_japanese)** (ABEJA ăă) Shinya Otani, Takayoshi Makabe, Anuj Arora, and Kyo Hattori ăăăȘăȘăŒăč.
+1. **[GPT-2](https://huggingface.co/docs/transformers/model_doc/gpt2)** (OpenAI ăă) Alec Radford*, Jeffrey Wu*, Rewon Child, David Luan, Dario Amodei** and Ilya Sutskever** ăăć
Źéăăăç ç©¶è«æ: [Language Models are Unsupervised Multitask Learners](https://blog.openai.com/better-language-models/)
+1. **[GPT-J](https://huggingface.co/docs/transformers/model_doc/gptj)** (EleutherAI ăă) Ben Wang and Aran Komatsuzaki ăăć
ŹéăăăăŹăăžăăȘăŒ [kingoflolz/mesh-transformer-jax](https://github.com/kingoflolz/mesh-transformer-jax/)
+1. **[GPT-Sw3](https://huggingface.co/docs/transformers/main/model_doc/gpt-sw3)** (AI-Sweden ăă) Ariel Ekgren, Amaru Cuba Gyllensten, Evangelia Gogoulou, Alice Heiman, Severine Verlinden, Joey Ăhman, Fredrik Carlsson, Magnus Sahlgren ăăć
Źéăăăç ç©¶è«æ: [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)
+1. **[GroupViT](https://huggingface.co/docs/transformers/model_doc/groupvit)** (UCSD, NVIDIA ăă) Jiarui Xu, Shalini De Mello, Sifei Liu, Wonmin Byeon, Thomas Breuel, Jan Kautz, Xiaolong Wang ăăć
Źéăăăç ç©¶è«æ: [GroupViT: Semantic Segmentation Emerges from Text Supervision](https://arxiv.org/abs/2202.11094)
+1. **[Hubert](https://huggingface.co/docs/transformers/model_doc/hubert)** (Facebook ăă) Wei-Ning Hsu, Benjamin Bolte, Yao-Hung Hubert Tsai, Kushal Lakhotia, Ruslan Salakhutdinov, Abdelrahman Mohamed ăăć
Źéăăăç ç©¶è«æ: [HuBERT: Self-Supervised Speech Representation Learning by Masked Prediction of Hidden Units](https://arxiv.org/abs/2106.07447)
+1. **[I-BERT](https://huggingface.co/docs/transformers/model_doc/ibert)** (Berkeley ăă) Sehoon Kim, Amir Gholami, Zhewei Yao, Michael W. Mahoney, Kurt Keutzer ăăć
Źéăăăç ç©¶è«æ: [I-BERT: Integer-only BERT Quantization](https://arxiv.org/abs/2101.01321)
+1. **[ImageGPT](https://huggingface.co/docs/transformers/model_doc/imagegpt)** (OpenAI ăă) Mark Chen, Alec Radford, Rewon Child, Jeffrey Wu, Heewoo Jun, David Luan, Ilya Sutskever ăăć
Źéăăăç ç©¶è«æ: [Generative Pretraining from Pixels](https://openai.com/blog/image-gpt/)
+1. **[Jukebox](https://huggingface.co/docs/transformers/model_doc/jukebox)** (OpenAI ăă) Prafulla Dhariwal, Heewoo Jun, Christine Payne, Jong Wook Kim, Alec Radford, Ilya Sutskever ăăć
Źéăăăç ç©¶è«æ: [Jukebox: A Generative Model for Music](https://arxiv.org/pdf/2005.00341.pdf)
+1. **[LayoutLM](https://huggingface.co/docs/transformers/model_doc/layoutlm)** (Microsoft Research Asia ăă) Yiheng Xu, Minghao Li, Lei Cui, Shaohan Huang, Furu Wei, Ming Zhou ăăć
Źéăăăç ç©¶è«æ: [LayoutLM: Pre-training of Text and Layout for Document Image Understanding](https://arxiv.org/abs/1912.13318)
+1. **[LayoutLMv2](https://huggingface.co/docs/transformers/model_doc/layoutlmv2)** (Microsoft Research Asia ăă) Yang Xu, Yiheng Xu, Tengchao Lv, Lei Cui, Furu Wei, Guoxin Wang, Yijuan Lu, Dinei Florencio, Cha Zhang, Wanxiang Che, Min Zhang, Lidong Zhou ăăć
Źéăăăç ç©¶è«æ: [LayoutLMv2: Multi-modal Pre-training for Visually-Rich Document Understanding](https://arxiv.org/abs/2012.14740)
+1. **[LayoutLMv3](https://huggingface.co/docs/transformers/model_doc/layoutlmv3)** (Microsoft Research Asia ăă) Yupan Huang, Tengchao Lv, Lei Cui, Yutong Lu, Furu Wei ăăć
Źéăăăç ç©¶è«æ: [LayoutLMv3: Pre-training for Document AI with Unified Text and Image Masking](https://arxiv.org/abs/2204.08387)
+1. **[LayoutXLM](https://huggingface.co/docs/transformers/model_doc/layoutxlm)** (Microsoft Research Asia ăă) Yiheng Xu, Tengchao Lv, Lei Cui, Guoxin Wang, Yijuan Lu, Dinei Florencio, Cha Zhang, Furu Wei ăăć
Źéăăăç ç©¶è«æ: [LayoutXLM: Multimodal Pre-training for Multilingual Visually-rich Document Understanding](https://arxiv.org/abs/2104.08836)
+1. **[LED](https://huggingface.co/docs/transformers/model_doc/led)** (AllenAI ăă) Iz Beltagy, Matthew E. Peters, Arman Cohan ăăć
Źéăăăç ç©¶è«æ: [Longformer: The Long-Document Transformer](https://arxiv.org/abs/2004.05150)
+1. **[LeViT](https://huggingface.co/docs/transformers/model_doc/levit)** (Meta AI ăă) Ben Graham, Alaaeldin El-Nouby, Hugo Touvron, Pierre Stock, Armand Joulin, HervĂ© JĂ©gou, Matthijs Douze ăăć
Źéăăăç ç©¶è«æ: [LeViT: A Vision Transformer in ConvNet's Clothing for Faster Inference](https://arxiv.org/abs/2104.01136)
+1. **[LiLT](https://huggingface.co/docs/transformers/model_doc/lilt)** (South China University of Technology ăă) Jiapeng Wang, Lianwen Jin, Kai Ding ăăć
Źéăăăç ç©¶è«æ: [LiLT: A Simple yet Effective Language-Independent Layout Transformer for Structured Document Understanding](https://arxiv.org/abs/2202.13669)
+1. **[Longformer](https://huggingface.co/docs/transformers/model_doc/longformer)** (AllenAI ăă) Iz Beltagy, Matthew E. Peters, Arman Cohan ăăć
Źéăăăç ç©¶è«æ: [Longformer: The Long-Document Transformer](https://arxiv.org/abs/2004.05150)
+1. **[LongT5](https://huggingface.co/docs/transformers/model_doc/longt5)** (Google AI ăă) Mandy Guo, Joshua Ainslie, David Uthus, Santiago Ontanon, Jianmo Ni, Yun-Hsuan Sung, Yinfei Yang ăăć
Źéăăăç ç©¶è«æ: [LongT5: Efficient Text-To-Text Transformer for Long Sequences](https://arxiv.org/abs/2112.07916)
+1. **[LUKE](https://huggingface.co/docs/transformers/model_doc/luke)** (Studio Ousia ăă) Ikuya Yamada, Akari Asai, Hiroyuki Shindo, Hideaki Takeda, Yuji Matsumoto ăăć
Źéăăăç ç©¶è«æ: [LUKE: Deep Contextualized Entity Representations with Entity-aware Self-attention](https://arxiv.org/abs/2010.01057)
+1. **[LXMERT](https://huggingface.co/docs/transformers/model_doc/lxmert)** (UNC Chapel Hill ăă) Hao Tan and Mohit Bansal ăăć
Źéăăăç ç©¶è«æ: [LXMERT: Learning Cross-Modality Encoder Representations from Transformers for Open-Domain Question Answering](https://arxiv.org/abs/1908.07490)
+1. **[M-CTC-T](https://huggingface.co/docs/transformers/model_doc/mctct)** (Facebook ăă) Loren Lugosch, Tatiana Likhomanenko, Gabriel Synnaeve, and Ronan Collobert ăăć
Źéăăăç ç©¶è«æ: [Pseudo-Labeling For Massively Multilingual Speech Recognition](https://arxiv.org/abs/2111.00161)
+1. **[M2M100](https://huggingface.co/docs/transformers/model_doc/m2m_100)** (Facebook ăă) 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 ăăć
Źéăăăç ç©¶è«æ: [Beyond English-Centric Multilingual Machine Translation](https://arxiv.org/abs/2010.11125)
+1. **[MarianMT](https://huggingface.co/docs/transformers/model_doc/marian)** Jörg Tiedemann ăă. [OPUS](http://opus.nlpl.eu/) ăäœżăăȘăăćŠçżăăă "Machine translation" (ăă·ăłăă©ăłăčăŹăŒă·ă§ăł) ăąăă«. [Marian Framework](https://marian-nmt.github.io/) ăŻMicrosoft Translator TeamăăçŸćšéçșäžă§ă.
+1. **[MarkupLM](https://huggingface.co/docs/transformers/model_doc/markuplm)** (Microsoft Research Asia ăă) Junlong Li, Yiheng Xu, Lei Cui, Furu Wei ăăć
Źéăăăç ç©¶è«æ: [MarkupLM: Pre-training of Text and Markup Language for Visually-rich Document Understanding](https://arxiv.org/abs/2110.08518)
+1. **[Mask2Former](https://huggingface.co/docs/transformers/main/model_doc/mask2former)** (FAIR and UIUC ăă) Bowen Cheng, Ishan Misra, Alexander G. Schwing, Alexander Kirillov, Rohit Girdhar. ăăć
Źéăăăç ç©¶è«æ [Masked-attention Mask Transformer for Universal Image Segmentation](https://arxiv.org/abs/2112.01527)
+1. **[MaskFormer](https://huggingface.co/docs/transformers/model_doc/maskformer)** (Meta and UIUC ăă) Bowen Cheng, Alexander G. Schwing, Alexander Kirillov ăăć
Źéăăăç ç©¶è«æ: [Per-Pixel Classification is Not All You Need for Semantic Segmentation](https://arxiv.org/abs/2107.06278)
+1. **[mBART](https://huggingface.co/docs/transformers/model_doc/mbart)** (Facebook ăă) Yinhan Liu, Jiatao Gu, Naman Goyal, Xian Li, Sergey Edunov, Marjan Ghazvininejad, Mike Lewis, Luke Zettlemoyer ăăć
Źéăăăç ç©¶è«æ: [Multilingual Denoising Pre-training for Neural Machine Translation](https://arxiv.org/abs/2001.08210)
+1. **[mBART-50](https://huggingface.co/docs/transformers/model_doc/mbart)** (Facebook ăă) Yuqing Tang, Chau Tran, Xian Li, Peng-Jen Chen, Naman Goyal, Vishrav Chaudhary, Jiatao Gu, Angela Fan ăăć
Źéăăăç ç©¶è«æ: [Multilingual Translation with Extensible Multilingual Pretraining and Finetuning](https://arxiv.org/abs/2008.00401)
+1. **[Megatron-BERT](https://huggingface.co/docs/transformers/model_doc/megatron-bert)** (NVIDIA ăă) Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper and Bryan Catanzaro ăăć
Źéăăăç ç©¶è«æ: [Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism](https://arxiv.org/abs/1909.08053)
+1. **[Megatron-GPT2](https://huggingface.co/docs/transformers/model_doc/megatron_gpt2)** (NVIDIA ăă) Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper and Bryan Catanzaro ăăć
Źéăăăç ç©¶è«æ: [Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism](https://arxiv.org/abs/1909.08053)
+1. **[mLUKE](https://huggingface.co/docs/transformers/model_doc/mluke)** (Studio Ousia ăă) Ryokan Ri, Ikuya Yamada, and Yoshimasa Tsuruoka ăăć
Źéăăăç ç©¶è«æ: [mLUKE: The Power of Entity Representations in Multilingual Pretrained Language Models](https://arxiv.org/abs/2110.08151)
+1. **[MobileBERT](https://huggingface.co/docs/transformers/model_doc/mobilebert)** (CMU/Google Brain ăă) Zhiqing Sun, Hongkun Yu, Xiaodan Song, Renjie Liu, Yiming Yang, and Denny Zhou ăăć
Źéăăăç ç©¶è«æ: [MobileBERT: a Compact Task-Agnostic BERT for Resource-Limited Devices](https://arxiv.org/abs/2004.02984)
+1. **[MobileNetV1](https://huggingface.co/docs/transformers/model_doc/mobilenet_v1)** (Google Inc. ăă) Andrew G. Howard, Menglong Zhu, Bo Chen, Dmitry Kalenichenko, Weijun Wang, Tobias Weyand, Marco Andreetto, Hartwig Adam ăăć
Źéăăăç ç©¶è«æ: [MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications](https://arxiv.org/abs/1704.04861)
+1. **[MobileNetV2](https://huggingface.co/docs/transformers/model_doc/mobilenet_v2)** (Google Inc. ăă) Mark Sandler, Andrew Howard, Menglong Zhu, Andrey Zhmoginov, Liang-Chieh Chen ăăć
Źéăăăç ç©¶è«æ: [MobileNetV2: Inverted Residuals and Linear Bottlenecks](https://arxiv.org/abs/1801.04381)
+1. **[MobileViT](https://huggingface.co/docs/transformers/model_doc/mobilevit)** (Apple ăă) Sachin Mehta and Mohammad Rastegari ăăć
Źéăăăç ç©¶è«æ: [MobileViT: Light-weight, General-purpose, and Mobile-friendly Vision Transformer](https://arxiv.org/abs/2110.02178)
+1. **[MPNet](https://huggingface.co/docs/transformers/model_doc/mpnet)** (Microsoft Research ăă) Kaitao Song, Xu Tan, Tao Qin, Jianfeng Lu, Tie-Yan Liu ăăć
Źéăăăç ç©¶è«æ: [MPNet: Masked and Permuted Pre-training for Language Understanding](https://arxiv.org/abs/2004.09297)
+1. **[MT5](https://huggingface.co/docs/transformers/model_doc/mt5)** (Google AI ăă) Linting Xue, Noah Constant, Adam Roberts, Mihir Kale, Rami Al-Rfou, Aditya Siddhant, Aditya Barua, Colin Raffel ăăć
Źéăăăç ç©¶è«æ: [mT5: A massively multilingual pre-trained text-to-text transformer](https://arxiv.org/abs/2010.11934)
+1. **[MVP](https://huggingface.co/docs/transformers/model_doc/mvp)** (RUC AI Box ăă) Tianyi Tang, Junyi Li, Wayne Xin Zhao and Ji-Rong Wen ăăć
Źéăăăç ç©¶è«æ: [MVP: Multi-task Supervised Pre-training for Natural Language Generation](https://arxiv.org/abs/2206.12131)
+1. **[NAT](https://huggingface.co/docs/transformers/model_doc/nat)** (SHI Labs ăă) Ali Hassani, Steven Walton, Jiachen Li, Shen Li, and Humphrey Shi ăăć
Źéăăăç ç©¶è«æ: [Neighborhood Attention Transformer](https://arxiv.org/abs/2204.07143)
+1. **[Nezha](https://huggingface.co/docs/transformers/model_doc/nezha)** (Huawei Noahâs Ark Lab ăă) Junqiu Wei, Xiaozhe Ren, Xiaoguang Li, Wenyong Huang, Yi Liao, Yasheng Wang, Jiashu Lin, Xin Jiang, Xiao Chen and Qun Liu ăăć
Źéăăăç ç©¶è«æ: [NEZHA: Neural Contextualized Representation for Chinese Language Understanding](https://arxiv.org/abs/1909.00204)
+1. **[NLLB](https://huggingface.co/docs/transformers/model_doc/nllb)** (Meta ăă) the NLLB team ăăć
Źéăăăç ç©¶è«æ: [No Language Left Behind: Scaling Human-Centered Machine Translation](https://arxiv.org/abs/2207.04672)
+1. **[Nyströmformer](https://huggingface.co/docs/transformers/model_doc/nystromformer)** (the University of Wisconsin - Madison ăă) Yunyang Xiong, Zhanpeng Zeng, Rudrasis Chakraborty, Mingxing Tan, Glenn Fung, Yin Li, Vikas Singh ăăć
Źéăăăç ç©¶è«æ: [Nyströmformer: A Nyström-Based Algorithm for Approximating Self-Attention](https://arxiv.org/abs/2102.03902)
+1. **[OneFormer](https://huggingface.co/docs/transformers/main/model_doc/oneformer)** (SHI Labs ăă) Jitesh Jain, Jiachen Li, MangTik Chiu, Ali Hassani, Nikita Orlov, Humphrey Shi ăăć
Źéăăăç ç©¶è«æ: [OneFormer: One Transformer to Rule Universal Image Segmentation](https://arxiv.org/abs/2211.06220)
+1. **[OPT](https://huggingface.co/docs/transformers/master/model_doc/opt)** (Meta AI ăă) Susan Zhang, Stephen Roller, Naman Goyal, Mikel Artetxe, Moya Chen, Shuohui Chen et al ăăć
Źéăăăç ç©¶è«æ: [OPT: Open Pre-trained Transformer Language Models](https://arxiv.org/abs/2205.01068)
+1. **[OWL-ViT](https://huggingface.co/docs/transformers/model_doc/owlvit)** (Google AI ăă) 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 ăăć
Źéăăăç ç©¶è«æ: [Simple Open-Vocabulary Object Detection with Vision Transformers](https://arxiv.org/abs/2205.06230)
+1. **[Pegasus](https://huggingface.co/docs/transformers/model_doc/pegasus)** (Google ăă) Jingqing Zhang, Yao Zhao, Mohammad Saleh and Peter J. Liu ăăć
Źéăăăç ç©¶è«æ: [PEGASUS: Pre-training with Extracted Gap-sentences for Abstractive Summarization](https://arxiv.org/abs/1912.08777)
+1. **[PEGASUS-X](https://huggingface.co/docs/transformers/model_doc/pegasus_x)** (Google ăă) Jason Phang, Yao Zhao, and Peter J. Liu ăăć
Źéăăăç ç©¶è«æ: [Investigating Efficiently Extending Transformers for Long Input Summarization](https://arxiv.org/abs/2208.04347)
+1. **[Perceiver IO](https://huggingface.co/docs/transformers/model_doc/perceiver)** (Deepmind ăă) 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 ăăć
Źéăăăç ç©¶è«æ: [Perceiver IO: A General Architecture for Structured Inputs & Outputs](https://arxiv.org/abs/2107.14795)
+1. **[PhoBERT](https://huggingface.co/docs/transformers/model_doc/phobert)** (VinAI Research ăă) Dat Quoc Nguyen and Anh Tuan Nguyen ăăć
Źéăăăç ç©¶è«æ: [PhoBERT: Pre-trained language models for Vietnamese](https://www.aclweb.org/anthology/2020.findings-emnlp.92/)
+1. **[PLBart](https://huggingface.co/docs/transformers/model_doc/plbart)** (UCLA NLP ăă) Wasi Uddin Ahmad, Saikat Chakraborty, Baishakhi Ray, Kai-Wei Chang ăăć
Źéăăăç ç©¶è«æ: [Unified Pre-training for Program Understanding and Generation](https://arxiv.org/abs/2103.06333)
+1. **[PoolFormer](https://huggingface.co/docs/transformers/model_doc/poolformer)** (Sea AI Labs ăă) Yu, Weihao and Luo, Mi and Zhou, Pan and Si, Chenyang and Zhou, Yichen and Wang, Xinchao and Feng, Jiashi and Yan, Shuicheng ăăć
Źéăăăç ç©¶è«æ: [MetaFormer is Actually What You Need for Vision](https://arxiv.org/abs/2111.11418)
+1. **[ProphetNet](https://huggingface.co/docs/transformers/model_doc/prophetnet)** (Microsoft Research ăă) Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang and Ming Zhou ăăć
Źéăăăç ç©¶è«æ: [ProphetNet: Predicting Future N-gram for Sequence-to-Sequence Pre-training](https://arxiv.org/abs/2001.04063)
+1. **[QDQBert](https://huggingface.co/docs/transformers/model_doc/qdqbert)** (NVIDIA ăă) Hao Wu, Patrick Judd, Xiaojie Zhang, Mikhail Isaev and Paulius Micikevicius ăăć
Źéăăăç ç©¶è«æ: [Integer Quantization for Deep Learning Inference: Principles and Empirical Evaluation](https://arxiv.org/abs/2004.09602)
+1. **[RAG](https://huggingface.co/docs/transformers/model_doc/rag)** (Facebook ăă) 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 ăăć
Źéăăăç ç©¶è«æ: [Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks](https://arxiv.org/abs/2005.11401)
+1. **[REALM](https://huggingface.co/docs/transformers/model_doc/realm.html)** (Google Research ăă) Kelvin Guu, Kenton Lee, Zora Tung, Panupong Pasupat and Ming-Wei Chang ăăć
Źéăăăç ç©¶è«æ: [REALM: Retrieval-Augmented Language Model Pre-Training](https://arxiv.org/abs/2002.08909)
+1. **[Reformer](https://huggingface.co/docs/transformers/model_doc/reformer)** (Google Research ăă) Nikita Kitaev, Ćukasz Kaiser, Anselm Levskaya ăăć
Źéăăăç ç©¶è«æ: [Reformer: The Efficient Transformer](https://arxiv.org/abs/2001.04451)
+1. **[RegNet](https://huggingface.co/docs/transformers/model_doc/regnet)** (META Platforms ăă) Ilija Radosavovic, Raj Prateek Kosaraju, Ross Girshick, Kaiming He, Piotr DollĂĄr ăăć
Źéăăăç ç©¶è«æ: [Designing Network Design Space](https://arxiv.org/abs/2003.13678)
+1. **[RemBERT](https://huggingface.co/docs/transformers/model_doc/rembert)** (Google Research ăă) Hyung Won Chung, Thibault FĂ©vry, Henry Tsai, M. Johnson, Sebastian Ruder ăăć
Źéăăăç ç©¶è«æ: [Rethinking embedding coupling in pre-trained language models](https://arxiv.org/abs/2010.12821)
+1. **[ResNet](https://huggingface.co/docs/transformers/model_doc/resnet)** (Microsoft Research ăă) Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun ăăć
Źéăăăç ç©¶è«æ: [Deep Residual Learning for Image Recognition](https://arxiv.org/abs/1512.03385)
+1. **[RoBERTa](https://huggingface.co/docs/transformers/model_doc/roberta)** (Facebook ăă), Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Mandar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, Veselin Stoyanov ăăć
Źéăăăç ç©¶è«æ: [RoBERTa: A Robustly Optimized BERT Pretraining Approach](https://arxiv.org/abs/1907.11692)
+1. **[RoBERTa-PreLayerNorm](https://huggingface.co/docs/transformers/main/model_doc/roberta-prelayernorm)** (Facebook ăă) Myle Ott, Sergey Edunov, Alexei Baevski, Angela Fan, Sam Gross, Nathan Ng, David Grangier, Michael Auli ăăć
Źéăăăç ç©¶è«æ: [fairseq: A Fast, Extensible Toolkit for Sequence Modeling](https://arxiv.org/abs/1904.01038)
+1. **[RoCBert](https://huggingface.co/docs/transformers/main/model_doc/roc_bert)** (WeChatAI ăă) HuiSu, WeiweiShi, XiaoyuShen, XiaoZhou, TuoJi, JiaruiFang, JieZhou ăăć
Źéăăăç ç©¶è«æ: [RoCBert: Robust Chinese Bert with Multimodal Contrastive Pretraining](https://aclanthology.org/2022.acl-long.65.pdf)
+1. **[RoFormer](https://huggingface.co/docs/transformers/model_doc/roformer)** (ZhuiyiTechnology ăă), Jianlin Su and Yu Lu and Shengfeng Pan and Bo Wen and Yunfeng Liu ăăć
Źéăăăç ç©¶è«æ: [RoFormer: Enhanced Transformer with Rotary Position Embedding](https://arxiv.org/abs/2104.09864)
+1. **[SegFormer](https://huggingface.co/docs/transformers/model_doc/segformer)** (NVIDIA ăă) Enze Xie, Wenhai Wang, Zhiding Yu, Anima Anandkumar, Jose M. Alvarez, Ping Luo ăăć
Źéăăăç ç©¶è«æ: [SegFormer: Simple and Efficient Design for Semantic Segmentation with Transformers](https://arxiv.org/abs/2105.15203)
+1. **[SEW](https://huggingface.co/docs/transformers/model_doc/sew)** (ASAPP ăă) Felix Wu, Kwangyoun Kim, Jing Pan, Kyu Han, Kilian Q. Weinberger, Yoav Artzi ăăć
Źéăăăç ç©¶è«æ: [Performance-Efficiency Trade-offs in Unsupervised Pre-training for Speech Recognition](https://arxiv.org/abs/2109.06870)
+1. **[SEW-D](https://huggingface.co/docs/transformers/model_doc/sew_d)** (ASAPP ăă) Felix Wu, Kwangyoun Kim, Jing Pan, Kyu Han, Kilian Q. Weinberger, Yoav Artzi ăăć
Źéăăăç ç©¶è«æ: [Performance-Efficiency Trade-offs in Unsupervised Pre-training for Speech Recognition](https://arxiv.org/abs/2109.06870)
+1. **[SpeechToTextTransformer](https://huggingface.co/docs/transformers/model_doc/speech_to_text)** (Facebook ăă), Changhan Wang, Yun Tang, Xutai Ma, Anne Wu, Dmytro Okhonko, Juan Pino ăăć
Źéăăăç ç©¶è«æ: [fairseq S2T: Fast Speech-to-Text Modeling with fairseq](https://arxiv.org/abs/2010.05171)
+1. **[SpeechToTextTransformer2](https://huggingface.co/docs/transformers/model_doc/speech_to_text_2)** (Facebook ăă), Changhan Wang, Anne Wu, Juan Pino, Alexei Baevski, Michael Auli, Alexis Conneau ăăć
Źéăăăç ç©¶è«æ: [Large-Scale Self- and Semi-Supervised Learning for Speech Translation](https://arxiv.org/abs/2104.06678)
+1. **[Splinter](https://huggingface.co/docs/transformers/model_doc/splinter)** (Tel Aviv University ăă), Ori Ram, Yuval Kirstain, Jonathan Berant, Amir Globerson, Omer Levy ăăć
Źéăăăç ç©¶è«æ: [Few-Shot Question Answering by Pretraining Span Selection](https://arxiv.org/abs/2101.00438)
+1. **[SqueezeBERT](https://huggingface.co/docs/transformers/model_doc/squeezebert)** (Berkeley ăă) Forrest N. Iandola, Albert E. Shaw, Ravi Krishna, and Kurt W. Keutzer ăăć
Źéăăăç ç©¶è«æ: [SqueezeBERT: What can computer vision teach NLP about efficient neural networks?](https://arxiv.org/abs/2006.11316)
+1. **[Swin Transformer](https://huggingface.co/docs/transformers/model_doc/swin)** (Microsoft ăă) Ze Liu, Yutong Lin, Yue Cao, Han Hu, Yixuan Wei, Zheng Zhang, Stephen Lin, Baining Guo ăăć
Źéăăăç ç©¶è«æ: [Swin Transformer: Hierarchical Vision Transformer using Shifted Windows](https://arxiv.org/abs/2103.14030)
+1. **[Swin Transformer V2](https://huggingface.co/docs/transformers/model_doc/swinv2)** (Microsoft ăă) Ze Liu, Han Hu, Yutong Lin, Zhuliang Yao, Zhenda Xie, Yixuan Wei, Jia Ning, Yue Cao, Zheng Zhang, Li Dong, Furu Wei, Baining Guo ăăć
Źéăăăç ç©¶è«æ: [Swin Transformer V2: Scaling Up Capacity and Resolution](https://arxiv.org/abs/2111.09883)
+1. **[Swin2SR](https://huggingface.co/docs/transformers/main/model_doc/swin2sr)** (University of WĂŒrzburg ăă) Marcos V. Conde, Ui-Jin Choi, Maxime Burchi, Radu Timofte ăăć
Źéăăăç ç©¶è«æ: [Swin2SR: SwinV2 Transformer for Compressed Image Super-Resolution and Restoration](https://arxiv.org/abs/2209.11345)
+1. **[SwitchTransformers](https://huggingface.co/docs/transformers/main/model_doc/switch_transformers)** (Google ăă) William Fedus, Barret Zoph, Noam Shazeer ăăć
Źéăăăç ç©¶è«æ: [Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity](https://arxiv.org/abs/2101.03961)
+1. **[T5](https://huggingface.co/docs/transformers/model_doc/t5)** (Google AI ăă) 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 ăăć
Źéăăăç ç©¶è«æ: [Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer](https://arxiv.org/abs/1910.10683)
+1. **[T5v1.1](https://huggingface.co/docs/transformers/model_doc/t5v1.1)** (Google AI ăă) 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 ăăć
ŹéăăăăŹăăžăăȘăŒ [google-research/text-to-text-transfer-transformer](https://github.com/google-research/text-to-text-transfer-transformer/blob/main/released_checkpoints.md#t511)
+1. **[Table Transformer](https://huggingface.co/docs/transformers/model_doc/table-transformer)** (Microsoft Research ăă) Brandon Smock, Rohith Pesala, Robin Abraham ăăć
Źéăăăç ç©¶è«æ: [PubTables-1M: Towards Comprehensive Table Extraction From Unstructured Documents](https://arxiv.org/abs/2110.00061)
+1. **[TAPAS](https://huggingface.co/docs/transformers/model_doc/tapas)** (Google AI ăă) Jonathan Herzig, PaweĆ Krzysztof Nowak, Thomas MĂŒller, Francesco Piccinno and Julian Martin Eisenschlos ăăć
Źéăăăç ç©¶è«æ: [TAPAS: Weakly Supervised Table Parsing via Pre-training](https://arxiv.org/abs/2004.02349)
+1. **[TAPEX](https://huggingface.co/docs/transformers/model_doc/tapex)** (Microsoft Research ăă) Qian Liu, Bei Chen, Jiaqi Guo, Morteza Ziyadi, Zeqi Lin, Weizhu Chen, Jian-Guang Lou ăăć
Źéăăăç ç©¶è«æ: [TAPEX: Table Pre-training via Learning a Neural SQL Executor](https://arxiv.org/abs/2107.07653)
+1. **[Time Series Transformer](https://huggingface.co/docs/transformers/model_doc/time_series_transformer)** (HuggingFace ăă).
+1. **[TimeSformer](https://huggingface.co/docs/transformers/main/model_doc/timesformer)** (Facebook ăă) Gedas Bertasius, Heng Wang, Lorenzo Torresani ăăć
Źéăăăç ç©¶è«æ: [Is Space-Time Attention All You Need for Video Understanding?](https://arxiv.org/abs/2102.05095)
+1. **[Trajectory Transformer](https://huggingface.co/docs/transformers/model_doc/trajectory_transformers)** (the University of California at Berkeley ăă) Michael Janner, Qiyang Li, Sergey Levine ăăć
Źéăăăç ç©¶è«æ: [Offline Reinforcement Learning as One Big Sequence Modeling Problem](https://arxiv.org/abs/2106.02039)
+1. **[Transformer-XL](https://huggingface.co/docs/transformers/model_doc/transfo-xl)** (Google/CMU ăă) Zihang Dai*, Zhilin Yang*, Yiming Yang, Jaime Carbonell, Quoc V. Le, Ruslan Salakhutdinov ăăć
Źéăăăç ç©¶è«æ: [Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context](https://arxiv.org/abs/1901.02860)
+1. **[TrOCR](https://huggingface.co/docs/transformers/model_doc/trocr)** (Microsoft ăă), Minghao Li, Tengchao Lv, Lei Cui, Yijuan Lu, Dinei Florencio, Cha Zhang, Zhoujun Li, Furu Wei ăăć
Źéăăăç ç©¶è«æ: [TrOCR: Transformer-based Optical Character Recognition with Pre-trained Models](https://arxiv.org/abs/2109.10282)
+1. **[UL2](https://huggingface.co/docs/transformers/model_doc/ul2)** (Google Research ăă) Yi Tay, Mostafa Dehghani, Vinh Q ăăć
Źéăăăç ç©¶è«æ: [Unifying Language Learning Paradigms](https://arxiv.org/abs/2205.05131v1) Tran, Xavier Garcia, Dara Bahri, Tal Schuster, Huaixiu Steven Zheng, Neil Houlsby, Donald Metzler
+1. **[UniSpeech](https://huggingface.co/docs/transformers/model_doc/unispeech)** (Microsoft Research ăă) Chengyi Wang, Yu Wu, Yao Qian, Kenichi Kumatani, Shujie Liu, Furu Wei, Michael Zeng, Xuedong Huang ăăć
Źéăăăç ç©¶è«æ: [UniSpeech: Unified Speech Representation Learning with Labeled and Unlabeled Data](https://arxiv.org/abs/2101.07597)
+1. **[UniSpeechSat](https://huggingface.co/docs/transformers/model_doc/unispeech-sat)** (Microsoft Research ăă) Sanyuan Chen, Yu Wu, Chengyi Wang, Zhengyang Chen, Zhuo Chen, Shujie Liu, Jian Wu, Yao Qian, Furu Wei, Jinyu Li, Xiangzhan Yu ăăć
Źéăăăç ç©¶è«æ: [UNISPEECH-SAT: UNIVERSAL SPEECH REPRESENTATION LEARNING WITH SPEAKER AWARE PRE-TRAINING](https://arxiv.org/abs/2110.05752)
+1. **[UPerNet](https://huggingface.co/docs/transformers/main/model_doc/upernet)** (Peking University ăă) Tete Xiao, Yingcheng Liu, Bolei Zhou, Yuning Jiang, Jian Sun. ăăć
Źéăăăç ç©¶è«æ [Unified Perceptual Parsing for Scene Understanding](https://arxiv.org/abs/1807.10221)
+1. **[VAN](https://huggingface.co/docs/transformers/model_doc/van)** (Tsinghua University and Nankai University ăă) Meng-Hao Guo, Cheng-Ze Lu, Zheng-Ning Liu, Ming-Ming Cheng, Shi-Min Hu ăăć
Źéăăăç ç©¶è«æ: [Visual Attention Network](https://arxiv.org/abs/2202.09741)
+1. **[VideoMAE](https://huggingface.co/docs/transformers/model_doc/videomae)** (Multimedia Computing Group, Nanjing University ăă) Zhan Tong, Yibing Song, Jue Wang, Limin Wang ăăć
Źéăăăç ç©¶è«æ: [VideoMAE: Masked Autoencoders are Data-Efficient Learners for Self-Supervised Video Pre-Training](https://arxiv.org/abs/2203.12602)
+1. **[ViLT](https://huggingface.co/docs/transformers/model_doc/vilt)** (NAVER AI Lab/Kakao Enterprise/Kakao Brain ăă) Wonjae Kim, Bokyung Son, Ildoo Kim ăăć
Źéăăăç ç©¶è«æ: [ViLT: Vision-and-Language Transformer Without Convolution or Region Supervision](https://arxiv.org/abs/2102.03334)
+1. **[Vision Transformer (ViT)](https://huggingface.co/docs/transformers/model_doc/vit)** (Google AI ăă) Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xiaohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg Heigold, Sylvain Gelly, Jakob Uszkoreit, Neil Houlsby ăăć
Źéăăăç ç©¶è«æ: [An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale](https://arxiv.org/abs/2010.11929)
+1. **[VisualBERT](https://huggingface.co/docs/transformers/model_doc/visual_bert)** (UCLA NLP ăă) Liunian Harold Li, Mark Yatskar, Da Yin, Cho-Jui Hsieh, Kai-Wei Chang ăăć
Źéăăăç ç©¶è«æ: [VisualBERT: A Simple and Performant Baseline for Vision and Language](https://arxiv.org/pdf/1908.03557)
+1. **[ViT Hybrid](https://huggingface.co/docs/transformers/main/model_doc/vit_hybrid)** (Google AI ăă) Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xiaohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg Heigold, Sylvain Gelly, Jakob Uszkoreit, Neil Houlsby ăăć
Źéăăăç ç©¶è«æ: [An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale](https://arxiv.org/abs/2010.11929)
+1. **[ViTMAE](https://huggingface.co/docs/transformers/model_doc/vit_mae)** (Meta AI ăă) Kaiming He, Xinlei Chen, Saining Xie, Yanghao Li, Piotr DollĂĄr, Ross Girshick ăăć
Źéăăăç ç©¶è«æ: [Masked Autoencoders Are Scalable Vision Learners](https://arxiv.org/abs/2111.06377)
+1. **[ViTMSN](https://huggingface.co/docs/transformers/model_doc/vit_msn)** (Meta AI ăă) Mahmoud Assran, Mathilde Caron, Ishan Misra, Piotr Bojanowski, Florian Bordes, Pascal Vincent, Armand Joulin, Michael Rabbat, Nicolas Ballas ăăć
Źéăăăç ç©¶è«æ: [Masked Siamese Networks for Label-Efficient Learning](https://arxiv.org/abs/2204.07141)
+1. **[Wav2Vec2](https://huggingface.co/docs/transformers/model_doc/wav2vec2)** (Facebook AI ăă) Alexei Baevski, Henry Zhou, Abdelrahman Mohamed, Michael Auli ăăć
Źéăăăç ç©¶è«æ: [wav2vec 2.0: A Framework for Self-Supervised Learning of Speech Representations](https://arxiv.org/abs/2006.11477)
+1. **[Wav2Vec2-Conformer](https://huggingface.co/docs/transformers/model_doc/wav2vec2-conformer)** (Facebook AI ăă) Changhan Wang, Yun Tang, Xutai Ma, Anne Wu, Sravya Popuri, Dmytro Okhonko, Juan Pino ăăć
Źéăăăç ç©¶è«æ: [FAIRSEQ S2T: Fast Speech-to-Text Modeling with FAIRSEQ](https://arxiv.org/abs/2010.05171)
+1. **[Wav2Vec2Phoneme](https://huggingface.co/docs/transformers/model_doc/wav2vec2_phoneme)** (Facebook AI ăă) Qiantong Xu, Alexei Baevski, Michael Auli ăăć
Źéăăăç ç©¶è«æ: [Simple and Effective Zero-shot Cross-lingual Phoneme Recognition](https://arxiv.org/abs/2109.11680)
+1. **[WavLM](https://huggingface.co/docs/transformers/model_doc/wavlm)** (Microsoft Research ăă) 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 ăăć
Źéăăăç ç©¶è«æ: [WavLM: Large-Scale Self-Supervised Pre-Training for Full Stack Speech Processing](https://arxiv.org/abs/2110.13900)
+1. **[Whisper](https://huggingface.co/docs/transformers/model_doc/whisper)** (OpenAI ăă) Alec Radford, Jong Wook Kim, Tao Xu, Greg Brockman, Christine McLeavey, Ilya Sutskever ăăć
Źéăăăç ç©¶è«æ: [Robust Speech Recognition via Large-Scale Weak Supervision](https://cdn.openai.com/papers/whisper.pdf)
+1. **[X-CLIP](https://huggingface.co/docs/transformers/model_doc/xclip)** (Microsoft Research ăă) Bolin Ni, Houwen Peng, Minghao Chen, Songyang Zhang, Gaofeng Meng, Jianlong Fu, Shiming Xiang, Haibin Ling ăăć
Źéăăăç ç©¶è«æ: [Expanding Language-Image Pretrained Models for General Video Recognition](https://arxiv.org/abs/2208.02816)
+1. **[XGLM](https://huggingface.co/docs/transformers/model_doc/xglm)** (From Facebook AI) 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 ăăć
Źéăăăç ç©¶è«æ: [Few-shot Learning with Multilingual Language Models](https://arxiv.org/abs/2112.10668)
+1. **[XLM](https://huggingface.co/docs/transformers/model_doc/xlm)** (Facebook ăă) Guillaume Lample and Alexis Conneau ăăć
Źéăăăç ç©¶è«æ: [Cross-lingual Language Model Pretraining](https://arxiv.org/abs/1901.07291)
+1. **[XLM-ProphetNet](https://huggingface.co/docs/transformers/model_doc/xlm-prophetnet)** (Microsoft Research ăă) Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang and Ming Zhou ăăć
Źéăăăç ç©¶è«æ: [ProphetNet: Predicting Future N-gram for Sequence-to-Sequence Pre-training](https://arxiv.org/abs/2001.04063)
+1. **[XLM-RoBERTa](https://huggingface.co/docs/transformers/model_doc/xlm-roberta)** (Facebook AI ăă), Alexis Conneau*, Kartikay Khandelwal*, Naman Goyal, Vishrav Chaudhary, Guillaume Wenzek, Francisco GuzmĂĄn, Edouard Grave, Myle Ott, Luke Zettlemoyer and Veselin Stoyanov ăăć
Źéăăăç ç©¶è«æ: [Unsupervised Cross-lingual Representation Learning at Scale](https://arxiv.org/abs/1911.02116)
+1. **[XLM-RoBERTa-XL](https://huggingface.co/docs/transformers/model_doc/xlm-roberta-xl)** (Facebook AI ăă), Naman Goyal, Jingfei Du, Myle Ott, Giri Anantharaman, Alexis Conneau ăăć
Źéăăăç ç©¶è«æ: [Larger-Scale Transformers for Multilingual Masked Language Modeling](https://arxiv.org/abs/2105.00572)
+1. **[XLNet](https://huggingface.co/docs/transformers/model_doc/xlnet)** (Google/CMU ăă) Zhilin Yang*, Zihang Dai*, Yiming Yang, Jaime Carbonell, Ruslan Salakhutdinov, Quoc V. Le ăăć
Źéăăăç ç©¶è«æ: [âXLNet: Generalized Autoregressive Pretraining for Language Understanding](https://arxiv.org/abs/1906.08237)
+1. **[XLS-R](https://huggingface.co/docs/transformers/model_doc/xls_r)** (Facebook AI ăă) 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 ăăć
Źéăăăç ç©¶è«æ: [XLS-R: Self-supervised Cross-lingual Speech Representation Learning at Scale](https://arxiv.org/abs/2111.09296)
+1. **[XLSR-Wav2Vec2](https://huggingface.co/docs/transformers/model_doc/xlsr_wav2vec2)** (Facebook AI ăă) Alexis Conneau, Alexei Baevski, Ronan Collobert, Abdelrahman Mohamed, Michael Auli ăăć
Źéăăăç ç©¶è«æ: [Unsupervised Cross-Lingual Representation Learning For Speech Recognition](https://arxiv.org/abs/2006.13979)
+1. **[YOLOS](https://huggingface.co/docs/transformers/model_doc/yolos)** (Huazhong University of Science & Technology ăă) Yuxin Fang, Bencheng Liao, Xinggang Wang, Jiemin Fang, Jiyang Qi, Rui Wu, Jianwei Niu, Wenyu Liu ăăć
Źéăăăç ç©¶è«æ: [You Only Look at One Sequence: Rethinking Transformer in Vision through Object Detection](https://arxiv.org/abs/2106.00666)
+1. **[YOSO](https://huggingface.co/docs/transformers/model_doc/yoso)** (the University of Wisconsin - Madison ăă) Zhanpeng Zeng, Yunyang Xiong, Sathya N. Ravi, Shailesh Acharya, Glenn Fung, Vikas Singh ăăć
Źéăăăç ç©¶è«æ: [You Only Sample (Almost) Once: Linear Cost Self-Attention Via Bernoulli Sampling](https://arxiv.org/abs/2111.09714)
+
+
+### ă”ăăŒăăăăŠăăăăŹăŒă ăŻăŒăŻ
+
+仄äžăźăăŒăă«ăŻăăăăăźăąăă«ă§ă”ăăŒăăăăŠăăă©ă€ăă©ăȘăç€șăăŠăăŸăă"slow"ăšćŒă°ăăPythonăăŒăŻăă€ă¶ăŒăđ€ Tokenizers ă©ă€ăă©ăȘă«ăă"fast"ăăŒăŻăă€ă¶ăŒăPyTorch, TensorFlow, Flaxăź5ă€ăźăăăăăă”ăăŒăăăăŠăăăăç€șăăŠăăŸăă
+
+
+
+| Model | Tokenizer slow | Tokenizer fast | PyTorch support | TensorFlow support | Flax Support |
+|:-----------------------------:|:--------------:|:--------------:|:---------------:|:------------------:|:------------:|
+| ALBERT | â
| â
| â
| â
| â
|
+| AltCLIP | â | â | â
| â | â |
+| Audio Spectrogram Transformer | â | â | â
| â | â |
+| BART | â
| â
| â
| â
| â
|
+| BEiT | â | â | â
| â | â
|
+| BERT | â
| â
| â
| â
| â
|
+| Bert Generation | â
| â | â
| â | â |
+| BigBird | â
| â
| â
| â | â
|
+| BigBird-Pegasus | â | â | â
| â | â |
+| BioGpt | â
| â | â
| â | â |
+| BiT | â | â | â
| â | â |
+| Blenderbot | â
| â
| â
| â
| â
|
+| BlenderbotSmall | â
| â
| â
| â
| â
|
+| BLIP | â | â | â
| â | â |
+| BLOOM | â | â
| â
| â | â |
+| CamemBERT | â
| â
| â
| â
| â |
+| CANINE | â
| â | â
| â | â |
+| Chinese-CLIP | â | â | â
| â | â |
+| CLIP | â
| â
| â
| â
| â
|
+| CLIPSeg | â | â | â
| â | â |
+| CodeGen | â
| â
| â
| â | â |
+| Conditional DETR | â | â | â
| â | â |
+| ConvBERT | â
| â
| â
| â
| â |
+| ConvNeXT | â | â | â
| â
| â |
+| CTRL | â
| â | â
| â
| â |
+| CvT | â | â | â
| â
| â |
+| Data2VecAudio | â | â | â
| â | â |
+| Data2VecText | â | â | â
| â | â |
+| Data2VecVision | â | â | â
| â
| â |
+| DeBERTa | â
| â
| â
| â
| â |
+| DeBERTa-v2 | â
| â
| â
| â
| â |
+| Decision Transformer | â | â | â
| â | â |
+| Deformable DETR | â | â | â
| â | â |
+| DeiT | â | â | â
| â
| â |
+| DETR | â | â | â
| â | â |
+| DiNAT | â | â | â
| â | â |
+| DistilBERT | â
| â
| â
| â
| â
|
+| DonutSwin | â | â | â
| â | â |
+| DPR | â
| â
| â
| â
| â |
+| DPT | â | â | â
| â | â |
+| ELECTRA | â
| â
| â
| â
| â
|
+| Encoder decoder | â | â | â
| â
| â
|
+| ERNIE | â | â | â
| â | â |
+| ESM | â
| â | â
| â
| â |
+| FairSeq Machine-Translation | â
| â | â
| â | â |
+| FlauBERT | â
| â | â
| â
| â |
+| FLAVA | â | â | â
| â | â |
+| FNet | â
| â
| â
| â | â |
+| Funnel Transformer | â
| â
| â
| â
| â |
+| GIT | â | â | â
| â | â |
+| GLPN | â | â | â
| â | â |
+| GPT Neo | â | â | â
| â | â
|
+| GPT NeoX | â | â
| â
| â | â |
+| GPT NeoX Japanese | â
| â | â
| â | â |
+| GPT-J | â | â | â
| â
| â
|
+| GPT-Sw3 | â
| â
| â
| â
| â
|
+| GroupViT | â | â | â
| â
| â |
+| Hubert | â | â | â
| â
| â |
+| I-BERT | â | â | â
| â | â |
+| ImageGPT | â | â | â
| â | â |
+| Jukebox | â
| â | â
| â | â |
+| LayoutLM | â
| â
| â
| â
| â |
+| LayoutLMv2 | â
| â
| â
| â | â |
+| LayoutLMv3 | â
| â
| â
| â
| â |
+| LED | â
| â
| â
| â
| â |
+| LeViT | â | â | â
| â | â |
+| LiLT | â | â | â
| â | â |
+| Longformer | â
| â
| â
| â
| â |
+| LongT5 | â | â | â
| â | â
|
+| LUKE | â
| â | â
| â | â |
+| LXMERT | â
| â
| â
| â
| â |
+| M-CTC-T | â | â | â
| â | â |
+| M2M100 | â
| â | â
| â | â |
+| Marian | â
| â | â
| â
| â
|
+| MarkupLM | â
| â
| â
| â | â |
+| Mask2Former | â | â | â
| â | â |
+| MaskFormer | â | â | â
| â | â |
+| MaskFormerSwin | â | â | â | â | â |
+| mBART | â
| â
| â
| â
| â
|
+| Megatron-BERT | â | â | â
| â | â |
+| MobileBERT | â
| â
| â
| â
| â |
+| MobileNetV1 | â | â | â
| â | â |
+| MobileNetV2 | â | â | â
| â | â |
+| MobileViT | â | â | â
| â
| â |
+| MPNet | â
| â
| â
| â
| â |
+| MT5 | â
| â
| â
| â
| â
|
+| MVP | â
| â
| â
| â | â |
+| NAT | â | â | â
| â | â |
+| Nezha | â | â | â
| â | â |
+| Nyströmformer | â | â | â
| â | â |
+| OpenAI GPT | â
| â
| â
| â
| â |
+| OpenAI GPT-2 | â
| â
| â
| â
| â
|
+| OPT | â | â | â
| â
| â
|
+| OWL-ViT | â | â | â
| â | â |
+| Pegasus | â
| â
| â
| â
| â
|
+| PEGASUS-X | â | â | â
| â | â |
+| Perceiver | â
| â | â
| â | â |
+| PLBart | â
| â | â
| â | â |
+| PoolFormer | â | â | â
| â | â |
+| ProphetNet | â
| â | â
| â | â |
+| QDQBert | â | â | â
| â | â |
+| RAG | â
| â | â
| â
| â |
+| REALM | â
| â
| â
| â | â |
+| Reformer | â
| â
| â
| â | â |
+| RegNet | â | â | â
| â
| â
|
+| RemBERT | â
| â
| â
| â
| â |
+| ResNet | â | â | â
| â
| â
|
+| RetriBERT | â
| â
| â
| â | â |
+| RoBERTa | â
| â
| â
| â
| â
|
+| RoBERTa-PreLayerNorm | â | â | â
| â
| â
|
+| RoCBert | â
| â | â
| â | â |
+| RoFormer | â
| â
| â
| â
| â
|
+| SegFormer | â | â | â
| â
| â |
+| SEW | â | â | â
| â | â |
+| SEW-D | â | â | â
| â | â |
+| Speech Encoder decoder | â | â | â
| â | â
|
+| Speech2Text | â
| â | â
| â
| â |
+| Speech2Text2 | â
| â | â | â | â |
+| Splinter | â
| â
| â
| â | â |
+| SqueezeBERT | â
| â
| â
| â | â |
+| Swin Transformer | â | â | â
| â
| â |
+| Swin Transformer V2 | â | â | â
| â | â |
+| Swin2SR | â | â | â
| â | â |
+| SwitchTransformers | â | â | â
| â | â |
+| T5 | â
| â
| â
| â
| â
|
+| Table Transformer | â | â | â
| â | â |
+| TAPAS | â
| â | â
| â
| â |
+| Time Series Transformer | â | â | â
| â | â |
+| TimeSformer | â | â | â
| â | â |
+| Trajectory Transformer | â | â | â
| â | â |
+| Transformer-XL | â
| â | â
| â
| â |
+| TrOCR | â | â | â
| â | â |
+| UniSpeech | â | â | â
| â | â |
+| UniSpeechSat | â | â | â
| â | â |
+| UPerNet | â | â | â
| â | â |
+| VAN | â | â | â
| â | â |
+| VideoMAE | â | â | â
| â | â |
+| ViLT | â | â | â
| â | â |
+| Vision Encoder decoder | â | â | â
| â
| â
|
+| VisionTextDualEncoder | â | â | â
| â | â
|
+| VisualBERT | â | â | â
| â | â |
+| ViT | â | â | â
| â
| â
|
+| ViT Hybrid | â | â | â
| â | â |
+| ViTMAE | â | â | â
| â
| â |
+| ViTMSN | â | â | â
| â | â |
+| Wav2Vec2 | â
| â | â
| â
| â
|
+| Wav2Vec2-Conformer | â | â | â
| â | â |
+| WavLM | â | â | â
| â | â |
+| Whisper | â
| â | â
| â
| â |
+| X-CLIP | â | â | â
| â | â |
+| XGLM | â
| â
| â
| â
| â
|
+| XLM | â
| â | â
| â
| â |
+| XLM-ProphetNet | â
| â | â
| â | â |
+| XLM-RoBERTa | â
| â
| â
| â
| â
|
+| XLM-RoBERTa-XL | â | â | â
| â | â |
+| XLNet | â
| â
| â
| â
| â |
+| YOLOS | â | â | â
| â | â |
+| YOSO | â | â | â
| â | â |
+
+
\ No newline at end of file
diff --git a/docs/source/ja/index.mdx b/docs/source/ja/index.mdx
deleted file mode 100644
index f55a3fd42a53..000000000000
--- a/docs/source/ja/index.mdx
+++ /dev/null
@@ -1,395 +0,0 @@
-
-
-# đ€ Transformers
-
-[PyTorch](https://pytorch.org/), [TensorFlow](https://www.tensorflow.org/), [JAX](https://jax.readthedocs.io/en/latest/)ăźăăăźæć
ç«Żæ©æą°ćŠçżă
-
-đ€ Transformers ăŻæć
端ăźćŠçżæžăżăąăă«ăç°Ąćă«ăăŠăłăăŒăăăŠćŠçżăăAPIăšăăŒă«ăæäŸăăŸăăćŠçżæžăżăąăă«ăäœżçšăăăăšă§èšçźăłăčăăšäșé
žćççŽ ăźæćșéăćæžă§ăăăŸăăŒăăăăąăă«ăćŠçżăăăăă«èŠæ±ăăăæéăšăȘăœăŒăčăçŻçŽăăăăšăă§ăăŸăă ăăăăźăąăă«ăŻä»„äžăźăăăȘç°ăȘăăąăăȘăăŁă«ăăăäžèŹçăȘăżăčăŻăă”ăăŒăăăŸă:
-
-đ **èȘç¶èšèȘćŠç**: ăăăčăćéĄă ćșæèĄšçŸæœćșă èłȘććżçă èšèȘăąăăȘăłă°ă æç« èŠçŽă æ©æą°çż»èšłă è€æ°éžæăăăăčăçæă
-đŒïž **ăłăłăă„ăŒăżăăžă§ăł**: ç»ććéĄă ç©äœæ€ćșă ă»ă°ăĄăłăăŒă·ă§ăłă
-đŁïž **éłćٰ**: èȘćéłćٰèȘèăéłćٰćéĄă
-đ **ăă«ăăąăŒăă«**: ăăŒăă«èłȘććżçă ć
ćŠæćèȘè(OCR)ă ăčăăŁăłăăăăăă„ăĄăłăăăăźæ
ć ±æœćșă ćç»ćéĄă visual question answering(èŠèŠçèłȘććżç)ă
-
-đ€ Transformers ăŻPyTorch, TensorFlow, JAXéăźăăŹăŒă ăŻăŒăŻçžäșéçšæ§ăă”ăăŒăăăŠăăŸăă ăăăŻăąăă«ăźćæź”éă§ç°ăȘăăăŹăŒă ăŻăŒăŻăäœżăăăăźæè»æ§ăæäŸăăŸăăăăăăŹăŒă ăŻăŒăŻă§3èĄăźăłăŒăă§ăąăă«ăćŠçżăăć„ăźăăŹăŒă ăŻăŒăŻă§æšè«ăźăăă«ăąăă«ăăăŒăăăăăšăćŻèœă§ăăăŸăăæŹçȘç°ćąăźăăăă€ăźăăă«ăąăă«ăONNXăTorchScriptăźăăăȘćœąćŒă§ăšăŻăčăăŒăăăăăšăćŻèœă§ăă
-
-[Hub](https://huggingface.co/models), [forum](https://discuss.huggingface.co/), [Discord](https://discord.com/invite/JfAtkvEtRb)ă§æé·äžăźăłăă„ăăăŁă«ä»æ„ćć ăăŸăăăïŒ
-
-## Hugging FaceăăŒă ă«ăăă«ăčăżă ă”ăăŒăăăćžæăźć Žć
-
-
-
-
-
-## çźæŹĄ
-
-ăăă„ăĄăłăăŻä»„äžăź5ă€ăźă»ăŻă·ă§ăłă§æ§æăăăŠăăŸă:
-
-- **ăŻăăă«** ăŻăă©ă€ăă©ăȘăźăŻă€ăăŻăăąăŒăšă©ă€ăă©ăȘăäœżăć§ăăăăăźă€ăłăčăăŒă«æé ăæäŸăăŠăăŸăă
-- **ăă„ăŒăăȘăąă«** ăŻăććżè
ăć§ăăăźă«æé©ăȘć Žæă§ăăăăźă»ăŻă·ă§ăłă§ăŻăă©ă€ăă©ăȘăäœżăć§ăăăăă«ćż
èŠăȘćșæŹçăȘăčăă«ăçżćŸă§ăăŸăă
-- **HOW-TOăŹă€ă** ăŻăèšèȘăąăăȘăłă°ăźăăă«ćŠçżæžăżăąăă«ăfinetuningăăăăšăă«ăčăżă ăąăă«ăźäœæăšć
±æăźæčæłăȘă©ăšăăŁăçčćźăźçźæšăéæăăăăăźæčæłăç€șăăŠăăŸăă
-- **ăłăłă»ăăăŹă€ă** ăŻăăąăă«ăăżăčăŻăăă㊠đ€ TransformersăźèšèšææłăźèæŻă«ăăćșæŹçă«ăłăłă»ăăăèăæčă«ă€ăăŠăăæ·±ăèćŻăè§ŁèȘŹăăŠăăŸăă
-- **API** ć
šăŠăźăŻă©ăčăšéąæ°ăèȘŹæăăŸă:
-
- - **MAIN CLASSES** ăŻăconfiguration, model, tokenizer, pipelineăšăăŁăæăéèŠăȘăŻă©ăčă«ă€ăăŠè©łçްă«èȘŹæăăŠăăŸăă
- - **MODELS** ăŻăă©ă€ăă©ăȘă§ćźèŁ
ăăăŠăăăăăăăźăąăă«ă«éąéŁăăăŻă©ăčăšéąæ°ăè©łçŽ°ă«èȘŹæăăŠăăŸăă
- - **INTERNAL HELPERS** ăŻăć
éšă§äœżçšăăăŠăăăŠăŒăăŁăȘăăŁăŻă©ăčăéąæ°ăè©łçŽ°ă«èȘŹæăăŠăăŸăă
-
-### ă”ăăŒăăăăŠăăăąăă«
-
-
-
-1. **[ALBERT](https://huggingface.co/docs/transformers/model_doc/albert)** (Google Research and the Toyota Technological Institute at Chicago ăă) Zhenzhong Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut ăăć
Źéăăăç ç©¶è«æ: [ALBERT: A Lite BERT for Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942)
-1. **[AltCLIP](https://huggingface.co/docs/transformers/main/model_doc/altclip)** (BAAI ăă) Chen, Zhongzhi and Liu, Guang and Zhang, Bo-Wen and Ye, Fulong and Yang, Qinghong and Wu, Ledell ăăć
Źéăăăç ç©¶è«æ: [AltCLIP: Altering the Language Encoder in CLIP for Extended Language Capabilities](https://arxiv.org/abs/2211.06679)
-1. **[Audio Spectrogram Transformer](https://huggingface.co/docs/transformers/model_doc/audio-spectrogram-transformer)** (MIT ăă) Yuan Gong, Yu-An Chung, James Glass ăăć
Źéăăăç ç©¶è«æ: [AST: Audio Spectrogram Transformer](https://arxiv.org/abs/2104.01778)
-1. **[BART](https://huggingface.co/docs/transformers/model_doc/bart)** (Facebook ăă) Mike Lewis, Yinhan Liu, Naman Goyal, Marjan Ghazvininejad, Abdelrahman Mohamed, Omer Levy, Ves Stoyanov and Luke Zettlemoyer ăăć
Źéăăăç ç©¶è«æ: [BART: Denoising Sequence-to-Sequence Pre-training for Natural Language Generation, Translation, and Comprehension](https://arxiv.org/abs/1910.13461)
-1. **[BARThez](https://huggingface.co/docs/transformers/model_doc/barthez)** (Ăcole polytechnique ăă) Moussa Kamal Eddine, Antoine J.-P. Tixier, Michalis Vazirgiannis ăăć
Źéăăăç ç©¶è«æ: [BARThez: a Skilled Pretrained French Sequence-to-Sequence Model](https://arxiv.org/abs/2010.12321)
-1. **[BARTpho](https://huggingface.co/docs/transformers/model_doc/bartpho)** (VinAI Research ăă) Nguyen Luong Tran, Duong Minh Le and Dat Quoc Nguyen ăăć
Źéăăăç ç©¶è«æ: [BARTpho: Pre-trained Sequence-to-Sequence Models for Vietnamese](https://arxiv.org/abs/2109.09701)
-1. **[BEiT](https://huggingface.co/docs/transformers/model_doc/beit)** (Microsoft ăă) Hangbo Bao, Li Dong, Furu Wei ăăć
Źéăăăç ç©¶è«æ: [BEiT: BERT Pre-Training of Image Transformers](https://arxiv.org/abs/2106.08254)
-1. **[BERT](https://huggingface.co/docs/transformers/model_doc/bert)** (Google ăă) Jacob Devlin, Ming-Wei Chang, Kenton Lee and Kristina Toutanova ăăć
Źéăăăç ç©¶è«æ: [BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding](https://arxiv.org/abs/1810.04805)
-1. **[BERT For Sequence Generation](https://huggingface.co/docs/transformers/model_doc/bert-generation)** (Google ăă) Sascha Rothe, Shashi Narayan, Aliaksei Severyn ăăć
Źéăăăç ç©¶è«æ: [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://arxiv.org/abs/1907.12461)
-1. **[BERTweet](https://huggingface.co/docs/transformers/model_doc/bertweet)** (VinAI Research ăă) Dat Quoc Nguyen, Thanh Vu and Anh Tuan Nguyen ăăć
Źéăăăç ç©¶è«æ: [BERTweet: A pre-trained language model for English Tweets](https://aclanthology.org/2020.emnlp-demos.2/)
-1. **[BigBird-Pegasus](https://huggingface.co/docs/transformers/model_doc/bigbird_pegasus)** (Google Research ăă) Manzil Zaheer, Guru Guruganesh, Avinava Dubey, Joshua Ainslie, Chris Alberti, Santiago Ontanon, Philip Pham, Anirudh Ravula, Qifan Wang, Li Yang, Amr Ahmed ăăć
Źéăăăç ç©¶è«æ: [Big Bird: Transformers for Longer Sequences](https://arxiv.org/abs/2007.14062)
-1. **[BigBird-RoBERTa](https://huggingface.co/docs/transformers/model_doc/big_bird)** (Google Research ăă) Manzil Zaheer, Guru Guruganesh, Avinava Dubey, Joshua Ainslie, Chris Alberti, Santiago Ontanon, Philip Pham, Anirudh Ravula, Qifan Wang, Li Yang, Amr Ahmed ăăć
Źéăăăç ç©¶è«æ: [Big Bird: Transformers for Longer Sequences](https://arxiv.org/abs/2007.14062)
-1. **[BioGpt](https://huggingface.co/docs/transformers/main/model_doc/biogpt)** (Microsoft Research AI4Science ăă) Renqian Luo, Liai Sun, Yingce Xia, Tao Qin, Sheng Zhang, Hoifung Poon and Tie-Yan Liu ăăć
Źéăăăç ç©¶è«æ: [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)
-1. **[BiT](https://huggingface.co/docs/transformers/main/model_doc/bit)** (Google AI ăă) Alexander Kolesnikov, Lucas Beyer, Xiaohua Zhai, Joan Puigcerver, Jessica Yung, Sylvain Gelly, Neil ăăć
Źéăăăç ç©¶è«æ: [Big Transfer (BiT)](https://arxiv.org/abs/1912.11370)Houlsby.
-1. **[Blenderbot](https://huggingface.co/docs/transformers/model_doc/blenderbot)** (Facebook ăă) 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 ăăć
Źéăăăç ç©¶è«æ: [Recipes for building an open-domain chatbot](https://arxiv.org/abs/2004.13637)
-1. **[BlenderbotSmall](https://huggingface.co/docs/transformers/model_doc/blenderbot-small)** (Facebook ăă) 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 ăăć
Źéăăăç ç©¶è«æ: [Recipes for building an open-domain chatbot](https://arxiv.org/abs/2004.13637)
-1. **[BLIP](https://huggingface.co/docs/transformers/main/model_doc/blip)** (Salesforce ăă) Junnan Li, Dongxu Li, Caiming Xiong, Steven Hoi ăăć
Źéăăăç ç©¶è«æ: [BLIP: Bootstrapping Language-Image Pre-training for Unified Vision-Language Understanding and Generation](https://arxiv.org/abs/2201.12086)
-1. **[BLOOM](https://huggingface.co/docs/transformers/model_doc/bloom)** (BigScience workshop ăă) [BigScience Workshop](https://bigscience.huggingface.co/) ăăć
ŹéăăăŸăă.
-1. **[BORT](https://huggingface.co/docs/transformers/model_doc/bort)** (Alexa ăă) Adrian de Wynter and Daniel J. Perry ăăć
Źéăăăç ç©¶è«æ: [Optimal Subarchitecture Extraction For BERT](https://arxiv.org/abs/2010.10499)
-1. **[ByT5](https://huggingface.co/docs/transformers/model_doc/byt5)** (Google Research ăă) Linting Xue, Aditya Barua, Noah Constant, Rami Al-Rfou, Sharan Narang, Mihir Kale, Adam Roberts, Colin Raffel ăăć
Źéăăăç ç©¶è«æ: [ByT5: Towards a token-free future with pre-trained byte-to-byte models](https://arxiv.org/abs/2105.13626)
-1. **[CamemBERT](https://huggingface.co/docs/transformers/model_doc/camembert)** (Inria/Facebook/Sorbonne ăă) Louis Martin*, Benjamin Muller*, Pedro Javier Ortiz SuĂĄrez*, Yoann Dupont, Laurent Romary, Ăric Villemonte de la Clergerie, DjamĂ© Seddah and BenoĂźt Sagot ăăć
Źéăăăç ç©¶è«æ: [CamemBERT: a Tasty French Language Model](https://arxiv.org/abs/1911.03894)
-1. **[CANINE](https://huggingface.co/docs/transformers/model_doc/canine)** (Google Research ăă) Jonathan H. Clark, Dan Garrette, Iulia Turc, John Wieting ăăć
Źéăăăç ç©¶è«æ: [CANINE: Pre-training an Efficient Tokenization-Free Encoder for Language Representation](https://arxiv.org/abs/2103.06874)
-1. **[Chinese-CLIP](https://huggingface.co/docs/transformers/model_doc/chinese_clip)** (OFA-Sys ăă) An Yang, Junshu Pan, Junyang Lin, Rui Men, Yichang Zhang, Jingren Zhou, Chang Zhou ăăć
Źéăăăç ç©¶è«æ: [Chinese CLIP: Contrastive Vision-Language Pretraining in Chinese](https://arxiv.org/abs/2211.01335)
-1. **[CLIP](https://huggingface.co/docs/transformers/model_doc/clip)** (OpenAI ăă) 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 ăăć
Źéăăăç ç©¶è«æ: [Learning Transferable Visual Models From Natural Language Supervision](https://arxiv.org/abs/2103.00020)
-1. **[CLIPSeg](https://huggingface.co/docs/transformers/model_doc/clipseg)** (University of Göttingen ăă) Timo LĂŒddecke and Alexander Ecker ăăć
Źéăăăç ç©¶è«æ: [Image Segmentation Using Text and Image Prompts](https://arxiv.org/abs/2112.10003)
-1. **[CodeGen](https://huggingface.co/docs/transformers/model_doc/codegen)** (Salesforce ăă) Erik Nijkamp, Bo Pang, Hiroaki Hayashi, Lifu Tu, Huan Wang, Yingbo Zhou, Silvio Savarese, Caiming Xiong ăăć
Źéăăăç ç©¶è«æ: [A Conversational Paradigm for Program Synthesis](https://arxiv.org/abs/2203.13474)
-1. **[Conditional DETR](https://huggingface.co/docs/transformers/model_doc/conditional_detr)** (Microsoft Research Asia ăă) Depu Meng, Xiaokang Chen, Zejia Fan, Gang Zeng, Houqiang Li, Yuhui Yuan, Lei Sun, Jingdong Wang ăăć
Źéăăăç ç©¶è«æ: [Conditional DETR for Fast Training Convergence](https://arxiv.org/abs/2108.06152)
-1. **[ConvBERT](https://huggingface.co/docs/transformers/model_doc/convbert)** (YituTech ăă) Zihang Jiang, Weihao Yu, Daquan Zhou, Yunpeng Chen, Jiashi Feng, Shuicheng Yan ăăć
Źéăăăç ç©¶è«æ: [ConvBERT: Improving BERT with Span-based Dynamic Convolution](https://arxiv.org/abs/2008.02496)
-1. **[ConvNeXT](https://huggingface.co/docs/transformers/model_doc/convnext)** (Facebook AI ăă) Zhuang Liu, Hanzi Mao, Chao-Yuan Wu, Christoph Feichtenhofer, Trevor Darrell, Saining Xie ăăć
Źéăăăç ç©¶è«æ: [A ConvNet for the 2020s](https://arxiv.org/abs/2201.03545)
-1. **[ConvNeXTV2](model_doc/convnextv2)** (from Facebook AI) released with the paper [ConvNeXt V2: Co-designing and Scaling ConvNets with Masked Autoencoders](https://arxiv.org/abs/2301.00808) by Sanghyun Woo, Shoubhik Debnath, Ronghang Hu, Xinlei Chen, Zhuang Liu, In So Kweon, Saining Xie.
-1. **[CPM](https://huggingface.co/docs/transformers/model_doc/cpm)** (Tsinghua University ăă) 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 ăăć
Źéăăăç ç©¶è«æ: [CPM: A Large-scale Generative Chinese Pre-trained Language Model](https://arxiv.org/abs/2012.00413)
-1. **[CTRL](https://huggingface.co/docs/transformers/model_doc/ctrl)** (Salesforce ăă) Nitish Shirish Keskar*, Bryan McCann*, Lav R. Varshney, Caiming Xiong and Richard Socher ăăć
Źéăăăç ç©¶è«æ: [CTRL: A Conditional Transformer Language Model for Controllable Generation](https://arxiv.org/abs/1909.05858)
-1. **[CvT](https://huggingface.co/docs/transformers/model_doc/cvt)** (Microsoft ăă) Haiping Wu, Bin Xiao, Noel Codella, Mengchen Liu, Xiyang Dai, Lu Yuan, Lei Zhang ăăć
Źéăăăç ç©¶è«æ: [CvT: Introducing Convolutions to Vision Transformers](https://arxiv.org/abs/2103.15808)
-1. **[Data2Vec](https://huggingface.co/docs/transformers/model_doc/data2vec)** (Facebook ăă) Alexei Baevski, Wei-Ning Hsu, Qiantong Xu, Arun Babu, Jiatao Gu, Michael Auli ăăć
Źéăăăç ç©¶è«æ: [Data2Vec: A General Framework for Self-supervised Learning in Speech, Vision and Language](https://arxiv.org/abs/2202.03555)
-1. **[DeBERTa](https://huggingface.co/docs/transformers/model_doc/deberta)** (Microsoft ăă) Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen ăăć
Źéăăăç ç©¶è«æ: [DeBERTa: Decoding-enhanced BERT with Disentangled Attention](https://arxiv.org/abs/2006.03654)
-1. **[DeBERTa-v2](https://huggingface.co/docs/transformers/model_doc/deberta-v2)** (Microsoft ăă) Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen ăăć
Źéăăăç ç©¶è«æ: [DeBERTa: Decoding-enhanced BERT with Disentangled Attention](https://arxiv.org/abs/2006.03654)
-1. **[Decision Transformer](https://huggingface.co/docs/transformers/model_doc/decision_transformer)** (Berkeley/Facebook/Google ăă) Lili Chen, Kevin Lu, Aravind Rajeswaran, Kimin Lee, Aditya Grover, Michael Laskin, Pieter Abbeel, Aravind Srinivas, Igor Mordatch ăăć
Źéăăăç ç©¶è«æ: [Decision Transformer: Reinforcement Learning via Sequence Modeling](https://arxiv.org/abs/2106.01345)
-1. **[Deformable DETR](https://huggingface.co/docs/transformers/model_doc/deformable_detr)** (SenseTime Research ăă) Xizhou Zhu, Weijie Su, Lewei Lu, Bin Li, Xiaogang Wang, Jifeng Dai ăăć
Źéăăăç ç©¶è«æ: [Deformable DETR: Deformable Transformers for End-to-End Object Detection](https://arxiv.org/abs/2010.04159)
-1. **[DeiT](https://huggingface.co/docs/transformers/model_doc/deit)** (Facebook ăă) Hugo Touvron, Matthieu Cord, Matthijs Douze, Francisco Massa, Alexandre Sablayrolles, HervĂ© JĂ©gou ăăć
Źéăăăç ç©¶è«æ: [Training data-efficient image transformers & distillation through attention](https://arxiv.org/abs/2012.12877)
-1. **[DETR](https://huggingface.co/docs/transformers/model_doc/detr)** (Facebook ăă) Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov, Sergey Zagoruyko ăăć
Źéăăăç ç©¶è«æ: [End-to-End Object Detection with Transformers](https://arxiv.org/abs/2005.12872)
-1. **[DialoGPT](https://huggingface.co/docs/transformers/model_doc/dialogpt)** (Microsoft Research ăă) Yizhe Zhang, Siqi Sun, Michel Galley, Yen-Chun Chen, Chris Brockett, Xiang Gao, Jianfeng Gao, Jingjing Liu, Bill Dolan ăăć
Źéăăăç ç©¶è«æ: [DialoGPT: Large-Scale Generative Pre-training for Conversational Response Generation](https://arxiv.org/abs/1911.00536)
-1. **[DiNAT](https://huggingface.co/docs/transformers/model_doc/dinat)** (SHI Labs ăă) Ali Hassani and Humphrey Shi ăăć
Źéăăăç ç©¶è«æ: [Dilated Neighborhood Attention Transformer](https://arxiv.org/abs/2209.15001)
-1. **[DistilBERT](https://huggingface.co/docs/transformers/model_doc/distilbert)** (HuggingFace ăă), Victor Sanh, Lysandre Debut and Thomas Wolf. ćăææłă§ GPT2, RoBERTa ăš Multilingual BERT ăźć§çžźăèĄăăŸăă.ć§çžźăăăăąăă«ăŻăăăă [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/research_projects/distillation)ă[DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/research_projects/distillation)ă[DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/research_projects/distillation) ăšćä»ăăăăŸăă. ć
Źéăăăç ç©¶è«æ: [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter](https://arxiv.org/abs/1910.01108)
-1. **[DiT](https://huggingface.co/docs/transformers/model_doc/dit)** (Microsoft Research ăă) Junlong Li, Yiheng Xu, Tengchao Lv, Lei Cui, Cha Zhang, Furu Wei ăăć
Źéăăăç ç©¶è«æ: [DiT: Self-supervised Pre-training for Document Image Transformer](https://arxiv.org/abs/2203.02378)
-1. **[Donut](https://huggingface.co/docs/transformers/model_doc/donut)** (NAVER ăă), Geewook Kim, Teakgyu Hong, Moonbin Yim, Jeongyeon Nam, Jinyoung Park, Jinyeong Yim, Wonseok Hwang, Sangdoo Yun, Dongyoon Han, Seunghyun Park ăăć
Źéăăăç ç©¶è«æ: [OCR-free Document Understanding Transformer](https://arxiv.org/abs/2111.15664)
-1. **[DPR](https://huggingface.co/docs/transformers/model_doc/dpr)** (Facebook ăă) Vladimir Karpukhin, Barlas OÄuz, Sewon Min, Patrick Lewis, Ledell Wu, Sergey Edunov, Danqi Chen, and Wen-tau Yih ăăć
Źéăăăç ç©¶è«æ: [Dense Passage Retrieval for Open-Domain Question Answering](https://arxiv.org/abs/2004.04906)
-1. **[DPT](https://huggingface.co/docs/transformers/master/model_doc/dpt)** (Intel Labs ăă) RenĂ© Ranftl, Alexey Bochkovskiy, Vladlen Koltun ăăć
Źéăăăç ç©¶è«æ: [Vision Transformers for Dense Prediction](https://arxiv.org/abs/2103.13413)
-1. **[EfficientNet](https://huggingface.co/docs/transformers/model_doc/efficientnet)** (from Google Research) released with the paper [EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks](https://arxiv.org/abs/1905.11946) by Mingxing Tan and Quoc V. Le.
-1. **[ELECTRA](https://huggingface.co/docs/transformers/model_doc/electra)** (Google Research/Stanford University ăă) Kevin Clark, Minh-Thang Luong, Quoc V. Le, Christopher D. Manning ăăć
Źéăăăç ç©¶è«æ: [ELECTRA: Pre-training text encoders as discriminators rather than generators](https://arxiv.org/abs/2003.10555)
-1. **[EncoderDecoder](https://huggingface.co/docs/transformers/model_doc/encoder-decoder)** (Google Research ăă) Sascha Rothe, Shashi Narayan, Aliaksei Severyn ăăć
Źéăăăç ç©¶è«æ: [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://arxiv.org/abs/1907.12461)
-1. **[ERNIE](https://huggingface.co/docs/transformers/model_doc/ernie)** (Baidu ăă) Yu Sun, Shuohuan Wang, Yukun Li, Shikun Feng, Xuyi Chen, Han Zhang, Xin Tian, Danxiang Zhu, Hao Tian, Hua Wu ăăć
Źéăăăç ç©¶è«æ: [ERNIE: Enhanced Representation through Knowledge Integration](https://arxiv.org/abs/1904.09223)
-1. **[ESM](https://huggingface.co/docs/transformers/model_doc/esm)** (Meta AI ăă) ăŻăă©ăłăčăă©ăŒăăŒăăăă€ăłèšèȘăąăă«ă§ă. **ESM-1b** 㯠Alexander Rives, Joshua Meier, Tom Sercu, Siddharth Goyal, Zeming Lin, Jason Liu, Demi Guo, Myle Ott, C. Lawrence Zitnick, Jerry Ma, and Rob Fergus ăăć
Źéăăăç ç©¶è«æ: [Biological structure and function emerge from scaling unsupervised learning to 250 million protein sequences](https://www.pnas.org/content/118/15/e2016239118). **ESM-1v** 㯠Joshua Meier, Roshan Rao, Robert Verkuil, Jason Liu, Tom Sercu and Alexander Rivesăăăć
Źéăăăç ç©¶è«æ: [Language models enable zero-shot prediction of the effects of mutations on protein function](https://doi.org/10.1101/2021.07.09.450648). **ESM-2** ăšă**ESMFold** 㯠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 ăăć
Źéăăăç ç©¶è«æ: [Language models of protein sequences at the scale of evolution enable accurate structure prediction](https://doi.org/10.1101/2022.07.20.500902)
-1. **[FLAN-T5](https://huggingface.co/docs/transformers/model_doc/flan-t5)** (Google AI ăă) 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 ăăć
ŹéăăăăŹăăžăăȘăŒ [google-research/t5x](https://github.com/google-research/t5x/blob/main/docs/models.md#flan-t5-checkpoints) Le, and Jason Wei
-1. **[FlauBERT](https://huggingface.co/docs/transformers/model_doc/flaubert)** (CNRS ăă) Hang Le, LoĂŻc Vial, Jibril Frej, Vincent Segonne, Maximin Coavoux, Benjamin Lecouteux, Alexandre Allauzen, BenoĂźt CrabbĂ©, Laurent Besacier, Didier Schwab ăăć
Źéăăăç ç©¶è«æ: [FlauBERT: Unsupervised Language Model Pre-training for French](https://arxiv.org/abs/1912.05372)
-1. **[FLAVA](https://huggingface.co/docs/transformers/model_doc/flava)** (Facebook AI ăă) Amanpreet Singh, Ronghang Hu, Vedanuj Goswami, Guillaume Couairon, Wojciech Galuba, Marcus Rohrbach, and Douwe Kiela ăăć
Źéăăăç ç©¶è«æ: [FLAVA: A Foundational Language And Vision Alignment Model](https://arxiv.org/abs/2112.04482)
-1. **[FNet](https://huggingface.co/docs/transformers/model_doc/fnet)** (Google Research ăă) James Lee-Thorp, Joshua Ainslie, Ilya Eckstein, Santiago Ontanon ăăć
Źéăăăç ç©¶è«æ: [FNet: Mixing Tokens with Fourier Transforms](https://arxiv.org/abs/2105.03824)
-1. **[Funnel Transformer](https://huggingface.co/docs/transformers/model_doc/funnel)** (CMU/Google Brain ăă) Zihang Dai, Guokun Lai, Yiming Yang, Quoc V. Le ăăć
Źéăăăç ç©¶è«æ: [Funnel-Transformer: Filtering out Sequential Redundancy for Efficient Language Processing](https://arxiv.org/abs/2006.03236)
-1. **[GIT](https://huggingface.co/docs/transformers/main/model_doc/git)** (Microsoft Research ăă) Jianfeng Wang, Zhengyuan Yang, Xiaowei Hu, Linjie Li, Kevin Lin, Zhe Gan, Zicheng Liu, Ce Liu, Lijuan Wang. ăăć
Źéăăăç ç©¶è«æ [GIT: A Generative Image-to-text Transformer for Vision and Language](https://arxiv.org/abs/2205.14100)
-1. **[GLPN](https://huggingface.co/docs/transformers/model_doc/glpn)** (KAIST ăă) Doyeon Kim, Woonghyun Ga, Pyungwhan Ahn, Donggyu Joo, Sehwan Chun, Junmo Kim ăăć
Źéăăăç ç©¶è«æ: [Global-Local Path Networks for Monocular Depth Estimation with Vertical CutDepth](https://arxiv.org/abs/2201.07436)
-1. **[GPT](https://huggingface.co/docs/transformers/model_doc/openai-gpt)** (OpenAI ăă) Alec Radford, Karthik Narasimhan, Tim Salimans and Ilya Sutskever ăăć
Źéăăăç ç©¶è«æ: [Improving Language Understanding by Generative Pre-Training](https://blog.openai.com/language-unsupervised/)
-1. **[GPT Neo](https://huggingface.co/docs/transformers/model_doc/gpt_neo)** (EleutherAI ăă) Sid Black, Stella Biderman, Leo Gao, Phil Wang and Connor Leahy ăăć
ŹéăăăăŹăăžăăȘăŒ : [EleutherAI/gpt-neo](https://github.com/EleutherAI/gpt-neo)
-1. **[GPT NeoX](https://huggingface.co/docs/transformers/model_doc/gpt_neox)** (EleutherAI ăă) 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 ăăć
Źéăăăç ç©¶è«æ: [GPT-NeoX-20B: An Open-Source Autoregressive Language Model](https://arxiv.org/abs/2204.06745)
-1. **[GPT NeoX Japanese](https://huggingface.co/docs/transformers/model_doc/gpt_neox_japanese)** (ABEJA ăă) Shinya Otani, Takayoshi Makabe, Anuj Arora, and Kyo Hattori ăăăȘăȘăŒăč.
-1. **[GPT-2](https://huggingface.co/docs/transformers/model_doc/gpt2)** (OpenAI ăă) Alec Radford*, Jeffrey Wu*, Rewon Child, David Luan, Dario Amodei** and Ilya Sutskever** ăăć
Źéăăăç ç©¶è«æ: [Language Models are Unsupervised Multitask Learners](https://blog.openai.com/better-language-models/)
-1. **[GPT-J](https://huggingface.co/docs/transformers/model_doc/gptj)** (EleutherAI ăă) Ben Wang and Aran Komatsuzaki ăăć
ŹéăăăăŹăăžăăȘăŒ [kingoflolz/mesh-transformer-jax](https://github.com/kingoflolz/mesh-transformer-jax/)
-1. **[GPT-Sw3](https://huggingface.co/docs/transformers/main/model_doc/gpt-sw3)** (AI-Sweden ăă) Ariel Ekgren, Amaru Cuba Gyllensten, Evangelia Gogoulou, Alice Heiman, Severine Verlinden, Joey Ăhman, Fredrik Carlsson, Magnus Sahlgren ăăć
Źéăăăç ç©¶è«æ: [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)
-1. **[GroupViT](https://huggingface.co/docs/transformers/model_doc/groupvit)** (UCSD, NVIDIA ăă) Jiarui Xu, Shalini De Mello, Sifei Liu, Wonmin Byeon, Thomas Breuel, Jan Kautz, Xiaolong Wang ăăć
Źéăăăç ç©¶è«æ: [GroupViT: Semantic Segmentation Emerges from Text Supervision](https://arxiv.org/abs/2202.11094)
-1. **[Hubert](https://huggingface.co/docs/transformers/model_doc/hubert)** (Facebook ăă) Wei-Ning Hsu, Benjamin Bolte, Yao-Hung Hubert Tsai, Kushal Lakhotia, Ruslan Salakhutdinov, Abdelrahman Mohamed ăăć
Źéăăăç ç©¶è«æ: [HuBERT: Self-Supervised Speech Representation Learning by Masked Prediction of Hidden Units](https://arxiv.org/abs/2106.07447)
-1. **[I-BERT](https://huggingface.co/docs/transformers/model_doc/ibert)** (Berkeley ăă) Sehoon Kim, Amir Gholami, Zhewei Yao, Michael W. Mahoney, Kurt Keutzer ăăć
Źéăăăç ç©¶è«æ: [I-BERT: Integer-only BERT Quantization](https://arxiv.org/abs/2101.01321)
-1. **[ImageGPT](https://huggingface.co/docs/transformers/model_doc/imagegpt)** (OpenAI ăă) Mark Chen, Alec Radford, Rewon Child, Jeffrey Wu, Heewoo Jun, David Luan, Ilya Sutskever ăăć
Źéăăăç ç©¶è«æ: [Generative Pretraining from Pixels](https://openai.com/blog/image-gpt/)
-1. **[Jukebox](https://huggingface.co/docs/transformers/model_doc/jukebox)** (OpenAI ăă) Prafulla Dhariwal, Heewoo Jun, Christine Payne, Jong Wook Kim, Alec Radford, Ilya Sutskever ăăć
Źéăăăç ç©¶è«æ: [Jukebox: A Generative Model for Music](https://arxiv.org/pdf/2005.00341.pdf)
-1. **[LayoutLM](https://huggingface.co/docs/transformers/model_doc/layoutlm)** (Microsoft Research Asia ăă) Yiheng Xu, Minghao Li, Lei Cui, Shaohan Huang, Furu Wei, Ming Zhou ăăć
Źéăăăç ç©¶è«æ: [LayoutLM: Pre-training of Text and Layout for Document Image Understanding](https://arxiv.org/abs/1912.13318)
-1. **[LayoutLMv2](https://huggingface.co/docs/transformers/model_doc/layoutlmv2)** (Microsoft Research Asia ăă) Yang Xu, Yiheng Xu, Tengchao Lv, Lei Cui, Furu Wei, Guoxin Wang, Yijuan Lu, Dinei Florencio, Cha Zhang, Wanxiang Che, Min Zhang, Lidong Zhou ăăć
Źéăăăç ç©¶è«æ: [LayoutLMv2: Multi-modal Pre-training for Visually-Rich Document Understanding](https://arxiv.org/abs/2012.14740)
-1. **[LayoutLMv3](https://huggingface.co/docs/transformers/model_doc/layoutlmv3)** (Microsoft Research Asia ăă) Yupan Huang, Tengchao Lv, Lei Cui, Yutong Lu, Furu Wei ăăć
Źéăăăç ç©¶è«æ: [LayoutLMv3: Pre-training for Document AI with Unified Text and Image Masking](https://arxiv.org/abs/2204.08387)
-1. **[LayoutXLM](https://huggingface.co/docs/transformers/model_doc/layoutxlm)** (Microsoft Research Asia ăă) Yiheng Xu, Tengchao Lv, Lei Cui, Guoxin Wang, Yijuan Lu, Dinei Florencio, Cha Zhang, Furu Wei ăăć
Źéăăăç ç©¶è«æ: [LayoutXLM: Multimodal Pre-training for Multilingual Visually-rich Document Understanding](https://arxiv.org/abs/2104.08836)
-1. **[LED](https://huggingface.co/docs/transformers/model_doc/led)** (AllenAI ăă) Iz Beltagy, Matthew E. Peters, Arman Cohan ăăć
Źéăăăç ç©¶è«æ: [Longformer: The Long-Document Transformer](https://arxiv.org/abs/2004.05150)
-1. **[LeViT](https://huggingface.co/docs/transformers/model_doc/levit)** (Meta AI ăă) Ben Graham, Alaaeldin El-Nouby, Hugo Touvron, Pierre Stock, Armand Joulin, HervĂ© JĂ©gou, Matthijs Douze ăăć
Źéăăăç ç©¶è«æ: [LeViT: A Vision Transformer in ConvNet's Clothing for Faster Inference](https://arxiv.org/abs/2104.01136)
-1. **[LiLT](https://huggingface.co/docs/transformers/model_doc/lilt)** (South China University of Technology ăă) Jiapeng Wang, Lianwen Jin, Kai Ding ăăć
Źéăăăç ç©¶è«æ: [LiLT: A Simple yet Effective Language-Independent Layout Transformer for Structured Document Understanding](https://arxiv.org/abs/2202.13669)
-1. **[Longformer](https://huggingface.co/docs/transformers/model_doc/longformer)** (AllenAI ăă) Iz Beltagy, Matthew E. Peters, Arman Cohan ăăć
Źéăăăç ç©¶è«æ: [Longformer: The Long-Document Transformer](https://arxiv.org/abs/2004.05150)
-1. **[LongT5](https://huggingface.co/docs/transformers/model_doc/longt5)** (Google AI ăă) Mandy Guo, Joshua Ainslie, David Uthus, Santiago Ontanon, Jianmo Ni, Yun-Hsuan Sung, Yinfei Yang ăăć
Źéăăăç ç©¶è«æ: [LongT5: Efficient Text-To-Text Transformer for Long Sequences](https://arxiv.org/abs/2112.07916)
-1. **[LUKE](https://huggingface.co/docs/transformers/model_doc/luke)** (Studio Ousia ăă) Ikuya Yamada, Akari Asai, Hiroyuki Shindo, Hideaki Takeda, Yuji Matsumoto ăăć
Źéăăăç ç©¶è«æ: [LUKE: Deep Contextualized Entity Representations with Entity-aware Self-attention](https://arxiv.org/abs/2010.01057)
-1. **[LXMERT](https://huggingface.co/docs/transformers/model_doc/lxmert)** (UNC Chapel Hill ăă) Hao Tan and Mohit Bansal ăăć
Źéăăăç ç©¶è«æ: [LXMERT: Learning Cross-Modality Encoder Representations from Transformers for Open-Domain Question Answering](https://arxiv.org/abs/1908.07490)
-1. **[M-CTC-T](https://huggingface.co/docs/transformers/model_doc/mctct)** (Facebook ăă) Loren Lugosch, Tatiana Likhomanenko, Gabriel Synnaeve, and Ronan Collobert ăăć
Źéăăăç ç©¶è«æ: [Pseudo-Labeling For Massively Multilingual Speech Recognition](https://arxiv.org/abs/2111.00161)
-1. **[M2M100](https://huggingface.co/docs/transformers/model_doc/m2m_100)** (Facebook ăă) 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 ăăć
Źéăăăç ç©¶è«æ: [Beyond English-Centric Multilingual Machine Translation](https://arxiv.org/abs/2010.11125)
-1. **[MarianMT](https://huggingface.co/docs/transformers/model_doc/marian)** Jörg Tiedemann ăă. [OPUS](http://opus.nlpl.eu/) ăäœżăăȘăăćŠçżăăă "Machine translation" (ăă·ăłăă©ăłăčăŹăŒă·ă§ăł) ăąăă«. [Marian Framework](https://marian-nmt.github.io/) ăŻMicrosoft Translator TeamăăçŸćšéçșäžă§ă.
-1. **[MarkupLM](https://huggingface.co/docs/transformers/model_doc/markuplm)** (Microsoft Research Asia ăă) Junlong Li, Yiheng Xu, Lei Cui, Furu Wei ăăć
Źéăăăç ç©¶è«æ: [MarkupLM: Pre-training of Text and Markup Language for Visually-rich Document Understanding](https://arxiv.org/abs/2110.08518)
-1. **[Mask2Former](https://huggingface.co/docs/transformers/main/model_doc/mask2former)** (FAIR and UIUC ăă) Bowen Cheng, Ishan Misra, Alexander G. Schwing, Alexander Kirillov, Rohit Girdhar. ăăć
Źéăăăç ç©¶è«æ [Masked-attention Mask Transformer for Universal Image Segmentation](https://arxiv.org/abs/2112.01527)
-1. **[MaskFormer](https://huggingface.co/docs/transformers/model_doc/maskformer)** (Meta and UIUC ăă) Bowen Cheng, Alexander G. Schwing, Alexander Kirillov ăăć
Źéăăăç ç©¶è«æ: [Per-Pixel Classification is Not All You Need for Semantic Segmentation](https://arxiv.org/abs/2107.06278)
-1. **[mBART](https://huggingface.co/docs/transformers/model_doc/mbart)** (Facebook ăă) Yinhan Liu, Jiatao Gu, Naman Goyal, Xian Li, Sergey Edunov, Marjan Ghazvininejad, Mike Lewis, Luke Zettlemoyer ăăć
Źéăăăç ç©¶è«æ: [Multilingual Denoising Pre-training for Neural Machine Translation](https://arxiv.org/abs/2001.08210)
-1. **[mBART-50](https://huggingface.co/docs/transformers/model_doc/mbart)** (Facebook ăă) Yuqing Tang, Chau Tran, Xian Li, Peng-Jen Chen, Naman Goyal, Vishrav Chaudhary, Jiatao Gu, Angela Fan ăăć
Źéăăăç ç©¶è«æ: [Multilingual Translation with Extensible Multilingual Pretraining and Finetuning](https://arxiv.org/abs/2008.00401)
-1. **[Megatron-BERT](https://huggingface.co/docs/transformers/model_doc/megatron-bert)** (NVIDIA ăă) Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper and Bryan Catanzaro ăăć
Źéăăăç ç©¶è«æ: [Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism](https://arxiv.org/abs/1909.08053)
-1. **[Megatron-GPT2](https://huggingface.co/docs/transformers/model_doc/megatron_gpt2)** (NVIDIA ăă) Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper and Bryan Catanzaro ăăć
Źéăăăç ç©¶è«æ: [Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism](https://arxiv.org/abs/1909.08053)
-1. **[mLUKE](https://huggingface.co/docs/transformers/model_doc/mluke)** (Studio Ousia ăă) Ryokan Ri, Ikuya Yamada, and Yoshimasa Tsuruoka ăăć
Źéăăăç ç©¶è«æ: [mLUKE: The Power of Entity Representations in Multilingual Pretrained Language Models](https://arxiv.org/abs/2110.08151)
-1. **[MobileBERT](https://huggingface.co/docs/transformers/model_doc/mobilebert)** (CMU/Google Brain ăă) Zhiqing Sun, Hongkun Yu, Xiaodan Song, Renjie Liu, Yiming Yang, and Denny Zhou ăăć
Źéăăăç ç©¶è«æ: [MobileBERT: a Compact Task-Agnostic BERT for Resource-Limited Devices](https://arxiv.org/abs/2004.02984)
-1. **[MobileNetV1](https://huggingface.co/docs/transformers/model_doc/mobilenet_v1)** (Google Inc. ăă) Andrew G. Howard, Menglong Zhu, Bo Chen, Dmitry Kalenichenko, Weijun Wang, Tobias Weyand, Marco Andreetto, Hartwig Adam ăăć
Źéăăăç ç©¶è«æ: [MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications](https://arxiv.org/abs/1704.04861)
-1. **[MobileNetV2](https://huggingface.co/docs/transformers/model_doc/mobilenet_v2)** (Google Inc. ăă) Mark Sandler, Andrew Howard, Menglong Zhu, Andrey Zhmoginov, Liang-Chieh Chen ăăć
Źéăăăç ç©¶è«æ: [MobileNetV2: Inverted Residuals and Linear Bottlenecks](https://arxiv.org/abs/1801.04381)
-1. **[MobileViT](https://huggingface.co/docs/transformers/model_doc/mobilevit)** (Apple ăă) Sachin Mehta and Mohammad Rastegari ăăć
Źéăăăç ç©¶è«æ: [MobileViT: Light-weight, General-purpose, and Mobile-friendly Vision Transformer](https://arxiv.org/abs/2110.02178)
-1. **[MPNet](https://huggingface.co/docs/transformers/model_doc/mpnet)** (Microsoft Research ăă) Kaitao Song, Xu Tan, Tao Qin, Jianfeng Lu, Tie-Yan Liu ăăć
Źéăăăç ç©¶è«æ: [MPNet: Masked and Permuted Pre-training for Language Understanding](https://arxiv.org/abs/2004.09297)
-1. **[MT5](https://huggingface.co/docs/transformers/model_doc/mt5)** (Google AI ăă) Linting Xue, Noah Constant, Adam Roberts, Mihir Kale, Rami Al-Rfou, Aditya Siddhant, Aditya Barua, Colin Raffel ăăć
Źéăăăç ç©¶è«æ: [mT5: A massively multilingual pre-trained text-to-text transformer](https://arxiv.org/abs/2010.11934)
-1. **[MVP](https://huggingface.co/docs/transformers/model_doc/mvp)** (RUC AI Box ăă) Tianyi Tang, Junyi Li, Wayne Xin Zhao and Ji-Rong Wen ăăć
Źéăăăç ç©¶è«æ: [MVP: Multi-task Supervised Pre-training for Natural Language Generation](https://arxiv.org/abs/2206.12131)
-1. **[NAT](https://huggingface.co/docs/transformers/model_doc/nat)** (SHI Labs ăă) Ali Hassani, Steven Walton, Jiachen Li, Shen Li, and Humphrey Shi ăăć
Źéăăăç ç©¶è«æ: [Neighborhood Attention Transformer](https://arxiv.org/abs/2204.07143)
-1. **[Nezha](https://huggingface.co/docs/transformers/model_doc/nezha)** (Huawei Noahâs Ark Lab ăă) Junqiu Wei, Xiaozhe Ren, Xiaoguang Li, Wenyong Huang, Yi Liao, Yasheng Wang, Jiashu Lin, Xin Jiang, Xiao Chen and Qun Liu ăăć
Źéăăăç ç©¶è«æ: [NEZHA: Neural Contextualized Representation for Chinese Language Understanding](https://arxiv.org/abs/1909.00204)
-1. **[NLLB](https://huggingface.co/docs/transformers/model_doc/nllb)** (Meta ăă) the NLLB team ăăć
Źéăăăç ç©¶è«æ: [No Language Left Behind: Scaling Human-Centered Machine Translation](https://arxiv.org/abs/2207.04672)
-1. **[Nyströmformer](https://huggingface.co/docs/transformers/model_doc/nystromformer)** (the University of Wisconsin - Madison ăă) Yunyang Xiong, Zhanpeng Zeng, Rudrasis Chakraborty, Mingxing Tan, Glenn Fung, Yin Li, Vikas Singh ăăć
Źéăăăç ç©¶è«æ: [Nyströmformer: A Nyström-Based Algorithm for Approximating Self-Attention](https://arxiv.org/abs/2102.03902)
-1. **[OneFormer](https://huggingface.co/docs/transformers/main/model_doc/oneformer)** (SHI Labs ăă) Jitesh Jain, Jiachen Li, MangTik Chiu, Ali Hassani, Nikita Orlov, Humphrey Shi ăăć
Źéăăăç ç©¶è«æ: [OneFormer: One Transformer to Rule Universal Image Segmentation](https://arxiv.org/abs/2211.06220)
-1. **[OPT](https://huggingface.co/docs/transformers/master/model_doc/opt)** (Meta AI ăă) Susan Zhang, Stephen Roller, Naman Goyal, Mikel Artetxe, Moya Chen, Shuohui Chen et al ăăć
Źéăăăç ç©¶è«æ: [OPT: Open Pre-trained Transformer Language Models](https://arxiv.org/abs/2205.01068)
-1. **[OWL-ViT](https://huggingface.co/docs/transformers/model_doc/owlvit)** (Google AI ăă) 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 ăăć
Źéăăăç ç©¶è«æ: [Simple Open-Vocabulary Object Detection with Vision Transformers](https://arxiv.org/abs/2205.06230)
-1. **[Pegasus](https://huggingface.co/docs/transformers/model_doc/pegasus)** (Google ăă) Jingqing Zhang, Yao Zhao, Mohammad Saleh and Peter J. Liu ăăć
Źéăăăç ç©¶è«æ: [PEGASUS: Pre-training with Extracted Gap-sentences for Abstractive Summarization](https://arxiv.org/abs/1912.08777)
-1. **[PEGASUS-X](https://huggingface.co/docs/transformers/model_doc/pegasus_x)** (Google ăă) Jason Phang, Yao Zhao, and Peter J. Liu ăăć
Źéăăăç ç©¶è«æ: [Investigating Efficiently Extending Transformers for Long Input Summarization](https://arxiv.org/abs/2208.04347)
-1. **[Perceiver IO](https://huggingface.co/docs/transformers/model_doc/perceiver)** (Deepmind ăă) 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 ăăć
Źéăăăç ç©¶è«æ: [Perceiver IO: A General Architecture for Structured Inputs & Outputs](https://arxiv.org/abs/2107.14795)
-1. **[PhoBERT](https://huggingface.co/docs/transformers/model_doc/phobert)** (VinAI Research ăă) Dat Quoc Nguyen and Anh Tuan Nguyen ăăć
Źéăăăç ç©¶è«æ: [PhoBERT: Pre-trained language models for Vietnamese](https://www.aclweb.org/anthology/2020.findings-emnlp.92/)
-1. **[PLBart](https://huggingface.co/docs/transformers/model_doc/plbart)** (UCLA NLP ăă) Wasi Uddin Ahmad, Saikat Chakraborty, Baishakhi Ray, Kai-Wei Chang ăăć
Źéăăăç ç©¶è«æ: [Unified Pre-training for Program Understanding and Generation](https://arxiv.org/abs/2103.06333)
-1. **[PoolFormer](https://huggingface.co/docs/transformers/model_doc/poolformer)** (Sea AI Labs ăă) Yu, Weihao and Luo, Mi and Zhou, Pan and Si, Chenyang and Zhou, Yichen and Wang, Xinchao and Feng, Jiashi and Yan, Shuicheng ăăć
Źéăăăç ç©¶è«æ: [MetaFormer is Actually What You Need for Vision](https://arxiv.org/abs/2111.11418)
-1. **[ProphetNet](https://huggingface.co/docs/transformers/model_doc/prophetnet)** (Microsoft Research ăă) Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang and Ming Zhou ăăć
Źéăăăç ç©¶è«æ: [ProphetNet: Predicting Future N-gram for Sequence-to-Sequence Pre-training](https://arxiv.org/abs/2001.04063)
-1. **[QDQBert](https://huggingface.co/docs/transformers/model_doc/qdqbert)** (NVIDIA ăă) Hao Wu, Patrick Judd, Xiaojie Zhang, Mikhail Isaev and Paulius Micikevicius ăăć
Źéăăăç ç©¶è«æ: [Integer Quantization for Deep Learning Inference: Principles and Empirical Evaluation](https://arxiv.org/abs/2004.09602)
-1. **[RAG](https://huggingface.co/docs/transformers/model_doc/rag)** (Facebook ăă) 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 ăăć
Źéăăăç ç©¶è«æ: [Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks](https://arxiv.org/abs/2005.11401)
-1. **[REALM](https://huggingface.co/docs/transformers/model_doc/realm.html)** (Google Research ăă) Kelvin Guu, Kenton Lee, Zora Tung, Panupong Pasupat and Ming-Wei Chang ăăć
Źéăăăç ç©¶è«æ: [REALM: Retrieval-Augmented Language Model Pre-Training](https://arxiv.org/abs/2002.08909)
-1. **[Reformer](https://huggingface.co/docs/transformers/model_doc/reformer)** (Google Research ăă) Nikita Kitaev, Ćukasz Kaiser, Anselm Levskaya ăăć
Źéăăăç ç©¶è«æ: [Reformer: The Efficient Transformer](https://arxiv.org/abs/2001.04451)
-1. **[RegNet](https://huggingface.co/docs/transformers/model_doc/regnet)** (META Platforms ăă) Ilija Radosavovic, Raj Prateek Kosaraju, Ross Girshick, Kaiming He, Piotr DollĂĄr ăăć
Źéăăăç ç©¶è«æ: [Designing Network Design Space](https://arxiv.org/abs/2003.13678)
-1. **[RemBERT](https://huggingface.co/docs/transformers/model_doc/rembert)** (Google Research ăă) Hyung Won Chung, Thibault FĂ©vry, Henry Tsai, M. Johnson, Sebastian Ruder ăăć
Źéăăăç ç©¶è«æ: [Rethinking embedding coupling in pre-trained language models](https://arxiv.org/abs/2010.12821)
-1. **[ResNet](https://huggingface.co/docs/transformers/model_doc/resnet)** (Microsoft Research ăă) Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun ăăć
Źéăăăç ç©¶è«æ: [Deep Residual Learning for Image Recognition](https://arxiv.org/abs/1512.03385)
-1. **[RoBERTa](https://huggingface.co/docs/transformers/model_doc/roberta)** (Facebook ăă), Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Mandar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, Veselin Stoyanov ăăć
Źéăăăç ç©¶è«æ: [RoBERTa: A Robustly Optimized BERT Pretraining Approach](https://arxiv.org/abs/1907.11692)
-1. **[RoBERTa-PreLayerNorm](https://huggingface.co/docs/transformers/main/model_doc/roberta-prelayernorm)** (Facebook ăă) Myle Ott, Sergey Edunov, Alexei Baevski, Angela Fan, Sam Gross, Nathan Ng, David Grangier, Michael Auli ăăć
Źéăăăç ç©¶è«æ: [fairseq: A Fast, Extensible Toolkit for Sequence Modeling](https://arxiv.org/abs/1904.01038)
-1. **[RoCBert](https://huggingface.co/docs/transformers/main/model_doc/roc_bert)** (WeChatAI ăă) HuiSu, WeiweiShi, XiaoyuShen, XiaoZhou, TuoJi, JiaruiFang, JieZhou ăăć
Źéăăăç ç©¶è«æ: [RoCBert: Robust Chinese Bert with Multimodal Contrastive Pretraining](https://aclanthology.org/2022.acl-long.65.pdf)
-1. **[RoFormer](https://huggingface.co/docs/transformers/model_doc/roformer)** (ZhuiyiTechnology ăă), Jianlin Su and Yu Lu and Shengfeng Pan and Bo Wen and Yunfeng Liu ăăć
Źéăăăç ç©¶è«æ: [RoFormer: Enhanced Transformer with Rotary Position Embedding](https://arxiv.org/abs/2104.09864)
-1. **[SegFormer](https://huggingface.co/docs/transformers/model_doc/segformer)** (NVIDIA ăă) Enze Xie, Wenhai Wang, Zhiding Yu, Anima Anandkumar, Jose M. Alvarez, Ping Luo ăăć
Źéăăăç ç©¶è«æ: [SegFormer: Simple and Efficient Design for Semantic Segmentation with Transformers](https://arxiv.org/abs/2105.15203)
-1. **[SEW](https://huggingface.co/docs/transformers/model_doc/sew)** (ASAPP ăă) Felix Wu, Kwangyoun Kim, Jing Pan, Kyu Han, Kilian Q. Weinberger, Yoav Artzi ăăć
Źéăăăç ç©¶è«æ: [Performance-Efficiency Trade-offs in Unsupervised Pre-training for Speech Recognition](https://arxiv.org/abs/2109.06870)
-1. **[SEW-D](https://huggingface.co/docs/transformers/model_doc/sew_d)** (ASAPP ăă) Felix Wu, Kwangyoun Kim, Jing Pan, Kyu Han, Kilian Q. Weinberger, Yoav Artzi ăăć
Źéăăăç ç©¶è«æ: [Performance-Efficiency Trade-offs in Unsupervised Pre-training for Speech Recognition](https://arxiv.org/abs/2109.06870)
-1. **[SpeechToTextTransformer](https://huggingface.co/docs/transformers/model_doc/speech_to_text)** (Facebook ăă), Changhan Wang, Yun Tang, Xutai Ma, Anne Wu, Dmytro Okhonko, Juan Pino ăăć
Źéăăăç ç©¶è«æ: [fairseq S2T: Fast Speech-to-Text Modeling with fairseq](https://arxiv.org/abs/2010.05171)
-1. **[SpeechToTextTransformer2](https://huggingface.co/docs/transformers/model_doc/speech_to_text_2)** (Facebook ăă), Changhan Wang, Anne Wu, Juan Pino, Alexei Baevski, Michael Auli, Alexis Conneau ăăć
Źéăăăç ç©¶è«æ: [Large-Scale Self- and Semi-Supervised Learning for Speech Translation](https://arxiv.org/abs/2104.06678)
-1. **[Splinter](https://huggingface.co/docs/transformers/model_doc/splinter)** (Tel Aviv University ăă), Ori Ram, Yuval Kirstain, Jonathan Berant, Amir Globerson, Omer Levy ăăć
Źéăăăç ç©¶è«æ: [Few-Shot Question Answering by Pretraining Span Selection](https://arxiv.org/abs/2101.00438)
-1. **[SqueezeBERT](https://huggingface.co/docs/transformers/model_doc/squeezebert)** (Berkeley ăă) Forrest N. Iandola, Albert E. Shaw, Ravi Krishna, and Kurt W. Keutzer ăăć
Źéăăăç ç©¶è«æ: [SqueezeBERT: What can computer vision teach NLP about efficient neural networks?](https://arxiv.org/abs/2006.11316)
-1. **[Swin Transformer](https://huggingface.co/docs/transformers/model_doc/swin)** (Microsoft ăă) Ze Liu, Yutong Lin, Yue Cao, Han Hu, Yixuan Wei, Zheng Zhang, Stephen Lin, Baining Guo ăăć
Źéăăăç ç©¶è«æ: [Swin Transformer: Hierarchical Vision Transformer using Shifted Windows](https://arxiv.org/abs/2103.14030)
-1. **[Swin Transformer V2](https://huggingface.co/docs/transformers/model_doc/swinv2)** (Microsoft ăă) Ze Liu, Han Hu, Yutong Lin, Zhuliang Yao, Zhenda Xie, Yixuan Wei, Jia Ning, Yue Cao, Zheng Zhang, Li Dong, Furu Wei, Baining Guo ăăć
Źéăăăç ç©¶è«æ: [Swin Transformer V2: Scaling Up Capacity and Resolution](https://arxiv.org/abs/2111.09883)
-1. **[Swin2SR](https://huggingface.co/docs/transformers/main/model_doc/swin2sr)** (University of WĂŒrzburg ăă) Marcos V. Conde, Ui-Jin Choi, Maxime Burchi, Radu Timofte ăăć
Źéăăăç ç©¶è«æ: [Swin2SR: SwinV2 Transformer for Compressed Image Super-Resolution and Restoration](https://arxiv.org/abs/2209.11345)
-1. **[SwitchTransformers](https://huggingface.co/docs/transformers/main/model_doc/switch_transformers)** (Google ăă) William Fedus, Barret Zoph, Noam Shazeer ăăć
Źéăăăç ç©¶è«æ: [Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity](https://arxiv.org/abs/2101.03961)
-1. **[T5](https://huggingface.co/docs/transformers/model_doc/t5)** (Google AI ăă) 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 ăăć
Źéăăăç ç©¶è«æ: [Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer](https://arxiv.org/abs/1910.10683)
-1. **[T5v1.1](https://huggingface.co/docs/transformers/model_doc/t5v1.1)** (Google AI ăă) 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 ăăć
ŹéăăăăŹăăžăăȘăŒ [google-research/text-to-text-transfer-transformer](https://github.com/google-research/text-to-text-transfer-transformer/blob/main/released_checkpoints.md#t511)
-1. **[Table Transformer](https://huggingface.co/docs/transformers/model_doc/table-transformer)** (Microsoft Research ăă) Brandon Smock, Rohith Pesala, Robin Abraham ăăć
Źéăăăç ç©¶è«æ: [PubTables-1M: Towards Comprehensive Table Extraction From Unstructured Documents](https://arxiv.org/abs/2110.00061)
-1. **[TAPAS](https://huggingface.co/docs/transformers/model_doc/tapas)** (Google AI ăă) Jonathan Herzig, PaweĆ Krzysztof Nowak, Thomas MĂŒller, Francesco Piccinno and Julian Martin Eisenschlos ăăć
Źéăăăç ç©¶è«æ: [TAPAS: Weakly Supervised Table Parsing via Pre-training](https://arxiv.org/abs/2004.02349)
-1. **[TAPEX](https://huggingface.co/docs/transformers/model_doc/tapex)** (Microsoft Research ăă) Qian Liu, Bei Chen, Jiaqi Guo, Morteza Ziyadi, Zeqi Lin, Weizhu Chen, Jian-Guang Lou ăăć
Źéăăăç ç©¶è«æ: [TAPEX: Table Pre-training via Learning a Neural SQL Executor](https://arxiv.org/abs/2107.07653)
-1. **[Time Series Transformer](https://huggingface.co/docs/transformers/model_doc/time_series_transformer)** (HuggingFace ăă).
-1. **[TimeSformer](https://huggingface.co/docs/transformers/main/model_doc/timesformer)** (Facebook ăă) Gedas Bertasius, Heng Wang, Lorenzo Torresani ăăć
Źéăăăç ç©¶è«æ: [Is Space-Time Attention All You Need for Video Understanding?](https://arxiv.org/abs/2102.05095)
-1. **[Trajectory Transformer](https://huggingface.co/docs/transformers/model_doc/trajectory_transformers)** (the University of California at Berkeley ăă) Michael Janner, Qiyang Li, Sergey Levine ăăć
Źéăăăç ç©¶è«æ: [Offline Reinforcement Learning as One Big Sequence Modeling Problem](https://arxiv.org/abs/2106.02039)
-1. **[Transformer-XL](https://huggingface.co/docs/transformers/model_doc/transfo-xl)** (Google/CMU ăă) Zihang Dai*, Zhilin Yang*, Yiming Yang, Jaime Carbonell, Quoc V. Le, Ruslan Salakhutdinov ăăć
Źéăăăç ç©¶è«æ: [Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context](https://arxiv.org/abs/1901.02860)
-1. **[TrOCR](https://huggingface.co/docs/transformers/model_doc/trocr)** (Microsoft ăă), Minghao Li, Tengchao Lv, Lei Cui, Yijuan Lu, Dinei Florencio, Cha Zhang, Zhoujun Li, Furu Wei ăăć
Źéăăăç ç©¶è«æ: [TrOCR: Transformer-based Optical Character Recognition with Pre-trained Models](https://arxiv.org/abs/2109.10282)
-1. **[UL2](https://huggingface.co/docs/transformers/model_doc/ul2)** (Google Research ăă) Yi Tay, Mostafa Dehghani, Vinh Q ăăć
Źéăăăç ç©¶è«æ: [Unifying Language Learning Paradigms](https://arxiv.org/abs/2205.05131v1) Tran, Xavier Garcia, Dara Bahri, Tal Schuster, Huaixiu Steven Zheng, Neil Houlsby, Donald Metzler
-1. **[UniSpeech](https://huggingface.co/docs/transformers/model_doc/unispeech)** (Microsoft Research ăă) Chengyi Wang, Yu Wu, Yao Qian, Kenichi Kumatani, Shujie Liu, Furu Wei, Michael Zeng, Xuedong Huang ăăć
Źéăăăç ç©¶è«æ: [UniSpeech: Unified Speech Representation Learning with Labeled and Unlabeled Data](https://arxiv.org/abs/2101.07597)
-1. **[UniSpeechSat](https://huggingface.co/docs/transformers/model_doc/unispeech-sat)** (Microsoft Research ăă) Sanyuan Chen, Yu Wu, Chengyi Wang, Zhengyang Chen, Zhuo Chen, Shujie Liu, Jian Wu, Yao Qian, Furu Wei, Jinyu Li, Xiangzhan Yu ăăć
Źéăăăç ç©¶è«æ: [UNISPEECH-SAT: UNIVERSAL SPEECH REPRESENTATION LEARNING WITH SPEAKER AWARE PRE-TRAINING](https://arxiv.org/abs/2110.05752)
-1. **[UPerNet](https://huggingface.co/docs/transformers/main/model_doc/upernet)** (Peking University ăă) Tete Xiao, Yingcheng Liu, Bolei Zhou, Yuning Jiang, Jian Sun. ăăć
Źéăăăç ç©¶è«æ [Unified Perceptual Parsing for Scene Understanding](https://arxiv.org/abs/1807.10221)
-1. **[VAN](https://huggingface.co/docs/transformers/model_doc/van)** (Tsinghua University and Nankai University ăă) Meng-Hao Guo, Cheng-Ze Lu, Zheng-Ning Liu, Ming-Ming Cheng, Shi-Min Hu ăăć
Źéăăăç ç©¶è«æ: [Visual Attention Network](https://arxiv.org/abs/2202.09741)
-1. **[VideoMAE](https://huggingface.co/docs/transformers/model_doc/videomae)** (Multimedia Computing Group, Nanjing University ăă) Zhan Tong, Yibing Song, Jue Wang, Limin Wang ăăć
Źéăăăç ç©¶è«æ: [VideoMAE: Masked Autoencoders are Data-Efficient Learners for Self-Supervised Video Pre-Training](https://arxiv.org/abs/2203.12602)
-1. **[ViLT](https://huggingface.co/docs/transformers/model_doc/vilt)** (NAVER AI Lab/Kakao Enterprise/Kakao Brain ăă) Wonjae Kim, Bokyung Son, Ildoo Kim ăăć
Źéăăăç ç©¶è«æ: [ViLT: Vision-and-Language Transformer Without Convolution or Region Supervision](https://arxiv.org/abs/2102.03334)
-1. **[Vision Transformer (ViT)](https://huggingface.co/docs/transformers/model_doc/vit)** (Google AI ăă) Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xiaohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg Heigold, Sylvain Gelly, Jakob Uszkoreit, Neil Houlsby ăăć
Źéăăăç ç©¶è«æ: [An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale](https://arxiv.org/abs/2010.11929)
-1. **[VisualBERT](https://huggingface.co/docs/transformers/model_doc/visual_bert)** (UCLA NLP ăă) Liunian Harold Li, Mark Yatskar, Da Yin, Cho-Jui Hsieh, Kai-Wei Chang ăăć
Źéăăăç ç©¶è«æ: [VisualBERT: A Simple and Performant Baseline for Vision and Language](https://arxiv.org/pdf/1908.03557)
-1. **[ViT Hybrid](https://huggingface.co/docs/transformers/main/model_doc/vit_hybrid)** (Google AI ăă) Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xiaohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg Heigold, Sylvain Gelly, Jakob Uszkoreit, Neil Houlsby ăăć
Źéăăăç ç©¶è«æ: [An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale](https://arxiv.org/abs/2010.11929)
-1. **[ViTMAE](https://huggingface.co/docs/transformers/model_doc/vit_mae)** (Meta AI ăă) Kaiming He, Xinlei Chen, Saining Xie, Yanghao Li, Piotr DollĂĄr, Ross Girshick ăăć
Źéăăăç ç©¶è«æ: [Masked Autoencoders Are Scalable Vision Learners](https://arxiv.org/abs/2111.06377)
-1. **[ViTMSN](https://huggingface.co/docs/transformers/model_doc/vit_msn)** (Meta AI ăă) Mahmoud Assran, Mathilde Caron, Ishan Misra, Piotr Bojanowski, Florian Bordes, Pascal Vincent, Armand Joulin, Michael Rabbat, Nicolas Ballas ăăć
Źéăăăç ç©¶è«æ: [Masked Siamese Networks for Label-Efficient Learning](https://arxiv.org/abs/2204.07141)
-1. **[Wav2Vec2](https://huggingface.co/docs/transformers/model_doc/wav2vec2)** (Facebook AI ăă) Alexei Baevski, Henry Zhou, Abdelrahman Mohamed, Michael Auli ăăć
Źéăăăç ç©¶è«æ: [wav2vec 2.0: A Framework for Self-Supervised Learning of Speech Representations](https://arxiv.org/abs/2006.11477)
-1. **[Wav2Vec2-Conformer](https://huggingface.co/docs/transformers/model_doc/wav2vec2-conformer)** (Facebook AI ăă) Changhan Wang, Yun Tang, Xutai Ma, Anne Wu, Sravya Popuri, Dmytro Okhonko, Juan Pino ăăć
Źéăăăç ç©¶è«æ: [FAIRSEQ S2T: Fast Speech-to-Text Modeling with FAIRSEQ](https://arxiv.org/abs/2010.05171)
-1. **[Wav2Vec2Phoneme](https://huggingface.co/docs/transformers/model_doc/wav2vec2_phoneme)** (Facebook AI ăă) Qiantong Xu, Alexei Baevski, Michael Auli ăăć
Źéăăăç ç©¶è«æ: [Simple and Effective Zero-shot Cross-lingual Phoneme Recognition](https://arxiv.org/abs/2109.11680)
-1. **[WavLM](https://huggingface.co/docs/transformers/model_doc/wavlm)** (Microsoft Research ăă) 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 ăăć
Źéăăăç ç©¶è«æ: [WavLM: Large-Scale Self-Supervised Pre-Training for Full Stack Speech Processing](https://arxiv.org/abs/2110.13900)
-1. **[Whisper](https://huggingface.co/docs/transformers/model_doc/whisper)** (OpenAI ăă) Alec Radford, Jong Wook Kim, Tao Xu, Greg Brockman, Christine McLeavey, Ilya Sutskever ăăć
Źéăăăç ç©¶è«æ: [Robust Speech Recognition via Large-Scale Weak Supervision](https://cdn.openai.com/papers/whisper.pdf)
-1. **[X-CLIP](https://huggingface.co/docs/transformers/model_doc/xclip)** (Microsoft Research ăă) Bolin Ni, Houwen Peng, Minghao Chen, Songyang Zhang, Gaofeng Meng, Jianlong Fu, Shiming Xiang, Haibin Ling ăăć
Źéăăăç ç©¶è«æ: [Expanding Language-Image Pretrained Models for General Video Recognition](https://arxiv.org/abs/2208.02816)
-1. **[XGLM](https://huggingface.co/docs/transformers/model_doc/xglm)** (From Facebook AI) 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 ăăć
Źéăăăç ç©¶è«æ: [Few-shot Learning with Multilingual Language Models](https://arxiv.org/abs/2112.10668)
-1. **[XLM](https://huggingface.co/docs/transformers/model_doc/xlm)** (Facebook ăă) Guillaume Lample and Alexis Conneau ăăć
Źéăăăç ç©¶è«æ: [Cross-lingual Language Model Pretraining](https://arxiv.org/abs/1901.07291)
-1. **[XLM-ProphetNet](https://huggingface.co/docs/transformers/model_doc/xlm-prophetnet)** (Microsoft Research ăă) Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang and Ming Zhou ăăć
Źéăăăç ç©¶è«æ: [ProphetNet: Predicting Future N-gram for Sequence-to-Sequence Pre-training](https://arxiv.org/abs/2001.04063)
-1. **[XLM-RoBERTa](https://huggingface.co/docs/transformers/model_doc/xlm-roberta)** (Facebook AI ăă), Alexis Conneau*, Kartikay Khandelwal*, Naman Goyal, Vishrav Chaudhary, Guillaume Wenzek, Francisco GuzmĂĄn, Edouard Grave, Myle Ott, Luke Zettlemoyer and Veselin Stoyanov ăăć
Źéăăăç ç©¶è«æ: [Unsupervised Cross-lingual Representation Learning at Scale](https://arxiv.org/abs/1911.02116)
-1. **[XLM-RoBERTa-XL](https://huggingface.co/docs/transformers/model_doc/xlm-roberta-xl)** (Facebook AI ăă), Naman Goyal, Jingfei Du, Myle Ott, Giri Anantharaman, Alexis Conneau ăăć
Źéăăăç ç©¶è«æ: [Larger-Scale Transformers for Multilingual Masked Language Modeling](https://arxiv.org/abs/2105.00572)
-1. **[XLNet](https://huggingface.co/docs/transformers/model_doc/xlnet)** (Google/CMU ăă) Zhilin Yang*, Zihang Dai*, Yiming Yang, Jaime Carbonell, Ruslan Salakhutdinov, Quoc V. Le ăăć
Źéăăăç ç©¶è«æ: [âXLNet: Generalized Autoregressive Pretraining for Language Understanding](https://arxiv.org/abs/1906.08237)
-1. **[XLS-R](https://huggingface.co/docs/transformers/model_doc/xls_r)** (Facebook AI ăă) 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 ăăć
Źéăăăç ç©¶è«æ: [XLS-R: Self-supervised Cross-lingual Speech Representation Learning at Scale](https://arxiv.org/abs/2111.09296)
-1. **[XLSR-Wav2Vec2](https://huggingface.co/docs/transformers/model_doc/xlsr_wav2vec2)** (Facebook AI ăă) Alexis Conneau, Alexei Baevski, Ronan Collobert, Abdelrahman Mohamed, Michael Auli ăăć
Źéăăăç ç©¶è«æ: [Unsupervised Cross-Lingual Representation Learning For Speech Recognition](https://arxiv.org/abs/2006.13979)
-1. **[YOLOS](https://huggingface.co/docs/transformers/model_doc/yolos)** (Huazhong University of Science & Technology ăă) Yuxin Fang, Bencheng Liao, Xinggang Wang, Jiemin Fang, Jiyang Qi, Rui Wu, Jianwei Niu, Wenyu Liu ăăć
Źéăăăç ç©¶è«æ: [You Only Look at One Sequence: Rethinking Transformer in Vision through Object Detection](https://arxiv.org/abs/2106.00666)
-1. **[YOSO](https://huggingface.co/docs/transformers/model_doc/yoso)** (the University of Wisconsin - Madison ăă) Zhanpeng Zeng, Yunyang Xiong, Sathya N. Ravi, Shailesh Acharya, Glenn Fung, Vikas Singh ăăć
Źéăăăç ç©¶è«æ: [You Only Sample (Almost) Once: Linear Cost Self-Attention Via Bernoulli Sampling](https://arxiv.org/abs/2111.09714)
-
-
-### ă”ăăŒăăăăŠăăăăŹăŒă ăŻăŒăŻ
-
-仄äžăźăăŒăă«ăŻăăăăăźăąăă«ă§ă”ăăŒăăăăŠăăă©ă€ăă©ăȘăç€șăăŠăăŸăă"slow"ăšćŒă°ăăPythonăăŒăŻăă€ă¶ăŒăđ€ Tokenizers ă©ă€ăă©ăȘă«ăă"fast"ăăŒăŻăă€ă¶ăŒăPyTorch, TensorFlow, Flaxăź5ă€ăźăăăăăă”ăăŒăăăăŠăăăăç€șăăŠăăŸăă
-
-
-
-| Model | Tokenizer slow | Tokenizer fast | PyTorch support | TensorFlow support | Flax Support |
-|:-----------------------------:|:--------------:|:--------------:|:---------------:|:------------------:|:------------:|
-| ALBERT | â
| â
| â
| â
| â
|
-| AltCLIP | â | â | â
| â | â |
-| Audio Spectrogram Transformer | â | â | â
| â | â |
-| BART | â
| â
| â
| â
| â
|
-| BEiT | â | â | â
| â | â
|
-| BERT | â
| â
| â
| â
| â
|
-| Bert Generation | â
| â | â
| â | â |
-| BigBird | â
| â
| â
| â | â
|
-| BigBird-Pegasus | â | â | â
| â | â |
-| BioGpt | â
| â | â
| â | â |
-| BiT | â | â | â
| â | â |
-| Blenderbot | â
| â
| â
| â
| â
|
-| BlenderbotSmall | â
| â
| â
| â
| â
|
-| BLIP | â | â | â
| â | â |
-| BLOOM | â | â
| â
| â | â |
-| CamemBERT | â
| â
| â
| â
| â |
-| CANINE | â
| â | â
| â | â |
-| Chinese-CLIP | â | â | â
| â | â |
-| CLIP | â
| â
| â
| â
| â
|
-| CLIPSeg | â | â | â
| â | â |
-| CodeGen | â
| â
| â
| â | â |
-| Conditional DETR | â | â | â
| â | â |
-| ConvBERT | â
| â
| â
| â
| â |
-| ConvNeXT | â | â | â
| â
| â |
-| CTRL | â
| â | â
| â
| â |
-| CvT | â | â | â
| â
| â |
-| Data2VecAudio | â | â | â
| â | â |
-| Data2VecText | â | â | â
| â | â |
-| Data2VecVision | â | â | â
| â
| â |
-| DeBERTa | â
| â
| â
| â
| â |
-| DeBERTa-v2 | â
| â
| â
| â
| â |
-| Decision Transformer | â | â | â
| â | â |
-| Deformable DETR | â | â | â
| â | â |
-| DeiT | â | â | â
| â
| â |
-| DETR | â | â | â
| â | â |
-| DiNAT | â | â | â
| â | â |
-| DistilBERT | â
| â
| â
| â
| â
|
-| DonutSwin | â | â | â
| â | â |
-| DPR | â
| â
| â
| â
| â |
-| DPT | â | â | â
| â | â |
-| ELECTRA | â
| â
| â
| â
| â
|
-| Encoder decoder | â | â | â
| â
| â
|
-| ERNIE | â | â | â
| â | â |
-| ESM | â
| â | â
| â
| â |
-| FairSeq Machine-Translation | â
| â | â
| â | â |
-| FlauBERT | â
| â | â
| â
| â |
-| FLAVA | â | â | â
| â | â |
-| FNet | â
| â
| â
| â | â |
-| Funnel Transformer | â
| â
| â
| â
| â |
-| GIT | â | â | â
| â | â |
-| GLPN | â | â | â
| â | â |
-| GPT Neo | â | â | â
| â | â
|
-| GPT NeoX | â | â
| â
| â | â |
-| GPT NeoX Japanese | â
| â | â
| â | â |
-| GPT-J | â | â | â
| â
| â
|
-| GPT-Sw3 | â
| â
| â
| â
| â
|
-| GroupViT | â | â | â
| â
| â |
-| Hubert | â | â | â
| â
| â |
-| I-BERT | â | â | â
| â | â |
-| ImageGPT | â | â | â
| â | â |
-| Jukebox | â
| â | â
| â | â |
-| LayoutLM | â
| â
| â
| â
| â |
-| LayoutLMv2 | â
| â
| â
| â | â |
-| LayoutLMv3 | â
| â
| â
| â
| â |
-| LED | â
| â
| â
| â
| â |
-| LeViT | â | â | â
| â | â |
-| LiLT | â | â | â
| â | â |
-| Longformer | â
| â
| â
| â
| â |
-| LongT5 | â | â | â
| â | â
|
-| LUKE | â
| â | â
| â | â |
-| LXMERT | â
| â
| â
| â
| â |
-| M-CTC-T | â | â | â
| â | â |
-| M2M100 | â
| â | â
| â | â |
-| Marian | â
| â | â
| â
| â
|
-| MarkupLM | â
| â
| â
| â | â |
-| Mask2Former | â | â | â
| â | â |
-| MaskFormer | â | â | â
| â | â |
-| MaskFormerSwin | â | â | â | â | â |
-| mBART | â
| â
| â
| â
| â
|
-| Megatron-BERT | â | â | â
| â | â |
-| MobileBERT | â
| â
| â
| â
| â |
-| MobileNetV1 | â | â | â
| â | â |
-| MobileNetV2 | â | â | â
| â | â |
-| MobileViT | â | â | â
| â
| â |
-| MPNet | â
| â
| â
| â
| â |
-| MT5 | â
| â
| â
| â
| â
|
-| MVP | â
| â
| â
| â | â |
-| NAT | â | â | â
| â | â |
-| Nezha | â | â | â
| â | â |
-| Nyströmformer | â | â | â
| â | â |
-| OpenAI GPT | â
| â
| â
| â
| â |
-| OpenAI GPT-2 | â
| â
| â
| â
| â
|
-| OPT | â | â | â
| â
| â
|
-| OWL-ViT | â | â | â
| â | â |
-| Pegasus | â
| â
| â
| â
| â
|
-| PEGASUS-X | â | â | â
| â | â |
-| Perceiver | â
| â | â
| â | â |
-| PLBart | â
| â | â
| â | â |
-| PoolFormer | â | â | â
| â | â |
-| ProphetNet | â
| â | â
| â | â |
-| QDQBert | â | â | â
| â | â |
-| RAG | â
| â | â
| â
| â |
-| REALM | â
| â
| â
| â | â |
-| Reformer | â
| â
| â
| â | â |
-| RegNet | â | â | â
| â
| â
|
-| RemBERT | â
| â
| â
| â
| â |
-| ResNet | â | â | â
| â
| â
|
-| RetriBERT | â
| â
| â
| â | â |
-| RoBERTa | â
| â
| â
| â
| â
|
-| RoBERTa-PreLayerNorm | â | â | â
| â
| â
|
-| RoCBert | â
| â | â
| â | â |
-| RoFormer | â
| â
| â
| â
| â
|
-| SegFormer | â | â | â
| â
| â |
-| SEW | â | â | â
| â | â |
-| SEW-D | â | â | â
| â | â |
-| Speech Encoder decoder | â | â | â
| â | â
|
-| Speech2Text | â
| â | â
| â
| â |
-| Speech2Text2 | â
| â | â | â | â |
-| Splinter | â
| â
| â
| â | â |
-| SqueezeBERT | â
| â
| â
| â | â |
-| Swin Transformer | â | â | â
| â
| â |
-| Swin Transformer V2 | â | â | â
| â | â |
-| Swin2SR | â | â | â
| â | â |
-| SwitchTransformers | â | â | â
| â | â |
-| T5 | â
| â
| â
| â
| â
|
-| Table Transformer | â | â | â
| â | â |
-| TAPAS | â
| â | â
| â
| â |
-| Time Series Transformer | â | â | â
| â | â |
-| TimeSformer | â | â | â
| â | â |
-| Trajectory Transformer | â | â | â
| â | â |
-| Transformer-XL | â
| â | â
| â
| â |
-| TrOCR | â | â | â
| â | â |
-| UniSpeech | â | â | â
| â | â |
-| UniSpeechSat | â | â | â
| â | â |
-| UPerNet | â | â | â
| â | â |
-| VAN | â | â | â
| â | â |
-| VideoMAE | â | â | â
| â | â |
-| ViLT | â | â | â
| â | â |
-| Vision Encoder decoder | â | â | â
| â
| â
|
-| VisionTextDualEncoder | â | â | â
| â | â
|
-| VisualBERT | â | â | â
| â | â |
-| ViT | â | â | â
| â
| â
|
-| ViT Hybrid | â | â | â
| â | â |
-| ViTMAE | â | â | â
| â
| â |
-| ViTMSN | â | â | â
| â | â |
-| Wav2Vec2 | â
| â | â
| â
| â
|
-| Wav2Vec2-Conformer | â | â | â
| â | â |
-| WavLM | â | â | â
| â | â |
-| Whisper | â
| â | â
| â
| â |
-| X-CLIP | â | â | â
| â | â |
-| XGLM | â
| â
| â
| â
| â
|
-| XLM | â
| â | â
| â
| â |
-| XLM-ProphetNet | â
| â | â
| â | â |
-| XLM-RoBERTa | â
| â
| â
| â
| â
|
-| XLM-RoBERTa-XL | â | â | â
| â | â |
-| XLNet | â
| â
| â
| â
| â |
-| YOLOS | â | â | â
| â | â |
-| YOSO | â | â | â
| â | â |
-
-
\ No newline at end of file
diff --git a/docs/source/ja/installation.md b/docs/source/ja/installation.md
new file mode 100644
index 000000000000..3b8646672e52
--- /dev/null
+++ b/docs/source/ja/installation.md
@@ -0,0 +1,244 @@
+
+
+# ă€ăłăčăăŒă«
+
+äœżçšăăŠăăDeep Learningă©ă€ăă©ăȘă«ćŻŸăăŠăđ€ Transformersăă€ăłăčăăŒă«ăăŠăăŁăă·ă„ăèšćźăăăăŠăȘăă·ă§ăłă§ăȘăă©ă€ăłă§ćźèĄă§ăăăăă« đ€ TransformersăèšćźăăŸăă
+
+đ€ TransformersăŻPython 3.6+, PyTorch 1.1.0+, TensorFlow 2.0+, Flaxă§ćäœçąșèȘăăŠăăŸăă äœżçšăăŠăăDeep Learningă©ă€ăă©ăȘă«ćăăăŠă仄äžăźă€ăłăčăăŒă«æčæłă«ćŸăŁăŠăă ăă:
+
+* [PyTorch](https://pytorch.org/get-started/locally/)ăźă€ăłăčăăŒă«æé ă
+* [TensorFlow 2.0](https://www.tensorflow.org/install/pip)ăźă€ăłăčăăŒă«æé ă
+* [Flax](https://flax.readthedocs.io/en/latest/)ăźă€ăłăčăăŒă«æé ă
+
+## pipă§ăźă€ăłăčăăŒă«
+
+đ€ Transformersă[仟æłç°ćą](https://docs.python.org/3/library/venv.html)ă«ă€ăłăčăăŒă«ăăćż
èŠăăăăŸăă ăăăPythonăźä»źæłç°ćąă«éŠŽæăżăăȘăć ŽćăŻăăăź[ăŹă€ă](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/)ăă芧ăă ăăă仟æłç°ćąă«ăăŁăŠç°ăȘăăăăžă§ăŻăăźçźĄçăăăç°Ąćă«ăȘăăäŸćéąäżéăźäșææ§ăźćéĄăćéżă§ăăŸăă
+
+ăŸăăăăăžă§ăŻăăăŁăŹăŻăăȘă«ä»źæłç°ćąăäœæăăăăšăăć§ăăŸăăă:
+
+```bash
+python -m venv .env
+```
+
+仟æłç°ćąăè”·ćăăŸăăăăLinuxăšMacOsăźć ŽćăŻä»„äžăźăłăăłăă§è”·ćăăŸă:
+
+```bash
+source .env/bin/activate
+```
+Windowsă§ä»źæłç°ćąăè”·ćăăŸă
+
+```bash
+.env/Scripts/activate
+```
+
+ăăă§ăæŹĄăźăłăăłăă§đ€ Transformersăă€ăłăčăăŒă«ăăæșćăæŽăăŸăă:
+
+```bash
+pip install transformers
+```
+
+CPUćŻŸćżăźăżćż
èŠăȘć Žćăđ€ TransformersăšDeep Learningă©ă€ăă©ăȘă1èĄă§ă€ăłăčăăŒă«ă§ăăăăă«ăȘăŁăŠăăŠäŸżć©ă§ăăäŸăă°ăđ€ TransformersăšPyTorchă仄äžăźăăă«äžç·ă«ă€ăłăčăăŒă«ă§ăăŸă:
+
+```bash
+pip install transformers[torch]
+```
+
+đ€ TransformersăšTensorFlow 2.0:
+
+```bash
+pip install transformers[tf-cpu]
+```
+
+đ€ TransformersăšFlax:
+
+```bash
+pip install transformers[flax]
+```
+
+æćŸă«ă仄äžăźăłăăłăăćźèĄăăăăšă§đ€ TransformersăæŁăăă€ăłăčăăŒă«ăăăŠăăăăçąșèȘăăŸăăćŠçżæžăżăąăă«ăăăŠăłăăŒăăăăŸă:
+
+```bash
+python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('we love you'))"
+```
+
+ăăźćŸăă©ăă«ăšăčăłăąăćșćăăăŸă:
+
+```bash
+[{'label': 'POSITIVE', 'score': 0.9998704791069031}]
+```
+
+## ăœăŒăčăăăźă€ăłăčăăŒă«
+
+仄äžăźăłăăłăă§ăœăŒăčăăđ€ Transformersăă€ăłăčăăŒă«ăăŸă:
+
+```bash
+pip install git+https://github.com/huggingface/transformers
+```
+
+ăăźăłăăłăăŻææ°ăźćźćźçă§ăŻăȘăăéçșă«ăăăææ°ăź`main`ăăŒăžă§ăłăă€ăłăčăăŒă«ăăŸăă`main`ăăŒăžă§ăłăŻææ°ăźéçșç¶æłă«ćŻŸćżăăăźă«äŸżć©ă§ăăäŸăă°ăæćŸăźć
ŹćŒăȘăȘăŒăč仄éă«ăă°ăäżźæŁăăăăăæ°ăăăȘăȘăŒăčăăŸă ć±éăăăŠăăȘăć ŽćăȘă©ă§ăăăăăăăăăŻ`main`ăăŒăžă§ăłăćžžă«ćźćźăăŠăăăšăŻéăăȘăăăšăæćłăăŸăăç§ăăĄăŻ`main`ăăŒăžă§ăłăźéçšăç¶æăăăăćȘăăă»ăšăă©ăźćéĄăŻéćžžăæ°æéăă1æ„仄ć
ă«è§Łæ±șăăăŸăăăăćéĄă«ééăăć ŽćăŻăăăæ©ăäżźæŁă§ăăăăă«[Issue](https://github.com/huggingface/transformers/issues)ăäœæăăŠăă ăăïŒ
+
+仄äžăźăłăăłăăćźèĄăăŠăđ€ TransformersăæŁăăă€ăłăčăăŒă«ăăăŠăăăă©ăăăçąșèȘăăŸă:
+
+```bash
+python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('I love you'))"
+```
+
+## ç·šéćŻèœăȘă€ăłăčăăŒă«
+
+ćż
èŠă«ćżăăŠăç·šéćŻèœăȘă€ăłăčăăŒă«ăăăŸă:
+
+* ăœăŒăčăłăŒăăź`main`ăăŒăžă§ăłăäœżăăŸăă
+* đ€ Transformersă«ăłăłăăȘăă„ăŒăăăăłăŒăăźć€æŽăăăčăăăćż
èŠăăăăŸăă
+
+仄äžăźăłăăłăă§ăŹăăžăăȘăăŻăăŒăłăăŠăđ€ Transformersăă€ăłăčăăŒă«ăăŸă:
+
+```bash
+git clone https://github.com/huggingface/transformers.git
+cd transformers
+pip install -e .
+```
+
+äžèšăźăłăăłăăŻăăŹăăžăăȘăăŻăăŒăłăăăă©ă«ăăšPythonăźă©ă€ăă©ăȘăăăčăăȘăłăŻăăŸăăPythonăŻéćžžăźă©ă€ăă©ăȘăăčă«ć ăăŠăăăȘăăăŻăăŒăłăăăă©ă«ăăźäžăèŠăăăă«ăȘăăŸăăäŸăă°ăPythonăăă±ăŒăžăéćžžă`~/anaconda3/envs/main/lib/python3.7/site-packages/`ă«ă€ăłăčăăŒă«ăăăŠăăć ŽćăPythonăŻăŻăăŒăłăăăă©ă«ăăæ€çŽąăăăăă«ăȘăăŸă: `~/transformers/`.
+
+
+
+ă©ă€ăă©ăȘăŒăäœżăç¶ăăăć ŽćăŻătransformersăă©ă«ăăŒăäżæăă€ă„ăăćż
èŠăăăăŸăă
+
+
+
+ăăă§ăæŹĄăźăłăăłăă§ç°Ąćă«ăŻăăŒăłăđ€ Transformersăźææ°çă«æŽæ°ă§ăăŸă:
+
+```bash
+cd ~/transformers/
+git pull
+```
+
+Pythonç°ćąăŻæŹĄćăźćźèĄæă«đ€ Transformersăź`main`ăăŒăžă§ăłăèŠă€ăăăăă«ăȘăăŸăă
+
+## condaă§ăźă€ăłăčăăŒă«
+
+`huggingface`ăźcondaăăŁăłăă«ăăă€ăłăčăăŒă«ăăŸă:
+
+```bash
+conda install -c huggingface transformers
+```
+
+## ăăŁăă·ă„ăźèšćź
+
+ćŠçżæžăżăąăă«ăŻăăŠăłăăŒăăăăăăŒă«ă«ă«ăăŁăă·ă„ăăăŸă: `~/.cache/huggingface/hub`. ăăăŻă·ă§ă«ç°ćąć€æ°`TRANSFORMERS_CACHE`ă§æćźăăăăăă©ă«ăăźăăŁăŹăŻăăȘă§ăăWindowsă§ăŻăăăă©ă«ăăźăăŁăŹăŻăăȘăŻ`C:\Users\username\.cache\huggingface\hub`ă«ăȘăŁăŠăăŸăăç°ăȘăăăŁăă·ă„ăăŁăŹăŻăăȘăæćźăăăăă«ă仄äžăźă·ă§ă«ç°ćąć€æ°ă〿ŽăăăăšăćŻèœă§ăăćȘć
ćșŠăŻä»„äžăźé çȘă«ćŻŸćżăăŸă:
+
+1. ă·ă§ă«ç°ćąć€æ° (ăăă©ă«ă): `HUGGINGFACE_HUB_CACHE` ăŸă㯠`TRANSFORMERS_CACHE`.
+2. ă·ă§ă«ç°ćąć€æ°: `HF_HOME`.
+3. ă·ă§ă«ç°ćąć€æ°: `XDG_CACHE_HOME` + `/huggingface`.
+
+
+
+ăăă仄ćăźăăŒăžă§ăłăźă©ă€ăă©ăȘăäœżçšăăŠăăäșșă§ă`PYTORCH_TRANSFORMERS_CACHE`ăŸăăŻ`PYTORCH_PRETRAINED_BERT_CACHE`ăèšćźăăŠăăć Žćăă·ă§ă«ç°ćąć€æ°`TRANSFORMERS_CACHE`ăæćźăăȘăéăđ€ TransformersăŻăăăăźă·ă§ă«ç°ćąć€æ°ăäœżçšăăŸăă
+
+
+
+## ăȘăă©ă€ăłăąăŒă
+
+đ€ TransformersăŻăăŒă«ă«ăăĄă€ă«ăźăżăäœżçšăăăăšă§ăăĄă€ăąăŠă©ăŒă«ăăȘăă©ă€ăłăźç°ćąă§ăćäœăăăăăšăă§ăăŸăăăăźćäœăæćčă«ăăăăă«ăŻăç°ćąć€æ°`TRANSFORMERS_OFFLINE=1`ăèšćźăăŸăă
+
+
+
+ç°ćąć€æ°`HF_DATASETS_OFFLINE=1`ăèšćźăăăȘăă©ă€ăłăăŹăŒăăłă°ăŻăŒăŻăăăŒă«[đ€ Datasets](https://huggingface.co/docs/datasets/)ăèżœć ăăŸăă
+
+
+
+äŸăă°ăć€éšă€ăłăčăżăłăčă«ćŻŸăăŠăăĄă€ăąăŠă©ăŒă«ă§äżè·ăăăéćžžăźăăăăŻăŒăŻäžă§ăăă°ă©ă ăćźèĄăăć Žćăé枞仄äžăźăăăȘăłăăłăă§ćźèĄăăăăšă«ăȘăăŸă:
+
+```bash
+python examples/pytorch/translation/run_translation.py --model_name_or_path t5-small --dataset_name wmt16 --dataset_config ro-en ...
+```
+
+ăȘăă©ă€ăłă€ăłăčăżăłăčă§ăăźćăăăă°ă©ă ăćźèĄăăŸă:
+
+```bash
+HF_DATASETS_OFFLINE=1 TRANSFORMERS_OFFLINE=1 \
+python examples/pytorch/translation/run_translation.py --model_name_or_path t5-small --dataset_name wmt16 --dataset_config ro-en ...
+```
+
+ăăźăčăŻăȘăăăŻăăăŒă«ă«ăăĄă€ă«ăźăżăæ€çŽąăăăăšăćăăŁăŠăăăźă§ăăăłă°ăąăăăăăăżă€ă ăąăŠăăćŸ
ăŁăăăăăăšăȘăćźèĄăăăăŻăă§ăă
+
+### ăȘăă©ă€ăłă§äœżçšăăăăă«ăąăă«ăăăŒăŻăă€ă¶ăŒăććŸăă
+
+ăȘăă©ă€ăłă§đ€ Transformersăäœżçšăăăă1ă€ăźæčæłăŻăćăăŁăŠăăĄă€ă«ăăăŠăłăăŒăăăŠăăăăȘăă©ă€ăłă§äœżçšăăćż
èŠăăăăšăă«ăăźăăŒă«ă«ăăčăæćźăăăăšă§ăăăăă«ăŻ3ă€ăźæčæłăăăăŸă:
+
+* [Model Hub](https://huggingface.co/models)ăźăŠăŒă¶ăŒă€ăłăżăŒăă§ăŒăčäžăăâăąă€ăłăłăăŻăȘăăŻăăŠăăĄă€ă«ăăăŠăłăăŒăăăæčæłă
+
+ 
+
+* [`PreTrainedModel.from_pretrained`]ăăăł[`PreTrainedModel.save_pretrained`]ăźăŻăŒăŻăăăŒăäœżçšăăæčæł:
+
+ 1. [`PreTrainedModel.from_pretrained`]ă§ćăăŁăŠăăĄă€ă«ăăăŠăłăăŒăăăŸă:
+
+ ```py
+ >>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("bigscience/T0_3B")
+ >>> model = AutoModelForSeq2SeqLM.from_pretrained("bigscience/T0_3B")
+ ```
+
+ 2. [`PreTrainedModel.save_pretrained`]ă§æćźăăăăăŁăŹăŻăăȘă«ăăĄă€ă«ăäżćăăŠăăăŸă:
+
+ ```py
+ >>> tokenizer.save_pretrained("./your/path/bigscience_t0")
+ >>> model.save_pretrained("./your/path/bigscience_t0")
+ ```
+
+ 3. ăȘăă©ă€ăłă«ăăæă[`PreTrainedModel.from_pretrained`]ă«æćźăăăăŁăŹăŻăăȘăăăăĄă€ă«ăăȘăăŒăăăŸă:
+
+ ```py
+ >>> tokenizer = AutoTokenizer.from_pretrained("./your/path/bigscience_t0")
+ >>> model = AutoModel.from_pretrained("./your/path/bigscience_t0")
+ ```
+
+* ăăă°ă©ă çă«[huggingface_hub](https://github.com/huggingface/huggingface_hub/tree/main/src/huggingface_hub)ă©ă€ăă©ăȘăçšăăŠăăăĄă€ă«ăăăŠăłăăŒăăăæčæł:
+
+ 1. 仟æłç°ćąă«`huggingface_hub`ă©ă€ăă©ăȘăă€ăłăčăăŒă«ăăŸă:
+
+ ```bash
+ python -m pip install huggingface_hub
+ ```
+
+ 2. æćźăźăăčă«ăăĄă€ă«ăăăŠăłăăŒăăăăăă«ă[`hf_hub_download`](https://huggingface.co/docs/hub/adding-a-library#download-files-from-the-hub)éąæ°ăäœżçšăăŸăăäŸăă°ă仄äžăźăłăăłăă§ă[T0](https://huggingface.co/bigscience/T0_3B)ăąăă«ăź`config.json`ăăĄă€ă«ăæćźăźăăčă«ăăŠăłăăŒăă§ăăŸă:
+
+ ```py
+ >>> from huggingface_hub import hf_hub_download
+
+ >>> hf_hub_download(repo_id="bigscience/T0_3B", filename="config.json", cache_dir="./your/path/bigscience_t0")
+ ```
+
+ăăĄă€ă«ăăăŠăłăăŒăăăăăăŒă«ă«ă«ăăŁăă·ă„ăăăăăăăźăăŒă«ă«ăăčăæćźăăŠăăĄă€ă«ăăăŒăăăŠäœżçšăăŸă:
+
+```py
+>>> from transformers import AutoConfig
+
+>>> config = AutoConfig.from_pretrained("./your/path/bigscience_t0/config.json")
+```
+
+
+
+Hubă«äżćăăăŠăăăăĄă€ă«ăăăŠăłăăŒăăăæčæłăźè©łçްă«ă€ăăŠăŻă[How to download files from the Hub](https://huggingface.co/docs/hub/how-to-downstream)ă»ăŻă·ă§ăłăćç
§ăăŠăă ăăă
+
+
\ No newline at end of file
diff --git a/docs/source/ja/installation.mdx b/docs/source/ja/installation.mdx
deleted file mode 100644
index 0ae6cad52d09..000000000000
--- a/docs/source/ja/installation.mdx
+++ /dev/null
@@ -1,240 +0,0 @@
-
-
-# ă€ăłăčăăŒă«
-
-äœżçšăăŠăăDeep Learningă©ă€ăă©ăȘă«ćŻŸăăŠăđ€ Transformersăă€ăłăčăăŒă«ăăŠăăŁăă·ă„ăèšćźăăăăŠăȘăă·ă§ăłă§ăȘăă©ă€ăłă§ćźèĄă§ăăăăă« đ€ TransformersăèšćźăăŸăă
-
-đ€ TransformersăŻPython 3.6+, PyTorch 1.1.0+, TensorFlow 2.0+, Flaxă§ćäœçąșèȘăăŠăăŸăă äœżçšăăŠăăDeep Learningă©ă€ăă©ăȘă«ćăăăŠă仄äžăźă€ăłăčăăŒă«æčæłă«ćŸăŁăŠăă ăă:
-
-* [PyTorch](https://pytorch.org/get-started/locally/)ăźă€ăłăčăăŒă«æé ă
-* [TensorFlow 2.0](https://www.tensorflow.org/install/pip)ăźă€ăłăčăăŒă«æé ă
-* [Flax](https://flax.readthedocs.io/en/latest/)ăźă€ăłăčăăŒă«æé ă
-
-## pipă§ăźă€ăłăčăăŒă«
-
-đ€ Transformersă[仟æłç°ćą](https://docs.python.org/3/library/venv.html)ă«ă€ăłăčăăŒă«ăăćż
èŠăăăăŸăă ăăăPythonăźä»źæłç°ćąă«éŠŽæăżăăȘăć ŽćăŻăăăź[ăŹă€ă](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/)ăă芧ăă ăăă仟æłç°ćąă«ăăŁăŠç°ăȘăăăăžă§ăŻăăźçźĄçăăăç°Ąćă«ăȘăăäŸćéąäżéăźäșææ§ăźćéĄăćéżă§ăăŸăă
-
-ăŸăăăăăžă§ăŻăăăŁăŹăŻăăȘă«ä»źæłç°ćąăäœæăăăăšăăć§ăăŸăăă:
-
-```bash
-python -m venv .env
-```
-
-仟æłç°ćąăè”·ćăăŸăăăăLinuxăšMacOsăźć ŽćăŻä»„äžăźăłăăłăă§è”·ćăăŸă:
-
-```bash
-source .env/bin/activate
-```
-Windowsă§ä»źæłç°ćąăè”·ćăăŸă
-
-```bash
-.env/Scripts/activate
-```
-
-ăăă§ăæŹĄăźăłăăłăă§đ€ Transformersăă€ăłăčăăŒă«ăăæșćăæŽăăŸăă:
-
-```bash
-pip install transformers
-```
-
-CPUćŻŸćżăźăżćż
èŠăȘć Žćăđ€ TransformersăšDeep Learningă©ă€ăă©ăȘă1èĄă§ă€ăłăčăăŒă«ă§ăăăăă«ăȘăŁăŠăăŠäŸżć©ă§ăăäŸăă°ăđ€ TransformersăšPyTorchă仄äžăźăăă«äžç·ă«ă€ăłăčăăŒă«ă§ăăŸă:
-
-```bash
-pip install transformers[torch]
-```
-
-đ€ TransformersăšTensorFlow 2.0:
-
-```bash
-pip install transformers[tf-cpu]
-```
-
-đ€ TransformersăšFlax:
-
-```bash
-pip install transformers[flax]
-```
-
-æćŸă«ă仄äžăźăłăăłăăćźèĄăăăăšă§đ€ TransformersăæŁăăă€ăłăčăăŒă«ăăăŠăăăăçąșèȘăăŸăăćŠçżæžăżăąăă«ăăăŠăłăăŒăăăăŸă:
-
-```bash
-python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('we love you'))"
-```
-
-ăăźćŸăă©ăă«ăšăčăłăąăćșćăăăŸă:
-
-```bash
-[{'label': 'POSITIVE', 'score': 0.9998704791069031}]
-```
-
-## ăœăŒăčăăăźă€ăłăčăăŒă«
-
-仄äžăźăłăăłăă§ăœăŒăčăăđ€ Transformersăă€ăłăčăăŒă«ăăŸă:
-
-```bash
-pip install git+https://github.com/huggingface/transformers
-```
-
-ăăźăłăăłăăŻææ°ăźćźćźçă§ăŻăȘăăéçșă«ăăăææ°ăź`main`ăăŒăžă§ăłăă€ăłăčăăŒă«ăăŸăă`main`ăăŒăžă§ăłăŻææ°ăźéçșç¶æłă«ćŻŸćżăăăźă«äŸżć©ă§ăăäŸăă°ăæćŸăźć
ŹćŒăȘăȘăŒăč仄éă«ăă°ăäżźæŁăăăăăæ°ăăăȘăȘăŒăčăăŸă ć±éăăăŠăăȘăć ŽćăȘă©ă§ăăăăăăăăăŻ`main`ăăŒăžă§ăłăćžžă«ćźćźăăŠăăăšăŻéăăȘăăăšăæćłăăŸăăç§ăăĄăŻ`main`ăăŒăžă§ăłăźéçšăç¶æăăăăćȘăăă»ăšăă©ăźćéĄăŻéćžžăæ°æéăă1æ„仄ć
ă«è§Łæ±șăăăŸăăăăćéĄă«ééăăć ŽćăŻăăăæ©ăäżźæŁă§ăăăăă«[Issue](https://github.com/huggingface/transformers/issues)ăäœæăăŠăă ăăïŒ
-
-仄äžăźăłăăłăăćźèĄăăŠăđ€ TransformersăæŁăăă€ăłăčăăŒă«ăăăŠăăăă©ăăăçąșèȘăăŸă:
-
-```bash
-python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('I love you'))"
-```
-
-## ç·šéćŻèœăȘă€ăłăčăăŒă«
-
-ćż
èŠă«ćżăăŠăç·šéćŻèœăȘă€ăłăčăăŒă«ăăăŸă:
-
-* ăœăŒăčăłăŒăăź`main`ăăŒăžă§ăłăäœżăăŸăă
-* đ€ Transformersă«ăłăłăăȘăă„ăŒăăăăłăŒăăźć€æŽăăăčăăăćż
èŠăăăăŸăă
-
-仄äžăźăłăăłăă§ăŹăăžăăȘăăŻăăŒăłăăŠăđ€ Transformersăă€ăłăčăăŒă«ăăŸă:
-
-```bash
-git clone https://github.com/huggingface/transformers.git
-cd transformers
-pip install -e .
-```
-
-äžèšăźăłăăłăăŻăăŹăăžăăȘăăŻăăŒăłăăăă©ă«ăăšPythonăźă©ă€ăă©ăȘăăăčăăȘăłăŻăăŸăăPythonăŻéćžžăźă©ă€ăă©ăȘăăčă«ć ăăŠăăăȘăăăŻăăŒăłăăăă©ă«ăăźäžăèŠăăăă«ăȘăăŸăăäŸăă°ăPythonăăă±ăŒăžăéćžžă`~/anaconda3/envs/main/lib/python3.7/site-packages/`ă«ă€ăłăčăăŒă«ăăăŠăăć ŽćăPythonăŻăŻăăŒăłăăăă©ă«ăăæ€çŽąăăăăă«ăȘăăŸă: `~/transformers/`.
-
-
-
-ă©ă€ăă©ăȘăŒăäœżăç¶ăăăć ŽćăŻătransformersăă©ă«ăăŒăäżæăă€ă„ăăćż
èŠăăăăŸăă
-
-
-
-ăăă§ăæŹĄăźăłăăłăă§ç°Ąćă«ăŻăăŒăłăđ€ Transformersăźææ°çă«æŽæ°ă§ăăŸă:
-
-```bash
-cd ~/transformers/
-git pull
-```
-
-Pythonç°ćąăŻæŹĄćăźćźèĄæă«đ€ Transformersăź`main`ăăŒăžă§ăłăèŠă€ăăăăă«ăȘăăŸăă
-
-## condaă§ăźă€ăłăčăăŒă«
-
-`huggingface`ăźcondaăăŁăłăă«ăăă€ăłăčăăŒă«ăăŸă:
-
-```bash
-conda install -c huggingface transformers
-```
-
-## ăăŁăă·ă„ăźèšćź
-
-ćŠçżæžăżăąăă«ăŻăăŠăłăăŒăăăăăăŒă«ă«ă«ăăŁăă·ă„ăăăŸă: `~/.cache/huggingface/hub`. ăăăŻă·ă§ă«ç°ćąć€æ°`TRANSFORMERS_CACHE`ă§æćźăăăăăă©ă«ăăźăăŁăŹăŻăăȘă§ăăWindowsă§ăŻăăăă©ă«ăăźăăŁăŹăŻăăȘăŻ`C:\Users\username\.cache\huggingface\hub`ă«ăȘăŁăŠăăŸăăç°ăȘăăăŁăă·ă„ăăŁăŹăŻăăȘăæćźăăăăă«ă仄äžăźă·ă§ă«ç°ćąć€æ°ă〿ŽăăăăšăćŻèœă§ăăćȘć
ćșŠăŻä»„äžăźé çȘă«ćŻŸćżăăŸă:
-
-1. ă·ă§ă«ç°ćąć€æ° (ăăă©ă«ă): `HUGGINGFACE_HUB_CACHE` ăŸă㯠`TRANSFORMERS_CACHE`.
-2. ă·ă§ă«ç°ćąć€æ°: `HF_HOME`.
-3. ă·ă§ă«ç°ćąć€æ°: `XDG_CACHE_HOME` + `/huggingface`.
-
-
-
-ăăă仄ćăźăăŒăžă§ăłăźă©ă€ăă©ăȘăäœżçšăăŠăăäșșă§ă`PYTORCH_TRANSFORMERS_CACHE`ăŸăăŻ`PYTORCH_PRETRAINED_BERT_CACHE`ăèšćźăăŠăăć Žćăă·ă§ă«ç°ćąć€æ°`TRANSFORMERS_CACHE`ăæćźăăȘăéăđ€ TransformersăŻăăăăźă·ă§ă«ç°ćąć€æ°ăäœżçšăăŸăă
-
-
-
-## ăȘăă©ă€ăłăąăŒă
-
-đ€ TransformersăŻăăŒă«ă«ăăĄă€ă«ăźăżăäœżçšăăăăšă§ăăĄă€ăąăŠă©ăŒă«ăăȘăă©ă€ăłăźç°ćąă§ăćäœăăăăăšăă§ăăŸăăăăźćäœăæćčă«ăăăăă«ăŻăç°ćąć€æ°`TRANSFORMERS_OFFLINE=1`ăèšćźăăŸăă
-
-
-
-ç°ćąć€æ°`HF_DATASETS_OFFLINE=1`ăèšćźăăăȘăă©ă€ăłăăŹăŒăăłă°ăŻăŒăŻăăăŒă«[đ€ Datasets](https://huggingface.co/docs/datasets/)ăèżœć ăăŸăă
-
-
-
-äŸăă°ăć€éšă€ăłăčăżăłăčă«ćŻŸăăŠăăĄă€ăąăŠă©ăŒă«ă§äżè·ăăăéćžžăźăăăăŻăŒăŻäžă§ăăă°ă©ă ăćźèĄăăć Žćăé枞仄äžăźăăăȘăłăăłăă§ćźèĄăăăăšă«ăȘăăŸă:
-
-```bash
-python examples/pytorch/translation/run_translation.py --model_name_or_path t5-small --dataset_name wmt16 --dataset_config ro-en ...
-```
-
-ăȘăă©ă€ăłă€ăłăčăżăłăčă§ăăźćăăăă°ă©ă ăćźèĄăăŸă:
-
-```bash
-HF_DATASETS_OFFLINE=1 TRANSFORMERS_OFFLINE=1 \
-python examples/pytorch/translation/run_translation.py --model_name_or_path t5-small --dataset_name wmt16 --dataset_config ro-en ...
-```
-
-ăăźăčăŻăȘăăăŻăăăŒă«ă«ăăĄă€ă«ăźăżăæ€çŽąăăăăšăćăăŁăŠăăăźă§ăăăłă°ăąăăăăăăżă€ă ăąăŠăăćŸ
ăŁăăăăăăšăȘăćźèĄăăăăŻăă§ăă
-
-### ăȘăă©ă€ăłă§äœżçšăăăăă«ăąăă«ăăăŒăŻăă€ă¶ăŒăććŸăă
-
-ăȘăă©ă€ăłă§đ€ Transformersăäœżçšăăăă1ă€ăźæčæłăŻăćăăŁăŠăăĄă€ă«ăăăŠăłăăŒăăăŠăăăăȘăă©ă€ăłă§äœżçšăăćż
èŠăăăăšăă«ăăźăăŒă«ă«ăăčăæćźăăăăšă§ăăăăă«ăŻ3ă€ăźæčæłăăăăŸă:
-
-* [Model Hub](https://huggingface.co/models)ăźăŠăŒă¶ăŒă€ăłăżăŒăă§ăŒăčäžăăâăąă€ăłăłăăŻăȘăăŻăăŠăăĄă€ă«ăăăŠăłăăŒăăăæčæłă
-
- 
-
-* [`PreTrainedModel.from_pretrained`]ăăăł[`PreTrainedModel.save_pretrained`]ăźăŻăŒăŻăăăŒăäœżçšăăæčæł:
-
- 1. [`PreTrainedModel.from_pretrained`]ă§ćăăŁăŠăăĄă€ă«ăăăŠăłăăŒăăăŸă:
-
- ```py
- >>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
-
- >>> tokenizer = AutoTokenizer.from_pretrained("bigscience/T0_3B")
- >>> model = AutoModelForSeq2SeqLM.from_pretrained("bigscience/T0_3B")
- ```
-
- 2. [`PreTrainedModel.save_pretrained`]ă§æćźăăăăăŁăŹăŻăăȘă«ăăĄă€ă«ăäżćăăŠăăăŸă:
-
- ```py
- >>> tokenizer.save_pretrained("./your/path/bigscience_t0")
- >>> model.save_pretrained("./your/path/bigscience_t0")
- ```
-
- 3. ăȘăă©ă€ăłă«ăăæă[`PreTrainedModel.from_pretrained`]ă«æćźăăăăŁăŹăŻăăȘăăăăĄă€ă«ăăȘăăŒăăăŸă:
-
- ```py
- >>> tokenizer = AutoTokenizer.from_pretrained("./your/path/bigscience_t0")
- >>> model = AutoModel.from_pretrained("./your/path/bigscience_t0")
- ```
-
-* ăăă°ă©ă çă«[huggingface_hub](https://github.com/huggingface/huggingface_hub/tree/main/src/huggingface_hub)ă©ă€ăă©ăȘăçšăăŠăăăĄă€ă«ăăăŠăłăăŒăăăæčæł:
-
- 1. 仟æłç°ćąă«`huggingface_hub`ă©ă€ăă©ăȘăă€ăłăčăăŒă«ăăŸă:
-
- ```bash
- python -m pip install huggingface_hub
- ```
-
- 2. æćźăźăăčă«ăăĄă€ă«ăăăŠăłăăŒăăăăăă«ă[`hf_hub_download`](https://huggingface.co/docs/hub/adding-a-library#download-files-from-the-hub)éąæ°ăäœżçšăăŸăăäŸăă°ă仄äžăźăłăăłăă§ă[T0](https://huggingface.co/bigscience/T0_3B)ăąăă«ăź`config.json`ăăĄă€ă«ăæćźăźăăčă«ăăŠăłăăŒăă§ăăŸă:
-
- ```py
- >>> from huggingface_hub import hf_hub_download
-
- >>> hf_hub_download(repo_id="bigscience/T0_3B", filename="config.json", cache_dir="./your/path/bigscience_t0")
- ```
-
-ăăĄă€ă«ăăăŠăłăăŒăăăăăăŒă«ă«ă«ăăŁăă·ă„ăăăăăăăźăăŒă«ă«ăăčăæćźăăŠăăĄă€ă«ăăăŒăăăŠäœżçšăăŸă:
-
-```py
->>> from transformers import AutoConfig
-
->>> config = AutoConfig.from_pretrained("./your/path/bigscience_t0/config.json")
-```
-
-
-
-Hubă«äżćăăăŠăăăăĄă€ă«ăăăŠăłăăŒăăăæčæłăźè©łçްă«ă€ăăŠăŻă[How to download files from the Hub](https://huggingface.co/docs/hub/how-to-downstream)ă»ăŻă·ă§ăłăćç
§ăăŠăă ăăă
-
-
\ No newline at end of file
diff --git a/docs/source/ja/multilingual.md b/docs/source/ja/multilingual.md
new file mode 100644
index 000000000000..86dabb94633c
--- /dev/null
+++ b/docs/source/ja/multilingual.md
@@ -0,0 +1,178 @@
+
+
+# æšè«ăźăăăźć€èšèȘăąăă«
+
+[[open-in-colab]]
+
+đ€ Transformers ă«ăŻăăă€ăăźć€èšèȘăąăă«ăăăăăăăăźæšè«ăźäœżçšæčæłăŻćäžèšèȘăąăă«ăšăŻç°ăȘăăŸăăăă ăăć€èšèȘăąăă«ăźäœżçšæčæłăăăčăŠç°ăȘăăăă§ăŻăăăŸăăă [bert-base-multilingual-uncased](https://huggingface.co/bert-base-multilingual-uncased) ăȘă©ăźäžéšăźăąăă«ăŻăćäžèšèȘăąăă«ăšćæ§ă«äœżçšă§ăăŸăă ăăźăŹă€ăă§ăŻăæšè«ăźăăă«äœżçšæčæłăç°ăȘăć€èšèȘăąăă«ăă©ăźăăă«äœżăăăç€șăăŸăă
+
+## XLM
+
+XLM ă«ăŻ10ăźç°ăȘăăă§ăăŻăă€ăłăăăăăăăźăăĄăź1ă€ă ăăćäžèšèȘă§ăă æźăăź9ă€ăźăąăă«ăă§ăăŻăă€ăłăăŻăèšèȘćă蟌ăżăäœżçšăăăă§ăăŻăă€ăłăăšäœżçšăăȘăăă§ăăŻăă€ăłăăź2ă€ăźă«ăăŽăȘă«ćăăăăšăă§ăăŸăă
+
+### èšèȘăźćă蟌ăżăăă XLM
+
+æŹĄăź XLM ăąăă«ăŻăèšèȘăźćă蟌ăżăäœżçšăăŠăæšè«ă§äœżçšăăăèšèȘăæćźăăŸăă
+
+- `xlm-mlm-ende-1024` (ăăčăŻćăăăèšèȘăąăăȘăłă°ăè±èȘ-ăă€ăèȘ)
+- `xlm-mlm-enfr-1024` (ăăčăŻćăăăèšèȘăąăăȘăłă°ăè±èȘ-ăă©ăłăčèȘ)
+- `xlm-mlm-enro-1024` (ăăčăŻćăăăèšèȘăąăăȘăłă°ăè±èȘ-ă«ăŒăăăąèȘ)
+- `xlm-mlm-xnli15-1024` (ăăčăŻćăăăèšèȘăąăăȘăłă°ăXNLI èšèȘ)
+- `xlm-mlm-tlm-xnli15-1024` (ăăčăŻćăăăèšèȘăąăăȘăłă° + çż»èšł + XNLI èšèȘ)
+- `xlm-clm-enfr-1024` (ć æèšèȘăąăăȘăłă°ăè±èȘ-ăă©ăłăčèȘ)
+- `xlm-clm-ende-1024` (ć æèšèȘăąăăȘăłă°ăè±èȘ-ăă€ăèȘ)
+
+èšèȘăźćă蟌ăżăŻăăąăă«ă«æžĄăăă `input_ids` ăšćăćœąç¶ăźăăłăœă«ăšăăŠèĄšăăăŸăă ăăăăźăăłăœă«ăźć€ăŻăäœżçšăăăèšèȘă«äŸćăăăăŒăŻăă€ă¶ăŒăź `lang2id` ăăăł `id2lang` 㱿§ă«ăăŁăŠèć„ăăăŸăă
+
+ăăźäŸă§ăŻă`xlm-clm-enfr-1024` ăă§ăăŻăă€ăłăăăăŒăăăŸă (ć æèšèȘăąăăȘăłă°ăè±èȘ-ăă©ăłăčèȘ)ă
+
+```py
+>>> import torch
+>>> from transformers import XLMTokenizer, XLMWithLMHeadModel
+
+>>> tokenizer = XLMTokenizer.from_pretrained("xlm-clm-enfr-1024")
+>>> model = XLMWithLMHeadModel.from_pretrained("xlm-clm-enfr-1024")
+```
+
+ăăŒăŻăă€ă¶ăŒăź `lang2id` 㱿§ăŻăăăźăąăă«ăźèšèȘăšăăź ID ăèĄšç€șăăŸăă
+
+```py
+>>> print(tokenizer.lang2id)
+{'en': 0, 'fr': 1}
+```
+
+æŹĄă«ăć
„ćäŸăäœæăăŸăă
+
+```py
+>>> input_ids = torch.tensor([tokenizer.encode("Wikipedia was used to")]) # batch size of 1
+```
+
+èšèȘ ID ă `en` ă«èšćźăăăăăäœżçšăăŠèšèȘăźćă蟌ăżăćźçŸ©ăăŸăă èšèȘăźćă蟌ăżăŻăè±èȘăźèšèȘ ID ă§ăăăăă`0` ă§ćăăăăăăłăœă«ă§ăă ăăźăăłăœă«ăŻ `input_ids` ăšćăă”ă€ășă«ăăćż
èŠăăăăŸăă
+
+```py
+>>> language_id = tokenizer.lang2id["en"] # 0
+>>> langs = torch.tensor([language_id] * input_ids.shape[1]) # torch.tensor([0, 0, 0, ..., 0])
+
+>>> # We reshape it to be of size (batch_size, sequence_length)
+>>> langs = langs.view(1, -1) # is now of shape [1, sequence_length] (we have a batch size of 1)
+```
+
+ăăă§ă`input_ids` ăšèšèȘăźćă蟌ăżăăąăă«ă«æžĄăăăšăă§ăăŸăă
+
+```py
+>>> outputs = model(input_ids, langs=langs)
+```
+
+[run_generation.py](https://github.com/huggingface/transformers/tree/main/examples/pytorch/text-generation/run_generation.py) ăčăŻăȘăăăŻă`xlm-clm` ăă§ăăŻăă€ăłăăäœżçšăăŠăèšèȘăćă蟌ăŸăăăăăčăăçæă§ăăŸăă
+
+### èšèȘăźćă蟌ăżăăȘăXLM
+
+æŹĄăź XLM ăąăă«ăŻăæšè«äžă«èšèȘăźćă蟌ăżăćż
èŠăšăăŸăăă
+
+- `xlm-mlm-17-1280` (ăăčăŻćăăăèšèȘăąăăȘăłă°ă17ăźèšèȘ)
+- `xlm-mlm-100-1280` (ăăčăŻćăăăèšèȘăąăăȘăłă°ă100ăźèšèȘ)
+
+ăăăăźăąăă«ăŻă仄ćăź XLM ăă§ăăŻăă€ăłăăšăŻç°ăȘăăäžèŹçăȘæăźèĄšçŸă«äœżçšăăăŸăă
+
+## BERT
+
+仄äžăź BERT ăąăă«ăŻăć€èšèȘăżăčăŻă«äœżçšă§ăăŸăă
+
+- `bert-base-multilingual-uncased` (ăăčăŻćăăăèšèȘăąăăȘăłă° + æŹĄăźæăźäșæžŹă102ăźèšèȘ)
+- `bert-base-multilingual-cased` (ăăčăŻćăăăèšèȘăąăăȘăłă° + æŹĄăźæăźäșæžŹă104ăźèšèȘ)
+
+ăăăăźăąăă«ăŻăæšè«äžă«èšèȘăźćă蟌ăżăćż
èŠăšăăŸăăă æèăăèšèȘăèć„ăăăăă«ćżăăŠæšæžŹăăćż
èŠăăăăŸăă
+
+## XLM-RoBERTa
+
+æŹĄăź XLM-RoBERTa ăąăă«ăŻăć€èšèȘăżăčăŻă«äœżçšă§ăăŸăă
+
+- `xlm-roberta-base` (ăăčăŻćăăăèšèȘăąăăȘăłă°ă100ăźèšèȘ)
+- `xlm-roberta-large` (ăăčăŻćăăăèšèȘăąăăȘăłă°ă100ăźèšèȘ)
+
+XLM-RoBERTa ăŻă100ăźèšèȘă§æ°ăăäœæăăăłăŻăȘăŒăăłă°ăăă2.5 TB ăź CommonCrawl ăăŒăżă§ăăŹăŒăăłă°ăăăŸăăă ăăăŻăćéĄăă·ăŒă±ăłăčăźă©ăă«ä»ăăèłȘććżçăȘă©ăźăăŠăłăčăăȘăŒă ăżăčăŻă§ămBERT ă XLM ăȘă©ăźä»„ćă«ăȘăȘăŒăčăăăć€èšèȘăąăă«ă性ćč
ă«æčćăăŸăă
+
+## M2M100
+
+æŹĄăź M2M100 ăąăă«ăŻăć€èšèȘçż»èšłă«äœżçšă§ăăŸăă
+
+- `facebook/m2m100_418M` (çż»èšł)
+- `facebook/m2m100_1.2B` (çż»èšł)
+
+ăăźäŸă§ăŻă`facebook/m2m100_418M` ăă§ăăŻăă€ăłăăăăŒăăăŠăäžćœèȘăăè±èȘă«çż»èšłăăŸăă ăăŒăŻăă€ă¶ăŒă§ăœăŒăčèšèȘăèšćźă§ăăŸăă
+
+```py
+>>> from transformers import M2M100ForConditionalGeneration, M2M100Tokenizer
+
+>>> en_text = "Do not meddle in the affairs of wizards, for they are subtle and quick to anger."
+>>> chinese_text = "äžèŠææć·«ćž«çäșć, ć çșä»ćæŻćŸźćŠç, ćŸćż«ć°±æçŒæ."
+
+>>> tokenizer = M2M100Tokenizer.from_pretrained("facebook/m2m100_418M", src_lang="zh")
+>>> model = M2M100ForConditionalGeneration.from_pretrained("facebook/m2m100_418M")
+```
+
+ăăăčăăăăŒăŻăłćăăŸăă
+
+```py
+>>> encoded_zh = tokenizer(chinese_text, return_tensors="pt")
+```
+
+M2M100 ăŻăæćă«çæăăăăăŒăŻăłăšăăŠăżăŒăČăăèšèȘ ID ăćŒ·ć¶çă«ăżăŒăČăăèšèȘă«çż»èšłăăŸăă è±èȘă«çż»èšłăăă«ăŻă`generate` ăĄăœăăă§ `forced_bos_token_id` ă `en` ă«èšćźăăŸăă
+
+```py
+>>> generated_tokens = model.generate(**encoded_zh, forced_bos_token_id=tokenizer.get_lang_id("en"))
+>>> tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)
+'Do not interfere with the matters of the witches, because they are delicate and will soon be angry.'
+```
+
+## MBart
+
+ć€èšèȘçż»èšłă«ăŻăæŹĄăź MBart ăąăă«ăäœżçšă§ăăŸăă
+
+- `facebook/mbart-large-50-one-to-many-mmt` (One-to-many multilingual machine translation, 50 languages)
+- `facebook/mbart-large-50-many-to-many-mmt` (Many-to-many multilingual machine translation, 50 languages)
+- `facebook/mbart-large-50-many-to-one-mmt` (Many-to-one multilingual machine translation, 50 languages)
+- `facebook/mbart-large-50` (Multilingual translation, 50 languages)
+- `facebook/mbart-large-cc25`
+
+ăăźäŸă§ăŻă`facebook/mbart-large-50-many-to-many-mmt` ăă§ăăŻăă€ăłăăăăŒăăăŠăăăŁăłă©ăłăèȘăè±èȘă«çż»èšłăăŸăăăăŒăŻăă€ă¶ăŒă§ăœăŒăčèšèȘăèšćźă§ăăŸăă
+
+```py
+>>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
+
+>>> en_text = "Do not meddle in the affairs of wizards, for they are subtle and quick to anger."
+>>> fi_text = "ĂlĂ€ sekaannu velhojen asioihin, sillĂ€ ne ovat hienovaraisia ja nopeasti vihaisia."
+
+>>> tokenizer = AutoTokenizer.from_pretrained("facebook/mbart-large-50-many-to-many-mmt", src_lang="fi_FI")
+>>> model = AutoModelForSeq2SeqLM.from_pretrained("facebook/mbart-large-50-many-to-many-mmt")
+```
+
+ăăăčăăăăŒăŻăłćăăŸăă
+
+```py
+>>> encoded_en = tokenizer(en_text, return_tensors="pt")
+```
+
+MBart ăŻăæćă«çæăăăăăŒăŻăłăšăăŠăżăŒăČăăèšèȘ ID ăćŒ·ć¶çă«ăżăŒăČăăèšèȘă«çż»èšłăăŸăă è±èȘă«çż»èšłăăă«ăŻă`generate` ăĄăœăăă§ `forced_bos_token_id` ă `en` ă«èšćźăăŸăă
+
+```py
+>>> generated_tokens = model.generate(**encoded_en, forced_bos_token_id=tokenizer.lang_code_to_id("en_XX"))
+>>> tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)
+"Don't interfere with the wizard's affairs, because they are subtle, will soon get angry."
+```
+
+`facebook/mbart-large-50-many-to-one-mmt` ăă§ăăŻăă€ăłăăäœżçšăăŠăăć Žćăæćă«çæăăăăăŒăŻăłăšăăŠăżăŒăČăăèšèȘ ID ăćŒ·ć¶ăăćż
èŠăŻăăăŸăăăăă仄ć€ăźć ŽćăäœżçšæčæłăŻćăă§ăă
\ No newline at end of file
diff --git a/docs/source/ja/multilingual.mdx b/docs/source/ja/multilingual.mdx
deleted file mode 100644
index a5ccc18385a2..000000000000
--- a/docs/source/ja/multilingual.mdx
+++ /dev/null
@@ -1,174 +0,0 @@
-
-
-# æšè«ăźăăăźć€èšèȘăąăă«
-
-[[open-in-colab]]
-
-đ€ Transformers ă«ăŻăăă€ăăźć€èšèȘăąăă«ăăăăăăăăźæšè«ăźäœżçšæčæłăŻćäžèšèȘăąăă«ăšăŻç°ăȘăăŸăăăă ăăć€èšèȘăąăă«ăźäœżçšæčæłăăăčăŠç°ăȘăăăă§ăŻăăăŸăăă [bert-base-multilingual-uncased](https://huggingface.co/bert-base-multilingual-uncased) ăȘă©ăźäžéšăźăąăă«ăŻăćäžèšèȘăąăă«ăšćæ§ă«äœżçšă§ăăŸăă ăăźăŹă€ăă§ăŻăæšè«ăźăăă«äœżçšæčæłăç°ăȘăć€èšèȘăąăă«ăă©ăźăăă«äœżăăăç€șăăŸăă
-
-## XLM
-
-XLM ă«ăŻ10ăźç°ăȘăăă§ăăŻăă€ăłăăăăăăăźăăĄăź1ă€ă ăăćäžèšèȘă§ăă æźăăź9ă€ăźăąăă«ăă§ăăŻăă€ăłăăŻăèšèȘćă蟌ăżăäœżçšăăăă§ăăŻăă€ăłăăšäœżçšăăȘăăă§ăăŻăă€ăłăăź2ă€ăźă«ăăŽăȘă«ćăăăăšăă§ăăŸăă
-
-### èšèȘăźćă蟌ăżăăă XLM
-
-æŹĄăź XLM ăąăă«ăŻăèšèȘăźćă蟌ăżăäœżçšăăŠăæšè«ă§äœżçšăăăèšèȘăæćźăăŸăă
-
-- `xlm-mlm-ende-1024` (ăăčăŻćăăăèšèȘăąăăȘăłă°ăè±èȘ-ăă€ăèȘ)
-- `xlm-mlm-enfr-1024` (ăăčăŻćăăăèšèȘăąăăȘăłă°ăè±èȘ-ăă©ăłăčèȘ)
-- `xlm-mlm-enro-1024` (ăăčăŻćăăăèšèȘăąăăȘăłă°ăè±èȘ-ă«ăŒăăăąèȘ)
-- `xlm-mlm-xnli15-1024` (ăăčăŻćăăăèšèȘăąăăȘăłă°ăXNLI èšèȘ)
-- `xlm-mlm-tlm-xnli15-1024` (ăăčăŻćăăăèšèȘăąăăȘăłă° + çż»èšł + XNLI èšèȘ)
-- `xlm-clm-enfr-1024` (ć æèšèȘăąăăȘăłă°ăè±èȘ-ăă©ăłăčèȘ)
-- `xlm-clm-ende-1024` (ć æèšèȘăąăăȘăłă°ăè±èȘ-ăă€ăèȘ)
-
-èšèȘăźćă蟌ăżăŻăăąăă«ă«æžĄăăă `input_ids` ăšćăćœąç¶ăźăăłăœă«ăšăăŠèĄšăăăŸăă ăăăăźăăłăœă«ăźć€ăŻăäœżçšăăăèšèȘă«äŸćăăăăŒăŻăă€ă¶ăŒăź `lang2id` ăăăł `id2lang` 㱿§ă«ăăŁăŠèć„ăăăŸăă
-
-ăăźäŸă§ăŻă`xlm-clm-enfr-1024` ăă§ăăŻăă€ăłăăăăŒăăăŸă (ć æèšèȘăąăăȘăłă°ăè±èȘ-ăă©ăłăčèȘ)ă
-
-```py
->>> import torch
->>> from transformers import XLMTokenizer, XLMWithLMHeadModel
-
->>> tokenizer = XLMTokenizer.from_pretrained("xlm-clm-enfr-1024")
->>> model = XLMWithLMHeadModel.from_pretrained("xlm-clm-enfr-1024")
-```
-
-ăăŒăŻăă€ă¶ăŒăź `lang2id` 㱿§ăŻăăăźăąăă«ăźèšèȘăšăăź ID ăèĄšç€șăăŸăă
-
-```py
->>> print(tokenizer.lang2id)
-{'en': 0, 'fr': 1}
-```
-
-æŹĄă«ăć
„ćäŸăäœæăăŸăă
-
-```py
->>> input_ids = torch.tensor([tokenizer.encode("Wikipedia was used to")]) # batch size of 1
-```
-
-èšèȘ ID ă `en` ă«èšćźăăăăăäœżçšăăŠèšèȘăźćă蟌ăżăćźçŸ©ăăŸăă èšèȘăźćă蟌ăżăŻăè±èȘăźèšèȘ ID ă§ăăăăă`0` ă§ćăăăăăăłăœă«ă§ăă ăăźăăłăœă«ăŻ `input_ids` ăšćăă”ă€ășă«ăăćż
èŠăăăăŸăă
-
-```py
->>> language_id = tokenizer.lang2id["en"] # 0
->>> langs = torch.tensor([language_id] * input_ids.shape[1]) # torch.tensor([0, 0, 0, ..., 0])
-
->>> # We reshape it to be of size (batch_size, sequence_length)
->>> langs = langs.view(1, -1) # is now of shape [1, sequence_length] (we have a batch size of 1)
-```
-
-ăăă§ă`input_ids` ăšèšèȘăźćă蟌ăżăăąăă«ă«æžĄăăăšăă§ăăŸăă
-
-```py
->>> outputs = model(input_ids, langs=langs)
-```
-
-[run_generation.py](https://github.com/huggingface/transformers/tree/main/examples/pytorch/text-generation/run_generation.py) ăčăŻăȘăăăŻă`xlm-clm` ăă§ăăŻăă€ăłăăäœżçšăăŠăèšèȘăćă蟌ăŸăăăăăčăăçæă§ăăŸăă
-
-### èšèȘăźćă蟌ăżăăȘăXLM
-
-æŹĄăź XLM ăąăă«ăŻăæšè«äžă«èšèȘăźćă蟌ăżăćż
èŠăšăăŸăăă
-
-- `xlm-mlm-17-1280` (ăăčăŻćăăăèšèȘăąăăȘăłă°ă17ăźèšèȘ)
-- `xlm-mlm-100-1280` (ăăčăŻćăăăèšèȘăąăăȘăłă°ă100ăźèšèȘ)
-
-ăăăăźăąăă«ăŻă仄ćăź XLM ăă§ăăŻăă€ăłăăšăŻç°ăȘăăäžèŹçăȘæăźèĄšçŸă«äœżçšăăăŸăă
-
-## BERT
-
-仄äžăź BERT ăąăă«ăŻăć€èšèȘăżăčăŻă«äœżçšă§ăăŸăă
-
-- `bert-base-multilingual-uncased` (ăăčăŻćăăăèšèȘăąăăȘăłă° + æŹĄăźæăźäșæžŹă102ăźèšèȘ)
-- `bert-base-multilingual-cased` (ăăčăŻćăăăèšèȘăąăăȘăłă° + æŹĄăźæăźäșæžŹă104ăźèšèȘ)
-
-ăăăăźăąăă«ăŻăæšè«äžă«èšèȘăźćă蟌ăżăćż
èŠăšăăŸăăă æèăăèšèȘăèć„ăăăăă«ćżăăŠæšæžŹăăćż
èŠăăăăŸăă
-
-## XLM-RoBERTa
-
-æŹĄăź XLM-RoBERTa ăąăă«ăŻăć€èšèȘăżăčăŻă«äœżçšă§ăăŸăă
-
-- `xlm-roberta-base` (ăăčăŻćăăăèšèȘăąăăȘăłă°ă100ăźèšèȘ)
-- `xlm-roberta-large` (ăăčăŻćăăăèšèȘăąăăȘăłă°ă100ăźèšèȘ)
-
-XLM-RoBERTa ăŻă100ăźèšèȘă§æ°ăăäœæăăăłăŻăȘăŒăăłă°ăăă2.5 TB ăź CommonCrawl ăăŒăżă§ăăŹăŒăăłă°ăăăŸăăă ăăăŻăćéĄăă·ăŒă±ăłăčăźă©ăă«ä»ăăèłȘććżçăȘă©ăźăăŠăłăčăăȘăŒă ăżăčăŻă§ămBERT ă XLM ăȘă©ăźä»„ćă«ăȘăȘăŒăčăăăć€èšèȘăąăă«ă性ćč
ă«æčćăăŸăă
-
-## M2M100
-
-æŹĄăź M2M100 ăąăă«ăŻăć€èšèȘçż»èšłă«äœżçšă§ăăŸăă
-
-- `facebook/m2m100_418M` (çż»èšł)
-- `facebook/m2m100_1.2B` (çż»èšł)
-
-ăăźäŸă§ăŻă`facebook/m2m100_418M` ăă§ăăŻăă€ăłăăăăŒăăăŠăäžćœèȘăăè±èȘă«çż»èšłăăŸăă ăăŒăŻăă€ă¶ăŒă§ăœăŒăčèšèȘăèšćźă§ăăŸăă
-
-```py
->>> from transformers import M2M100ForConditionalGeneration, M2M100Tokenizer
-
->>> en_text = "Do not meddle in the affairs of wizards, for they are subtle and quick to anger."
->>> chinese_text = "äžèŠææć·«ćž«çäșć, ć çșä»ćæŻćŸźćŠç, ćŸćż«ć°±æçŒæ."
-
->>> tokenizer = M2M100Tokenizer.from_pretrained("facebook/m2m100_418M", src_lang="zh")
->>> model = M2M100ForConditionalGeneration.from_pretrained("facebook/m2m100_418M")
-```
-
-ăăăčăăăăŒăŻăłćăăŸăă
-
-```py
->>> encoded_zh = tokenizer(chinese_text, return_tensors="pt")
-```
-
-M2M100 ăŻăæćă«çæăăăăăŒăŻăłăšăăŠăżăŒăČăăèšèȘ ID ăćŒ·ć¶çă«ăżăŒăČăăèšèȘă«çż»èšłăăŸăă è±èȘă«çż»èšłăăă«ăŻă`generate` ăĄăœăăă§ `forced_bos_token_id` ă `en` ă«èšćźăăŸăă
-
-```py
->>> generated_tokens = model.generate(**encoded_zh, forced_bos_token_id=tokenizer.get_lang_id("en"))
->>> tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)
-'Do not interfere with the matters of the witches, because they are delicate and will soon be angry.'
-```
-
-## MBart
-
-ć€èšèȘçż»èšłă«ăŻăæŹĄăź MBart ăąăă«ăäœżçšă§ăăŸăă
-
-- `facebook/mbart-large-50-one-to-many-mmt` (One-to-many multilingual machine translation, 50 languages)
-- `facebook/mbart-large-50-many-to-many-mmt` (Many-to-many multilingual machine translation, 50 languages)
-- `facebook/mbart-large-50-many-to-one-mmt` (Many-to-one multilingual machine translation, 50 languages)
-- `facebook/mbart-large-50` (Multilingual translation, 50 languages)
-- `facebook/mbart-large-cc25`
-
-ăăźäŸă§ăŻă`facebook/mbart-large-50-many-to-many-mmt` ăă§ăăŻăă€ăłăăăăŒăăăŠăăăŁăłă©ăłăèȘăè±èȘă«çż»èšłăăŸăăăăŒăŻăă€ă¶ăŒă§ăœăŒăčèšèȘăèšćźă§ăăŸăă
-
-```py
->>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
-
->>> en_text = "Do not meddle in the affairs of wizards, for they are subtle and quick to anger."
->>> fi_text = "ĂlĂ€ sekaannu velhojen asioihin, sillĂ€ ne ovat hienovaraisia ja nopeasti vihaisia."
-
->>> tokenizer = AutoTokenizer.from_pretrained("facebook/mbart-large-50-many-to-many-mmt", src_lang="fi_FI")
->>> model = AutoModelForSeq2SeqLM.from_pretrained("facebook/mbart-large-50-many-to-many-mmt")
-```
-
-ăăăčăăăăŒăŻăłćăăŸăă
-
-```py
->>> encoded_en = tokenizer(en_text, return_tensors="pt")
-```
-
-MBart ăŻăæćă«çæăăăăăŒăŻăłăšăăŠăżăŒăČăăèšèȘ ID ăćŒ·ć¶çă«ăżăŒăČăăèšèȘă«çż»èšłăăŸăă è±èȘă«çż»èšłăăă«ăŻă`generate` ăĄăœăăă§ `forced_bos_token_id` ă `en` ă«èšćźăăŸăă
-
-```py
->>> generated_tokens = model.generate(**encoded_en, forced_bos_token_id=tokenizer.lang_code_to_id("en_XX"))
->>> tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)
-"Don't interfere with the wizard's affairs, because they are subtle, will soon get angry."
-```
-
-`facebook/mbart-large-50-many-to-one-mmt` ăă§ăăŻăă€ăłăăäœżçšăăŠăăć Žćăæćă«çæăăăăăŒăŻăłăšăăŠăżăŒăČăăèšèȘ ID ăćŒ·ć¶ăăćż
èŠăŻăăăŸăăăăă仄ć€ăźć ŽćăäœżçšæčæłăŻćăă§ăă
\ No newline at end of file
diff --git a/docs/source/ko/_toctree.yml b/docs/source/ko/_toctree.yml
index a9e1ff921d6b..d200b3b7e9ca 100644
--- a/docs/source/ko/_toctree.yml
+++ b/docs/source/ko/_toctree.yml
@@ -8,174 +8,178 @@
title: ììíêž°
- sections:
- local: pipeline_tutorial
- title: ì¶ëĄ ì ìí Pipeline
+ title: PipelineìŒëĄ ì¶ëĄ íêž°
- local: autoclass_tutorial
- title: ìë íŽëì€ëĄ ìŹì íì”ë ìžì€íŽì€ ëĄëíêž°
+ title: AutoClassëĄ ìŹì íì”ë ìžì€íŽì€ ëĄëíêž°
- local: preprocessing
- title: ì ìČ늏
+ title: ë°ìŽí° ì ìČ늏íêž°
- local: training
title: ìŹì íì”ë ëȘšëž ëŻžìž ìĄ°ì íêž°
+ - local: run_scripts
+ title: ì€íŹëŠœížëĄ íì”íêž°
- local: accelerate
- title: đ€ Accelerate넌 íì©í ë¶ì° íì”
+ title: đ€ AccelerateëĄ ë¶ì° íì” ê”Źì±íêž°
- local: model_sharing
- title: ëȘšëž êł”ì íêž°
- title: (ëČìì€) íí 늏ìŒ
+ title: ë§ë ëȘšëž êł”ì íêž°
+ - local: transformers_agents
+ title: ììŽì íž
+ title: íí 늏ìŒ
- sections:
- sections:
- - local: create_a_model
- title: ë§ì¶€í ìí€í
ìČ ë§ë€êž°
- - local: custom_models
- title: ìŹì©ì ì ì ëȘšëž êł”ì íêž°
- - local: run_scripts
- title: ì€íŹëŠœížëĄ íì”íêž°
- - local: sagemaker
- title: Amazon SageMakerìì íì” ì€ííêž°
- - local: in_translation
- title: (ëČìì€) Converting from TensorFlow checkpoints
- - local: serialization
- title: ONNXëĄ ëŽëłŽëŽêž°
- - local: torchscript
- title: TorchScriptëĄ ëŽëłŽëŽêž°
- - local: in_translation
- title: (ëČìì€) Troubleshoot
- title: (ëČìì€) ìŒë°ì ìž ìŹì©ë°©ëČ
- - sections:
- - local: in_translation
- title: (ëČìì€) Use tokenizers from đ€ Tokenizers
- - local: multilingual
- title: ë€ê”ìŽ ëȘšëž ì¶ëĄ íêž°
- - local: in_translation
- title: (ëČìì€) Text generation strategies
- - sections:
- local: tasks/sequence_classification
title: í
ì€íž ë¶ë„
- local: tasks/token_classification
title: í í° ë¶ë„
- local: tasks/question_answering
title: ì§ì ìë”(Question Answering)
- - local: in_translation
- title: (ëČìì€) Causal language modeling
+ - local: tasks/language_modeling
+ title: ìžêłŒì ìžìŽ ëȘšëžë§(Causal language modeling)
- local: tasks/masked_language_modeling
title: ë§ì€íčë ìžìŽ ëȘšëžë§(Masked language modeling)
- local: tasks/translation
title: ëČì
- local: tasks/summarization
title: ììœ
- - local: in_translation
- title: (ëČìì€) Multiple choice
- title: (ëČìì€) íì€íŹëł ê°ìŽë
- isExpanded: false
- title: (ëČìì€) ìì°ìŽìČ늏
+ - local: tasks/multiple_choice
+ title: ê°êŽì 돞ì (Multiple Choice)
+ title: ìì°ìŽìČ늏
+ isExpanded: false
- sections:
- - local: in_translation
- title: (ëČìì€) Audio classification
- - local: in_translation
- title: (ëČìì€) Automatic speech recognition
+ - local: in_translation
+ title: (ëČìì€) Audio classification
+ - local: tasks/asr
+ title: ìë ìì± ìžì
title: (ëČìì€) ì€ëì€
+ isExpanded: false
- sections:
- - local: tasks/image_classification
- title: ìŽëŻžì§ ë¶ë„
- - local: in_translation
- title: (ëČìì€) Semantic segmentation
- - local: in_translation
- title: (ëČìì€) Video classification
- - local: in_translation
- title: (ëČìì€) Object detection
- - local: in_translation
- title: (ëČìì€) Zero-shot object detection
- - local: tasks/zero_shot_image_classification
- title: ì ëĄì·(zero-shot) ìŽëŻžì§ ë¶ë„
- - local: in_translation
- title: (ëČìì€) Depth estimation
+ - local: tasks/image_classification
+ title: ìŽëŻžì§ ë¶ë„
+ - local: in_translation
+ title: (ëČìì€) Semantic segmentation
+ - local: tasks/video_classification
+ title: ìì ë¶ë„
+ - local: tasks/object_detection
+ title: ê°ìČŽ íì§
+ - local: tasks/zero_shot_object_detection
+ title: ì ëĄì·(zero-shot) ê°ìČŽ íì§
+ - local: tasks/zero_shot_image_classification
+ title: ì ëĄì·(zero-shot) ìŽëŻžì§ ë¶ë„
+ - local: tasks/monocular_depth_estimation
+ title: ëšìŒ ìì êž°ë° êčìŽ ì¶ì
title: (ëČìì€) 컎íší° ëčì
+ isExpanded: false
- sections:
- - local: tasks/image_captioning
- title: ìŽëŻžì§ ìșĄì
ë
+ - local: tasks/image_captioning
+ title: ìŽëŻžì§ ìșĄì
ë
+ - local: tasks/document_question_answering
+ title: 돞ì ì§ì ìë”(Document Question Answering)
+ title: ë©í°ëȘšëŹ
+ isExpanded: false
+ title: íì€íŹ ê°ìŽë
+- sections:
+ - local: fast_tokenizers
+ title: đ€ Tokenizers ëŒìŽëžëŹëŠŹìì í íŹëìŽì ìŹì©íêž°
+ - local: multilingual
+ title: ë€ê”ìŽ ëȘšëž ì¶ëĄ íêž°
- local: in_translation
- title: (ëČìì€) Document Question Answering
- title: (ëČìì€) ë©í°ëȘšëŹ
- - sections:
+ title: (ëČìì€) Customize text generation strategy
+ - local: create_a_model
+ title: ëȘšëžëł API ìŹì©íêž°
+ - local: custom_models
+ title: ìŹì©ì ì ì ëȘšëž êł”ì íêž°
+ - local: sagemaker
+ title: Amazon SageMakerìì íì” ì€ííêž°
+ - local: serialization
+ title: ONNXëĄ ëŽëłŽëŽêž°
+ - local: tflite
+ title: TFLiteëĄ ëŽëłŽëŽêž°
+ - local: torchscript
+ title: TorchScriptëĄ ëŽëłŽëŽêž°
- local: in_translation
- title: (ëČìì€) Overview
+ title: (ëČìì€) Benchmarks
- local: in_translation
- title: (ëČìì€) Training on one GPU
+ title: (ëČìì€) Notebooks with examples
- local: in_translation
- title: (ëČìì€) Training on many GPUs
+ title: (ëČìì€) Community resources
+ - local: custom_tools
+ title: ìŹì©ì ì ì ëê”Źì í륏ííž
+ - local: troubleshooting
+ title: 돞ì íŽêȰ
+ title: (ëČìì€) ê°ë°ì ê°ìŽë
+- sections:
+ - local: performance
+ title: ì±ë„ ë° íì„ì±
- local: in_translation
- title: (ëČìì€) Training on CPU
+ title: (ëČìì€) Training on one GPU
- local: in_translation
- title: (ëČìì€) Training on many CPUs
+ title: (ëČìì€) Training on many GPUs
+ - local: perf_train_cpu
+ title: CPUìì íë š
+ - local: perf_train_cpu_many
+ title: ë€ì€ CPUìì íë šíêž°
- local: in_translation
title: (ëČìì€) Training on TPUs
- local: in_translation
title: (ëČìì€) Training on TPU with TensorFlow
- local: in_translation
title: (ëČìì€) Training on Specialized Hardware
- - local: in_translation
- title: (ëČìì€) Inference on CPU
- - local: in_translation
- title: (ëČìì€) Inference on one GPU
- - local: in_translation
- title: (ëČìì€) Inference on many GPUs
+ - local: perf_infer_cpu
+ title: CPUëĄ ì¶ëĄ íêž°
+ - local: perf_infer_gpu_one
+ title: íëì GPU넌 íì©í ì¶ëĄ
+ - local: perf_infer_gpu_many
+ title: ìŹëŹ GPUìì ì¶ëĄ
- local: in_translation
title: (ëČìì€) Inference on Specialized Hardware
- - local: in_translation
- title: (ëČìì€) Custom hardware for training
+ - local: perf_hardware
+ title: íë šì© ìŹì©ì ë§ì¶€í íëìšìŽ
- local: in_translation
title: (ëČìì€) Instantiating a big model
- local: in_translation
title: (ëČìì€) Debugging
- - local: in_translation
- title: (ëČìì€) Hyperparameter Search using Trainer API
- - local: in_translation
- title: (ëČìì€) XLA Integration for TensorFlow Models
- title: (ëČìì€) ì±ë„ ë° íì„ì±
- - sections:
+ - local: hpo_train
+ title: Trainer API넌 ìŹì©í íìŽíŒíëŒëŻží° íì
+ - local: tf_xla
+ title: TensorFlow ëȘšëžì ìí XLA í”í©
+ title: (ëČìì€) ì±ë„ ë° íì„ì±
+- sections:
- local: in_translation
title: (ëČìì€) How to contribute to transformers?
- - local: in_translation
- title: (ëČìì€) How to add a model to đ€ Transformers?
- - local: in_translation
- title: (ëČìì€) How to convert a đ€ Transformers model to TensorFlow?
+ - local: add_new_model
+ title: đ€ Transformersì ìëĄìŽ ëȘšëžì ì¶ê°íë ë°©ëČ
+ - local: add_tensorflow_model
+ title: ìŽë»êČ đ€ Transformers ëȘšëžì TensorFlowëĄ ëłííëì?
- local: in_translation
title: (ëČìì€) How to add a pipeline to đ€ Transformers?
- - local: in_translation
- title: (ëČìì€) Testing
+ - local: testing
+ title: í
ì€íž
- local: in_translation
title: (ëČìì€) Checks on a Pull Request
- title: (ëČìì€) êž°ìŹíêž°
- - local: notebooks
- title: (ëČìì€) đ€ Transformers Notebooks
- - local: in_translation
- title: (ëČìì€) Community resources
- - local: in_translation
- title: (ëČìì€) Benchmarks
- - local: in_translation
- title: (ëČìì€) Migrating from previous packages
- title: (ëČìì€) How-to ê°ìŽë
+ title: (ëČìì€) êž°ìŹíêž°
+
- sections:
- - local: in_translation
- title: (ëČìì€) Philosophy
+ - local: philosophy
+ title: ìŽë
êłŒ ëȘ©í
- local: in_translation
title: (ëČìì€) Glossary
- - local: in_translation
- title: (ëČìì€) What đ€ Transformers can do
- - local: in_translation
- title: (ëČìì€) How đ€ Transformers solve tasks
- - local: in_translation
- title: (ëČìì€) The Transformer model family
+ - local: task_summary
+ title: đ€ TransformersëĄ í ì ìë ìì
+ - local: tasks_explained
+ title: đ€ TransformersëĄ ìì
ì íŽêȰíë ë°©ëČ
+ - local: model_summary
+ title: Transformer ëȘšëžê”°
- local: in_translation
title: (ëČìì€) Summary of the tokenizers
- - local: in_translation
- title: (ëČìì€) Attention mechanisms
- - local: in_translation
- title: (ëČìì€) Padding and truncation
- - local: in_translation
- title: (ëČìì€) BERTology
- - local: in_translation
- title: (ëČìì€) Perplexity of fixed-length models
- - local: in_translation
- title: (ëČìì€) Pipelines for webserver inference
+ - local: attention
+ title: ìŽí
ì
맀컀ëìŠ
+ - local: pad_truncation
+ title: íšë©êłŒ ìëŒëŽêž°
+ - local: bertology
+ title: BERTology
+ - local: perplexity
+ title: êł ì êžžìŽ ëȘšëžì ííë ìí°(Perplexity)
+ - local: pipeline_webserver
+ title: ì¶ëĄ ìč ìëČ넌 ìí íìŽíëŒìž
title: (ëČìì€) ê°ë
ê°ìŽë
- sections:
- sections:
@@ -263,6 +267,8 @@
title: (ëČìì€) ConvBERT
- local: in_translation
title: (ëČìì€) CPM
+ - local: in_translation
+ title: (ëČìì€) CPMANT
- local: in_translation
title: (ëČìì€) CTRL
- local: in_translation
@@ -309,6 +315,8 @@
title: (ëČìì€) GPT-J
- local: in_translation
title: (ëČìì€) GPT2
+ - local: in_translation
+ title: (ëČìì€) GPTBigCode
- local: in_translation
title: (ëČìì€) GPTSAN Japanese
- local: in_translation
@@ -361,6 +369,8 @@
title: (ëČìì€) NLLB-MoE
- local: in_translation
title: (ëČìì€) Nyströmformer
+ - local: in_translation
+ title: (ëČìì€) Open-Llama
- local: in_translation
title: (ëČìì€) OPT
- local: in_translation
@@ -460,6 +470,8 @@
title: (ëČìì€) EfficientFormer
- local: in_translation
title: (ëČìì€) EfficientNet
+ - local: in_translation
+ title: (ëČìì€) FocalNet
- local: in_translation
title: (ëČìì€) GLPN
- local: in_translation
@@ -572,6 +584,8 @@
title: (ëČìì€) CLIPSeg
- local: in_translation
title: (ëČìì€) Data2Vec
+ - local: in_translation
+ title: (ëČìì€) DePlot
- local: in_translation
title: (ëČìì€) Donut
- local: in_translation
@@ -592,6 +606,8 @@
title: (ëČìì€) LiLT
- local: in_translation
title: (ëČìì€) LXMERT
+ - local: in_translation
+ title: (ëČìì€) MatCha
- local: in_translation
title: (ëČìì€) MGP-STR
- local: in_translation
@@ -602,6 +618,8 @@
title: (ëČìì€) Perceiver
- local: in_translation
title: (ëČìì€) Pix2Struct
+ - local: in_translation
+ title: (ëČìì€) Segment Anything
- local: in_translation
title: (ëČìì€) Speech Encoder Decoder Models
- local: in_translation
@@ -661,4 +679,4 @@
- local: in_translation
title: (ëČìì€) Utilities for Time Series
title: (ëČìì€) Internal Helpers
- title: (ëČìì€) API
\ No newline at end of file
+ title: (ëČìì€) API
diff --git a/docs/source/ko/accelerate.md b/docs/source/ko/accelerate.md
new file mode 100644
index 000000000000..0ef8957de3ac
--- /dev/null
+++ b/docs/source/ko/accelerate.md
@@ -0,0 +1,136 @@
+
+
+# đ€ Accelerate넌 íì©í ë¶ì° íì”[[distributed-training-with-accelerate]]
+
+ëȘšëžìŽ ì»€ì§ë©Žì ëłë Ź ìČ늏ë ì íë íëìšìŽìì ë í° ëȘšëžì íë šíêł íë š ìë넌 ëȘ ë°°ëĄ ê°ìííêž° ìí ì ë”ìŒëĄ ë±ì„íì”ëë€. Hugging Faceììë ìŹì©ìê° íëì ëšžì ì ìŹëŹ ê°ì GPU넌 ìŹì©íë ìŹëŹ ëšžì ì ìŹëŹ ê°ì GPU넌 ìŹì©íë ëȘšë ì íì ë¶ì° ì€ì ìì đ€ Transformers ëȘšëžì ìœêČ íë ší ì ìëëĄ ëêž° ìíŽ [đ€ Accelerate](https://huggingface.co/docs/accelerate) ëŒìŽëžëŹëŠŹë„Œ ë§ë€ìì”ëë€. ìŽ íí 늏ìŒììë ë¶ì° íêČœìì íë ší ì ìëëĄ êž°ëłž PyTorch íë š 룚í넌 컀ì€í°ë§ìŽìŠíë ë°©ëČì ììëŽ
ìë€.
+
+## ì€ì [[setup]]
+
+đ€ Accelerate ì€ìč ììíêž°:
+
+```bash
+pip install accelerate
+```
+
+ê·ž ë€ì, [`~accelerate.Accelerator`] ê°ìČŽë„Œ ë¶ëŹì€êł ìì±í©ëë€. [`~accelerate.Accelerator`]ë ìëìŒëĄ ë¶ì° ì€ì ì íì ê°ì§íêł íë šì íìí ëȘšë ê”Źì± ìì넌 ìŽêž°íí©ëë€. ì„ìčì ëȘšëžì ëȘ
ìì ìŒëĄ ë°°ìčí íìë ìì”ëë€.
+
+```py
+>>> from accelerate import Accelerator
+
+>>> accelerator = Accelerator()
+```
+
+## ê°ìí넌 ìí ì€ëč[[prepare-to-accelerate]]
+
+ë€ì ëšêłë êŽë šë ëȘšë íë š ê°ìČŽë„Œ [`~accelerate.Accelerator.prepare`] ë©ìëì ì ëŹíë êČì
ëë€. ìŹêž°ìë íë š ë° íê° ë°ìŽí°ëĄë, ëȘšëž ë° ì”í°ë§ìŽì ê° íŹíšë©ëë€:
+
+```py
+>>> train_dataloader, eval_dataloader, model, optimizer = accelerator.prepare(
+... train_dataloader, eval_dataloader, model, optimizer
+... )
+```
+
+## ë°±ìë(Backward)[[backward]]
+
+ë§ì§ë§ìŒëĄ íë š 룚íì ìŒë°ì ìž `loss.backward()`넌 đ€ Accelerateì [`~accelerate.Accelerator.backward`] ë©ìëëĄ ëìČŽíêž°ë§ í멎 ë©ëë€:
+
+```py
+>>> for epoch in range(num_epochs):
+... for batch in train_dataloader:
+... outputs = model(**batch)
+... loss = outputs.loss
+... accelerator.backward(loss)
+
+... optimizer.step()
+... lr_scheduler.step()
+... optimizer.zero_grad()
+... progress_bar.update(1)
+```
+
+ë€ì ìœëìì ëłŒ ì ìëŻìŽ, íë š 룚íì ìœë ë€ ì€ë§ ì¶ê°í멎 ë¶ì° íì”ì íì±íí ì ìì”ëë€!
+
+```diff
++ from accelerate import Accelerator
+ from transformers import AdamW, AutoModelForSequenceClassification, get_scheduler
+
++ accelerator = Accelerator()
+
+ model = AutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=2)
+ optimizer = AdamW(model.parameters(), lr=3e-5)
+
+- device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
+- model.to(device)
+
++ train_dataloader, eval_dataloader, model, optimizer = accelerator.prepare(
++ train_dataloader, eval_dataloader, model, optimizer
++ )
+
+ num_epochs = 3
+ num_training_steps = num_epochs * len(train_dataloader)
+ lr_scheduler = get_scheduler(
+ "linear",
+ optimizer=optimizer,
+ num_warmup_steps=0,
+ num_training_steps=num_training_steps
+ )
+
+ progress_bar = tqdm(range(num_training_steps))
+
+ model.train()
+ for epoch in range(num_epochs):
+ for batch in train_dataloader:
+- batch = {k: v.to(device) for k, v in batch.items()}
+ outputs = model(**batch)
+ loss = outputs.loss
+- loss.backward()
++ accelerator.backward(loss)
+
+ optimizer.step()
+ lr_scheduler.step()
+ optimizer.zero_grad()
+ progress_bar.update(1)
+```
+
+## íì”[[train]]
+
+êŽë š ìœë넌 ì¶ê°í íìë ì€íŹëŠœížë Colaboratoryì ê°ì ë
žížë¶ìì íë šì ììíìžì.
+
+### ì€íŹëŠœížëĄ íì”íêž°[[train-with-a-script]]
+
+ì€íŹëŠœížìì íë šì ì€ííë êČœì°, ë€ì ëȘ
ë čì ì€ííìŹ ê”Źì± íìŒì ìì±íêł ì ì„í©ëë€:
+
+```bash
+accelerate config
+```
+
+Then launch your training with:
+
+```bash
+accelerate launch train.py
+```
+
+### ë
žížë¶ìŒëĄ íì”íêž°[[train-with-a-notebook]]
+
+Collaboratoryì TPU넌 ìŹì©íë €ë êČœì°, ë
žížë¶ììë đ€ Accelerate넌 ì€íí ì ìì”ëë€. íë šì ëŽëčíë ëȘšë ìœë넌 íšìëĄ ê°ìžì [`~accelerate.notebook_launcher`]ì ì ëŹíìžì:
+
+```py
+>>> from accelerate import notebook_launcher
+
+>>> notebook_launcher(training_function)
+```
+
+đ€ Accelerate ë° ë€ìí êž°ë„ì ëí ììží ëŽì©ì [documentation](https://huggingface.co/docs/accelerate)넌 ì°žìĄ°íìžì.
\ No newline at end of file
diff --git a/docs/source/ko/accelerate.mdx b/docs/source/ko/accelerate.mdx
deleted file mode 100644
index e79b7a9bcf69..000000000000
--- a/docs/source/ko/accelerate.mdx
+++ /dev/null
@@ -1,132 +0,0 @@
-
-
-# đ€ Accelerate넌 íì©í ë¶ì° íì”[[distributed-training-with-accelerate]]
-
-ëȘšëžìŽ ì»€ì§ë©Žì ëłë Ź ìČ늏ë ì íë íëìšìŽìì ë í° ëȘšëžì íë šíêł íë š ìë넌 ëȘ ë°°ëĄ ê°ìííêž° ìí ì ë”ìŒëĄ ë±ì„íì”ëë€. Hugging Faceììë ìŹì©ìê° íëì ëšžì ì ìŹëŹ ê°ì GPU넌 ìŹì©íë ìŹëŹ ëšžì ì ìŹëŹ ê°ì GPU넌 ìŹì©íë ëȘšë ì íì ë¶ì° ì€ì ìì đ€ Transformers ëȘšëžì ìœêČ íë ší ì ìëëĄ ëêž° ìíŽ [đ€ Accelerate](https://huggingface.co/docs/accelerate) ëŒìŽëžëŹëŠŹë„Œ ë§ë€ìì”ëë€. ìŽ íí 늏ìŒììë ë¶ì° íêČœìì íë ší ì ìëëĄ êž°ëłž PyTorch íë š 룚í넌 컀ì€í°ë§ìŽìŠíë ë°©ëČì ììëŽ
ìë€.
-
-## ì€ì [[setup]]
-
-đ€ Accelerate ì€ìč ììíêž°:
-
-```bash
-pip install accelerate
-```
-
-ê·ž ë€ì, [`~accelerate.Accelerator`] ê°ìČŽë„Œ ë¶ëŹì€êł ìì±í©ëë€. [`~accelerate.Accelerator`]ë ìëìŒëĄ ë¶ì° ì€ì ì íì ê°ì§íêł íë šì íìí ëȘšë ê”Źì± ìì넌 ìŽêž°íí©ëë€. ì„ìčì ëȘšëžì ëȘ
ìì ìŒëĄ ë°°ìčí íìë ìì”ëë€.
-
-```py
->>> from accelerate import Accelerator
-
->>> accelerator = Accelerator()
-```
-
-## ê°ìí넌 ìí ì€ëč[[prepare-to-accelerate]]
-
-ë€ì ëšêłë êŽë šë ëȘšë íë š ê°ìČŽë„Œ [`~accelerate.Accelerator.prepare`] ë©ìëì ì ëŹíë êČì
ëë€. ìŹêž°ìë íë š ë° íê° ë°ìŽí°ëĄë, ëȘšëž ë° ì”í°ë§ìŽì ê° íŹíšë©ëë€:
-
-```py
->>> train_dataloader, eval_dataloader, model, optimizer = accelerator.prepare(
-... train_dataloader, eval_dataloader, model, optimizer
-... )
-```
-
-## ë°±ìë(Backward)[[backward]]
-
-ë§ì§ë§ìŒëĄ íë š 룚íì ìŒë°ì ìž `loss.backward()`넌 đ€ Accelerateì [`~accelerate.Accelerator.backward`] ë©ìëëĄ ëìČŽíêž°ë§ í멎 ë©ëë€:
-
-```py
->>> for epoch in range(num_epochs):
-... for batch in train_dataloader:
-... outputs = model(**batch)
-... loss = outputs.loss
-... accelerator.backward(loss)
-
-... optimizer.step()
-... lr_scheduler.step()
-... optimizer.zero_grad()
-... progress_bar.update(1)
-```
-
-ë€ì ìœëìì ëłŒ ì ìëŻìŽ, íë š 룚íì ìœë ë€ ì€ë§ ì¶ê°í멎 ë¶ì° íì”ì íì±íí ì ìì”ëë€!
-
-```diff
-+ from accelerate import Accelerator
- from transformers import AdamW, AutoModelForSequenceClassification, get_scheduler
-
-+ accelerator = Accelerator()
-
- model = AutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=2)
- optimizer = AdamW(model.parameters(), lr=3e-5)
-
-- device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
-- model.to(device)
-
-+ train_dataloader, eval_dataloader, model, optimizer = accelerator.prepare(
-+ train_dataloader, eval_dataloader, model, optimizer
-+ )
-
- num_epochs = 3
- num_training_steps = num_epochs * len(train_dataloader)
- lr_scheduler = get_scheduler(
- "linear",
- optimizer=optimizer,
- num_warmup_steps=0,
- num_training_steps=num_training_steps
- )
-
- progress_bar = tqdm(range(num_training_steps))
-
- model.train()
- for epoch in range(num_epochs):
- for batch in train_dataloader:
-- batch = {k: v.to(device) for k, v in batch.items()}
- outputs = model(**batch)
- loss = outputs.loss
-- loss.backward()
-+ accelerator.backward(loss)
-
- optimizer.step()
- lr_scheduler.step()
- optimizer.zero_grad()
- progress_bar.update(1)
-```
-
-## íì”[[train]]
-
-êŽë š ìœë넌 ì¶ê°í íìë ì€íŹëŠœížë Colaboratoryì ê°ì ë
žížë¶ìì íë šì ììíìžì.
-
-### ì€íŹëŠœížëĄ íì”íêž°[[train-with-a-script]]
-
-ì€íŹëŠœížìì íë šì ì€ííë êČœì°, ë€ì ëȘ
ë čì ì€ííìŹ ê”Źì± íìŒì ìì±íêł ì ì„í©ëë€:
-
-```bash
-accelerate config
-```
-
-Then launch your training with:
-
-```bash
-accelerate launch train.py
-```
-
-### ë
žížë¶ìŒëĄ íì”íêž°[[train-with-a-notebook]]
-
-Collaboratoryì TPU넌 ìŹì©íë €ë êČœì°, ë
žížë¶ììë đ€ Accelerate넌 ì€íí ì ìì”ëë€. íë šì ëŽëčíë ëȘšë ìœë넌 íšìëĄ ê°ìžì [`~accelerate.notebook_launcher`]ì ì ëŹíìžì:
-
-```py
->>> from accelerate import notebook_launcher
-
->>> notebook_launcher(training_function)
-```
-
-đ€ Accelerate ë° ë€ìí êž°ë„ì ëí ììží ëŽì©ì [documentation](https://huggingface.co/docs/accelerate)넌 ì°žìĄ°íìžì.
\ No newline at end of file
diff --git a/docs/source/ko/add_new_model.md b/docs/source/ko/add_new_model.md
new file mode 100644
index 000000000000..6ae32d2ac60f
--- /dev/null
+++ b/docs/source/ko/add_new_model.md
@@ -0,0 +1,630 @@
+
+
+# Hugging Face Transformers넌 ì¶ê°íë ë°©ëČì 돎ììžê°ì? [[how-to-add-a-model-to-transformers]]
+
+Hugging Face Transformers ëŒìŽëžëŹëŠŹë ì»€ëź€ëí° êž°ìŹìë€ ëë¶ì ìëĄìŽ ëȘšëžì ì êł”í ì ìë êČœì°ê° ë§ì”ëë€. íì§ë§ ìŽë ëì ì ìž íëĄì ížìŽë©° Hugging Face Transformers ëŒìŽëžëŹëŠŹì ê”Źíí ëȘšëžì ëí êčì ìŽíŽê° íìí©ëë€. Hugging Faceììë ë ë§ì ì»€ëź€ëí° ë©€ëČê° ëȘšëžì ì ê·čì ìŒëĄ ì¶ê°í ì ìëëĄ ì§ìíêł ì íë©°, ìŽ ê°ìŽë넌 í”íŽ PyTorch ëȘšëžì ì¶ê°íë êłŒì ì ìëŽíêł ìì”ëë€ (PyTorchê° ì€ìčëìŽ ìëì§ íìžíŽìŁŒìžì).
+
+
+
+TensorFlow ëȘšëžì ê”Źííêł ì íë êČœì° [đ€ Transformers ëȘšëžì TensorFlowëĄ ëłííë ë°©ëČ](add_tensorflow_model) ê°ìŽë넌 ìŽíŽëłŽìžì!
+
+
+
+ìŽ êłŒì ì ì§íí멎 ë€ìêłŒ ê°ì ëŽì©ì ìŽíŽíêČ ë©ëë€:
+
+- ì€í ìì€ì ëȘšëČ ìŹëĄì ëí í”ì°°ë „ì ì»ì”ëë€.
+- ê°ì„ ìžêž° ìë ë„ëŹë ëŒìŽëžëŹëŠŹì ì€êł ììčì ìŽíŽí©ëë€.
+- ëê·ëȘš ëȘšëžì íšìšì ìŒëĄ í
ì€ížíë ë°©ëČì ë°°ìëë€.
+- `black`, `ruff`, `make fix-copies`ì ê°ì Python ì ížëŠŹí°ë„Œ í”í©íìŹ êčëíêł ê°ë
ì± ìë ìœë넌 ìì±íë ë°©ëČì ë°°ìëë€.
+
+Hugging Face íì íì ëìì ì€ ì€ëčê° ëìŽ ììŒëŻëĄ íŒìê° ìëëŒë ì ì êž°ì”íìžì. đ€ â€ïž
+
+ììì ìì đ€ Transformersì ìíë ëȘšëžì ì¶ê°íêž° ìíŽ [New model addition](https://github.com/huggingface/transformers/issues/new?assignees=&labels=New+model&template=new-model-addition.yml) ìŽì넌 ìŽìŽìŒ í©ëë€. íčì ëȘšëžì êž°ìŹíë ë° íčëłí êčë€ëĄìŽ êž°ì€ì ê°ì§ì§ ìë êČœì° [New model label](https://github.com/huggingface/transformers/labels/New%20model)ì íí°ë§íìŹ ììČëì§ ìì ëȘšëžìŽ ìëì§ íìžíêł ìì
í ì ìì”ëë€.
+
+ìëĄìŽ ëȘšëž ììČì ìŽìë€ë©Ž ìČ« ëČì§ž ëšêłë đ€ Transformersì ì”ìíŽì§ë êČì
ëë€!
+
+## đ€ Transformersì ì ë°ì ìž ê°ì [[general-overview-of-transformers]]
+
+뚌ì đ€ Transformersì ëí ì ë°ì ìž ê°ì넌 íì
íŽìŒ í©ëë€. đ€ Transformersë ë§€ì° ìŁŒêŽì ìž ëŒìŽëžëŹëŠŹìŽêž° ë돞ì íŽëč ëŒìŽëžëŹëŠŹì ìČ íìŽë ì€êł ì í ìŹíì ëìíì§ ìì ìë ìì”ëë€. ê·žëŹë ì°ëŠŹì êČœíì ëŒìŽëžëŹëŠŹì êž°ëłžì ìž ì€êł ì íêłŒ ìČ íì đ€ Transformersì ê·ëȘšë„Œ íšìšì ìŒëĄ íì„í멎ì ì ì§ ëłŽì ëčì©ì í©ëŠŹì ìž ìì€ìŒëĄ ì ì§íë êČì
ëë€.
+
+[ëŒìŽëžëŹëŠŹì ìČ íì ëí 돞ì](philosophy)넌 ìœë êČìŽ ëŒìŽëžëŹëŠŹë„Œ ë ì ìŽíŽíë ìąì ììì ì
ëë€. ëȘšë ëȘšëžì ì ì©íë €ë ëȘ ê°ì§ ìì
ë°©ìì ëí ì í ìŹíìŽ ìì”ëë€:
+
+- ìŒë°ì ìŒëĄ ì¶ìí볎ë€ë ê”Źì±ì ì íží©ëë€.
+- ìœë넌 ëł”ì íë êČìŽ íì ëì êČì ìëëë€. ìœëì ê°ë
ì±ìŽë ì ê·Œì±ì íŹêČ í„ììíšë€ë©Ž ëł”ì íë êČì ìąì”ëë€.
+- ëȘšëž íìŒì ê°ë„í í ë
늜ì ìŒëĄ ì ì§ëìŽìŒ í©ëë€. ë°ëŒì íčì ëȘšëžì ìœë넌 ìœì ë íŽëč `modeling_....py` íìŒë§ íìží멎 ë©ëë€.
+
+ì°ëŠŹë ëŒìŽëžëŹëŠŹì ìœëê° ì íì ì êł”íë ìëšëżë§ ìëëŒ ê°ì íêł ì íë ì íìŽëŒêł ë ìê°í©ëë€. ë°ëŒì ëȘšëžì ì¶ê°í ë, ìŹì©ìë ëȘšëžì ìŹì©í ìŹëëżë§ ìëëŒ ìœë넌 ìœêł ìŽíŽíêł íìí êČœì° ìĄ°ì í ì ìë ëȘšë ìŹëêčì§ë íŹíšíë€ë ì ì êž°ì”íŽìŒ í©ëë€.
+
+ìŽë„Œ ìŒëì ëêł ìŒë°ì ìž ëŒìŽëžëŹëŠŹ ì€êłì ëíŽ ìĄ°êž ë ììží ìì볎êČ ì”ëë€.
+
+### ëȘšëž ê°ì [[overview-of-models]]
+
+ëȘšëžì ì±êł”ì ìŒëĄ ì¶ê°íë €ë©Ž ëȘšëžêłŒ íŽëč ê”Źì±ìž [`PreTrainedModel`] ë° [`PretrainedConfig`] ê°ì ìížìì©ì ìŽíŽíë êČìŽ ì€ìí©ëë€. ì넌 ë€ìŽ, đ€ Transformersì ì¶ê°íë €ë ëȘšëžì `BrandNewBert`ëŒêł ë¶ë„ŽêČ ì”ëë€.
+
+ë€ìì ìŽíŽëłŽêČ ì”ëë€:
+
+
+
+볎ë€ìíŒ, đ€ Transformersììë ììì ìŹì©íì§ë§ ì¶ìí ìì€ì ì”ìíìŒëĄ ì ì§í©ëë€. ëŒìŽëžëŹëŠŹì ìŽë€ ëȘšëžììë ë ìì€ ìŽìì ì¶ìíê° ìĄŽìŹíì§ ìì”ëë€. `BrandNewBertModel`ì `BrandNewBertPreTrainedModel`ìì ììë°êł , ìŽ íŽëì€ë [`PreTrainedModel`]ìì ììë°ì”ëë€. ìŽëĄìš ìëĄìŽ ëȘšëžì [`PreTrainedModel`]ìë§ ììĄŽíëëĄ íë €êł í©ëë€. ëȘšë ìëĄìŽ ëȘšëžì ìëìŒëĄ ì êł”ëë ì€ìí êž°ë„ì [`~PreTrainedModel.from_pretrained`] ë° [`~PreTrainedModel.save_pretrained`]ì
ëë€. ìŽëŹí êž°ë„ ìžìë `BrandNewBertModel.forward`ì ê°ì ë€ë„ž ì€ìí êž°ë„ì ìëĄìŽ `modeling_brand_new_bert.py` ì€íŹëŠœížìì ìì í ì ìëìŽìŒ í©ëë€. ëí `BrandNewBertForMaskedLM`êłŒ ê°ì íčì í€ë ë ìŽìŽë„Œ ê°ì§ ëȘšëžì `BrandNewBertModel`ì ììë°ì§ ìêł forward passìì ížì¶í ì ìë `BrandNewBertModel`ì ìŹì©íìŹ ì¶ìí ìì€ì ëźêČ ì ì§í©ëë€. ëȘšë ìëĄìŽ ëȘšëžì `BrandNewBertConfig`ëŒë ê”Źì± íŽëì€ë„Œ íìëĄ í©ëë€. ìŽ ê”Źì±ì íì [`PreTrainedModel`]ì ìì±ìŒëĄ ì ì„ëë©°, ë°ëŒì `BrandNewBertPreTrainedModel`ì ììë°ë ëȘšë íŽëì€ìì `config` ìì±ì í”íŽ ìĄìžì€í ì ìì”ëë€:
+
+```python
+model = BrandNewBertModel.from_pretrained("brandy/brand_new_bert")
+model.config # model has access to its config
+```
+
+ëȘšëžêłŒ ë§ì°Źê°ì§ëĄ ê”Źì±ì [`PretrainedConfig`]ìì êž°ëłž ì§ë Źí ë° ìì§ë Źí êž°ë„ì ììë°ì”ëë€. ê”Źì±êłŒ ëȘšëžì íì *pytorch_model.bin* íìŒêłŒ *config.json* íìŒëĄ ê°ê° ëłëëĄ ì§ë Źíë©ëë€. [`~PreTrainedModel.save_pretrained`]넌 ížì¶í멎 ìëìŒëĄ [`~PretrainedConfig.save_pretrained`]ë ížì¶ëëŻëĄ ëȘšëžêłŒ ê”Źì±ìŽ ëȘšë ì ì„ë©ëë€.
+
+
+### ìœë ì€íìŒ [[code-style]]
+
+ìëĄìŽ ëȘšëžì ìì±í ë, Transformersë ìŁŒêŽì ìž ëŒìŽëžëŹëŠŹìŽë©° ëȘ ê°ì§ ë
íčí ìœë© ì€íìŒìŽ ìì”ëë€:
+
+1. ëȘšëžì forward passë ëȘšëž íìŒì ìì í ìì±ëìŽìŒ í©ëë€. ëŒìŽëžëŹëŠŹì ë€ë„ž ëȘšëžìì ëžëĄì ìŹìŹì©íë €ë©Ž ìœë넌 ëł”ìŹíìŹ ìì `# Copied from` ìŁŒìêłŒ íšê» ë¶ìŹëŁìŒë©Ž ë©ëë€ (ì: [ìŹêž°](https://github.com/huggingface/transformers/blob/v4.17.0/src/transformers/models/roberta/modeling_roberta.py#L160)넌 ì°žìĄ°íìžì).
+2. ìœëë ìì í ìŽíŽíêž° ìŹììŒ í©ëë€. ëłì ìŽëŠì ëȘ
ííêČ ì§ì íêł ìœìŽë„Œ ìŹì©íì§ ìë êČìŽ ìąì”ëë€. ì넌 ë€ìŽ, `act`볎ë€ë `activation`ì ì íží©ëë€. í êžì ëłì ìŽëŠì 룚íì ìžë±ì€ìž êČœì°ë„Œ ì ìžíêł ê¶ì„ëì§ ìì”ëë€.
+3. ë ìŒë°ì ìŒëĄ, ì§§ì ë§ëČ ê°ì ìœë볎ë€ë êžžêł ëȘ
ìì ìž ìœë넌 ì íží©ëë€.
+4. PyTorchìì `nn.Sequential`ì íì íŽëì€ëĄ ë§ë€ì§ ë§êł `nn.Module`ì íì íŽëì€ëĄ ë§ë€êł forward pass넌 ìì±íìŹ ë€ë„ž ìŹëìŽ ìœë넌 ëč 넎êČ ëëČê·ží ì ìëëĄ í©ëë€. print 돞ìŽë ì€ëšì ì ì¶ê°í ì ìì”ëë€.
+5. íšì ìê·žëìČìë íì
ìŁŒìì ìŹì©íŽìŒ í©ëë€. ê·ž ìžìë íì
ìŁŒìëłŽë€ ëłì ìŽëŠìŽ íšìŹ ìœêž° ìœêł ìŽíŽíêž° ìœì”ëë€.
+
+### í íŹëìŽì ê°ì [[overview-of-tokenizers]]
+
+ìì§ ì€ëčëì§ ììì”ëë€ :-( ìŽ ìčì
ì êł§ ì¶ê°ë ìì ì
ëë€!
+
+## đ€ Transformersì ëȘšëž ì¶ê°íë ëšêłëł ë°©ëČ [[stepbystep-recipe-to-add-a-model-to-transformers]]
+
+ê°ì ëȘšëžì ìŽìíë ë°©ëČì ëí ì ížê° ë€ë„Žêž° ë돞ì ë€ë„ž êž°ìŹìë€ìŽ Hugging Faceì ëȘšëžì ìŽìíë ë°©ëČì ëí ììœì ìŽíŽëłŽë êČìŽ ë§€ì° ì ì©í ì ìì”ëë€. ë€ìì ëȘšëžì ìŽìíë ë°©ëČì ëí ì»€ëź€ëí° ëžëĄê·ž êČìëŹŒ ëȘ©ëĄì
ëë€:
+
+1. [GPT2 ëȘšëž ìŽìíêž°](https://medium.com/huggingface/from-tensorflow-to-pytorch-265f40ef2a28) - [Thomas](https://huggingface.co/thomwolf)
+2. [WMT19 MT ëȘšëž ìŽìíêž°](https://huggingface.co/blog/porting-fsmt) - [Stas](https://huggingface.co/stas)
+
+êČœíì ëȘšëžì ì¶ê°í ë ìŁŒìíŽìŒ í ê°ì„ ì€ìí ìŹíì ë€ìêłŒ ê°ì”ëë€:
+
+- ê°ì ìŒì ë°ëł”íì§ ë§ìžì! ìëĄìŽ đ€ Transformers ëȘšëžì ìíŽ ì¶ê°í ìœëì ëë¶ë¶ì ìŽëŻž đ€ Transformers ìŽëê°ì ìĄŽìŹí©ëë€. ìŽëŻž ìĄŽìŹíë ëł”ìŹí ì ìë ì ìŹí ëȘšëžêłŒ í íŹëìŽì 넌 ì°Ÿëë° ìê°ì íŹìíìžì. [grep](https://www.gnu.org/software/grep/)ì [rg](https://github.com/BurntSushi/ripgrep)넌 ì°žêł íìžì. ëȘšëžì í íŹëìŽì ê° í ëȘšëžì êž°ë°ìŒëĄ íêł ëȘšëžë§ ìœëê° ë€ë„ž ëȘšëžì êž°ë°ìŒëĄ íë êČœì°ê° ìĄŽìŹí ìë ìì”ëë€. ì넌 ë€ìŽ FSMTì ëȘšëžë§ ìœëë BART넌 êž°ë°ìŒëĄ íêł FSMTì í íŹëìŽì ìœëë XLMì êž°ë°ìŒëĄ í©ëë€.
+- ìŽêČì êłŒíì ìž ëì 볎ë€ë êł”íì ìž ëì ì
ëë€. ë
ŒëŹžì ëȘšëžì ëȘšë ìŽëĄ ì ìžĄë©Žì ìŽíŽíë €ë êČëłŽë€ íšìšì ìž ëëČêč
íêČœì ë§ëë ë° ë ë§ì ìê°ì ìëčíŽìŒ í©ëë€.
+- ë§í ë ëìì ììČíìžì! ëȘšëžì đ€ Transformersì í”ìŹ ê”Źì± ìììŽëŻëĄ Hugging Faceì ì°ëŠŹë ëčì ìŽ ëȘšëžì ì¶ê°íë ê° ëšêłìì êž°êșŒìŽ ëìì ì€ ì€ëčê° ëìŽ ìì”ëë€. ì§ì ìŽ ìë€êł ëëŒë©Ž ìŁŒì íì§ ë§êł ëìì ììČíìžì.
+
+ë€ìììë ëȘšëžì đ€ TransformersëĄ ìŽìíë ë° ê°ì„ ì ì©í ìŒë°ì ìž ì 찚넌 ì êł”íë €êł ë
žë „í©ëë€.
+
+ë€ì ëȘ©ëĄì ëȘšëžì ì¶ê°íë ë° ìííŽìŒ í ëȘšë ìì
ì ììœìŽë©° To-Do ëȘ©ëĄìŒëĄ ìŹì©í ì ìì”ëë€:
+
+â (ì í ìŹí) BrandNewBertì ìŽëĄ ì ìžĄë©Ž ìŽíŽ
+â Hugging Face ê°ë° íêČœ ì€ëč
+â ìëłž 늏íŹì§í 늏ì ëëČêč
íêČœ ì€ì
+â ìëłž 늏íŹì§í 늏ì ìČŽíŹíŹìžížë„Œ ìŹì©íìŹ `forward()` passê° ì±êł”ì ìŒëĄ ì€íëë ì€íŹëŠœíž ìì±
+â đ€ Transformersì ëȘšëž ì€ìŒë í€ ì±êł”ì ìŒëĄ ì¶ê°
+â ìëłž ìČŽíŹíŹìžížë„Œ đ€ Transformers ìČŽíŹíŹìžížëĄ ì±êł”ì ìŒëĄ ëłí
+â đ€ Transformersìì ìëłž ìČŽíŹíŹìžížì ëìŒí ì¶ë „ì ëŽìŁŒë `forward()` pass ì±êł”ì ìŒëĄ ì€í
+â đ€ Transformersìì ëȘšëž í
ì€íž ìëŁ
+â đ€ Transformersì í íŹëìŽì ì±êł”ì ìŒëĄ ì¶ê°
+â ìą
ëš ê° í”í© í
ì€íž ì€í
+â 돞ì ìì± ìëŁ
+â ëȘšëž ê°ì€ìč넌 íëžì ì
ëĄë
+â Pull request ì ì¶
+â (ì í ìŹí) ë°ëȘš ë
žížë¶ ì¶ê°
+
+ì°ì , ìŒë°ì ìŒëĄë `BrandNewBert`ì ìŽëĄ ì ìž ìŽíŽëĄ ììíë êČì ê¶ì„í©ëë€. ê·žëŹë ìŽëĄ ì ìžĄë©Žì ì§ì ìŽíŽíë ëì *ì§ì íŽëłŽë©Žì* ëȘšëžì ìŽëĄ ì ìžĄë©Žì ìŽíŽíë êČì ì ížíë êČœì° ë°ëĄ `BrandNewBert` ìœë ëČ ìŽì€ëĄ ëč ì žëë êČë êŽì°źì”ëë€. ìŽ ì”ì
ì ìì§ëìŽë§ êž°ì ìŽ ìŽëĄ ì êž°ì ëłŽë€ ë ë°ìŽë êČœì°, `BrandNewBert`ì ë
ŒëŹžì ìŽíŽíë ë° ìŽë €ììŽ ìë êČœì°, ëë êłŒíì ìž ë
ŒëŹžì ìœë êČëłŽë€ íëĄê·žëë°ì íšìŹ ë í„믞 ìë êČœì°ì ë ì í©í ì ìì”ëë€.
+
+### 1. (ì í ìŹí) BrandNewBertì ìŽëĄ ì ìžĄë©Ž [[1-optional-theoretical-aspects-of-brandnewbert]]
+
+ë§ìœ ê·žë° ìì ì ìž ìì
ìŽ ìĄŽìŹíë€ë©Ž, *BrandNewBert*ì ë
ŒëŹžì ìœìŽëłŽë ìê°ì ê°ì žìŒ í©ëë€. ìŽíŽíêž° ìŽë €ìŽ ìčì
ìŽ ë§ì ì ìì”ëë€. ê·žë ëëŒë ê±±ì íì§ ë§ìžì! ëȘ©íë ë
ŒëŹžì êčì ìŽëĄ ì ìŽíŽê° ìëëŒ *BrandNewBert*넌 đ€ Transformersìì íšêłŒì ìŒëĄ ìŹê”Źííêž° ìíŽ íìí ì ëłŽë„Œ ì¶ì¶íë êČì
ëë€. ìŽë„Œ ìíŽ ìŽëĄ ì ìžĄë©Žì ë돎 ë§ì ìê°ì íŹìí íìë ìì§ë§ ë€ìêłŒ ê°ì ì€ì ì ìž ìžĄë©Žì ì§ì€íŽìŒ í©ëë€:
+
+- *BrandNewBert*ë ìŽë€ ì íì ëȘšëžìžê°ì? BERTì ì ìŹí ìžìœë ëȘšëžìžê°ì? GPT2ì ì ìŹí ëìœë ëȘšëžìžê°ì? BARTì ì ìŹí ìžìœë-ëìœë ëȘšëžìžê°ì? ìŽë€ ê°ì ì°šìŽì ì ì”ìíì§ ìì êČœì°[model_summary](model_summary)넌 ì°žìĄ°íìžì.
+- *BrandNewBert*ì ìì© ë¶ìŒë 돎ììžê°ì? í
ì€íž ë¶ë„ìžê°ì? í
ì€íž ìì±ìžê°ì? ììœêłŒ ê°ì Seq2Seq ìì
ìžê°ì?
+- *brand_new_bert*ì BERT/GPT-2/BARTì ì°šìŽì ì 돎ììžê°ì?
+- *brand_new_bert*ì ê°ì„ ì ìŹí [đ€ Transformers ëȘšëž](https://huggingface.co/transformers/#contents)ì 돎ììžê°ì?
+- ìŽë€ ìą
ë„ì í íŹëìŽì ê° ìŹì©ëëì? Sentencepiece í íŹëìŽì ìžê°ì? Word piece í íŹëìŽì ìžê°ì? BERT ëë BARTì ìŹì©ëë ëìŒí í íŹëìŽì ìžê°ì?
+
+ëȘšëžì ìí€í
ìČì ëíŽ ì¶©ë¶í ìŽíŽíë€ë ìê°ìŽ ë í, ê¶êží ìŹíìŽ ììŒë©Ž Hugging Face íì 돞ìíììì€. ìŽë ëȘšëžì ìí€í
ìČ, ìŽí
ì
ë ìŽìŽ ë±ì êŽí ì§ëŹžì íŹíší ì ìì”ëë€. Hugging Faceì ì ì§ êŽëŠŹìë€ì ëłŽí” ìœë넌 êČí íë êČì ëíŽ ë§€ì° êž°ë»íëŻëĄ ëčì ì ëë ìŒì ë§€ì° íìí êČì
ëë€!
+
+### 2. ê°ë° íêČœ ì€ì [[2-next-prepare-your-environment]]
+
+1. ì ì„ì íìŽì§ìì "Fork" ëČíŒì íŽëŠíìŹ ì ì„ìì ìŹëłžì GitHub ìŹì©ì êłì ìŒëĄ ë§ëëë€.
+
+2. `transformers` fork넌 ëĄì»Ź ëì€íŹì íŽëĄ íêł ëČ ìŽì€ ì ì„ì넌 ìêČ© ì ì„ìëĄ ì¶ê°í©ëë€:
+
+```bash
+git clone https://github.com/[your Github handle]/transformers.git
+cd transformers
+git remote add upstream https://github.com/huggingface/transformers.git
+```
+
+3. ê°ë° íêČœì ì€ì í©ëë€. ë€ì ëȘ
ë čì ì€ííìŹ ê°ë° íêČœì ì€ì í ì ìì”ëë€:
+
+```bash
+python -m venv .env
+source .env/bin/activate
+pip install -e ".[dev]"
+```
+
+ê° ìŽì ìČŽì ì ë°ëŒ Transformersì ì íì ììĄŽì±ìŽ ê°ìê° ìŠê°í멎 ìŽ ëȘ
ë čìŽ ì€íší ì ìì”ëë€. ê·žë° êČœì°ìë ìì
ì€ìž ë„ ëŹë íë ììíŹ (PyTorch, TensorFlow ë°/ëë Flax)ì ì€ìčí í, ë€ì ëȘ
ë čì ìíí멎 ë©ëë€:
+
+```bash
+pip install -e ".[quality]"
+```
+
+ëë¶ë¶ì êČœì°ìë ìŽêČìŒëĄ ì¶©ë¶í©ëë€. ê·žë° ë€ì ìì ëë í ëŠŹëĄ ëìê°ëë€.
+
+```bash
+cd ..
+```
+
+4. Transformersì *brand_new_bert*ì PyTorch ëČì ì ì¶ê°íë êČì ê¶ì„í©ëë€. PyTorch넌 ì€ìčíë €ë©Ž ë€ì ë§íŹì ì§ìčšì ë°ë„Žììì€: https://pytorch.org/get-started/locally/.
+
+**ì°žêł :** CUDA넌 ì€ìčí íìë ìì”ëë€. ìëĄìŽ ëȘšëžìŽ CPUìì ìëíëëĄ ë§ëë êČìŒëĄ ì¶©ë¶í©ëë€.
+
+5. *brand_new_bert*넌 ìŽìíêž° ìíŽìë íŽëč ìëłž ì ì„ìì ì ê·Œí ì ììŽìŒ í©ëë€:
+
+```bash
+git clone https://github.com/org_that_created_brand_new_bert_org/brand_new_bert.git
+cd brand_new_bert
+pip install -e .
+```
+
+ìŽì *brand_new_bert*넌 đ€ TransformersëĄ ìŽìíêž° ìí ê°ë° íêČœì ì€ì íìì”ëë€.
+
+### 3.-4. ìëłž ì ì„ììì ìŹì íë šë ìČŽíŹíŹìžíž ì€ííêž° [[3.-4.-run-a-pretrained-checkpoint-using-the-original-repository]]
+
+뚌ì , ìëłž *brand_new_bert* ì ì„ììì ìì
ì ììí©ëë€. ìëłž ê”Źíì ëłŽí” "ì°ê”Źì©"ìŒëĄ ë§ìŽ ìŹì©ë©ëë€. ìŠ, 돞ìíê° ë¶ìĄ±íêł ìœëê° ìŽíŽíêž° ìŽë €ìž ì ìì”ëë€. ê·žëŹë ìŽêČìŽ ë°ëĄ *brand_new_bert*넌 ë€ì ê”Źííë €ë ëêž°ê° ëìŽìŒ í©ëë€. Hugging Faceììì ìŁŒì ëȘ©í ì€ íëë **ê±°ìžì ìŽêčš ìì ìë êČ**ìŽë©°, ìŽë ìŹêž°ìì ìœêČ íŽìëìŽ ëìíë ëȘšëžì ê°ì žìì ê°ë„í í **ì ê·Œ ê°ë„íêł ìŹì©ì ìčíì ìŽë©° ìëŠë”êČ** ë§ëë êČì
ëë€. ìŽêČì đ€ Transformersìì ëȘšëžì ë€ì ê”Źííë ê°ì„ ì€ìí ëêž°ì
ëë€ - ìëĄìŽ ëł”ìĄí NLP êž°ì ì **ëȘšëìêČ** ì ê·Œ ê°ë„íêČ ë§ëë êČì ëȘ©íëĄ í©ëë€.
+
+ë°ëŒì ìëłž ì ì„ìì ëíŽ ììží ìŽíŽëłŽë êČìŒëĄ ììíŽìŒ í©ëë€.
+
+ìëłž ì ì„ììì êł”ì ìŹì íë šë ëȘšëžì ì±êł”ì ìŒëĄ ì€ííë êČì ìą
ìą
**ê°ì„ ìŽë €ìŽ** ëšêłì
ëë€. ì°ëŠŹì êČœíì ë°ë„Žë©Ž, ìëłž ìœë ëČ ìŽì€ì ì”ìíŽì§ë ë° ìê°ì íŹìíë êČìŽ ë§€ì° ì€ìí©ëë€. ë€ìì íì
íŽìŒ í©ëë€:
+
+- ìŹì íë šë ê°ì€ìč넌 ìŽëì ì°Ÿì ì ìëì§?
+- ìŹì íë šë ê°ì€ìč넌 íŽëč ëȘšëžìëĄëíë ë°©ëČì?
+- ëȘšëžêłŒ ë
늜ì ìŒëĄ í íŹëìŽì 넌 ì€ííë ë°©ëČì?
+- ê°ëší forward passì íìí íŽëì€ì íšì넌 íì
íêž° ìíŽ forward pass넌 í ëČ ì¶ì íŽ ëłŽìžì. ìŒë°ì ìŒëĄ íŽëč íšìë€ë§ ë€ì ê”Źíí멎 ë©ëë€.
+- ëȘšëžì ì€ìí ê”Źì± ìì넌 ì°Ÿì ì ììŽìŒ í©ëë€. ëȘšëž íŽëì€ë ìŽëì ìëì? ëȘšëž íì íŽëì€(*EncoderModel*, *DecoderModel* ë±)ê° ìëì? self-attention ë ìŽìŽë ìŽëì ìëì? self-attention, cross-attention ë± ìŹëŹ ê°ì§ ë€ë„ž ìŽí
ì
ë ìŽìŽê° ìëì?
+- ìëłž íêČœìì ëȘšëžì ëëČê·ží ì ìë ë°©ëČì 돎ììžê°ì? *print* 돞ì ì¶ê°íŽìŒ íëì? *ipdb*ì ê°ì ëíì ëëČ거넌 ìŹì©í ì ìëì? PyCharmêłŒ ê°ì íšìšì ìž IDE넌 ìŹì©íŽ ëȘšëžì ëëČê·ží ì ìëì?
+
+ìëłž ì ì„ììì ìœë넌 ìŽìíë ìì
ì ììíêž° ì ì ìëłž ì ì„ììì ìœë넌 **íšìšì ìŒëĄ** ëëČê·ží ì ììŽìŒ í©ëë€! ëí, ì€í ìì€ ëŒìŽëžëŹëŠŹëĄ ìì
íêł ìë€ë êČì êž°ì”íŽìŒ í©ëë€. ë°ëŒì ìëłž ì ì„ììì issue넌 ìŽê±°ë pull request넌 ìŽêž°ë„Œ ìŁŒì íì§ ë§ììì€. ìŽ ì ì„ìì ì ì§ êŽëŠŹìë€ì ëê”°ê°ê° ìì ë€ì ìœë넌 ìŽíŽëłžë€ë êČì ëíŽ ë§€ì° êž°ë»í êČì
ëë€!
+
+íìŹ ìì ìì, ìë ëȘšëžì ëëČêč
íêž° ìíŽ ìŽë€ ëëČêč
íêČœêłŒ ì ë”ì ì ížíëì§ë ëčì ìêČ ëŹë žì”ëë€. ì°ëŠŹë êł ê°ì GPU íêČœì ê”Źì¶íë êČì ëčì¶ìČí©ëë€. ëì , ìë ì ì„ìëĄ ë€ìŽê°ì ìì
ì ììí ëì đ€ Transformers ëȘšëžì ê”Źíì ììí ëìë CPUìì ìì
íë êČìŽ ìąì”ëë€. ëȘšëžìŽ ìŽëŻž đ€ TransformersëĄ ì±êł”ì ìŒëĄ ìŽìëìì ëìë§ ëȘšëžìŽ GPUììë ììëëĄ ìëíëì§ íìžíŽìŒí©ëë€.
+
+ìŒë°ì ìŒëĄ, ìë ëȘšëžì ì€ííêž° ìí ë ê°ì§ ê°ë„í ëëČêč
íêČœìŽ ìì”ëë€.
+
+- [Jupyter ë
žížë¶](https://jupyter.org/) / [Google Colab](https://colab.research.google.com/notebooks/intro.ipynb)
+- ëĄì»Ź Python ì€íŹëŠœíž
+
+Jupyter ë
žížë¶ì ì„ì ì ì
ëšìëĄ ì€íí ì ìë€ë êČì
ëë€. ìŽë ë
ŒëŠŹì ìž ê”Źì± ìì넌 ë ì ë¶ëŠŹíêł ì€ê° êČ°êłŒë„Œ ì ì„í ì ììŒëŻëĄ ëëČêč
ìŹìŽíŽìŽ ë ëčšëŒì§ ì ìì”ëë€. ëí, ë
žížë¶ì ë€ë„ž êž°ìŹìì ìœêČ êł”ì í ì ììŒëŻëĄ Hugging Face íì ëìì ììČíë €ë êČœì° ë§€ì° ì ì©í ì ìì”ëë€. Jupyter ë
žížë¶ì ì”ìíë€ë©Ž ìŽë„Œ ìŹì©íë êČì ê°ë „í ì¶ìČí©ëë€.
+
+Jupyter ë
žížë¶ì ëšì ì ìŹì©ì ì”ìíì§ ìì êČœì° ìëĄìŽ íëĄê·žëë° íêČœì ì ìíë ë° ìê°ì í ì íŽìŒ íë©°, `ipdb`ì ê°ì ìë €ì§ ëëČêč
ëê”Źë„Œ ë ìŽì ìŹì©í ì ìì ìë ìë€ë êČì
ëë€.
+
+ê° ìœë ëČ ìŽì€ì ëíŽ ìąì ìČ« ëČì§ž ëšêłë íì **ìì** ìŹì íë šë ìČŽíŹíŹìžížë„Œ ëĄëíêł ë믞 ì ì ëČĄí° ì
ë „ì ìŹì©íìŹ ëšìŒ forward pass넌 ìŹííë êČì
ëë€. ìŽì ê°ì ì€íŹëŠœížë ë€ìêłŒ ê°ì ì ìì”ëë€(ììŹ ìœëëĄ ìì±):
+
+```python
+model = BrandNewBertModel.load_pretrained_checkpoint("/path/to/checkpoint/")
+input_ids = [0, 4, 5, 2, 3, 7, 9] # vector of input ids
+original_output = model.predict(input_ids)
+```
+
+ë€ììŒëĄ, ëëČêč
ì ë”ì ëíŽ ìŒë°ì ìŒëĄ ë€ìêłŒ ê°ì ëȘ ê°ì§ ì íì§ê° ìì”ëë€:
+
+- ìëłž ëȘšëžì ë§ì ìì í
ì€íž ê°ë„í ê”Źì± ììëĄ ë¶íŽíêł ê°ê°ì ëíŽ forward pass넌 ì€ííìŹ êČìŠí©ëë€.
+- ìëłž ëȘšëžì ìëłž *tokenizer*êłŒ ìëłž *model*ëĄë§ ë¶íŽíêł íŽëč ë¶ë¶ì ëíŽ forward pass넌 ì€íí í êČìŠì ìíŽ ì€ê° ì¶ë „(print 돞 ëë ì€ëšì )ì ìŹì©í©ëë€.
+
+ë€ì ë§íì§ë§, ìŽë€ ì ë”ì ì íí ì§ë ëčì ìêČ ëŹë € ìì”ëë€. ìëłž ìœë ëČ ìŽì€ì ë°ëŒ íë ëë ë€ë„ž ì ë”ìŽ ì 늏í ì ìì”ëë€.
+
+ìëłž ìœë ëČ ìŽì€ë„Œ ëȘšëžì ìì íì ê”Źì± ììëĄ ë¶íŽí ì ìëì§ ìŹë¶, ì넌 ë€ìŽ ìëłž ìœë ëČ ìŽì€ê° ìŠì ì€í ëȘšëìì ê°ëší ì€íë ì ìë êČœì°, ê·žë° êČœì°ìë ê·ž ë
žë „ìŽ ê°ìčê° ìë€ë êČìŽ ìŒë°ì ì
ëë€. ìŽêž°ì ë ìŽë €ìŽ ë°©ëČì ì ííë êČìë ëȘ ê°ì§ ì€ìí ì„ì ìŽ ìì”ëë€.
+
+- ìëłž ëȘšëžì đ€ Transformers ê”ŹíêłŒ ëčê”í ë ê° ê”Źì± ììê° ìŒìčíëì§ ìëìŒëĄ íìží ì ìì”ëë€. ìŠ, ìê°ì ìž ëčê”(print 돞ì í”í ëčê”ê° ìë) ëì đ€ Transformers ê”ŹíêłŒ ê·žì ëìíë ìëłž ê”Źì± ììê° ìŒìčíëì§ íìží ì ìì”ëë€.
+- ì ìČŽ ëȘšëžì ëȘšëëłëĄ, ìŠ ìì ê”Źì± ììëĄ ë¶íŽíšìŒëĄìš ëȘšëžì ìŽìíë í° ëŹžì 넌 ëšìí ê°ëł ê”Źì± ìì넌 ìŽìíë ìì 돞ì ëĄ ë¶íŽí ì ììŒëŻëĄ ìì
ì ë ì ê”ŹìĄ°íí ì ìì”ëë€.
+- ëȘšëžì ë
ŒëŠŹì ìŒëĄ ì믞 ìë ê”Źì± ììëĄ ë¶ëŠŹíë êČì ëȘšëžì ì€êłì ëí ë ëì ê°ì넌 ì»êł ëȘšëžì ë ì ìŽíŽíë ë° ëììŽ ë©ëë€.
+- ìŽëŹí ê”Źì± ììëł í
ì€ížë„Œ í”íŽ ìœë넌 ëłêČœí멎ì íê·ê° ë°ìíì§ ìëëĄ ëłŽì„í ì ìì”ëë€.
+
+[Lysandreì ELECTRA í”í© êČìŹ](https://gist.github.com/LysandreJik/db4c948f6b4483960de5cbac598ad4ed)ë ìŽë„Œ ìííë ìąì ìì ì
ëë€.
+
+ê·žëŹë ìëłž ìœë ëČ ìŽì€ê° ë§€ì° ëł”ìĄíê±°ë ì€ê° ê”Źì± ìì넌 컎íìŒë ëȘšëìì ì€ííë êČë§ íì©íë êČœì°, ëȘšëžì í
ì€íž ê°ë„í ìì íì ê”Źì± ììëĄ ë¶íŽíë êČìŽ ìê°ìŽ ë§ìŽ ììëê±°ë ë¶ê°ë„í ìë ìì”ëë€. [T5ì MeshTensorFlow](https://github.com/tensorflow/mesh/tree/master/mesh_tensorflow) ëŒìŽëžëŹëŠŹë ë§€ì° ëł”ìĄíë©° ëȘšëžì íì ê”Źì± ììëĄ ë¶íŽíë ê°ëší ë°©ëČì ì êł”íì§ ìì”ëë€. ìŽëŹí ëŒìŽëžëŹëŠŹì êČœì°, ëłŽí” print 돞ì í”íŽ íìží©ëë€.
+
+ìŽë€ ì ë”ì ì ííëëŒë ê¶ì„ëë ì ì°šë ëìŒí©ëë€. 뚌ì ìì ë ìŽìŽë„Œ ëëČê·žíêł ë§ì§ë§ ë ìŽìŽë„Œ ë§ì§ë§ì ëëČê·žíë êČìŽ ìąì”ëë€.
+
+ë€ì ììëĄ ê° ë ìŽìŽì ì¶ë „ì êČìíë êČìŽ ìąì”ëë€:
+
+1. ëȘšëžì ì ëŹë ì
ë „ ID ê°ì žì€êž°
+2. ìë ìëČ ë© ê°ì žì€êž°
+3. ìČ« ëČì§ž Transformer ë ìŽìŽì ì
ë „ ê°ì žì€êž°
+4. ìČ« ëČì§ž Transformer ë ìŽìŽì ì¶ë „ ê°ì žì€êž°
+5. ë€ì n-1ê°ì Transformer ë ìŽìŽì ì¶ë „ ê°ì žì€êž°
+6. BrandNewBert ëȘšëžì ì¶ë „ ê°ì žì€êž°
+
+ì
ë „ IDë ì ì ë°°ìŽëĄ ê”Źì±ëë©°, ì넌 ë€ìŽ `input_ids = [0, 4, 4, 3, 2, 4, 1, 7, 19]`ì ê°ì ì ìì”ëë€.
+
+ë€ì ë ìŽìŽì ì¶ë „ì ìą
ìą
ë€ì°šì ì€ì ë°°ìŽëĄ ê”Źì±ëë©°, ë€ìêłŒ ê°ìŽ ëíëŒ ì ìì”ëë€:
+
+```
+[[
+ [-0.1465, -0.6501, 0.1993, ..., 0.1451, 0.3430, 0.6024],
+ [-0.4417, -0.5920, 0.3450, ..., -0.3062, 0.6182, 0.7132],
+ [-0.5009, -0.7122, 0.4548, ..., -0.3662, 0.6091, 0.7648],
+ ...,
+ [-0.5613, -0.6332, 0.4324, ..., -0.3792, 0.7372, 0.9288],
+ [-0.5416, -0.6345, 0.4180, ..., -0.3564, 0.6992, 0.9191],
+ [-0.5334, -0.6403, 0.4271, ..., -0.3339, 0.6533, 0.8694]]],
+```
+
+đ€ Transformersì ì¶ê°ëë ëȘšë ëȘšëžì í”í© í
ì€ížë„Œ í”êłŒíŽìŒ í©ëë€. ìŠ, ìëłž ëȘšëžêłŒ đ€ Transformersì ìŹê”Źí ëČì ìŽ 0.001ì ì ë°ëëĄ ì íí ëìŒí ì¶ë „ì ëŽìŒ í©ëë€! ëìŒí ëȘšëžìŽ ë€ë„ž ëŒìŽëžëŹëŠŹìì ìì±ëìì ë ëŒìŽëžëŹëŠŹ íë ììíŹì ë°ëŒ ìœê° ë€ë„ž ì¶ë „ì ì»ë êČì ì ììŽëŻëĄ 1e-3(0.001)ì ì€ì°šë íì©í©ëë€. ê±°ì ëìŒí ì¶ë „ì ëŽë êČë§ìŒëĄë ì¶©ë¶íì§ ììŒë©°, ìëČœí ìŒìčíë ìì€ìŽìŽìŒ í©ëë€. ë°ëŒì đ€ Transformers ëČì ì ì€ê° ì¶ë „ì *brand_new_bert*ì ìë ê”Źíì ì€ê° ì¶ë „êłŒ ìŹëŹ ëČ ëčê”íŽìŒ í©ëë€. ìŽ êČœì° ìëłž ì ì„ìì **íšìšì ìž** ëëČêč
íêČœìŽ ì ëì ìŒëĄ ì€ìí©ëë€. ëëČêč
íêČœì ê°ë„í í íšìšì ìŒëĄ ë§ëë ëȘ ê°ì§ ìĄ°ìžì ì ìí©ëë€.
+
+- ì€ê° êČ°êłŒë„Œ ëëČê·žíë ê°ì„ ìąì ë°©ëČì ì°ŸìŒìžì. ìëłž ì ì„ìê° PyTorchëĄ ìì±ëìë€ë©Ž ìëłž ëȘšëžì ë ìì íì ê”Źì± ììëĄ ë¶íŽíìŹ ì€ê° ê°ì êČìíë ꞎ ì€íŹëŠœížë„Œ ìì±íë êČì ìê°ì íŹìí ê°ìčê° ìì”ëë€. ìëłž ì ì„ìê° Tensorflow 1ëĄ ìì±ëìë€ë©Ž [tf.print](https://www.tensorflow.org/api_docs/python/tf/print)ì ê°ì Tensorflow ì¶ë „ ìì
ì ìŹì©íìŹ ì€ê° ê°ì ì¶ë „íŽìŒ í ìë ìì”ëë€. ìëłž ì ì„ìê° JaxëĄ ìì±ëìë€ë©Ž forward pass넌 ì€íí ë ëȘšëžìŽ **jit ëì§ ìëëĄ** íŽìŒ í©ëë€. ì넌 ë€ìŽ [ìŽ ë§íŹ](https://github.com/google/jax/issues/196)넌 íìžíŽ ëłŽìžì.
+- ìŹì© ê°ë„í ê°ì„ ìì ìŹì íë šë ìČŽíŹíŹìžížë„Œ ìŹì©íìžì. ìČŽíŹíŹìžížê° ìììëĄ ëëČê·ž ìŹìŽíŽìŽ ë ëčšëŒì§ëë€. ì ë°ì ìŒëĄ forward passì 10ìŽ ìŽììŽ ê±žëŠŹë êČœì° íšìšì ìŽì§ ìì”ëë€. ë§€ì° í° ìČŽíŹíŹìžížë§ ìŹì©í ì ìë êČœì°, ì íêČœìì ììëĄ ìŽêž°íë ê°ì€ìčëĄ ë믞 ëȘšëžì ë§ë€êł íŽëč ê°ì€ìč넌 đ€ Transformers ëČì êłŒ ëčê”íêž° ìíŽ ì ì„íë êČìŽ ë ìëŻžê° ìì ì ìì”ëë€.
+- ëëČêč
ì€ì ìì ê°ì„ ìœêČ forward pass넌 ížì¶íë ë°©ëČì ìŹì©íìžì. ìëłž ì ì„ììì **ëšìŒ** forward passë§ ížì¶íë íšì넌 ì°Ÿë êČìŽ ìŽìì ì
ëë€. ìŽ íšìë ìŒë°ì ìŒëĄ `predict`, `evaluate`, `forward`, `__call__`êłŒ ê°ìŽ ížì¶ë©ëë€. `autoregressive_sample`êłŒ ê°ì í
ì€íž ìì±ìì `forward`넌 ìŹëŹ ëČ ížì¶íìŹ í
ì€ížë„Œ ìì±íë ë±ì ìì
ì ìííë íšì넌 ëëČê·žíêł ì¶ì§ ìì êČì
ëë€.
+- í í°í êłŒì ì ëȘšëžì *forward* passì ë¶ëŠŹíë €êł ë
žë „íìžì. ìëłž ì ì„ììì ì
ë „ 돞ììŽì ì
ë „íŽìŒ íë ìì ê° ìë êČœì°, ì
ë „ 돞ììŽìŽ ì
ë „ IDëĄ ëłêČœëë ìê°ì ì°Ÿìì ììíìžì. ìŽ êČœì° ì§ì ID넌 ì
ë „í ì ìëëĄ ìì ì€íŹëŠœížë„Œ ìì±íê±°ë ìëłž ìœë넌 ìì íŽìŒ í ìë ìì”ëë€.
+- ëëČêč
ì€ì ìì ëȘšëžìŽ íë š ëȘšëê° ìëëŒë êČì íìžíìžì. íë š ëȘšëììë ëȘšëžì ìŹëŹ ëëĄìì ë ìŽìŽ ë돞ì 돎ìì ì¶ë „ìŽ ìì±ë ì ìì”ëë€. ëëČêč
íêČœìì forward passê° **êȰì ëĄ ì **ìŽëëĄ íŽìŒ í©ëë€. ëë ëìŒí íë ììíŹì ìë êČœì° *transformers.utils.set_seed*넌 ìŹì©íìžì.
+
+ë€ì ìčì
ììë *brand_new_bert*ì ëíŽ ìŽ ìì
ì ìííë ë° ë ê”ŹìČŽì ìž ìžë¶ ìŹí/íì ì êł”í©ëë€.
+
+### 5.-14. đ€ Transformersì BrandNewBert넌 ìŽìíêž° [[5.-14.-port-brandnewbert-to-transformers]]
+
+ìŽì , ë§ìčšëŽ đ€ Transformersì ìëĄìŽ ìœë넌 ì¶ê°í ì ìì”ëë€. đ€ Transformers íŹíŹì íŽëĄ ìŒëĄ ìŽëíìžì:
+
+```bash
+cd transformers
+```
+
+ë€ìêłŒ ê°ìŽ ìŽëŻž ìĄŽìŹíë ëȘšëžì ëȘšëž ìí€í
ìČì ì íí ìŒìčíë ëȘšëžì ì¶ê°íë íčëłí êČœì°ìë [ìŽ ìčì
](#write-a-conversion-script)ì ì€ëȘ
ëëëĄ ëłí ì€íŹëŠœížë§ ì¶ê°í멎 ë©ëë€. ìŽ êČœì°ìë ìŽëŻž ìĄŽìŹíë ëȘšëžì ì ìČŽ ëȘšëž ìí€í
ìČ넌 ê·žëëĄ ìŹìŹì©í ì ìì”ëë€.
+
+ê·žë ì§ ììŒë©Ž ìëĄìŽ ëȘšëž ìì±ì ììí©ìë€. ìŹêž°ìì ë ê°ì§ ì íì§ê° ìì”ëë€:
+
+- `transformers-cli add-new-model-like`넌 ìŹì©íìŹ êž°ìĄŽ ëȘšëžêłŒ ì ìŹí ìëĄìŽ ëȘšëž ì¶ê°íêž°
+- `transformers-cli add-new-model`ì ìŹì©íìŹ í
í늿ì êž°ë°ìŒëĄ í ìëĄìŽ ëȘšëž ì¶ê°íêž° (ì íí ëȘšëž ì íì ë°ëŒ BERT ëë Bartì ì ìŹí ëȘšì”ìŒ êČì
ëë€)
+
+ë êČœì° ëȘšë, ëȘšëžì êž°ëłž ì ëłŽë„Œ ì
ë „íë ì€ëŹžìĄ°ìŹê° ì ìë©ëë€. ë ëČì§ž ëȘ
ë čìŽë `cookiecutter`넌 ì€ìčíŽìŒ í©ëë€. ììží ì 볎ë [ìŹêž°](https://github.com/huggingface/transformers/tree/main/templates/adding_a_new_model)ìì íìží ì ìì”ëë€.
+
+**huggingface/transformers ë©ìž ì ì„ìì Pull Request ìŽêž°**
+
+ìëìŒëĄ ìì±ë ìœë넌 ìì íêž° ì ì, ì§êžì "ìì
ì§í ì€ (WIP)" í 늏íì€ížë„Œ ìŽêž° ìí ìêž°ì
ëë€. ì넌 ë€ìŽ, đ€ Transformersì "*brand_new_bert* ì¶ê°"ëŒë ì ëȘ©ì "[WIP] Add *brand_new_bert*" í 늏íì€ížë„Œ ìœëë€. ìŽë êČ í멎 ëčì êłŒ Hugging Face íìŽ đ€ Transformersì ëȘšëžì í”í©íë ìì
ì íšê»í ì ìì”ëë€.
+
+ë€ìì ìííŽìŒ í©ëë€:
+
+1. ë©ìž ëžëìčìì ìì
ì ì ì€ëȘ
íë ìŽëŠìŒëĄ ëžëìč ìì±
+
+```bash
+git checkout -b add_brand_new_bert
+```
+
+2. ìëìŒëĄ ìì±ë ìœë 컀ë°
+
+```bash
+git add .
+git commit
+```
+
+3. íìŹ ë©ìžì ê°ì žì€êł 늏ëČ ìŽì€
+
+```bash
+git fetch upstream
+git rebase upstream/main
+```
+
+4. ëłêČœ ìŹíì êłì ì ížì
+
+```bash
+git push -u origin a-descriptive-name-for-my-changes
+```
+
+5. ë§ìĄ±ì€ëœë€ë©Ž, GitHubìì ìì ì íŹíŹí ìč íìŽì§ëĄ ìŽëí©ëë€. "Pull request"넌 íŽëŠí©ëë€. Hugging Face íì ìŒë¶ ë©€ëČì GitHub ížë€ì 늏뷰ìŽëĄ ì¶ê°íìŹ Hugging Face íìŽ ììŒëĄì ëłêČœ ìŹíì ëíŽ ì늌ì ë°ì ì ìëëĄ í©ëë€.
+
+6. GitHub í 늏íì€íž ìč íìŽì§ ì€ë„žìȘœì ìë "Convert to draft"넌 íŽëŠíìŹ PRì ìŽììŒëĄ ëłêČœí©ëë€.
+
+ë€ììŒëĄ, ìŽë€ ì§ì ì ìŽëŁšìë€ë©Ž ìì
ì 컀ë°íêł êłì ì ížìíìŹ í 늏íì€ížì íìëëëĄ íŽìŒ í©ëë€. ëí, ë€ìêłŒ ê°ìŽ íìŹ ë©ìžêłŒ ìì
ì ì
ë°ìŽížíŽìŒ í©ëë€:
+
+```bash
+git fetch upstream
+git merge upstream/main
+```
+
+ìŒë°ì ìŒëĄ, ëȘšëž ëë ê”Źíì êŽí ëȘšë ì§ëŹžì ìì ì PRìì íŽìŒ íë©°, PRìì í ëĄ ëêł íŽêȰëìŽìŒ í©ëë€. ìŽë êČ í멎 Hugging Face íìŽ ìëĄìŽ ìœë넌 컀ë°íê±°ë ì§ëŹžì í ë íì ì늌ì ë°ì ì ìì”ëë€. Hugging Face íìêČ ëŹžì ëë ì§ëŹžì íšìšì ìŒëĄ ìŽíŽí ì ìëëĄ ì¶ê°í ìœë넌 ëȘ
ìíë êČìŽ ëììŽ ë ëê° ë§ì”ëë€.
+
+ìŽë„Œ ìíŽ, ëłêČœ ìŹíì ëȘšë ëłŒ ì ìë "Files changed" íìŒëĄ ìŽëíìŹ ì§ëŹžíêł ì íë ì€ëĄ ìŽëí ë€ì "+" êž°ížë„Œ íŽëŠíìŹ ìœë©ížë„Œ ì¶ê°í ì ìì”ëë€. ì§ëŹžìŽë 돞ì ê° íŽêȰë멎, ìì±ë ìœë©ížì "Resolve" ëČíŒì íŽëŠí ì ìì”ëë€.
+
+ë§ì°Źê°ì§ëĄ, Hugging Face íì ìœë넌 늏뷰í ë ìœë©ížë„Œ ëšêžž êČì
ëë€. ì°ëŠŹë PRìì ëë¶ë¶ì ì§ëŹžì GitHubìì 돻ë êČì ê¶ì„í©ëë€. êł”ê°ì íŹêČ ëììŽ ëì§ ìë ë§€ì° ìŒë°ì ìž ì§ëŹžì êČœì°, SlackìŽë ìŽë©ìŒì í”íŽ Hugging Face íìêČ ëŹžìí ì ìì”ëë€.
+
+**5. brand_new_bertì ëíŽ ìì±ë ëȘšëž ìœë넌 ì ì©íêž°**
+
+뚌ì , ì°ëŠŹë ëȘšëž ììČŽìë§ ìŽì ì ë§ì¶êł í íŹëìŽì ì ëíŽìë ì êČœ ì°ì§ ìì êČì
ëë€. ëȘšë êŽë š ìœëë ë€ìì ìì±ë íìŒìì ì°Ÿì ì ìì”ëë€: `src/transformers/models/brand_new_bert/modeling_brand_new_bert.py` ë° `src/transformers/models/brand_new_bert/configuration_brand_new_bert.py`.
+
+ìŽì ë§ìčšëŽ ìœë©ì ììí ì ìì”ëë€ :). `src/transformers/models/brand_new_bert/modeling_brand_new_bert.py`ì ìì±ë ìœëë ìžìœë ì ì© ëȘšëžìž êČœì° BERTì ëìŒí ìí€í
ìČ넌 ê°ì§ê±°ë, ìžìœë-ëìœë ëȘšëžìž êČœì° BARTì ëìŒí ìí€í
ìČ넌 ê°ì§ êČì
ëë€. ìŽ ìì ìì, ëȘšëžì ìŽëĄ ì ìžĄë©Žì ëíŽ ë°°ìŽ ëŽì©ì ë€ì ìêž°íŽìŒ í©ëë€: *ëȘšëžìŽ BERT ëë BARTì ìŽë»êČ ë€ë„žê°ì?*. ììŁŒ ëłêČœíŽìŒ íë êČì *self-attention* ë ìŽìŽ, ì ê·í ë ìŽìŽì ìì ë±ì ëłêČœíë êČì
ëë€. ë€ì ë§íì§ë§, ìì ì ëȘšëžì ê”Źííë ë° ëììŽ ëëëĄ Transformersìì ìŽëŻž ìĄŽìŹíë ëȘšëžì ì ìŹí ìí€í
ìČ넌 ìŽíŽëłŽë êČìŽ ì ì©í ì ìì”ëë€.
+
+**ì°žêł ëĄ** ìŽ ìì ìì, ìœëê° ìì í ì ííê±°ë êčšëíë€êł íì í íìë ìì”ëë€. ì€íë € ìČììë ìëłž ìœëì ìČ« ëČì§ž *ë¶ìì íêł * ëł”ìŹë ëČì ì `src/transformers/models/brand_new_bert/modeling_brand_new_bert.py`ì ì¶ê°íë êČìŽ ìąì”ëë€. íìí ëȘšë ìœëê° ì¶ê°ë ëêčì§ ìŽëŹí ìì
ì ì§íí í, ë€ì ìčì
ìì ì€ëȘ
í ëłí ì€íŹëŠœížë„Œ ìŹì©íìŹ ìœë넌 ì ì§ì ìŒëĄ ê°ì íêł ìì íë êČìŽ íšìŹ íšìšì ì
ëë€. ìŽ ìì ìì ìëíŽìŒ íë ì ìŒí êČì ë€ì ëȘ
ë čìŽ ìëíë êČì
ëë€:
+
+```python
+from transformers import BrandNewBertModel, BrandNewBertConfig
+
+model = BrandNewBertModel(BrandNewBertConfig())
+```
+
+ìì ëȘ
ë čì `BrandNewBertConfig()`ì ì ìë êž°ëłž ë§€ê°ëłìì ë°ëŒ 돎ìì ê°ì€ìčëĄ ëȘšëžì ìì±íë©°, ìŽëĄìš ëȘšë ê”Źì± ììì `init()` ë©ìëê° ìëíšì 볎ì„í©ëë€.
+
+ëȘšë 돎ìì ìŽêž°íë `BrandnewBertPreTrainedModel` íŽëì€ì `_init_weights` ë©ìëìì ìíëìŽìŒ í©ëë€. ìŽ ë©ìëë ê”Źì± ì€ì ëłìì ë°ëŒ ëȘšë 늏í ëȘšëì ìŽêž°ííŽìŒ í©ëë€. BERTì `_init_weights` ë©ìë ìì ë ë€ìêłŒ ê°ì”ëë€:
+
+```py
+def _init_weights(self, module):
+ """Initialize the weights"""
+ if isinstance(module, nn.Linear):
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
+ if module.bias is not None:
+ module.bias.data.zero_()
+ elif isinstance(module, nn.Embedding):
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
+ if module.padding_idx is not None:
+ module.weight.data[module.padding_idx].zero_()
+ elif isinstance(module, nn.LayerNorm):
+ module.bias.data.zero_()
+ module.weight.data.fill_(1.0)
+```
+
+ëȘ ê°ì§ ëȘšëì ëíŽ íčëłí ìŽêž°íê° íìí êČœì° ìŹì©ì ì ì ë°©ìì ìŹì©í ìë ìì”ëë€. ì넌 ë€ìŽ, `Wav2Vec2ForPreTraining`ìì ë§ì§ë§ ë ê°ì ì í ë ìŽìŽë ìŒë°ì ìž PyTorch `nn.Linear`ì ìŽêž°í넌 ê°ì žìŒ íì§ë§, ë€ë„ž ëȘšë ë ìŽìŽë ìì ê°ì ìŽêž°í넌 ìŹì©íŽìŒ í©ëë€. ìŽë ë€ìêłŒ ê°ìŽ ìœëíë©ëë€:
+
+```py
+def _init_weights(self, module):
+ """Initialize the weights"""
+ if isinstnace(module, Wav2Vec2ForPreTraining):
+ module.project_hid.reset_parameters()
+ module.project_q.reset_parameters()
+ module.project_hid._is_hf_initialized = True
+ module.project_q._is_hf_initialized = True
+ elif isinstance(module, nn.Linear):
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
+ if module.bias is not None:
+ module.bias.data.zero_()
+```
+
+`_is_hf_initialized` íëê·žë ìëžëȘšëì í ëČë§ ìŽêž°ííëëĄ ëŽë¶ì ìŒëĄ ìŹì©ë©ëë€. `module.project_q` ë° `module.project_hid`ì ëíŽ `True`ëĄ ì€ì íšìŒëĄìš, ì°ëŠŹê° ìíí ìŹì©ì ì ì ìŽêž°íê° ìŽíì ëźìŽì°ìŽì§ ìëëĄ í©ëë€. ìŠ, `_init_weights` íšìê° ìŽë€ìêČ ì ì©ëì§ ìì”ëë€.
+
+**6. ëłí ì€íŹëŠœíž ìì±íêž°**
+
+ë€ììŒëĄ, ëëČê·žì ìŹì©í ìČŽíŹíŹìžížë„Œ êž°ìĄŽ ì ì„ììì ë§ë đ€ Transformers ê”ŹíêłŒ ížíëë ìČŽíŹíŹìžížëĄ ëłíí ì ìë ëłí ì€íŹëŠœížë„Œ ìì±íŽìŒ í©ëë€. ëłí ì€íŹëŠœížë„Œ ìČìë¶í° ìì±íë êČ볎ë€ë *brand_new_bert*ì ëìŒí íë ììíŹëĄ ìì±ë ì ìŹí ëȘšëžì ëłíí êž°ìĄŽ ëłí ì€íŹëŠœížë„Œ ì°Ÿì볎ë êČìŽ ìąì”ëë€. ìŒë°ì ìŒëĄ êž°ìĄŽ ëłí ì€íŹëŠœížë„Œ ëł”ìŹíìŹ ìŹì© ìŹëĄì ë§êČ ìœê° ìì íë êČìŒëĄ ì¶©ë¶í©ëë€. ëȘšëžì ëíŽ ì ìŹí êž°ìĄŽ ëłí ì€íŹëŠœížë„Œ ìŽëìì ì°Ÿì ì ìëì§ Hugging Face íìêČ ëŹžìíë êČì ë§ì€ìŽì§ ë§ìžì.
+
+- TensorFlowìì PyTorchëĄ ëȘšëžì ìŽì íë êČœì°, ìąì ì°žêł ìëŁëĄ BERTì ëłí ì€íŹëŠœíž [ìŹêž°](https://github.com/huggingface/transformers/blob/7acfa95afb8194f8f9c1f4d2c6028224dbed35a2/src/transformers/models/bert/modeling_bert.py#L91)넌 ì°žìĄ°í ì ìì”ëë€.
+- PyTorchìì PyTorchëĄ ëȘšëžì ìŽì íë êČœì°, ìąì ì°žêł ìëŁëĄ BARTì ëłí ì€íŹëŠœíž [ìŹêž°](https://github.com/huggingface/transformers/blob/main/src/transformers/models/bart/convert_bart_original_pytorch_checkpoint_to_pytorch.py)넌 ì°žìĄ°í ì ìì”ëë€.
+
+ë€ìììë PyTorch ëȘšëžìŽ ë ìŽìŽ ê°ì€ìč넌 ì ì„íêł ë ìŽìŽ ìŽëŠì ì ìíë ë°©ëČì ëíŽ ê°ëší ì€ëȘ
íêČ ì”ëë€. PyTorchìì ë ìŽìŽì ìŽëŠì ë ìŽìŽì ì§ì í íŽëì€ ìì±ì ìŽëŠìŒëĄ ì ìë©ëë€. ë€ìêłŒ ê°ìŽ PyTorchìì `SimpleModel`ìŽëŒë ë믞 ëȘšëžì ì ìíŽ ëŽ
ìë€:
+
+```python
+from torch import nn
+
+
+class SimpleModel(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.dense = nn.Linear(10, 10)
+ self.intermediate = nn.Linear(10, 10)
+ self.layer_norm = nn.LayerNorm(10)
+```
+
+ìŽì ìŽ ëȘšëž ì ìì ìžì€íŽì€ë„Œ ìì±í ì ììŒë©° `dense`, `intermediate`, `layer_norm` ë±ì ê°ì€ìčê° ëë€íêČ í ëčë©ëë€. ëȘšëžì ì¶ë „íìŹ ìí€í
ìČ넌 íìží ì ìì”ëë€.
+
+```python
+model = SimpleModel()
+
+print(model)
+```
+
+ìŽë ë€ìêłŒ ê°ìŽ ì¶ë „ë©ëë€:
+
+```
+SimpleModel(
+ (dense): Linear(in_features=10, out_features=10, bias=True)
+ (intermediate): Linear(in_features=10, out_features=10, bias=True)
+ (layer_norm): LayerNorm((10,), eps=1e-05, elementwise_affine=True)
+)
+```
+
+ì°ëŠŹë ë ìŽìŽì ìŽëŠìŽ PyTorchìì íŽëì€ ìì±ì ìŽëŠìŒëĄ ì ìëìŽ ìë êČì ëłŒ ì ìì”ëë€. íčì ë ìŽìŽì ê°ì€ìč ê°ì ì¶ë „íìŹ íìží ì ìì”ëë€:
+
+```python
+print(model.dense.weight.data)
+```
+
+ê°ì€ìčê° ëŹŽììëĄ ìŽêž°íëììì íìží ì ìì”ëë€.
+
+```
+tensor([[-0.0818, 0.2207, -0.0749, -0.0030, 0.0045, -0.1569, -0.1598, 0.0212,
+ -0.2077, 0.2157],
+ [ 0.1044, 0.0201, 0.0990, 0.2482, 0.3116, 0.2509, 0.2866, -0.2190,
+ 0.2166, -0.0212],
+ [-0.2000, 0.1107, -0.1999, -0.3119, 0.1559, 0.0993, 0.1776, -0.1950,
+ -0.1023, -0.0447],
+ [-0.0888, -0.1092, 0.2281, 0.0336, 0.1817, -0.0115, 0.2096, 0.1415,
+ -0.1876, -0.2467],
+ [ 0.2208, -0.2352, -0.1426, -0.2636, -0.2889, -0.2061, -0.2849, -0.0465,
+ 0.2577, 0.0402],
+ [ 0.1502, 0.2465, 0.2566, 0.0693, 0.2352, -0.0530, 0.1859, -0.0604,
+ 0.2132, 0.1680],
+ [ 0.1733, -0.2407, -0.1721, 0.1484, 0.0358, -0.0633, -0.0721, -0.0090,
+ 0.2707, -0.2509],
+ [-0.1173, 0.1561, 0.2945, 0.0595, -0.1996, 0.2988, -0.0802, 0.0407,
+ 0.1829, -0.1568],
+ [-0.1164, -0.2228, -0.0403, 0.0428, 0.1339, 0.0047, 0.1967, 0.2923,
+ 0.0333, -0.0536],
+ [-0.1492, -0.1616, 0.1057, 0.1950, -0.2807, -0.2710, -0.1586, 0.0739,
+ 0.2220, 0.2358]]).
+```
+
+ëłí ì€íŹëŠœížììë ìŽëŹí 돎ììëĄ ìŽêž°íë ê°ì€ìč넌 ìČŽíŹíŹìžížì íŽëč ë ìŽìŽì ì íí ê°ì€ìčëĄ ì±ììŒ í©ëë€. ì넌 ë€ë©Ž ë€ìêłŒ ê°ì”ëë€:
+
+```python
+# retrieve matching layer weights, e.g. by
+# recursive algorithm
+layer_name = "dense"
+pretrained_weight = array_of_dense_layer
+
+model_pointer = getattr(model, "dense")
+
+model_pointer.weight.data = torch.from_numpy(pretrained_weight)
+```
+
+ìŽë êČ í멎 PyTorch ëȘšëžì 돎ììëĄ ìŽêž°íë ê° ê°ì€ìčì íŽëč ìČŽíŹíŹìžíž ê°ì€ìčê° **ëȘšìêłŒ ìŽëŠ** ëȘšëìì ì íí ìŒìčíëì§ íìžíŽìŒ í©ëë€. ìŽë„Œ ìíŽ ëȘšìì ëí assert 돞ì ì¶ê°íêł ìČŽíŹíŹìžíž ê°ì€ìčì ìŽëŠì ì¶ë „íŽìŒ í©ëë€. ì넌 ë€ìŽ ë€ìêłŒ ê°ì 돞ì„ì ì¶ê°íŽìŒ í©ëë€:
+
+```python
+assert (
+ model_pointer.weight.shape == pretrained_weight.shape
+), f"Pointer shape of random weight {model_pointer.shape} and array shape of checkpoint weight {pretrained_weight.shape} mismatched"
+```
+
+ëí ë ê°ì€ìčì ìŽëŠì ì¶ë „íìŹ ìŒìčíëì§ íìžíŽìŒ í©ëë€. *ìì*:
+
+```python
+logger.info(f"Initialize PyTorch weight {layer_name} from {pretrained_weight.name}")
+```
+
+ëȘšì ëë ìŽëŠìŽ ìŒìčíì§ ìë êČœì°, ëë€ìŒëĄ ìŽêž°íë ë ìŽìŽì ìëȘ»ë ìČŽíŹíŹìžíž ê°ì€ìč넌 í ëčí êČìŒëĄ ì¶ìžĄë©ëë€.
+
+ìëȘ»ë ëȘšìì `BrandNewBertConfig()`ì ê”Źì± ë§€ê°ëłì ì€ì ìŽ ëłííë €ë ìČŽíŹíŹìžížì ìŹì©ë ì€ì êłŒ ì íí ìŒìčíì§ ìêž° ëëŹžìŒ ê°ë„ì±ìŽ ê°ì„ íœëë€. ê·žëŹë PyTorchì ë ìŽìŽ ê”Źí ììČŽìì ê°ì€ìč넌 ì ìčíŽìŒ í ìë ìì”ëë€.
+
+ë§ì§ë§ìŒëĄ, **ëȘšë ** íìí ê°ì€ìčê° ìŽêž°íëìëì§ íìžíêł ìŽêž°íì ìŹì©ëì§ ìì ëȘšë ìČŽíŹíŹìžíž ê°ì€ìč넌 ì¶ë „íìŹ ëȘšëžìŽ ìŹë°ë„ŽêČ ëłíëìëì§ íìžíŽìŒ í©ëë€. ìëȘ»ë ëȘšì 돞ì„ìŽë ìëȘ»ë ìŽëŠ í ëčìŒëĄ ìžíŽ ëłí ìëê° ì€íšíë êČì ìì í ì ìì
ëë€. ìŽë `BrandNewBertConfig()`ìì ìëȘ»ë ë§€ê°ëłì넌 ìŹì©íê±°ë đ€ Transformers ê”Źíìì ìëȘ»ë ìí€í
ìČ, đ€ Transformers ê”Źíì ê”Źì± ìì ì€ íëì `init()` íšìì ëČê·žê° ìë êČœì°ìŽê±°ë ìČŽíŹíŹìžíž ê°ì€ìč ì€ íë넌 ì ìčíŽìŒ íë êČœì°ìŒ ê°ë„ì±ìŽ ê°ì„ ëì”ëë€.
+
+ìŽ ëšêłë ìŽì ëšêłì íšê» ë°ëł”ëìŽìŒ íë©° ëȘšë ìČŽíŹíŹìžížì ê°ì€ìčê° Transformers ëȘšëžì ìŹë°ë„ŽêČ ëĄëëìì ëêčì§ êłìëìŽìŒ í©ëë€. đ€ Transformers ê”Źíì ìČŽíŹíŹìžížë„Œ ìŹë°ë„ŽêČ ëĄëí íìë `/path/to/converted/checkpoint/folder`ì ê°ì ìíë íŽëì ëȘšëžì ì ì„í ì ììŽìŒ í©ëë€. íŽëč íŽëìë `pytorch_model.bin` íìŒêłŒ `config.json` íìŒìŽ ëȘšë íŹíšëìŽìŒ í©ëë€.
+
+```python
+model.save_pretrained("/path/to/converted/checkpoint/folder")
+```
+
+**7. ìë°©í„ íšì€ ê”Źííêž°**
+
+đ€ Transformers ê”Źíì ìŹì íë šë ê°ì€ìč넌 ì ííêČ ëĄëí íìë ìë°©í„ íšì€ê° ìŹë°ë„ŽêČ ê”Źíëìëì§ íìžíŽìŒ í©ëë€. [ìëłž ì ì„ìì ì”ìíŽì§êž°](#34-run-a-pretrained-checkpoint-using-the-original-repository)ìì ìŽëŻž ìëłž ì ì„ì넌 ìŹì©íìŹ ëȘšëžì ìë°©í„ íšì€ë„Œ ì€ííë ì€íŹëŠœížë„Œ ë§ë€ìì”ëë€. ìŽì ìëłž ëì đ€ Transformers ê”Źíì ìŹì©íë ì ìŹí ì€íŹëŠœížë„Œ ìì±íŽìŒ í©ëë€. ë€ìêłŒ ê°ìŽ ìì±ëìŽìŒ í©ëë€:
+
+```python
+model = BrandNewBertModel.from_pretrained("/path/to/converted/checkpoint/folder")
+input_ids = [0, 4, 4, 3, 2, 4, 1, 7, 19]
+output = model(input_ids).last_hidden_states
+```
+
+đ€ Transformers ê”ŹíêłŒ ìëłž ëȘšëž ê”ŹíìŽ ìČìë¶í° ì íí ëìŒí ì¶ë „ì ì êł”íì§ ìê±°ë ìë°©í„ íšì€ìì ì€ë„ê° ë°ìí ê°ë„ì±ìŽ ë§€ì° ëì”ëë€. ì€ë§íì§ ë§ìžì. ììë ìŒì
ëë€! 뚌ì , ìë°©í„ íšì€ìì ì€ë„ê° ë°ìíì§ ìëëĄ íŽìŒ í©ëë€. ìą
ìą
ìëȘ»ë ì°šììŽ ìŹì©ëìŽ *ì°šì ë¶ìŒìč* ì€ë„ê° ë°ìíê±°ë ìëȘ»ë ë°ìŽí° ì í ê°ìČŽê° ìŹì©ëë êČœì°ê° ìì”ëë€. ì넌 ë€ë©Ž `torch.long` ëì ì `torch.float32`ê° ìŹì©ë êČœì°ì
ëë€. íŽêȰí ì ìë ì€ë„ê° ë°ìí멎 Hugging Face íì ëìì ììČíë êČìŽ ìąì”ëë€.
+
+đ€ Transformers ê”ŹíìŽ ìŹë°ë„ŽêČ ìëíëì§ íìžíë ë§ì§ë§ ëšêłë ì¶ë „ìŽ `1e-3`ì ì ë°ëëĄ ëìŒíì§ íìžíë êČì
ëë€. 뚌ì , ì¶ë „ ëȘšììŽ ëìŒíëëĄ ëłŽì„íŽìŒ í©ëë€. ìŠ, đ€ Transformers ê”Źí ì€íŹëŠœížì ìëłž ê”Źí ìŹìŽìì `outputs.shape`ë ëìŒí ê°ì ë°ííŽìŒ í©ëë€. ê·ž ë€ììŒëĄ, ì¶ë „ ê°ìŽ ëìŒíëëĄ íŽìŒ í©ëë€. ìŽë ìëĄìŽ ëȘšëžì ì¶ê°í ë ê°ì„ ìŽë €ìŽ ë¶ë¶ ì€ íëì
ëë€. ì¶ë „ìŽ ëìŒíì§ ìì ìŒë°ì ìž ì€ì ìŹëĄë ë€ìêłŒ ê°ì”ëë€:
+
+- ìŒë¶ ë ìŽìŽê° ì¶ê°ëì§ ììì”ëë€. ìŠ, *íì±í* ë ìŽìŽê° ì¶ê°ëì§ ììê±°ë ìì°š ì°êČ°ìŽ ëč ìĄì”ëë€.
+- ëšìŽ ìëČ ë© íë ŹìŽ ì°êȰëì§ ììì”ëë€.
+- ìëȘ»ë ììč ìëČ ë©ìŽ ìŹì©ëìì”ëë€. ìëłž ê”Źíììë ì€íì
ì ìŹì©í©ëë€.
+- ìë°©í„ íšì€ ì€ì DropoutìŽ ì ì©ëìì”ëë€. ìŽë„Œ ìì íë €ë©Ž *model.trainingìŽ False*ìžì§ íìžíêł ìë°©í„ íšì€ ì€ì Dropout ë ìŽìŽê° ìëȘ» íì±íëì§ ìëëĄ íìžì. ìŠ, [PyTorchì êž°ë„ì Dropout](https://pytorch.org/docs/stable/nn.functional.html?highlight=dropout#torch.nn.functional.dropout)ì *self.training*ì ì ëŹíìžì.
+
+돞ì 넌 íŽêȰíë ê°ì„ ìąì ë°©ëČì ìŒë°ì ìŒëĄ ìëłž ê”ŹíêłŒ đ€ Transformers ê”Źíì ìë°©í„ íšì€ë„Œ ëëí ëêł ì°šìŽì ìŽ ìëì§ íìžíë êČì
ëë€. ìŽìì ìŒëĄë ìë°©í„ íšì€ì ì€ê° ì¶ë „ì ëëČê·ž/ì¶ë „íìŹ ìëłž ê”ŹíêłŒ đ€ Transformers ê”Źíì ì íí ììč넌 ì°Ÿì ì ììŽìŒ í©ëë€. 뚌ì , ë ì€íŹëŠœížì íëìœë©ë `input_ids`ê° ëìŒíì§ íìžíìžì. ë€ììŒëĄ, `input_ids`ì ìČ« ëČì§ž ëłíì ì¶ë „(ìŒë°ì ìŒëĄ ëšìŽ ìëČ ë©)ìŽ ëìŒíì§ íìžíìžì. ê·žë° ë€ì ë€ížìíŹì ê°ì„ ë§ì§ë§ ë ìŽìŽêčì§ ì§ííŽëłŽìžì. ìŽë ìì ìì ë ê”Źí ìŹìŽì ì°šìŽê° ìë êČì ìêČ ëëë°, ìŽë đ€ Transformers ê”Źíì ëČê·ž ììč넌 ê°ëŠŹíŹ êČì
ëë€. ì íŹ êČœíììŒëĄë ìëłž ê”ŹíêłŒ đ€ Transformers ê”Źí ëȘšëìì ëìŒí ììčì ë§ì ì¶ë „ 돞ì ì¶ê°íêł ìŽë€ì ì€ê° ííì ëíŽ ëìŒí ê°ì 볎ìŽë ì¶ë „ 돞ì ì°ìì ìŒëĄ ì ê±°íë êČìŽ ê°ëšíêł íšêłŒì ìž ë°©ëČì
ëë€.
+
+`torch.allclose(original_output, output, atol=1e-3)`ëĄ ì¶ë „ì íìžíìŹ ë ê”ŹíìŽ ëìŒí ì¶ë „ì íë êČì íì íë€ë©Ž, ê°ì„ ìŽë €ìŽ ë¶ë¶ì ëëŹì”ëë€! ì¶íë늜ëë€. ëšì ìì
ì ìŹìŽ ìŒìŽ ë êČì
ëë€ đ.
+
+**8. íìí ëȘšë ëȘšëž í
ì€íž ì¶ê°íêž°**
+
+ìŽ ìì ìì ìëĄìŽ ëȘšëžì ì±êł”ì ìŒëĄ ì¶ê°íì”ëë€. ê·žëŹë íŽëč ëȘšëžìŽ ìê”Źëë ëììžì ìì í ë¶í©íì§ ìì ìë ìì”ëë€. đ€ Transformersì ìëČœíêČ ížíëë ê”Źíìžì§ íìžíêž° ìíŽ ëȘšë ìŒë° í
ì€ížë„Œ í”êłŒíŽìŒ í©ëë€. Cookiecutterë ìë§ë ëȘšëžì ìí í
ì€íž íìŒì ìëìŒëĄ ì¶ê°íì êČì
ëë€. ìë§ë `tests/models/brand_new_bert/test_modeling_brand_new_bert.py`ì ê°ì êČœëĄì ììčí êČì
ëë€. ìŽ í
ì€íž íìŒì ì€ííìŹ ìŒë° í
ì€ížê° ëȘšë í”êłŒíëì§ íìžíìžì.
+
+```bash
+pytest tests/models/brand_new_bert/test_modeling_brand_new_bert.py
+```
+
+ëȘšë ìŒë° í
ì€ížë„Œ ìì í í, ìŽì ìíí ìì
ì ì¶©ë¶í í
ì€ížíìŹ ë€ì ìŹíì 볎ì„íŽìŒ í©ëë€.
+
+- a) ì»€ëź€ëí°ê° *brand_new_bert*ì íčì í
ì€ížë„Œ ìŽíŽëŽìŒëĄìš ìì
ì ìœêČ ìŽíŽí ì ìëëĄ íš
+- b) ëȘšëžì ëí í„í ëłêČœ ìŹíìŽ ëȘšëžì ì€ìí êž°ë„ì ìììí€ì§ ìëëĄ íš
+
+뚌ì í”í© í
ì€ížë„Œ ì¶ê°íŽìŒ í©ëë€. ìŽëŹí í”í© í
ì€ížë ìŽì ì ëȘšëžì đ€ TransformersëĄ ê”Źííêž° ìíŽ ìŹì©í ëëČêč
ì€íŹëŠœížì ëìŒí ìì
ì ìíí©ëë€. Cookiecutterì ìŽëŻž ìŽëŹí ëȘšëž í
ì€ížì í
íëŠżìž `BrandNewBertModelIntegrationTests`ê° ì¶ê°ëìŽ ììŒë©°, ìŹëŹë¶ìŽ ìì±íŽìŒ í ëŽì©ìŒëĄë§ ì±ì ëŁìŒë©Ž ë©ëë€. ìŽëŹí í
ì€ížê° í”êłŒíëì§ íìžíë €ë©Ž ë€ìì ì€ííìžì.
+
+```bash
+RUN_SLOW=1 pytest -sv tests/models/brand_new_bert/test_modeling_brand_new_bert.py::BrandNewBertModelIntegrationTests
+```
+
+
+
+Windows넌 ìŹì©íë êČœì° `RUN_SLOW=1`ì `SET RUN_SLOW=1`ëĄ ë°êżìŒ í©ëë€.
+
+
+
+ëì§žëĄ, *brand_new_bert*ì íčíë ëȘšë êž°ë„ë ëłëì í
ì€ížìì ì¶ê°ëĄ í
ì€ížíŽìŒ í©ëë€. ìŽ ë¶ë¶ì ìą
ìą
ìíëë°, ë ê°ì§ ìžĄë©Žìì ê”ì„í ì ì©í©ëë€.
+
+- *brand_new_bert*ì íčì êž°ë„ìŽ ìŽë»êČ ìëíŽìŒ íëì§ ëłŽìŹì€ìŒëĄìš ì»€ëź€ëí°ìêČ ëȘšëž ì¶ê° êłŒì ìì ì”ëí ì§ìì ì ëŹíë ë° ëììŽ ë©ëë€.
+- í„í êž°ìŹìë ìŽëŹí íčì í
ì€ížë„Œ ì€ííìŹ ëȘšëžì ëí ëłêČœ ìŹíì ëč 넎êČ í
ì€íží ì ìì”ëë€.
+
+
+**9. í íŹëìŽì ê”Źííêž°**
+
+ë€ììŒëĄ, *brand_new_bert*ì í íŹëìŽì 넌 ì¶ê°íŽìŒ í©ëë€. ëłŽí” í íŹëìŽì ë đ€ Transformersì êž°ìĄŽ í íŹëìŽì ì ëìŒíê±°ë ë§€ì° ì ìŹí©ëë€.
+
+í íŹëìŽì ê° ìŹë°ë„ŽêČ ìëíëì§ íìžíêž° ìíŽ ëšŒì ìëłž 늏íŹì§í 늏ìì 돞ììŽì ì
ë „íêł `input_ids`넌 ë°ííë ì€íŹëŠœížë„Œ ìì±íë êČìŽ ìąì”ëë€. ë€ìêłŒ ê°ì ì ìŹí ì€íŹëŠœížìŒ ì ìì”ëë€ (ììŹ ìœëëĄ ìì±):
+
+```python
+input_str = "This is a long example input string containing special characters .$?-, numbers 2872 234 12 and words."
+model = BrandNewBertModel.load_pretrained_checkpoint("/path/to/checkpoint/")
+input_ids = model.tokenize(input_str)
+```
+
+ìëłž 늏íŹì§í ëŠŹë„Œ ììží ìŽíŽëłŽêł ìŹë°ë„ž í íŹëìŽì íšì넌 ì°Ÿê±°ë, ëł”ì ëłžìì ëłêČœ ìŹíì ì ì©íìŹ `input_ids`ë§ ì¶ë „íëëĄ íŽìŒ í©ëë€. ìëłž 늏íŹì§í ëŠŹë„Œ ìŹì©íë êž°ë„ì ìž í í°í ì€íŹëŠœížë„Œ ìì±í í, đ€ Transformersì ì ìŹí ì€íŹëŠœížë„Œ ìì±íŽìŒ í©ëë€. ë€ìêłŒ ê°ìŽ ìì±ëìŽìŒ í©ëë€:
+
+```python
+from transformers import BrandNewBertTokenizer
+
+input_str = "This is a long example input string containing special characters .$?-, numbers 2872 234 12 and words."
+
+tokenizer = BrandNewBertTokenizer.from_pretrained("/path/to/tokenizer/folder/")
+
+input_ids = tokenizer(input_str).input_ids
+```
+
+ë ê°ì `input_ids`ê° ëìŒí ê°ì ë°íí ë, ë§ì§ë§ ëšêłëĄ í íŹëìŽì í
ì€íž íìŒë ì¶ê°íŽìŒ í©ëë€.
+
+*brand_new_bert*ì ëȘšëžë§ í
ì€íž íìŒêłŒ ì ìŹíêČ, *brand_new_bert*ì í íŹëìŽì ìŽì
í
ì€íž íìŒìë ëȘ ê°ì§ íëìœë©ë í”í© í
ì€ížê° íŹíšëìŽìŒ í©ëë€.
+
+**10. ìą
ëš ê° í”í© í
ì€íž ì€í**
+
+í íŹëìŽì 넌 ì¶ê°í íìë ëȘšëžêłŒ í íŹëìŽì 넌 ìŹì©íìŹ ëȘ ê°ì§ ìą
ëš ê° í”í© í
ì€ížë„Œ ì¶ê°íŽìŒ í©ëë€. `tests/models/brand_new_bert/test_modeling_brand_new_bert.py`ì ì¶ê°íŽìŁŒìžì. ìŽëŹí í
ì€ížë đ€ Transformers ê”ŹíìŽ ììëëĄ ìëíëì§ë„Œ ì믞 ìë text-to-text ììëĄ ëłŽìŹì€ìŒ í©ëë€. ê·ž ììëĄë *ì넌 ë€ìŽ* source-to-target ëČì ì, article-to-summary ì, question-to-answer ì ë±ìŽ íŹíšë ì ìì”ëë€. ë¶ëŹìš ìČŽíŹíŹìžíž ì€ ìŽë êČë ë€ìŽì€ížëŠŒ ìì
ìì ëŻžìž ìĄ°ì ëì§ ììë€ë©Ž, ëȘšëž í
ì€ížë§ìŒëĄ ì¶©ë¶í©ëë€. ëȘšëžìŽ ìì í êž°ë„ì ê°ì¶ìëì§ íìžíêž° ìíŽ ë§ì§ë§ ëšêłëĄ GPUìì ëȘšë í
ì€ížë„Œ ì€ííë êČìŽ ìąì”ëë€. ëȘšëžì ëŽë¶ í
ìì ìŒë¶ì `.to(self.device)` 돞ì ì¶ê°íë êČì ììì ì ììŒë©°, ìŽ êČœì° í
ì€ížìì ì€ë„ëĄ íìë©ëë€. GPUì ìĄìžì€í ì ìë êČœì°, Hugging Face íìŽ í
ì€ížë„Œ ëì ì€íí ì ìì”ëë€.
+
+**11. êž°ì 돞ì ì¶ê°**
+
+ìŽì *brand_new_bert*ì íìí ëȘšë êž°ë„ìŽ ì¶ê°ëìì”ëë€. ê±°ì ëëŹì”ëë€! ì¶ê°íŽìŒ í êČì ë©ì§ êž°ì 돞ìêłŒ êž°ì 돞ì íìŽì§ì
ëë€. Cookiecutterê° `docs/source/model_doc/brand_new_bert.md`ëŒë í
í늿 íìŒì ì¶ê°íŽì€Źì êČì
ëë€. ìŽ íìŽì§ë„Œ ìŹì©íêž° ì ì ëȘšëžì ìŹì©íë ìŹì©ìë€ì ìŒë°ì ìŒëĄ ìŽ íìŽì§ë„Œ 뚌ì íìží©ëë€. ë°ëŒì 돞ìë ìŽíŽíêž° ìœêł ê°êȰíŽìŒ í©ëë€. ëȘšëžì ìŹì©íë ë°©ëČì 볎ìŹìŁŒêž° ìíŽ *í*ì ì¶ê°íë êČìŽ ì»€ëź€ëí°ì ë§€ì° ì ì©í©ëë€. ë
ì€ížë§ì êŽë šíìŹ Hugging Face íì 돞ìíë êČì ìŁŒì íì§ ë§ìžì.
+
+ë€ììŒëĄ, `src/transformers/models/brand_new_bert/modeling_brand_new_bert.py`ì ì¶ê°ë ë
ì€ížë§ìŽ ìŹë°ë„Žë©° íìí ëȘšë ì
ë „ ë° ì¶ë „ì íŹíšíëëĄ íìžíìžì. [ìŹêž°](writing-documentation)ìì ì°ëŠŹì 돞ì ìì± ê°ìŽëì ë
ì€ížë§ íìì ëí ììž ê°ìŽëê° ìì”ëë€. 돞ìë ìŒë°ì ìŒëĄ ì»€ëź€ëí°ì ëȘšëžì ìČ« ëČì§ž ì ì ìŽêž° ë돞ì, 돞ìë ì ìŽë ìœëë§íŒì ìŁŒì넌 êž°ìžìŹìŒ í©ëë€.
+
+**ìœë 늏í©í ë§**
+
+ìąìì, ìŽì *brand_new_bert*넌 ìí ëȘšë íìí ìœë넌 ì¶ê°íì”ëë€. ìŽ ìì ìì ë€ìì ì€ííìŹ ì ìŹì ìŒëĄ ìëȘ»ë ìœë ì€íìŒì ìì íŽìŒ í©ëë€:
+
+ê·žëŠŹêł ìœë© ì€íìŒìŽ íì§ ì êČì í”êłŒíëì§ íìžíêž° ìíŽ ë€ìì ì€ííêł íìžíŽìŒ í©ëë€:
+
+```bash
+make style
+```
+
+đ€ Transformersìë ìŹì í ì€íší ì ìë ëȘ ê°ì§ ë§€ì° ìêČ©í ëììž í
ì€ížê° ìì”ëë€. ìŽë ë
ì€ížë§ì ëëœë ì 볎ë ìëȘ»ë ëȘ
ëȘ
ë돞ì ìą
ìą
ë°ìí©ëë€. ìŹêž°ì ë§í멎 Hugging Face íìŽ ëìì ì€ êČì
ëë€.
+
+```bash
+make quality
+```
+
+ë§ì§ë§ìŒëĄ, ìœëê° ì íí ìëíë êČì íìží íìë íì ìœë넌 늏í©í ë§íë êČìŽ ìąì ìê°ì
ëë€. ëȘšë í
ì€ížê° í”êłŒë ì§êžì ì¶ê°í ìœë넌 ë€ì êČí íêł ëŠŹí©í ë§íë ìąì ìêž°ì
ëë€.
+
+ìŽì ìœë© ë¶ë¶ì ìëŁíì”ëë€. ì¶íí©ëë€! đ ë©ì žì! đ
+
+**12. ëȘšëžì ëȘšëž íëžì ì
ëĄëíìžì**
+
+ìŽ ë§ì§ë§ íížììë ëȘšë ìČŽíŹíŹìžížë„Œ ëłííìŹ ëȘšëž íëžì ì
ëĄëíêł ê° ì
ëĄëë ëȘšëž ìČŽíŹíŹìžížì ëí ëȘšëž ìčŽë넌 ì¶ê°íŽìŒ í©ëë€. [Model sharing and uploading Page](model_sharing)넌 ìœêł íëž êž°ë„ì ì”ìíŽì§ìžì. *brand_new_bert*ì ì ì ìĄ°ì§ ìëì ëȘšëžì ì
ëĄëí ì ìë íìí ìĄìžì€ ê¶íì ì»êž° ìíŽ Hugging Face íêłŒ íì
íŽìŒ í©ëë€. `transformers`ì ëȘšë ëȘšëžì ìë `push_to_hub` ë©ìëë ìČŽíŹíŹìžížë„Œ íëžì ëč ë„Žêł íšìšì ìŒëĄ ì
ëĄëíë ë°©ëČì
ëë€. ìëì ìì ìœë ìĄ°ê°ìŽ ë¶ìŹì ž ìì”ëë€:
+
+ê° ìČŽíŹíŹìžížì ì í©í ëȘšëž ìčŽë넌 ë§ëë ë° ìê°ì í ì íë êČì ê°ìčê° ìì”ëë€. ëȘšëž ìčŽëë ìČŽíŹíŹìžížì íčì±ì ê°ìĄ°íŽìŒ í©ëë€. *ì넌 ë€ìŽ* ìŽ ìČŽíŹíŹìžížë ìŽë€ ë°ìŽí°ì
ìì ìŹì íë š/ìžë¶ íë šëìëì§? ìŽ ëȘšëžì ìŽë€ íì ìì
ìì ìŹì©íŽìŒ íëì§? ê·žëŠŹêł ëȘšëžì ìŹë°ë„ŽêČ ìŹì©íë ë°©ëČì ëí ëȘ ê°ì§ ìœëë íŹíšíŽìŒ í©ëë€.
+
+```python
+brand_new_bert.push_to_hub("brand_new_bert")
+# Uncomment the following line to push to an organization.
+# brand_new_bert.push_to_hub("/brand_new_bert")
+```
+
+**13. (ì í ìŹí) ë
žížë¶ ì¶ê°**
+
+*brand_new_bert*넌 ë€ìŽì€ížëŠŒ ìì
ìì ì¶ëĄ ëë ëŻžìž ìĄ°ì ì ìŹì©íë ë°©ëČì ììží 볎ìŹìŁŒë ë
žížë¶ì ì¶ê°íë êČìŽ ë§€ì° ì ì©í©ëë€. ìŽêČì PRì ëłí©íë ë° íìì ìŽì§ë ìì§ë§ ì»€ëź€ëí°ì ë§€ì° ì ì©í©ëë€.
+
+**14. ìëŁë PR ì ì¶**
+
+ìŽì íëĄê·žëë°ì ë§ìł€ìŒë©°, ë§ì§ë§ ëšêłëĄ PRì ë©ìž ëžëìčì ëłí©íŽìŒ í©ëë€. ëłŽí” Hugging Face íì ìŽëŻž ìŹêž°êčì§ ëìì ìŁŒìì êČì
ëë€. ê·žëŹë PRì ë©ì§ ì€ëȘ
ì ì¶ê°íêł ëŠŹë·°ìŽìêČ íčì ëììž ì í ìŹíì ê°ìĄ°íë €ë©Ž ìëŁë PRì ìœê°ì ì€ëȘ
ì ì¶ê°íë ìê°ì í ì íë êČìŽ ê°ìčê° ìì”ëë€.
+
+### ìì
ëŹŒì êł”ì íìžì!! [[share-your-work]]
+
+ìŽì ì»€ëź€ëí°ìì ìì
ëŹŒì ìžì ë°ì ìê°ì
ëë€! ëȘšëž ì¶ê° ìì
ì ìëŁíë êČì Transformersì ì ìČŽ NLP ì»€ëź€ëí°ì í° êž°ìŹì
ëë€. ëčì ì ìœëì ìŽìë ìŹì íë šë ëȘšëžì ìë°±, ìŹì§ìŽ ììČ ëȘ
ì ê°ë°ìì ì°ê”Źìì ìíŽ íì€í ìŹì©ë êČì
ëë€. ëčì ì ìì
ì ìëì€ëŹìíŽìŒ íë©° ìŽë„Œ ì»€ëź€ëí°ì êł”ì íŽìŒ í©ëë€.
+
+**ëčì ì ì»€ëź€ëí° ëŽ ëȘšë ìŹëë€ìêČ ë§€ì° ìœêČ ì ê·Œ ê°ë„í ë ë€ë„ž ëȘšëžì ë§ë€ìì”ëë€! đ€Ż**
diff --git a/docs/source/ko/add_tensorflow_model.md b/docs/source/ko/add_tensorflow_model.md
new file mode 100644
index 000000000000..b0d7a064f828
--- /dev/null
+++ b/docs/source/ko/add_tensorflow_model.md
@@ -0,0 +1,263 @@
+
+
+# ìŽë»êČ đ€ Transformers ëȘšëžì TensorFlowëĄ ëłííëì? [[how-to-convert-a-transformers-model-to-tensorflow]]
+
+đ€ TransformersìììČëŒ ìŹì©í ì ìë ìŹëŹ ê°ì§ íë ììíŹê° ìë€ë êČì ì í늏ìŒìŽì
ì ì€êłí ë ê·žë€ì ê°ì ì ì ì°íêČ ìŽì©í ì ìë€ë ì„ì ìŽ ìì§ë§, ëȘšëž ëłëĄ ížíì±ì ì¶ê°íŽìŒ íë€ë ëšì ëí ìĄŽìŹíë€ë êČì ì믞í©ëë€. ìąì ììì êž°ìĄŽ ëȘšëžì TensorFlow ížíì±ì ì¶ê°íë êČìŽ [ìČìë¶í° ìëĄìŽ ëȘšëžì ì¶ê°íë êČ](add_new_model)볎ë€ë ê°ëšíë€ë êČì
ëë€!
+
+ë§ìœ ëê·ëȘš TensorFlow ëȘšëžì ë êčìŽ ìŽíŽíë €ê±°ë, ì€í ìì€ì í° êž°ìŹë„Œ íë €ê±°ë, ì íí ëȘšëžì Tensorflow넌 íì©íë €íë€ë©Ž, ìŽ ìëŽìë ìŹëŹë¶ê» ëììŽ ë êČì
ëë€.
+
+ìŽ ê°ìŽëë Hugging Face íì ì”ìíì ê°ë
ìëìì đ€ Transformersìì ìŹì©ëë TensorFlow ëȘšëž ê°ì€ìčì/ëë ìí€í
ìČ넌 êž°ìŹí ì ìë ì»€ëź€ëí° ê”Źì±ììž ìŹëŹë¶ì ëììŒëĄ í©ëë€.
+ìëĄìŽ ëȘšëžì ìì±íë êČì ìŹìŽ ìŒìŽ ìëì§ë§, ìŽ ê°ìŽë넌 í”íŽ ìĄ°êž ë íë€êł íšìŹ ìŹìŽ ìì
ìŒëĄ ë§ë€ ì ìì”ëë€.
+ëȘšëì êČœíì ëȘšìŒë êČì ìŽ ìì
ì ì ì°šì ìŒëĄ ë ìœêČ ë§ëë ë° ê”ì„í ì€ìíêž° ë돞ì, ìŽ ê°ìŽë넌 ê°ì ìíŹë§í ì ììŽ ë ì€ë„Žë©Ž êł”ì íìë걞 ì ê·čì ìŒëĄ ê¶ì„í©ëë€!
+
+ë êčìŽ ììëłŽêž° ì ì, đ€ Transformers넌 ìČì ì íë êČœì° ë€ì ìëŁë„Œ íìžíë êČìŽ ìąì”ëë€:
+- [đ€ Transformersì ìŒë° ê°ì](add_new_model#general-overview-of-transformers)
+- [Hugging Faceì TensorFlow ìČ í](https://huggingface.co/blog/tensorflow-philosophy)
+
+ìŽ ê°ìŽëì ëëšžì§ ë¶ë¶ììë ìëĄìŽ TensorFlow ëȘšëž ìí€í
ìČ넌 ì¶ê°íë ë° íìí ëšêł, Pytorch넌 TensorFlow ëȘšëž ê°ì€ìčëĄ ëłííë ì ì°š ë° ML íë ììíŹ ê°ì ë¶ìŒìč넌 íšìšì ìŒëĄ ëëČêč
íë ë°©ëČì ìêČ ë êČì
ëë€. ììíŽëŽ
ìë€!
+
+
+
+ìŹì©íë €ë ëȘšëžìŽ ìŽëŻž íŽëčíë TensorFlow ìí€í
ìČê° ìëì§ íì€íì§ ìëì?
+
+ì íí ëȘšëž([ì](https://huggingface.co/bert-base-uncased/blob/main/config.json#L14))ì `config.json`ì `model_type` íë넌 íìžíŽëłŽìžì. đ€ Transformersì íŽëč ëȘšëž íŽëìë "modeling_tf"ëĄ ììíë íìŒìŽ ìë êČœì°, íŽëč ëȘšëžìë íŽëč TensorFlow ìí€í
ìČ([ì](https://github.com/huggingface/transformers/tree/main/src/transformers/models/bert))ê° ìë€ë ì믞ì
ëë€.
+
+
+
+## TensorFlow ëȘšëž ìí€í
ìČ ìœë ì¶ê°íë ëšêłëł ê°ìŽë [[step-by-step-guide-to add-tensorFlow-model-architecture-code]]
+
+ëê·ëȘš ìí€í
ìČ넌 ê°ì§ ëȘšëžì ì€êłíë ë°©ëČìë ìŹëŹê°ì§ê° ììŒë©°, íŽëč ì€êłë„Œ ê”Źííë ë°©ëČë ìŹëŹ ê°ì§ì
ëë€.
+ê·žëŹë ì°ëŠŹë [đ€ Transformers ìŒë° ê°ì](add_new_model#general-overview-of-transformers)ìì ìžêží ëëĄ ìŒêŽë ì€êł ì íì ë°ëŒìŒì§ë§ đ€ Transformers넌 ìŹì©íêž° íží êČìŽëŒë íêł í ìêČŹì ê°ì§êł ìì”ëë€.
+ì°ëŠŹì êČœíì í”íŽ TensorFlow ëȘšëžì ì¶ê°íë ë° êŽë šë ì€ìí ëȘ ê°ì§ ìŹíì ìë € ë늎 ì ìì”ëë€:
+
+- ìŽëŻž ìë걞 ë€ì ê°ë°íë € íì§ ë§ìžì! ì”ìí 2ê°ì ìŽëŻž ê”Źíë ëȘšëžì ëê° ì°žìĄ°íŽìŒ í©ëë€. ê”Źííë €ë ëȘšëžêłŒ êž°ë„ì ëìŒí Pytorch ëȘšëž íëì ê°ì 돞ì ì íì íêł ìë ë€ë„ž TensorFlow ëȘšëž íë넌 ìŽíŽëłŽìžì.
+- ì°ìí ëȘšëž ê”Źíì ìê°ìŽ ì§ëë ëšììì”ëë€. ìŽêČì ìœëê° ìëŠë”ë€ë ìŽì ê° ìëëŒ ìœëê° ëȘ
ííêł ëëČêč
ë° ê°ì ìŽ ìœêž° ë돞ì
ëë€. TensorFlow ê”Źíìì ë€ë„ž ëȘšëžë€êłŒ íšíŽì ëê°ìŽ íêł Pytorch ê”ŹíêłŒì ë¶ìŒìč넌 ì”ìííìŹ ë©ìží
ìŽëì ì
ëŹŽë„Œ ìœêČ íë€ë©Ž, êž°ìŹí ìœëê° ì€ëëëĄ ì ì§ë ì ìì”ëë€.
+- íìíë€ë©Ž ëìì ììČíìžì! đ€ Transformers íì ìŹëŹë¶ì ëêž° ìíŽ ììŒë©°, ìŹëŹë¶ìŽ ì§ë©Ží ëìŒí 돞ì ì ëí íŽêȰì±
ì ìŽëŻž ì°Ÿì êČœì°ë ìì ì ìì”ëë€.
+
+TensorFlow ëȘšëž ìí€í
ìČ넌 ì¶ê°íë ë° íìí ëšêłë„Œ ê°ë”ì ìŒëĄ ìšëłŽë©Ž:
+1. ëłííë €ë ëȘšëž ì í
+2. transformers ê°ë° íêČœ ì€ëč
+3. (ì í ìŹí) ìŽëĄ ì ìžĄë©Ž ë° êž°ìĄŽ ê”Źí ìŽíŽ
+4. ëȘšëž ìí€í
ìČ ê”Źí
+5. ëȘšëž í
ì€íž ê”Źí
+6. PR (pull request) ì ì¶
+7. (ì í ìŹí) ë°ëȘš ëčë ë° êł”ì
+
+### 1.-3. ëȘšëž êž°ìŹ ì€ëč [[1.-3.-prepare-your-model-contribution]]
+
+**1. ëłííë €ë ëȘšëž ì í**
+
+ì°ì êž°ëłž ìŹíë¶í° ììíŽ ëłŽêČ ì”ëë€. 뚌ì ëłííë €ë ìí€í
ìČ넌 ìììŒ í©ëë€.
+íčì ìí€í
ìČì ëí êŽìŹ ìë êČœì°, đ€ Transformers íìêČ ì ìì ììČíë êČì ìŹëŹë¶ì ìí„ë „ì ê·čëííë ìąì ë°©ëČì
ëë€.
+ì°ëŠŹë TensorFlowìì ëč ì ž ìë ê°ì„ ì ëȘ
í ìí€í
ìČëĄ ìŽëìŽ ë늏êČ ì”ëë€.
+TensorFlowìì ìŹì©í ëȘšëžìŽ ìŽëŻž đ€ Transformersì TensorFlow ìí€í
ìČ ê”ŹíìŽ ìì§ë§ ê°ì€ìčê° ìë êČœì°,
+ìŽ íìŽì§ì [ê°ì€ìč ì¶ê° ìčì
](#adding-tensorflow-weights-to-hub)ìŒëĄ ë°ëĄ ìŽëíì
ë ë©ëë€.
+
+ê°ëší ë§íŽì, ìŽ ìëŽìì ëëšžì§ ë¶ë¶ì TensorFlow ëČì ì *BrandNewBert*([ê°ìŽë](add_new_model)ì ëìŒí ìì )넌 êž°ìŹíë €êł êȰì íë€êł ê°ì í©ëë€.
+
+
+
+TensorFlow ëȘšëž ìí€í
ìČì ìì
ì ììíêž° ì ì íŽëč ìì
ìŽ ì§í ì€ìžì§ íìžíìžì.
+`BrandNewBert`넌 êČìíìŹ
+[pull request GitHub íìŽì§](https://github.com/huggingface/transformers/pulls?q=is%3Apr)ìì TensorFlow êŽë š pull requestê° ìëì§ íìží ì ìì”ëë€.
+
+
+
+**2. transformers ê°ë° íêČœ ì€ëč**
+
+
+ëȘšëž ìí€í
ìČ넌 ì íí í, êŽë š ìì
ì ìíí ìë넌 믞늏 ìëŠŹêž° ìíŽ Draft PRì ìŹìžì. ìë ì§ìčšëëĄ íì멎 íêČœì ì€ì íêł Draft PRì ìŽ ì ìì”ëë€.
+
+1. 'Fork' ëČíŒì íŽëŠíìŹ [늏íŹì§í°ëŠŹ](https://github.com/huggingface/transformers)넌 íŹíŹíìžì. ìŽë êČ í멎 GitHub ìŹì©ì êłì ì ìœëì ìŹëłžìŽ ìì±ë©ëë€.
+
+
+2. `transformers` íŹíŹë„Œ ëĄì»Ź ëì€íŹì íŽëĄ íêł ìëłž 늏íŹì§í°ëŠŹë„Œ ìêČ© 늏íŹì§í°ëŠŹëĄ ì¶ê°íìžì.
+
+```bash
+git clone https://github.com/[your Github handle]/transformers.git
+cd transformers
+git remote add upstream https://github.com/huggingface/transformers.git
+```
+
+3. ê°ë° íêČœì ì€ì íìžì. ì넌 ë€ìŽ, ë€ì ëȘ
ë čì ì€ííìŹ ê°ë° íêČœì ì€ì í ì ìì”ëë€.
+
+```bash
+python -m venv .env
+source .env/bin/activate
+pip install -e ".[dev]"
+```
+
+ìŽì ìČŽì ì ë°ëŒì Transformersì ì íì ìą
ìì±ìŽ ìŠê°í멎ì ì ëȘ
ë čìŽ ì€íší ìë ìì”ëë€. ê·žë° êČœì° TensorFlow넌 ì€ìčí í ë€ìì ì€ííìžì.
+
+```bash
+pip install -e ".[quality]"
+```
+
+**ì°žêł :** CUDA넌 ì€ìčí íìë ìì”ëë€. ìëĄìŽ ëȘšëžìŽ CPUìì ìëíëëĄ ë§ëë êČë§ìŒëĄ ì¶©ë¶í©ëë€.
+
+4. ë©ìž ëžëìčìì ë§ëë €ë êž°ë„ìŽ ì ííëë ìŽëŠìŒëĄ ëžëìč넌 ë§ëëë€.
+
+```bash
+git checkout -b add_tf_brand_new_bert
+```
+
+5. ë©ìž ëžëìčì íìŹ ìí넌 íìč(fetch)íêł ëŠŹëČ ìŽì€íìžì.
+
+```bash
+git fetch upstream
+git rebase upstream/main
+```
+
+6. `transformers/src/models/brandnewbert/`ì `modeling_tf_brandnewbert.py`ëŒë ëč `.py` íìŒì ì¶ê°íìžì. ìŽ íìŒìŽ TensorFlow ëȘšëž íìŒìŽ ë êČì
ëë€.
+
+7. ëłêČœ ìŹíì êłì ì ížìíìžì.
+
+```bash
+git add .
+git commit -m "initial commit"
+git push -u origin add_tf_brand_new_bert
+```
+
+8. ë§ìĄ±ì€ëŹìŽ êČœì° GitHubìì íŹíŹë ìč íìŽì§ëĄ ìŽëí©ëë€. "Pull request"넌 íŽëŠí©ëë€. Hugging Face íì GitHub ID넌 늏뷰ìŽëĄ ì¶ê°íŽì, ììŒëĄì ëłêČœ ìŹíì ëíŽ Hugging Face íìŽ ì늌ì ë°ì ì ìëëĄ í©ëë€.
+
+
+9. GitHub Pull Requests íìŽì§ì ì€ë„žìȘœì ìë "Convert to draft"넌 íŽëŠíìŹ PRì ìŽììŒëĄ ëłêČœíìžì.
+
+ìŽì đ€ Transformersìì *BrandNewBert*넌 TensorFlowëĄ ëłíí ê°ë° íêČœì ì€ì íì”ëë€.
+
+
+**3. (ì í ìŹí) ìŽëĄ ì ìžĄë©Ž ë° êž°ìĄŽ ê”Źí ìŽíŽ**
+
+
+*BrandNewBert*ìČëŒ ììží êžìŽ ìë€ë©Ž ìê°ì ëŽìŽ ë
ŒëŹžì ìœë걞 ì¶ìČë늜ëë€. ìŽíŽíêž° ìŽë €ìŽ ë¶ë¶ìŽ ë§ì ì ìì”ëë€. ê·žë ë€êł íŽì ê±±ì íì§ ë§ìžì! ëȘ©íë ë
ŒëŹžì ìŹëìë ìŽëĄ ì ìŽíŽê° ìëëŒ TensorFlow넌 ìŹì©íìŹ đ€ Transformersì ëȘšëžì íšêłŒì ìŒëĄ ë€ì ê”Źííë ë° íìí íì ì ëłŽë„Œ ì¶ì¶íë êČì
ëë€. ë§ì ìê°ì ìŽëĄ ì ìŽíŽì íŹìí íìë ìì§ë§ ì€ì©ì ìž ìžĄë©Žìì íìŹ ìĄŽìŹíë ëȘšëž 돞ì íìŽì§(e.g. [model docs for BERT](model_doc/bert))ì ì§ì€íë êČìŽ ìąì”ëë€.
+
+
+ëȘšëžì êž°ëłž ìŹíì ìŽíŽí í, êž°ìĄŽ ê”Źíì ìŽíŽíë êČìŽ ì€ìí©ëë€. ìŽë ìì
ì€ìž ëȘšëžì ëí ì€ì ê”ŹíìŽ ìŹëŹë¶ì êž°ëì ìŒìčíšì íìžíêł , TensorFlow ìžĄë©Žììì êž°ì ì 돞ì 넌 ììí ì ìì”ëë€.
+
+ë§ëí ìì ì ëłŽë„Œ ìČììŒëĄ íì”í ë ìëëčíë êČì ìì°ì€ëŹìŽ ìŒì
ëë€. ìŽ ëšêłìì ëȘšëžì ëȘšë ìžĄë©Žì ìŽíŽíŽìŒ íë íìë ì í ìì”ëë€. ê·žëŹë ì°ëŠŹë Hugging Faceì [íŹëŒ](https://discuss.huggingface.co/)ì í”íŽ ì§ëŹžìŽ ìë êČœì° ëë”ì ê”Źí êČì ê¶ì„í©ëë€.
+
+### 4. ëȘšëž ê”Źí [[4-model-implementation]]
+
+
+ìŽì ëëìŽ ìœë©ì ììí ìê°ì
ëë€. ì°ëŠŹì ì ìë ììì ì PyTorch íìŒ ììČŽì
ëë€: `modeling_brand_new_bert.py`ì ëŽì©ì
+`src/transformers/models/brand_new_bert/` ëŽë¶ì
+`modeling_tf_brand_new_bert.py`ì ëł”ìŹí©ëë€. ìŽ ìčì
ì ëȘ©íë íìŒì ìì íêł đ€ Transformersì import ê”ŹìĄ°ë„Œ ì
ë°ìŽížíìŹ `TFBrandNewBert` ë° `TFBrandNewBert.from_pretrained(model_repo, from_pt=True)`ê° ì±êł”ì ìŒëĄ ìëíë TensorFlow *BrandNewBert* ëȘšëžì ê°ì žìŹ ì ìëëĄ íë êČì
ëë€.
+
+ì ê°ì€ëœêČë, PyTorch ëȘšëžì TensorFlowëĄ ëłííë ê·ìčì ìì”ëë€. ê·žëŹë íëĄìžì€ë„Œ ê°ë„íí ìííêČ ë§ë€êž° ìíŽ ë€ì íì ë°ë„Œ ì ìì”ëë€.
+
+- ëȘšë íŽëì€ ìŽëŠ ìì `TF`넌 ë¶ì
ëë€(ì: `BrandNewBert`ë `TFBrandNewBert`ê° ë©ëë€).
+- ëë¶ë¶ì PyTorch ìì
ìë ì§ì ì ìž TensorFlow ëìČŽê° ìì”ëë€. ì넌 ë€ìŽ, `torch.nn.Linear`ë `tf.keras.layers.Dense`ì íŽëčíêł , `torch.nn.Dropout`ì `tf.keras.layers.Dropout`ì íŽëčí©ëë€. íčì ìì
ì ëíŽ íì ìŽ ìë êČœì° [TensorFlow 돞ì](https://www.tensorflow.org/api_docs/python/tf)ë [PyTorch 돞ì](https://pytorch.org/docs/stable/)넌 ì°žìĄ°í ì ìì”ëë€.
+- đ€ Transformers ìœëëČ ìŽì€ìì íšíŽì ì°ŸìŒìžì. ì§ì ì ìž ëìČŽê° ìë íčì ìì
ì ë§ë멎 ë€ë„ž ìŹëìŽ ìŽëŻž ëìŒí 돞ì 넌 íŽêȰí êČœì°ê° ë§ì”ëë€.
+- êž°ëłžì ìŒëĄ PyTorchì ëìŒí ëłì ìŽëŠêłŒ ê”ŹìĄ°ë„Œ ì ì§íìžì. ìŽë êČ í멎 ëëČêč
êłŒ 돞ì ì¶ì , ê·žëŠŹêł ëŹžì íŽêȰ ì¶ê°ê° ë ìŹìì§ëë€.
+- ìŒë¶ ë ìŽìŽë ê° íë ììíŹë§ë€ ë€ë„ž êž°ëłžê°ì ê°ì§êł ìì”ëë€. ëíì ìž ìëĄ ë°°ìč ì ê·í ë ìŽìŽì epsilonì [PyTorch](https://pytorch.org/docs/stable/generated/torch.nn.BatchNorm2d.html#torch.nn.BatchNorm2d)ìì `1e-5`ìŽêł [TensorFlow](https://www.tensorflow.org/api_docs/python/tf/keras/layers/BatchNormalization)ìì `1e-3`ì
ëë€. 돞ì넌 ëȘšë íìžíìžì!
+- PyTorchì `nn.Parameter` ëłìë ìŒë°ì ìŒëĄ TF ë ìŽìŽì `build()` ëŽìì ìŽêž°ííŽìŒ í©ëë€. ë€ì ì넌 ì°žìĄ°íìžì: [PyTorch](https://github.com/huggingface/transformers/blob/655f72a6896c0533b1bdee519ed65a059c2425ac/src/transformers/models/vit_mae/modeling_vit_mae.py#L212) /
+ [TensorFlow](https://github.com/huggingface/transformers/blob/655f72a6896c0533b1bdee519ed65a059c2425ac/src/transformers/models/vit_mae/modeling_tf_vit_mae.py#L220)
+- PyTorch ëȘšëžì íšì ìëšì `#copied from ...`ê° ìë êČœì°, TensorFlow ëȘšëžì TensorFlow ìí€í
ìČê° ìë€ë©Ž TensorFlow ëȘšëžìŽ íŽëč íšì넌 ëł”ìŹí ìí€í
ìČìì ìŹì©í ì ìì”ëë€.
+- TensorFlow íšììì `name` ìì±ì ìŹë°ë„ŽêČ í ëčíë êČì `from_pt=True` ê°ì€ìč ê”ì°š ëĄë©ì ìííë ë° ì€ìí©ëë€. `name`ì ëë¶ë¶ PyTorch ìœëì íŽëč ëłìì ìŽëŠì
ëë€. `name`ìŽ ì ëëĄ ì€ì ëì§ ììŒë©Ž ëȘšëž ê°ì€ìč넌 ëĄëí ë ì€ë„ ë©ìì§ìì íìží ì ìì”ëë€.
+- êž°ëłž ëȘšëž íŽëì€ìž `BrandNewBertModel`ì ëĄì§ì ì€ì ëĄ Keras ë ìŽìŽ ìëžíŽëì€([ìì](https://github.com/huggingface/transformers/blob/4fd32a1f499e45f009c2c0dea4d81c321cba7e02/src/transformers/models/bert/modeling_tf_bert.py#L719))ìž `TFBrandNewBertMainLayer`ì ìì”ëë€. `TFBrandNewBertModel`ì ìŽ ë ìŽìŽë„Œ ê°ìžêž°ë§ íë ëíŒ ìí ì í©ëë€.
+- Keras ëȘšëžì ìŹì íë šë ê°ì€ìč넌 ëĄëíêž° ìíŽ ëčëëìŽìŒ í©ëë€. ë°ëŒì `TFBrandNewBertPreTrainedModel`ì ëȘšëžì ì
ë „ ìì ìž `dummy_inputs`([ìì](https://github.com/huggingface/transformers/blob/4fd32a1f499e45f009c2c0dea4d81c321cba7e02/src/transformers/models/bert/modeling_tf_bert.py#L916)) ì ì§íŽìŒ í©ëë€.
+- ëììŽ íìí êČœì° ëìì ììČíìžì. ì°ëŠŹë ìŹêž° ììŽì ëìì ëëŠŹêž° ìíŽ ìë êČì
ëë€! đ€
+
+ëȘšëž íìŒ ììČŽ ìžìë ëȘšëž íŽëì€ ë° êŽë š 돞ì íìŽì§ì ëí íŹìží°ë„Œ ì¶ê°íŽìŒ í©ëë€. ìŽ ë¶ë¶ì ë€ë„ž PR([ìì](https://github.com/huggingface/transformers/pull/18020/files))ì íšíŽì ë°ëŒ ìì í ìëŁí ì ìì”ëë€. ë€ìì íìí ìë ëłêČœ ëȘ©ëĄì
ëë€.
+
+- `src/transformers/__init__.py`ì *BrandNewBert*ì ëȘšë êł”ê° íŽëì€ë„Œ íŹíší©ëë€.
+- `src/transformers/models/auto/modeling_tf_auto.py`ìì *BrandNewBert* íŽëì€ë„Œ íŽëč Auto íŽëì€ì ì¶ê°í©ëë€.
+- `utils/documentation_tests.txt`ì ëȘšëž íìŒì 돞ìííë í
ì€íž íìŒ ëȘ©ëĄì ì¶ê°í©ëë€.
+- `src/transformers/utils/dummy_tf_objects.py`ì *BrandNewBert*ì êŽë šë ë ìŽì§ ëĄë© íŽëì€ë„Œ ì¶ê°í©ëë€.
+- `src/transformers/models/brand_new_bert/__init__.py`ìì êł”ê° íŽëì€ì ëí import ê”ŹìĄ°ë„Œ ì
ë°ìŽíží©ëë€.
+- `docs/source/en/model_doc/brand_new_bert.md`ìì *BrandNewBert*ì êł”ê° ë©ìëì ëí 돞ì íŹìží°ë„Œ ì¶ê°í©ëë€.
+- `docs/source/en/model_doc/brand_new_bert.md`ì *BrandNewBert* êž°ìŹì ëȘ©ëĄì ìì ì ì¶ê°í©ëë€.
+- ë§ì§ë§ìŒëĄ â
ë
čì ìČŽíŹë°ì€ë„Œ TensorFlow ìŽ docs/source/en/index.md ì BrandNewBertì ì¶ê°í©ëë€.
+
+ê”ŹíìŽ ë§ìĄ±í멎 ë€ì ìČŽíŹëŠŹì€ížë„Œ ì€ííìŹ ëȘšëž ìí€í
ìČê° ì€ëčëìëì§ íìžíìžì.
+
+1. íë š ìê°ì ë€ë„ŽêČ ëìíë `training` ìžìëĄ ë¶ëŠŹë ëȘšë ë ìŽìŽ(ì: Dropout)ë ì”ìì íŽëì€ìì ì íë©ëë€.
+2. #copied from ...ê°ë„í ëë§ë€ ìŹì©íì”ëë€.
+3. `TFBrandNewBertMainLayer`ì ê·žêČì ìŹì©íë ëȘšë íŽëì€ë `call`íšìëĄ `@unpack_inputs`ì íšê» ë°ìœë ìŽí° ë©ëë€.
+4. `TFBrandNewBertMainLayer`ë `@keras_serializable`ëĄ ë°ìœë ìŽí° ë©ëë€.
+5. TensorFlow ëȘšëžì `TFBrandNewBert.from_pretrained(model_repo, from_pt=True)`넌 ìŹì©íìŹ PyTorch ê°ì€ìčìì ëĄëí ì ìì”ëë€.
+6. ìì ì
ë „ íìì ìŹì©íìŹ TensorFlow ëȘšëžì ížì¶í ì ìì”ëë€.
+
+### 5. ëȘšëž í
ì€íž ê”Źí [[5-add-model-tests]]
+
+TensorFlow ëȘšëž ìí€í
ìČ넌 ê”Źííë ë° ì±êł”íì”ëë€! ìŽì TensorFlow ëȘšëžì í
ì€ížíë ê”Źíì ìì±í ì°šëĄì
ëë€. ìŽë„Œ í”íŽ ëȘšëžìŽ ììëëĄ ìëíëì§ íìží ì ìì”ëë€. ìŽì ì ì°ëŠŹë `test_modeling_brand_new_bert.py` íìŒì `tests/models/brand_new_bert/ into test_modeling_tf_brand_new_bert.py`ì ëł”ìŹí ë€, TensorFlowëĄ ê”ìČŽíë êČìŽ ìąì”ëë€. ì§êžì, ëȘšë `.from_pretrained()`ì `from_pt=True`넌 ìŹì©íìŹ ìĄŽìŹíë Pytorch ê°ì€ìč넌 ê°ì žì€ëëĄ íŽìŒí©ëë€.
+
+ìëŁíì
šìŒë©Ž, ìŽì ì§ì€ì ìê°ìŽ ì°Ÿììì”ëë€: í
ì€ížë„Œ ì€ííŽ ëłŽìžì! đŹ
+
+```bash
+NVIDIA_TF32_OVERRIDE=0 RUN_SLOW=1 RUN_PT_TF_CROSS_TESTS=1 \
+py.test -vv tests/models/brand_new_bert/test_modeling_tf_brand_new_bert.py
+```
+
+ì€ë„ê° ë§ìŽ ëíë êČìŽì§ë§ êŽì°źì”ëë€! êž°êł íì” ëȘšëžì ëëČêč
íë êČì ì
ëȘ
ëêČ ìŽë €ì°ë©° ì±êł”ì í”ìŹ ììë ìžëŽìŹì
ëë€ (`breakpoint()`ë íìí©ëë€). ì°ëŠŹì êČœíììŒëĄë ML íë ììíŹ ìŹìŽì 믞ëŹí ë¶ìŒìčëĄ ìžíŽ ê°ì„ ìŽë €ìŽ ëŹžì ê° ë°ìí©ëë€. ìŽì ëí ëȘ ê°ì§ ì§ìčšìŽ ìŽ ê°ìŽëì ë ë¶ë¶ì ìì”ëë€. ë€ë„ž êČœì°ìë ìŒë° í
ì€ížê° ì§ì ëȘšëžì ì ì©ëì§ ìì ì ììŒë©°, ìŽ êČœì° ëȘšëž í
ì€íž íŽëì€ ë ëČšìì ìŹì ì넌 ì ìí©ëë€. 돞ì ê° ëŹŽììŽë ì§ ìêŽììŽ ëŹžì ê° ììŒë©Ž ëčì ìŽ êł ëŠœëìë€ë©Ž draft pull requestìì ëìì ììČíë êČìŽ ìąì”ëë€.
+
+ëȘšë í
ì€ížê° í”êłŒë멎 ì¶íí©ëë€. ìŽì ëȘšëžì đ€ Transformers ëŒìŽëžëŹëŠŹì ì¶ê°í ì€ëčê° ê±°ì ìëŁë êČì
ëë€! đ
+
+
+í
ì€ížë„Œ ì¶ê°íë ë°©ëČì ëí ììží ëŽì©ì [đ€ Transformersì í
ì€íž ê°ìŽë](https://huggingface.co/transformers/contributing.html#running-tests)넌 ì°žìĄ°íìžì.
+
+### 6.-7. ëȘšë ìŹì©ìê° ëčì ì ëȘšëžì ìŹì©í ì ìêČ íêž° [[6.-7.-ensure-everyone -can-use-your-model]]
+
+**6. í ììČ ì ì¶íêž°**
+
+ê”ŹíêłŒ í
ì€ížê° ìëŁë멎 í ììČì ì ì¶í ìê°ì
ëë€. ìœë넌 ížìíêž° ì ì ìœë ìì ë§ì¶êž° ì ížëŠŹí°ìž `make fixup` đȘ 넌 ì€ííìžì. ìŽë êČ í멎 ìëìŒëĄ ìì ì€ë„넌 ìì íë©° ìë êČìŹê° ì€íšíë êČì ë°©ì§í ì ìì”ëë€.
+
+ìŽì ëëííž í ììČì ì€ì í ììČìŒëĄ ëłííë ìê°ì
ëë€. "늏뷰 ì€ëčëš" ëČíŒì íŽëŠíêł Joao (`@gante`)ì Matt (`@Rocketknight1`)넌 늏뷰ìŽëĄ ì¶ê°íìžì. ëȘšëž í ììČìë ì ìŽë 3ëȘ
ì 늏뷰ìŽê° íìíì§ë§, ê·žë€ìŽ ëčì ì ëȘšëžì ì ì í ì¶ê° 늏뷰ìŽë„Œ ì°Ÿì êČì
ëë€.
+
+ëȘšë 늏뷰ìŽë€ìŽ PR ìíì ë§ìĄ±í멎 ë§ì§ë§ìŒëĄ `.from_pretrained()` ížì¶ìì `from_pt=True` íë귞넌 ì ê±°íë êČì
ëë€. TensorFlow ê°ì€ìčê° ìêž° ë돞ì ìŽë„Œ ì¶ê°íŽìŒ í©ëë€! ìŽë„Œ ìííë ë°©ëČì ìë ìčì
ì ì§ìčšì íìžíìžì.
+
+ë§ìčšëŽ TensorFlow ê°ì€ìčê° ëłí©ëêł , ì ìŽë 3ëȘ
ì ëŠŹë·°ìŽ ìčìžì ë°ììŒë©° ëȘšë CI êČìŹê° í”êłŒëìë€ë©Ž, ëĄì»ŹëĄ í
ì€ížë„Œ í ëČ ë íìžíìžì.
+
+```bash
+NVIDIA_TF32_OVERRIDE=0 RUN_SLOW=1 RUN_PT_TF_CROSS_TESTS=1 \
+py.test -vv tests/models/brand_new_bert/test_modeling_tf_brand_new_bert.py
+```
+
+ê·žëŠŹêł ì°ëŠŹë ëčì ì PRì ëłí©í êČì
ëë€! ë§ìŒì€í€ ëŹì±ì ì¶íë늜ëë€! đ
+
+**7. (ì í ìŹí) ë°ëȘšë„Œ ë§ë€êł ìžìêłŒ êł”ì íêž°**
+
+ì€í ìì€ì ê°ì„ ìŽë €ìŽ ë¶ë¶ ì€ íëë ë°êČŹì
ëë€. ë€ë„ž ìŹì©ìë€ìŽ ëčì ì ë©ì§ TensorFlow êž°ìŹë„Œ ìŽë»êČ ì ì ììêčì? ëŹŒëĄ ì ì í ì»€ëź€ëìŒìŽì
ìŒëĄ ê°ë„í©ëë€! đŁ
+
+ì»€ëź€ëí°ì ëȘšëžì êł”ì íë ë ê°ì§ ìŁŒì ë°©ëČìŽ ìì”ëë€:
+- ë°ëȘš ë§ë€êž°. Gradio ë°ëȘš, ë
žížë¶ ë° ëȘšëžì ìëíë ë€ë„ž ìŹëŻžìë ë°©ëČì íŹíší©ëë€. [ì»€ëź€ëí° êž°ë° ë°ëȘš](https://huggingface.co/docs/transformers/community)ì ë
žížë¶ì ì¶ê°íë êČì ì ê·č ê¶ì„í©ëë€.
+- Twitterì LinkedInêłŒ ê°ì ìì
믞ëìŽì ìŽìŒêž° êł”ì íêž°. ëčì ì ìì
ì ìëì€ëŹìíêł ì»€ëź€ëí°ì ëčì ì ì
ì ì êł”ì íŽìŒ í©ëë€. ìŽì ëčì ì ëȘšëžì ì ìžêłì ììČ ëȘ
ì ìì§ëìŽì ì°ê”Źìë€ì ìíŽ ìŹì©ë ì ìì”ëë€ đ! ì°ëŠŹë ëčì ì êČìëŹŒì 늏ížìíêł ì»€ëź€ëí°ì íšê» ëčì ì ìì
ì êł”ì íë ë° ëììŽ ë êČì
ëë€.
+
+
+## đ€ íëžì TensorFlow ê°ì€ìč ì¶ê°íêž° [[adding-tensorFlow-weights-to-đ€-hub]]
+
+TensorFlow ëȘšëž ìí€í
ìČê° đ€ Transformersìì ìŹì© ê°ë„íë€êł ê°ì íêł , PyTorch ê°ì€ìč넌 TensorFlow ê°ì€ìčëĄ ëłííë êČì ìœì”ëë€!
+
+ë€ìì ê·ž ë°©ëČì
ëë€:
+1. í°ëŻžëìì Hugging Face êłì ìŒëĄ ëĄê·žìžëìŽ ìëì§ íìžíììì€. `huggingface-cli login` ëȘ
ë čìŽë„Œ ìŹì©íìŹ ëĄê·žìží ì ìì”ëë€. (ìĄìžì€ í í°ì [ìŹêž°](https://huggingface.co/settings/tokens)ìì ì°Ÿì ì ìì”ëë€.)
+2. `transformers-cli pt-to-tf --model-name foo/bar`넌 ì€ííììì€. ìŹêž°ì `foo/bar`ë ëłííë €ë PyTorch ê°ì€ìčê° ìë ëȘšëž ì ì„ìì ìŽëŠì
ëë€.
+3. ë°©êž ë§ë đ€ íëž PRìì `@joaogante`ì `@Rocketknight1`ì íê·ží©ëë€.
+
+ê·žêČ ë€ì
ëë€! đ
+
+
+## ML íë ììíŹ ê° ëëČêč
đ[[debugging-mismatches-across-ml-frameworks]]
+
+ìëĄìŽ ìí€í
ìČ넌 ì¶ê°íê±°ë êž°ìĄŽ ìí€í
ìČì ëí TensorFlow ê°ì€ìč넌 ìì±í ë, PyTorchì TensorFlow ê°ì ë¶ìŒìčëĄ ìží ì€ë„ê° ë°ìí ì ìì”ëë€. ìŹì§ìŽ ë íë ììíŹì ëȘšëž ìí€í
ìČ ìœëê° ëìŒíŽ ëłŽìŒ ìë ìì”ëë€. ëŹŽìš ìŒìŽ ëČìŽì§êł ìë 걞êčì? đ€
+
+뚌ì , ìŽëŹí ë¶ìŒìč넌 ìŽíŽíë ìŽì ì ëíŽ ìŽìŒêž°íŽ ëłŽêČ ì”ëë€. ë§ì ì»€ëź€ëí° ë©€ëČë€ì đ€ Transformers ëȘšëžì ê·žëëĄ ìŹì©íêł , ì°ëŠŹì ëȘšëžìŽ ììëëĄ ìëí êČìŽëŒêł 믿ì”ëë€. ë íë ììíŹ ê°ì í° ë¶ìŒìčê° ììŒë©Ž ëȘšëžìŽ ì ìŽë íëì íë ììíŹì ëí ì°žìĄ° ê”Źíì ë°ë„Žì§ ììì ì믞í©ëë€. ìŽë ëȘšëžìŽ ìëí ëëĄ ìëíì§ ìì ì ììì ëíë
ëë€. ìŽë ìì ì€íëì§ ìë ëȘšëžëłŽë€ ëì ì ìì”ëë€! ë°ëŒì ì°ëŠŹë ëȘšë ëȘšëžì íë ììíŹ ë¶ìŒìč넌 `1e-5`ëłŽë€ ìêČ ì ì§íë êČì ëȘ©íëĄ í©ëë€.
+
+êž°í ì«ì 돞ì ì ë§ì°Źê°ì§ëĄ, ìžìží 돞ì ê° ìì”ëë€. ê·žëŠŹêł ìžìžíšì ì§ì€íë êł”ì ìì íì ììë ìžëŽìŹì
ëë€. ìŽëŹí ìą
ë„ì 돞ì ê° ë°ìí ë ê¶ì„ëë ìì
íëŠì ë€ìêłŒ ê°ì”ëë€:
+1. ë¶ìŒìčì ììžì ì°Ÿì볎ììì€. ëłí ì€ìž ëȘšëžì ìë§ë íčì ì§ì êčì§ ê±°ì ëìŒí ëŽë¶ ëłì넌 ê°ì§êł ìì êČì
ëë€. ë íë ììíŹì ìí€í
ìČì `breakpoint()` 돞ì ëŁêł , ììì ìëëĄ ì«ì ëłìì ê°ì ëčê”íìŹ ëŹžì ì ê·Œìì ì°Ÿìë
ëë€.
+2. ìŽì 돞ì ì ê·Œìì ì°ŸììŒëŻëĄ đ€ Transformers íì ì°ëœíìžì. ì°ëŠŹë ëčì·í 돞ì 넌 ìŽì ì êČȘìì ì ììŒë©° ëč 넎êČ íŽêȰì±
ì ì êł”í ì ìì”ëë€. ììžì ìž êČœì°ìë StackOverflowì GitHub ìŽìì ê°ì ìžêž°ìë íìŽì§ë„Œ íìžíììì€.
+3. ë ìŽì íŽêȰì±
ìŽ ìë êČœì°, ë êčìŽ ë€ìŽê°ìŒ í©ëë€. ìąì ììì 돞ì ì ììžì ì°ŸììŒëŻëĄ ëëšžì§ ëȘšëžì ì¶ìííêł ëŹžì ê° ìë ëȘ
ë čìŽì ìŽì ì ë§ì¶ ì ìì”ëë€! ëì ììì íŽëč ëȘ
ë čìŽì ìì€ ê”Źíì ëíŽ ììëŽìŒ íë€ë êČì
ëë€. ìŒë¶ êČœì°ìë ì°žìĄ° ê”Źíì 돞ì ê° ìì ìë ììŒë ì
ì€ížëŠŒ ì ì„ììì ìŽì넌 ìŽêž°ë„Œ êșŒëŠŹì§ ë§ììì€.
+
+ìŽë€ êČœì°ìë đ€ Transformers íêłŒì í ëĄ ì í”íŽ ë¶ìŒìč넌 ìì í ì ìì ìë ìì”ëë€. ëȘšëžì ì¶ë „ ë ìŽìŽìì ë¶ìŒìčê° ë§€ì° ìì§ë§ ìšêČšì§ ìíìì íŹêČ ëíë ì ìêž° ë돞ì
ëë€. ìŽ êČœì° ëȘšëžì ë°°íŹíë êČì ì°ì ìíêž° ìíŽ ë¶ìŒìč넌 돎ìíêž°ëĄ êȰì í ìë ìì”ëë€. ììì ìžêží `pt-to-tf` CLIìë ê°ì€ìč ëłí ì ì€ë„ ë©ìì§ë„Œ 돎ìíë `--max-error` íëê·žê° ìì”ëë€.
diff --git a/docs/source/ko/attention.md b/docs/source/ko/attention.md
new file mode 100644
index 000000000000..8f82a4b851e4
--- /dev/null
+++ b/docs/source/ko/attention.md
@@ -0,0 +1,54 @@
+
+
+# ìŽí
ì
ë©ì»€ëìŠ[[attention_mechanisms]]
+
+ëë¶ë¶ì ížëì€íŹëšž ëȘšëžì ì ë°©íë Źìž ì ìČŽ ìŽí
ì
ì ìŹì©í©ëë€.
+íì§ë§ ìŽë ꞎ í
ì€ížë„Œ ë€ëٰ ëë í° êłì° ëłëȘ© íìì ì ë°í ì ìì”ëë€.
+`Longformer`ì `Reformer`ë íë š ìë넌 ëìŽêž° ìíŽ ìŽí
ì
íë Źì íŹì ëČì ì ìŹì©íìŹ íšìšì ëìŽë €ë ëȘšëžì
ëë€.
+
+## LSH ìŽí
ì
[[lsh_attention]]
+
+
+[Reformer](#reformer)ë LSH(Locality Sensitive Hashing) ìŽí
ì
ì ìŹì©í©ëë€. softmax(QK^t)ììë íë Ź QK^tì (softmax ì°šììì) ê°ì„ í° ììë€ë§ ì ì©í êž°ìŹë„Œ í êČì
ëë€.
+ë°ëŒì ê°ê°ì ìżŒëŠŹ qì ëíŽ, qì ê°êčìŽ í€ kë§ êł ë €í ì ìì”ëë€. íŽì íšìë qì kê° ê°êčìŽì§ ìŹë¶ë„Œ êȰì íë ë° ìŹì©ë©ëë€.
+ìŽí
ì
ë§ì€íŹë íìŹ í í°ì ë§ì€íčíìŹ ëłêČœë©ëë€. ìŽ ë ìČ« ëČì§ž ììčì í í°ì ì ìží©ëë€. ìëí멎 ìżŒëŠŹì í€ê° ëìŒí ê°ì ê°êČ ëêž° ë돞ì
ëë€(ìëĄ ë§€ì° ì ìŹíš).
+íŽìë ìœê°ì 돎ììì±ì ê°ì§ ì ììŒëŻëĄ, ì€ì ëĄë ìŹëŹ ê°ì íŽì íšìê° ìŹì©ëêł (`n_rounds` ë§€ê°ëłìì ìíŽ êȰì ëš) ê·ž íì íê· ê°ì ì·šíêČ ë©ëë€.
+
+## ì§ì ìŽí
ì
[[local_attention]]
+
+[Longformer](#longformer)ë ì§ì ìŽí
ì
ì ìŹì©í©ëë€. ìą
ìą
íčì í í°ì ëíŽ ì§ì 컚í
ì€íž(ì: ìŒìȘœêłŒ ì€ë„žìȘœì ìë ë ê°ì í í°ì 돎ììžê°ì?)ë§ìŒëĄë ìì
ì ìííëë° ì¶©ë¶í©ëë€.
+ëí ìì ì°œ(window)ì ê°ì§ ìŽí
ì
ë ìŽìŽë„Œ ìììŒëĄìš ë§ì§ë§ ë ìŽìŽë ì°œ ëŽì í í°ëżë§ ìëëŒ ë ë§ì ìì í í°ì ëí ìì© ìì(receptive field)ì ê°êČ ëìŽ ì ìČŽ 돞ì„ì ííì ê”Źì¶í ì ìì”ëë€.
+
+ìŹì ì ì íë ìŒë¶ ì
ë „ í í°ë€ì ì ì ìŽí
ì
ì ë°ì”ëë€. ìŽ ëȘ ê°ì í í°ì ëíŽìë ìŽí
ì
íë ŹìŽ ëȘšë í í°ì ì ê·Œí ì ììŒë©°, ìŽ êłŒì ì ëìčì ìŒëĄ ìŽëŁšìŽì§ëë€.
+ë€ë„ž ëȘšë í í°ë€ì ëĄì»Ź ì°œ ëŽì í í°ë€ì ëíŽ íŽëč íčì í í°ë€ìë ì ê·Œí ì ìì”ëë€. ìŽë ë
ŒëŹžì Figure 2dìì ëíëë©°, ìëì ìí ìŽí
ì
ë§ì€íŹê° ì ìëìŽ ìì”ëë€:
+
+
+
+
+
+
+
+ì ì íëŒëŻží°ì ìŽí
ì
íë Źì ìŹì©í멎 ëȘšëžìŽ ë í° ìíì€ ì
ë „ êžžìŽë„Œ ê°ì§ ì ìì”ëë€.
+
+## ë€ë„ž ë°©ëČë€[[other_tricks]]
+
+### ì¶ëł ììč ìžìœë©[[axial_positional_encodings]]
+
+[Reformer](#reformer)ë ì¶ëł ììč ìžìœë©(axial positional encodings)ì ìŹì©í©ëë€. êž°ìĄŽì ížëì€íŹëšž ëȘšëžììë ììč ìžìœë© íë Ź Eë íŹêž°ê° \\(l \times d\\)ìž íë ŹìŽë©°,
+ìŹêž°ì \\(l\\)ì ìíì€ êžžìŽ(sequence length)ìŽêł \\(d\\)ë ìšêČšì§ ìí(hidden state)ì ì°šìì
ëë€. ë§€ì° êžŽ í
ì€ížì êČœì°, ìŽ íë Źì ë§€ì° íŹë©° GPU ììì êł”ê°ì ë§ìŽ ì°šì§í ì ìì”ëë€.
+ìŽë„Œ ìííêž° ìíŽ, ì¶ëł ììč ìžìœë©ì í° íë Ź E넌 ë ê°ì ìì íë Ź E1êłŒ E2ëĄ ë¶íŽí©ëë€. ìŽë E1ì íŹêž°ë \\(l_{1} \times d_{1}\\)ìŽêł , E2ì íŹêž°ë \\(l_{2} \times d_{2}\\)ì
ëë€.
+ìŽë \\(l_{1} \times l_{2} = l\\)ìŽêł \\(d_{1} + d_{2} = d\\)(êžžìŽì ëí êł±ì
ì°ì°ì ìŹì©í멎 íšìŹ ììì§ëë€). Eì ìê° ëšêł jì ëí ìëČ ë©ì E1ìì ìê° ëšêł \\(j \% l1\\)ì ìëČ ë©êłŒ E2ìì ìê° ëšêł \\(j // l1\\)ì ìëČ ë©ì ì°êȰíìŹ ì»ì”ëë€.
\ No newline at end of file
diff --git a/docs/source/ko/autoclass_tutorial.md b/docs/source/ko/autoclass_tutorial.md
new file mode 100644
index 000000000000..9ecfd9c2015d
--- /dev/null
+++ b/docs/source/ko/autoclass_tutorial.md
@@ -0,0 +1,144 @@
+
+
+# AutoClassëĄ ìŹì íì”ë ìžì€íŽì€ ëĄë[[load-pretrained-instances-with-an-autoclass]]
+
+ížëì€íŹëšž ìí€í
ìČê° ë§€ì° ë€ìíêž° ë돞ì ìČŽíŹíŹìžížì ë§ë ìí€í
ìČ넌 ìì±íë êČìŽ ìŽë €ìž ì ìì”ëë€. ëŒìŽëžëŹëŠŹë„Œ ìœêł ê°ëšíë©° ì ì°íêČ ìŹì©íêž° ìí Transformer í”ìŹ ìČ íì ìŒíìŒëĄ, `AutoClass`ë ìŁŒìŽì§ ìČŽíŹíŹìžížìì ìŹë°ë„ž ìí€í
ìČ넌 ìëìŒëĄ ì¶ëĄ íìŹ ëĄëí©ëë€. `from_pretrained()` ë©ìë넌 ìŹì©í멎 ëȘšë ìí€í
ìČì ëíŽ ìŹì íì”ë ëȘšëžì ëč 넎êČ ëĄëí ì ììŒëŻëĄ ëȘšëžì ìČìë¶í° íì”íë ë° ìê°êłŒ 늏ìì€ë„Œ íŹì
í íìê° ìì”ëë€.
+ìČŽíŹíŹìžížì ê”Źì ë°ì§ ìë ìœë넌 ìì±íë€ë êČì ìœëê° í ìČŽíŹíŹìžížìì ìëí멎 ìí€í
ìČê° ë€ë„ŽëëŒë ë€ë„ž ìČŽíŹíŹìžíž(ì ìŹí ìì
ì ëíŽ íì”ë êČœì°)ììë ìëíë€ë êČì ì믞í©ëë€.
+
+
+
+ìí€í
ìČë ëȘšëžì êłšêČ©ì ì믞íë©° ìČŽíŹíŹìžížë ìŁŒìŽì§ ìí€í
ìČì ëí ê°ì€ìčì
ëë€. ì넌 ë€ìŽ, [BERT](https://huggingface.co/bert-base-uncased)ë ìí€í
ìČìŽêł , `bert-base-uncased`ë ìČŽíŹíŹìžížì
ëë€. ëȘšëžì ìí€í
ìČ ëë ìČŽíŹíŹìžížë„Œ ì믞í ì ìë ìŒë°ì ìž ì©ìŽì
ëë€.
+
+
+
+ìŽ íí 늏ìŒììë ë€ìì íì”í©ëë€:
+
+* ìŹì íì”ë í íŹëìŽì ëĄëíêž°.
+* ìŹì íì”ë ìŽëŻžì§ íëĄìžì ëĄëíêž°.
+* ìŹì íì”ë íčì§ ì¶ì¶êž° ëĄëíêž°.
+* ìŹì íë šë íëĄìžì ëĄëíêž°.
+* ìŹì íì”ë ëȘšëž ëĄëíêž°.
+
+## AutoTokenizer[[autotokenizer]]
+
+ê±°ì ëȘšë NLP ìì
ì í íŹëìŽì ëĄ ììë©ëë€. í íŹëìŽì ë ìŹì©ìì ì
ë „ì ëȘšëžìì ìČ늏í ì ìë íììŒëĄ ëłíí©ëë€.
+[`AutoTokenizer.from_pretrained`]ëĄ í íŹëìŽì 넌 ëĄëí©ëë€:
+
+```py
+>>> from transformers import AutoTokenizer
+
+>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
+```
+
+ê·žëŠŹêł ìëì ê°ìŽ ì
ë „ì í í°íí©ëë€:
+
+```py
+>>> sequence = "In a hole in the ground there lived a hobbit."
+>>> print(tokenizer(sequence))
+{'input_ids': [101, 1999, 1037, 4920, 1999, 1996, 2598, 2045, 2973, 1037, 7570, 10322, 4183, 1012, 102],
+ 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}
+```
+
+## AutoImageProcessor[[autoimageprocessor]]
+
+ëčì ìì
ì êČœì° ìŽëŻžì§ íëĄìžìê° ìŽëŻžì§ë„Œ ìŹë°ë„ž ì
ë „ íììŒëĄ ìČ늏í©ëë€.
+
+```py
+>>> from transformers import AutoImageProcessor
+
+>>> image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224")
+```
+
+
+## AutoFeatureExtractor[[autofeatureextractor]]
+
+ì€ëì€ ìì
ì êČœì° íčì§ ì¶ì¶êž°ê° ì€ëì€ ì ížë„Œ ìŹë°ë„ž ì
ë „ íììŒëĄ ìČ늏í©ëë€.
+
+[`AutoFeatureExtractor.from_pretrained`]ëĄ íčì§ ì¶ì¶êž°ë„Œ ëĄëí©ëë€:
+
+```py
+>>> from transformers import AutoFeatureExtractor
+
+>>> feature_extractor = AutoFeatureExtractor.from_pretrained(
+... "ehcalabres/wav2vec2-lg-xlsr-en-speech-emotion-recognition"
+... )
+```
+
+## AutoProcessor[[autoprocessor]]
+
+ë©í°ëȘšëŹ ìì
ìë ë ê°ì§ ì íì ì ìČ늏 ëê”Źë„Œ êȰí©í íëĄìžìê° íìí©ëë€. ì넌 ë€ìŽ LayoutLMV2 ëȘšëžìë ìŽëŻžì§ë„Œ ìČ늏íë ìŽëŻžì§ íëĄìžìì í
ì€ížë„Œ ìČ늏íë í íŹëìŽì ê° íìíë©°, íëĄìžìë ìŽ ë ê°ì§ë„Œ êȰí©í©ëë€.
+
+[`AutoProcessor.from_pretrained()`]ëĄ íëĄìžì넌 ëĄëí©ëë€:
+
+```py
+>>> from transformers import AutoProcessor
+
+>>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv2-base-uncased")
+```
+
+## AutoModel[[automodel]]
+
+
+
+ë§ì§ë§ìŒëĄ AutoModelForíŽëì€ë„Œ ìŹì©í멎 ìŁŒìŽì§ ìì
ì ëíŽ ëŻžëŠŹ íì”ë ëȘšëžì ëĄëí ì ìì”ëë€ (ìŹì© ê°ë„í ìì
ì ì ìČŽ ëȘ©ëĄì [ìŹêž°](model_doc/auto)넌 ì°žìĄ°íìžì). ì넌 ë€ìŽ, [`AutoModelForSequenceClassification.from_pretrained`]넌 ìŹì©íìŹ ìíì€ ë¶ë„ì© ëȘšëžì ëĄëí ì ìì”ëë€:
+
+```py
+>>> from transformers import AutoModelForSequenceClassification
+
+>>> model = AutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased")
+```
+
+ëìŒí ìČŽíŹíŹìžížë„Œ ìœêČ ìŹìŹì©íìŹ ë€ë„ž ìì
ì ìí€í
ìČ넌 ëĄëí ì ìì”ëë€:
+
+```py
+>>> from transformers import AutoModelForTokenClassification
+
+>>> model = AutoModelForTokenClassification.from_pretrained("distilbert-base-uncased")
+```
+
+
+
+PyTorchëȘšëžì êČœì° `from_pretrained()` ë©ìëë ëŽë¶ì ìŒëĄ íŒíŽì ìŹì©íìŹ ìì íì§ ìì êČìŒëĄ ìë €ì§ `torch.load()`넌 ìŹì©í©ëë€.
+ìŒë°ì ìŒëĄ ì ëą°í ì ìë ìì€ìì ê°ì žìê±°ë ëłìĄ°ëìì ì ìë ëȘšëžì ëĄëíì§ ë§ìžì. íêč
íìŽì€ íëžìì ížì€í
ëë êł”ê° ëȘšëžì êČœì° ìŽëŹí 볎ì ìíìŽ ë¶ë¶ì ìŒëĄ ìíëë©°, ê° ì»€ë° ì ë©ìšìŽë„Œ [êČìŹí©ëë€](https://huggingface.co/docs/hub/security-malware). GPG넌 ìŹì©íŽ ìëȘ
ë [ì»€ë° êČìŠ](https://huggingface.co/docs/hub/security-gpg#signing-commits-with-gpg)êłŒ ê°ì ëȘšëČìŹëĄë [돞ì](https://huggingface.co/docs/hub/security)넌 ì°žìĄ°íìžì.
+
+í
ìíëĄì°ì Flax ìČŽíŹíŹìžížë ìí„ì ë°ì§ ììŒë©°, `from_pretrained`ë©ìëì `from_tf` ì `from_flax` í€ìë ê°ëł ìžì넌 ìŹì©íìŹ ìŽ ëŹžì 넌 ì°íí ì ìì”ëë€.
+
+
+
+ìŒë°ì ìŒëĄ AutoTokenizer íŽëì€ì AutoModelFor íŽëì€ë„Œ ìŹì©íìŹ ëŻžëŠŹ íì”ë ëȘšëž ìžì€íŽì€ë„Œ ëĄëíë êČìŽ ìąì”ëë€. ìŽë êČ í멎 ë§€ëČ ìŹë°ë„ž ìí€í
ìČ넌 ëĄëí ì ìì”ëë€. ë€ì [íí 늏ìŒ](preprocessing)ììë ìëĄêČ ëĄëí í íŹëìŽì , ìŽëŻžì§ íëĄìžì, íčì§ ì¶ì¶êž°ë„Œ ìŹì©íìŹ ëŻžìž íëì© ë°ìŽí° ìžížë„Œ ì ìČ늏íë ë°©ëČì ëíŽ ììëŽ
ëë€.
+
+
+ë§ì§ë§ìŒëĄ `TFAutoModelFor` íŽëì€ë„Œ ìŹì©í멎 ìŁŒìŽì§ ìì
ì ëíŽ ìŹì íë šë ëȘšëžì ëĄëí ì ìì”ëë€. (ìŹì© ê°ë„í ìì
ì ì ìČŽ ëȘ©ëĄì [ìŹêž°](model_doc/auto)넌 ì°žìĄ°íìžì. ì넌 ë€ìŽ, [`TFAutoModelForSequenceClassification.from_pretrained`]ëĄ ìíì€ ë¶ë„넌 ìí ëȘšëžì ëĄëí©ëë€:
+
+```py
+>>> from transformers import TFAutoModelForSequenceClassification
+
+>>> model = TFAutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased")
+```
+
+ìœêČ ëìŒí ìČŽíŹíŹìžížë„Œ ìŹìŹì©íìŹ ë€ë„ž ìì
ì ìí€í
ìČ넌 ëĄëí ì ìì”ëë€:
+
+```py
+>>> from transformers import TFAutoModelForTokenClassification
+
+>>> model = TFAutoModelForTokenClassification.from_pretrained("distilbert-base-uncased")
+```
+
+ìŒë°ì ìŒëĄ, `AutoTokenizer`íŽëì€ì `TFAutoModelFor` íŽëì€ë„Œ ìŹì©íìŹ ëŻžëŠŹ íì”ë ëȘšëž ìžì€íŽì€ë„Œ ëĄëíë êČìŽ ìąì”ëë€. ìŽë êČ í멎 ë§€ëČ ìŹë°ë„ž ìí€í
ìČ넌 ëĄëí ì ìì”ëë€. ë€ì [íí 늏ìŒ](preprocessing)ììë ìëĄêČ ëĄëí í íŹëìŽì , ìŽëŻžì§ íëĄìžì, íčì§ ì¶ì¶êž°ë„Œ ìŹì©íìŹ ëŻžìž íëì© ë°ìŽí° ìžížë„Œ ì ìČ늏íë ë°©ëČì ëíŽ ììëŽ
ëë€.
+
+
diff --git a/docs/source/ko/autoclass_tutorial.mdx b/docs/source/ko/autoclass_tutorial.mdx
deleted file mode 100644
index dfbfda2d5148..000000000000
--- a/docs/source/ko/autoclass_tutorial.mdx
+++ /dev/null
@@ -1,140 +0,0 @@
-
-
-# AutoClassëĄ ìŹì íì”ë ìžì€íŽì€ ëĄë[[load-pretrained-instances-with-an-autoclass]]
-
-ížëì€íŹëšž ìí€í
ìČê° ë§€ì° ë€ìíêž° ë돞ì ìČŽíŹíŹìžížì ë§ë ìí€í
ìČ넌 ìì±íë êČìŽ ìŽë €ìž ì ìì”ëë€. ëŒìŽëžëŹëŠŹë„Œ ìœêł ê°ëšíë©° ì ì°íêČ ìŹì©íêž° ìí Transformer í”ìŹ ìČ íì ìŒíìŒëĄ, `AutoClass`ë ìŁŒìŽì§ ìČŽíŹíŹìžížìì ìŹë°ë„ž ìí€í
ìČ넌 ìëìŒëĄ ì¶ëĄ íìŹ ëĄëí©ëë€. `from_pretrained()` ë©ìë넌 ìŹì©í멎 ëȘšë ìí€í
ìČì ëíŽ ìŹì íì”ë ëȘšëžì ëč 넎êČ ëĄëí ì ììŒëŻëĄ ëȘšëžì ìČìë¶í° íì”íë ë° ìê°êłŒ 늏ìì€ë„Œ íŹì
í íìê° ìì”ëë€.
-ìČŽíŹíŹìžížì ê”Źì ë°ì§ ìë ìœë넌 ìì±íë€ë êČì ìœëê° í ìČŽíŹíŹìžížìì ìëí멎 ìí€í
ìČê° ë€ë„ŽëëŒë ë€ë„ž ìČŽíŹíŹìžíž(ì ìŹí ìì
ì ëíŽ íì”ë êČœì°)ììë ìëíë€ë êČì ì믞í©ëë€.
-
-
-
-ìí€í
ìČë ëȘšëžì êłšêČ©ì ì믞íë©° ìČŽíŹíŹìžížë ìŁŒìŽì§ ìí€í
ìČì ëí ê°ì€ìčì
ëë€. ì넌 ë€ìŽ, [BERT](https://huggingface.co/bert-base-uncased)ë ìí€í
ìČìŽêł , `bert-base-uncased`ë ìČŽíŹíŹìžížì
ëë€. ëȘšëžì ìí€í
ìČ ëë ìČŽíŹíŹìžížë„Œ ì믞í ì ìë ìŒë°ì ìž ì©ìŽì
ëë€.
-
-
-
-ìŽ íí 늏ìŒììë ë€ìì íì”í©ëë€:
-
-* ìŹì íì”ë í íŹëìŽì ëĄëíêž°.
-* ìŹì íì”ë ìŽëŻžì§ íëĄìžì ëĄëíêž°.
-* ìŹì íì”ë íčì§ ì¶ì¶êž° ëĄëíêž°.
-* ìŹì íë šë íëĄìžì ëĄëíêž°.
-* ìŹì íì”ë ëȘšëž ëĄëíêž°.
-
-## AutoTokenizer[[autotokenizer]]
-
-ê±°ì ëȘšë NLP ìì
ì í íŹëìŽì ëĄ ììë©ëë€. í íŹëìŽì ë ìŹì©ìì ì
ë „ì ëȘšëžìì ìČ늏í ì ìë íììŒëĄ ëłíí©ëë€.
-[`AutoTokenizer.from_pretrained`]ëĄ í íŹëìŽì 넌 ëĄëí©ëë€:
-
-```py
->>> from transformers import AutoTokenizer
-
->>> tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
-```
-
-ê·žëŠŹêł ìëì ê°ìŽ ì
ë „ì í í°íí©ëë€:
-
-```py
->>> sequence = "In a hole in the ground there lived a hobbit."
->>> print(tokenizer(sequence))
-{'input_ids': [101, 1999, 1037, 4920, 1999, 1996, 2598, 2045, 2973, 1037, 7570, 10322, 4183, 1012, 102],
- 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
- 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}
-```
-
-## AutoImageProcessor[[autoimageprocessor]]
-
-ëčì ìì
ì êČœì° ìŽëŻžì§ íëĄìžìê° ìŽëŻžì§ë„Œ ìŹë°ë„ž ì
ë „ íììŒëĄ ìČ늏í©ëë€.
-
-```py
->>> from transformers import AutoImageProcessor
-
->>> image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224")
-```
-
-
-## AutoFeatureExtractor[[autofeatureextractor]]
-
-ì€ëì€ ìì
ì êČœì° íčì§ ì¶ì¶êž°ê° ì€ëì€ ì ížë„Œ ìŹë°ë„ž ì
ë „ íììŒëĄ ìČ늏í©ëë€.
-
-[`AutoFeatureExtractor.from_pretrained`]ëĄ íčì§ ì¶ì¶êž°ë„Œ ëĄëí©ëë€:
-
-```py
->>> from transformers import AutoFeatureExtractor
-
->>> feature_extractor = AutoFeatureExtractor.from_pretrained(
-... "ehcalabres/wav2vec2-lg-xlsr-en-speech-emotion-recognition"
-... )
-```
-
-## AutoProcessor[[autoprocessor]]
-
-ë©í°ëȘšëŹ ìì
ìë ë ê°ì§ ì íì ì ìČ늏 ëê”Źë„Œ êȰí©í íëĄìžìê° íìí©ëë€. ì넌 ë€ìŽ LayoutLMV2 ëȘšëžìë ìŽëŻžì§ë„Œ ìČ늏íë ìŽëŻžì§ íëĄìžìì í
ì€ížë„Œ ìČ늏íë í íŹëìŽì ê° íìíë©°, íëĄìžìë ìŽ ë ê°ì§ë„Œ êȰí©í©ëë€.
-
-[`AutoProcessor.from_pretrained()`]ëĄ íëĄìžì넌 ëĄëí©ëë€:
-
-```py
->>> from transformers import AutoProcessor
-
->>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv2-base-uncased")
-```
-
-## AutoModel[[automodel]]
-
-
-
-ë§ì§ë§ìŒëĄ AutoModelForíŽëì€ë„Œ ìŹì©í멎 ìŁŒìŽì§ ìì
ì ëíŽ ëŻžëŠŹ íì”ë ëȘšëžì ëĄëí ì ìì”ëë€ (ìŹì© ê°ë„í ìì
ì ì ìČŽ ëȘ©ëĄì [ìŹêž°](model_doc/auto)넌 ì°žìĄ°íìžì). ì넌 ë€ìŽ, [`AutoModelForSequenceClassification.from_pretrained`]넌 ìŹì©íìŹ ìíì€ ë¶ë„ì© ëȘšëžì ëĄëí ì ìì”ëë€:
-
-```py
->>> from transformers import AutoModelForSequenceClassification
-
->>> model = AutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased")
-```
-
-ëìŒí ìČŽíŹíŹìžížë„Œ ìœêČ ìŹìŹì©íìŹ ë€ë„ž ìì
ì ìí€í
ìČ넌 ëĄëí ì ìì”ëë€:
-
-```py
->>> from transformers import AutoModelForTokenClassification
-
->>> model = AutoModelForTokenClassification.from_pretrained("distilbert-base-uncased")
-```
-
-
-
-PyTorchëȘšëžì êČœì° `from_pretrained()` ë©ìëë ëŽë¶ì ìŒëĄ íŒíŽì ìŹì©íìŹ ìì íì§ ìì êČìŒëĄ ìë €ì§ `torch.load()`넌 ìŹì©í©ëë€.
-ìŒë°ì ìŒëĄ ì ëą°í ì ìë ìì€ìì ê°ì žìê±°ë ëłìĄ°ëìì ì ìë ëȘšëžì ëĄëíì§ ë§ìžì. íêč
íìŽì€ íëžìì ížì€í
ëë êł”ê° ëȘšëžì êČœì° ìŽëŹí 볎ì ìíìŽ ë¶ë¶ì ìŒëĄ ìíëë©°, ê° ì»€ë° ì ë©ìšìŽë„Œ [êČìŹí©ëë€](https://huggingface.co/docs/hub/security-malware). GPG넌 ìŹì©íŽ ìëȘ
ë [ì»€ë° êČìŠ](https://huggingface.co/docs/hub/security-gpg#signing-commits-with-gpg)êłŒ ê°ì ëȘšëČìŹëĄë [돞ì](https://huggingface.co/docs/hub/security)넌 ì°žìĄ°íìžì.
-
-í
ìíëĄì°ì Flax ìČŽíŹíŹìžížë ìí„ì ë°ì§ ììŒë©°, `from_pretrained`ë©ìëì `from_tf` ì `from_flax` í€ìë ê°ëł ìžì넌 ìŹì©íìŹ ìŽ ëŹžì 넌 ì°íí ì ìì”ëë€.
-
-
-
-ìŒë°ì ìŒëĄ AutoTokenizer íŽëì€ì AutoModelFor íŽëì€ë„Œ ìŹì©íìŹ ëŻžëŠŹ íì”ë ëȘšëž ìžì€íŽì€ë„Œ ëĄëíë êČìŽ ìąì”ëë€. ìŽë êČ í멎 ë§€ëČ ìŹë°ë„ž ìí€í
ìČ넌 ëĄëí ì ìì”ëë€. ë€ì [íí 늏ìŒ](preprocessing)ììë ìëĄêČ ëĄëí í íŹëìŽì , ìŽëŻžì§ íëĄìžì, íčì§ ì¶ì¶êž°ë„Œ ìŹì©íìŹ ëŻžìž íëì© ë°ìŽí° ìžížë„Œ ì ìČ늏íë ë°©ëČì ëíŽ ììëŽ
ëë€.
-
-
-ë§ì§ë§ìŒëĄ `TFAutoModelFor` íŽëì€ë„Œ ìŹì©í멎 ìŁŒìŽì§ ìì
ì ëíŽ ìŹì íë šë ëȘšëžì ëĄëí ì ìì”ëë€. (ìŹì© ê°ë„í ìì
ì ì ìČŽ ëȘ©ëĄì [ìŹêž°](model_doc/auto)넌 ì°žìĄ°íìžì. ì넌 ë€ìŽ, [`TFAutoModelForSequenceClassification.from_pretrained`]ëĄ ìíì€ ë¶ë„넌 ìí ëȘšëžì ëĄëí©ëë€:
-
-```py
->>> from transformers import TFAutoModelForSequenceClassification
-
->>> model = TFAutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased")
-```
-
-ìœêČ ëìŒí ìČŽíŹíŹìžížë„Œ ìŹìŹì©íìŹ ë€ë„ž ìì
ì ìí€í
ìČ넌 ëĄëí ì ìì”ëë€:
-
-```py
->>> from transformers import TFAutoModelForTokenClassification
-
->>> model = TFAutoModelForTokenClassification.from_pretrained("distilbert-base-uncased")
-```
-
-ìŒë°ì ìŒëĄ, `AutoTokenizer`íŽëì€ì `TFAutoModelFor` íŽëì€ë„Œ ìŹì©íìŹ ëŻžëŠŹ íì”ë ëȘšëž ìžì€íŽì€ë„Œ ëĄëíë êČìŽ ìąì”ëë€. ìŽë êČ í멎 ë§€ëČ ìŹë°ë„ž ìí€í
ìČ넌 ëĄëí ì ìì”ëë€. ë€ì [íí 늏ìŒ](preprocessing)ììë ìëĄêČ ëĄëí í íŹëìŽì , ìŽëŻžì§ íëĄìžì, íčì§ ì¶ì¶êž°ë„Œ ìŹì©íìŹ ëŻžìž íëì© ë°ìŽí° ìžížë„Œ ì ìČ늏íë ë°©ëČì ëíŽ ììëŽ
ëë€.
-
-
diff --git a/docs/source/ko/bertology.md b/docs/source/ko/bertology.md
new file mode 100644
index 000000000000..7b4f3dc4c493
--- /dev/null
+++ b/docs/source/ko/bertology.md
@@ -0,0 +1,41 @@
+
+
+# BERTology
+
+BERTì ê°ì ëê·ëȘš ížëì€íŹëšžì ëŽë¶ ëìì ìĄ°ìŹíë ì°ê”Ź ë¶ìŒê° ì ì ë ì€ìíŽì§êł ìì”ëë€.
+íčìë "BERTology"ëŒ ìčíêž°ë í©ëë€. ìŽ ë¶ìŒì ìąì ììë ë€ìêłŒ ê°ì”ëë€:
+
+
+- BERTë êł ì ì ìž NLP íìŽíëŒìžì ìŹë°êČŹ - Ian Tenney, Dipanjan Das, Ellie Pavlick:
+ https://arxiv.org/abs/1905.05950
+- 16ê°ì í€ëê° ì ë§ëĄ 1ê°ëłŽë€ ëìê°? - Paul Michel, Omer Levy, Graham Neubig:
+ https://arxiv.org/abs/1905.10650
+- BERTë 돎ìì 볎ëê°? BERTì ìŽí
ì
ë¶ì - Kevin Clark, Urvashi Khandelwal, Omer Levy, Christopher D. Manning:
+ https://arxiv.org/abs/1906.04341
+- CAT-probing: íëĄê·žëë° ìžìŽì ëíŽ ìŹì íë šë ëȘšëžìŽ ìŽë»êČ ìœë ê”ŹìĄ°ë„Œ 볎ëì§ ììëłŽêž° ìí ë©ížëŠ êž°ë° ì ê·Œ ë°©ëČ:
+ https://arxiv.org/abs/2210.04633
+
+ì°ëŠŹë ìŽ ìëĄìŽ ì°ê”Ź ë¶ìŒì ë°ì ì ëêž° ìíŽ, BERT/GPT/GPT-2 ëȘšëžì ëŽë¶ ííì ìŽíŽëłŒ ì ìë ëȘ ê°ì§ êž°ë„ì ì¶ê°íì”ëë€.
+ìŽ êž°ë„ë€ì ìŁŒëĄ Paul Michelì íë„í ìì
ì ì°žêł íìŹ ê°ë°ëìì”ëë€
+(https://arxiv.org/abs/1905.10650):
+
+
+- BERT/GPT/GPT-2ì ëȘšë ìë ìíì ì ê·Œíêž°,
+- BERT/GPT/GPT-2ì ê° í€ëì ëȘšë ìŽí
ì
ê°ì€ìčì ì ê·Œíêž°,
+- í€ëì ì¶ë „ ê°êłŒ ê·žëëìžížë„Œ êČìíìŹ í€ë ì€ìë ì ì넌 êłì°íêł https://arxiv.org/abs/1905.10650ìì ì€ëȘ
ë ëëĄ í€ë넌 ì ê±°íë êž°ë„ì ì êł”í©ëë€.
+
+ìŽëŹí êž°ë„ë€ì ìŽíŽíêł ì§ì ìŹì©íŽëłŒ ì ìëëĄ [bertology.py](https://github.com/huggingface/transformers/tree/main/examples/research_projects/bertology/run_bertology.py) ìì ì€íŹëŠœížë„Œ ì¶ê°íì”ëë€. ìŽ ìì ì€íŹëŠœížììë GLUEì ëíŽ ìŹì íë šë ëȘšëžìì ì ëłŽë„Œ ì¶ì¶íêł ëȘšëžì ê°ì§ìčêž°(prune)íŽëŽ
ëë€.
diff --git a/docs/source/ko/create_a_model.md b/docs/source/ko/create_a_model.md
new file mode 100644
index 000000000000..8c7be3291e24
--- /dev/null
+++ b/docs/source/ko/create_a_model.md
@@ -0,0 +1,388 @@
+
+
+# ë§ì¶€í ìí€í
ìČ ë§ë€êž°[[create-a-custom-architecture]]
+
+[`AutoClass`](model_doc/auto)ë ëȘšëž ìí€í
ìČ넌 ìëìŒëĄ ì¶ëĄ íêł ëŻžëŠŹ íì”ë configurationêłŒ ê°ì€ìč넌 ë€ìŽëĄëí©ëë€. ìŒë°ì ìŒëĄ ìČŽíŹíŹìžížì ê”Źì ë°ì§ ìë ìœë넌 ìì±íë €ë©Ž `AutoClass`넌 ìŹì©íë êČìŽ ìąì”ëë€. íì§ë§ íčì ëȘšëž íëŒëŻží°ë„Œ ëłŽë€ ìžë°íêČ ì ìŽíêł ì íë ìŹì©ìë ëȘ ê°ì§ êž°ëłž íŽëì€ë§ìŒëĄ 컀ì€í
đ€ Transformers ëȘšëžì ìì±í ì ìì”ëë€. ìŽë đ€ Transformers ëȘšëžì ì°ê”Ź, ê”ìĄ ëë ì€ííë ë° êŽìŹìŽ ìë ëȘšë ìŹì©ììêČ íčí ì ì©í ì ìì”ëë€. ìŽ ê°ìŽëììë 'AutoClass'넌 ìŹì©íì§ ìêł ì»€ì€í
ëȘšëžì ë§ëë ë°©ëČì ëíŽ ìì볎êČ ì”ëë€:
+
+- ëȘšëž configurationì ê°ì žì€êł ìŹì©ì ì§ì í©ëë€.
+- ëȘšëž ìí€í
ìČ넌 ìì±í©ëë€.
+- í
ì€ížì ìŹì©í ëëŠŹê±°ë ëč 넞 í í°íꞰ넌 ë§ëëë€.
+- ëčì ìì
ì ìí ìŽëŻžì§ íëĄìžì넌 ìì±í©ëë€.
+- ì€ëì€ ìì
ì ìí íčì± ì¶ì¶êž°ë„Œ ìì±í©ëë€.
+- ë©í°ëȘšëŹ ìì
ì© íëĄìžì넌 ìì±í©ëë€.
+
+## Configuration[[configuration]]
+
+[configuration](main_classes/configuration)ì ëȘšëžì íčì ìì±ì ëíë
ëë€. ê° ëȘšëž ê”Źì±ìë ìëĄ ë€ë„ž ìì±ìŽ ìì”ëë€. ì넌 ë€ìŽ, ëȘšë NLP ëȘšëžìë `hidden_size`, `num_attention_heads`, `num_hidden_layers` ë° `vocab_size` ìì±ìŽ êł”í”ìŒëĄ ìì”ëë€. ìŽëŹí ìì±ì ëȘšëžì ê”Źì±í attention heads ëë hidden layersì ì넌 ì§ì í©ëë€.
+
+[DistilBERT](model_doc/distilbert) ìì±ì êČìŹíêž° ìíŽ [`DistilBertConfig`]ì ì ê·ŒíìŹ ììží ìŽíŽëŽ
ëë€:
+
+```py
+>>> from transformers import DistilBertConfig
+
+>>> config = DistilBertConfig()
+>>> print(config)
+DistilBertConfig {
+ "activation": "gelu",
+ "attention_dropout": 0.1,
+ "dim": 768,
+ "dropout": 0.1,
+ "hidden_dim": 3072,
+ "initializer_range": 0.02,
+ "max_position_embeddings": 512,
+ "model_type": "distilbert",
+ "n_heads": 12,
+ "n_layers": 6,
+ "pad_token_id": 0,
+ "qa_dropout": 0.1,
+ "seq_classif_dropout": 0.2,
+ "sinusoidal_pos_embds": false,
+ "transformers_version": "4.16.2",
+ "vocab_size": 30522
+}
+```
+
+[`DistilBertConfig`]ë êž°ëłž [`DistilBertModel`]ì ëčëíë ë° ìŹì©ëë ëȘšë êž°ëłž ìì±ì íìí©ëë€. ëȘšë ìì±ì 컀ì€í°ë§ìŽì§ìŽ ê°ë„íëŻëĄ ì€íì ìí êł”ê°ì ë§ë€ ì ìì”ëë€. ì넌 ë€ìŽ êž°ëłž ëȘšëžì ë€ìêłŒ ê°ìŽ ì»€ì€í°ë§ìŽìŠí ì ìì”ëë€:
+
+- `activation` íëŒëŻží°ëĄ ë€ë„ž íì±í íšì넌 ìŹì©íŽ ëłŽìžì.
+- `attention_dropout` íëŒëŻží°ë„Œ ìŹì©íìŹ ìŽí
ì
íë„ ì ë ëì ëëĄìì ëčìšì ìŹì©íìžì.
+
+```py
+>>> my_config = DistilBertConfig(activation="relu", attention_dropout=0.4)
+>>> print(my_config)
+DistilBertConfig {
+ "activation": "relu",
+ "attention_dropout": 0.4,
+ "dim": 768,
+ "dropout": 0.1,
+ "hidden_dim": 3072,
+ "initializer_range": 0.02,
+ "max_position_embeddings": 512,
+ "model_type": "distilbert",
+ "n_heads": 12,
+ "n_layers": 6,
+ "pad_token_id": 0,
+ "qa_dropout": 0.1,
+ "seq_classif_dropout": 0.2,
+ "sinusoidal_pos_embds": false,
+ "transformers_version": "4.16.2",
+ "vocab_size": 30522
+}
+```
+
+ìŹì íì”ë ëȘšëž ìì±ì [`~PretrainedConfig.from_pretrained`] íšììì ìì í ì ìì”ëë€:
+
+```py
+>>> my_config = DistilBertConfig.from_pretrained("distilbert-base-uncased", activation="relu", attention_dropout=0.4)
+```
+
+ëȘšëž ê”Źì±ìŽ ë§ìĄ±ì€ëŹì°ë©Ž [`~PretrainedConfig.save_pretrained`]ëĄ ì ì„í ì ìì”ëë€. ì€ì íìŒì ì§ì ë ìì
êČœëĄì JSON íìŒëĄ ì ì„ë©ëë€:
+
+```py
+>>> my_config.save_pretrained(save_directory="./your_model_save_path")
+```
+
+configuration íìŒì ìŹìŹì©íë €ë©Ž [`~PretrainedConfig.from_pretrained`]넌 ìŹì©íìŹ ê°ì žì€ìžì:
+
+```py
+>>> my_config = DistilBertConfig.from_pretrained("./your_model_save_path/config.json")
+```
+
+
+
+configuration íìŒì ëì
ëëŠŹëĄ ì ì„íê±°ë ìŹì©ì ì ì configuration ìì±êłŒ êž°ëłž configuration ìì±ì ì°šìŽì ë§ ì ì„í ìë ìì”ëë€! ììží ëŽì©ì [configuration](main_classes/configuration) 돞ì넌 ì°žìĄ°íìžì.
+
+
+
+## ëȘšëž[[model]]
+
+ë€ì ëšêłë [ëȘšëž(model)](main_classes/models)ì ë§ëë êČì
ëë€. ëìšíêČ ìí€í
ìČëŒêł ë ë¶ëŠŹë ëȘšëžì ê° êłìž”ìŽ ìííë ëìêłŒ ë°ìíë ìì
ì ì ìí©ëë€. configurationì `num_hidden_layers`ì ê°ì ìì±ì ìí€í
ìČ넌 ì ìíë ë° ìŹì©ë©ëë€. ëȘšë ëȘšëžì êž°ëłž íŽëì€ [`PreTrainedModel`]êłŒ ì
ë „ ìëČ ë© íŹêž° ìĄ°ì ë° ì
í ìŽí
ì
í€ë ê°ì§ ìčêž°ì ê°ì ëȘ ê°ì§ ìŒë°ì ìž ë©ìë넌 êł”ì í©ëë€. ëí ëȘšë ëȘšëžì [`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) ëë [`flax.linen.Module`](https://flax.readthedocs.io/en/latest/flax.linen.html#module)ì ìëžíŽëì€ìŽêž°ë í©ëë€. ìŠ, ëȘšëžì ê° íë ììíŹì ìŹì©ëČêłŒ ížíë©ëë€.
+
+
+
+ìŹì©ì ì§ì configuration ìì±ì ëȘšëžì ê°ì žì”ëë€:
+
+```py
+>>> from transformers import DistilBertModel
+
+>>> my_config = DistilBertConfig.from_pretrained("./your_model_save_path/config.json")
+>>> model = DistilBertModel(my_config)
+```
+
+ìŽì ìŹì íì”ë ê°ì€ìč ëì ììì ê°ì ê°ì§ ëȘšëžìŽ ìì±ë©ëë€. ìŽ ëȘšëžì íë šíêž° ì êčì§ë ì ì©íêČ ìŹì©í ì ìì”ëë€. íë šì ëčì©êłŒ ìê°ìŽ ë§ìŽ ììëë íëĄìžì€ì
ëë€. ìŒë°ì ìŒëĄ íë šì íìí 늏ìì€ì ìŒë¶ë§ ìŹì©í멎ì ë ëì êČ°êłŒë„Œ ë ëčšëŠŹ ì»ìŒë €ë©Ž ìŹì íë šë ëȘšëžì ìŹì©íë êČìŽ ìąì”ëë€.
+
+ìŹì íì”ë ëȘšëžì [`~PreTrainedModel.from_pretrained`]ëĄ ìì±í©ëë€:
+
+```py
+>>> model = DistilBertModel.from_pretrained("distilbert-base-uncased")
+```
+
+đ€ Transformersìì ì êł”í ëȘšëžì ìŹì íì”ë ê°ì€ìč넌 ìŹì©íë êČœì° êž°ëłž ëȘšëž configurationì ìëìŒëĄ ë¶ëŹì”ëë€. ê·žëŹë ìíë êČœì° êž°ëłž ëȘšëž configuration ìì±ì ìŒë¶ ëë ì ë¶ë„Œ ìŹì©ì ì§ì ìŒëĄ ë°êż ì ìì”ëë€:
+
+```py
+>>> model = DistilBertModel.from_pretrained("distilbert-base-uncased", config=my_config)
+```
+
+
+ìŹì©ì ì§ì configuration ìì±ì ëȘšëžì ë¶ëŹì”ëë€:
+
+```py
+>>> from transformers import TFDistilBertModel
+
+>>> my_config = DistilBertConfig.from_pretrained("./your_model_save_path/my_config.json")
+>>> tf_model = TFDistilBertModel(my_config)
+```
+
+ìŽì ìŹì íì”ë ê°ì€ìč ëì ììì ê°ì ê°ì§ ëȘšëžìŽ ìì±ë©ëë€. ìŽ ëȘšëžì íë šíêž° ì êčì§ë ì ì©íêČ ìŹì©í ì ìì”ëë€. íë šì ëčì©êłŒ ìê°ìŽ ë§ìŽ ììëë íëĄìžì€ì
ëë€. ìŒë°ì ìŒëĄ íë šì íìí 늏ìì€ì ìŒë¶ë§ ìŹì©í멎ì ë ëì êČ°êłŒë„Œ ë ëčšëŠŹ ì»ìŒë €ë©Ž ìŹì íë šë ëȘšëžì ìŹì©íë êČìŽ ìąì”ëë€.
+
+ìŹì íì”ë ëȘšëžì [`~TFPreTrainedModel.from_pretrained`]ëĄ ìì±í©ëë€:
+
+```py
+>>> tf_model = TFDistilBertModel.from_pretrained("distilbert-base-uncased")
+```
+
+đ€ Transformersìì ì êł”í ëȘšëžì ìŹì íì”ë ê°ì€ìč넌 ìŹì©íë êČœì° êž°ëłž ëȘšëž configurationì ìëìŒëĄ ë¶ëŹì”ëë€. ê·žëŹë ìíë êČœì° êž°ëłž ëȘšëž configuration ìì±ì ìŒë¶ ëë ì ë¶ë„Œ ìŹì©ì ì§ì ìŒëĄ ë°êż ì ìì”ëë€:
+
+```py
+>>> tf_model = TFDistilBertModel.from_pretrained("distilbert-base-uncased", config=my_config)
+```
+
+
+
+### ëȘšëž í€ë[[model-heads]]
+
+ìŽ ìì ìì *ìë ìí(hidden state)*넌 ì¶ë „íë êž°ëłž DistilBERT ëȘšëžì ê°êČ ë©ëë€. ìë ìíë ì”ìą
ì¶ë „ì ìì±íêž° ìíŽ ëȘšëž í€ëì ì
ë „ìŒëĄ ì ëŹë©ëë€. đ€ Transformersë ëȘšëžìŽ íŽëč ìì
ì ì§ìíë í ê° ìì
ë§ë€ ë€ë„ž ëȘšëž í€ë넌 ì êł”í©ëë€(ìŠ, ëČìêłŒ ê°ì ìíì€ ê° ìì
ìë DistilBERT넌 ìŹì©í ì ìì).
+
+
+
+ì넌 ë€ìŽ, [`DistilBertForSequenceClassification`]ì ìíì€ ë¶ë„ í€ëê° ìë êž°ëłž DistilBERT ëȘšëžì
ëë€. ìíì€ ë¶ë„ í€ëë íë§ë ì¶ë „ ìì ìë ì í ë ìŽìŽì
ëë€.
+
+```py
+>>> from transformers import DistilBertForSequenceClassification
+
+>>> model = DistilBertForSequenceClassification.from_pretrained("distilbert-base-uncased")
+```
+
+ë€ë„ž ëȘšëž í€ëëĄ ì ííìŹ ìŽ ìČŽíŹíŹìžížë„Œ ë€ë„ž ìì
ì ìœêČ ìŹìŹì©í ì ìì”ëë€. ì§ììë” ìì
ì êČœì°, [`DistilBertForQuestionAnswering`] ëȘšëž í€ë넌 ìŹì©í ì ìì”ëë€. ì§ììë” í€ëë ìšêČšì§ ìí ì¶ë „ ìì ì í ë ìŽìŽê° ìë€ë ì ì ì ìží멎 ìíì€ ë¶ë„ í€ëì ì ìŹí©ëë€.
+
+```py
+>>> from transformers import DistilBertForQuestionAnswering
+
+>>> model = DistilBertForQuestionAnswering.from_pretrained("distilbert-base-uncased")
+```
+
+
+ì넌 ë€ìŽ, [`TFDistilBertForSequenceClassification`]ì ìíì€ ë¶ë„ í€ëê° ìë êž°ëłž DistilBERT ëȘšëžì
ëë€. ìíì€ ë¶ë„ í€ëë íë§ë ì¶ë „ ìì ìë ì í ë ìŽìŽì
ëë€.
+
+```py
+>>> from transformers import TFDistilBertForSequenceClassification
+
+>>> tf_model = TFDistilBertForSequenceClassification.from_pretrained("distilbert-base-uncased")
+```
+
+ë€ë„ž ëȘšëž í€ëëĄ ì ííìŹ ìŽ ìČŽíŹíŹìžížë„Œ ë€ë„ž ìì
ì ìœêČ ìŹìŹì©í ì ìì”ëë€. ì§ììë” ìì
ì êČœì°, [`TFDistilBertForQuestionAnswering`] ëȘšëž í€ë넌 ìŹì©í ì ìì”ëë€. ì§ììë” í€ëë ìšêČšì§ ìí ì¶ë „ ìì ì í ë ìŽìŽê° ìë€ë ì ì ì ìží멎 ìíì€ ë¶ë„ í€ëì ì ìŹí©ëë€.
+
+```py
+>>> from transformers import TFDistilBertForQuestionAnswering
+
+>>> tf_model = TFDistilBertForQuestionAnswering.from_pretrained("distilbert-base-uncased")
+```
+
+
+
+## í íŹëìŽì [[tokenizer]]
+
+í
ì€íž ë°ìŽí°ì ëȘšëžì ìŹì©íêž° ì ì ë§ì§ë§ìŒëĄ íìí êž°ëłž íŽëì€ë ìì í
ì€ížë„Œ í
ìëĄ ëłííë [í íŹëìŽì ](main_classes/tokenizer)ì
ëë€. đ€ Transformersì ìŹì©í ì ìë í íŹëìŽì ë ë ê°ì§ ì íìŽ ìì”ëë€:
+
+- [`PreTrainedTokenizer`]: íìŽìŹìŒëĄ ê”Źíë í íŹëìŽì ì
ëë€.
+- [`PreTrainedTokenizerFast`]: Rust êž°ë° [đ€ Tokenizer](https://huggingface.co/docs/tokenizers/python/latest/) ëŒìŽëžëŹëŠŹëĄ ë§ë€ìŽì§ í íŹëìŽì ì
ëë€. ìŽ í íŹëìŽì ë RustëĄ ê”ŹíëìŽ ë°°ìč í í°íìì íčí ëč ëŠ
ëë€. ëč 넞 í íŹëìŽì ë í í°ì ìë ëšìŽë 돞ìì ë§€ííë *ì€íì
ë§€í*êłŒ ê°ì ì¶ê° ë©ìëë ì êł”í©ëë€.
+ë í íŹëìŽì ëȘšë ìžìœë© ë° ëìœë©, ì í í° ì¶ê°, íčì í í° êŽëŠŹì ê°ì ìŒë°ì ìž ë°©ëČì ì§ìí©ëë€.
+
+
+
+ëȘšë ëȘšëžìŽ ëč 넞 í íŹëìŽì 넌 ì§ìíë êČì ìëëë€. ìŽ [í](index#supported-frameworks)ìì ëȘšëžì ëč 넞 í íŹëìŽì ì§ì ìŹë¶ë„Œ íìžíìžì.
+
+
+
+í íŹëìŽì 넌 ì§ì íì”í êČœì°, *ìŽí(vocabulary)* íìŒìì í íŹëìŽì 넌 ë§ë€ ì ìì”ëë€:
+
+```py
+>>> from transformers import DistilBertTokenizer
+
+>>> my_tokenizer = DistilBertTokenizer(vocab_file="my_vocab_file.txt", do_lower_case=False, padding_side="left")
+```
+
+ìŹì©ì ì§ì í íŹëìŽì ì ìŽíë ìŹì íì”ë ëȘšëžì í íŹëìŽì ìì ìì±ë ìŽíì ë€ë„Œ ì ìë€ë ì ì êž°ì”íë êČìŽ ì€ìí©ëë€. ìŹì íì”ë ëȘšëžì ìŹì©íë êČœì° ìŹì íì”ë ëȘšëžì ìŽí넌 ìŹì©íŽìŒ íë©°, ê·žë ì§ ììŒë©Ž ì
ë „ìŽ ìëŻžë„Œ ê°ì§ ëȘ»í©ëë€. [`DistilBertTokenizer`] íŽëì€ë„Œ ìŹì©íìŹ ìŹì íì”ë ëȘšëžì ìŽíëĄ í íŹëìŽì 넌 ìì±í©ëë€:
+
+```py
+>>> from transformers import DistilBertTokenizer
+
+>>> slow_tokenizer = DistilBertTokenizer.from_pretrained("distilbert-base-uncased")
+```
+
+[`DistilBertTokenizerFast`] íŽëì€ëĄ ëč 넞 í íŹëìŽì 넌 ìì±í©ëë€:
+
+```py
+>>> from transformers import DistilBertTokenizerFast
+
+>>> fast_tokenizer = DistilBertTokenizerFast.from_pretrained("distilbert-base-uncased")
+```
+
+
+
+[`AutoTokenizer`]ë êž°ëłžì ìŒëĄ ëč 넞 í íŹëìŽì 넌 ê°ì žì€ë €êł í©ëë€. ìŽ ëìì ëčíì±ííë €ë©Ž `from_pretrained`ìì `use_fast=False`넌 ì€ì í멎 ë©ëë€.
+
+
+
+## ìŽëŻžì§ íëĄìžì[[image-processor]]
+
+ìŽëŻžì§ íëĄìžì(image processor)ë ëčì ì
ë „ì ìČ늏í©ëë€. êž°ëłž [`~image_processing_utils.ImageProcessingMixin`] íŽëì€ìì ììí©ëë€.
+
+ìŹì©íë €ë©Ž ìŹì© ì€ìž ëȘšëžêłŒ ì°êȰë ìŽëŻžì§ íëĄìžì넌 ìì±í©ëë€. ì넌 ë€ìŽ, ìŽëŻžì§ ë¶ë„ì [ViT](model_doc/vit)넌 ìŹì©íë êČœì° êž°ëłž [`ViTImageProcessor`]넌 ìì±í©ëë€:
+
+```py
+>>> from transformers import ViTImageProcessor
+
+>>> vit_extractor = ViTImageProcessor()
+>>> print(vit_extractor)
+ViTImageProcessor {
+ "do_normalize": true,
+ "do_resize": true,
+ "feature_extractor_type": "ViTImageProcessor",
+ "image_mean": [
+ 0.5,
+ 0.5,
+ 0.5
+ ],
+ "image_std": [
+ 0.5,
+ 0.5,
+ 0.5
+ ],
+ "resample": 2,
+ "size": 224
+}
+```
+
+
+
+ìŹì©ì ì§ì ì ìíì§ ìë êČœì° `from_pretrained` ë©ìë넌 ìŹì©íìŹ ëȘšëžì êž°ëłž ìŽëŻžì§ íëĄìžì ë§€ê°ëłì넌 ë¶ëŹì€ë©Ž ë©ëë€.
+
+
+
+ìŹì©ì ì§ì ìŽëŻžì§ íëĄìžì넌 ìì±íë €ë©Ž [`ViTImageProcessor`] íëŒëŻží°ë„Œ ìì í©ëë€:
+
+```py
+>>> from transformers import ViTImageProcessor
+
+>>> my_vit_extractor = ViTImageProcessor(resample="PIL.Image.BOX", do_normalize=False, image_mean=[0.3, 0.3, 0.3])
+>>> print(my_vit_extractor)
+ViTImageProcessor {
+ "do_normalize": false,
+ "do_resize": true,
+ "feature_extractor_type": "ViTImageProcessor",
+ "image_mean": [
+ 0.3,
+ 0.3,
+ 0.3
+ ],
+ "image_std": [
+ 0.5,
+ 0.5,
+ 0.5
+ ],
+ "resample": "PIL.Image.BOX",
+ "size": 224
+}
+```
+
+## íčì± ì¶ì¶êž°[[feature-extractor]]
+
+íčì± ì¶ì¶êž°(feature extractor)ë ì€ëì€ ì
ë „ì ìČ늏í©ëë€. êž°ëłž [`~feature_extraction_utils.FeatureExtractionMixin`] íŽëì€ìì ììëë©°, ì€ëì€ ì
ë „ì ìČ늏íêž° ìíŽ [`SequenceFeatureExtractor`] íŽëì€ìì ììí ìë ìì”ëë€.
+
+ìŹì©íë €ë©Ž ìŹì© ì€ìž ëȘšëžêłŒ ì°êȰë íčì± ì¶ì¶êž°ë„Œ ìì±í©ëë€. ì넌 ë€ìŽ, ì€ëì€ ë¶ë„ì [Wav2Vec2](model_doc/wav2vec2)넌 ìŹì©íë êČœì° êž°ëłž [`Wav2Vec2FeatureExtractor`]넌 ìì±í©ëë€:
+
+```py
+>>> from transformers import Wav2Vec2FeatureExtractor
+
+>>> w2v2_extractor = Wav2Vec2FeatureExtractor()
+>>> print(w2v2_extractor)
+Wav2Vec2FeatureExtractor {
+ "do_normalize": true,
+ "feature_extractor_type": "Wav2Vec2FeatureExtractor",
+ "feature_size": 1,
+ "padding_side": "right",
+ "padding_value": 0.0,
+ "return_attention_mask": false,
+ "sampling_rate": 16000
+}
+```
+
+
+
+ìŹì©ì ì§ì ìŽ íìíì§ ìì êČœì° `from_pretrained` ë©ìë넌 ìŹì©íìŹ ëȘšëžì êž°ëłž íčì± ì¶ì¶êž° ă
ê°ëłì넌 ë¶ëŹ ì€ë©Ž ë©ëë€.
+
+
+
+ìŹì©ì ì§ì íčì± ì¶ì¶êž°ë„Œ ë§ë€ë €ë©Ž [`Wav2Vec2FeatureExtractor`] ë§€ê°ëłì넌 ìì í©ëë€:
+
+```py
+>>> from transformers import Wav2Vec2FeatureExtractor
+
+>>> w2v2_extractor = Wav2Vec2FeatureExtractor(sampling_rate=8000, do_normalize=False)
+>>> print(w2v2_extractor)
+Wav2Vec2FeatureExtractor {
+ "do_normalize": false,
+ "feature_extractor_type": "Wav2Vec2FeatureExtractor",
+ "feature_size": 1,
+ "padding_side": "right",
+ "padding_value": 0.0,
+ "return_attention_mask": false,
+ "sampling_rate": 8000
+}
+```
+
+
+## íëĄìžì[[processor]]
+
+ë©í°ëȘšëŹ ìì
ì ì§ìíë ëȘšëžì êČœì°, đ€ Transformersë íčì± ì¶ì¶êž° ë° í íŹëìŽì ì ê°ì ìČ늏 íŽëì€ë„Œ ëšìŒ ê°ìČŽëĄ ížëŠŹíêČ ëííë íëĄìžì íŽëì€ë„Œ ì êł”í©ëë€. ì넌 ë€ìŽ, ìë ìì± ìžì ìì
(Automatic Speech Recognition task (ASR))ì [`Wav2Vec2Processor`]넌 ìŹì©íë€êł ê°ì íŽ ëłŽêČ ì”ëë€. ìë ìì± ìžì ìì
ì ì€ëì€ë„Œ í
ì€ížëĄ ëłííëŻëĄ íčì± ì¶ì¶êž°ì í íŹëìŽì ê° íìí©ëë€.
+
+ì€ëì€ ì
ë „ì ìČ늏í íčì± ì¶ì¶êž°ë„Œ ë§ëëë€:
+
+```py
+>>> from transformers import Wav2Vec2FeatureExtractor
+
+>>> feature_extractor = Wav2Vec2FeatureExtractor(padding_value=1.0, do_normalize=True)
+```
+
+í
ì€íž ì
ë „ì ìČ늏í í íŹëìŽì 넌 ë§ëëë€:
+
+```py
+>>> from transformers import Wav2Vec2CTCTokenizer
+
+>>> tokenizer = Wav2Vec2CTCTokenizer(vocab_file="my_vocab_file.txt")
+```
+
+[`Wav2Vec2Processor`]ìì íčì± ì¶ì¶êž°ì í íŹëìŽì 넌 êȰí©í©ëë€:
+
+```py
+>>> from transformers import Wav2Vec2Processor
+
+>>> processor = Wav2Vec2Processor(feature_extractor=feature_extractor, tokenizer=tokenizer)
+```
+
+configurationêłŒ ëȘšëžìŽëŒë ë ê°ì§ êž°ëłž íŽëì€ì ì¶ê° ì ìČ늏 íŽëì€(í íŹëìŽì , ìŽëŻžì§ íëĄìžì, íčì± ì¶ì¶êž° ëë íëĄìžì)넌 ìŹì©í멎 đ€ Transformersìì ì§ìíë ëȘšë ëȘšëžì ë§ë€ ì ìì”ëë€. ìŽëŹí ê° êž°ëłž íŽëì€ë ê”Źì±ìŽ ê°ë„íëŻëĄ ìíë íčì ìì±ì ìŹì©í ì ìì”ëë€. íì”ì ìíŽ ëȘšëžì ìœêČ ì€ì íê±°ë êž°ìĄŽì ìŹì íì”ë ëȘšëžì ìì íìŹ ëŻžìž ìĄ°ì í ì ìì”ëë€.
diff --git a/docs/source/ko/create_a_model.mdx b/docs/source/ko/create_a_model.mdx
deleted file mode 100644
index 15b14583c83c..000000000000
--- a/docs/source/ko/create_a_model.mdx
+++ /dev/null
@@ -1,384 +0,0 @@
-
-
-# ë§ì¶€í ìí€í
ìČ ë§ë€êž°[[create-a-custom-architecture]]
-
-[`AutoClass`](model_doc/auto)ë ëȘšëž ìí€í
ìČ넌 ìëìŒëĄ ì¶ëĄ íêł ëŻžëŠŹ íì”ë configurationêłŒ ê°ì€ìč넌 ë€ìŽëĄëí©ëë€. ìŒë°ì ìŒëĄ ìČŽíŹíŹìžížì ê”Źì ë°ì§ ìë ìœë넌 ìì±íë €ë©Ž `AutoClass`넌 ìŹì©íë êČìŽ ìąì”ëë€. íì§ë§ íčì ëȘšëž íëŒëŻží°ë„Œ ëłŽë€ ìžë°íêČ ì ìŽíêł ì íë ìŹì©ìë ëȘ ê°ì§ êž°ëłž íŽëì€ë§ìŒëĄ 컀ì€í
đ€ Transformers ëȘšëžì ìì±í ì ìì”ëë€. ìŽë đ€ Transformers ëȘšëžì ì°ê”Ź, ê”ìĄ ëë ì€ííë ë° êŽìŹìŽ ìë ëȘšë ìŹì©ììêČ íčí ì ì©í ì ìì”ëë€. ìŽ ê°ìŽëììë 'AutoClass'넌 ìŹì©íì§ ìêł ì»€ì€í
ëȘšëžì ë§ëë ë°©ëČì ëíŽ ìì볎êČ ì”ëë€:
-
-- ëȘšëž configurationì ê°ì žì€êł ìŹì©ì ì§ì í©ëë€.
-- ëȘšëž ìí€í
ìČ넌 ìì±í©ëë€.
-- í
ì€ížì ìŹì©í ëëŠŹê±°ë ëč 넞 í í°íꞰ넌 ë§ëëë€.
-- ëčì ìì
ì ìí ìŽëŻžì§ íëĄìžì넌 ìì±í©ëë€.
-- ì€ëì€ ìì
ì ìí íčì± ì¶ì¶êž°ë„Œ ìì±í©ëë€.
-- ë©í°ëȘšëŹ ìì
ì© íëĄìžì넌 ìì±í©ëë€.
-
-## Configuration[[configuration]]
-
-[configuration](main_classes/configuration)ì ëȘšëžì íčì ìì±ì ëíë
ëë€. ê° ëȘšëž ê”Źì±ìë ìëĄ ë€ë„ž ìì±ìŽ ìì”ëë€. ì넌 ë€ìŽ, ëȘšë NLP ëȘšëžìë `hidden_size`, `num_attention_heads`, `num_hidden_layers` ë° `vocab_size` ìì±ìŽ êł”í”ìŒëĄ ìì”ëë€. ìŽëŹí ìì±ì ëȘšëžì ê”Źì±í attention heads ëë hidden layersì ì넌 ì§ì í©ëë€.
-
-[DistilBERT](model_doc/distilbert) ìì±ì êČìŹíêž° ìíŽ [`DistilBertConfig`]ì ì ê·ŒíìŹ ììží ìŽíŽëŽ
ëë€:
-
-```py
->>> from transformers import DistilBertConfig
-
->>> config = DistilBertConfig()
->>> print(config)
-DistilBertConfig {
- "activation": "gelu",
- "attention_dropout": 0.1,
- "dim": 768,
- "dropout": 0.1,
- "hidden_dim": 3072,
- "initializer_range": 0.02,
- "max_position_embeddings": 512,
- "model_type": "distilbert",
- "n_heads": 12,
- "n_layers": 6,
- "pad_token_id": 0,
- "qa_dropout": 0.1,
- "seq_classif_dropout": 0.2,
- "sinusoidal_pos_embds": false,
- "transformers_version": "4.16.2",
- "vocab_size": 30522
-}
-```
-
-[`DistilBertConfig`]ë êž°ëłž [`DistilBertModel`]ì ëčëíë ë° ìŹì©ëë ëȘšë êž°ëłž ìì±ì íìí©ëë€. ëȘšë ìì±ì 컀ì€í°ë§ìŽì§ìŽ ê°ë„íëŻëĄ ì€íì ìí êł”ê°ì ë§ë€ ì ìì”ëë€. ì넌 ë€ìŽ êž°ëłž ëȘšëžì ë€ìêłŒ ê°ìŽ ì»€ì€í°ë§ìŽìŠí ì ìì”ëë€:
-
-- `activation` íëŒëŻží°ëĄ ë€ë„ž íì±í íšì넌 ìŹì©íŽ ëłŽìžì.
-- `attention_dropout` íëŒëŻží°ë„Œ ìŹì©íìŹ ìŽí
ì
íë„ ì ë ëì ëëĄìì ëčìšì ìŹì©íìžì.
-
-```py
->>> my_config = DistilBertConfig(activation="relu", attention_dropout=0.4)
->>> print(my_config)
-DistilBertConfig {
- "activation": "relu",
- "attention_dropout": 0.4,
- "dim": 768,
- "dropout": 0.1,
- "hidden_dim": 3072,
- "initializer_range": 0.02,
- "max_position_embeddings": 512,
- "model_type": "distilbert",
- "n_heads": 12,
- "n_layers": 6,
- "pad_token_id": 0,
- "qa_dropout": 0.1,
- "seq_classif_dropout": 0.2,
- "sinusoidal_pos_embds": false,
- "transformers_version": "4.16.2",
- "vocab_size": 30522
-}
-```
-
-ìŹì íì”ë ëȘšëž ìì±ì [`~PretrainedConfig.from_pretrained`] íšììì ìì í ì ìì”ëë€:
-
-```py
->>> my_config = DistilBertConfig.from_pretrained("distilbert-base-uncased", activation="relu", attention_dropout=0.4)
-```
-
-ëȘšëž ê”Źì±ìŽ ë§ìĄ±ì€ëŹì°ë©Ž [`~PretrainedConfig.save_pretrained`]ëĄ ì ì„í ì ìì”ëë€. ì€ì íìŒì ì§ì ë ìì
êČœëĄì JSON íìŒëĄ ì ì„ë©ëë€:
-
-```py
->>> my_config.save_pretrained(save_directory="./your_model_save_path")
-```
-
-configuration íìŒì ìŹìŹì©íë €ë©Ž [`~PretrainedConfig.from_pretrained`]넌 ìŹì©íìŹ ê°ì žì€ìžì:
-
-```py
->>> my_config = DistilBertConfig.from_pretrained("./your_model_save_path/config.json")
-```
-
-
-
-configuration íìŒì ëì
ëëŠŹëĄ ì ì„íê±°ë ìŹì©ì ì ì configuration ìì±êłŒ êž°ëłž configuration ìì±ì ì°šìŽì ë§ ì ì„í ìë ìì”ëë€! ììží ëŽì©ì [configuration](main_classes/configuration) 돞ì넌 ì°žìĄ°íìžì.
-
-
-
-## ëȘšëž[[model]]
-
-ë€ì ëšêłë [ëȘšëž(model)](main_classes/models)ì ë§ëë êČì
ëë€. ëìšíêČ ìí€í
ìČëŒêł ë ë¶ëŠŹë ëȘšëžì ê° êłìž”ìŽ ìííë ëìêłŒ ë°ìíë ìì
ì ì ìí©ëë€. configurationì `num_hidden_layers`ì ê°ì ìì±ì ìí€í
ìČ넌 ì ìíë ë° ìŹì©ë©ëë€. ëȘšë ëȘšëžì êž°ëłž íŽëì€ [`PreTrainedModel`]êłŒ ì
ë „ ìëČ ë© íŹêž° ìĄ°ì ë° ì
í ìŽí
ì
í€ë ê°ì§ ìčêž°ì ê°ì ëȘ ê°ì§ ìŒë°ì ìž ë©ìë넌 êł”ì í©ëë€. ëí ëȘšë ëȘšëžì [`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) ëë [`flax.linen.Module`](https://flax.readthedocs.io/en/latest/flax.linen.html#module)ì ìëžíŽëì€ìŽêž°ë í©ëë€. ìŠ, ëȘšëžì ê° íë ììíŹì ìŹì©ëČêłŒ ížíë©ëë€.
-
-
-
-ìŹì©ì ì§ì configuration ìì±ì ëȘšëžì ê°ì žì”ëë€:
-
-```py
->>> from transformers import DistilBertModel
-
->>> my_config = DistilBertConfig.from_pretrained("./your_model_save_path/config.json")
->>> model = DistilBertModel(my_config)
-```
-
-ìŽì ìŹì íì”ë ê°ì€ìč ëì ììì ê°ì ê°ì§ ëȘšëžìŽ ìì±ë©ëë€. ìŽ ëȘšëžì íë šíêž° ì êčì§ë ì ì©íêČ ìŹì©í ì ìì”ëë€. íë šì ëčì©êłŒ ìê°ìŽ ë§ìŽ ììëë íëĄìžì€ì
ëë€. ìŒë°ì ìŒëĄ íë šì íìí 늏ìì€ì ìŒë¶ë§ ìŹì©í멎ì ë ëì êČ°êłŒë„Œ ë ëčšëŠŹ ì»ìŒë €ë©Ž ìŹì íë šë ëȘšëžì ìŹì©íë êČìŽ ìąì”ëë€.
-
-ìŹì íì”ë ëȘšëžì [`~PreTrainedModel.from_pretrained`]ëĄ ìì±í©ëë€:
-
-```py
->>> model = DistilBertModel.from_pretrained("distilbert-base-uncased")
-```
-
-đ€ Transformersìì ì êł”í ëȘšëžì ìŹì íì”ë ê°ì€ìč넌 ìŹì©íë êČœì° êž°ëłž ëȘšëž configurationì ìëìŒëĄ ë¶ëŹì”ëë€. ê·žëŹë ìíë êČœì° êž°ëłž ëȘšëž configuration ìì±ì ìŒë¶ ëë ì ë¶ë„Œ ìŹì©ì ì§ì ìŒëĄ ë°êż ì ìì”ëë€:
-
-```py
->>> model = DistilBertModel.from_pretrained("distilbert-base-uncased", config=my_config)
-```
-
-
-ìŹì©ì ì§ì configuration ìì±ì ëȘšëžì ë¶ëŹì”ëë€:
-
-```py
->>> from transformers import TFDistilBertModel
-
->>> my_config = DistilBertConfig.from_pretrained("./your_model_save_path/my_config.json")
->>> tf_model = TFDistilBertModel(my_config)
-```
-
-ìŽì ìŹì íì”ë ê°ì€ìč ëì ììì ê°ì ê°ì§ ëȘšëžìŽ ìì±ë©ëë€. ìŽ ëȘšëžì íë šíêž° ì êčì§ë ì ì©íêČ ìŹì©í ì ìì”ëë€. íë šì ëčì©êłŒ ìê°ìŽ ë§ìŽ ììëë íëĄìžì€ì
ëë€. ìŒë°ì ìŒëĄ íë šì íìí 늏ìì€ì ìŒë¶ë§ ìŹì©í멎ì ë ëì êČ°êłŒë„Œ ë ëčšëŠŹ ì»ìŒë €ë©Ž ìŹì íë šë ëȘšëžì ìŹì©íë êČìŽ ìąì”ëë€.
-
-ìŹì íì”ë ëȘšëžì [`~TFPreTrainedModel.from_pretrained`]ëĄ ìì±í©ëë€:
-
-```py
->>> tf_model = TFDistilBertModel.from_pretrained("distilbert-base-uncased")
-```
-
-đ€ Transformersìì ì êł”í ëȘšëžì ìŹì íì”ë ê°ì€ìč넌 ìŹì©íë êČœì° êž°ëłž ëȘšëž configurationì ìëìŒëĄ ë¶ëŹì”ëë€. ê·žëŹë ìíë êČœì° êž°ëłž ëȘšëž configuration ìì±ì ìŒë¶ ëë ì ë¶ë„Œ ìŹì©ì ì§ì ìŒëĄ ë°êż ì ìì”ëë€:
-
-```py
->>> tf_model = TFDistilBertModel.from_pretrained("distilbert-base-uncased", config=my_config)
-```
-
-
-
-### ëȘšëž í€ë[[model-heads]]
-
-ìŽ ìì ìì *ìë ìí(hidden state)*넌 ì¶ë „íë êž°ëłž DistilBERT ëȘšëžì ê°êČ ë©ëë€. ìë ìíë ì”ìą
ì¶ë „ì ìì±íêž° ìíŽ ëȘšëž í€ëì ì
ë „ìŒëĄ ì ëŹë©ëë€. đ€ Transformersë ëȘšëžìŽ íŽëč ìì
ì ì§ìíë í ê° ìì
ë§ë€ ë€ë„ž ëȘšëž í€ë넌 ì êł”í©ëë€(ìŠ, ëČìêłŒ ê°ì ìíì€ ê° ìì
ìë DistilBERT넌 ìŹì©í ì ìì).
-
-
-
-ì넌 ë€ìŽ, [`DistilBertForSequenceClassification`]ì ìíì€ ë¶ë„ í€ëê° ìë êž°ëłž DistilBERT ëȘšëžì
ëë€. ìíì€ ë¶ë„ í€ëë íë§ë ì¶ë „ ìì ìë ì í ë ìŽìŽì
ëë€.
-
-```py
->>> from transformers import DistilBertForSequenceClassification
-
->>> model = DistilBertForSequenceClassification.from_pretrained("distilbert-base-uncased")
-```
-
-ë€ë„ž ëȘšëž í€ëëĄ ì ííìŹ ìŽ ìČŽíŹíŹìžížë„Œ ë€ë„ž ìì
ì ìœêČ ìŹìŹì©í ì ìì”ëë€. ì§ììë” ìì
ì êČœì°, [`DistilBertForQuestionAnswering`] ëȘšëž í€ë넌 ìŹì©í ì ìì”ëë€. ì§ììë” í€ëë ìšêČšì§ ìí ì¶ë „ ìì ì í ë ìŽìŽê° ìë€ë ì ì ì ìží멎 ìíì€ ë¶ë„ í€ëì ì ìŹí©ëë€.
-
-```py
->>> from transformers import DistilBertForQuestionAnswering
-
->>> model = DistilBertForQuestionAnswering.from_pretrained("distilbert-base-uncased")
-```
-
-
-ì넌 ë€ìŽ, [`TFDistilBertForSequenceClassification`]ì ìíì€ ë¶ë„ í€ëê° ìë êž°ëłž DistilBERT ëȘšëžì
ëë€. ìíì€ ë¶ë„ í€ëë íë§ë ì¶ë „ ìì ìë ì í ë ìŽìŽì
ëë€.
-
-```py
->>> from transformers import TFDistilBertForSequenceClassification
-
->>> tf_model = TFDistilBertForSequenceClassification.from_pretrained("distilbert-base-uncased")
-```
-
-ë€ë„ž ëȘšëž í€ëëĄ ì ííìŹ ìŽ ìČŽíŹíŹìžížë„Œ ë€ë„ž ìì
ì ìœêČ ìŹìŹì©í ì ìì”ëë€. ì§ììë” ìì
ì êČœì°, [`TFDistilBertForQuestionAnswering`] ëȘšëž í€ë넌 ìŹì©í ì ìì”ëë€. ì§ììë” í€ëë ìšêČšì§ ìí ì¶ë „ ìì ì í ë ìŽìŽê° ìë€ë ì ì ì ìží멎 ìíì€ ë¶ë„ í€ëì ì ìŹí©ëë€.
-
-```py
->>> from transformers import TFDistilBertForQuestionAnswering
-
->>> tf_model = TFDistilBertForQuestionAnswering.from_pretrained("distilbert-base-uncased")
-```
-
-
-
-## í íŹëìŽì [[tokenizer]]
-
-í
ì€íž ë°ìŽí°ì ëȘšëžì ìŹì©íêž° ì ì ë§ì§ë§ìŒëĄ íìí êž°ëłž íŽëì€ë ìì í
ì€ížë„Œ í
ìëĄ ëłííë [í íŹëìŽì ](main_classes/tokenizer)ì
ëë€. đ€ Transformersì ìŹì©í ì ìë í íŹëìŽì ë ë ê°ì§ ì íìŽ ìì”ëë€:
-
-- [`PreTrainedTokenizer`]: íìŽìŹìŒëĄ ê”Źíë í íŹëìŽì ì
ëë€.
-- [`PreTrainedTokenizerFast`]: Rust êž°ë° [đ€ Tokenizer](https://huggingface.co/docs/tokenizers/python/latest/) ëŒìŽëžëŹëŠŹëĄ ë§ë€ìŽì§ í íŹëìŽì ì
ëë€. ìŽ í íŹëìŽì ë RustëĄ ê”ŹíëìŽ ë°°ìč í í°íìì íčí ëč ëŠ
ëë€. ëč 넞 í íŹëìŽì ë í í°ì ìë ëšìŽë 돞ìì ë§€ííë *ì€íì
ë§€í*êłŒ ê°ì ì¶ê° ë©ìëë ì êł”í©ëë€.
-ë í íŹëìŽì ëȘšë ìžìœë© ë° ëìœë©, ì í í° ì¶ê°, íčì í í° êŽëŠŹì ê°ì ìŒë°ì ìž ë°©ëČì ì§ìí©ëë€.
-
-
-
-ëȘšë ëȘšëžìŽ ëč 넞 í íŹëìŽì 넌 ì§ìíë êČì ìëëë€. ìŽ [í](index#supported-frameworks)ìì ëȘšëžì ëč 넞 í íŹëìŽì ì§ì ìŹë¶ë„Œ íìžíìžì.
-
-
-
-í íŹëìŽì 넌 ì§ì íì”í êČœì°, *ìŽí(vocabulary)* íìŒìì í íŹëìŽì 넌 ë§ë€ ì ìì”ëë€:
-
-```py
->>> from transformers import DistilBertTokenizer
-
->>> my_tokenizer = DistilBertTokenizer(vocab_file="my_vocab_file.txt", do_lower_case=False, padding_side="left")
-```
-
-ìŹì©ì ì§ì í íŹëìŽì ì ìŽíë ìŹì íì”ë ëȘšëžì í íŹëìŽì ìì ìì±ë ìŽíì ë€ë„Œ ì ìë€ë ì ì êž°ì”íë êČìŽ ì€ìí©ëë€. ìŹì íì”ë ëȘšëžì ìŹì©íë êČœì° ìŹì íì”ë ëȘšëžì ìŽí넌 ìŹì©íŽìŒ íë©°, ê·žë ì§ ììŒë©Ž ì
ë „ìŽ ìëŻžë„Œ ê°ì§ ëȘ»í©ëë€. [`DistilBertTokenizer`] íŽëì€ë„Œ ìŹì©íìŹ ìŹì íì”ë ëȘšëžì ìŽíëĄ í íŹëìŽì 넌 ìì±í©ëë€:
-
-```py
->>> from transformers import DistilBertTokenizer
-
->>> slow_tokenizer = DistilBertTokenizer.from_pretrained("distilbert-base-uncased")
-```
-
-[`DistilBertTokenizerFast`] íŽëì€ëĄ ëč 넞 í íŹëìŽì 넌 ìì±í©ëë€:
-
-```py
->>> from transformers import DistilBertTokenizerFast
-
->>> fast_tokenizer = DistilBertTokenizerFast.from_pretrained("distilbert-base-uncased")
-```
-
-
-
-[`AutoTokenizer`]ë êž°ëłžì ìŒëĄ ëč 넞 í íŹëìŽì 넌 ê°ì žì€ë €êł í©ëë€. ìŽ ëìì ëčíì±ííë €ë©Ž `from_pretrained`ìì `use_fast=False`넌 ì€ì í멎 ë©ëë€.
-
-
-
-## ìŽëŻžì§ íëĄìžì[[image-processor]]
-
-ìŽëŻžì§ íëĄìžì(image processor)ë ëčì ì
ë „ì ìČ늏í©ëë€. êž°ëłž [`~image_processing_utils.ImageProcessingMixin`] íŽëì€ìì ììí©ëë€.
-
-ìŹì©íë €ë©Ž ìŹì© ì€ìž ëȘšëžêłŒ ì°êȰë ìŽëŻžì§ íëĄìžì넌 ìì±í©ëë€. ì넌 ë€ìŽ, ìŽëŻžì§ ë¶ë„ì [ViT](model_doc/vit)넌 ìŹì©íë êČœì° êž°ëłž [`ViTImageProcessor`]넌 ìì±í©ëë€:
-
-```py
->>> from transformers import ViTImageProcessor
-
->>> vit_extractor = ViTImageProcessor()
->>> print(vit_extractor)
-ViTImageProcessor {
- "do_normalize": true,
- "do_resize": true,
- "feature_extractor_type": "ViTImageProcessor",
- "image_mean": [
- 0.5,
- 0.5,
- 0.5
- ],
- "image_std": [
- 0.5,
- 0.5,
- 0.5
- ],
- "resample": 2,
- "size": 224
-}
-```
-
-
-
-ìŹì©ì ì§ì ì ìíì§ ìë êČœì° `from_pretrained` ë©ìë넌 ìŹì©íìŹ ëȘšëžì êž°ëłž ìŽëŻžì§ íëĄìžì ë§€ê°ëłì넌 ë¶ëŹì€ë©Ž ë©ëë€.
-
-
-
-ìŹì©ì ì§ì ìŽëŻžì§ íëĄìžì넌 ìì±íë €ë©Ž [`ViTImageProcessor`] íëŒëŻží°ë„Œ ìì í©ëë€:
-
-```py
->>> from transformers import ViTImageProcessor
-
->>> my_vit_extractor = ViTImageProcessor(resample="PIL.Image.BOX", do_normalize=False, image_mean=[0.3, 0.3, 0.3])
->>> print(my_vit_extractor)
-ViTImageProcessor {
- "do_normalize": false,
- "do_resize": true,
- "feature_extractor_type": "ViTImageProcessor",
- "image_mean": [
- 0.3,
- 0.3,
- 0.3
- ],
- "image_std": [
- 0.5,
- 0.5,
- 0.5
- ],
- "resample": "PIL.Image.BOX",
- "size": 224
-}
-```
-
-## íčì± ì¶ì¶êž°[[feature-extractor]]
-
-íčì± ì¶ì¶êž°(feature extractor)ë ì€ëì€ ì
ë „ì ìČ늏í©ëë€. êž°ëłž [`~feature_extraction_utils.FeatureExtractionMixin`] íŽëì€ìì ììëë©°, ì€ëì€ ì
ë „ì ìČ늏íêž° ìíŽ [`SequenceFeatureExtractor`] íŽëì€ìì ììí ìë ìì”ëë€.
-
-ìŹì©íë €ë©Ž ìŹì© ì€ìž ëȘšëžêłŒ ì°êȰë íčì± ì¶ì¶êž°ë„Œ ìì±í©ëë€. ì넌 ë€ìŽ, ì€ëì€ ë¶ë„ì [Wav2Vec2](model_doc/wav2vec2)넌 ìŹì©íë êČœì° êž°ëłž [`Wav2Vec2FeatureExtractor`]넌 ìì±í©ëë€:
-
-```py
->>> from transformers import Wav2Vec2FeatureExtractor
-
->>> w2v2_extractor = Wav2Vec2FeatureExtractor()
->>> print(w2v2_extractor)
-Wav2Vec2FeatureExtractor {
- "do_normalize": true,
- "feature_extractor_type": "Wav2Vec2FeatureExtractor",
- "feature_size": 1,
- "padding_side": "right",
- "padding_value": 0.0,
- "return_attention_mask": false,
- "sampling_rate": 16000
-}
-```
-
-
-
-ìŹì©ì ì§ì ìŽ íìíì§ ìì êČœì° `from_pretrained` ë©ìë넌 ìŹì©íìŹ ëȘšëžì êž°ëłž íčì± ì¶ì¶êž° ă
ê°ëłì넌 ë¶ëŹ ì€ë©Ž ë©ëë€.
-
-
-
-ìŹì©ì ì§ì íčì± ì¶ì¶êž°ë„Œ ë§ë€ë €ë©Ž [`Wav2Vec2FeatureExtractor`] ë§€ê°ëłì넌 ìì í©ëë€:
-
-```py
->>> from transformers import Wav2Vec2FeatureExtractor
-
->>> w2v2_extractor = Wav2Vec2FeatureExtractor(sampling_rate=8000, do_normalize=False)
->>> print(w2v2_extractor)
-Wav2Vec2FeatureExtractor {
- "do_normalize": false,
- "feature_extractor_type": "Wav2Vec2FeatureExtractor",
- "feature_size": 1,
- "padding_side": "right",
- "padding_value": 0.0,
- "return_attention_mask": false,
- "sampling_rate": 8000
-}
-```
-
-
-## íëĄìžì[[processor]]
-
-ë©í°ëȘšëŹ ìì
ì ì§ìíë ëȘšëžì êČœì°, đ€ Transformersë íčì± ì¶ì¶êž° ë° í íŹëìŽì ì ê°ì ìČ늏 íŽëì€ë„Œ ëšìŒ ê°ìČŽëĄ ížëŠŹíêČ ëííë íëĄìžì íŽëì€ë„Œ ì êł”í©ëë€. ì넌 ë€ìŽ, ìë ìì± ìžì ìì
(Automatic Speech Recognition task (ASR))ì [`Wav2Vec2Processor`]넌 ìŹì©íë€êł ê°ì íŽ ëłŽêČ ì”ëë€. ìë ìì± ìžì ìì
ì ì€ëì€ë„Œ í
ì€ížëĄ ëłííëŻëĄ íčì± ì¶ì¶êž°ì í íŹëìŽì ê° íìí©ëë€.
-
-ì€ëì€ ì
ë „ì ìČ늏í íčì± ì¶ì¶êž°ë„Œ ë§ëëë€:
-
-```py
->>> from transformers import Wav2Vec2FeatureExtractor
-
->>> feature_extractor = Wav2Vec2FeatureExtractor(padding_value=1.0, do_normalize=True)
-```
-
-í
ì€íž ì
ë „ì ìČ늏í í íŹëìŽì 넌 ë§ëëë€:
-
-```py
->>> from transformers import Wav2Vec2CTCTokenizer
-
->>> tokenizer = Wav2Vec2CTCTokenizer(vocab_file="my_vocab_file.txt")
-```
-
-[`Wav2Vec2Processor`]ìì íčì± ì¶ì¶êž°ì í íŹëìŽì 넌 êȰí©í©ëë€:
-
-```py
->>> from transformers import Wav2Vec2Processor
-
->>> processor = Wav2Vec2Processor(feature_extractor=feature_extractor, tokenizer=tokenizer)
-```
-
-configurationêłŒ ëȘšëžìŽëŒë ë ê°ì§ êž°ëłž íŽëì€ì ì¶ê° ì ìČ늏 íŽëì€(í íŹëìŽì , ìŽëŻžì§ íëĄìžì, íčì± ì¶ì¶êž° ëë íëĄìžì)넌 ìŹì©í멎 đ€ Transformersìì ì§ìíë ëȘšë ëȘšëžì ë§ë€ ì ìì”ëë€. ìŽëŹí ê° êž°ëłž íŽëì€ë ê”Źì±ìŽ ê°ë„íëŻëĄ ìíë íčì ìì±ì ìŹì©í ì ìì”ëë€. íì”ì ìíŽ ëȘšëžì ìœêČ ì€ì íê±°ë êž°ìĄŽì ìŹì íì”ë ëȘšëžì ìì íìŹ ëŻžìž ìĄ°ì í ì ìì”ëë€.
diff --git a/docs/source/ko/custom_models.md b/docs/source/ko/custom_models.md
new file mode 100644
index 000000000000..72dad7caaff2
--- /dev/null
+++ b/docs/source/ko/custom_models.md
@@ -0,0 +1,346 @@
+
+
+# ìŹì©ì ì ì ëȘšëž êł”ì íêž°[[sharing-custom-models]]
+
+đ€ Transformers ëŒìŽëžëŹëŠŹë ìœêČ íì„í ì ìëëĄ ì€êłëìì”ëë€.
+ëȘšë ëȘšëžì ì¶ìí ììŽ ì ì„ìì ì§ì ë íì íŽëì ìì í ìœë©ëìŽ ììŒëŻëĄ, ììœêČ ëȘšëžë§ íìŒì ëł”ìŹíêł íìì ë°ëŒ ìĄ°ì í ì ìì”ëë€.
+
+ìì í ìëĄìŽ ëȘšëžì ë§ëë êČœì°ìë ìČìë¶í° ììíë êČìŽ ë ìŹìž ì ìì”ëë€.
+ìŽ íí 늏ìŒììë Transformers ëŽìì ìŹì©í ì ìëëĄ ìŹì©ì ì ì ëȘšëžêłŒ ê”Źì±ì ìì±íë ë°©ëČêłŒ
+đ€ Transformers ëŒìŽëžëŹëŠŹì ìë êČœì°ìë ëê”Źë ìŹì©í ì ìëëĄ (ììĄŽì±êłŒ íšê») ì»€ëź€ëí°ì êł”ì íë ë°©ëČì ë°°ìž ì ìì”ëë€.
+
+[timm ëŒìŽëžëŹëŠŹ](https://github.com/rwightman/pytorch-image-models)ì ResNet íŽëì€ë„Œ [`PreTrainedModel`]ëĄ ëíí ResNet ëȘšëžì ìëĄ ëȘšë êČì ì€ëȘ
í©ëë€.
+
+## ìŹì©ì ì ì ê”Źì± ìì±íêž°[[writing-a-custom-configuration]]
+
+ëȘšëžì ë€ìŽê°êž° ì ì 뚌ì ê”Źì±ì ìì±íŽëłŽëëĄ íêČ ì”ëë€.
+ëȘšëžì `configuration`ì ëȘšëžì ë§ë€êž° ìíŽ íìí ëȘšë ì€ìí êČë€ì íŹíšíêł ìë ê°ìČŽì
ëë€.
+ë€ì ìčì
ìì ëłŒ ì ìëŻìŽ, ëȘšëžì `config`넌 ìŹì©íŽìë§ ìŽêž°íí ì ìêž° ë돞ì ìëČœí ê”Źì±ìŽ íìí©ëë€.
+
+ìë ììììë ResNet íŽëì€ì ìžì(argument)넌 ìĄ°ì íŽëłŽêČ ì”ëë€.
+ë€ë„ž ê”Źì±ì ê°ë„í ResNet ì€ ë€ë„ž ì íì ì êł”í©ëë€.
+ê·žë° ë€ì ëȘ ê°ì§ ì íšì±ì íìží í íŽëč ìžì넌 ì ì„í©ëë€.
+
+```python
+from transformers import PretrainedConfig
+from typing import List
+
+
+class ResnetConfig(PretrainedConfig):
+ model_type = "resnet"
+
+ def __init__(
+ self,
+ block_type="bottleneck",
+ layers: List[int] = [3, 4, 6, 3],
+ num_classes: int = 1000,
+ input_channels: int = 3,
+ cardinality: int = 1,
+ base_width: int = 64,
+ stem_width: int = 64,
+ stem_type: str = "",
+ avg_down: bool = False,
+ **kwargs,
+ ):
+ if block_type not in ["basic", "bottleneck"]:
+ raise ValueError(f"`block_type` must be 'basic' or bottleneck', got {block_type}.")
+ if stem_type not in ["", "deep", "deep-tiered"]:
+ raise ValueError(f"`stem_type` must be '', 'deep' or 'deep-tiered', got {stem_type}.")
+
+ self.block_type = block_type
+ self.layers = layers
+ self.num_classes = num_classes
+ self.input_channels = input_channels
+ self.cardinality = cardinality
+ self.base_width = base_width
+ self.stem_width = stem_width
+ self.stem_type = stem_type
+ self.avg_down = avg_down
+ super().__init__(**kwargs)
+```
+
+ìŹì©ì ì ì `configuration`ì ìì±í ë êž°ì”íŽìŒ í ìž ê°ì§ ì€ìí ìŹíì ë€ìêłŒ ê°ì”ëë€:
+- `PretrainedConfig`ì ììíŽìŒ í©ëë€.
+- `PretrainedConfig`ì `__init__`ì ëȘšë kwargs넌 íì©íŽìŒ íêł ,
+- ìŽëŹí `kwargs`ë ìì íŽëì€ `__init__`ì ì ëŹëìŽìŒ í©ëë€.
+
+ììì đ€ Transformers ëŒìŽëžëŹëŠŹìì ëȘšë êž°ë„ì ê°ì žì€ë êČì
ëë€.
+ìŽëŹí ì ìŒëĄë¶í° ëč륯ëë ë ê°ì§ ì ìœ ìĄ°ê±Žì `PretrainedConfig`ì ì€ì íë êČëłŽë€ ë ë§ì íëê° ìì”ëë€.
+`from_pretrained` ë©ìëëĄ ê”Źì±ì ë€ì ëĄëí ë íŽëč íëë ê”Źì±ìì ìëœí í ìì íŽëì€ëĄ 볎ëŽìŒ í©ëë€.
+
+ëȘšëžì auto íŽëì€ì ë±ëĄíì§ ìë í, `configuration`ìì `model_type`ì ì ì(ìŹêž°ì `model_type="resnet"`)íë êČì íì ìŹíìŽ ìëëë€ (ë§ì§ë§ ìčì
ì°žìĄ°).
+
+ìŽë êČ í멎 ëŒìŽëžëŹëŠŹì ë€ë„ž ëȘšëž ê”Źì±êłŒ ë§ì°Źê°ì§ëĄ ê”Źì±ì ìœêČ ë§ë€êł ì ì„í ì ìì”ëë€.
+ë€ìì resnet50d ê”Źì±ì ìì±íêł ì ì„íë ë°©ëČì
ëë€:
+
+```py
+resnet50d_config = ResnetConfig(block_type="bottleneck", stem_width=32, stem_type="deep", avg_down=True)
+resnet50d_config.save_pretrained("custom-resnet")
+```
+
+ìŽë êČ í멎 `custom-resnet` íŽë ìì `config.json`ìŽëŒë íìŒìŽ ì ì„ë©ëë€.
+ê·žë° ë€ì `from_pretrained` ë©ìë넌 ìŹì©íìŹ ê”Źì±ì ë€ì ëĄëí ì ìì”ëë€.
+
+```py
+resnet50d_config = ResnetConfig.from_pretrained("custom-resnet")
+```
+
+ê”Źì±ì Hubì ì§ì ì
ëĄëíêž° ìíŽ [`PretrainedConfig`] íŽëì€ì [`~PretrainedConfig.push_to_hub`]ì ê°ì ë€ë„ž ë©ìë넌 ìŹì©í ì ìì”ëë€.
+
+
+## ìŹì©ì ì ì ëȘšëž ìì±íêž°[[writing-a-custom-model]]
+
+ìŽì ResNet ê”Źì±ìŽ ììŒëŻëĄ ëȘšëžì ìì±í ì ìì”ëë€.
+ì€ì ëĄë ë ê°ë„Œ ìì±í êČì
ëë€. íëë ìŽëŻžì§ ë°°ìčìì hidden features넌 ì¶ì¶íë êČ([`BertModel`]êłŒ ê°ìŽ), ë€ë„ž íëë ìŽëŻžì§ ë¶ë„ì ì í©í êČì
ëë€([`BertForSequenceClassification`]êłŒ ê°ìŽ).
+
+ìŽì ì ìžêžíëŻìŽ ìŽ ìì ììë ëšìíêČ íêž° ìíŽ ëȘšëžì ëìší ëíŒ(loose wrapper)ë§ ìì±í êČì
ëë€.
+ìŽ íŽëì€ë„Œ ìì±íêž° ì ì ëžëĄ ì íêłŒ ì€ì ëžëĄ íŽëì€ ê°ì ë§€í ìì
ë§ í멎 ë©ëë€.
+ê·žë° ë€ì `ResNet` íŽëì€ëĄ ì ëŹëìŽ `configuration`ì í”íŽ ëȘšëžìŽ ì ìžë©ëë€:
+
+```py
+from transformers import PreTrainedModel
+from timm.models.resnet import BasicBlock, Bottleneck, ResNet
+from .configuration_resnet import ResnetConfig
+
+
+BLOCK_MAPPING = {"basic": BasicBlock, "bottleneck": Bottleneck}
+
+
+class ResnetModel(PreTrainedModel):
+ config_class = ResnetConfig
+
+ def __init__(self, config):
+ super().__init__(config)
+ block_layer = BLOCK_MAPPING[config.block_type]
+ self.model = ResNet(
+ block_layer,
+ config.layers,
+ num_classes=config.num_classes,
+ in_chans=config.input_channels,
+ cardinality=config.cardinality,
+ base_width=config.base_width,
+ stem_width=config.stem_width,
+ stem_type=config.stem_type,
+ avg_down=config.avg_down,
+ )
+
+ def forward(self, tensor):
+ return self.model.forward_features(tensor)
+```
+
+ìŽëŻžì§ ë¶ë„ ëȘšëžì ë§ë€êž° ìíŽìë forward ë©ìëë§ ëłêČœí멎 ë©ëë€:
+
+```py
+import torch
+
+
+class ResnetModelForImageClassification(PreTrainedModel):
+ config_class = ResnetConfig
+
+ def __init__(self, config):
+ super().__init__(config)
+ block_layer = BLOCK_MAPPING[config.block_type]
+ self.model = ResNet(
+ block_layer,
+ config.layers,
+ num_classes=config.num_classes,
+ in_chans=config.input_channels,
+ cardinality=config.cardinality,
+ base_width=config.base_width,
+ stem_width=config.stem_width,
+ stem_type=config.stem_type,
+ avg_down=config.avg_down,
+ )
+
+ def forward(self, tensor, labels=None):
+ logits = self.model(tensor)
+ if labels is not None:
+ loss = torch.nn.cross_entropy(logits, labels)
+ return {"loss": loss, "logits": logits}
+ return {"logits": logits}
+```
+
+ë êČœì° ëȘšë `PreTrainedModel`넌 ììë°êł , `config`넌 í”íŽ ìì íŽëì€ ìŽêž°í넌 ížì¶íë€ë ì ì êž°ì”íìžì (ìŒë°ì ìž `torch.nn.Module`ì ìì±í ëì ëčì·íš).
+ëȘšëžì auto íŽëì€ì ë±ëĄíêł ì¶ì êČœì°ìë `config_class`넌 ì€ì íë ë¶ë¶ìŽ íìì
ëë€ (ë§ì§ë§ ìčì
ì°žìĄ°).
+
+
+
+ëŒìŽëžëŹëŠŹì ìĄŽìŹíë ëȘšëžêłŒ ê”ì„í ì ìŹíë€ë©Ž, ëȘšëžì ìì±í ë ê”Źì±ì ì°žìĄ°íŽ ìŹìŹì©í ì ìì”ëë€.
+
+
+
+ìíë êČì ëȘšëžìŽ ë°ííëëĄ í ì ìì§ë§, `ResnetModelForImageClassification`ìì íë êČ ìČëŒ
+ë ìŽëžì í”êłŒì쌰ì ë ìì€êłŒ íšê» ìŹì ííëĄ ë°ííë êČìŽ [`Trainer`] íŽëì€ ëŽìì ì§ì ëȘšëžì ìŹì©íêž°ì ì ì©í©ëë€.
+ìì ë§ì íì” ëŁší ëë ë€ë„ž íì” ëŒìŽëžëŹëŠŹë„Œ ìŹì©í êłíìŽëŒë©Ž ë€ë„ž ì¶ë „ íìì ìŹì©íŽë ìąì”ëë€.
+
+ìŽì ëȘšëž íŽëì€ê° ììŒëŻëĄ íë ìì±íŽ ëłŽêČ ì”ëë€:
+
+```py
+resnet50d = ResnetModelForImageClassification(resnet50d_config)
+```
+
+ë€ì ë§íì§ë§, [`~PreTrainedModel.save_pretrained`]ëë [`~PreTrainedModel.push_to_hub`]ìČëŒ [`PreTrainedModel`]ì ìíë ëȘšë ë©ìë넌 ìŹì©í ì ìì”ëë€.
+ë€ì ìčì
ìì ë ëČì§ž ë©ìë넌 ìŹì©íŽ ëȘšëž ìœëì ëȘšëž ê°ì€ìč넌 ì
ëĄëíë ë°©ëČì ìŽíŽëłŽêČ ì”ëë€.
+뚌ì , ëȘšëž ëŽë¶ì ìŹì íë šë ê°ì€ìč넌 ëĄëíŽ ëłŽêČ ì”ëë€.
+
+ìŽ ìì 넌 íì©í ëë, ìŹì©ì ì ì ëȘšëžì ìì ë§ì ë°ìŽí°ëĄ íì”ìíŹ êČì
ëë€.
+ìŽ íí 늏ìŒììë ëč 넎êČ ì§ííêž° ìíŽ ìŹì íë šë resnet50d넌 ìŹì©íêČ ì”ëë€.
+ìë ëȘšëžì resnet50dì ëíŒìŽêž° ë돞ì, ê°ì€ìč넌 ìœêČ ëĄëí ì ìì”ëë€.
+
+
+```py
+import timm
+
+pretrained_model = timm.create_model("resnet50d", pretrained=True)
+resnet50d.model.load_state_dict(pretrained_model.state_dict())
+```
+
+ìŽì [`~PreTrainedModel.save_pretrained`] ëë [`~PreTrainedModel.push_to_hub`]넌 ìŹì©í ë ëȘšëž ìœëê° ì ì„ëëì§ íìžíŽëŽ
ìë€.
+
+## HubëĄ ìœë ì
ëĄëíêž°[[sending-the-code-to-the-hub]]
+
+
+
+ìŽ APIë ì€íì ìŽë©° ë€ì 늎늏ì€ìì ìœê°ì ëłêČœ ìŹíìŽ ìì ì ìì”ëë€.
+
+
+
+뚌ì ëȘšëžìŽ `.py` íìŒì ìì í ì ìëìŽ ìëì§ íìžíìžì.
+ëȘšë íìŒìŽ ëìŒí ìì
êČœëĄì ìêž° ë돞ì ìëêČœëĄ ìíŹíž(relative import)ì ììĄŽí ì ìì”ëë€ (transformersììë ìŽ êž°ë„ì ëí íì ëȘšëì ì§ìíì§ ìì”ëë€).
+ìŽ ììììë ìì
êČœëĄ ìì `resnet_model`ìì `modeling_resnet.py` íìŒêłŒ `configuration_resnet.py` íìŒì ì ìí©ëë€.
+ê”Źì± íìŒìë `ResnetConfig`ì ëí ìœëê° ìêł ëȘšëžë§ íìŒìë `ResnetModel` ë° `ResnetModelForImageClassification`ì ëí ìœëê° ìì”ëë€.
+
+```
+.
+âââ resnet_model
+ âââ __init__.py
+ âââ configuration_resnet.py
+ âââ modeling_resnet.py
+```
+
+PythonìŽ `resnet_model`ì ëȘšëëĄ ìŹì©í ì ìëëĄ ê°ì§íë ëȘ©ì ìŽêž° ë돞ì `__init__.py`ë ëčìŽ ìì ì ìì”ëë€.
+
+
+
+ëŒìŽëžëŹëŠŹìì ëȘšëžë§ íìŒì ëł”ìŹíë êČœì°,
+ëȘšë íìŒ ìëšì ìë ìë êČœëĄ ìíŹíž(relative import) ë¶ë¶ì `transformers` íší€ì§ìì ìíŹíž íëëĄ ëłêČœíŽìŒ í©ëë€.
+
+
+
+êž°ìĄŽ ê”Źì±ìŽë ëȘšëžì ìŹìŹì©(ëë ìëž íŽëì€í)í ì ìì”ëë€.
+
+ì»€ëź€ëí°ì ëȘšëžì êł”ì íêž° ìíŽìë ë€ì ëšêłë„Œ ë°ëŒìŒ í©ëë€:
+뚌ì , ìëĄ ë§ë íìŒì ResNet ëȘšëžêłŒ ê”Źì±ì ìíŹíží©ëë€:
+
+```py
+from resnet_model.configuration_resnet import ResnetConfig
+from resnet_model.modeling_resnet import ResnetModel, ResnetModelForImageClassification
+```
+
+ë€ììŒëĄ `save_pretrained` ë©ìë넌 ìŹì©íŽ íŽëč ê°ìČŽì ìœë íìŒì ëł”ìŹíêł ,
+ëł”ìŹí íìŒì Auto íŽëì€ëĄ ë±ëĄíêł (ëȘšëžìž êČœì°) ì€íí©ëë€:
+
+```py
+ResnetConfig.register_for_auto_class()
+ResnetModel.register_for_auto_class("AutoModel")
+ResnetModelForImageClassification.register_for_auto_class("AutoModelForImageClassification")
+```
+
+`configuration`ì ëí auto íŽëì€ë„Œ ì§ì í íìë ìì§ë§(`configuration` êŽë š auto íŽëì€ë AutoConfig íŽëì€ íëë§ ìì), ëȘšëžì êČœì°ìë ì§ì íŽìŒ í©ëë€.
+ìŹì©ì ì§ì ëȘšëžì ë€ìí ìì
ì ì í©í ì ììŒëŻëĄ, ëȘšëžì ë§ë auto íŽëì€ë„Œ ì§ì íŽìŒ í©ëë€.
+
+ë€ììŒëĄ, ìŽì ì ìì
íë êČêłŒ ë§ì°Źê°ì§ëĄ ê”Źì±êłŒ ëȘšëžì ìì±í©ëë€:
+
+```py
+resnet50d_config = ResnetConfig(block_type="bottleneck", stem_width=32, stem_type="deep", avg_down=True)
+resnet50d = ResnetModelForImageClassification(resnet50d_config)
+
+pretrained_model = timm.create_model("resnet50d", pretrained=True)
+resnet50d.model.load_state_dict(pretrained_model.state_dict())
+```
+
+ìŽì ëȘšëžì HubëĄ ì
ëĄëíêž° ìíŽ ëĄê·žìž ìíìžì§ íìžíìžì.
+í°ëŻžëìì ë€ì ìœë넌 ì€ííŽ íìží ì ìì”ëë€:
+
+```bash
+huggingface-cli login
+```
+
+ìŁŒíŒí° ë
žížë¶ì êČœì°ìë ë€ìêłŒ ê°ì”ëë€:
+
+```py
+from huggingface_hub import notebook_login
+
+notebook_login()
+```
+
+ê·žë° ë€ì ìŽë êČ ìì ì ë€ìì€íìŽì€(ëë ìì ìŽ ìí ìĄ°ì§)ì ì
ëĄëí ì ìì”ëë€:
+```py
+resnet50d.push_to_hub("custom-resnet50d")
+```
+
+On top of the modeling weights and the configuration in json format, this also copied the modeling and
+configuration `.py` files in the folder `custom-resnet50d` and uploaded the result to the Hub. You can check the result
+in this [model repo](https://huggingface.co/sgugger/custom-resnet50d).
+json íìì ëȘšëžë§ ê°ì€ìčì ê”Źì± ìžìë `custom-resnet50d` íŽë ìì ëȘšëžë§êłŒ ê”Źì± `.py` íìŒì ëł”ìŹííŽ Hubì ì
ëĄëí©ëë€.
+[ëȘšëž ì ì„ì](https://huggingface.co/sgugger/custom-resnet50d)ìì êČ°êłŒë„Œ íìží ì ìì”ëë€.
+
+[sharing tutorial](model_sharing) 돞ìì `push_to_hub` ë©ìëìì ììží ëŽì©ì íìží ì ìì”ëë€.
+
+
+## ìŹì©ì ì ì ìœëëĄ ëȘšëž ìŹì©íêž°[[using-a-model-with-custom-code]]
+
+auto íŽëì€ì `from_pretrained` ë©ìë넌 ìŹì©íìŹ ìŹì©ì ì§ì ìœë íìŒêłŒ íšê» ëȘšë ê”Źì±, ëȘšëž, í íŹëìŽì 넌 ìŹì©í ì ìì”ëë€.
+Hubì ì
ëĄëë ëȘšë íìŒ ë° ìœëë ë©ìšìŽê° ìëì§ êČìŹëì§ë§ (ììží ëŽì©ì [Hub 볎ì](https://huggingface.co/docs/hub/security#malware-scanning) ì€ëȘ
ì°žìĄ°),
+ìì ì 컎íší°ìì ëȘšëž ìœëì ìì±ìê° ì
ì± ìœë넌 ì€ííì§ ìëì§ íìžíŽìŒ í©ëë€.
+ìŹì©ì ì ì ìœëëĄ ëȘšëžì ìŹì©íë €ë©Ž `trust_remote_code=True`ëĄ ì€ì íìžì:
+
+```py
+from transformers import AutoModelForImageClassification
+
+model = AutoModelForImageClassification.from_pretrained("sgugger/custom-resnet50d", trust_remote_code=True)
+```
+
+ëȘšëž ìì±ìê° ì
ìì ìŒëĄ ìœë넌 ì
ë°ìŽížíì§ ììë€ë ì ì íìžíêž° ìíŽ, ì»€ë° íŽì(commit hash)넌 `revision`ìŒëĄ ì ëŹíë êČë ê°ë „í ê¶ì„ë©ëë€ (ëȘšëž ìì±ì넌 ìì í ì ëą°íì§ ìë êČœì°).
+
+```py
+commit_hash = "ed94a7c6247d8aedce4647f00f20de6875b5b292"
+model = AutoModelForImageClassification.from_pretrained(
+ "sgugger/custom-resnet50d", trust_remote_code=True, revision=commit_hash
+)
+```
+
+Hubìì ëȘšëž ì ì„ìì ì»€ë° êž°ëĄì ì°ŸìëłŒ ë, ëȘšë 컀ë°ì ì»€ë° íŽì넌 ìœêČ ëł”ìŹí ì ìë ëČíŒìŽ ìì”ëë€.
+
+## ìŹì©ì ì ì ìœëëĄ ë§ë ëȘšëžì auto íŽëì€ëĄ ë±ëĄíêž°[[registering-a-model-with-custom-code-to-the-auto-classes]]
+
+đ€ Transformers넌 ììíë ëŒìŽëžëŹëŠŹë„Œ ìì±íë êČœì° ìŹì©ì ì ì ëȘšëžì auto íŽëì€ì ì¶ê°í ì ìì”ëë€.
+ìŹì©ì ì ì ëȘšëžì ìŹì©íêž° ìíŽ íŽëč ëŒìŽëžëŹëŠŹë„Œ ìíŹížíŽìŒ íêž° ë돞ì, ìŽë HubëĄ ìœë넌 ì
ëĄëíë êČêłŒ ë€ëŠ
ëë€ (Hubìì ìëì ìŒëĄ ëȘšëž ìœë넌 ë€ìŽëĄë íë êČêłŒ ë°ë).
+
+ê”Źì±ì êž°ìĄŽ ëȘšëž ì íêłŒ ë€ë„ž `model_type` ìì±ìŽ ìêł ëȘšëž íŽëì€ì ìŹë°ë„ž `config_class` ìì±ìŽ ìë í,
+ë€ìêłŒ ê°ìŽ auto íŽëì€ì ì¶ê°í ì ìì”ëë€:
+
+```py
+from transformers import AutoConfig, AutoModel, AutoModelForImageClassification
+
+AutoConfig.register("resnet", ResnetConfig)
+AutoModel.register(ResnetConfig, ResnetModel)
+AutoModelForImageClassification.register(ResnetConfig, ResnetModelForImageClassification)
+```
+
+ìŹì©ì ì ì ê”Źì±ì [`AutoConfig`]ì ë±ëĄí ë ìŹì©ëë ìČ« ëČì§ž ìžìë ìŹì©ì ì ì ê”Źì±ì `model_type`êłŒ ìŒìčíŽìŒ í©ëë€.
+ëí, ìŹì©ì ì ì ëȘšëžì auto íŽëì€ì ë±ëĄí ë ìŹì©ëë ìČ« ëČì§ž ìžìë íŽëč ëȘšëžì `config_class`ì ìŒìčíŽìŒ í©ëë€.
\ No newline at end of file
diff --git a/docs/source/ko/custom_models.mdx b/docs/source/ko/custom_models.mdx
deleted file mode 100644
index 6e9d91fcda27..000000000000
--- a/docs/source/ko/custom_models.mdx
+++ /dev/null
@@ -1,342 +0,0 @@
-
-
-# ìŹì©ì ì ì ëȘšëž êł”ì íêž°[[sharing-custom-models]]
-
-đ€ Transformers ëŒìŽëžëŹëŠŹë ìœêČ íì„í ì ìëëĄ ì€êłëìì”ëë€.
-ëȘšë ëȘšëžì ì¶ìí ììŽ ì ì„ìì ì§ì ë íì íŽëì ìì í ìœë©ëìŽ ììŒëŻëĄ, ììœêČ ëȘšëžë§ íìŒì ëł”ìŹíêł íìì ë°ëŒ ìĄ°ì í ì ìì”ëë€.
-
-ìì í ìëĄìŽ ëȘšëžì ë§ëë êČœì°ìë ìČìë¶í° ììíë êČìŽ ë ìŹìž ì ìì”ëë€.
-ìŽ íí 늏ìŒììë Transformers ëŽìì ìŹì©í ì ìëëĄ ìŹì©ì ì ì ëȘšëžêłŒ ê”Źì±ì ìì±íë ë°©ëČêłŒ
-đ€ Transformers ëŒìŽëžëŹëŠŹì ìë êČœì°ìë ëê”Źë ìŹì©í ì ìëëĄ (ììĄŽì±êłŒ íšê») ì»€ëź€ëí°ì êł”ì íë ë°©ëČì ë°°ìž ì ìì”ëë€.
-
-[timm ëŒìŽëžëŹëŠŹ](https://github.com/rwightman/pytorch-image-models)ì ResNet íŽëì€ë„Œ [`PreTrainedModel`]ëĄ ëíí ResNet ëȘšëžì ìëĄ ëȘšë êČì ì€ëȘ
í©ëë€.
-
-## ìŹì©ì ì ì ê”Źì± ìì±íêž°[[writing-a-custom-configuration]]
-
-ëȘšëžì ë€ìŽê°êž° ì ì 뚌ì ê”Źì±ì ìì±íŽëłŽëëĄ íêČ ì”ëë€.
-ëȘšëžì `configuration`ì ëȘšëžì ë§ë€êž° ìíŽ íìí ëȘšë ì€ìí êČë€ì íŹíšíêł ìë ê°ìČŽì
ëë€.
-ë€ì ìčì
ìì ëłŒ ì ìëŻìŽ, ëȘšëžì `config`넌 ìŹì©íŽìë§ ìŽêž°íí ì ìêž° ë돞ì ìëČœí ê”Źì±ìŽ íìí©ëë€.
-
-ìë ììììë ResNet íŽëì€ì ìžì(argument)넌 ìĄ°ì íŽëłŽêČ ì”ëë€.
-ë€ë„ž ê”Źì±ì ê°ë„í ResNet ì€ ë€ë„ž ì íì ì êł”í©ëë€.
-ê·žë° ë€ì ëȘ ê°ì§ ì íšì±ì íìží í íŽëč ìžì넌 ì ì„í©ëë€.
-
-```python
-from transformers import PretrainedConfig
-from typing import List
-
-
-class ResnetConfig(PretrainedConfig):
- model_type = "resnet"
-
- def __init__(
- self,
- block_type="bottleneck",
- layers: List[int] = [3, 4, 6, 3],
- num_classes: int = 1000,
- input_channels: int = 3,
- cardinality: int = 1,
- base_width: int = 64,
- stem_width: int = 64,
- stem_type: str = "",
- avg_down: bool = False,
- **kwargs,
- ):
- if block_type not in ["basic", "bottleneck"]:
- raise ValueError(f"`block_type` must be 'basic' or bottleneck', got {block_type}.")
- if stem_type not in ["", "deep", "deep-tiered"]:
- raise ValueError(f"`stem_type` must be '', 'deep' or 'deep-tiered', got {stem_type}.")
-
- self.block_type = block_type
- self.layers = layers
- self.num_classes = num_classes
- self.input_channels = input_channels
- self.cardinality = cardinality
- self.base_width = base_width
- self.stem_width = stem_width
- self.stem_type = stem_type
- self.avg_down = avg_down
- super().__init__(**kwargs)
-```
-
-ìŹì©ì ì ì `configuration`ì ìì±í ë êž°ì”íŽìŒ í ìž ê°ì§ ì€ìí ìŹíì ë€ìêłŒ ê°ì”ëë€:
-- `PretrainedConfig`ì ììíŽìŒ í©ëë€.
-- `PretrainedConfig`ì `__init__`ì ëȘšë kwargs넌 íì©íŽìŒ íêł ,
-- ìŽëŹí `kwargs`ë ìì íŽëì€ `__init__`ì ì ëŹëìŽìŒ í©ëë€.
-
-ììì đ€ Transformers ëŒìŽëžëŹëŠŹìì ëȘšë êž°ë„ì ê°ì žì€ë êČì
ëë€.
-ìŽëŹí ì ìŒëĄë¶í° ëč륯ëë ë ê°ì§ ì ìœ ìĄ°ê±Žì `PretrainedConfig`ì ì€ì íë êČëłŽë€ ë ë§ì íëê° ìì”ëë€.
-`from_pretrained` ë©ìëëĄ ê”Źì±ì ë€ì ëĄëí ë íŽëč íëë ê”Źì±ìì ìëœí í ìì íŽëì€ëĄ 볎ëŽìŒ í©ëë€.
-
-ëȘšëžì auto íŽëì€ì ë±ëĄíì§ ìë í, `configuration`ìì `model_type`ì ì ì(ìŹêž°ì `model_type="resnet"`)íë êČì íì ìŹíìŽ ìëëë€ (ë§ì§ë§ ìčì
ì°žìĄ°).
-
-ìŽë êČ í멎 ëŒìŽëžëŹëŠŹì ë€ë„ž ëȘšëž ê”Źì±êłŒ ë§ì°Źê°ì§ëĄ ê”Źì±ì ìœêČ ë§ë€êł ì ì„í ì ìì”ëë€.
-ë€ìì resnet50d ê”Źì±ì ìì±íêł ì ì„íë ë°©ëČì
ëë€:
-
-```py
-resnet50d_config = ResnetConfig(block_type="bottleneck", stem_width=32, stem_type="deep", avg_down=True)
-resnet50d_config.save_pretrained("custom-resnet")
-```
-
-ìŽë êČ í멎 `custom-resnet` íŽë ìì `config.json`ìŽëŒë íìŒìŽ ì ì„ë©ëë€.
-ê·žë° ë€ì `from_pretrained` ë©ìë넌 ìŹì©íìŹ ê”Źì±ì ë€ì ëĄëí ì ìì”ëë€.
-
-```py
-resnet50d_config = ResnetConfig.from_pretrained("custom-resnet")
-```
-
-ê”Źì±ì Hubì ì§ì ì
ëĄëíêž° ìíŽ [`PretrainedConfig`] íŽëì€ì [`~PretrainedConfig.push_to_hub`]ì ê°ì ë€ë„ž ë©ìë넌 ìŹì©í ì ìì”ëë€.
-
-
-## ìŹì©ì ì ì ëȘšëž ìì±íêž°[[writing-a-custom-model]]
-
-ìŽì ResNet ê”Źì±ìŽ ììŒëŻëĄ ëȘšëžì ìì±í ì ìì”ëë€.
-ì€ì ëĄë ë ê°ë„Œ ìì±í êČì
ëë€. íëë ìŽëŻžì§ ë°°ìčìì hidden features넌 ì¶ì¶íë êČ([`BertModel`]êłŒ ê°ìŽ), ë€ë„ž íëë ìŽëŻžì§ ë¶ë„ì ì í©í êČì
ëë€([`BertForSequenceClassification`]êłŒ ê°ìŽ).
-
-ìŽì ì ìžêžíëŻìŽ ìŽ ìì ììë ëšìíêČ íêž° ìíŽ ëȘšëžì ëìší ëíŒ(loose wrapper)ë§ ìì±í êČì
ëë€.
-ìŽ íŽëì€ë„Œ ìì±íêž° ì ì ëžëĄ ì íêłŒ ì€ì ëžëĄ íŽëì€ ê°ì ë§€í ìì
ë§ í멎 ë©ëë€.
-ê·žë° ë€ì `ResNet` íŽëì€ëĄ ì ëŹëìŽ `configuration`ì í”íŽ ëȘšëžìŽ ì ìžë©ëë€:
-
-```py
-from transformers import PreTrainedModel
-from timm.models.resnet import BasicBlock, Bottleneck, ResNet
-from .configuration_resnet import ResnetConfig
-
-
-BLOCK_MAPPING = {"basic": BasicBlock, "bottleneck": Bottleneck}
-
-
-class ResnetModel(PreTrainedModel):
- config_class = ResnetConfig
-
- def __init__(self, config):
- super().__init__(config)
- block_layer = BLOCK_MAPPING[config.block_type]
- self.model = ResNet(
- block_layer,
- config.layers,
- num_classes=config.num_classes,
- in_chans=config.input_channels,
- cardinality=config.cardinality,
- base_width=config.base_width,
- stem_width=config.stem_width,
- stem_type=config.stem_type,
- avg_down=config.avg_down,
- )
-
- def forward(self, tensor):
- return self.model.forward_features(tensor)
-```
-
-ìŽëŻžì§ ë¶ë„ ëȘšëžì ë§ë€êž° ìíŽìë forward ë©ìëë§ ëłêČœí멎 ë©ëë€:
-
-```py
-import torch
-
-
-class ResnetModelForImageClassification(PreTrainedModel):
- config_class = ResnetConfig
-
- def __init__(self, config):
- super().__init__(config)
- block_layer = BLOCK_MAPPING[config.block_type]
- self.model = ResNet(
- block_layer,
- config.layers,
- num_classes=config.num_classes,
- in_chans=config.input_channels,
- cardinality=config.cardinality,
- base_width=config.base_width,
- stem_width=config.stem_width,
- stem_type=config.stem_type,
- avg_down=config.avg_down,
- )
-
- def forward(self, tensor, labels=None):
- logits = self.model(tensor)
- if labels is not None:
- loss = torch.nn.cross_entropy(logits, labels)
- return {"loss": loss, "logits": logits}
- return {"logits": logits}
-```
-
-ë êČœì° ëȘšë `PreTrainedModel`넌 ììë°êł , `config`넌 í”íŽ ìì íŽëì€ ìŽêž°í넌 ížì¶íë€ë ì ì êž°ì”íìžì (ìŒë°ì ìž `torch.nn.Module`ì ìì±í ëì ëčì·íš).
-ëȘšëžì auto íŽëì€ì ë±ëĄíêł ì¶ì êČœì°ìë `config_class`넌 ì€ì íë ë¶ë¶ìŽ íìì
ëë€ (ë§ì§ë§ ìčì
ì°žìĄ°).
-
-
-
-ëŒìŽëžëŹëŠŹì ìĄŽìŹíë ëȘšëžêłŒ ê”ì„í ì ìŹíë€ë©Ž, ëȘšëžì ìì±í ë ê”Źì±ì ì°žìĄ°íŽ ìŹìŹì©í ì ìì”ëë€.
-
-
-
-ìíë êČì ëȘšëžìŽ ë°ííëëĄ í ì ìì§ë§, `ResnetModelForImageClassification`ìì íë êČ ìČëŒ
-ë ìŽëžì í”êłŒì쌰ì ë ìì€êłŒ íšê» ìŹì ííëĄ ë°ííë êČìŽ [`Trainer`] íŽëì€ ëŽìì ì§ì ëȘšëžì ìŹì©íêž°ì ì ì©í©ëë€.
-ìì ë§ì íì” ëŁší ëë ë€ë„ž íì” ëŒìŽëžëŹëŠŹë„Œ ìŹì©í êłíìŽëŒë©Ž ë€ë„ž ì¶ë „ íìì ìŹì©íŽë ìąì”ëë€.
-
-ìŽì ëȘšëž íŽëì€ê° ììŒëŻëĄ íë ìì±íŽ ëłŽêČ ì”ëë€:
-
-```py
-resnet50d = ResnetModelForImageClassification(resnet50d_config)
-```
-
-ë€ì ë§íì§ë§, [`~PreTrainedModel.save_pretrained`]ëë [`~PreTrainedModel.push_to_hub`]ìČëŒ [`PreTrainedModel`]ì ìíë ëȘšë ë©ìë넌 ìŹì©í ì ìì”ëë€.
-ë€ì ìčì
ìì ë ëČì§ž ë©ìë넌 ìŹì©íŽ ëȘšëž ìœëì ëȘšëž ê°ì€ìč넌 ì
ëĄëíë ë°©ëČì ìŽíŽëłŽêČ ì”ëë€.
-뚌ì , ëȘšëž ëŽë¶ì ìŹì íë šë ê°ì€ìč넌 ëĄëíŽ ëłŽêČ ì”ëë€.
-
-ìŽ ìì 넌 íì©í ëë, ìŹì©ì ì ì ëȘšëžì ìì ë§ì ë°ìŽí°ëĄ íì”ìíŹ êČì
ëë€.
-ìŽ íí 늏ìŒììë ëč 넎êČ ì§ííêž° ìíŽ ìŹì íë šë resnet50d넌 ìŹì©íêČ ì”ëë€.
-ìë ëȘšëžì resnet50dì ëíŒìŽêž° ë돞ì, ê°ì€ìč넌 ìœêČ ëĄëí ì ìì”ëë€.
-
-
-```py
-import timm
-
-pretrained_model = timm.create_model("resnet50d", pretrained=True)
-resnet50d.model.load_state_dict(pretrained_model.state_dict())
-```
-
-ìŽì [`~PreTrainedModel.save_pretrained`] ëë [`~PreTrainedModel.push_to_hub`]넌 ìŹì©í ë ëȘšëž ìœëê° ì ì„ëëì§ íìžíŽëŽ
ìë€.
-
-## HubëĄ ìœë ì
ëĄëíêž°[[sending-the-code-to-the-hub]]
-
-
-
-ìŽ APIë ì€íì ìŽë©° ë€ì 늎늏ì€ìì ìœê°ì ëłêČœ ìŹíìŽ ìì ì ìì”ëë€.
-
-
-
-뚌ì ëȘšëžìŽ `.py` íìŒì ìì í ì ìëìŽ ìëì§ íìžíìžì.
-ëȘšë íìŒìŽ ëìŒí ìì
êČœëĄì ìêž° ë돞ì ìëêČœëĄ ìíŹíž(relative import)ì ììĄŽí ì ìì”ëë€ (transformersììë ìŽ êž°ë„ì ëí íì ëȘšëì ì§ìíì§ ìì”ëë€).
-ìŽ ììììë ìì
êČœëĄ ìì `resnet_model`ìì `modeling_resnet.py` íìŒêłŒ `configuration_resnet.py` íìŒì ì ìí©ëë€.
-ê”Źì± íìŒìë `ResnetConfig`ì ëí ìœëê° ìêł ëȘšëžë§ íìŒìë `ResnetModel` ë° `ResnetModelForImageClassification`ì ëí ìœëê° ìì”ëë€.
-
-```
-.
-âââ resnet_model
- âââ __init__.py
- âââ configuration_resnet.py
- âââ modeling_resnet.py
-```
-
-PythonìŽ `resnet_model`ì ëȘšëëĄ ìŹì©í ì ìëëĄ ê°ì§íë ëȘ©ì ìŽêž° ë돞ì `__init__.py`ë ëčìŽ ìì ì ìì”ëë€.
-
-
-
-ëŒìŽëžëŹëŠŹìì ëȘšëžë§ íìŒì ëł”ìŹíë êČœì°,
-ëȘšë íìŒ ìëšì ìë ìë êČœëĄ ìíŹíž(relative import) ë¶ë¶ì `transformers` íší€ì§ìì ìíŹíž íëëĄ ëłêČœíŽìŒ í©ëë€.
-
-
-
-êž°ìĄŽ ê”Źì±ìŽë ëȘšëžì ìŹìŹì©(ëë ìëž íŽëì€í)í ì ìì”ëë€.
-
-ì»€ëź€ëí°ì ëȘšëžì êł”ì íêž° ìíŽìë ë€ì ëšêłë„Œ ë°ëŒìŒ í©ëë€:
-뚌ì , ìëĄ ë§ë íìŒì ResNet ëȘšëžêłŒ ê”Źì±ì ìíŹíží©ëë€:
-
-```py
-from resnet_model.configuration_resnet import ResnetConfig
-from resnet_model.modeling_resnet import ResnetModel, ResnetModelForImageClassification
-```
-
-ë€ììŒëĄ `save_pretrained` ë©ìë넌 ìŹì©íŽ íŽëč ê°ìČŽì ìœë íìŒì ëł”ìŹíêł ,
-ëł”ìŹí íìŒì Auto íŽëì€ëĄ ë±ëĄíêł (ëȘšëžìž êČœì°) ì€íí©ëë€:
-
-```py
-ResnetConfig.register_for_auto_class()
-ResnetModel.register_for_auto_class("AutoModel")
-ResnetModelForImageClassification.register_for_auto_class("AutoModelForImageClassification")
-```
-
-`configuration`ì ëí auto íŽëì€ë„Œ ì§ì í íìë ìì§ë§(`configuration` êŽë š auto íŽëì€ë AutoConfig íŽëì€ íëë§ ìì), ëȘšëžì êČœì°ìë ì§ì íŽìŒ í©ëë€.
-ìŹì©ì ì§ì ëȘšëžì ë€ìí ìì
ì ì í©í ì ììŒëŻëĄ, ëȘšëžì ë§ë auto íŽëì€ë„Œ ì§ì íŽìŒ í©ëë€.
-
-ë€ììŒëĄ, ìŽì ì ìì
íë êČêłŒ ë§ì°Źê°ì§ëĄ ê”Źì±êłŒ ëȘšëžì ìì±í©ëë€:
-
-```py
-resnet50d_config = ResnetConfig(block_type="bottleneck", stem_width=32, stem_type="deep", avg_down=True)
-resnet50d = ResnetModelForImageClassification(resnet50d_config)
-
-pretrained_model = timm.create_model("resnet50d", pretrained=True)
-resnet50d.model.load_state_dict(pretrained_model.state_dict())
-```
-
-ìŽì ëȘšëžì HubëĄ ì
ëĄëíêž° ìíŽ ëĄê·žìž ìíìžì§ íìžíìžì.
-í°ëŻžëìì ë€ì ìœë넌 ì€ííŽ íìží ì ìì”ëë€:
-
-```bash
-huggingface-cli login
-```
-
-ìŁŒíŒí° ë
žížë¶ì êČœì°ìë ë€ìêłŒ ê°ì”ëë€:
-
-```py
-from huggingface_hub import notebook_login
-
-notebook_login()
-```
-
-ê·žë° ë€ì ìŽë êČ ìì ì ë€ìì€íìŽì€(ëë ìì ìŽ ìí ìĄ°ì§)ì ì
ëĄëí ì ìì”ëë€:
-```py
-resnet50d.push_to_hub("custom-resnet50d")
-```
-
-On top of the modeling weights and the configuration in json format, this also copied the modeling and
-configuration `.py` files in the folder `custom-resnet50d` and uploaded the result to the Hub. You can check the result
-in this [model repo](https://huggingface.co/sgugger/custom-resnet50d).
-json íìì ëȘšëžë§ ê°ì€ìčì ê”Źì± ìžìë `custom-resnet50d` íŽë ìì ëȘšëžë§êłŒ ê”Źì± `.py` íìŒì ëł”ìŹííŽ Hubì ì
ëĄëí©ëë€.
-[ëȘšëž ì ì„ì](https://huggingface.co/sgugger/custom-resnet50d)ìì êČ°êłŒë„Œ íìží ì ìì”ëë€.
-
-[sharing tutorial](model_sharing) 돞ìì `push_to_hub` ë©ìëìì ììží ëŽì©ì íìží ì ìì”ëë€.
-
-
-## ìŹì©ì ì ì ìœëëĄ ëȘšëž ìŹì©íêž°[[using-a-model-with-custom-code]]
-
-auto íŽëì€ì `from_pretrained` ë©ìë넌 ìŹì©íìŹ ìŹì©ì ì§ì ìœë íìŒêłŒ íšê» ëȘšë ê”Źì±, ëȘšëž, í íŹëìŽì 넌 ìŹì©í ì ìì”ëë€.
-Hubì ì
ëĄëë ëȘšë íìŒ ë° ìœëë ë©ìšìŽê° ìëì§ êČìŹëì§ë§ (ììží ëŽì©ì [Hub 볎ì](https://huggingface.co/docs/hub/security#malware-scanning) ì€ëȘ
ì°žìĄ°),
-ìì ì 컎íší°ìì ëȘšëž ìœëì ìì±ìê° ì
ì± ìœë넌 ì€ííì§ ìëì§ íìžíŽìŒ í©ëë€.
-ìŹì©ì ì ì ìœëëĄ ëȘšëžì ìŹì©íë €ë©Ž `trust_remote_code=True`ëĄ ì€ì íìžì:
-
-```py
-from transformers import AutoModelForImageClassification
-
-model = AutoModelForImageClassification.from_pretrained("sgugger/custom-resnet50d", trust_remote_code=True)
-```
-
-ëȘšëž ìì±ìê° ì
ìì ìŒëĄ ìœë넌 ì
ë°ìŽížíì§ ììë€ë ì ì íìžíêž° ìíŽ, ì»€ë° íŽì(commit hash)넌 `revision`ìŒëĄ ì ëŹíë êČë ê°ë „í ê¶ì„ë©ëë€ (ëȘšëž ìì±ì넌 ìì í ì ëą°íì§ ìë êČœì°).
-
-```py
-commit_hash = "ed94a7c6247d8aedce4647f00f20de6875b5b292"
-model = AutoModelForImageClassification.from_pretrained(
- "sgugger/custom-resnet50d", trust_remote_code=True, revision=commit_hash
-)
-```
-
-Hubìì ëȘšëž ì ì„ìì ì»€ë° êž°ëĄì ì°ŸìëłŒ ë, ëȘšë 컀ë°ì ì»€ë° íŽì넌 ìœêČ ëł”ìŹí ì ìë ëČíŒìŽ ìì”ëë€.
-
-## ìŹì©ì ì ì ìœëëĄ ë§ë ëȘšëžì auto íŽëì€ëĄ ë±ëĄíêž°[[registering-a-model-with-custom-code-to-the-auto-classes]]
-
-đ€ Transformers넌 ììíë ëŒìŽëžëŹëŠŹë„Œ ìì±íë êČœì° ìŹì©ì ì ì ëȘšëžì auto íŽëì€ì ì¶ê°í ì ìì”ëë€.
-ìŹì©ì ì ì ëȘšëžì ìŹì©íêž° ìíŽ íŽëč ëŒìŽëžëŹëŠŹë„Œ ìíŹížíŽìŒ íêž° ë돞ì, ìŽë HubëĄ ìœë넌 ì
ëĄëíë êČêłŒ ë€ëŠ
ëë€ (Hubìì ìëì ìŒëĄ ëȘšëž ìœë넌 ë€ìŽëĄë íë êČêłŒ ë°ë).
-
-ê”Źì±ì êž°ìĄŽ ëȘšëž ì íêłŒ ë€ë„ž `model_type` ìì±ìŽ ìêł ëȘšëž íŽëì€ì ìŹë°ë„ž `config_class` ìì±ìŽ ìë í,
-ë€ìêłŒ ê°ìŽ auto íŽëì€ì ì¶ê°í ì ìì”ëë€:
-
-```py
-from transformers import AutoConfig, AutoModel, AutoModelForImageClassification
-
-AutoConfig.register("resnet", ResnetConfig)
-AutoModel.register(ResnetConfig, ResnetModel)
-AutoModelForImageClassification.register(ResnetConfig, ResnetModelForImageClassification)
-```
-
-ìŹì©ì ì ì ê”Źì±ì [`AutoConfig`]ì ë±ëĄí ë ìŹì©ëë ìČ« ëČì§ž ìžìë ìŹì©ì ì ì ê”Źì±ì `model_type`êłŒ ìŒìčíŽìŒ í©ëë€.
-ëí, ìŹì©ì ì ì ëȘšëžì auto íŽëì€ì ë±ëĄí ë ìŹì©ëë ìČ« ëČì§ž ìžìë íŽëč ëȘšëžì `config_class`ì ìŒìčíŽìŒ í©ëë€.
\ No newline at end of file
diff --git a/docs/source/ko/custom_tools.md b/docs/source/ko/custom_tools.md
new file mode 100644
index 000000000000..1accecab3d00
--- /dev/null
+++ b/docs/source/ko/custom_tools.md
@@ -0,0 +1,748 @@
+
+
+# ìŹì©ì ì ì ëê”Źì í륏ííž[[custom-tools-and-prompts]]
+
+
+
+Transformersì êŽë šíìŹ ìŽë€ ëê”Źì ììŽì ížê° ìëì§ ì ëȘšë„Žì ë€ë©Ž [Transformers Agents](transformers_agents) íìŽì§ë„Œ 뚌ì ìœìŽëłŽìêž° ë°ëëë€.
+
+
+
+
+
+Transformers Agentë ì€í ì€ìž APIëĄ ìžì ë ì§ ëłêČœë ì ìì”ëë€.
+API ëë êž°ë° ëȘšëžìŽ ëłêČœëêž° ìœêž° ë돞ì ììŽì ížê° ë°ííë êČ°êłŒë ëŹëŒì§ ì ìì”ëë€.
+
+
+
+ììŽì ížìêČ ê¶íì ë¶ìŹíêł ìëĄìŽ ìì
ì ìííêČ íë €ë©Ž ìŹì©ì ì ì ëê”Źì í륏íížë„Œ ë§ë€êł ìŹì©íë êČìŽ ëŹŽìëłŽë€ ì€ìí©ëë€.
+ìŽ ê°ìŽëììë ë€ìêłŒ ê°ì ëŽì©ì ìŽíŽëłŽêČ ì”ëë€:
+
+- í륏íížë„Œ ìŹì©ì ì ìíë ë°©ëČ
+- ìŹì©ì ì ì ëê”Źë„Œ ìŹì©íë ë°©ëČ
+- ìŹì©ì ì ì ëê”Źë„Œ ë§ëë ë°©ëČ
+
+## í륏íížë„Œ ìŹì©ì ì ìíêž°[[customizing-the-prompt]]
+
+[Transformers Agents](transformers_agents)ìì ì€ëȘ
í êČìČëŒ ììŽì ížë [`~Agent.run`] ë° [`~Agent.chat`] ëȘšëìì ì€íí ì ìì”ëë€.
+`run`(ì€í) ëȘšëì `chat`(ì±í
) ëȘšë ëȘšë ëìŒí ëĄì§ì êž°ë°ìŒëĄ í©ëë€.
+ììŽì ížë„Œ ê”Źëíë ìžìŽ ëȘšëžì ꞎ í륏íížì ë°ëŒ ìĄ°ê±ŽìŽ ì§ì ëêł , ì€ì§ í í°ì ëëŹí ëêčì§ ë€ì í í°ì ìì±íìŹ í륏íížë„Œ ììí©ëë€.
+`chat` ëȘšëììë í륏íížê° ìŽì ìŹì©ì ì
ë „ ë° ëȘšëž ìì±ìŒëĄ ì°ì„ëë€ë ì ìŽ ë ëȘšëì ì ìŒí ì°šìŽì ì
ëë€.
+ìŽë„Œ í”íŽ ììŽì ížê° êłŒê±° ìížìì©ì ì ê·Œí ì ìêČ ëëŻëĄ ììŽì ížìêČ ìŒìą
ì ë©ëȘšëŠŹë„Œ ì êł”íë ì
ì
ëë€.
+
+### í륏íížì ê”ŹìĄ°[[structure-of-the-prompt]]
+
+ìŽë»êČ í륏ííž ìŹì©ì ì ì넌 ì í ì ìëì§ ìŽíŽíêž° ìíŽ í륏íížì ê”ŹìĄ°ë„Œ ììží ìŽíŽëŽ
ìë€.
+í륏íížë íŹêČ ë€ ë¶ë¶ìŒëĄ ê”Źì±ëìŽ ìì”ëë€.
+
+- 1. ëì
: ììŽì ížê° ìŽë»êČ íëíŽìŒ íëì§, ëê”Źì ê°ë
ì ëí ì€ëȘ
.
+- 2. ëȘšë ëê”Źì ëí ì€ëȘ
. ìŽë ë°íìì ìŹì©ìê° ì ì/ì íí ëê”ŹëĄ ëì ìŒëĄ ëìČŽëë `<>` í í°ìŒëĄ ì ìë©ëë€.
+- 3. ìì
ìì ë° íŽëč ì룚ì
ìžíž.
+- 4. íìŹ ìì ë° íŽêȰ ììČ.
+
+ê° ë¶ë¶ì ë ì ìŽíŽí ì ìëëĄ ì§§ì ëČì ì í”íŽ `run` í륏íížê° ìŽë»êČ ëłŽìŽëì§ ìŽíŽëłŽêČ ì”ëë€:
+
+````text
+I will ask you to perform a task, your job is to come up with a series of simple commands in Python that will perform the task.
+[...]
+You can print intermediate results if it makes sense to do so.
+
+Tools:
+- document_qa: This is a tool that answers a question about a document (pdf). It takes an input named `document` which should be the document containing the information, as well as a `question` that is the question about the document. It returns a text that contains the answer to the question.
+- image_captioner: This is a tool that generates a description of an image. It takes an input named `image` which should be the image to the caption and returns a text that contains the description in English.
+[...]
+
+Task: "Answer the question in the variable `question` about the image stored in the variable `image`. The question is in French."
+
+I will use the following tools: `translator` to translate the question into English and then `image_qa` to answer the question on the input image.
+
+Answer:
+```py
+translated_question = translator(question=question, src_lang="French", tgt_lang="English")
+print(f"The translated question is {translated_question}.")
+answer = image_qa(image=image, question=translated_question)
+print(f"The answer is {answer}")
+```
+
+Task: "Identify the oldest person in the `document` and create an image showcasing the result as a banner."
+
+I will use the following tools: `document_qa` to find the oldest person in the document, then `image_generator` to generate an image according to the answer.
+
+Answer:
+```py
+answer = document_qa(document, question="What is the oldest person?")
+print(f"The answer is {answer}.")
+image = image_generator("A banner showing " + answer)
+```
+
+[...]
+
+Task: "Draw me a picture of rivers and lakes"
+
+I will use the following
+````
+
+ëì
(*"ëê”Ź:"* ìì í
ì€íž)ììë ëȘšëžìŽ ìŽë»êČ ìëíêł ëŹŽìì íŽìŒ íëì§ ì ííêČ ì€ëȘ
í©ëë€.
+ììŽì ížë íì ê°ì ë°©ììŒëĄ ìëíŽìŒ íëŻëĄ ìŽ ë¶ë¶ì ìŹì©ì ì ìí íìê° ìì ê°ë„ì±ìŽ ëì”ëë€.
+
+ë ëČì§ž ë¶ë¶(*"ëê”Ź"* ìëì êžëšžëŠŹ êž°íž)ì `run` ëë `chat`ì ížì¶í ë ëì ìŒëĄ ì¶ê°ë©ëë€.
+ì íí `agent.toolbox`ì ìë ëê”Ź ìë§íŒ êžëšžëŠŹ êž°ížê° ìêł , ê° êžëšžëŠŹ êž°ížë ëê”Źì ìŽëŠêłŒ ì€ëȘ
ìŒëĄ ê”Źì±ë©ëë€:
+
+```text
+- :
+```
+
+돞ì ì§ììë” ëê”Źë„Œ ê°ì žì€êł ìŽëŠêłŒ ì€ëȘ
ì ì¶ë „íŽì ëč 넎êČ íìžíŽ ëłŽêČ ì”ëë€.
+
+```py
+from transformers import load_tool
+
+document_qa = load_tool("document-question-answering")
+print(f"- {document_qa.name}: {document_qa.description}")
+```
+
+ê·žëŹë©Ž ë€ì êČ°êłŒê° ì¶ë „ë©ëë€:
+```text
+- document_qa: This is a tool that answers a question about a document (pdf). It takes an input named `document` which should be the document containing the information, as well as a `question` that is the question about the document. It returns a text that contains the answer to the question.
+```
+
+ìŹêž°ì ëê”Ź ìŽëŠìŽ ì§§êł ì ííë€ë êČì ì ì ìì”ëë€.
+ì€ëȘ
ì ë ë¶ë¶ìŒëĄ ê”Źì±ëìŽ ìëë°, ìČ« ëČì§ž ë¶ë¶ììë ëê”Źì êž°ë„ì ì€ëȘ
íêł ë ëČì§ž ë¶ë¶ììë ììëë ì
ë „ ìžìì ë°í ê°ì ëȘ
ìí©ëë€.
+
+ììŽì ížê° ëê”Źë„Œ ìŹë°ë„ŽêČ ìŹì©íë €ë©Ž ìąì ëê”Ź ìŽëŠêłŒ ëê”Ź ì€ëȘ
ìŽ ë§€ì° ì€ìí©ëë€.
+ììŽì ížê° ëê”Źì ëíŽ ì ì ìë ì ìŒí ì 볎ë ìŽëŠêłŒ ì€ëȘ
ëżìŽëŻëĄ, ìŽ ë ê°ì§ë„Œ ì ííêČ ìì±íêł ëê”Ź ììì ìë êž°ìĄŽ ëê”Źì ì€íìŒêłŒ ìŒìčíëì§ íìžíŽìŒ í©ëë€.
+íčí ìŽëŠì ë°ëŒ ììëë ëȘšë ìžìê° ì€ëȘ
ì ìœë ì€íìŒëĄ ìžêžëìŽ ìëì§, ììëë ì íêłŒ ê·ž ì íìŽ ëŹŽììžì§ì ëí ì€ëȘ
ìŽ íŹíšëìŽ ìëì§ íìžíìžì.
+
+
+
+ëê”Źì ìŽë€ ìŽëŠêłŒ ì€ëȘ
ìŽ ììŽìŒ íëì§ ìŽíŽíë €ë©Ž ìì ë Transformers ëê”Źì ìŽëŠêłŒ ì€ëȘ
ì íìžíìžì.
+[`Agent.toolbox`] ìì±ì ê°ì§ ëȘšë ëê”Źë„Œ ëłŒ ì ìì”ëë€.
+
+
+
+ìž ëČì§ž ë¶ë¶ìë ììŽì ížê° ìŽë€ ìą
ë„ì ìŹì©ì ììČì ëíŽ ìŽë€ ìœë넌 ìì±íŽìŒ íëì§ ì ííêČ ëłŽìŹìŁŒë ìì ë ìì ìžížê° íŹíšëìŽ ìì”ëë€.
+ììŽì ížë„Œ ì§ìíë ëê·ëȘš ìžìŽ ëȘšëžì í륏íížìì íšíŽì ìžìíêł ìëĄìŽ ë°ìŽí°ëĄ íšíŽì ë°ëł”íë ë° ë§€ì° ë„ìí©ëë€.
+ë°ëŒì ììŽì ížê° ì€ì ëĄ ìŹë°ë„ž ì€í ê°ë„í ìœë넌 ìì±í ê°ë„ì±ì ê·čëííë ë°©ììŒëĄ ìì 넌 ìì±íë êČìŽ ë§€ì° ì€ìí©ëë€.
+
+í ê°ì§ ì넌 ìŽíŽëłŽêČ ì”ëë€:
+
+````text
+Task: "Identify the oldest person in the `document` and create an image showcasing the result as a banner."
+
+I will use the following tools: `document_qa` to find the oldest person in the document, then `image_generator` to generate an image according to the answer.
+
+Answer:
+```py
+answer = document_qa(document, question="What is the oldest person?")
+print(f"The answer is {answer}.")
+image = image_generator("A banner showing " + answer)
+```
+
+````
+ìì
ì€ëȘ
, ììŽì ížê° ìííë €ë ìì
ì ëí ì€ëȘ
, ë§ì§ë§ìŒëĄ ìì±ë ìœë, ìŽ ìž ë¶ë¶ìŒëĄ ê”Źì±ë í륏íížë ëȘšëžì ë°ëł”íìŹ ì êł”ë©ëë€.
+í륏íížì ìŒë¶ìž ëȘšë ìì ë ìŽëŹí ì íí íšíŽìŒëĄ ëìŽ ììŒëŻëĄ, ììŽì ížê° ì í í°ì ìì±í ë ì íí ëìŒí íšíŽì ìŹíí ì ìì”ëë€.
+
+í륏ííž ìì ë Transformers íìŽ ì ëłíêł ìŒë šì [problem statements](https://github.com/huggingface/transformers/blob/main/src/transformers/tools/evaluate_agent.py)ì ë°ëŒ ìêČ©íêČ íê°íìŹ
+ììŽì ížì í륏íížê° ììŽì ížì ì€ì ìŹì© ìŹëĄë„Œ ì”ëí ì íŽêȰí ì ìëëĄ ëłŽì„í©ëë€.
+
+í륏íížì ë§ì§ë§ ë¶ë¶ì ë€ìì íŽëčí©ëë€:
+```text
+Task: "Draw me a picture of rivers and lakes"
+
+I will use the following
+```
+
+ìŽë ììŽì ížê° ìëŁíŽìŒ í ì”ìą
ì ìž ëŻžìì± ìì ì
ëë€. 믞ìì± ìì ë ì€ì ìŹì©ì ì
ë „ì ë°ëŒ ëì ìŒëĄ ë§ë€ìŽì§ëë€.
+ì ììì êČœì° ìŹì©ìê° ë€ìêłŒ ê°ìŽ ì€ííì”ëë€:
+
+```py
+agent.run("Draw me a picture of rivers and lakes")
+```
+
+ìŹì©ì ì
ë „ - *ìŠ* Task: *"Draw me a picture of rivers and lakes"*ê° í륏ííž í
í늿ì ë§ì¶° "Task: \n\n I will use the following"ëĄ ìșì€í
ë©ëë€.
+ìŽ ëŹžì„ì ììŽì ížìêČ ìĄ°ê±ŽìŽ ì ì©ëë í륏íížì ë§ì§ë§ ì€ì ê”Źì±íëŻëĄ ììŽì ížê° ìŽì ìì ìì ìíí êČêłŒ ì íí ëìŒí ë°©ììŒëĄ ìì 넌 ìëŁíëëĄ ê°ë „íêČ ìí„ì 믞ìč©ëë€.
+
+ë돎 ììží ì€ëȘ
íì§ ìëëŒë ì±í
í
í늿ì í륏ííž ê”ŹìĄ°ë ëìŒíì§ë§ ìì ì ì€íìŒìŽ ìœê° ë€ëŠ
ëë€. *ì넌 ë€ë©Ž*:
+
+````text
+[...]
+
+=====
+
+Human: Answer the question in the variable `question` about the image stored in the variable `image`.
+
+Assistant: I will use the tool `image_qa` to answer the question on the input image.
+
+```py
+answer = image_qa(text=question, image=image)
+print(f"The answer is {answer}")
+```
+
+Human: I tried this code, it worked but didn't give me a good result. The question is in French
+
+Assistant: In this case, the question needs to be translated first. I will use the tool `translator` to do this.
+
+```py
+translated_question = translator(question=question, src_lang="French", tgt_lang="English")
+print(f"The translated question is {translated_question}.")
+answer = image_qa(text=translated_question, image=image)
+print(f"The answer is {answer}")
+```
+
+=====
+
+[...]
+````
+
+`run` í륏íížì ììë ë°ëëĄ, ê° `chat` í륏íížì ììë *Human(ìŹë)*êłŒ *Assistant(ìŽìì€íŽíž)* ê°ì íë ìŽìì ê”íìŽ ìì”ëë€. ëȘšë ê”íì `run` í륏íížì ìì ì ìŹí ê”ŹìĄ°ëĄ ëìŽ ìì”ëë€.
+ìŹì©ìì ì
ë „ìŽ *Human:* ë€ì ì¶ê°ëë©°, ììŽì ížìêČ ìœë넌 ìì±íêž° ì ì ìííŽìŒ í ìì
ì 뚌ì ìì±íëŒë ë©ìì§ê° íìë©ëë€.
+ê”íì ìŽì ê”íì êž°ë°ìŒëĄ í ì ììŒëŻëĄ ìì ê°ìŽ ìŹì©ìê° "**ìŽ** ìœë넌 ìëíì”ëë€"ëŒêł ì
ë „í멎 ìŽì ì ìì±ë ììŽì ížì ìœë넌 ì°žìĄ°íìŹ êłŒê±° ê”íì ì°žìĄ°í ì ìì”ëë€.
+
+`.chat`ì ì€íí멎 ìŹì©ìì ì
ë „ ëë *ìì
*ìŽ ëŻžìì±ë ììì ììëĄ ìșì€í
ë©ëë€:
+```text
+Human: \n\nAssistant:
+```
+ê·žëŹë©Ž ììŽì ížê° ìŽë„Œ ìì±í©ëë€. `run` ëȘ
ë čêłŒ ëŹëŠŹ `chat` ëȘ
ë čì ìëŁë ìì 넌 í륏íížì ì¶ê°íìŹ ììŽì ížìêČ ë€ì `chat` ì°šëĄì ëí ë ë§ì 돞맄ì ì êł”í©ëë€.
+
+ìŽì í륏íížê° ìŽë»êČ ê”Źì±ëìŽ ìëì§ ìììŒë ìŽë»êČ ìŹì©ì ì ìí ì ìëì§ ìŽíŽëŽ
ìë€!
+
+### ìąì ìŹì©ì ì
ë „ ìì±íêž°[[writing-good-user-inputs]]
+
+ëê·ëȘš ìžìŽ ëȘšëžìŽ ìŹì©ìì ìë넌 ìŽíŽíë ë„ë „ìŽ ì ì ë í„ìëêł ìì§ë§, ììŽì ížê° ìŹë°ë„ž ìì
ì ì íí ì ìëëĄ ì”ëí ì íì±ì ì ì§íë êČì í° ëììŽ ë©ëë€.
+ì”ëí ì ííë€ë êČì 돎ìì ì믞í êčì?
+
+ììŽì ížë í륏íížìì ëê”Ź ìŽëŠ ëȘ©ëĄêłŒ íŽëč ì€ëȘ
ì ëłŒ ì ìì”ëë€.
+ë ë§ì ëê”Źê° ì¶ê°ë ìëĄ ììŽì ížê° ìŹë°ë„ž ëê”Źë„Œ ì ííêž°ê° ë ìŽë €ìì§êł ì€íí ëê”Źì ìŹë°ë„ž ìì넌 ì ííë êČì ëì± ìŽë €ìì§ëë€.
+ìŒë°ì ìž ì€íš ìŹëĄë„Œ ìŽíŽëłŽêČ ì”ëë€. ìŹêž°ìë ë¶ìí ìœëë§ ë°ííêČ ì”ëë€.
+
+```py
+from transformers import HfAgent
+
+agent = HfAgent("https://api-inference.huggingface.co/models/bigcode/starcoder")
+
+agent.run("Show me a tree", return_code=True)
+```
+
+ê·žëŹë©Ž ë€ì êČ°êłŒê° ì¶ë „ë©ëë€:
+
+```text
+==Explanation from the agent==
+I will use the following tool: `image_segmenter` to create a segmentation mask for the image.
+
+
+==Code generated by the agent==
+mask = image_segmenter(image, prompt="tree")
+```
+
+ì°ëŠŹê° ìíë êČ°êłŒê° ìë ìë ìì”ëë€. ëì ë돎 ìŽëŻžì§ê° ìì±ëꞰ넌 ìí ê°ë„ì±ìŽ ë ëì”ëë€.
+ë°ëŒì ììŽì ížê° íčì ëê”Źë„Œ ìŹì©íëëĄ ì ëíë €ë©Ž ëê”Źì ìŽëŠêłŒ ì€ëȘ
ì ìë ì€ìí í€ìë넌 ìŹì©íë êČìŽ ë§€ì° ì ì©í ì ìì”ëë€. íëČ ìŽíŽëłŽêČ ì”ëë€.
+```py
+agent.toolbox["image_generator"].description
+```
+
+```text
+'This is a tool that creates an image according to a prompt, which is a text description. It takes an input named `prompt` which contains the image description and outputs an image.
+```
+
+ìŽëŠêłŒ ì€ëȘ
ì "image", "prompt", "create" ë° "generate" í€ìë넌 ìŹì©í©ëë€. ìŽ ëšìŽë€ì ìŹì©í멎 ë ì ìëí ê°ë„ì±ìŽ ëì”ëë€. í륏íížë„Œ ìĄ°êž ë ê”ŹìČŽííŽ ëłŽêČ ì”ëë€.
+
+```py
+agent.run("Create an image of a tree", return_code=True)
+```
+
+ìŽ ìœëë ë€ì í륏íížë„Œ ë§ë€ìŽë
ëë€:
+```text
+==Explanation from the agent==
+I will use the following tool `image_generator` to generate an image of a tree.
+
+
+==Code generated by the agent==
+image = image_generator(prompt="tree")
+```
+
+íšìŹ ë«ë€ì! ì íŹê° ìíë êČêłŒ ëčì·íŽ ëłŽì
ëë€.
+ìŠ, ììŽì ížê° ìì
ì ìŹë°ë„ž ëê”Źì ìŹë°ë„ŽêČ ë§€ííë ë° ìŽë €ìì êČȘêł ìë€ë©Ž ëê”Ź ìŽëŠêłŒ ì€ëȘ
ìì ê°ì„ êŽë šì±ìŽ ëì í€ìë넌 ì°ŸìëłŽêł ìŽë„Œ í”íŽ ìì
ììČì ê”ŹìČŽííŽ ëłŽìžì.
+
+### ëê”Ź ì€ëȘ
ìŹì©ì ì ìíêž°[[customizing-the-tool-descriptions]]
+
+ìì ìŽíŽëłž êČìČëŒ ììŽì ížë ê° ëê”Źì ìŽëŠêłŒ ì€ëȘ
ì ìĄìžì€í ì ìì”ëë€.
+êž°ëłž ëê”Źìë ë§€ì° ì íí ìŽëŠêłŒ ì€ëȘ
ìŽ ììŽìŒ íì§ë§ íčì ìŹì© ìŹëĄì ë§êČ ëê”Źì ì€ëȘ
ìŽë ìŽëŠì ëłêČœíë êČìŽ ëììŽ ë ìë ìì”ëë€.
+ìŽë ë§€ì° ì ìŹí ìŹëŹ ëê”Źë„Œ ì¶ê°íê±°ë íčì ëë©ìž(*ì*: ìŽëŻžì§ ìì± ë° ëłí)ìë§ ììŽì ížë„Œ ìŹì©íë €ë êČœì°ì íčí ì€ìíŽì§ ì ìì”ëë€.
+
+ìŒë°ì ìž ëŹžì ë ìŽëŻžì§ ìì± ìì
ì ë§ìŽ ìŹì©ëë êČœì° ììŽì ížê° ìŽëŻžì§ ìì±êłŒ ìŽëŻžì§ ëłí/ìì ì íŒëíë êČì
ëë€. *ì넌 ë€ìŽ,*
+```py
+agent.run("Make an image of a house and a car", return_code=True)
+```
+ê·žëŹë©Ž ë€ì êČ°êłŒê° ì¶ë „ë©ëë€:
+```text
+==Explanation from the agent==
+I will use the following tools `image_generator` to generate an image of a house and `image_transformer` to transform the image of a car into the image of a house.
+
+==Code generated by the agent==
+house_image = image_generator(prompt="A house")
+car_image = image_generator(prompt="A car")
+house_car_image = image_transformer(image=car_image, prompt="A house")
+```
+
+êČ°êłŒëŹŒìŽ ì°ëŠŹê° ìŹêž°ì ìíë êČêłŒ ì íí ìŒìčíì§ ìì ì ìì”ëë€. ììŽì ížê° `image_generator`ì `image_transformer`ì ì°šìŽì ì ìŽíŽíêž° ìŽë €ìì ë ê°ì§ë„Œ íšê» ìŹì©íë êČœì°ê° ë§ì êČ ê°ì”ëë€.
+
+ìŹêž°ì `image_transformer`ì ëê”Ź ìŽëŠêłŒ ì€ëȘ
ì ëłêČœíìŹ ììŽì ížê° ëìž ì ìì”ëë€.
+"image" ë° "prompt"ì ìœê° ë¶ëŠŹíêž° ìíŽ `modifier`ëŒêł ëì ë¶ë„ŽêČ ì”ëë€:
+```py
+agent.toolbox["modifier"] = agent.toolbox.pop("image_transformer")
+agent.toolbox["modifier"].description = agent.toolbox["modifier"].description.replace(
+ "transforms an image according to a prompt", "modifies an image"
+)
+```
+
+ìŽì "modify"ì ì ìŽëŻžì§ íëĄìžì넌 ìŹì©íëŒë ê°ë „í ì ížìŽëŻëĄ ìì í륏íížì ëììŽ ë êČì
ëë€. ë€ì ì€ííŽ ëŽ
ìë€.
+
+```py
+agent.run("Make an image of a house and a car", return_code=True)
+```
+
+ìŹêž°ì ë€ìêłŒ ê°ì êČ°êłŒë„Œ ì»êČ ë©ëë€:
+```text
+==Explanation from the agent==
+I will use the following tools: `image_generator` to generate an image of a house, then `image_generator` to generate an image of a car.
+
+
+==Code generated by the agent==
+house_image = image_generator(prompt="A house")
+car_image = image_generator(prompt="A car")
+```
+
+ì°ëŠŹê° ìŒëì ëìë êČêłŒ íì€í ë ê°êčììĄì”ëë€! íì§ë§ ì§êłŒ ìëì°šê° ëȘšë ê°ì ìŽëŻžì§ì íŹíšë멎 ìąêČ ì”ëë€. ìì
ì ëšìŒ ìŽëŻžì§ ìì±ì ë ì§ì€í멎 ëììŽ ë êČì
ëë€:
+
+```py
+agent.run("Create image: 'A house and car'", return_code=True)
+```
+
+```text
+==Explanation from the agent==
+I will use the following tool: `image_generator` to generate an image.
+
+
+==Code generated by the agent==
+image = image_generator(prompt="A house and car")
+```
+
+
+
+ììŽì ížë ìŹì í íčí ìŹëŹ ê°ìČŽì ìŽëŻžì§ë„Œ ìì±íë êČêłŒ ê°ìŽ ìœê° ë ëł”ìĄí ìŹì© ìŹëĄìì ì·šìœí êČœì°ê° ë§ì”ëë€.
+ììŒëĄ ëȘ ëŹ ìì ììŽì íž ììČŽì êž°ëłž í륏íížê° ëì± ê°ì ëìŽ ììŽì ížê° ë€ìí ìŹì©ì ì
ë „ì ëì± ê°ë „íêČ ëìí ì ìëëĄ í ìì ì
ëë€.
+
+
+
+### ì ìČŽ í륏ííž ìŹì©ì ì ìíêž°[[customizing-the-whole-prompt]]
+
+ìŹì©ììêČ ì”ëíì ì ì°ì±ì ì êł”íêž° ìíŽ [ì](#structure-of-the-prompt)ì ì€ëȘ
ë ì ìČŽ í륏ííž í
í늿ì ìŹì©ìê° ëźìŽìž ì ìì”ëë€.
+ìŽ êČœì° ìŹì©ì ì ì í륏íížì ìê° ìčì
, ëê”Ź ìčì
, ìì ìčì
ë° ëŻžìì± ìì ìčì
ìŽ íŹíšëìŽ ìëì§ íìžíìžì.
+`run` í륏ííž í
í늿ì ëźìŽì°ë €ë©Ž ë€ìêłŒ ê°ìŽ í멎 ë©ëë€:
+
+```py
+template = """ [...] """
+
+agent = HfAgent(your_endpoint, run_prompt_template=template)
+```
+
+
+
+ììŽì ížê° ìŹì© ê°ë„í ëê”Źë„Œ ìžìíêł ìŹì©ìì í륏íížë„Œ ìŹë°ë„ŽêČ ìœì
í ì ìëëĄ `<>` 돞ììŽêłŒ `<>`넌 `template` ìŽëê°ì ì ìíŽìŒ í©ëë€.
+
+
+
+ë§ì°Źê°ì§ëĄ `chat` í륏ííž í
í늿ì ëźìŽìž ì ìì”ëë€. `chat` ëȘšëììë íì ë€ìêłŒ ê°ì ê”í íìì ìŹì©íë€ë ì ì ì ìíìžì:
+
+```text
+Human: <>
+
+Assistant:
+```
+
+ë°ëŒì ìŹì©ì ì ì `chat` í륏ííž í
í늿ì ìì ììë ìŽ íìì ìŹì©íë êČìŽ ì€ìí©ëë€.
+ë€ìêłŒ ê°ìŽ ìžì€íŽì€í í ë `chat` í
í늿ì ëźìŽìž ì ìì”ëë€.
+
+```
+template = """ [...] """
+
+agent = HfAgent(url_endpoint=your_endpoint, chat_prompt_template=template)
+```
+
+
+
+ììŽì ížê° ìŹì© ê°ë„í ëê”Źë„Œ ìžìí ì ìëëĄ `<>` 돞ììŽì `template` ìŽëê°ì ì ìíŽìŒ í©ëë€.
+
+
+
+ë êČœì° ëȘšë ì»€ëź€ëí°ì ëê”°ê°ê° ížì€í
íë í
í늿ì ìŹì©íë €ë êČœì° í륏ííž í
í늿 ëì ì ì„ì ID넌 ì ëŹí ì ìì”ëë€.
+êž°ëłž í륏íížë [ìŽ ì ì„ì](https://huggingface.co/datasets/huggingface-tools/default-prompts)넌 ìëĄ ë€ ì ìì”ëë€.
+
+Hubì ì ì„ìì ìŹì©ì ì ì í륏íížë„Œ ì
ëĄëíìŹ ì»€ëź€ëí°ì êł”ì íë €ë©Ž ë€ìì íìžíìžì:
+- ë°ìŽí° ìžíž ì ì„ì넌 ìŹì©íìžì.
+- `run` ëȘ
ë čì ëí í륏ííž í
í늿ì `run_prompt_template.txt`ëŒë íìŒì ëŁìŒìžì.
+- `chat` ëȘ
ë čì ëí í륏ííž í
í늿ì `chat_prompt_template.txt`ëŒë íìŒì ëŁìŒìžì.
+
+## ìŹì©ì ì ì ëê”Ź ìŹì©íêž°[[using-custom-tools]]
+
+ìŽ ìčì
ììë ìŽëŻžì§ ìì±ì íčíë ë ê°ì§ êž°ìĄŽ ìŹì©ì ì ì ëê”Źë„Œ íì©íêČ ì”ëë€:
+
+- ë ë§ì ìŽëŻžì§ ìì ì íì©íêž° ìíŽ [huggingface-tools/image-transformation](https://huggingface.co/spaces/huggingface-tools/image-transformation)ì
+ [diffusers/controlnet-canny-tool](https://huggingface.co/spaces/diffusers/controlnet-canny-tool)ëĄ ëìČŽí©ëë€.
+- êž°ëłž ëê”Ź ììì ìŽëŻžì§ ì
ì€ìŒìŒë§ì ìí ìëĄìŽ ëê”Źê° ì¶ê°ëìì”ëë€:
+ [diffusers/latent-upscaler-tool](https://huggingface.co/spaces/diffusers/latent-upscaler-tool)ê° êž°ìĄŽ ìŽëŻžì§ ëłí ëê”Źë„Œ ëìČŽí©ëë€.
+
+ížëŠŹí [`load_tool`] íšì넌 ìŹì©íìŹ ìŹì©ì ì ì ëê”Źë„Œ ê°ì žì€ë êČìŒëĄ ììíêČ ì”ëë€:
+
+```py
+from transformers import load_tool
+
+controlnet_transformer = load_tool("diffusers/controlnet-canny-tool")
+upscaler = load_tool("diffusers/latent-upscaler-tool")
+```
+
+ììŽì ížìêČ ìŹì©ì ì ì ëê”Źë„Œ ì¶ê°í멎 ëê”Źì ì€ëȘ
êłŒ ìŽëŠìŽ ììŽì ížì í륏íížì ìëìŒëĄ íŹíšë©ëë€.
+ë°ëŒì ììŽì ížê° ìŹì© ë°©ëČì ìŽíŽí ì ìëëĄ ìŹì©ì ì ì ëê”Źì ì€ëȘ
êłŒ ìŽëŠì ì ìì±íŽìŒ í©ëë€.
+`controlnet_transformer`ì ì€ëȘ
êłŒ ìŽëŠì ìŽíŽëłŽêČ ì”ëë€:
+
+```py
+print(f"Description: '{controlnet_transformer.description}'")
+print(f"Name: '{controlnet_transformer.name}'")
+```
+
+ê·žëŹë©Ž ë€ì êČ°êłŒê° ì¶ë „ë©ëë€:
+```text
+Description: 'This is a tool that transforms an image with ControlNet according to a prompt.
+It takes two inputs: `image`, which should be the image to transform, and `prompt`, which should be the prompt to use to change it. It returns the modified image.'
+Name: 'image_transformer'
+```
+
+ìŽëŠêłŒ ì€ëȘ
ìŽ ì ííêł [íë ìŽí
ë ëê”Ź ìžíž(curated set of tools)](./transformers_agents#a-curated-set-of-tools)ì ì€íìŒì ë§ì”ëë€.
+ë€ììŒëĄ, `controlnet_transformer`ì `upscaler`ëĄ ììŽì ížë„Œ ìžì€íŽì€ííŽ ëŽ
ìë€:
+```py
+tools = [controlnet_transformer, upscaler]
+agent = HfAgent("https://api-inference.huggingface.co/models/bigcode/starcoder", additional_tools=tools)
+```
+
+ìŽ ëȘ
ë čì ì€íí멎 ë€ì ì ëłŽê° íìë©ëë€:
+
+```text
+image_transformer has been replaced by as provided in `additional_tools`
+```
+
+íë ìŽí
ë ëê”Ź ìžížìë ìŽëŻž 'image_transformer' ëê”Źê° ììŒë©°, ìŽ ëê”Źë ìŹì©ì ì ì ëê”ŹëĄ ëìČŽë©ëë€.
+
+
+
+êž°ìĄŽ ëê”Źì ëê°ì ìì
ì ìŹì©ì ì ì ëê”Źë„Œ ìŹì©íë €ë êČœì° êž°ìĄŽ ëê”Źë„Œ ëźìŽì°ë êČìŽ ì ì©í ì ìì”ëë€.
+ììŽì ížê° íŽëč ìì
ì ë„ìíêž° ë돞ì
ëë€.
+ìŽ êČœì° ìŹì©ì ì ì ëê”Źê° ëźìŽìŽ ëê”Źì ì íí ëìŒí API넌 ë°ëŒìŒ íë©°, ê·žë ì§ ììŒë©Ž íŽëč ëê”Źë„Œ ìŹì©íë ëȘšë ìì ê° ì
ë°ìŽížëëëĄ í륏ííž í
í늿ì ìĄ°ì íŽìŒ íë€ë ì ì ì ìíìžì.
+
+
+
+ì
ì€ìŒìŒëŹ ëê”Źì ì§ì ë 'image_upscaler'ëŒë ìŽëŠ ìì§ êž°ëłž ëê”Ź ìììë ìĄŽìŹíì§ ìêž° ë돞ì, ëê”Ź ëȘ©ëĄì íŽëč ìŽëŠìŽ ê°ëší ì¶ê°ëìì”ëë€.
+ììŽì ížê° íìŹ ìŹì©í ì ìë ëê”Ź ììë ìžì ë ì§ `agent.toolbox` ìì±ì í”íŽ íìží ì ìì”ëë€:
+
+```py
+print("\n".join([f"- {a}" for a in agent.toolbox.keys()]))
+```
+
+```text
+- document_qa
+- image_captioner
+- image_qa
+- image_segmenter
+- transcriber
+- summarizer
+- text_classifier
+- text_qa
+- text_reader
+- translator
+- image_transformer
+- text_downloader
+- image_generator
+- video_generator
+- image_upscaler
+```
+
+ììŽì ížì ëê”Ź ììì `image_upscaler`ê° ì¶ê°ë ì ì ìŁŒëȘ©íìžì.
+
+ìŽì ìëĄìŽ ëê”Źë„Œ ìŹì©íŽëŽ
ìë€! [Transformers Agents Quickstart](./transformers_agents#single-execution-run)ìì ìì±í ìŽëŻžì§ë„Œ ë€ì ìŹì©íêČ ì”ëë€.
+
+```py
+from diffusers.utils import load_image
+
+image = load_image(
+ "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/rivers_and_lakes.png"
+)
+```
+
+
+
+ìŽëŻžì§ë„Œ ìëŠë€ìŽ êČšìž íêČœìŒëĄ ë°êż ëŽ
ìë€:
+
+```py
+image = agent.run("Transform the image: 'A frozen lake and snowy forest'", image=image)
+```
+
+```text
+==Explanation from the agent==
+I will use the following tool: `image_transformer` to transform the image.
+
+
+==Code generated by the agent==
+image = image_transformer(image, prompt="A frozen lake and snowy forest")
+```
+
+
+
+ìëĄìŽ ìŽëŻžì§ ìČ늏 ëê”Źë ìŽëŻžì§ë„Œ ë§€ì° ê°ë „íêČ ìì í ì ìë ControlNetì êž°ë°ìŒëĄ í©ëë€.
+êž°ëłžì ìŒëĄ ìŽëŻžì§ ìČ늏 ëê”Źë 512x512 íœì
íŹêž°ì ìŽëŻžì§ë„Œ ë°íí©ëë€. ìŽë„Œ ì
ì€ìŒìŒë§í ì ìëì§ ìŽíŽëŽ
ìë€.
+
+```py
+image = agent.run("Upscale the image", image)
+```
+
+```text
+==Explanation from the agent==
+I will use the following tool: `image_upscaler` to upscale the image.
+
+
+==Code generated by the agent==
+upscaled_image = image_upscaler(image)
+```
+
+
+
+ììŽì ížë ì
ì€ìŒìŒëŹ ëê”Źì ì€ëȘ
êłŒ ìŽëŠë§ ëłŽêł ë°©êž ì¶ê°í ì
ì€ìŒìŒëŹ ëê”Źì "ìŽëŻžì§ ì
ì€ìŒìŒë§"ìŽëŒë í륏íížë„Œ ìëìŒëĄ ë§€ííìŹ ìŹë°ë„ŽêČ ì€ííì”ëë€.
+
+ë€ììŒëĄ ì ìŹì©ì ì ì ëê”Źë„Œ ë§ëë ë°©ëČì ìŽíŽëłŽêČ ì”ëë€.
+
+### ì ëê”Ź ì¶ê°íêž°[[adding-new-tools]]
+
+ìŽ ìčì
ììë ììŽì ížìêČ ì¶ê°í ì ìë ì ëê”Źë„Œ ë§ëë ë°©ëČì ëłŽìŹ ë늜ëë€.
+
+#### ì ëê”Ź ë§ë€êž°[[creating-a-new-tool]]
+
+뚌ì ëê”Źë„Œ ë§ëë êČë¶í° ììíêČ ì”ëë€.
+íčì ìì
ì ëíŽ ê°ì„ ë§ì ë€ìŽëĄë넌 ë°ì Hugging Face Hubì ëȘšëžì ê°ì žì€ë, ê·žë€ì§ ì ì©íì§ë ìì§ë§ ìŹëŻžìë ìì
ì ì¶ê°íêČ ì”ëë€.
+
+ë€ì ìœë넌 ìŹì©í멎 ë©ëë€:
+
+```python
+from huggingface_hub import list_models
+
+task = "text-classification"
+
+model = next(iter(list_models(filter=task, sort="downloads", direction=-1)))
+print(model.id)
+```
+`text-classification`(í
ì€íž ë¶ë„) ìì
ì êČœì° `'facebook/bart-large-mnli'`넌 ë°ííêł , `translation`(ëČì) ìì
ì êČœì° `'t5-base'`넌 ë°íí©ëë€.
+
+ìŽë„Œ ììŽì ížê° íì©í ì ìë ëê”ŹëĄ ëłííë €ë©Ž ìŽë»êČ íŽìŒ í êčì?
+ëȘšë ëê”Źë íìí ìŁŒì ìì±ì 볎ì íë ìíŒíŽëì€ `Tool`ì ììĄŽí©ëë€. ìŽë„Œ ììíë íŽëì€ë„Œ ë§ë€ìŽ ëłŽêČ ì”ëë€:
+
+```python
+from transformers import Tool
+
+
+class HFModelDownloadsTool(Tool):
+ pass
+```
+
+ìŽ íŽëì€ìë ëȘ ê°ì§ ìê”ŹìŹíìŽ ìì”ëë€:
+- ëê”Ź ììČŽì ìŽëŠì íŽëčíë `name` ìì±. ìíëȘ
ìŽ ìë ë€ë„ž ëê”Źì ížíëëëĄ `model_download_counter`ëĄ ìŽëŠì ì§ì íêČ ì”ëë€.
+- ììŽì ížì í륏íížë„Œ ì±ì°ë ë° ìŹì©ëë ìì± `description`.
+- `inputs` ë° `outputs` ìì±. ìŽë„Œ ì ìí멎 Python ìží°í늏í°ê° ì íì ëí ì 볎ì ì
ê°í ì íì íë ë° ëììŽ ëë©°,
+ ëê”Źë„Œ íëžì ížìí ë gradio ë°ëȘšë„Œ ìì±í ì ìì”ëë€.
+ ë ìì± ëȘšë ê°ì 'í
ì€íž', 'ìŽëŻžì§' ëë 'ì€ëì€'ê° ë ì ìë ìì ê°ì 늏ì€ížì
ëë€.
+- ì¶ëĄ ìœëê° íŹíšë `__call__` ë©ìë. ìŽêČìŽ ì°ëŠŹê° ììì ë€ëŁšìë ìœëì
ëë€!
+
+ìŽì íŽëì€ì ëȘšì”ì ë€ìêłŒ ê°ì”ëë€:
+
+```python
+from transformers import Tool
+from huggingface_hub import list_models
+
+
+class HFModelDownloadsTool(Tool):
+ name = "model_download_counter"
+ description = (
+ "This is a tool that returns the most downloaded model of a given task on the Hugging Face Hub. "
+ "It takes the name of the category (such as text-classification, depth-estimation, etc), and "
+ "returns the name of the checkpoint."
+ )
+
+ inputs = ["text"]
+ outputs = ["text"]
+
+ def __call__(self, task: str):
+ model = next(iter(list_models(filter=task, sort="downloads", direction=-1)))
+ return model.id
+```
+
+ìŽì ëê”Źë„Œ ììœêČ ìŹì©í ì ìêČ ëìì”ëë€.
+ëê”Źë„Œ íìŒì ì ì„íêł ë©ìž ì€íŹëŠœížìì ê°ì žì”ëë€. ìŽ íìŒì ìŽëŠì `model_downloads.py`ëĄ ì§ì í멎 êČ°êłŒì ìŒëĄ ê°ì žì€êž° ìœëë ë€ìêłŒ ê°ì”ëë€:
+
+```python
+from model_downloads import HFModelDownloadsTool
+
+tool = HFModelDownloadsTool()
+```
+
+ë€ë„ž ìŹëë€ìŽ ìŽ êž°ë„ì íì©í ì ìëëĄ íêł ìŽêž°í넌 ë ê°ëšíêČ íë €ë©Ž ë€ìì€íìŽì€ ìëì HubëĄ ížìíë êČìŽ ìąì”ëë€.
+ê·žë êČ íë €ë©Ž `tool` ëłììì `push_to_hub`넌 ížì¶í멎 ë©ëë€:
+
+```python
+tool.push_to_hub("hf-model-downloads")
+```
+
+ìŽì íëžì ìœëê° ìêČŒì”ëë€! ë§ì§ë§ ëšêłìž ììŽì ížê° ìœë넌 ìŹì©íëëĄ íë ëšêłë„Œ ìŽíŽëłŽêČ ì”ëë€.
+
+#### ììŽì ížê° ëê”Źë„Œ ìŹì©íêČ íêž°[[Having-the-agent-use-the-tool]]
+
+ìŽì ìŽë° ììŒëĄ íëžì ìĄŽìŹíë ëê”Źë„Œ ìžì€íŽì€íí ì ìì”ëë€(ëê”Źì ìŹì©ì ìŽëŠì ëłêČœíìžì):
+We now have our tool that lives on the Hub which can be instantiated as such (change the user name for your tool):
+
+```python
+from transformers import load_tool
+
+tool = load_tool("lysandre/hf-model-downloads")
+```
+
+ìŽ ëê”Źë„Œ ììŽì ížìì ìŹì©íë €ë©Ž ììŽì íž ìŽêž°í ë©ìëì `additional_tools` ë§€ê°ëłìì ì ëŹíêž°ë§ í멎 ë©ëë€:
+
+```python
+from transformers import HfAgent
+
+agent = HfAgent("https://api-inference.huggingface.co/models/bigcode/starcoder", additional_tools=[tool])
+
+agent.run(
+ "Can you read out loud the name of the model that has the most downloads in the 'text-to-video' task on the Hugging Face Hub?"
+)
+```
+ê·žëŹë©Ž ë€ìêłŒ ê°ì êČ°êłŒê° ì¶ë „ë©ëë€:
+```text
+==Code generated by the agent==
+model = model_download_counter(task="text-to-video")
+print(f"The model with the most downloads is {model}.")
+audio_model = text_reader(model)
+
+
+==Result==
+The model with the most downloads is damo-vilab/text-to-video-ms-1.7b.
+```
+
+and generates the following audio.
+
+| **Audio** |
+|------------------------------------------------------------------------------------------------------------------------------------------------------|
+| |
+
+
+
+
+LLMì ë°ëŒ ìŒë¶ë ë§€ì° ì·šìœíêž° ë돞ì ì ëëĄ ìëíë €ë©Ž ë§€ì° ì íí í륏íížê° íìí©ëë€.
+ììŽì ížê° ëê”Źë„Œ ì íì©íêž° ìíŽìë ëê”Źì ìŽëŠêłŒ ì€ëȘ
ì ì ì ìíë êČìŽ ëŹŽìëłŽë€ ì€ìí©ëë€.
+
+
+
+### êž°ìĄŽ ëê”Ź ëìČŽíêž°[[replacing-existing-tools]]
+
+ììŽì ížì ëê”Ź ììì ì íëȘ©ì ë°°ì íêž°ë§ í멎 êž°ìĄŽ ëê”Źë„Œ ëìČŽí ì ìì”ëë€. ë°©ëČì ë€ìêłŒ ê°ì”ëë€:
+
+```python
+from transformers import HfAgent, load_tool
+
+agent = HfAgent("https://api-inference.huggingface.co/models/bigcode/starcoder")
+agent.toolbox["image-transformation"] = load_tool("diffusers/controlnet-canny-tool")
+```
+
+
+
+ë€ë„ž ëê”ŹëĄ ê”ìČŽí ëë ìŁŒìíìžì! ìŽ ìì
ìŒëĄ ììŽì ížì í륏íížë ìĄ°ì ë©ëë€.
+ìì
ì ë ì í©í í륏íížê° ììŒë©Ž ìąì ì ìì§ë§,
+ë€ë„ž ëê”ŹëłŽë€ ë ë§ìŽ ì íëê±°ë ì ìí ëê”Ź ëì ë€ë„ž ëê”Źê° ì íë ìë ìì”ëë€.
+
+
+
+## gradio-tools ìŹì©íêž°[[leveraging-gradio-tools]]
+
+[gradio-tools](https://github.com/freddyaboulton/gradio-tools)ë Hugging Face Spaces넌 ëê”ŹëĄ ìŹì©í ì ìë ê°ë „í ëŒìŽëžëŹëŠŹì
ëë€.
+êž°ìĄŽì ë§ì Spacesëżë§ ìëëŒ ìŹì©ì ì ì Spaces넌 ìŹì©íìŹ ëììží ì ìëëĄ ì§ìí©ëë€.
+
+ì°ëŠŹë `Tool.from_gradio` ë©ìë넌 ìŹì©íìŹ `gradio_tools`ì ëí ì§ìì ì êł”í©ëë€.
+ì넌 ë€ìŽ, í륏íížë„Œ ê°ì íêł ë ëì ìŽëŻžì§ë„Œ ìì±íêž° ìíŽ `gradio-tools` íŽí·ìì ì êł”ëë `StableDiffusionPromptGeneratorTool` ëê”Źë„Œ íì©íêł ì í©ëë€.
+
+뚌ì `gradio_tools`ìì ëê”Źë„Œ ê°ì žìì ìžì€íŽì€íí©ëë€:
+
+```python
+from gradio_tools import StableDiffusionPromptGeneratorTool
+
+gradio_tool = StableDiffusionPromptGeneratorTool()
+```
+
+íŽëč ìžì€íŽì€ë„Œ `Tool.from_gradio` ë©ìëì ì ëŹí©ëë€:
+
+```python
+from transformers import Tool
+
+tool = Tool.from_gradio(gradio_tool)
+```
+
+ìŽì ìŒë°ì ìž ìŹì©ì ì ì ëê”Źì ëê°ìŽ êŽëŠŹí ì ìì”ëë€.
+ìŽë„Œ íì©íìŹ `a rabbit wearing a space suit'(ì°ìŁŒëł”ì ì
ì í ëŒ)ëŒë í륏íížë„Œ ê°ì íì”ëë€:
+
+```python
+from transformers import HfAgent
+
+agent = HfAgent("https://api-inference.huggingface.co/models/bigcode/starcoder", additional_tools=[tool])
+
+agent.run("Generate an image of the `prompt` after improving it.", prompt="A rabbit wearing a space suit")
+```
+
+ëȘšëžìŽ ëê”Źë„Œ ì ì í íì©í©ëë€:
+```text
+==Explanation from the agent==
+I will use the following tools: `StableDiffusionPromptGenerator` to improve the prompt, then `image_generator` to generate an image according to the improved prompt.
+
+
+==Code generated by the agent==
+improved_prompt = StableDiffusionPromptGenerator(prompt)
+print(f"The improved prompt is {improved_prompt}.")
+image = image_generator(improved_prompt)
+```
+
+ë§ì§ë§ìŒëĄ ìŽëŻžì§ë„Œ ìì±íêž° ì ì:
+
+
+
+
+
+gradio-toolsë ë€ë„ž ëȘšëŹëŠŹí°ëĄ ìì
í ëìë *í
ì€íž* ì
ë „ ë° ì¶ë „ì íìëĄ í©ëë€.
+ìŽ ê”Źíì ìŽëŻžì§ ë° ì€ëì€ ê°ìČŽìì ìëí©ëë€.
+íìŹë ìŽ ë ê°ì§ê° ížíëì§ ìì§ë§ ì§ì ê°ì ì ìíŽ ë
žë „í멎ì ëč 넎êČ ížíë êČì
ëë€.
+
+
+
+## í„í LangchainêłŒì ížíì±[[future-compatibility-with-langchain]]
+
+ì íŹë Langchainì ìąìíë©° ë§€ì° ë§€ë „ì ìž ëê”Ź ëȘšìì ê°ì§êł ìë€êł ìê°í©ëë€.
+ìŽëŹí ëê”Źë„Œ ìČ늏íêž° ìíŽ Langchainì ë€ë„ž ëȘšëŹëŠŹí°ì ìì
í ëìë *í
ì€íž* ì
ë „êłŒ ì¶ë „ì íìëĄ í©ëë€.
+ìŽë ìą
ìą
ê°ìČŽì ì§ë Źíë(ìŠ, ëì€íŹì ì ì„ë) ëČì ì
ëë€.
+
+ìŽ ì°šìŽëĄ ìžíŽ transformers-agentsì Langchain ê°ìë ë©í° ëȘšëŹëŠŹí°ê° ìČ늏ëì§ ìì”ëë€.
+í„í ëČì ìì ìŽ ì íìŽ íŽêȰëꞰ넌 ë°ëŒë©°, ìŽ ížíì±ì ëŹì±í ì ìëëĄ ìŽë Źí Langchain ìŹì©ìì ëìì íìí©ëë€.
+
+ì íŹë ë ëì ì§ìì ì êł”íêł ì í©ëë€. ëìì ìŁŒêł ì¶ìŒìë€ë©Ž, [ìŽì넌 ìŽìŽ](https://github.com/huggingface/transformers/issues/new) ìêČŹì êł”ì íŽ ìŁŒìžì.
diff --git a/docs/source/ko/fast_tokenizers.md b/docs/source/ko/fast_tokenizers.md
new file mode 100644
index 000000000000..a6d1f14283bb
--- /dev/null
+++ b/docs/source/ko/fast_tokenizers.md
@@ -0,0 +1,71 @@
+
+
+# đ€ Tokenizers ëŒìŽëžëŹëŠŹì í íŹëìŽì ìŹì©íêž°[[use-tokenizers-from-tokenizers]]
+
+[`PreTrainedTokenizerFast`]ë [đ€ Tokenizers](https://huggingface.co/docs/tokenizers) ëŒìŽëžëŹëŠŹì êž°ë°í©ëë€. đ€ Tokenizers ëŒìŽëžëŹëŠŹì í íŹëìŽì ë
+đ€ TransformersëĄ ë§€ì° ê°ëšíêČ ë¶ëŹìŹ ì ìì”ëë€.
+
+ê”ŹìČŽì ìž ëŽì©ì ë€ìŽê°êž° ì ì, ëȘ ì€ì ìœëëĄ ë믞 í íŹëìŽì 넌 ë§ë€ìŽ ëłŽêČ ì”ëë€:
+
+```python
+>>> from tokenizers import Tokenizer
+>>> from tokenizers.models import BPE
+>>> from tokenizers.trainers import BpeTrainer
+>>> from tokenizers.pre_tokenizers import Whitespace
+
+>>> tokenizer = Tokenizer(BPE(unk_token="[UNK]"))
+>>> trainer = BpeTrainer(special_tokens=["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]"])
+
+>>> tokenizer.pre_tokenizer = Whitespace()
+>>> files = [...]
+>>> tokenizer.train(files, trainer)
+```
+
+ì°ëŠŹê° ì ìí íìŒì í”íŽ ìŽì íì”ë í íŹëìŽì 넌 ê°êČ ëìì”ëë€. ìŽ ë°íììì êłì ìŹì©íê±°ë JSON íìŒëĄ ì ì„íìŹ ëì€ì ìŹì©í ì ìì”ëë€.
+
+## í íŹëìŽì ê°ìČŽëĄë¶í° ì§ì ë¶ëŹì€êž°[[loading-directly-from-the-tokenizer-object]]
+
+đ€ Transformers ëŒìŽëžëŹëŠŹìì ìŽ í íŹëìŽì ê°ìČŽë„Œ íì©íë ë°©ëČì ìŽíŽëłŽêČ ì”ëë€.
+[`PreTrainedTokenizerFast`] íŽëì€ë ìžì€íŽì€íë *í íŹëìŽì * ê°ìČŽë„Œ ìžìëĄ ë°ì ìœêČ ìžì€íŽì€íí ì ìì”ëë€:
+
+```python
+>>> from transformers import PreTrainedTokenizerFast
+
+>>> fast_tokenizer = PreTrainedTokenizerFast(tokenizer_object=tokenizer)
+```
+
+ìŽì `fast_tokenizer` ê°ìČŽë đ€ Transformers í íŹëìŽì ìì êł”ì íë ëȘšë ë©ìëì íšê» ìŹì©í ì ìì”ëë€! ììží ëŽì©ì [í íŹëìŽì íìŽì§](main_classes/tokenizer)넌 ì°žìĄ°íìžì.
+
+## JSON íìŒìì ë¶ëŹì€êž°[[loading-from-a-JSON-file]]
+
+
+
+JSON íìŒìì í íŹëìŽì 넌 ë¶ëŹì€êž° ìíŽ, 뚌ì í íŹëìŽì 넌 ì ì„íŽ ëłŽêČ ì”ëë€:
+
+```python
+>>> tokenizer.save("tokenizer.json")
+```
+
+JSON íìŒì ì ì„í êČœëĄë `tokenizer_file` ë§€ê°ëłì넌 ìŹì©íìŹ [`PreTrainedTokenizerFast`] ìŽêž°í ë©ìëì ì ëŹí ì ìì”ëë€:
+
+```python
+>>> from transformers import PreTrainedTokenizerFast
+
+>>> fast_tokenizer = PreTrainedTokenizerFast(tokenizer_file="tokenizer.json")
+```
+
+ìŽì `fast_tokenizer` ê°ìČŽë đ€ Transformers í íŹëìŽì ìì êł”ì íë ëȘšë ë©ìëì íšê» ìŹì©í ì ìì”ëë€! ììží ëŽì©ì [í íŹëìŽì íìŽì§](main_classes/tokenizer)넌 ì°žìĄ°íìžì.
diff --git a/docs/source/ko/hpo_train.md b/docs/source/ko/hpo_train.md
new file mode 100644
index 000000000000..c7b25306930a
--- /dev/null
+++ b/docs/source/ko/hpo_train.md
@@ -0,0 +1,124 @@
+
+
+# Trainer API넌 ìŹì©í íìŽíŒíëŒëŻží° íì [[hyperparameter-search-using-trainer-api]]
+
+đ€ Transformersììë đ€ Transformers ëȘšëžì íì”ìí€ëë° ì”ì íë [`Trainer`] íŽëì€ë„Œ ì êł”íêž° ë돞ì, ìŹì©ìë ì§ì íë š 룚í넌 ìì±í íì ììŽ ëì± ê°ížíêČ íì”ì ìíŹ ì ìì”ëë€. ëí, [`Trainer`]ë íìŽíŒíëŒëŻží° íìì ìí API넌 ì êł”í©ëë€. ìŽ ëŹžììì ìŽ API넌 íì©íë ë°©ëČì ììì íšê» 볎ìŹë늏êČ ì”ëë€.
+
+## íìŽíŒíëŒëŻží° íì ë°±ìë [[hyperparameter-search-backend]]
+
+[`Trainer`]ë íìŹ ìë 4ê°ì§ íìŽíŒíëŒëŻží° íì ë°±ìë넌 ì§ìí©ëë€:
+[optuna](https://optuna.org/)ì [sigopt](https://sigopt.com/), [raytune](https://docs.ray.io/en/latest/tune/index.html), [wandb](https://wandb.ai/site/sweeps) ì
ëë€.
+
+íìŽíŒíëŒëŻží° íì ë°±ìëëĄ ìŹì©íêž° ì ì ìëì ëȘ
ë čìŽë„Œ ìŹì©íìŹ ëŒìŽëžëŹëŠŹë€ì ì€ìčíìžì.
+```bash
+pip install optuna/sigopt/wandb/ray[tune]
+```
+
+## ìì ìì íìŽíŒíëŒëŻží° íìì íì±ííë ë°©ëČ [[how-to-enable-hyperparameter-search-in-example]]
+
+íìŽíŒíëŒëŻží° íì êł”ê°ì ì ìíìžì. íìŽíŒíëŒëŻží° íì ë°±ìëë§ë€ ìëĄ ë€ë„ž íììŽ íìí©ëë€.
+
+sigoptì êČœì°, íŽëč [object_parameter](https://docs.sigopt.com/ai-module-api-references/api_reference/objects/object_parameter) 돞ì넌 ì°žìĄ°íìŹ ìëì ê°ìŽ ìì±íìžì:
+```py
+>>> def sigopt_hp_space(trial):
+... return [
+... {"bounds": {"min": 1e-6, "max": 1e-4}, "name": "learning_rate", "type": "double"},
+... {
+... "categorical_values": ["16", "32", "64", "128"],
+... "name": "per_device_train_batch_size",
+... "type": "categorical",
+... },
+... ]
+```
+
+optunaì êČœì°, íŽëč [object_parameter](https://optuna.readthedocs.io/en/stable/tutorial/10_key_features/002_configurations.html#sphx-glr-tutorial-10-key-features-002-configurations-py) 돞ì넌 ì°žìĄ°íìŹ ìëì ê°ìŽ ìì±íìžì:
+
+```py
+>>> def optuna_hp_space(trial):
+... return {
+... "learning_rate": trial.suggest_float("learning_rate", 1e-6, 1e-4, log=True),
+... "per_device_train_batch_size": trial.suggest_categorical("per_device_train_batch_size", [16, 32, 64, 128]),
+... }
+```
+
+raytuneì êČœì°, íŽëč [object_parameter](https://docs.ray.io/en/latest/tune/api/search_space.html) 돞ì넌 ì°žìĄ°íìŹ ìëì ê°ìŽ ìì±íìžì:
+
+```py
+>>> def ray_hp_space(trial):
+... return {
+... "learning_rate": tune.loguniform(1e-6, 1e-4),
+... "per_device_train_batch_size": tune.choice([16, 32, 64, 128]),
+... }
+```
+
+wandbì êČœì°, íŽëč [object_parameter](https://docs.wandb.ai/guides/sweeps/configuration) 돞ì넌 ì°žìĄ°íìŹ ìëì ê°ìŽ ìì±íìžì:
+
+```py
+>>> def wandb_hp_space(trial):
+... return {
+... "method": "random",
+... "metric": {"name": "objective", "goal": "minimize"},
+... "parameters": {
+... "learning_rate": {"distribution": "uniform", "min": 1e-6, "max": 1e-4},
+... "per_device_train_batch_size": {"values": [16, 32, 64, 128]},
+... },
+... }
+```
+
+`model_init` íšì넌 ì ìíêł ìŽë„Œ [`Trainer`]ì ì ëŹíìžì. ìëë ê·ž ììì
ëë€.
+```py
+>>> def model_init(trial):
+... return AutoModelForSequenceClassification.from_pretrained(
+... model_args.model_name_or_path,
+... from_tf=bool(".ckpt" in model_args.model_name_or_path),
+... config=config,
+... cache_dir=model_args.cache_dir,
+... revision=model_args.model_revision,
+... use_auth_token=True if model_args.use_auth_token else None,
+... )
+```
+
+ìëì ê°ìŽ `model_init` íšì, íë š ìžì, íë š ë° í
ì€íž ë°ìŽí°ì
, ê·žëŠŹêł íê° íšì넌 ìŹì©íìŹ [`Trainer`]넌 ìì±íìžì:
+
+```py
+>>> trainer = Trainer(
+... model=None,
+... args=training_args,
+... train_dataset=small_train_dataset,
+... eval_dataset=small_eval_dataset,
+... compute_metrics=compute_metrics,
+... tokenizer=tokenizer,
+... model_init=model_init,
+... data_collator=data_collator,
+... )
+```
+
+íìŽíŒíëŒëŻží° íìì ížì¶íêł , ì”ì ì ìí ë§€ê°ëłì넌 ê°ì žì€ìžì. ë°±ìëë `"optuna"`/`"sigopt"`/`"wandb"`/`"ray"` ì€ìì ì íí ì ìì”ëë€. ë°©í„ì `"minimize"` ëë `"maximize"` ì€ ì ííë©°, ëȘ©í넌 ì”ìíí êČìžì§ ì”ëíí êČìžì§ë„Œ êȰì í©ëë€.
+
+ìì ë§ì compute_objective íšì넌 ì ìí ì ìì”ëë€. ë§ìœ ìŽ íšì넌 ì ìíì§ ììŒë©Ž, êž°ëłž compute_objectiveê° ížì¶ëêł , f1êłŒ ê°ì íê° ì§íì í©ìŽ ëȘ©íŻê°ìŒëĄ ë°íë©ëë€.
+
+```py
+>>> best_trial = trainer.hyperparameter_search(
+... direction="maximize",
+... backend="optuna",
+... hp_space=optuna_hp_space,
+... n_trials=20,
+... compute_objective=compute_objective,
+... )
+```
+
+## DDP ëŻžìž ìĄ°ì ì ìí íìŽíŒíëŒëŻží° íì [[hyperparameter-search-for-ddp-finetune]]
+íìŹ, DDP(Distributed Data Parallelism; ë¶ì° ë°ìŽí° ëłë ŹìČ늏)넌 ìí íìŽíŒíëŒëŻží° íìì optunaì sigoptìì ê°ë„í©ëë€. ì”ìì íëĄìžì€ê° íìŽíŒíëŒëŻží° íì êłŒì ì ììíêł ê·ž êČ°êłŒë„Œ ë€ë„ž íëĄìžì€ì ì ëŹí©ëë€.
diff --git a/docs/source/ko/in_translation.md b/docs/source/ko/in_translation.md
new file mode 100644
index 000000000000..61ff1426a452
--- /dev/null
+++ b/docs/source/ko/in_translation.md
@@ -0,0 +1,5 @@
+
+
+# ìŽìŹí ëČì ì€ì
ëë€. ìĄ°êž ìŽë° ë§ëì!
\ No newline at end of file
diff --git a/docs/source/ko/in_translation.mdx b/docs/source/ko/in_translation.mdx
deleted file mode 100644
index ead906183348..000000000000
--- a/docs/source/ko/in_translation.mdx
+++ /dev/null
@@ -1 +0,0 @@
-# ìŽìŹí ëČì ì€ì
ëë€. ìĄ°êž ìŽë° ë§ëì!
\ No newline at end of file
diff --git a/docs/source/ko/index.md b/docs/source/ko/index.md
new file mode 100644
index 000000000000..f0ec9ae1b8b9
--- /dev/null
+++ b/docs/source/ko/index.md
@@ -0,0 +1,362 @@
+
+
+# đ€ Transformers
+
+[PyTorch](https://pytorch.org/), [TensorFlow](https://www.tensorflow.org/), [JAX](https://jax.readthedocs.io/en/latest/)넌 ìí ì”ìČšëš ëšžì ëŹë
+
+đ€ Transformersë ìŹì íì”ë ì”ìČšëš ëȘšëžë€ì ìœêČ ë€ìŽëĄëíêł íë šìíŹ ì ìë APIì ëê”Źë„Œ ì êł”í©ëë€. ìŹì íì”ë ëȘšëžì ì°ë©Ž 컎íší
ëčì©êłŒ íì ë°°ì¶ëìŽ ì€êł , ëȘšëžì ìČìë¶í° íë šìí€ë ë° íìí ìê°êłŒ 늏ìì€ë„Œ ì ìœí ì ìì”ëë€. ì íŹ ëȘšëžë€ì ë€ìí ë¶ìŒì íì€íŹë„Œ ì§ìí©ëë€.
+
+đ **ìì°ìŽ ìČ늏**: í
ì€íž ë¶ë„, ê°ìČŽëȘ
ìžì, ì§ììë”, ìžìŽ ëȘšëžë§, ììœ, ëČì, ê°êŽì ì§ììë”, í
ì€íž ìì±
+đŒïž **컎íší° ëčì **: ìŽëŻžì§ ë¶ë„, ê°ìČŽ íì§, ê°ìČŽ ë¶í
+đŁïž **ì€ëì€**: ìëìì±ìžì, ì€ëì€ ë¶ë„
+đ **ë©í°ëȘšëŹ**: í ì§ììë”, êŽí 돞ì ìžì (OCR), ì€ìșí 돞ììì ì 볎 ì¶ì¶, ëčëì€ ë¶ë„, ìê° ì§ììë”
+
+đ€ Transformersë PyTorch, TensorFlowì JAX ê°ì ìížìŽì©ì±ì ì§ìí©ëë€. ì ì°íêČ ëȘšëžì ê° ëšêłë§ë€ ë€ë„ž íë ììíŹë„Œ ìŹì©í ìë ìì”ëë€. ì넌 ë€ìŽ ìœë 3ì€ë§ ìšì ëȘšëžì íë šìíš ë€ì, ë€ë„ž íë ììíŹ ììì ì¶ëĄ í ì ìì”ëë€. ëȘšëžì ìŽì íêČœì ë°°íŹíêž° ìíŽ ONNXë TorchScript íììŒëĄ ëŽëłŽëŒ ìë ìì”ëë€.
+
+ì»€ëź€ëí°ì ì°žìŹíìë €ë©Ž [Hub](https://huggingface.co/models), [íŹëŒ](https://discuss.huggingface.co/), [ëì€ìœë](https://discord.com/invite/JfAtkvEtRb)넌 방돞íŽìŁŒìžì!
+
+## Hugging Face íêłŒ ì§ì ëííêł ì¶ìŒì ê°ì?[[hugging-face-team]]
+
+
+
+
+
+## ìœí
ìž [[contents]]
+
+ì íŹ êž°ì 돞ìë íŹêČ 5ê° ìčì
ìŒëĄ ëë ì ìì”ëë€:
+
+- **ììíêž°**ìì ëŒìŽëžëŹëŠŹë„Œ ê°ëší íìŽëłŽêł , ëłžêČ©ì ìŒëĄ ë°ìŽë€ ì ìêČ ì€ìč ë°©ëČì ìëŽí©ëë€.
+- **íí 늏ìŒ**ìì ëŒìŽëžëŹëŠŹì ì”ìíŽì§ ì ìëëĄ ììžíêł ë ìœêČ êž°ëłžì ìž ë¶ë¶ì ìëŽí©ëë€.
+- **How-to ê°ìŽë**ìì ìžìŽ ëȘšëžë§ì ìíŽ ìŹì íì”ë ëȘšëžì íìž íëíë ë°©ëČìŽë, ì§ì ëȘšëžì ìì±íêł êł”ì íë ë°©ëČêłŒ ê°ìŽ íčì ëȘ©í넌 ëŹì±íë ë°©ëČì ìëŽí©ëë€.
+- **ê°ë
ê°ìŽë**ìì đ€ Transformersì ì€êł ìČ íêłŒ íšê» ëȘšëžìŽë íì€íŹ ë€ì ìšêČšì§ ê°ë
ë€êłŒ ììŽëìŽë„Œ íê”Źíêł ì€ëȘ
ì ë§ë¶ì
ëë€.
+- **API**ìì ëȘšë íŽëì€ì íšì넌 ì€ëȘ
í©ëë€.
+
+ - **ë©ìž íŽëì€**ìì configuration, model, tokenizer, pipelineêłŒ ê°ìŽ ì ìŒ ì€ìí íŽëì€ë€ì ììží ì€ëȘ
í©ëë€.
+ - **ëȘšëž**ìì ëŒìŽëžëŹëŠŹ ì ê”Źíë ê° ëȘšëžêłŒ ì°êŽë íŽëì€ì íšì넌 ììží ì€ëȘ
í©ëë€.
+ - **ëŽë¶ ì ížëŠŹí°**ìì ëŽë¶ì ìŒëĄ ìŹì©ëë ì ížëŠŹí° íŽëì€ì íšì넌 ììží ì€ëȘ
í©ëë€.
+
+### ì§ì ëȘšëž[[supported-models]]
+
+
+
+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://arxiv.org/abs/1909.11942), by Zhenzhong Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.
+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://arxiv.org/abs/1910.13461) by Mike Lewis, Yinhan Liu, Naman Goyal, Marjan Ghazvininejad, Abdelrahman Mohamed, Omer Levy, Ves Stoyanov and Luke Zettlemoyer.
+1. **[BARThez](model_doc/barthez)** (from Ăcole polytechnique) released with the paper [BARThez: a Skilled Pretrained French Sequence-to-Sequence Model](https://arxiv.org/abs/2010.12321) by Moussa Kamal Eddine, Antoine J.-P. Tixier, Michalis Vazirgiannis.
+1. **[BARTpho](model_doc/bartpho)** (from VinAI Research) released with the paper [BARTpho: Pre-trained Sequence-to-Sequence Models for Vietnamese](https://arxiv.org/abs/2109.09701) by Nguyen Luong Tran, Duong Minh Le and Dat Quoc Nguyen.
+1. **[BEiT](model_doc/beit)** (from Microsoft) released with the paper [BEiT: BERT Pre-Training of Image Transformers](https://arxiv.org/abs/2106.08254) by Hangbo Bao, Li Dong, Furu Wei.
+1. **[BERT](model_doc/bert)** (from Google) released with the paper [BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding](https://arxiv.org/abs/1810.04805) by Jacob Devlin, Ming-Wei Chang, Kenton Lee and Kristina Toutanova.
+1. **[BERT For Sequence Generation](model_doc/bert-generation)** (from Google) released with the paper [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://arxiv.org/abs/1907.12461) by Sascha Rothe, Shashi Narayan, Aliaksei Severyn.
+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.
+1. **[BigBird-Pegasus](model_doc/bigbird_pegasus)** (from Google Research) released with the paper [Big Bird: Transformers for Longer Sequences](https://arxiv.org/abs/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.
+1. **[BigBird-RoBERTa](model_doc/big_bird)** (from Google Research) released with the paper [Big Bird: Transformers for Longer Sequences](https://arxiv.org/abs/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.
+1. **[Blenderbot](model_doc/blenderbot)** (from Facebook) released with the paper [Recipes for building an open-domain chatbot](https://arxiv.org/abs/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.
+1. **[BlenderbotSmall](model_doc/blenderbot-small)** (from Facebook) released with the paper [Recipes for building an open-domain chatbot](https://arxiv.org/abs/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.
+1. **[BLOOM](model_doc/bloom)** (from BigScience workshop) released by the [BigScience Workshop](https://bigscience.huggingface.co/).
+1. **[BORT](model_doc/bort)** (from Alexa) released with the paper [Optimal Subarchitecture Extraction For BERT](https://arxiv.org/abs/2010.10499) by Adrian de Wynter and Daniel J. Perry.
+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://arxiv.org/abs/2105.13626) by Linting Xue, Aditya Barua, Noah Constant, Rami Al-Rfou, Sharan Narang, Mihir Kale, Adam Roberts, Colin Raffel.
+1. **[CamemBERT](model_doc/camembert)** (from Inria/Facebook/Sorbonne) released with the paper [CamemBERT: a Tasty French Language Model](https://arxiv.org/abs/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.
+1. **[CANINE](model_doc/canine)** (from Google Research) released with the paper [CANINE: Pre-training an Efficient Tokenization-Free Encoder for Language Representation](https://arxiv.org/abs/2103.06874) by Jonathan H. Clark, Dan Garrette, Iulia Turc, John Wieting.
+1. **[CLIP](model_doc/clip)** (from OpenAI) released with the paper [Learning Transferable Visual Models From Natural Language Supervision](https://arxiv.org/abs/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.
+1. **[CLIPSeg](model_doc/clipseg)** (from University of Göttingen) released with the paper [Image Segmentation Using Text and Image Prompts](https://arxiv.org/abs/2112.10003) by Timo LĂŒddecke and Alexander Ecker.
+1. **[CodeGen](model_doc/codegen)** (from Salesforce) released with the paper [A Conversational Paradigm for Program Synthesis](https://arxiv.org/abs/2203.13474) by Erik Nijkamp, Bo Pang, Hiroaki Hayashi, Lifu Tu, Huan Wang, Yingbo Zhou, Silvio Savarese, Caiming Xiong.
+1. **[Conditional DETR](model_doc/conditional_detr)** (from Microsoft Research Asia) released with the paper [Conditional DETR for Fast Training Convergence](https://arxiv.org/abs/2108.06152) by Depu Meng, Xiaokang Chen, Zejia Fan, Gang Zeng, Houqiang Li, Yuhui Yuan, Lei Sun, Jingdong Wang.
+1. **[ConvBERT](model_doc/convbert)** (from YituTech) released with the paper [ConvBERT: Improving BERT with Span-based Dynamic Convolution](https://arxiv.org/abs/2008.02496) by Zihang Jiang, Weihao Yu, Daquan Zhou, Yunpeng Chen, Jiashi Feng, Shuicheng Yan.
+1. **[ConvNeXT](model_doc/convnext)** (from Facebook AI) released with the paper [A ConvNet for the 2020s](https://arxiv.org/abs/2201.03545) by Zhuang Liu, Hanzi Mao, Chao-Yuan Wu, Christoph Feichtenhofer, Trevor Darrell, Saining Xie.
+1. **[ConvNeXTV2](model_doc/convnextv2)** (from Facebook AI) released with the paper [ConvNeXt V2: Co-designing and Scaling ConvNets with Masked Autoencoders](https://arxiv.org/abs/2301.00808) by Sanghyun Woo, Shoubhik Debnath, Ronghang Hu, Xinlei Chen, Zhuang Liu, In So Kweon, Saining Xie.
+1. **[CPM](model_doc/cpm)** (from Tsinghua University) released with the paper [CPM: A Large-scale Generative Chinese Pre-trained Language Model](https://arxiv.org/abs/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.
+1. **[CTRL](model_doc/ctrl)** (from Salesforce) released with the paper [CTRL: A Conditional Transformer Language Model for Controllable Generation](https://arxiv.org/abs/1909.05858) by Nitish Shirish Keskar*, Bryan McCann*, Lav R. Varshney, Caiming Xiong and Richard Socher.
+1. **[CvT](model_doc/cvt)** (from Microsoft) released with the paper [CvT: Introducing Convolutions to Vision Transformers](https://arxiv.org/abs/2103.15808) by Haiping Wu, Bin Xiao, Noel Codella, Mengchen Liu, Xiyang Dai, Lu Yuan, Lei Zhang.
+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://arxiv.org/abs/2202.03555) by Alexei Baevski, Wei-Ning Hsu, Qiantong Xu, Arun Babu, Jiatao Gu, Michael Auli.
+1. **[DeBERTa](model_doc/deberta)** (from Microsoft) released with the paper [DeBERTa: Decoding-enhanced BERT with Disentangled Attention](https://arxiv.org/abs/2006.03654) by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen.
+1. **[DeBERTa-v2](model_doc/deberta-v2)** (from Microsoft) released with the paper [DeBERTa: Decoding-enhanced BERT with Disentangled Attention](https://arxiv.org/abs/2006.03654) by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen.
+1. **[Decision Transformer](model_doc/decision_transformer)** (from Berkeley/Facebook/Google) released with the paper [Decision Transformer: Reinforcement Learning via Sequence Modeling](https://arxiv.org/abs/2106.01345) by Lili Chen, Kevin Lu, Aravind Rajeswaran, Kimin Lee, Aditya Grover, Michael Laskin, Pieter Abbeel, Aravind Srinivas, Igor Mordatch.
+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://arxiv.org/abs/2010.04159) by Xizhou Zhu, Weijie Su, Lewei Lu, Bin Li, Xiaogang Wang, Jifeng Dai.
+1. **[DeiT](model_doc/deit)** (from Facebook) released with the paper [Training data-efficient image transformers & distillation through attention](https://arxiv.org/abs/2012.12877) by Hugo Touvron, Matthieu Cord, Matthijs Douze, Francisco Massa, Alexandre Sablayrolles, Hervé Jégou.
+1. **[DETR](model_doc/detr)** (from Facebook) released with the paper [End-to-End Object Detection with Transformers](https://arxiv.org/abs/2005.12872) by Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov, Sergey Zagoruyko.
+1. **[DialoGPT](model_doc/dialogpt)** (from Microsoft Research) released with the paper [DialoGPT: Large-Scale Generative Pre-training for Conversational Response Generation](https://arxiv.org/abs/1911.00536) by Yizhe Zhang, Siqi Sun, Michel Galley, Yen-Chun Chen, Chris Brockett, Xiang Gao, Jianfeng Gao, Jingjing Liu, Bill Dolan.
+1. **[DistilBERT](model_doc/distilbert)** (from HuggingFace), released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter](https://arxiv.org/abs/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/tree/main/examples/research_projects/distillation), RoBERTa into [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/research_projects/distillation), Multilingual BERT into [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/research_projects/distillation) and a German version of DistilBERT.
+1. **[DiT](model_doc/dit)** (from Microsoft Research) released with the paper [DiT: Self-supervised Pre-training for Document Image Transformer](https://arxiv.org/abs/2203.02378) by Junlong Li, Yiheng Xu, Tengchao Lv, Lei Cui, Cha Zhang, Furu Wei.
+1. **[Donut](model_doc/donut)** (from NAVER), released together with the paper [OCR-free Document Understanding Transformer](https://arxiv.org/abs/2111.15664) by Geewook Kim, Teakgyu Hong, Moonbin Yim, Jeongyeon Nam, Jinyoung Park, Jinyeong Yim, Wonseok Hwang, Sangdoo Yun, Dongyoon Han, Seunghyun Park.
+1. **[DPR](model_doc/dpr)** (from Facebook) released with the paper [Dense Passage Retrieval for Open-Domain Question Answering](https://arxiv.org/abs/2004.04906) by Vladimir Karpukhin, Barlas OÄuz, Sewon Min, Patrick Lewis, Ledell Wu, Sergey Edunov, Danqi Chen, and Wen-tau Yih.
+1. **[DPT](master/model_doc/dpt)** (from Intel Labs) released with the paper [Vision Transformers for Dense Prediction](https://arxiv.org/abs/2103.13413) by René Ranftl, Alexey Bochkovskiy, Vladlen Koltun.
+1. **[EfficientNet](model_doc/efficientnet)** (from Google Research) released with the paper [EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks](https://arxiv.org/abs/1905.11946) by Mingxing Tan and Quoc V. Le.
+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://arxiv.org/abs/2003.10555) by Kevin Clark, Minh-Thang Luong, Quoc V. Le, Christopher D. Manning.
+1. **[EncoderDecoder](model_doc/encoder-decoder)** (from Google Research) released with the paper [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://arxiv.org/abs/1907.12461) by Sascha Rothe, Shashi Narayan, Aliaksei Severyn.
+1. **[ERNIE](model_doc/ernie)** (from Baidu) released with the paper [ERNIE: Enhanced Representation through Knowledge Integration](https://arxiv.org/abs/1904.09223) by Yu Sun, Shuohuan Wang, Yukun Li, Shikun Feng, Xuyi Chen, Han Zhang, Xin Tian, Danxiang Zhu, Hao Tian, Hua Wu.
+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.
+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
+1. **[FlauBERT](model_doc/flaubert)** (from CNRS) released with the paper [FlauBERT: Unsupervised Language Model Pre-training for French](https://arxiv.org/abs/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.
+1. **[FLAVA](model_doc/flava)** (from Facebook AI) released with the paper [FLAVA: A Foundational Language And Vision Alignment Model](https://arxiv.org/abs/2112.04482) by Amanpreet Singh, Ronghang Hu, Vedanuj Goswami, Guillaume Couairon, Wojciech Galuba, Marcus Rohrbach, and Douwe Kiela.
+1. **[FNet](model_doc/fnet)** (from Google Research) released with the paper [FNet: Mixing Tokens with Fourier Transforms](https://arxiv.org/abs/2105.03824) by James Lee-Thorp, Joshua Ainslie, Ilya Eckstein, Santiago Ontanon.
+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://arxiv.org/abs/2006.03236) by Zihang Dai, Guokun Lai, Yiming Yang, Quoc V. Le.
+1. **[GLPN](model_doc/glpn)** (from KAIST) released with the paper [Global-Local Path Networks for Monocular Depth Estimation with Vertical CutDepth](https://arxiv.org/abs/2201.07436) by Doyeon Kim, Woonghyun Ga, Pyungwhan Ahn, Donggyu Joo, Sehwan Chun, Junmo Kim.
+1. **[GPT](model_doc/openai-gpt)** (from OpenAI) released with the paper [Improving Language Understanding by Generative Pre-Training](https://blog.openai.com/language-unsupervised/) by Alec Radford, Karthik Narasimhan, Tim Salimans and Ilya Sutskever.
+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.
+1. **[GPT NeoX](model_doc/gpt_neox)** (from EleutherAI) released with the paper [GPT-NeoX-20B: An Open-Source Autoregressive Language Model](https://arxiv.org/abs/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
+1. **[GPT NeoX Japanese](model_doc/gpt_neox_japanese)** (from ABEJA) released by Shinya Otani, Takayoshi Makabe, Anuj Arora, and Kyo Hattori.
+1. **[GPT-2](model_doc/gpt2)** (from OpenAI) released with the paper [Language Models are Unsupervised Multitask Learners](https://blog.openai.com/better-language-models/) by Alec Radford*, Jeffrey Wu*, Rewon Child, David Luan, Dario Amodei** and Ilya Sutskever**.
+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.
+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).
+1. **[GroupViT](model_doc/groupvit)** (from UCSD, NVIDIA) released with the paper [GroupViT: Semantic Segmentation Emerges from Text Supervision](https://arxiv.org/abs/2202.11094) by Jiarui Xu, Shalini De Mello, Sifei Liu, Wonmin Byeon, Thomas Breuel, Jan Kautz, Xiaolong Wang.
+1. **[Hubert](model_doc/hubert)** (from Facebook) released with the paper [HuBERT: Self-Supervised Speech Representation Learning by Masked Prediction of Hidden Units](https://arxiv.org/abs/2106.07447) by Wei-Ning Hsu, Benjamin Bolte, Yao-Hung Hubert Tsai, Kushal Lakhotia, Ruslan Salakhutdinov, Abdelrahman Mohamed.
+1. **[I-BERT](model_doc/ibert)** (from Berkeley) released with the paper [I-BERT: Integer-only BERT Quantization](https://arxiv.org/abs/2101.01321) by Sehoon Kim, Amir Gholami, Zhewei Yao, Michael W. Mahoney, Kurt Keutzer.
+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.
+1. **[Jukebox](model_doc/jukebox)** (from OpenAI) released with the paper [Jukebox: A Generative Model for Music](https://arxiv.org/pdf/2005.00341.pdf) by Prafulla Dhariwal, Heewoo Jun, Christine Payne, Jong Wook Kim, Alec Radford, Ilya Sutskever.
+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://arxiv.org/abs/1912.13318) by Yiheng Xu, Minghao Li, Lei Cui, Shaohan Huang, Furu Wei, Ming Zhou.
+1. **[LayoutLMv2](model_doc/layoutlmv2)** (from Microsoft Research Asia) released with the paper [LayoutLMv2: Multi-modal Pre-training for Visually-Rich Document Understanding](https://arxiv.org/abs/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.
+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://arxiv.org/abs/2204.08387) by Yupan Huang, Tengchao Lv, Lei Cui, Yutong Lu, Furu Wei.
+1. **[LayoutXLM](model_doc/layoutxlm)** (from Microsoft Research Asia) released with the paper [LayoutXLM: Multimodal Pre-training for Multilingual Visually-rich Document Understanding](https://arxiv.org/abs/2104.08836) by Yiheng Xu, Tengchao Lv, Lei Cui, Guoxin Wang, Yijuan Lu, Dinei Florencio, Cha Zhang, Furu Wei.
+1. **[LED](model_doc/led)** (from AllenAI) released with the paper [Longformer: The Long-Document Transformer](https://arxiv.org/abs/2004.05150) by Iz Beltagy, Matthew E. Peters, Arman Cohan.
+1. **[LeViT](model_doc/levit)** (from Meta AI) released with the paper [LeViT: A Vision Transformer in ConvNet's Clothing for Faster Inference](https://arxiv.org/abs/2104.01136) by Ben Graham, Alaaeldin El-Nouby, Hugo Touvron, Pierre Stock, Armand Joulin, Hervé Jégou, Matthijs Douze.
+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://arxiv.org/abs/2202.13669) by Jiapeng Wang, Lianwen Jin, Kai Ding.
+1. **[Longformer](model_doc/longformer)** (from AllenAI) released with the paper [Longformer: The Long-Document Transformer](https://arxiv.org/abs/2004.05150) by Iz Beltagy, Matthew E. Peters, Arman Cohan.
+1. **[LongT5](model_doc/longt5)** (from Google AI) released with the paper [LongT5: Efficient Text-To-Text Transformer for Long Sequences](https://arxiv.org/abs/2112.07916) by Mandy Guo, Joshua Ainslie, David Uthus, Santiago Ontanon, Jianmo Ni, Yun-Hsuan Sung, Yinfei Yang.
+1. **[LUKE](model_doc/luke)** (from Studio Ousia) released with the paper [LUKE: Deep Contextualized Entity Representations with Entity-aware Self-attention](https://arxiv.org/abs/2010.01057) by Ikuya Yamada, Akari Asai, Hiroyuki Shindo, Hideaki Takeda, Yuji Matsumoto.
+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://arxiv.org/abs/1908.07490) by Hao Tan and Mohit Bansal.
+1. **[M-CTC-T](model_doc/mctct)** (from Facebook) released with the paper [Pseudo-Labeling For Massively Multilingual Speech Recognition](https://arxiv.org/abs/2111.00161) by Loren Lugosch, Tatiana Likhomanenko, Gabriel Synnaeve, and Ronan Collobert.
+1. **[M2M100](model_doc/m2m_100)** (from Facebook) released with the paper [Beyond English-Centric Multilingual Machine Translation](https://arxiv.org/abs/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.
+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.
+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://arxiv.org/abs/2110.08518) by Junlong Li, Yiheng Xu, Lei Cui, Furu Wei.
+1. **[Mask2Former](model_doc/mask2former)** (from FAIR and UIUC) released with the paper [Masked-attention Mask Transformer for Universal Image Segmentation](https://arxiv.org/abs/2112.01527) by Bowen Cheng, Ishan Misra, Alexander G. Schwing, Alexander Kirillov, Rohit Girdhar.
+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://arxiv.org/abs/2107.06278) by Bowen Cheng, Alexander G. Schwing, Alexander Kirillov.
+1. **[mBART](model_doc/mbart)** (from Facebook) released with the paper [Multilingual Denoising Pre-training for Neural Machine Translation](https://arxiv.org/abs/2001.08210) by Yinhan Liu, Jiatao Gu, Naman Goyal, Xian Li, Sergey Edunov, Marjan Ghazvininejad, Mike Lewis, Luke Zettlemoyer.
+1. **[mBART-50](model_doc/mbart)** (from Facebook) released with the paper [Multilingual Translation with Extensible Multilingual Pretraining and Finetuning](https://arxiv.org/abs/2008.00401) by Yuqing Tang, Chau Tran, Xian Li, Peng-Jen Chen, Naman Goyal, Vishrav Chaudhary, Jiatao Gu, Angela Fan.
+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://arxiv.org/abs/1909.08053) by Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper and Bryan Catanzaro.
+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://arxiv.org/abs/1909.08053) by Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper and Bryan Catanzaro.
+1. **[mLUKE](model_doc/mluke)** (from Studio Ousia) released with the paper [mLUKE: The Power of Entity Representations in Multilingual Pretrained Language Models](https://arxiv.org/abs/2110.08151) by Ryokan Ri, Ikuya Yamada, and Yoshimasa Tsuruoka.
+1. **[MobileBERT](model_doc/mobilebert)** (from CMU/Google Brain) released with the paper [MobileBERT: a Compact Task-Agnostic BERT for Resource-Limited Devices](https://arxiv.org/abs/2004.02984) by Zhiqing Sun, Hongkun Yu, Xiaodan Song, Renjie Liu, Yiming Yang, and Denny Zhou.
+1. **[MobileViT](model_doc/mobilevit)** (from Apple) released with the paper [MobileViT: Light-weight, General-purpose, and Mobile-friendly Vision Transformer](https://arxiv.org/abs/2110.02178) by Sachin Mehta and Mohammad Rastegari.
+1. **[MPNet](model_doc/mpnet)** (from Microsoft Research) released with the paper [MPNet: Masked and Permuted Pre-training for Language Understanding](https://arxiv.org/abs/2004.09297) by Kaitao Song, Xu Tan, Tao Qin, Jianfeng Lu, Tie-Yan Liu.
+1. **[MT5](model_doc/mt5)** (from Google AI) released with the paper [mT5: A massively multilingual pre-trained text-to-text transformer](https://arxiv.org/abs/2010.11934) by Linting Xue, Noah Constant, Adam Roberts, Mihir Kale, Rami Al-Rfou, Aditya Siddhant, Aditya Barua, Colin Raffel.
+1. **[MVP](model_doc/mvp)** (from RUC AI Box) released with the paper [MVP: Multi-task Supervised Pre-training for Natural Language Generation](https://arxiv.org/abs/2206.12131) by Tianyi Tang, Junyi Li, Wayne Xin Zhao and Ji-Rong Wen.
+1. **[Nezha](model_doc/nezha)** (from Huawei Noahâs Ark Lab) released with the paper [NEZHA: Neural Contextualized Representation for Chinese Language Understanding](https://arxiv.org/abs/1909.00204) by Junqiu Wei, Xiaozhe Ren, Xiaoguang Li, Wenyong Huang, Yi Liao, Yasheng Wang, Jiashu Lin, Xin Jiang, Xiao Chen and Qun Liu.
+1. **[NLLB](model_doc/nllb)** (from Meta) released with the paper [No Language Left Behind: Scaling Human-Centered Machine Translation](https://arxiv.org/abs/2207.04672) by the NLLB team.
+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://arxiv.org/abs/2102.03902) by Yunyang Xiong, Zhanpeng Zeng, Rudrasis Chakraborty, Mingxing Tan, Glenn Fung, Yin Li, Vikas Singh.
+1. **[OneFormer](model_doc/oneformer)** (from SHI Labs) released with the paper [OneFormer: One Transformer to Rule Universal Image Segmentation](https://arxiv.org/abs/2211.06220) by Jitesh Jain, Jiachen Li, MangTik Chiu, Ali Hassani, Nikita Orlov, Humphrey Shi.
+1. **[OPT](master/model_doc/opt)** (from Meta AI) released with the paper [OPT: Open Pre-trained Transformer Language Models](https://arxiv.org/abs/2205.01068) by Susan Zhang, Stephen Roller, Naman Goyal, Mikel Artetxe, Moya Chen, Shuohui Chen et al.
+1. **[OWL-ViT](model_doc/owlvit)** (from Google AI) released with the paper [Simple Open-Vocabulary Object Detection with Vision Transformers](https://arxiv.org/abs/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.
+1. **[Pegasus](model_doc/pegasus)** (from Google) released with the paper [PEGASUS: Pre-training with Extracted Gap-sentences for Abstractive Summarization](https://arxiv.org/abs/1912.08777) by Jingqing Zhang, Yao Zhao, Mohammad Saleh and Peter J. Liu.
+1. **[PEGASUS-X](model_doc/pegasus_x)** (from Google) released with the paper [Investigating Efficiently Extending Transformers for Long Input Summarization](https://arxiv.org/abs/2208.04347) by Jason Phang, Yao Zhao, and Peter J. Liu.
+1. **[Perceiver IO](model_doc/perceiver)** (from Deepmind) released with the paper [Perceiver IO: A General Architecture for Structured Inputs & Outputs](https://arxiv.org/abs/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.
+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.
+1. **[PLBart](model_doc/plbart)** (from UCLA NLP) released with the paper [Unified Pre-training for Program Understanding and Generation](https://arxiv.org/abs/2103.06333) by Wasi Uddin Ahmad, Saikat Chakraborty, Baishakhi Ray, Kai-Wei Chang.
+1. **[PoolFormer](model_doc/poolformer)** (from Sea AI Labs) released with the paper [MetaFormer is Actually What You Need for Vision](https://arxiv.org/abs/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.
+1. **[ProphetNet](model_doc/prophetnet)** (from Microsoft Research) released with the paper [ProphetNet: Predicting Future N-gram for Sequence-to-Sequence Pre-training](https://arxiv.org/abs/2001.04063) by Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang and Ming Zhou.
+1. **[QDQBert](model_doc/qdqbert)** (from NVIDIA) released with the paper [Integer Quantization for Deep Learning Inference: Principles and Empirical Evaluation](https://arxiv.org/abs/2004.09602) by Hao Wu, Patrick Judd, Xiaojie Zhang, Mikhail Isaev and Paulius Micikevicius.
+1. **[RAG](model_doc/rag)** (from Facebook) released with the paper [Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks](https://arxiv.org/abs/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.
+1. **[REALM](model_doc/realm.html)** (from Google Research) released with the paper [REALM: Retrieval-Augmented Language Model Pre-Training](https://arxiv.org/abs/2002.08909) by Kelvin Guu, Kenton Lee, Zora Tung, Panupong Pasupat and Ming-Wei Chang.
+1. **[Reformer](model_doc/reformer)** (from Google Research) released with the paper [Reformer: The Efficient Transformer](https://arxiv.org/abs/2001.04451) by Nikita Kitaev, Ćukasz Kaiser, Anselm Levskaya.
+1. **[RegNet](model_doc/regnet)** (from META Platforms) released with the paper [Designing Network Design Space](https://arxiv.org/abs/2003.13678) by Ilija Radosavovic, Raj Prateek Kosaraju, Ross Girshick, Kaiming He, Piotr DollĂĄr.
+1. **[RemBERT](model_doc/rembert)** (from Google Research) released with the paper [Rethinking embedding coupling in pre-trained language models](https://arxiv.org/abs/2010.12821) by Hyung Won Chung, Thibault Févry, Henry Tsai, M. Johnson, Sebastian Ruder.
+1. **[ResNet](model_doc/resnet)** (from Microsoft Research) released with the paper [Deep Residual Learning for Image Recognition](https://arxiv.org/abs/1512.03385) by Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun.
+1. **[RoBERTa](model_doc/roberta)** (from Facebook), released together with the paper [RoBERTa: A Robustly Optimized BERT Pretraining Approach](https://arxiv.org/abs/1907.11692) by Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Mandar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, Veselin Stoyanov.
+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.
+1. **[RoFormer](model_doc/roformer)** (from ZhuiyiTechnology), released together with the paper [RoFormer: Enhanced Transformer with Rotary Position Embedding](https://arxiv.org/abs/2104.09864) by Jianlin Su and Yu Lu and Shengfeng Pan and Bo Wen and Yunfeng Liu.
+1. **[SegFormer](model_doc/segformer)** (from NVIDIA) released with the paper [SegFormer: Simple and Efficient Design for Semantic Segmentation with Transformers](https://arxiv.org/abs/2105.15203) by Enze Xie, Wenhai Wang, Zhiding Yu, Anima Anandkumar, Jose M. Alvarez, Ping Luo.
+1. **[SEW](model_doc/sew)** (from ASAPP) released with the paper [Performance-Efficiency Trade-offs in Unsupervised Pre-training for Speech Recognition](https://arxiv.org/abs/2109.06870) by Felix Wu, Kwangyoun Kim, Jing Pan, Kyu Han, Kilian Q. Weinberger, Yoav Artzi.
+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://arxiv.org/abs/2109.06870) by Felix Wu, Kwangyoun Kim, Jing Pan, Kyu Han, Kilian Q. Weinberger, Yoav Artzi.
+1. **[SpeechToTextTransformer](model_doc/speech_to_text)** (from Facebook), released together with the paper [fairseq S2T: Fast Speech-to-Text Modeling with fairseq](https://arxiv.org/abs/2010.05171) by Changhan Wang, Yun Tang, Xutai Ma, Anne Wu, Dmytro Okhonko, Juan Pino.
+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://arxiv.org/abs/2104.06678) by Changhan Wang, Anne Wu, Juan Pino, Alexei Baevski, Michael Auli, Alexis Conneau.
+1. **[Splinter](model_doc/splinter)** (from Tel Aviv University), released together with the paper [Few-Shot Question Answering by Pretraining Span Selection](https://arxiv.org/abs/2101.00438) by Ori Ram, Yuval Kirstain, Jonathan Berant, Amir Globerson, Omer Levy.
+1. **[SqueezeBERT](model_doc/squeezebert)** (from Berkeley) released with the paper [SqueezeBERT: What can computer vision teach NLP about efficient neural networks?](https://arxiv.org/abs/2006.11316) by Forrest N. Iandola, Albert E. Shaw, Ravi Krishna, and Kurt W. Keutzer.
+1. **[Swin Transformer](model_doc/swin)** (from Microsoft) released with the paper [Swin Transformer: Hierarchical Vision Transformer using Shifted Windows](https://arxiv.org/abs/2103.14030) by Ze Liu, Yutong Lin, Yue Cao, Han Hu, Yixuan Wei, Zheng Zhang, Stephen Lin, Baining Guo.
+1. **[Swin Transformer V2](model_doc/swinv2)** (from Microsoft) released with the paper [Swin Transformer V2: Scaling Up Capacity and Resolution](https://arxiv.org/abs/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.
+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://arxiv.org/abs/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.
+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.
+1. **[Table Transformer](model_doc/table-transformer)** (from Microsoft Research) released with the paper [PubTables-1M: Towards Comprehensive Table Extraction From Unstructured Documents](https://arxiv.org/abs/2110.00061) by Brandon Smock, Rohith Pesala, Robin Abraham.
+1. **[TAPAS](model_doc/tapas)** (from Google AI) released with the paper [TAPAS: Weakly Supervised Table Parsing via Pre-training](https://arxiv.org/abs/2004.02349) by Jonathan Herzig, PaweĆ Krzysztof Nowak, Thomas MĂŒller, Francesco Piccinno and Julian Martin Eisenschlos.
+1. **[TAPEX](model_doc/tapex)** (from Microsoft Research) released with the paper [TAPEX: Table Pre-training via Learning a Neural SQL Executor](https://arxiv.org/abs/2107.07653) by Qian Liu, Bei Chen, Jiaqi Guo, Morteza Ziyadi, Zeqi Lin, Weizhu Chen, Jian-Guang Lou.
+1. **[Time Series Transformer](model_doc/time_series_transformer)** (from HuggingFace).
+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://arxiv.org/abs/2106.02039) by Michael Janner, Qiyang Li, Sergey Levine
+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://arxiv.org/abs/1901.02860) by Zihang Dai*, Zhilin Yang*, Yiming Yang, Jaime Carbonell, Quoc V. Le, Ruslan Salakhutdinov.
+1. **[TrOCR](model_doc/trocr)** (from Microsoft), released together with the paper [TrOCR: Transformer-based Optical Character Recognition with Pre-trained Models](https://arxiv.org/abs/2109.10282) by Minghao Li, Tengchao Lv, Lei Cui, Yijuan Lu, Dinei Florencio, Cha Zhang, Zhoujun Li, Furu Wei.
+1. **[UL2](model_doc/ul2)** (from Google Research) released with the paper [Unifying Language Learning Paradigms](https://arxiv.org/abs/2205.05131v1) by Yi Tay, Mostafa Dehghani, Vinh Q. Tran, Xavier Garcia, Dara Bahri, Tal Schuster, Huaixiu Steven Zheng, Neil Houlsby, Donald Metzler
+1. **[UniSpeech](model_doc/unispeech)** (from Microsoft Research) released with the paper [UniSpeech: Unified Speech Representation Learning with Labeled and Unlabeled Data](https://arxiv.org/abs/2101.07597) by Chengyi Wang, Yu Wu, Yao Qian, Kenichi Kumatani, Shujie Liu, Furu Wei, Michael Zeng, Xuedong Huang.
+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://arxiv.org/abs/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.
+1. **[VAN](model_doc/van)** (from Tsinghua University and Nankai University) released with the paper [Visual Attention Network](https://arxiv.org/abs/2202.09741) by Meng-Hao Guo, Cheng-Ze Lu, Zheng-Ning Liu, Ming-Ming Cheng, Shi-Min Hu.
+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://arxiv.org/abs/2203.12602) by Zhan Tong, Yibing Song, Jue Wang, Limin Wang.
+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://arxiv.org/abs/2102.03334) by Wonjae Kim, Bokyung Son, Ildoo Kim.
+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://arxiv.org/abs/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.
+1. **[VisualBERT](model_doc/visual_bert)** (from UCLA NLP) released with the paper [VisualBERT: A Simple and Performant Baseline for Vision and Language](https://arxiv.org/pdf/1908.03557) by Liunian Harold Li, Mark Yatskar, Da Yin, Cho-Jui Hsieh, Kai-Wei Chang.
+1. **[ViTMAE](model_doc/vit_mae)** (from Meta AI) released with the paper [Masked Autoencoders Are Scalable Vision Learners](https://arxiv.org/abs/2111.06377) by Kaiming He, Xinlei Chen, Saining Xie, Yanghao Li, Piotr DollĂĄr, Ross Girshick.
+1. **[ViTMSN](model_doc/vit_msn)** (from Meta AI) released with the paper [Masked Siamese Networks for Label-Efficient Learning](https://arxiv.org/abs/2204.07141) by Mahmoud Assran, Mathilde Caron, Ishan Misra, Piotr Bojanowski, Florian Bordes, Pascal Vincent, Armand Joulin, Michael Rabbat, Nicolas Ballas.
+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://arxiv.org/abs/2006.11477) by Alexei Baevski, Henry Zhou, Abdelrahman Mohamed, Michael Auli.
+1. **[Wav2Vec2-Conformer](model_doc/wav2vec2-conformer)** (from Facebook AI) released with the paper [FAIRSEQ S2T: Fast Speech-to-Text Modeling with FAIRSEQ](https://arxiv.org/abs/2010.05171) by Changhan Wang, Yun Tang, Xutai Ma, Anne Wu, Sravya Popuri, Dmytro Okhonko, Juan Pino.
+1. **[Wav2Vec2Phoneme](model_doc/wav2vec2_phoneme)** (from Facebook AI) released with the paper [Simple and Effective Zero-shot Cross-lingual Phoneme Recognition](https://arxiv.org/abs/2109.11680) by Qiantong Xu, Alexei Baevski, Michael Auli.
+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://arxiv.org/abs/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.
+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.
+1. **[X-CLIP](model_doc/xclip)** (from Microsoft Research) released with the paper [Expanding Language-Image Pretrained Models for General Video Recognition](https://arxiv.org/abs/2208.02816) by Bolin Ni, Houwen Peng, Minghao Chen, Songyang Zhang, Gaofeng Meng, Jianlong Fu, Shiming Xiang, Haibin Ling.
+1. **[XGLM](model_doc/xglm)** (From Facebook AI) released with the paper [Few-shot Learning with Multilingual Language Models](https://arxiv.org/abs/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.
+1. **[XLM](model_doc/xlm)** (from Facebook) released together with the paper [Cross-lingual Language Model Pretraining](https://arxiv.org/abs/1901.07291) by Guillaume Lample and Alexis Conneau.
+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://arxiv.org/abs/2001.04063) by Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang and Ming Zhou.
+1. **[XLM-RoBERTa](model_doc/xlm-roberta)** (from Facebook AI), released together with the paper [Unsupervised Cross-lingual Representation Learning at Scale](https://arxiv.org/abs/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.
+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://arxiv.org/abs/2105.00572) by Naman Goyal, Jingfei Du, Myle Ott, Giri Anantharaman, Alexis Conneau.
+1. **[XLNet](model_doc/xlnet)** (from Google/CMU) released with the paper [âXLNet: Generalized Autoregressive Pretraining for Language Understanding](https://arxiv.org/abs/1906.08237) by Zhilin Yang*, Zihang Dai*, Yiming Yang, Jaime Carbonell, Ruslan Salakhutdinov, Quoc V. Le.
+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://arxiv.org/abs/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.
+1. **[XLSR-Wav2Vec2](model_doc/xlsr_wav2vec2)** (from Facebook AI) released with the paper [Unsupervised Cross-Lingual Representation Learning For Speech Recognition](https://arxiv.org/abs/2006.13979) by Alexis Conneau, Alexei Baevski, Ronan Collobert, Abdelrahman Mohamed, Michael Auli.
+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://arxiv.org/abs/2106.00666) by Yuxin Fang, Bencheng Liao, Xinggang Wang, Jiemin Fang, Jiyang Qi, Rui Wu, Jianwei Niu, Wenyu Liu.
+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://arxiv.org/abs/2111.09714) by Zhanpeng Zeng, Yunyang Xiong, Sathya N. Ravi, Shailesh Acharya, Glenn Fung, Vikas Singh.
+
+
+### ì§ì íë ììíŹ[[supported-framework]]
+
+ìë íë ëŒìŽëžëŹëŠŹ ì ê° ëȘšëžì ì§ì íí©ì ëíë
ëë€. í í°í넌 íìŽìŹ (ëłìč "slow") ëë đ€ Tokenizers (ëłìč "fast") ëŒìŽëžëŹëŠŹëĄ íëì§; (Flax넌 í”í) Jax, PyTorch, TensorFlow ì€ ìŽë€ íë ììíŹë„Œ ì§ìíëì§ íìëìŽ ìì”ëë€.
+
+
+
+| Model | Tokenizer slow | Tokenizer fast | PyTorch support | TensorFlow support | Flax Support |
+|:---------------------------:|:--------------:|:--------------:|:---------------:|:------------------:|:------------:|
+| ALBERT | â
| â
| â
| â
| â
|
+| BART | â
| â
| â
| â
| â
|
+| BEiT | â | â | â
| â | â
|
+| BERT | â
| â
| â
| â
| â
|
+| Bert Generation | â
| â | â
| â | â |
+| BigBird | â
| â
| â
| â | â
|
+| BigBird-Pegasus | â | â | â
| â | â |
+| Blenderbot | â
| â
| â
| â
| â
|
+| BlenderbotSmall | â
| â
| â
| â
| â
|
+| BLOOM | â | â
| â
| â | â |
+| CamemBERT | â
| â
| â
| â
| â |
+| CANINE | â
| â | â
| â | â |
+| CLIP | â
| â
| â
| â
| â
|
+| CLIPSeg | â | â | â
| â | â |
+| CodeGen | â
| â
| â
| â | â |
+| Conditional DETR | â | â | â
| â | â |
+| ConvBERT | â
| â
| â
| â
| â |
+| ConvNeXT | â | â | â
| â
| â |
+| CTRL | â
| â | â
| â
| â |
+| CvT | â | â | â
| â
| â |
+| Data2VecAudio | â | â | â
| â | â |
+| Data2VecText | â | â | â
| â | â |
+| Data2VecVision | â | â | â
| â
| â |
+| DeBERTa | â
| â
| â
| â
| â |
+| DeBERTa-v2 | â
| â
| â
| â
| â |
+| Decision Transformer | â | â | â
| â | â |
+| Deformable DETR | â | â | â
| â | â |
+| DeiT | â | â | â
| â
| â |
+| DETR | â | â | â
| â | â |
+| DistilBERT | â
| â
| â
| â
| â
|
+| DonutSwin | â | â | â
| â | â |
+| DPR | â
| â
| â
| â
| â |
+| DPT | â | â | â
| â | â |
+| ELECTRA | â
| â
| â
| â
| â
|
+| Encoder decoder | â | â | â
| â
| â
|
+| ERNIE | â | â | â
| â | â |
+| ESM | â
| â | â
| â
| â |
+| FairSeq Machine-Translation | â
| â | â
| â | â |
+| FlauBERT | â
| â | â
| â
| â |
+| FLAVA | â | â | â
| â | â |
+| FNet | â
| â
| â
| â | â |
+| Funnel Transformer | â
| â
| â
| â
| â |
+| GLPN | â | â | â
| â | â |
+| GPT Neo | â | â | â
| â | â
|
+| GPT NeoX | â | â
| â
| â | â |
+| GPT NeoX Japanese | â
| â | â
| â | â |
+| GPT-J | â | â | â
| â
| â
|
+| GroupViT | â | â | â
| â
| â |
+| Hubert | â | â | â
| â
| â |
+| I-BERT | â | â | â
| â | â |
+| ImageGPT | â | â | â
| â | â |
+| Jukebox | â
| â | â
| â | â |
+| LayoutLM | â
| â
| â
| â
| â |
+| LayoutLMv2 | â
| â
| â
| â | â |
+| LayoutLMv3 | â
| â
| â
| â
| â |
+| LED | â
| â
| â
| â
| â |
+| LeViT | â | â | â
| â | â |
+| LiLT | â | â | â
| â | â |
+| Longformer | â
| â
| â
| â
| â |
+| LongT5 | â | â | â
| â | â
|
+| LUKE | â
| â | â
| â | â |
+| LXMERT | â
| â
| â
| â
| â |
+| M-CTC-T | â | â | â
| â | â |
+| M2M100 | â
| â | â
| â | â |
+| Marian | â
| â | â
| â
| â
|
+| MarkupLM | â
| â
| â
| â | â |
+| MaskFormer | â | â | â
| â | â |
+| mBART | â
| â
| â
| â
| â
|
+| Megatron-BERT | â | â | â
| â | â |
+| MobileBERT | â
| â
| â
| â
| â |
+| MobileViT | â | â | â
| â
| â |
+| MPNet | â
| â
| â
| â
| â |
+| MT5 | â
| â
| â
| â
| â
|
+| MVP | â
| â
| â
| â | â |
+| Nezha | â | â | â
| â | â |
+| Nyströmformer | â | â | â
| â | â |
+| OpenAI GPT | â
| â
| â
| â
| â |
+| OpenAI GPT-2 | â
| â
| â
| â
| â
|
+| OPT | â | â | â
| â
| â
|
+| OWL-ViT | â | â | â
| â | â |
+| Pegasus | â
| â
| â
| â
| â
|
+| PEGASUS-X | â | â | â
| â | â |
+| Perceiver | â
| â | â
| â | â |
+| PLBart | â
| â | â
| â | â |
+| PoolFormer | â | â | â
| â | â |
+| ProphetNet | â
| â | â
| â | â |
+| QDQBert | â | â | â
| â | â |
+| RAG | â
| â | â
| â
| â |
+| REALM | â
| â
| â
| â | â |
+| Reformer | â
| â
| â
| â | â |
+| RegNet | â | â | â
| â
| â
|
+| RemBERT | â
| â
| â
| â
| â |
+| ResNet | â | â | â
| â
| â
|
+| RetriBERT | â
| â
| â
| â | â |
+| RoBERTa | â
| â
| â
| â
| â
|
+| RoCBert | â
| â | â
| â | â |
+| RoFormer | â
| â
| â
| â
| â
|
+| SegFormer | â | â | â
| â
| â |
+| SEW | â | â | â
| â | â |
+| SEW-D | â | â | â
| â | â |
+| Speech Encoder decoder | â | â | â
| â | â
|
+| Speech2Text | â
| â | â
| â
| â |
+| Speech2Text2 | â
| â | â | â | â |
+| Splinter | â
| â
| â
| â | â |
+| SqueezeBERT | â
| â
| â
| â | â |
+| Swin Transformer | â | â | â
| â
| â |
+| Swin Transformer V2 | â | â | â
| â | â |
+| T5 | â
| â
| â
| â
| â
|
+| Table Transformer | â | â | â
| â | â |
+| TAPAS | â
| â | â
| â
| â |
+| Time Series Transformer | â | â | â
| â | â |
+| Trajectory Transformer | â | â | â
| â | â |
+| Transformer-XL | â
| â | â
| â
| â |
+| TrOCR | â | â | â
| â | â |
+| UniSpeech | â | â | â
| â | â |
+| UniSpeechSat | â | â | â
| â | â |
+| VAN | â | â | â
| â | â |
+| VideoMAE | â | â | â
| â | â |
+| ViLT | â | â | â
| â | â |
+| Vision Encoder decoder | â | â | â
| â
| â
|
+| VisionTextDualEncoder | â | â | â
| â | â
|
+| VisualBERT | â | â | â
| â | â |
+| ViT | â | â | â
| â
| â
|
+| ViTMAE | â | â | â
| â
| â |
+| ViTMSN | â | â | â
| â | â |
+| Wav2Vec2 | â
| â | â
| â
| â
|
+| Wav2Vec2-Conformer | â | â | â
| â | â |
+| WavLM | â | â | â
| â | â |
+| Whisper | â
| â | â
| â
| â |
+| X-CLIP | â | â | â
| â | â |
+| XGLM | â
| â
| â
| â
| â
|
+| XLM | â
| â | â
| â
| â |
+| XLM-ProphetNet | â
| â | â
| â | â |
+| XLM-RoBERTa | â
| â
| â
| â
| â
|
+| XLM-RoBERTa-XL | â | â | â
| â | â |
+| XLNet | â
| â
| â
| â
| â |
+| YOLOS | â | â | â
| â | â |
+| YOSO | â | â | â
| â | â |
+
+
diff --git a/docs/source/ko/index.mdx b/docs/source/ko/index.mdx
deleted file mode 100644
index 5a6428d69487..000000000000
--- a/docs/source/ko/index.mdx
+++ /dev/null
@@ -1,358 +0,0 @@
-
-
-# đ€ Transformers
-
-[PyTorch](https://pytorch.org/), [TensorFlow](https://www.tensorflow.org/), [JAX](https://jax.readthedocs.io/en/latest/)넌 ìí ì”ìČšëš ëšžì ëŹë
-
-đ€ Transformersë ìŹì íì”ë ì”ìČšëš ëȘšëžë€ì ìœêČ ë€ìŽëĄëíêł íë šìíŹ ì ìë APIì ëê”Źë„Œ ì êł”í©ëë€. ìŹì íì”ë ëȘšëžì ì°ë©Ž 컎íší
ëčì©êłŒ íì ë°°ì¶ëìŽ ì€êł , ëȘšëžì ìČìë¶í° íë šìí€ë ë° íìí ìê°êłŒ 늏ìì€ë„Œ ì ìœí ì ìì”ëë€. ì íŹ ëȘšëžë€ì ë€ìí ë¶ìŒì íì€íŹë„Œ ì§ìí©ëë€.
-
-đ **ìì°ìŽ ìČ늏**: í
ì€íž ë¶ë„, ê°ìČŽëȘ
ìžì, ì§ììë”, ìžìŽ ëȘšëžë§, ììœ, ëČì, ê°êŽì ì§ììë”, í
ì€íž ìì±
-đŒïž **컎íší° ëčì **: ìŽëŻžì§ ë¶ë„, ê°ìČŽ íì§, ê°ìČŽ ë¶í
-đŁïž **ì€ëì€**: ìëìì±ìžì, ì€ëì€ ë¶ë„
-đ **ë©í°ëȘšëŹ**: í ì§ììë”, êŽí 돞ì ìžì (OCR), ì€ìșí 돞ììì ì 볎 ì¶ì¶, ëčëì€ ë¶ë„, ìê° ì§ììë”
-
-đ€ Transformersë PyTorch, TensorFlowì JAX ê°ì ìížìŽì©ì±ì ì§ìí©ëë€. ì ì°íêČ ëȘšëžì ê° ëšêłë§ë€ ë€ë„ž íë ììíŹë„Œ ìŹì©í ìë ìì”ëë€. ì넌 ë€ìŽ ìœë 3ì€ë§ ìšì ëȘšëžì íë šìíš ë€ì, ë€ë„ž íë ììíŹ ììì ì¶ëĄ í ì ìì”ëë€. ëȘšëžì ìŽì íêČœì ë°°íŹíêž° ìíŽ ONNXë TorchScript íììŒëĄ ëŽëłŽëŒ ìë ìì”ëë€.
-
-ì»€ëź€ëí°ì ì°žìŹíìë €ë©Ž [Hub](https://huggingface.co/models), [íŹëŒ](https://discuss.huggingface.co/), [ëì€ìœë](https://discord.com/invite/JfAtkvEtRb)넌 방돞íŽìŁŒìžì!
-
-## Hugging Face íêłŒ ì§ì ëííêł ì¶ìŒì ê°ì?[[hugging-face-team]]
-
-
-
-
-
-## ìœí
ìž [[contents]]
-
-ì íŹ êž°ì 돞ìë íŹêČ 5ê° ìčì
ìŒëĄ ëë ì ìì”ëë€:
-
-- **ììíêž°**ìì ëŒìŽëžëŹëŠŹë„Œ ê°ëší íìŽëłŽêł , ëłžêČ©ì ìŒëĄ ë°ìŽë€ ì ìêČ ì€ìč ë°©ëČì ìëŽí©ëë€.
-- **íí 늏ìŒ**ìì ëŒìŽëžëŹëŠŹì ì”ìíŽì§ ì ìëëĄ ììžíêł ë ìœêČ êž°ëłžì ìž ë¶ë¶ì ìëŽí©ëë€.
-- **How-to ê°ìŽë**ìì ìžìŽ ëȘšëžë§ì ìíŽ ìŹì íì”ë ëȘšëžì íìž íëíë ë°©ëČìŽë, ì§ì ëȘšëžì ìì±íêł êł”ì íë ë°©ëČêłŒ ê°ìŽ íčì ëȘ©í넌 ëŹì±íë ë°©ëČì ìëŽí©ëë€.
-- **ê°ë
ê°ìŽë**ìì đ€ Transformersì ì€êł ìČ íêłŒ íšê» ëȘšëžìŽë íì€íŹ ë€ì ìšêČšì§ ê°ë
ë€êłŒ ììŽëìŽë„Œ íê”Źíêł ì€ëȘ
ì ë§ë¶ì
ëë€.
-- **API**ìì ëȘšë íŽëì€ì íšì넌 ì€ëȘ
í©ëë€.
-
- - **ë©ìž íŽëì€**ìì configuration, model, tokenizer, pipelineêłŒ ê°ìŽ ì ìŒ ì€ìí íŽëì€ë€ì ììží ì€ëȘ
í©ëë€.
- - **ëȘšëž**ìì ëŒìŽëžëŹëŠŹ ì ê”Źíë ê° ëȘšëžêłŒ ì°êŽë íŽëì€ì íšì넌 ììží ì€ëȘ
í©ëë€.
- - **ëŽë¶ ì ížëŠŹí°**ìì ëŽë¶ì ìŒëĄ ìŹì©ëë ì ížëŠŹí° íŽëì€ì íšì넌 ììží ì€ëȘ
í©ëë€.
-
-### ì§ì ëȘšëž[[supported-models]]
-
-
-
-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://arxiv.org/abs/1909.11942), by Zhenzhong Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.
-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://arxiv.org/abs/1910.13461) by Mike Lewis, Yinhan Liu, Naman Goyal, Marjan Ghazvininejad, Abdelrahman Mohamed, Omer Levy, Ves Stoyanov and Luke Zettlemoyer.
-1. **[BARThez](model_doc/barthez)** (from Ăcole polytechnique) released with the paper [BARThez: a Skilled Pretrained French Sequence-to-Sequence Model](https://arxiv.org/abs/2010.12321) by Moussa Kamal Eddine, Antoine J.-P. Tixier, Michalis Vazirgiannis.
-1. **[BARTpho](model_doc/bartpho)** (from VinAI Research) released with the paper [BARTpho: Pre-trained Sequence-to-Sequence Models for Vietnamese](https://arxiv.org/abs/2109.09701) by Nguyen Luong Tran, Duong Minh Le and Dat Quoc Nguyen.
-1. **[BEiT](model_doc/beit)** (from Microsoft) released with the paper [BEiT: BERT Pre-Training of Image Transformers](https://arxiv.org/abs/2106.08254) by Hangbo Bao, Li Dong, Furu Wei.
-1. **[BERT](model_doc/bert)** (from Google) released with the paper [BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding](https://arxiv.org/abs/1810.04805) by Jacob Devlin, Ming-Wei Chang, Kenton Lee and Kristina Toutanova.
-1. **[BERT For Sequence Generation](model_doc/bert-generation)** (from Google) released with the paper [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://arxiv.org/abs/1907.12461) by Sascha Rothe, Shashi Narayan, Aliaksei Severyn.
-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.
-1. **[BigBird-Pegasus](model_doc/bigbird_pegasus)** (from Google Research) released with the paper [Big Bird: Transformers for Longer Sequences](https://arxiv.org/abs/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.
-1. **[BigBird-RoBERTa](model_doc/big_bird)** (from Google Research) released with the paper [Big Bird: Transformers for Longer Sequences](https://arxiv.org/abs/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.
-1. **[Blenderbot](model_doc/blenderbot)** (from Facebook) released with the paper [Recipes for building an open-domain chatbot](https://arxiv.org/abs/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.
-1. **[BlenderbotSmall](model_doc/blenderbot-small)** (from Facebook) released with the paper [Recipes for building an open-domain chatbot](https://arxiv.org/abs/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.
-1. **[BLOOM](model_doc/bloom)** (from BigScience workshop) released by the [BigScience Workshop](https://bigscience.huggingface.co/).
-1. **[BORT](model_doc/bort)** (from Alexa) released with the paper [Optimal Subarchitecture Extraction For BERT](https://arxiv.org/abs/2010.10499) by Adrian de Wynter and Daniel J. Perry.
-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://arxiv.org/abs/2105.13626) by Linting Xue, Aditya Barua, Noah Constant, Rami Al-Rfou, Sharan Narang, Mihir Kale, Adam Roberts, Colin Raffel.
-1. **[CamemBERT](model_doc/camembert)** (from Inria/Facebook/Sorbonne) released with the paper [CamemBERT: a Tasty French Language Model](https://arxiv.org/abs/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.
-1. **[CANINE](model_doc/canine)** (from Google Research) released with the paper [CANINE: Pre-training an Efficient Tokenization-Free Encoder for Language Representation](https://arxiv.org/abs/2103.06874) by Jonathan H. Clark, Dan Garrette, Iulia Turc, John Wieting.
-1. **[CLIP](model_doc/clip)** (from OpenAI) released with the paper [Learning Transferable Visual Models From Natural Language Supervision](https://arxiv.org/abs/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.
-1. **[CLIPSeg](model_doc/clipseg)** (from University of Göttingen) released with the paper [Image Segmentation Using Text and Image Prompts](https://arxiv.org/abs/2112.10003) by Timo LĂŒddecke and Alexander Ecker.
-1. **[CodeGen](model_doc/codegen)** (from Salesforce) released with the paper [A Conversational Paradigm for Program Synthesis](https://arxiv.org/abs/2203.13474) by Erik Nijkamp, Bo Pang, Hiroaki Hayashi, Lifu Tu, Huan Wang, Yingbo Zhou, Silvio Savarese, Caiming Xiong.
-1. **[Conditional DETR](model_doc/conditional_detr)** (from Microsoft Research Asia) released with the paper [Conditional DETR for Fast Training Convergence](https://arxiv.org/abs/2108.06152) by Depu Meng, Xiaokang Chen, Zejia Fan, Gang Zeng, Houqiang Li, Yuhui Yuan, Lei Sun, Jingdong Wang.
-1. **[ConvBERT](model_doc/convbert)** (from YituTech) released with the paper [ConvBERT: Improving BERT with Span-based Dynamic Convolution](https://arxiv.org/abs/2008.02496) by Zihang Jiang, Weihao Yu, Daquan Zhou, Yunpeng Chen, Jiashi Feng, Shuicheng Yan.
-1. **[ConvNeXT](model_doc/convnext)** (from Facebook AI) released with the paper [A ConvNet for the 2020s](https://arxiv.org/abs/2201.03545) by Zhuang Liu, Hanzi Mao, Chao-Yuan Wu, Christoph Feichtenhofer, Trevor Darrell, Saining Xie.
-1. **[ConvNeXTV2](model_doc/convnextv2)** (from Facebook AI) released with the paper [ConvNeXt V2: Co-designing and Scaling ConvNets with Masked Autoencoders](https://arxiv.org/abs/2301.00808) by Sanghyun Woo, Shoubhik Debnath, Ronghang Hu, Xinlei Chen, Zhuang Liu, In So Kweon, Saining Xie.
-1. **[CPM](model_doc/cpm)** (from Tsinghua University) released with the paper [CPM: A Large-scale Generative Chinese Pre-trained Language Model](https://arxiv.org/abs/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.
-1. **[CTRL](model_doc/ctrl)** (from Salesforce) released with the paper [CTRL: A Conditional Transformer Language Model for Controllable Generation](https://arxiv.org/abs/1909.05858) by Nitish Shirish Keskar*, Bryan McCann*, Lav R. Varshney, Caiming Xiong and Richard Socher.
-1. **[CvT](model_doc/cvt)** (from Microsoft) released with the paper [CvT: Introducing Convolutions to Vision Transformers](https://arxiv.org/abs/2103.15808) by Haiping Wu, Bin Xiao, Noel Codella, Mengchen Liu, Xiyang Dai, Lu Yuan, Lei Zhang.
-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://arxiv.org/abs/2202.03555) by Alexei Baevski, Wei-Ning Hsu, Qiantong Xu, Arun Babu, Jiatao Gu, Michael Auli.
-1. **[DeBERTa](model_doc/deberta)** (from Microsoft) released with the paper [DeBERTa: Decoding-enhanced BERT with Disentangled Attention](https://arxiv.org/abs/2006.03654) by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen.
-1. **[DeBERTa-v2](model_doc/deberta-v2)** (from Microsoft) released with the paper [DeBERTa: Decoding-enhanced BERT with Disentangled Attention](https://arxiv.org/abs/2006.03654) by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen.
-1. **[Decision Transformer](model_doc/decision_transformer)** (from Berkeley/Facebook/Google) released with the paper [Decision Transformer: Reinforcement Learning via Sequence Modeling](https://arxiv.org/abs/2106.01345) by Lili Chen, Kevin Lu, Aravind Rajeswaran, Kimin Lee, Aditya Grover, Michael Laskin, Pieter Abbeel, Aravind Srinivas, Igor Mordatch.
-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://arxiv.org/abs/2010.04159) by Xizhou Zhu, Weijie Su, Lewei Lu, Bin Li, Xiaogang Wang, Jifeng Dai.
-1. **[DeiT](model_doc/deit)** (from Facebook) released with the paper [Training data-efficient image transformers & distillation through attention](https://arxiv.org/abs/2012.12877) by Hugo Touvron, Matthieu Cord, Matthijs Douze, Francisco Massa, Alexandre Sablayrolles, Hervé Jégou.
-1. **[DETR](model_doc/detr)** (from Facebook) released with the paper [End-to-End Object Detection with Transformers](https://arxiv.org/abs/2005.12872) by Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov, Sergey Zagoruyko.
-1. **[DialoGPT](model_doc/dialogpt)** (from Microsoft Research) released with the paper [DialoGPT: Large-Scale Generative Pre-training for Conversational Response Generation](https://arxiv.org/abs/1911.00536) by Yizhe Zhang, Siqi Sun, Michel Galley, Yen-Chun Chen, Chris Brockett, Xiang Gao, Jianfeng Gao, Jingjing Liu, Bill Dolan.
-1. **[DistilBERT](model_doc/distilbert)** (from HuggingFace), released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter](https://arxiv.org/abs/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/tree/main/examples/research_projects/distillation), RoBERTa into [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/research_projects/distillation), Multilingual BERT into [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/research_projects/distillation) and a German version of DistilBERT.
-1. **[DiT](model_doc/dit)** (from Microsoft Research) released with the paper [DiT: Self-supervised Pre-training for Document Image Transformer](https://arxiv.org/abs/2203.02378) by Junlong Li, Yiheng Xu, Tengchao Lv, Lei Cui, Cha Zhang, Furu Wei.
-1. **[Donut](model_doc/donut)** (from NAVER), released together with the paper [OCR-free Document Understanding Transformer](https://arxiv.org/abs/2111.15664) by Geewook Kim, Teakgyu Hong, Moonbin Yim, Jeongyeon Nam, Jinyoung Park, Jinyeong Yim, Wonseok Hwang, Sangdoo Yun, Dongyoon Han, Seunghyun Park.
-1. **[DPR](model_doc/dpr)** (from Facebook) released with the paper [Dense Passage Retrieval for Open-Domain Question Answering](https://arxiv.org/abs/2004.04906) by Vladimir Karpukhin, Barlas OÄuz, Sewon Min, Patrick Lewis, Ledell Wu, Sergey Edunov, Danqi Chen, and Wen-tau Yih.
-1. **[DPT](master/model_doc/dpt)** (from Intel Labs) released with the paper [Vision Transformers for Dense Prediction](https://arxiv.org/abs/2103.13413) by René Ranftl, Alexey Bochkovskiy, Vladlen Koltun.
-1. **[EfficientNet](model_doc/efficientnet)** (from Google Research) released with the paper [EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks](https://arxiv.org/abs/1905.11946) by Mingxing Tan and Quoc V. Le.
-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://arxiv.org/abs/2003.10555) by Kevin Clark, Minh-Thang Luong, Quoc V. Le, Christopher D. Manning.
-1. **[EncoderDecoder](model_doc/encoder-decoder)** (from Google Research) released with the paper [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://arxiv.org/abs/1907.12461) by Sascha Rothe, Shashi Narayan, Aliaksei Severyn.
-1. **[ERNIE](model_doc/ernie)** (from Baidu) released with the paper [ERNIE: Enhanced Representation through Knowledge Integration](https://arxiv.org/abs/1904.09223) by Yu Sun, Shuohuan Wang, Yukun Li, Shikun Feng, Xuyi Chen, Han Zhang, Xin Tian, Danxiang Zhu, Hao Tian, Hua Wu.
-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.
-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
-1. **[FlauBERT](model_doc/flaubert)** (from CNRS) released with the paper [FlauBERT: Unsupervised Language Model Pre-training for French](https://arxiv.org/abs/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.
-1. **[FLAVA](model_doc/flava)** (from Facebook AI) released with the paper [FLAVA: A Foundational Language And Vision Alignment Model](https://arxiv.org/abs/2112.04482) by Amanpreet Singh, Ronghang Hu, Vedanuj Goswami, Guillaume Couairon, Wojciech Galuba, Marcus Rohrbach, and Douwe Kiela.
-1. **[FNet](model_doc/fnet)** (from Google Research) released with the paper [FNet: Mixing Tokens with Fourier Transforms](https://arxiv.org/abs/2105.03824) by James Lee-Thorp, Joshua Ainslie, Ilya Eckstein, Santiago Ontanon.
-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://arxiv.org/abs/2006.03236) by Zihang Dai, Guokun Lai, Yiming Yang, Quoc V. Le.
-1. **[GLPN](model_doc/glpn)** (from KAIST) released with the paper [Global-Local Path Networks for Monocular Depth Estimation with Vertical CutDepth](https://arxiv.org/abs/2201.07436) by Doyeon Kim, Woonghyun Ga, Pyungwhan Ahn, Donggyu Joo, Sehwan Chun, Junmo Kim.
-1. **[GPT](model_doc/openai-gpt)** (from OpenAI) released with the paper [Improving Language Understanding by Generative Pre-Training](https://blog.openai.com/language-unsupervised/) by Alec Radford, Karthik Narasimhan, Tim Salimans and Ilya Sutskever.
-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.
-1. **[GPT NeoX](model_doc/gpt_neox)** (from EleutherAI) released with the paper [GPT-NeoX-20B: An Open-Source Autoregressive Language Model](https://arxiv.org/abs/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
-1. **[GPT NeoX Japanese](model_doc/gpt_neox_japanese)** (from ABEJA) released by Shinya Otani, Takayoshi Makabe, Anuj Arora, and Kyo Hattori.
-1. **[GPT-2](model_doc/gpt2)** (from OpenAI) released with the paper [Language Models are Unsupervised Multitask Learners](https://blog.openai.com/better-language-models/) by Alec Radford*, Jeffrey Wu*, Rewon Child, David Luan, Dario Amodei** and Ilya Sutskever**.
-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.
-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).
-1. **[GroupViT](model_doc/groupvit)** (from UCSD, NVIDIA) released with the paper [GroupViT: Semantic Segmentation Emerges from Text Supervision](https://arxiv.org/abs/2202.11094) by Jiarui Xu, Shalini De Mello, Sifei Liu, Wonmin Byeon, Thomas Breuel, Jan Kautz, Xiaolong Wang.
-1. **[Hubert](model_doc/hubert)** (from Facebook) released with the paper [HuBERT: Self-Supervised Speech Representation Learning by Masked Prediction of Hidden Units](https://arxiv.org/abs/2106.07447) by Wei-Ning Hsu, Benjamin Bolte, Yao-Hung Hubert Tsai, Kushal Lakhotia, Ruslan Salakhutdinov, Abdelrahman Mohamed.
-1. **[I-BERT](model_doc/ibert)** (from Berkeley) released with the paper [I-BERT: Integer-only BERT Quantization](https://arxiv.org/abs/2101.01321) by Sehoon Kim, Amir Gholami, Zhewei Yao, Michael W. Mahoney, Kurt Keutzer.
-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.
-1. **[Jukebox](model_doc/jukebox)** (from OpenAI) released with the paper [Jukebox: A Generative Model for Music](https://arxiv.org/pdf/2005.00341.pdf) by Prafulla Dhariwal, Heewoo Jun, Christine Payne, Jong Wook Kim, Alec Radford, Ilya Sutskever.
-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://arxiv.org/abs/1912.13318) by Yiheng Xu, Minghao Li, Lei Cui, Shaohan Huang, Furu Wei, Ming Zhou.
-1. **[LayoutLMv2](model_doc/layoutlmv2)** (from Microsoft Research Asia) released with the paper [LayoutLMv2: Multi-modal Pre-training for Visually-Rich Document Understanding](https://arxiv.org/abs/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.
-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://arxiv.org/abs/2204.08387) by Yupan Huang, Tengchao Lv, Lei Cui, Yutong Lu, Furu Wei.
-1. **[LayoutXLM](model_doc/layoutxlm)** (from Microsoft Research Asia) released with the paper [LayoutXLM: Multimodal Pre-training for Multilingual Visually-rich Document Understanding](https://arxiv.org/abs/2104.08836) by Yiheng Xu, Tengchao Lv, Lei Cui, Guoxin Wang, Yijuan Lu, Dinei Florencio, Cha Zhang, Furu Wei.
-1. **[LED](model_doc/led)** (from AllenAI) released with the paper [Longformer: The Long-Document Transformer](https://arxiv.org/abs/2004.05150) by Iz Beltagy, Matthew E. Peters, Arman Cohan.
-1. **[LeViT](model_doc/levit)** (from Meta AI) released with the paper [LeViT: A Vision Transformer in ConvNet's Clothing for Faster Inference](https://arxiv.org/abs/2104.01136) by Ben Graham, Alaaeldin El-Nouby, Hugo Touvron, Pierre Stock, Armand Joulin, Hervé Jégou, Matthijs Douze.
-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://arxiv.org/abs/2202.13669) by Jiapeng Wang, Lianwen Jin, Kai Ding.
-1. **[Longformer](model_doc/longformer)** (from AllenAI) released with the paper [Longformer: The Long-Document Transformer](https://arxiv.org/abs/2004.05150) by Iz Beltagy, Matthew E. Peters, Arman Cohan.
-1. **[LongT5](model_doc/longt5)** (from Google AI) released with the paper [LongT5: Efficient Text-To-Text Transformer for Long Sequences](https://arxiv.org/abs/2112.07916) by Mandy Guo, Joshua Ainslie, David Uthus, Santiago Ontanon, Jianmo Ni, Yun-Hsuan Sung, Yinfei Yang.
-1. **[LUKE](model_doc/luke)** (from Studio Ousia) released with the paper [LUKE: Deep Contextualized Entity Representations with Entity-aware Self-attention](https://arxiv.org/abs/2010.01057) by Ikuya Yamada, Akari Asai, Hiroyuki Shindo, Hideaki Takeda, Yuji Matsumoto.
-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://arxiv.org/abs/1908.07490) by Hao Tan and Mohit Bansal.
-1. **[M-CTC-T](model_doc/mctct)** (from Facebook) released with the paper [Pseudo-Labeling For Massively Multilingual Speech Recognition](https://arxiv.org/abs/2111.00161) by Loren Lugosch, Tatiana Likhomanenko, Gabriel Synnaeve, and Ronan Collobert.
-1. **[M2M100](model_doc/m2m_100)** (from Facebook) released with the paper [Beyond English-Centric Multilingual Machine Translation](https://arxiv.org/abs/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.
-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.
-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://arxiv.org/abs/2110.08518) by Junlong Li, Yiheng Xu, Lei Cui, Furu Wei.
-1. **[Mask2Former](model_doc/mask2former)** (from FAIR and UIUC) released with the paper [Masked-attention Mask Transformer for Universal Image Segmentation](https://arxiv.org/abs/2112.01527) by Bowen Cheng, Ishan Misra, Alexander G. Schwing, Alexander Kirillov, Rohit Girdhar.
-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://arxiv.org/abs/2107.06278) by Bowen Cheng, Alexander G. Schwing, Alexander Kirillov.
-1. **[mBART](model_doc/mbart)** (from Facebook) released with the paper [Multilingual Denoising Pre-training for Neural Machine Translation](https://arxiv.org/abs/2001.08210) by Yinhan Liu, Jiatao Gu, Naman Goyal, Xian Li, Sergey Edunov, Marjan Ghazvininejad, Mike Lewis, Luke Zettlemoyer.
-1. **[mBART-50](model_doc/mbart)** (from Facebook) released with the paper [Multilingual Translation with Extensible Multilingual Pretraining and Finetuning](https://arxiv.org/abs/2008.00401) by Yuqing Tang, Chau Tran, Xian Li, Peng-Jen Chen, Naman Goyal, Vishrav Chaudhary, Jiatao Gu, Angela Fan.
-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://arxiv.org/abs/1909.08053) by Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper and Bryan Catanzaro.
-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://arxiv.org/abs/1909.08053) by Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper and Bryan Catanzaro.
-1. **[mLUKE](model_doc/mluke)** (from Studio Ousia) released with the paper [mLUKE: The Power of Entity Representations in Multilingual Pretrained Language Models](https://arxiv.org/abs/2110.08151) by Ryokan Ri, Ikuya Yamada, and Yoshimasa Tsuruoka.
-1. **[MobileBERT](model_doc/mobilebert)** (from CMU/Google Brain) released with the paper [MobileBERT: a Compact Task-Agnostic BERT for Resource-Limited Devices](https://arxiv.org/abs/2004.02984) by Zhiqing Sun, Hongkun Yu, Xiaodan Song, Renjie Liu, Yiming Yang, and Denny Zhou.
-1. **[MobileViT](model_doc/mobilevit)** (from Apple) released with the paper [MobileViT: Light-weight, General-purpose, and Mobile-friendly Vision Transformer](https://arxiv.org/abs/2110.02178) by Sachin Mehta and Mohammad Rastegari.
-1. **[MPNet](model_doc/mpnet)** (from Microsoft Research) released with the paper [MPNet: Masked and Permuted Pre-training for Language Understanding](https://arxiv.org/abs/2004.09297) by Kaitao Song, Xu Tan, Tao Qin, Jianfeng Lu, Tie-Yan Liu.
-1. **[MT5](model_doc/mt5)** (from Google AI) released with the paper [mT5: A massively multilingual pre-trained text-to-text transformer](https://arxiv.org/abs/2010.11934) by Linting Xue, Noah Constant, Adam Roberts, Mihir Kale, Rami Al-Rfou, Aditya Siddhant, Aditya Barua, Colin Raffel.
-1. **[MVP](model_doc/mvp)** (from RUC AI Box) released with the paper [MVP: Multi-task Supervised Pre-training for Natural Language Generation](https://arxiv.org/abs/2206.12131) by Tianyi Tang, Junyi Li, Wayne Xin Zhao and Ji-Rong Wen.
-1. **[Nezha](model_doc/nezha)** (from Huawei Noahâs Ark Lab) released with the paper [NEZHA: Neural Contextualized Representation for Chinese Language Understanding](https://arxiv.org/abs/1909.00204) by Junqiu Wei, Xiaozhe Ren, Xiaoguang Li, Wenyong Huang, Yi Liao, Yasheng Wang, Jiashu Lin, Xin Jiang, Xiao Chen and Qun Liu.
-1. **[NLLB](model_doc/nllb)** (from Meta) released with the paper [No Language Left Behind: Scaling Human-Centered Machine Translation](https://arxiv.org/abs/2207.04672) by the NLLB team.
-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://arxiv.org/abs/2102.03902) by Yunyang Xiong, Zhanpeng Zeng, Rudrasis Chakraborty, Mingxing Tan, Glenn Fung, Yin Li, Vikas Singh.
-1. **[OneFormer](model_doc/oneformer)** (from SHI Labs) released with the paper [OneFormer: One Transformer to Rule Universal Image Segmentation](https://arxiv.org/abs/2211.06220) by Jitesh Jain, Jiachen Li, MangTik Chiu, Ali Hassani, Nikita Orlov, Humphrey Shi.
-1. **[OPT](master/model_doc/opt)** (from Meta AI) released with the paper [OPT: Open Pre-trained Transformer Language Models](https://arxiv.org/abs/2205.01068) by Susan Zhang, Stephen Roller, Naman Goyal, Mikel Artetxe, Moya Chen, Shuohui Chen et al.
-1. **[OWL-ViT](model_doc/owlvit)** (from Google AI) released with the paper [Simple Open-Vocabulary Object Detection with Vision Transformers](https://arxiv.org/abs/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.
-1. **[Pegasus](model_doc/pegasus)** (from Google) released with the paper [PEGASUS: Pre-training with Extracted Gap-sentences for Abstractive Summarization](https://arxiv.org/abs/1912.08777) by Jingqing Zhang, Yao Zhao, Mohammad Saleh and Peter J. Liu.
-1. **[PEGASUS-X](model_doc/pegasus_x)** (from Google) released with the paper [Investigating Efficiently Extending Transformers for Long Input Summarization](https://arxiv.org/abs/2208.04347) by Jason Phang, Yao Zhao, and Peter J. Liu.
-1. **[Perceiver IO](model_doc/perceiver)** (from Deepmind) released with the paper [Perceiver IO: A General Architecture for Structured Inputs & Outputs](https://arxiv.org/abs/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.
-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.
-1. **[PLBart](model_doc/plbart)** (from UCLA NLP) released with the paper [Unified Pre-training for Program Understanding and Generation](https://arxiv.org/abs/2103.06333) by Wasi Uddin Ahmad, Saikat Chakraborty, Baishakhi Ray, Kai-Wei Chang.
-1. **[PoolFormer](model_doc/poolformer)** (from Sea AI Labs) released with the paper [MetaFormer is Actually What You Need for Vision](https://arxiv.org/abs/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.
-1. **[ProphetNet](model_doc/prophetnet)** (from Microsoft Research) released with the paper [ProphetNet: Predicting Future N-gram for Sequence-to-Sequence Pre-training](https://arxiv.org/abs/2001.04063) by Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang and Ming Zhou.
-1. **[QDQBert](model_doc/qdqbert)** (from NVIDIA) released with the paper [Integer Quantization for Deep Learning Inference: Principles and Empirical Evaluation](https://arxiv.org/abs/2004.09602) by Hao Wu, Patrick Judd, Xiaojie Zhang, Mikhail Isaev and Paulius Micikevicius.
-1. **[RAG](model_doc/rag)** (from Facebook) released with the paper [Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks](https://arxiv.org/abs/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.
-1. **[REALM](model_doc/realm.html)** (from Google Research) released with the paper [REALM: Retrieval-Augmented Language Model Pre-Training](https://arxiv.org/abs/2002.08909) by Kelvin Guu, Kenton Lee, Zora Tung, Panupong Pasupat and Ming-Wei Chang.
-1. **[Reformer](model_doc/reformer)** (from Google Research) released with the paper [Reformer: The Efficient Transformer](https://arxiv.org/abs/2001.04451) by Nikita Kitaev, Ćukasz Kaiser, Anselm Levskaya.
-1. **[RegNet](model_doc/regnet)** (from META Platforms) released with the paper [Designing Network Design Space](https://arxiv.org/abs/2003.13678) by Ilija Radosavovic, Raj Prateek Kosaraju, Ross Girshick, Kaiming He, Piotr DollĂĄr.
-1. **[RemBERT](model_doc/rembert)** (from Google Research) released with the paper [Rethinking embedding coupling in pre-trained language models](https://arxiv.org/abs/2010.12821) by Hyung Won Chung, Thibault Févry, Henry Tsai, M. Johnson, Sebastian Ruder.
-1. **[ResNet](model_doc/resnet)** (from Microsoft Research) released with the paper [Deep Residual Learning for Image Recognition](https://arxiv.org/abs/1512.03385) by Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun.
-1. **[RoBERTa](model_doc/roberta)** (from Facebook), released together with the paper [RoBERTa: A Robustly Optimized BERT Pretraining Approach](https://arxiv.org/abs/1907.11692) by Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Mandar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, Veselin Stoyanov.
-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.
-1. **[RoFormer](model_doc/roformer)** (from ZhuiyiTechnology), released together with the paper [RoFormer: Enhanced Transformer with Rotary Position Embedding](https://arxiv.org/abs/2104.09864) by Jianlin Su and Yu Lu and Shengfeng Pan and Bo Wen and Yunfeng Liu.
-1. **[SegFormer](model_doc/segformer)** (from NVIDIA) released with the paper [SegFormer: Simple and Efficient Design for Semantic Segmentation with Transformers](https://arxiv.org/abs/2105.15203) by Enze Xie, Wenhai Wang, Zhiding Yu, Anima Anandkumar, Jose M. Alvarez, Ping Luo.
-1. **[SEW](model_doc/sew)** (from ASAPP) released with the paper [Performance-Efficiency Trade-offs in Unsupervised Pre-training for Speech Recognition](https://arxiv.org/abs/2109.06870) by Felix Wu, Kwangyoun Kim, Jing Pan, Kyu Han, Kilian Q. Weinberger, Yoav Artzi.
-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://arxiv.org/abs/2109.06870) by Felix Wu, Kwangyoun Kim, Jing Pan, Kyu Han, Kilian Q. Weinberger, Yoav Artzi.
-1. **[SpeechToTextTransformer](model_doc/speech_to_text)** (from Facebook), released together with the paper [fairseq S2T: Fast Speech-to-Text Modeling with fairseq](https://arxiv.org/abs/2010.05171) by Changhan Wang, Yun Tang, Xutai Ma, Anne Wu, Dmytro Okhonko, Juan Pino.
-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://arxiv.org/abs/2104.06678) by Changhan Wang, Anne Wu, Juan Pino, Alexei Baevski, Michael Auli, Alexis Conneau.
-1. **[Splinter](model_doc/splinter)** (from Tel Aviv University), released together with the paper [Few-Shot Question Answering by Pretraining Span Selection](https://arxiv.org/abs/2101.00438) by Ori Ram, Yuval Kirstain, Jonathan Berant, Amir Globerson, Omer Levy.
-1. **[SqueezeBERT](model_doc/squeezebert)** (from Berkeley) released with the paper [SqueezeBERT: What can computer vision teach NLP about efficient neural networks?](https://arxiv.org/abs/2006.11316) by Forrest N. Iandola, Albert E. Shaw, Ravi Krishna, and Kurt W. Keutzer.
-1. **[Swin Transformer](model_doc/swin)** (from Microsoft) released with the paper [Swin Transformer: Hierarchical Vision Transformer using Shifted Windows](https://arxiv.org/abs/2103.14030) by Ze Liu, Yutong Lin, Yue Cao, Han Hu, Yixuan Wei, Zheng Zhang, Stephen Lin, Baining Guo.
-1. **[Swin Transformer V2](model_doc/swinv2)** (from Microsoft) released with the paper [Swin Transformer V2: Scaling Up Capacity and Resolution](https://arxiv.org/abs/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.
-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://arxiv.org/abs/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.
-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.
-1. **[Table Transformer](model_doc/table-transformer)** (from Microsoft Research) released with the paper [PubTables-1M: Towards Comprehensive Table Extraction From Unstructured Documents](https://arxiv.org/abs/2110.00061) by Brandon Smock, Rohith Pesala, Robin Abraham.
-1. **[TAPAS](model_doc/tapas)** (from Google AI) released with the paper [TAPAS: Weakly Supervised Table Parsing via Pre-training](https://arxiv.org/abs/2004.02349) by Jonathan Herzig, PaweĆ Krzysztof Nowak, Thomas MĂŒller, Francesco Piccinno and Julian Martin Eisenschlos.
-1. **[TAPEX](model_doc/tapex)** (from Microsoft Research) released with the paper [TAPEX: Table Pre-training via Learning a Neural SQL Executor](https://arxiv.org/abs/2107.07653) by Qian Liu, Bei Chen, Jiaqi Guo, Morteza Ziyadi, Zeqi Lin, Weizhu Chen, Jian-Guang Lou.
-1. **[Time Series Transformer](model_doc/time_series_transformer)** (from HuggingFace).
-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://arxiv.org/abs/2106.02039) by Michael Janner, Qiyang Li, Sergey Levine
-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://arxiv.org/abs/1901.02860) by Zihang Dai*, Zhilin Yang*, Yiming Yang, Jaime Carbonell, Quoc V. Le, Ruslan Salakhutdinov.
-1. **[TrOCR](model_doc/trocr)** (from Microsoft), released together with the paper [TrOCR: Transformer-based Optical Character Recognition with Pre-trained Models](https://arxiv.org/abs/2109.10282) by Minghao Li, Tengchao Lv, Lei Cui, Yijuan Lu, Dinei Florencio, Cha Zhang, Zhoujun Li, Furu Wei.
-1. **[UL2](model_doc/ul2)** (from Google Research) released with the paper [Unifying Language Learning Paradigms](https://arxiv.org/abs/2205.05131v1) by Yi Tay, Mostafa Dehghani, Vinh Q. Tran, Xavier Garcia, Dara Bahri, Tal Schuster, Huaixiu Steven Zheng, Neil Houlsby, Donald Metzler
-1. **[UniSpeech](model_doc/unispeech)** (from Microsoft Research) released with the paper [UniSpeech: Unified Speech Representation Learning with Labeled and Unlabeled Data](https://arxiv.org/abs/2101.07597) by Chengyi Wang, Yu Wu, Yao Qian, Kenichi Kumatani, Shujie Liu, Furu Wei, Michael Zeng, Xuedong Huang.
-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://arxiv.org/abs/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.
-1. **[VAN](model_doc/van)** (from Tsinghua University and Nankai University) released with the paper [Visual Attention Network](https://arxiv.org/abs/2202.09741) by Meng-Hao Guo, Cheng-Ze Lu, Zheng-Ning Liu, Ming-Ming Cheng, Shi-Min Hu.
-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://arxiv.org/abs/2203.12602) by Zhan Tong, Yibing Song, Jue Wang, Limin Wang.
-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://arxiv.org/abs/2102.03334) by Wonjae Kim, Bokyung Son, Ildoo Kim.
-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://arxiv.org/abs/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.
-1. **[VisualBERT](model_doc/visual_bert)** (from UCLA NLP) released with the paper [VisualBERT: A Simple and Performant Baseline for Vision and Language](https://arxiv.org/pdf/1908.03557) by Liunian Harold Li, Mark Yatskar, Da Yin, Cho-Jui Hsieh, Kai-Wei Chang.
-1. **[ViTMAE](model_doc/vit_mae)** (from Meta AI) released with the paper [Masked Autoencoders Are Scalable Vision Learners](https://arxiv.org/abs/2111.06377) by Kaiming He, Xinlei Chen, Saining Xie, Yanghao Li, Piotr DollĂĄr, Ross Girshick.
-1. **[ViTMSN](model_doc/vit_msn)** (from Meta AI) released with the paper [Masked Siamese Networks for Label-Efficient Learning](https://arxiv.org/abs/2204.07141) by Mahmoud Assran, Mathilde Caron, Ishan Misra, Piotr Bojanowski, Florian Bordes, Pascal Vincent, Armand Joulin, Michael Rabbat, Nicolas Ballas.
-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://arxiv.org/abs/2006.11477) by Alexei Baevski, Henry Zhou, Abdelrahman Mohamed, Michael Auli.
-1. **[Wav2Vec2-Conformer](model_doc/wav2vec2-conformer)** (from Facebook AI) released with the paper [FAIRSEQ S2T: Fast Speech-to-Text Modeling with FAIRSEQ](https://arxiv.org/abs/2010.05171) by Changhan Wang, Yun Tang, Xutai Ma, Anne Wu, Sravya Popuri, Dmytro Okhonko, Juan Pino.
-1. **[Wav2Vec2Phoneme](model_doc/wav2vec2_phoneme)** (from Facebook AI) released with the paper [Simple and Effective Zero-shot Cross-lingual Phoneme Recognition](https://arxiv.org/abs/2109.11680) by Qiantong Xu, Alexei Baevski, Michael Auli.
-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://arxiv.org/abs/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.
-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.
-1. **[X-CLIP](model_doc/xclip)** (from Microsoft Research) released with the paper [Expanding Language-Image Pretrained Models for General Video Recognition](https://arxiv.org/abs/2208.02816) by Bolin Ni, Houwen Peng, Minghao Chen, Songyang Zhang, Gaofeng Meng, Jianlong Fu, Shiming Xiang, Haibin Ling.
-1. **[XGLM](model_doc/xglm)** (From Facebook AI) released with the paper [Few-shot Learning with Multilingual Language Models](https://arxiv.org/abs/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.
-1. **[XLM](model_doc/xlm)** (from Facebook) released together with the paper [Cross-lingual Language Model Pretraining](https://arxiv.org/abs/1901.07291) by Guillaume Lample and Alexis Conneau.
-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://arxiv.org/abs/2001.04063) by Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang and Ming Zhou.
-1. **[XLM-RoBERTa](model_doc/xlm-roberta)** (from Facebook AI), released together with the paper [Unsupervised Cross-lingual Representation Learning at Scale](https://arxiv.org/abs/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.
-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://arxiv.org/abs/2105.00572) by Naman Goyal, Jingfei Du, Myle Ott, Giri Anantharaman, Alexis Conneau.
-1. **[XLNet](model_doc/xlnet)** (from Google/CMU) released with the paper [âXLNet: Generalized Autoregressive Pretraining for Language Understanding](https://arxiv.org/abs/1906.08237) by Zhilin Yang*, Zihang Dai*, Yiming Yang, Jaime Carbonell, Ruslan Salakhutdinov, Quoc V. Le.
-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://arxiv.org/abs/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.
-1. **[XLSR-Wav2Vec2](model_doc/xlsr_wav2vec2)** (from Facebook AI) released with the paper [Unsupervised Cross-Lingual Representation Learning For Speech Recognition](https://arxiv.org/abs/2006.13979) by Alexis Conneau, Alexei Baevski, Ronan Collobert, Abdelrahman Mohamed, Michael Auli.
-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://arxiv.org/abs/2106.00666) by Yuxin Fang, Bencheng Liao, Xinggang Wang, Jiemin Fang, Jiyang Qi, Rui Wu, Jianwei Niu, Wenyu Liu.
-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://arxiv.org/abs/2111.09714) by Zhanpeng Zeng, Yunyang Xiong, Sathya N. Ravi, Shailesh Acharya, Glenn Fung, Vikas Singh.
-
-
-### ì§ì íë ììíŹ[[supported-framework]]
-
-ìë íë ëŒìŽëžëŹëŠŹ ì ê° ëȘšëžì ì§ì íí©ì ëíë
ëë€. í í°í넌 íìŽìŹ (ëłìč "slow") ëë đ€ Tokenizers (ëłìč "fast") ëŒìŽëžëŹëŠŹëĄ íëì§; (Flax넌 í”í) Jax, PyTorch, TensorFlow ì€ ìŽë€ íë ììíŹë„Œ ì§ìíëì§ íìëìŽ ìì”ëë€.
-
-
-
-| Model | Tokenizer slow | Tokenizer fast | PyTorch support | TensorFlow support | Flax Support |
-|:---------------------------:|:--------------:|:--------------:|:---------------:|:------------------:|:------------:|
-| ALBERT | â
| â
| â
| â
| â
|
-| BART | â
| â
| â
| â
| â
|
-| BEiT | â | â | â
| â | â
|
-| BERT | â
| â
| â
| â
| â
|
-| Bert Generation | â
| â | â
| â | â |
-| BigBird | â
| â
| â
| â | â
|
-| BigBird-Pegasus | â | â | â
| â | â |
-| Blenderbot | â
| â
| â
| â
| â
|
-| BlenderbotSmall | â
| â
| â
| â
| â
|
-| BLOOM | â | â
| â
| â | â |
-| CamemBERT | â
| â
| â
| â
| â |
-| CANINE | â
| â | â
| â | â |
-| CLIP | â
| â
| â
| â
| â
|
-| CLIPSeg | â | â | â
| â | â |
-| CodeGen | â
| â
| â
| â | â |
-| Conditional DETR | â | â | â
| â | â |
-| ConvBERT | â
| â
| â
| â
| â |
-| ConvNeXT | â | â | â
| â
| â |
-| CTRL | â
| â | â
| â
| â |
-| CvT | â | â | â
| â
| â |
-| Data2VecAudio | â | â | â
| â | â |
-| Data2VecText | â | â | â
| â | â |
-| Data2VecVision | â | â | â
| â
| â |
-| DeBERTa | â
| â
| â
| â
| â |
-| DeBERTa-v2 | â
| â
| â
| â
| â |
-| Decision Transformer | â | â | â
| â | â |
-| Deformable DETR | â | â | â
| â | â |
-| DeiT | â | â | â
| â
| â |
-| DETR | â | â | â
| â | â |
-| DistilBERT | â
| â
| â
| â
| â
|
-| DonutSwin | â | â | â
| â | â |
-| DPR | â
| â
| â
| â
| â |
-| DPT | â | â | â
| â | â |
-| ELECTRA | â
| â
| â
| â
| â
|
-| Encoder decoder | â | â | â
| â
| â
|
-| ERNIE | â | â | â
| â | â |
-| ESM | â
| â | â
| â
| â |
-| FairSeq Machine-Translation | â
| â | â
| â | â |
-| FlauBERT | â
| â | â
| â
| â |
-| FLAVA | â | â | â
| â | â |
-| FNet | â
| â
| â
| â | â |
-| Funnel Transformer | â
| â
| â
| â
| â |
-| GLPN | â | â | â
| â | â |
-| GPT Neo | â | â | â
| â | â
|
-| GPT NeoX | â | â
| â
| â | â |
-| GPT NeoX Japanese | â
| â | â
| â | â |
-| GPT-J | â | â | â
| â
| â
|
-| GroupViT | â | â | â
| â
| â |
-| Hubert | â | â | â
| â
| â |
-| I-BERT | â | â | â
| â | â |
-| ImageGPT | â | â | â
| â | â |
-| Jukebox | â
| â | â
| â | â |
-| LayoutLM | â
| â
| â
| â
| â |
-| LayoutLMv2 | â
| â
| â
| â | â |
-| LayoutLMv3 | â
| â
| â
| â
| â |
-| LED | â
| â
| â
| â
| â |
-| LeViT | â | â | â
| â | â |
-| LiLT | â | â | â
| â | â |
-| Longformer | â
| â
| â
| â
| â |
-| LongT5 | â | â | â
| â | â
|
-| LUKE | â
| â | â
| â | â |
-| LXMERT | â
| â
| â
| â
| â |
-| M-CTC-T | â | â | â
| â | â |
-| M2M100 | â
| â | â
| â | â |
-| Marian | â
| â | â
| â
| â
|
-| MarkupLM | â
| â
| â
| â | â |
-| MaskFormer | â | â | â
| â | â |
-| mBART | â
| â
| â
| â
| â
|
-| Megatron-BERT | â | â | â
| â | â |
-| MobileBERT | â
| â
| â
| â
| â |
-| MobileViT | â | â | â
| â
| â |
-| MPNet | â
| â
| â
| â
| â |
-| MT5 | â
| â
| â
| â
| â
|
-| MVP | â
| â
| â
| â | â |
-| Nezha | â | â | â
| â | â |
-| Nyströmformer | â | â | â
| â | â |
-| OpenAI GPT | â
| â
| â
| â
| â |
-| OpenAI GPT-2 | â
| â
| â
| â
| â
|
-| OPT | â | â | â
| â
| â
|
-| OWL-ViT | â | â | â
| â | â |
-| Pegasus | â
| â
| â
| â
| â
|
-| PEGASUS-X | â | â | â
| â | â |
-| Perceiver | â
| â | â
| â | â |
-| PLBart | â
| â | â
| â | â |
-| PoolFormer | â | â | â
| â | â |
-| ProphetNet | â
| â | â
| â | â |
-| QDQBert | â | â | â
| â | â |
-| RAG | â
| â | â
| â
| â |
-| REALM | â
| â
| â
| â | â |
-| Reformer | â
| â
| â
| â | â |
-| RegNet | â | â | â
| â
| â
|
-| RemBERT | â
| â
| â
| â
| â |
-| ResNet | â | â | â
| â
| â
|
-| RetriBERT | â
| â
| â
| â | â |
-| RoBERTa | â
| â
| â
| â
| â
|
-| RoCBert | â
| â | â
| â | â |
-| RoFormer | â
| â
| â
| â
| â
|
-| SegFormer | â | â | â
| â
| â |
-| SEW | â | â | â
| â | â |
-| SEW-D | â | â | â
| â | â |
-| Speech Encoder decoder | â | â | â
| â | â
|
-| Speech2Text | â
| â | â
| â
| â |
-| Speech2Text2 | â
| â | â | â | â |
-| Splinter | â
| â
| â
| â | â |
-| SqueezeBERT | â
| â
| â
| â | â |
-| Swin Transformer | â | â | â
| â
| â |
-| Swin Transformer V2 | â | â | â
| â | â |
-| T5 | â
| â
| â
| â
| â
|
-| Table Transformer | â | â | â
| â | â |
-| TAPAS | â
| â | â
| â
| â |
-| Time Series Transformer | â | â | â
| â | â |
-| Trajectory Transformer | â | â | â
| â | â |
-| Transformer-XL | â
| â | â
| â
| â |
-| TrOCR | â | â | â
| â | â |
-| UniSpeech | â | â | â
| â | â |
-| UniSpeechSat | â | â | â
| â | â |
-| VAN | â | â | â
| â | â |
-| VideoMAE | â | â | â
| â | â |
-| ViLT | â | â | â
| â | â |
-| Vision Encoder decoder | â | â | â
| â
| â
|
-| VisionTextDualEncoder | â | â | â
| â | â
|
-| VisualBERT | â | â | â
| â | â |
-| ViT | â | â | â
| â
| â
|
-| ViTMAE | â | â | â
| â
| â |
-| ViTMSN | â | â | â
| â | â |
-| Wav2Vec2 | â
| â | â
| â
| â
|
-| Wav2Vec2-Conformer | â | â | â
| â | â |
-| WavLM | â | â | â
| â | â |
-| Whisper | â
| â | â
| â
| â |
-| X-CLIP | â | â | â
| â | â |
-| XGLM | â
| â
| â
| â
| â
|
-| XLM | â
| â | â
| â
| â |
-| XLM-ProphetNet | â
| â | â
| â | â |
-| XLM-RoBERTa | â
| â
| â
| â
| â
|
-| XLM-RoBERTa-XL | â | â | â
| â | â |
-| XLNet | â
| â
| â
| â
| â |
-| YOLOS | â | â | â
| â | â |
-| YOSO | â | â | â
| â | â |
-
-
diff --git a/docs/source/ko/installation.md b/docs/source/ko/installation.md
new file mode 100644
index 000000000000..cd72d8c6bcbf
--- /dev/null
+++ b/docs/source/ko/installation.md
@@ -0,0 +1,245 @@
+
+
+# ì€ìčë°©ëČ[[installation]]
+
+đ€ Transformers넌 ìŹì© ì€ìž ë„ëŹë ëŒìŽëžëŹëŠŹì ë§ì¶° ì€ìčíêł , ìșì넌 ê”Źì±íê±°ë ì íì ìŒëĄ ì€íëŒìžììë ì€íí ì ìëëĄ đ€ Transformers넌 ì€ì íë ë°©ëČì ë°°ì°êČ ì”ëë€.
+
+đ€ Transformersë Python 3.6+, PyTorch 1.1.0+, TensorFlow 2.0+ ë° Flaxìì í
ì€ížëìì”ëë€. ë„ëŹë ëŒìŽëžëŹëŠŹë„Œ ì€ìčíë €ë©Ž ìë ë§íŹë ì ë§ë€ì êł”ì ìŹìŽížë„Œ ì°žêł íŽìŁŒìžì.
+
+* [PyTorch](https://pytorch.org/get-started/locally/) ì€ìčíêž°
+* [TensorFlow 2.0](https://www.tensorflow.org/install/pip) ì€ìčíêž°
+* [Flax](https://flax.readthedocs.io/en/latest/) ì€ìčíêž°
+
+## pipìŒëĄ ì€ìčíêž°[[install-with-pip]]
+
+đ€ Transformers넌 [ê°ì íêČœ](https://docs.python.org/3/library/venv.html)ì ì€ìčíë êČì ì¶ìČë늜ëë€. Python ê°ì íêČœì ì”ìíì§ ìë€ë©Ž, ìŽ [ê°ìŽë](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/)넌 ì°žêł íìžì. ê°ì íêČœì ìŹì©í멎 ìëĄ ë€ë„ž íëĄì ížë€ì ëłŽë€ ìœêČ êŽëŠŹí ì ìêł , ììĄŽì± ê°ì ížíì± ëŹžì 넌 ë°©ì§í ì ìì”ëë€.
+
+뚌ì íëĄì íž ëë í 늏ìì ê°ì íêČœì ë§ë€ìŽ ì€ëë€.
+
+```bash
+python -m venv .env
+```
+
+ê°ì íêČœì íì±ííŽìŁŒìžì. Linuxë MacOSì êČœì°:
+
+```bash
+source .env/bin/activate
+```
+Windowsì êČœì°:
+
+```bash
+.env/Scripts/activate
+```
+
+ìŽì đ€ Transformers넌 ì€ìčí ì€ëčê° ëìì”ëë€. ë€ì ëȘ
ë čì ì
ë „íŽìŁŒìžì.
+
+```bash
+pip install transformers
+```
+
+CPUë§ ìšë ëë€ë©Ž, đ€ Transformersì ë„ëŹë ëŒìŽëžëŹëŠŹë„Œ ëš 1ì€ëĄ ì€ìčí ì ìì”ëë€. ì넌 ë€ìŽ đ€ Transformersì PyTorchì êČœì°:
+
+```bash
+pip install transformers[torch]
+```
+
+đ€ Transformersì TensorFlow 2.0ì êČœì°:
+
+```bash
+pip install transformers[tf-cpu]
+```
+
+đ€ Transformersì Flaxì êČœì°:
+
+```bash
+pip install transformers[flax]
+```
+
+ë§ì§ë§ìŒëĄ đ€ Transformersê° ì ëëĄ ì€ìčëìëì§ íìží ì°šëĄì
ëë€. ìŹì íë šë ëȘšëžì ë€ìŽëĄëíë ìœëì
ëë€.
+
+```bash
+python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('we love you'))"
+```
+
+ëŒëČšêłŒ ì ìê° ì¶ë „ë멎 ì ì€ìčë êČì
ëë€.
+
+```bash
+[{'label': 'POSITIVE', 'score': 0.9998704791069031}]
+```
+
+## ìì€ìì ì€ìčíêž°[[install-from-source]]
+
+đ€ Transformers넌 ìì€ìì ì€ìčíë €ë©Ž ìë ëȘ
ë čì ì€ííìžì.
+
+```bash
+pip install git+https://github.com/huggingface/transformers
+```
+
+ì ëȘ
ë čì ì”ì ìŽì§ë§ (ìì ì ìž) `stable` ëČì ìŽ ìë ì€íì±ìŽ ì§ì `main` ëČì ì ì€ìčí©ëë€. `main` ëČì ì ê°ë° íí©êłŒ ë°ë§ì¶ëë° ì ì©í©ëë€. ììëĄ ë§ì§ë§ êł”ì ëŠŽëŠŹì€ ìŽí ë°êČŹë ëČê·žê° íšìčëìì§ë§, ì 늎늏ì€ëĄ ìì§ ëĄ€ììëì§ë ìì êČœì°ë„Œ ë€ ì ìì”ëë€. ë°êż ë§í멎 `main` ëČì ìŽ ìì ì±êłŒë ê±°ëŠŹê° ìë€ë ë»ìŽêž°ë í©ëë€. ì íŹë `main` ëČì ì ìŹì©íëë° ëŹžì ê° ìëëĄ ë
žë „íêł ììŒë©°, ëë¶ë¶ì 돞ì ë ëê° ëȘ ìê°ìŽë í룚 ìì íŽêȰë©ëë€. ë§ìœ 돞ì ê° ë°ìí멎 [ìŽì](https://github.com/huggingface/transformers/issues)넌 ìŽìŽìŁŒì멎 ë ëčšëŠŹ íŽêȰí ì ìì”ëë€!
+
+ì êłŒ ë§ì°Źê°ì§ëĄ đ€ Transformersê° ì ëëĄ ì€ìčëìëì§ íìží ì°šëĄì
ëë€.
+
+```bash
+python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('I love you'))"
+```
+
+## ìì ê°ë„í ì€ìč[[editable-install]]
+
+ìì ê°ë„í ì€ìčê° íìí êČœì°ë ë€ìêłŒ ê°ì”ëë€.
+
+* `main` ëČì ì ìì€ ìœë넌 ìŹì©íêž° ìíŽ
+* đ€ Transformersì êž°ìŹíêł ì¶ìŽì ìœëì ëłêČœ ìŹíì í
ì€ížíêž° ìíŽ
+
+늏íŹì§í°ëŠŹë„Œ ëł”ì íêł đ€ Transformers넌 ì€ìčíë €ë©Ž ë€ì ëȘ
ë čì ì
ë „íŽìŁŒìžì.
+
+```bash
+git clone https://github.com/huggingface/transformers.git
+cd transformers
+pip install -e .
+```
+
+ì ëȘ
ë čì 늏íŹì§í°ëŠŹë„Œ ëł”ì í ììčì íŽëì Python ëŒìŽëžëŹëŠŹì êČœëĄë„Œ ì°êȰìí”ëë€. PythonìŽ ìŒë° ëŒìŽëžëŹëŠŹ êČœëĄ ìžì ëł”ì í íŽë ëŽë¶ë„Œ íìží êČì
ëë€. ì넌 ë€ìŽ Python íší€ì§ê° ìŒë°ì ìŒëĄ `~/anaconda3/envs/main/lib/python3.7/site-packages/`ì ì€ìčëìŽ ìëë°, ëȘ
ë čì ë°ì PythonìŽ ìŽì ëł”ì í íŽëìž `~/transformers/`ë êČìíêČ ë©ëë€.
+
+
+
+ëŒìŽëžëŹëŠŹë„Œ êłì ìŹì©íë €ë©Ž `transformers` íŽë넌 êŒ ì ì§íŽìŒ í©ëë€.
+
+
+
+ëł”ì ëłžì ì”ì ëČì ì đ€ TransformersëĄ ìœêČ ì
ë°ìŽíží ì ìì”ëë€.
+
+```bash
+cd ~/transformers/
+git pull
+```
+
+Python íêČœì ë€ì ì€íí멎 ì
ë°ìŽížë đ€ Transformersì `main` ëČì ì ì°ŸìëŒ êČì
ëë€.
+
+## condaëĄ ì€ìčíêž°[[install-with-conda]]
+
+`huggingface` conda ì±ëìì ì€ìčí ì ìì”ëë€.
+
+```bash
+conda install -c huggingface transformers
+```
+
+## ìșì ê”Źì±íêž°[[cache-setup]]
+
+ìŹì íë šë ëȘšëžì ë€ìŽëĄëë í ëĄì»Ź êČœëĄ `~/.cache/huggingface/hub`ì ìșìë©ëë€. ì
ž íêČœ ëłì `TRANSFORMERS_CACHE`ì êž°ëłž ëë í°ëŠŹì
ëë€. Windowsì êČœì° êž°ëłž ëë í°ëŠŹë `C:\Users\username\.cache\huggingface\hub`ì
ëë€. ìëì ì
ž íêČœ ëłì넌 (ì°ì ìì) ììëëĄ ëłêČœíìŹ ë€ë„ž ìșì ëë í ëŠŹë„Œ ì§ì í ì ìì”ëë€.
+
+1. ì
ž íêČœ ëłì (êž°ëłž): `HUGGINGFACE_HUB_CACHE` ëë `TRANSFORMERS_CACHE`
+2. ì
ž íêČœ ëłì: `HF_HOME`
+3. ì
ž íêČœ ëłì: `XDG_CACHE_HOME` + `/huggingface`
+
+
+
+êłŒê±° đ€ Transformersìì ì°ìë ì
ž íêČœ ëłì `PYTORCH_TRANSFORMERS_CACHE` ëë `PYTORCH_PRETRAINED_BERT_CACHE`ìŽ ì€ì ëìë€ë©Ž, ì
ž íêČœ ëłì `TRANSFORMERS_CACHE`ì ì§ì íì§ ìë í ì°ì ìŹì©ë©ëë€.
+
+
+
+## ì€íëŒìž ëȘšë[[offline-mode]]
+
+đ€ Transformers넌 ëĄì»Ź íìŒë§ ìŹì©íëëĄ íŽì ë°©íëČœ ëë ì€íëŒìž íêČœìì ì€íí ì ìì”ëë€. íì±ííë €ë©Ž `TRANSFORMERS_OFFLINE=1` íêČœ ëłì넌 ì€ì íìžì.
+
+
+
+`HF_DATASETS_OFFLINE=1` íêČœ ëłì넌 ì€ì íìŹ ì€íëŒìž íë š êłŒì ì [đ€ Datasets](https://huggingface.co/docs/datasets/)ì ì¶ê°í ì ìì”ëë€.
+
+
+
+ì넌 ë€ìŽ ìžë¶ êž°êž° ìŹìŽì ë°©íëČœì ë ìŒë° ë€ížìíŹìì íììČëŒ íëĄê·žëšì ë€ìêłŒ ê°ìŽ ì€íí ì ìì”ëë€.
+
+```bash
+python examples/pytorch/translation/run_translation.py --model_name_or_path t5-small --dataset_name wmt16 --dataset_config ro-en ...
+```
+
+ì€íëŒìž êž°êž°ìì ëìŒí íëĄê·žëšì ë€ìêłŒ ê°ìŽ ì€íí ì ìì”ëë€.
+
+```bash
+HF_DATASETS_OFFLINE=1 TRANSFORMERS_OFFLINE=1 \
+python examples/pytorch/translation/run_translation.py --model_name_or_path t5-small --dataset_name wmt16 --dataset_config ro-en ...
+```
+
+ìŽì ì€íŹëŠœížë ëĄì»Ź íìŒì ííŽìë§ êČìí êČìŽëŻëĄ, ì€íŹëŠœížê° ì€ëšëê±°ë ìê°ìŽ ìŽêłŒë ëêčì§ ë©ì¶°ìì§ ìêł ì ì€íë êČì
ëë€.
+
+### ì€íëŒìžì© ëȘšëž ë° í íŹëìŽì ë§ë€ìŽëêž°[[fetch-models-and-tokenizers-to-use-offline]]
+
+Another option for using đ€ Transformers offline is to download the files ahead of time, and then point to their local path when you need to use them offline. There are three ways to do this:
+đ€ Transformers넌 ì€íëŒìžìŒëĄ ìŹì©íë ë ë€ë„ž ë°©ëČì íìŒì 믞늏 ë€ìŽëĄëí ë€ì, ì€íëŒìžìŒ ë ìŹì©í ëĄì»Ź êČœëĄë„Œ ì§ì íŽëë êČì
ëë€. 3ê°ì§ ì€ íží ë°©ëČì êł ë„Žìžì.
+
+* [Model Hub](https://huggingface.co/models)ì UI넌 í”íŽ íìŒì ë€ìŽëĄëíë €ë©Ž â ììŽìœì íŽëŠíìžì.
+
+ 
+
+* [`PreTrainedModel.from_pretrained`]ì [`PreTrainedModel.save_pretrained`] ìíŹíëĄë„Œ íì©íìžì.
+
+ 1. 믞늏 [`PreTrainedModel.from_pretrained`]ëĄ íìŒì ë€ìŽëĄëíŽëìžì.
+
+ ```py
+ >>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("bigscience/T0_3B")
+ >>> model = AutoModelForSeq2SeqLM.from_pretrained("bigscience/T0_3B")
+ ```
+
+ 2. [`PreTrainedModel.save_pretrained`]ëĄ ì§ì ë êČœëĄì íìŒì ì ì„íŽëìžì.
+
+ ```py
+ >>> tokenizer.save_pretrained("./your/path/bigscience_t0")
+ >>> model.save_pretrained("./your/path/bigscience_t0")
+ ```
+
+ 3. ìŽì ì€íëŒìžìŒ ë [`PreTrainedModel.from_pretrained`]ëĄ ì ì„íŽëë íìŒì ì§ì ë êČœëĄìì ë€ì ë¶ëŹì€ìžì.
+
+ ```py
+ >>> tokenizer = AutoTokenizer.from_pretrained("./your/path/bigscience_t0")
+ >>> model = AutoModel.from_pretrained("./your/path/bigscience_t0")
+ ```
+
+* [huggingface_hub](https://github.com/huggingface/huggingface_hub/tree/main/src/huggingface_hub) ëŒìŽëžëŹëŠŹë„Œ íì©íŽì íìŒì ë€ìŽëĄëíìžì.
+
+ 1. ê°ìíêČœì `huggingface_hub` ëŒìŽëžëŹëŠŹë„Œ ì€ìčíìžì.
+
+ ```bash
+ python -m pip install huggingface_hub
+ ```
+
+ 2. [`hf_hub_download`](https://huggingface.co/docs/hub/adding-a-library#download-files-from-the-hub) íšìëĄ íìŒì íčì ììčì ë€ìŽëĄëí ì ìì”ëë€. ì넌 ë€ìŽ ìë ëȘ
ë čì [T0](https://huggingface.co/bigscience/T0_3B) ëȘšëžì `config.json` íìŒì ì§ì ë êČœëĄì ë€ìŽëĄëí©ëë€.
+
+ ```py
+ >>> from huggingface_hub import hf_hub_download
+
+ >>> hf_hub_download(repo_id="bigscience/T0_3B", filename="config.json", cache_dir="./your/path/bigscience_t0")
+ ```
+
+íìŒì ë€ìŽëĄëíêł ëĄì»Źì ìșì íŽëêł ë멎, ëì€ì ë¶ëŹì ìŹì©í ì ìëëĄ ëĄì»Ź êČœëĄë„Œ ì§ì íŽëìžì.
+
+```py
+>>> from transformers import AutoConfig
+
+>>> config = AutoConfig.from_pretrained("./your/path/bigscience_t0/config.json")
+```
+
+
+
+Hubì ì ì„ë íìŒì ë€ìŽëĄëíë ë°©ëČì ë ììží ììëłŽë €ë©Ž [Hubìì íìŒ ë€ìŽëĄëíêž°](https://huggingface.co/docs/hub/how-to-downstream) ìčì
ì ì°žêł íŽìŁŒìžì.
+
+
\ No newline at end of file
diff --git a/docs/source/ko/installation.mdx b/docs/source/ko/installation.mdx
deleted file mode 100644
index 6ca9a7b31355..000000000000
--- a/docs/source/ko/installation.mdx
+++ /dev/null
@@ -1,241 +0,0 @@
-
-
-# ì€ìčë°©ëČ[[installation]]
-
-đ€ Transformers넌 ìŹì© ì€ìž ë„ëŹë ëŒìŽëžëŹëŠŹì ë§ì¶° ì€ìčíêł , ìșì넌 ê”Źì±íê±°ë ì íì ìŒëĄ ì€íëŒìžììë ì€íí ì ìëëĄ đ€ Transformers넌 ì€ì íë ë°©ëČì ë°°ì°êČ ì”ëë€.
-
-đ€ Transformersë Python 3.6+, PyTorch 1.1.0+, TensorFlow 2.0+ ë° Flaxìì í
ì€ížëìì”ëë€. ë„ëŹë ëŒìŽëžëŹëŠŹë„Œ ì€ìčíë €ë©Ž ìë ë§íŹë ì ë§ë€ì êł”ì ìŹìŽížë„Œ ì°žêł íŽìŁŒìžì.
-
-* [PyTorch](https://pytorch.org/get-started/locally/) ì€ìčíêž°
-* [TensorFlow 2.0](https://www.tensorflow.org/install/pip) ì€ìčíêž°
-* [Flax](https://flax.readthedocs.io/en/latest/) ì€ìčíêž°
-
-## pipìŒëĄ ì€ìčíêž°[[install-with-pip]]
-
-đ€ Transformers넌 [ê°ì íêČœ](https://docs.python.org/3/library/venv.html)ì ì€ìčíë êČì ì¶ìČë늜ëë€. Python ê°ì íêČœì ì”ìíì§ ìë€ë©Ž, ìŽ [ê°ìŽë](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/)넌 ì°žêł íìžì. ê°ì íêČœì ìŹì©í멎 ìëĄ ë€ë„ž íëĄì ížë€ì ëłŽë€ ìœêČ êŽëŠŹí ì ìêł , ììĄŽì± ê°ì ížíì± ëŹžì 넌 ë°©ì§í ì ìì”ëë€.
-
-뚌ì íëĄì íž ëë í 늏ìì ê°ì íêČœì ë§ë€ìŽ ì€ëë€.
-
-```bash
-python -m venv .env
-```
-
-ê°ì íêČœì íì±ííŽìŁŒìžì. Linuxë MacOSì êČœì°:
-
-```bash
-source .env/bin/activate
-```
-Windowsì êČœì°:
-
-```bash
-.env/Scripts/activate
-```
-
-ìŽì đ€ Transformers넌 ì€ìčí ì€ëčê° ëìì”ëë€. ë€ì ëȘ
ë čì ì
ë „íŽìŁŒìžì.
-
-```bash
-pip install transformers
-```
-
-CPUë§ ìšë ëë€ë©Ž, đ€ Transformersì ë„ëŹë ëŒìŽëžëŹëŠŹë„Œ ëš 1ì€ëĄ ì€ìčí ì ìì”ëë€. ì넌 ë€ìŽ đ€ Transformersì PyTorchì êČœì°:
-
-```bash
-pip install transformers[torch]
-```
-
-đ€ Transformersì TensorFlow 2.0ì êČœì°:
-
-```bash
-pip install transformers[tf-cpu]
-```
-
-đ€ Transformersì Flaxì êČœì°:
-
-```bash
-pip install transformers[flax]
-```
-
-ë§ì§ë§ìŒëĄ đ€ Transformersê° ì ëëĄ ì€ìčëìëì§ íìží ì°šëĄì
ëë€. ìŹì íë šë ëȘšëžì ë€ìŽëĄëíë ìœëì
ëë€.
-
-```bash
-python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('we love you'))"
-```
-
-ëŒëČšêłŒ ì ìê° ì¶ë „ë멎 ì ì€ìčë êČì
ëë€.
-
-```bash
-[{'label': 'POSITIVE', 'score': 0.9998704791069031}]
-```
-
-## ìì€ìì ì€ìčíêž°[[install-from-source]]
-
-đ€ Transformers넌 ìì€ìì ì€ìčíë €ë©Ž ìë ëȘ
ë čì ì€ííìžì.
-
-```bash
-pip install git+https://github.com/huggingface/transformers
-```
-
-ì ëȘ
ë čì ì”ì ìŽì§ë§ (ìì ì ìž) `stable` ëČì ìŽ ìë ì€íì±ìŽ ì§ì `main` ëČì ì ì€ìčí©ëë€. `main` ëČì ì ê°ë° íí©êłŒ ë°ë§ì¶ëë° ì ì©í©ëë€. ììëĄ ë§ì§ë§ êł”ì ëŠŽëŠŹì€ ìŽí ë°êČŹë ëČê·žê° íšìčëìì§ë§, ì 늎늏ì€ëĄ ìì§ ëĄ€ììëì§ë ìì êČœì°ë„Œ ë€ ì ìì”ëë€. ë°êż ë§í멎 `main` ëČì ìŽ ìì ì±êłŒë ê±°ëŠŹê° ìë€ë ë»ìŽêž°ë í©ëë€. ì íŹë `main` ëČì ì ìŹì©íëë° ëŹžì ê° ìëëĄ ë
žë „íêł ììŒë©°, ëë¶ë¶ì 돞ì ë ëê° ëȘ ìê°ìŽë í룚 ìì íŽêȰë©ëë€. ë§ìœ 돞ì ê° ë°ìí멎 [ìŽì](https://github.com/huggingface/transformers/issues)넌 ìŽìŽìŁŒì멎 ë ëčšëŠŹ íŽêȰí ì ìì”ëë€!
-
-ì êłŒ ë§ì°Źê°ì§ëĄ đ€ Transformersê° ì ëëĄ ì€ìčëìëì§ íìží ì°šëĄì
ëë€.
-
-```bash
-python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('I love you'))"
-```
-
-## ìì ê°ë„í ì€ìč[[editable-install]]
-
-ìì ê°ë„í ì€ìčê° íìí êČœì°ë ë€ìêłŒ ê°ì”ëë€.
-
-* `main` ëČì ì ìì€ ìœë넌 ìŹì©íêž° ìíŽ
-* đ€ Transformersì êž°ìŹíêł ì¶ìŽì ìœëì ëłêČœ ìŹíì í
ì€ížíêž° ìíŽ
-
-늏íŹì§í°ëŠŹë„Œ ëł”ì íêł đ€ Transformers넌 ì€ìčíë €ë©Ž ë€ì ëȘ
ë čì ì
ë „íŽìŁŒìžì.
-
-```bash
-git clone https://github.com/huggingface/transformers.git
-cd transformers
-pip install -e .
-```
-
-ì ëȘ
ë čì 늏íŹì§í°ëŠŹë„Œ ëł”ì í ììčì íŽëì Python ëŒìŽëžëŹëŠŹì êČœëĄë„Œ ì°êȰìí”ëë€. PythonìŽ ìŒë° ëŒìŽëžëŹëŠŹ êČœëĄ ìžì ëł”ì í íŽë ëŽë¶ë„Œ íìží êČì
ëë€. ì넌 ë€ìŽ Python íší€ì§ê° ìŒë°ì ìŒëĄ `~/anaconda3/envs/main/lib/python3.7/site-packages/`ì ì€ìčëìŽ ìëë°, ëȘ
ë čì ë°ì PythonìŽ ìŽì ëł”ì í íŽëìž `~/transformers/`ë êČìíêČ ë©ëë€.
-
-
-
-ëŒìŽëžëŹëŠŹë„Œ êłì ìŹì©íë €ë©Ž `transformers` íŽë넌 êŒ ì ì§íŽìŒ í©ëë€.
-
-
-
-ëł”ì ëłžì ì”ì ëČì ì đ€ TransformersëĄ ìœêČ ì
ë°ìŽíží ì ìì”ëë€.
-
-```bash
-cd ~/transformers/
-git pull
-```
-
-Python íêČœì ë€ì ì€íí멎 ì
ë°ìŽížë đ€ Transformersì `main` ëČì ì ì°ŸìëŒ êČì
ëë€.
-
-## condaëĄ ì€ìčíêž°[[install-with-conda]]
-
-`huggingface` conda ì±ëìì ì€ìčí ì ìì”ëë€.
-
-```bash
-conda install -c huggingface transformers
-```
-
-## ìșì ê”Źì±íêž°[[cache-setup]]
-
-ìŹì íë šë ëȘšëžì ë€ìŽëĄëë í ëĄì»Ź êČœëĄ `~/.cache/huggingface/hub`ì ìșìë©ëë€. ì
ž íêČœ ëłì `TRANSFORMERS_CACHE`ì êž°ëłž ëë í°ëŠŹì
ëë€. Windowsì êČœì° êž°ëłž ëë í°ëŠŹë `C:\Users\username\.cache\huggingface\hub`ì
ëë€. ìëì ì
ž íêČœ ëłì넌 (ì°ì ìì) ììëëĄ ëłêČœíìŹ ë€ë„ž ìșì ëë í ëŠŹë„Œ ì§ì í ì ìì”ëë€.
-
-1. ì
ž íêČœ ëłì (êž°ëłž): `HUGGINGFACE_HUB_CACHE` ëë `TRANSFORMERS_CACHE`
-2. ì
ž íêČœ ëłì: `HF_HOME`
-3. ì
ž íêČœ ëłì: `XDG_CACHE_HOME` + `/huggingface`
-
-
-
-êłŒê±° đ€ Transformersìì ì°ìë ì
ž íêČœ ëłì `PYTORCH_TRANSFORMERS_CACHE` ëë `PYTORCH_PRETRAINED_BERT_CACHE`ìŽ ì€ì ëìë€ë©Ž, ì
ž íêČœ ëłì `TRANSFORMERS_CACHE`ì ì§ì íì§ ìë í ì°ì ìŹì©ë©ëë€.
-
-
-
-## ì€íëŒìž ëȘšë[[offline-mode]]
-
-đ€ Transformers넌 ëĄì»Ź íìŒë§ ìŹì©íëëĄ íŽì ë°©íëČœ ëë ì€íëŒìž íêČœìì ì€íí ì ìì”ëë€. íì±ííë €ë©Ž `TRANSFORMERS_OFFLINE=1` íêČœ ëłì넌 ì€ì íìžì.
-
-
-
-`HF_DATASETS_OFFLINE=1` íêČœ ëłì넌 ì€ì íìŹ ì€íëŒìž íë š êłŒì ì [đ€ Datasets](https://huggingface.co/docs/datasets/)ì ì¶ê°í ì ìì”ëë€.
-
-
-
-ì넌 ë€ìŽ ìžë¶ êž°êž° ìŹìŽì ë°©íëČœì ë ìŒë° ë€ížìíŹìì íììČëŒ íëĄê·žëšì ë€ìêłŒ ê°ìŽ ì€íí ì ìì”ëë€.
-
-```bash
-python examples/pytorch/translation/run_translation.py --model_name_or_path t5-small --dataset_name wmt16 --dataset_config ro-en ...
-```
-
-ì€íëŒìž êž°êž°ìì ëìŒí íëĄê·žëšì ë€ìêłŒ ê°ìŽ ì€íí ì ìì”ëë€.
-
-```bash
-HF_DATASETS_OFFLINE=1 TRANSFORMERS_OFFLINE=1 \
-python examples/pytorch/translation/run_translation.py --model_name_or_path t5-small --dataset_name wmt16 --dataset_config ro-en ...
-```
-
-ìŽì ì€íŹëŠœížë ëĄì»Ź íìŒì ííŽìë§ êČìí êČìŽëŻëĄ, ì€íŹëŠœížê° ì€ëšëê±°ë ìê°ìŽ ìŽêłŒë ëêčì§ ë©ì¶°ìì§ ìêł ì ì€íë êČì
ëë€.
-
-### ì€íëŒìžì© ëȘšëž ë° í íŹëìŽì ë§ë€ìŽëêž°[[fetch-models-and-tokenizers-to-use-offline]]
-
-Another option for using đ€ Transformers offline is to download the files ahead of time, and then point to their local path when you need to use them offline. There are three ways to do this:
-đ€ Transformers넌 ì€íëŒìžìŒëĄ ìŹì©íë ë ë€ë„ž ë°©ëČì íìŒì 믞늏 ë€ìŽëĄëí ë€ì, ì€íëŒìžìŒ ë ìŹì©í ëĄì»Ź êČœëĄë„Œ ì§ì íŽëë êČì
ëë€. 3ê°ì§ ì€ íží ë°©ëČì êł ë„Žìžì.
-
-* [Model Hub](https://huggingface.co/models)ì UI넌 í”íŽ íìŒì ë€ìŽëĄëíë €ë©Ž â ììŽìœì íŽëŠíìžì.
-
- 
-
-* [`PreTrainedModel.from_pretrained`]ì [`PreTrainedModel.save_pretrained`] ìíŹíëĄë„Œ íì©íìžì.
-
- 1. 믞늏 [`PreTrainedModel.from_pretrained`]ëĄ íìŒì ë€ìŽëĄëíŽëìžì.
-
- ```py
- >>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
-
- >>> tokenizer = AutoTokenizer.from_pretrained("bigscience/T0_3B")
- >>> model = AutoModelForSeq2SeqLM.from_pretrained("bigscience/T0_3B")
- ```
-
- 2. [`PreTrainedModel.save_pretrained`]ëĄ ì§ì ë êČœëĄì íìŒì ì ì„íŽëìžì.
-
- ```py
- >>> tokenizer.save_pretrained("./your/path/bigscience_t0")
- >>> model.save_pretrained("./your/path/bigscience_t0")
- ```
-
- 3. ìŽì ì€íëŒìžìŒ ë [`PreTrainedModel.from_pretrained`]ëĄ ì ì„íŽëë íìŒì ì§ì ë êČœëĄìì ë€ì ë¶ëŹì€ìžì.
-
- ```py
- >>> tokenizer = AutoTokenizer.from_pretrained("./your/path/bigscience_t0")
- >>> model = AutoModel.from_pretrained("./your/path/bigscience_t0")
- ```
-
-* [huggingface_hub](https://github.com/huggingface/huggingface_hub/tree/main/src/huggingface_hub) ëŒìŽëžëŹëŠŹë„Œ íì©íŽì íìŒì ë€ìŽëĄëíìžì.
-
- 1. ê°ìíêČœì `huggingface_hub` ëŒìŽëžëŹëŠŹë„Œ ì€ìčíìžì.
-
- ```bash
- python -m pip install huggingface_hub
- ```
-
- 2. [`hf_hub_download`](https://huggingface.co/docs/hub/adding-a-library#download-files-from-the-hub) íšìëĄ íìŒì íčì ììčì ë€ìŽëĄëí ì ìì”ëë€. ì넌 ë€ìŽ ìë ëȘ
ë čì [T0](https://huggingface.co/bigscience/T0_3B) ëȘšëžì `config.json` íìŒì ì§ì ë êČœëĄì ë€ìŽëĄëí©ëë€.
-
- ```py
- >>> from huggingface_hub import hf_hub_download
-
- >>> hf_hub_download(repo_id="bigscience/T0_3B", filename="config.json", cache_dir="./your/path/bigscience_t0")
- ```
-
-íìŒì ë€ìŽëĄëíêł ëĄì»Źì ìșì íŽëêł ë멎, ëì€ì ë¶ëŹì ìŹì©í ì ìëëĄ ëĄì»Ź êČœëĄë„Œ ì§ì íŽëìžì.
-
-```py
->>> from transformers import AutoConfig
-
->>> config = AutoConfig.from_pretrained("./your/path/bigscience_t0/config.json")
-```
-
-
-
-Hubì ì ì„ë íìŒì ë€ìŽëĄëíë ë°©ëČì ë ììží ììëłŽë €ë©Ž [Hubìì íìŒ ë€ìŽëĄëíêž°](https://huggingface.co/docs/hub/how-to-downstream) ìčì
ì ì°žêł íŽìŁŒìžì.
-
-
\ No newline at end of file
diff --git a/docs/source/ko/model_sharing.md b/docs/source/ko/model_sharing.md
new file mode 100644
index 000000000000..ed6836e8de56
--- /dev/null
+++ b/docs/source/ko/model_sharing.md
@@ -0,0 +1,232 @@
+
+
+# ëȘšëž êł”ì íêž°[[share-a-model]]
+
+ì§ë ë íí 늏ìŒìì ë¶ì° ì€ì ì ìíŽ PyTorch, Keras ë° đ€ Accelerate넌 ìŹì©íìŹ ëȘšëžì ëŻžìž ìĄ°ì íë ë°©ëČì 볎ìì”ëë€. ë€ì ëšêłë ëȘšëžì ì»€ëź€ëí°ì êł”ì íë êČì
ëë€! Hugging Faceë ìžêł”ì§ë„ì ëŻŒìŁŒí넌 ìíŽ ëȘšëìêČ ì§ìêłŒ ììì êł”ê°ì ìŒëĄ êł”ì íŽìŒ íë€êł 믿ì”ëë€. ë€ë„ž ìŹëë€ìŽ ìê°êłŒ ììì ì ìœí ì ìëëĄ ì»€ëź€ëí°ì ëȘšëžì êł”ì íë êČì êł ë €íŽ ëłŽìžì.
+
+ìŽ íí 늏ìŒìì [Model Hub](https://huggingface.co/models)ìì íë šëê±°ë ëŻžìž ìĄ°ì ëȘšëžì êł”ì íë ë ê°ì§ ë°©ëČì ëíŽ ììëŽ
ìë€:
+
+- API넌 í”íŽ íìŒì Hubì ížìí©ëë€.
+- ìčìŹìŽížë„Œ í”íŽ íìŒì HubëĄ ëìŽë€ ëì”ëë€.
+
+VIDEO
+
+
+
+ì»€ëź€ëí°ì ëȘšëžì êł”ì íë €ë©Ž, [huggingface.co](https://huggingface.co/join)ì êłì ìŽ íìí©ëë€. êž°ìĄŽ ìĄ°ì§ì ê°ì
íê±°ë ìëĄ ë§ë€ ìë ìì”ëë€.
+
+
+
+## ì ì„ì íčì§[[repository-features]]
+
+ëȘšëž íëžì ê° ì ì„ìë ìŒë°ì ìž GitHub ì ì„ììČëŒ ìëí©ëë€. ì ì„ìë ëČì êŽëŠŹ, ì»€ë° êž°ëĄ, ì°šìŽì ìê°í êž°ë„ì ì êł”í©ëë€.
+
+ëȘšëž íëžì ëŽì„ë ëČì êŽëŠŹë git ë° [git-lfs](https://git-lfs.github.com/)넌 êž°ë°ìŒëĄ í©ëë€. ìŠ, íëì ëȘšëžì íëì ì ì„ìëĄ ì·šêžíìŹ ì ê·Œ ì ìŽ ë° íì„ì±ìŽ í„ìë©ëë€. ëČì ì ìŽë ì»€ë° íŽì, íê·ž ëë ëžëìčëĄ ëȘšëžì íčì ëČì ì êł ì íë ë°©ëČìž *revision*ì íì©í©ëë€.
+
+ë°ëŒì `revision` ë§€ê°ëłì넌 ìŹì©íìŹ íčì ëȘšëž ëČì ì ê°ì žìŹ ì ìì”ëë€:
+
+```py
+>>> model = AutoModel.from_pretrained(
+... "julien-c/EsperBERTo-small", revision="v2.0.1" # tag name, or branch name, or commit hash
+... )
+```
+
+ëí ì ì„ììì íìŒì ìœêČ ížì§í ì ììŒë©°, ì»€ë° êž°ëĄêłŒ ì°šìŽë„Œ ëłŒ ì ìì”ëë€:
+
+
+
+## ì€ì [[setup]]
+
+ëȘšëžì íëžì êł”ì íêž° ì ì Hugging Face ìêČ© ìŠëȘ
ìŽ íìí©ëë€. í°ëŻžëì ìĄìžì€í ì ìë êČœì°, đ€ Transformersê° ì€ìčë ê°ì íêČœìì ë€ì ëȘ
ë čì ì€íí©ëë€. ê·žëŹë©Ž Hugging Face ìșì íŽë(êž°ëłžì ìŒëĄ `~/.cache/`)ì ìĄìžì€ í í°ì ì ì„í©ëë€:
+
+```bash
+huggingface-cli login
+```
+
+Jupyter ëë Colaboratoryì ê°ì ë
žížë¶ì ìŹì© ì€ìž êČœì°, [`huggingface_hub`](https://huggingface.co/docs/hub/adding-a-library) ëŒìŽëžëŹëŠŹê° ì€ìčëìëì§ íìžíìžì. ìŽ ëŒìŽëžëŹëŠŹë„Œ ìŹì©í멎 APIëĄ íëžì ìíž ìì©í ì ìì”ëë€.
+
+```bash
+pip install huggingface_hub
+```
+
+ê·žë° ë€ì `notebook_login`ëĄ íëžì ëĄê·žìžíêł , [ìŹêž°](https://huggingface.co/settings/token) ë§íŹìì ëĄê·žìží í í°ì ìì±í©ëë€:
+
+```py
+>>> from huggingface_hub import notebook_login
+
+>>> notebook_login()
+```
+
+## íë ììíŹ ê° ëȘšëž ëłííêž°[[convert-a-model-for-all-frameworks]]
+
+ë€ë„ž íë ììíŹëĄ ìì
íë ìŹì©ìê° ëȘšëžì ìŹì©í ì ìëëĄ íë €ë©Ž, PyTorch ë° TensorFlow ìČŽíŹíŹìžížë„Œ ëȘšë ìŹì©íìŹ ëȘšëžì ëłííêł ì
ëĄëíë êČìŽ ìąì”ëë€. ìŽ ëšêłë„Œ 걎ëë°ìŽë ìŹì©ìë ë€ë„ž íë ììíŹìì ëȘšëžì ê°ì žìŹ ì ìì§ë§, đ€ Transformersê° ìČŽíŹíŹìžížë„Œ ìŠììì ëłííŽìŒ íëŻëĄ ìëê° ëë €ì§ ì ìì”ëë€.
+
+ìČŽíŹíŹìžížë„Œ ë€ë„ž íë ììíŹëĄ ëłííë êČì ìœì”ëë€. PyTorch ë° TensorFlowê° ì€ìčëìŽ ìëì§ íìží ë€ì(ì€ìč ì§ìčšì [ìŹêž°](installation) ì°žìĄ°) ë€ë„ž íë ììíŹìì ìì
ì ëí íčì ëȘšëžì ì°Ÿì”ëë€.
+
+
+
+ìČŽíŹíŹìžížë„Œ TensorFlowìì PyTorchëĄ ëłííë €ë©Ž `from_tf=True`넌 ì§ì íìžì:
+
+```py
+>>> pt_model = DistilBertForSequenceClassification.from_pretrained("path/to/awesome-name-you-picked", from_tf=True)
+>>> pt_model.save_pretrained("path/to/awesome-name-you-picked")
+```
+
+
+ìČŽíŹíŹìžížë„Œ PyTorchìì TensorFlowëĄ ëłííë €ë©Ž `from_pt=True`넌 ì§ì íìžì:
+
+```py
+>>> tf_model = TFDistilBertForSequenceClassification.from_pretrained("path/to/awesome-name-you-picked", from_pt=True)
+```
+
+ê·žë° ë€ì ìëĄìŽ ìČŽíŹíŹìžížì íšê» ìëĄìŽ TensorFlow ëȘšëžì ì ì„í ì ìì”ëë€:
+
+```py
+>>> tf_model.save_pretrained("path/to/awesome-name-you-picked")
+```
+
+
+Flaxìì ëȘšëžì ìŹì©íë êČœì°, PyTorchìì FlaxëĄ ìČŽíŹíŹìžížë„Œ ëłíí ìë ìì”ëë€:
+
+```py
+>>> flax_model = FlaxDistilBertForSequenceClassification.from_pretrained(
+... "path/to/awesome-name-you-picked", from_pt=True
+... )
+```
+
+
+
+## íë š ì€ ëȘšëž ížìíêž°[[push-a-model-during-training]]
+
+
+
+
+
+ëȘšëžì íëžì êł”ì íë êČì ì¶ê° ë§€ê°ëłìë ìœë°±ì ì¶ê°íë êČë§íŒ ê°ëší©ëë€. [ëŻžìž ìĄ°ì íí 늏ìŒ](training)ìì [`TrainingArguments`] íŽëì€ë íìŽíŒíëŒëŻží°ì ì¶ê° íë š ì”ì
ì ì§ì íë êłłìŽëŒë êČì êž°ì”íìžì. ìŽëŹí íë š ì”ì
ì€ íëë ëȘšëžì íëžëĄ ì§ì ížìíë êž°ë„ì íŹíší©ëë€. [`TrainingArguments`]ìì `push_to_hub=True`넌 ì€ì íìžì:
+
+```py
+>>> training_args = TrainingArguments(output_dir="my-awesome-model", push_to_hub=True)
+```
+
+íìì ê°ìŽ íë š ìžì넌 [`Trainer`]ì ì ëŹí©ëë€:
+
+```py
+>>> trainer = Trainer(
+... model=model,
+... args=training_args,
+... train_dataset=small_train_dataset,
+... eval_dataset=small_eval_dataset,
+... compute_metrics=compute_metrics,
+... )
+```
+
+ëȘšëžì ëŻžìž ìĄ°ì í í, [`Trainer`]ìì [`~transformers.Trainer.push_to_hub`]넌 ížì¶íìŹ íë šë ëȘšëžì íëžëĄ ížìíìžì. đ€ Transformersë íë š íìŽíŒíëŒëŻží°, íë š êČ°êłŒ ë° íë ììíŹ ëČì ì ëȘšëž ìčŽëì ìëìŒëĄ ì¶ê°í©ëë€!
+
+```py
+>>> trainer.push_to_hub()
+```
+
+
+[`PushToHubCallback`]ì ìŹì©íìŹ ëȘšëžì íëžì êł”ì íë €ë©Ž, [`PushToHubCallback`]ì ë€ì ìžì넌 ì ìíìžì:
+
+- ì¶ë „ë ëȘšëžì íìŒ êČœëĄ
+- í íŹëìŽì
+- `{Hub ìŹì©ì ìŽëŠ}/{ëȘšëž ìŽëŠ}` íìì `hub_model_id`
+
+```py
+>>> from transformers import PushToHubCallback
+
+>>> push_to_hub_callback = PushToHubCallback(
+... output_dir="./your_model_save_path", tokenizer=tokenizer, hub_model_id="your-username/my-awesome-model"
+... )
+```
+
+[`fit`](https://keras.io/api/models/model_training_apis/)ì ìœë°±ì ì¶ê°í멎, đ€ Transformersê° íë šë ëȘšëžì íëžëĄ ížìí©ëë€:
+
+```py
+>>> model.fit(tf_train_dataset, validation_data=tf_validation_dataset, epochs=3, callbacks=push_to_hub_callback)
+```
+
+
+
+## `push_to_hub` íšì ìŹì©íêž°[[use-the-pushtohub-function]]
+
+ëȘšëžìì ì§ì `push_to_hub`넌 ížì¶íìŹ íëžì ì
ëĄëí ìë ìì”ëë€.
+
+`push_to_hub`ì ëȘšëž ìŽëŠì ì§ì íìžì:
+
+```py
+>>> pt_model.push_to_hub("my-awesome-model")
+```
+
+ìŽë êČ í멎 ìŹì©ì ìŽëŠ ìëì ëȘšëž ìŽëŠ `my-awesome-model`ëĄ ì ì„ìê° ìì±ë©ëë€. ìŽì ìŹì©ìë `from_pretrained` íšì넌 ìŹì©íìŹ ëȘšëžì ê°ì žìŹ ì ìì”ëë€:
+
+```py
+>>> from transformers import AutoModel
+
+>>> model = AutoModel.from_pretrained("your_username/my-awesome-model")
+```
+
+ìĄ°ì§ì ìíêł ëȘšëžì ìĄ°ì§ ìŽëŠìŒëĄ ëì ížìíë €ë©Ž `repo_id`ì ì¶ê°íìžì:
+
+```py
+>>> pt_model.push_to_hub("my-awesome-org/my-awesome-model")
+```
+
+`push_to_hub` íšìë ëȘšëž ì ì„ìì ë€ë„ž íìŒì ì¶ê°íë ë°ìë ìŹì©í ì ìì”ëë€. ì넌 ë€ìŽ ëȘšëž ì ì„ìì í íŹëìŽì 넌 ì¶ê°í ì ìì”ëë€:
+
+```py
+>>> tokenizer.push_to_hub("my-awesome-model")
+```
+
+ëë ëŻžìž ìĄ°ì ë PyTorch ëȘšëžì TensorFlow ëČì ì ì¶ê°í ìë ìì”ëë€:
+
+```py
+>>> tf_model.push_to_hub("my-awesome-model")
+```
+
+ìŽì Hugging Face íëĄíëĄ ìŽëí멎, ìëĄ ìì±í ëȘšëž ì ì„ìê° íìë©ëë€. **Files** íì íŽëŠí멎 ì ì„ìì ì
ëĄëí ëȘšë íìŒìŽ íìë©ëë€.
+
+ì ì„ìì íìŒì ë§ë€êł ì
ëĄëíë ë°©ëČì ëí ììží ëŽì©ì íëž ì€ëȘ
ì [ìŹêž°](https://huggingface.co/docs/hub/how-to-upstream)넌 ì°žìĄ°íìžì.
+
+## ìč ìží°íìŽì€ëĄ ì
ëĄëíêž°[[upload-with-the-web-interface]]
+
+ìœë ìë ì ê·Œ ë°©ìì ì ížíë ìŹì©ìë íëžì ìč ìží°íìŽì€ë„Œ í”íŽ ëȘšëžì ì
ëĄëí ì ìì”ëë€. [huggingface.co/new](https://huggingface.co/new)넌 방돞íìŹ ìëĄìŽ ì ì„ì넌 ìì±íìžì:
+
+
+
+ìŹêž°ì ëȘšëžì ëí ëȘ ê°ì§ ì ëłŽë„Œ ì¶ê°íìžì:
+
+- ì ì„ìì **ìì ì**넌 ì íí©ëë€. ìŽë ìŹì©ì ëë ìŹì©ìê° ìí ìĄ°ì§ìŒ ì ìì”ëë€.
+- ì ì„ì ìŽëŠìŽ ë ëȘšëžì ìŽëŠì ì íí©ëë€.
+- ëȘšëžìŽ êł”ê°ìžì§ ëčêł”ê°ìžì§ ì íí©ëë€.
+- ëȘšëžì ëŒìŽìŒì€ ìŹì©ì ì§ì í©ëë€.
+
+ìŽì **Files** íì íŽëŠíêł **Add file** ëČíŒì íŽëŠíìŹ ìëĄìŽ íìŒì ì ì„ìì ì
ëĄëí©ëë€. ê·žë° ë€ì ì
ëĄëí íìŒì ëìŽë€ ëêł ì»€ë° ë©ìì§ë„Œ ì¶ê°íìžì.
+
+
+
+## ëȘšëž ìčŽë ì¶ê°íêž°[[add-a-model-card]]
+
+ìŹì©ìê° ëȘšëžì êž°ë„, ì í, ì ìŹì íží„ ë° ì€ëŠŹì êł ë € ìŹíì ìŽíŽí ì ìëëĄ ì ì„ìì ëȘšëž ìčŽë넌 ì¶ê°íìžì. ëȘšëž ìčŽëë `README.md` íìŒì ì ìëìŽ ìì”ëë€. ë€ì ë°©ëČìŒëĄ ëȘšëž ìčŽë넌 ì¶ê°í ì ìì”ëë€:
+
+* `README.md` íìŒì ìëìŒëĄ ìì±íìŹ ì
ëĄëí©ëë€.
+* ëȘšëž ì ì„ììì **Edit model card** ëČíŒì íŽëŠí©ëë€.
+
+ëȘšëž ìčŽëì íŹíší ì 볎 ì íì ëí ìąì ìë DistilBert [ëȘšëž ìčŽë](https://huggingface.co/distilbert-base-uncased)넌 ì°žìĄ°íìžì. ëȘšëžì íì ë°ìê”ìŽë ìì Ż ìì ë± `README.md` íìŒìì ì ìŽí ì ìë ë€ë„ž ì”ì
ì ëí ììží ëŽì©ì [ìŹêž°](https://huggingface.co/docs/hub/models-cards) 돞ì넌 ì°žìĄ°íìžì.
diff --git a/docs/source/ko/model_sharing.mdx b/docs/source/ko/model_sharing.mdx
deleted file mode 100644
index 3dcd7a0ebcb7..000000000000
--- a/docs/source/ko/model_sharing.mdx
+++ /dev/null
@@ -1,228 +0,0 @@
-
-
-# ëȘšëž êł”ì íêž°[[share-a-model]]
-
-ì§ë ë íí 늏ìŒìì ë¶ì° ì€ì ì ìíŽ PyTorch, Keras ë° đ€ Accelerate넌 ìŹì©íìŹ ëȘšëžì ëŻžìž ìĄ°ì íë ë°©ëČì 볎ìì”ëë€. ë€ì ëšêłë ëȘšëžì ì»€ëź€ëí°ì êł”ì íë êČì
ëë€! Hugging Faceë ìžêł”ì§ë„ì ëŻŒìŁŒí넌 ìíŽ ëȘšëìêČ ì§ìêłŒ ììì êł”ê°ì ìŒëĄ êł”ì íŽìŒ íë€êł 믿ì”ëë€. ë€ë„ž ìŹëë€ìŽ ìê°êłŒ ììì ì ìœí ì ìëëĄ ì»€ëź€ëí°ì ëȘšëžì êł”ì íë êČì êł ë €íŽ ëłŽìžì.
-
-ìŽ íí 늏ìŒìì [Model Hub](https://huggingface.co/models)ìì íë šëê±°ë ëŻžìž ìĄ°ì ëȘšëžì êł”ì íë ë ê°ì§ ë°©ëČì ëíŽ ììëŽ
ìë€:
-
-- API넌 í”íŽ íìŒì Hubì ížìí©ëë€.
-- ìčìŹìŽížë„Œ í”íŽ íìŒì HubëĄ ëìŽë€ ëì”ëë€.
-
-VIDEO
-
-
-
-ì»€ëź€ëí°ì ëȘšëžì êł”ì íë €ë©Ž, [huggingface.co](https://huggingface.co/join)ì êłì ìŽ íìí©ëë€. êž°ìĄŽ ìĄ°ì§ì ê°ì
íê±°ë ìëĄ ë§ë€ ìë ìì”ëë€.
-
-
-
-## ì ì„ì íčì§[[repository-features]]
-
-ëȘšëž íëžì ê° ì ì„ìë ìŒë°ì ìž GitHub ì ì„ììČëŒ ìëí©ëë€. ì ì„ìë ëČì êŽëŠŹ, ì»€ë° êž°ëĄ, ì°šìŽì ìê°í êž°ë„ì ì êł”í©ëë€.
-
-ëȘšëž íëžì ëŽì„ë ëČì êŽëŠŹë git ë° [git-lfs](https://git-lfs.github.com/)넌 êž°ë°ìŒëĄ í©ëë€. ìŠ, íëì ëȘšëžì íëì ì ì„ìëĄ ì·šêžíìŹ ì ê·Œ ì ìŽ ë° íì„ì±ìŽ í„ìë©ëë€. ëČì ì ìŽë ì»€ë° íŽì, íê·ž ëë ëžëìčëĄ ëȘšëžì íčì ëČì ì êł ì íë ë°©ëČìž *revision*ì íì©í©ëë€.
-
-ë°ëŒì `revision` ë§€ê°ëłì넌 ìŹì©íìŹ íčì ëȘšëž ëČì ì ê°ì žìŹ ì ìì”ëë€:
-
-```py
->>> model = AutoModel.from_pretrained(
-... "julien-c/EsperBERTo-small", revision="v2.0.1" # tag name, or branch name, or commit hash
-... )
-```
-
-ëí ì ì„ììì íìŒì ìœêČ ížì§í ì ììŒë©°, ì»€ë° êž°ëĄêłŒ ì°šìŽë„Œ ëłŒ ì ìì”ëë€:
-
-
-
-## ì€ì [[setup]]
-
-ëȘšëžì íëžì êł”ì íêž° ì ì Hugging Face ìêČ© ìŠëȘ
ìŽ íìí©ëë€. í°ëŻžëì ìĄìžì€í ì ìë êČœì°, đ€ Transformersê° ì€ìčë ê°ì íêČœìì ë€ì ëȘ
ë čì ì€íí©ëë€. ê·žëŹë©Ž Hugging Face ìșì íŽë(êž°ëłžì ìŒëĄ `~/.cache/`)ì ìĄìžì€ í í°ì ì ì„í©ëë€:
-
-```bash
-huggingface-cli login
-```
-
-Jupyter ëë Colaboratoryì ê°ì ë
žížë¶ì ìŹì© ì€ìž êČœì°, [`huggingface_hub`](https://huggingface.co/docs/hub/adding-a-library) ëŒìŽëžëŹëŠŹê° ì€ìčëìëì§ íìžíìžì. ìŽ ëŒìŽëžëŹëŠŹë„Œ ìŹì©í멎 APIëĄ íëžì ìíž ìì©í ì ìì”ëë€.
-
-```bash
-pip install huggingface_hub
-```
-
-ê·žë° ë€ì `notebook_login`ëĄ íëžì ëĄê·žìžíêł , [ìŹêž°](https://huggingface.co/settings/token) ë§íŹìì ëĄê·žìží í í°ì ìì±í©ëë€:
-
-```py
->>> from huggingface_hub import notebook_login
-
->>> notebook_login()
-```
-
-## íë ììíŹ ê° ëȘšëž ëłííêž°[[convert-a-model-for-all-frameworks]]
-
-ë€ë„ž íë ììíŹëĄ ìì
íë ìŹì©ìê° ëȘšëžì ìŹì©í ì ìëëĄ íë €ë©Ž, PyTorch ë° TensorFlow ìČŽíŹíŹìžížë„Œ ëȘšë ìŹì©íìŹ ëȘšëžì ëłííêł ì
ëĄëíë êČìŽ ìąì”ëë€. ìŽ ëšêłë„Œ 걎ëë°ìŽë ìŹì©ìë ë€ë„ž íë ììíŹìì ëȘšëžì ê°ì žìŹ ì ìì§ë§, đ€ Transformersê° ìČŽíŹíŹìžížë„Œ ìŠììì ëłííŽìŒ íëŻëĄ ìëê° ëë €ì§ ì ìì”ëë€.
-
-ìČŽíŹíŹìžížë„Œ ë€ë„ž íë ììíŹëĄ ëłííë êČì ìœì”ëë€. PyTorch ë° TensorFlowê° ì€ìčëìŽ ìëì§ íìží ë€ì(ì€ìč ì§ìčšì [ìŹêž°](installation) ì°žìĄ°) ë€ë„ž íë ììíŹìì ìì
ì ëí íčì ëȘšëžì ì°Ÿì”ëë€.
-
-
-
-ìČŽíŹíŹìžížë„Œ TensorFlowìì PyTorchëĄ ëłííë €ë©Ž `from_tf=True`넌 ì§ì íìžì:
-
-```py
->>> pt_model = DistilBertForSequenceClassification.from_pretrained("path/to/awesome-name-you-picked", from_tf=True)
->>> pt_model.save_pretrained("path/to/awesome-name-you-picked")
-```
-
-
-ìČŽíŹíŹìžížë„Œ PyTorchìì TensorFlowëĄ ëłííë €ë©Ž `from_pt=True`넌 ì§ì íìžì:
-
-```py
->>> tf_model = TFDistilBertForSequenceClassification.from_pretrained("path/to/awesome-name-you-picked", from_pt=True)
-```
-
-ê·žë° ë€ì ìëĄìŽ ìČŽíŹíŹìžížì íšê» ìëĄìŽ TensorFlow ëȘšëžì ì ì„í ì ìì”ëë€:
-
-```py
->>> tf_model.save_pretrained("path/to/awesome-name-you-picked")
-```
-
-
-Flaxìì ëȘšëžì ìŹì©íë êČœì°, PyTorchìì FlaxëĄ ìČŽíŹíŹìžížë„Œ ëłíí ìë ìì”ëë€:
-
-```py
->>> flax_model = FlaxDistilBertForSequenceClassification.from_pretrained(
-... "path/to/awesome-name-you-picked", from_pt=True
-... )
-```
-
-
-
-## íë š ì€ ëȘšëž ížìíêž°[[push-a-model-during-training]]
-
-
-
-
-
-ëȘšëžì íëžì êł”ì íë êČì ì¶ê° ë§€ê°ëłìë ìœë°±ì ì¶ê°íë êČë§íŒ ê°ëší©ëë€. [ëŻžìž ìĄ°ì íí 늏ìŒ](training)ìì [`TrainingArguments`] íŽëì€ë íìŽíŒíëŒëŻží°ì ì¶ê° íë š ì”ì
ì ì§ì íë êłłìŽëŒë êČì êž°ì”íìžì. ìŽëŹí íë š ì”ì
ì€ íëë ëȘšëžì íëžëĄ ì§ì ížìíë êž°ë„ì íŹíší©ëë€. [`TrainingArguments`]ìì `push_to_hub=True`넌 ì€ì íìžì:
-
-```py
->>> training_args = TrainingArguments(output_dir="my-awesome-model", push_to_hub=True)
-```
-
-íìì ê°ìŽ íë š ìžì넌 [`Trainer`]ì ì ëŹí©ëë€:
-
-```py
->>> trainer = Trainer(
-... model=model,
-... args=training_args,
-... train_dataset=small_train_dataset,
-... eval_dataset=small_eval_dataset,
-... compute_metrics=compute_metrics,
-... )
-```
-
-ëȘšëžì ëŻžìž ìĄ°ì í í, [`Trainer`]ìì [`~transformers.Trainer.push_to_hub`]넌 ížì¶íìŹ íë šë ëȘšëžì íëžëĄ ížìíìžì. đ€ Transformersë íë š íìŽíŒíëŒëŻží°, íë š êČ°êłŒ ë° íë ììíŹ ëČì ì ëȘšëž ìčŽëì ìëìŒëĄ ì¶ê°í©ëë€!
-
-```py
->>> trainer.push_to_hub()
-```
-
-
-[`PushToHubCallback`]ì ìŹì©íìŹ ëȘšëžì íëžì êł”ì íë €ë©Ž, [`PushToHubCallback`]ì ë€ì ìžì넌 ì ìíìžì:
-
-- ì¶ë „ë ëȘšëžì íìŒ êČœëĄ
-- í íŹëìŽì
-- `{Hub ìŹì©ì ìŽëŠ}/{ëȘšëž ìŽëŠ}` íìì `hub_model_id`
-
-```py
->>> from transformers import PushToHubCallback
-
->>> push_to_hub_callback = PushToHubCallback(
-... output_dir="./your_model_save_path", tokenizer=tokenizer, hub_model_id="your-username/my-awesome-model"
-... )
-```
-
-[`fit`](https://keras.io/api/models/model_training_apis/)ì ìœë°±ì ì¶ê°í멎, đ€ Transformersê° íë šë ëȘšëžì íëžëĄ ížìí©ëë€:
-
-```py
->>> model.fit(tf_train_dataset, validation_data=tf_validation_dataset, epochs=3, callbacks=push_to_hub_callback)
-```
-
-
-
-## `push_to_hub` íšì ìŹì©íêž°[[use-the-pushtohub-function]]
-
-ëȘšëžìì ì§ì `push_to_hub`넌 ížì¶íìŹ íëžì ì
ëĄëí ìë ìì”ëë€.
-
-`push_to_hub`ì ëȘšëž ìŽëŠì ì§ì íìžì:
-
-```py
->>> pt_model.push_to_hub("my-awesome-model")
-```
-
-ìŽë êČ í멎 ìŹì©ì ìŽëŠ ìëì ëȘšëž ìŽëŠ `my-awesome-model`ëĄ ì ì„ìê° ìì±ë©ëë€. ìŽì ìŹì©ìë `from_pretrained` íšì넌 ìŹì©íìŹ ëȘšëžì ê°ì žìŹ ì ìì”ëë€:
-
-```py
->>> from transformers import AutoModel
-
->>> model = AutoModel.from_pretrained("your_username/my-awesome-model")
-```
-
-ìĄ°ì§ì ìíêł ëȘšëžì ìĄ°ì§ ìŽëŠìŒëĄ ëì ížìíë €ë©Ž `repo_id`ì ì¶ê°íìžì:
-
-```py
->>> pt_model.push_to_hub("my-awesome-org/my-awesome-model")
-```
-
-`push_to_hub` íšìë ëȘšëž ì ì„ìì ë€ë„ž íìŒì ì¶ê°íë ë°ìë ìŹì©í ì ìì”ëë€. ì넌 ë€ìŽ ëȘšëž ì ì„ìì í íŹëìŽì 넌 ì¶ê°í ì ìì”ëë€:
-
-```py
->>> tokenizer.push_to_hub("my-awesome-model")
-```
-
-ëë ëŻžìž ìĄ°ì ë PyTorch ëȘšëžì TensorFlow ëČì ì ì¶ê°í ìë ìì”ëë€:
-
-```py
->>> tf_model.push_to_hub("my-awesome-model")
-```
-
-ìŽì Hugging Face íëĄíëĄ ìŽëí멎, ìëĄ ìì±í ëȘšëž ì ì„ìê° íìë©ëë€. **Files** íì íŽëŠí멎 ì ì„ìì ì
ëĄëí ëȘšë íìŒìŽ íìë©ëë€.
-
-ì ì„ìì íìŒì ë§ë€êł ì
ëĄëíë ë°©ëČì ëí ììží ëŽì©ì íëž ì€ëȘ
ì [ìŹêž°](https://huggingface.co/docs/hub/how-to-upstream)넌 ì°žìĄ°íìžì.
-
-## ìč ìží°íìŽì€ëĄ ì
ëĄëíêž°[[upload-with-the-web-interface]]
-
-ìœë ìë ì ê·Œ ë°©ìì ì ížíë ìŹì©ìë íëžì ìč ìží°íìŽì€ë„Œ í”íŽ ëȘšëžì ì
ëĄëí ì ìì”ëë€. [huggingface.co/new](https://huggingface.co/new)넌 방돞íìŹ ìëĄìŽ ì ì„ì넌 ìì±íìžì:
-
-
-
-ìŹêž°ì ëȘšëžì ëí ëȘ ê°ì§ ì ëłŽë„Œ ì¶ê°íìžì:
-
-- ì ì„ìì **ìì ì**넌 ì íí©ëë€. ìŽë ìŹì©ì ëë ìŹì©ìê° ìí ìĄ°ì§ìŒ ì ìì”ëë€.
-- ì ì„ì ìŽëŠìŽ ë ëȘšëžì ìŽëŠì ì íí©ëë€.
-- ëȘšëžìŽ êł”ê°ìžì§ ëčêł”ê°ìžì§ ì íí©ëë€.
-- ëȘšëžì ëŒìŽìŒì€ ìŹì©ì ì§ì í©ëë€.
-
-ìŽì **Files** íì íŽëŠíêł **Add file** ëČíŒì íŽëŠíìŹ ìëĄìŽ íìŒì ì ì„ìì ì
ëĄëí©ëë€. ê·žë° ë€ì ì
ëĄëí íìŒì ëìŽë€ ëêł ì»€ë° ë©ìì§ë„Œ ì¶ê°íìžì.
-
-
-
-## ëȘšëž ìčŽë ì¶ê°íêž°[[add-a-model-card]]
-
-ìŹì©ìê° ëȘšëžì êž°ë„, ì í, ì ìŹì íží„ ë° ì€ëŠŹì êł ë € ìŹíì ìŽíŽí ì ìëëĄ ì ì„ìì ëȘšëž ìčŽë넌 ì¶ê°íìžì. ëȘšëž ìčŽëë `README.md` íìŒì ì ìëìŽ ìì”ëë€. ë€ì ë°©ëČìŒëĄ ëȘšëž ìčŽë넌 ì¶ê°í ì ìì”ëë€:
-
-* `README.md` íìŒì ìëìŒëĄ ìì±íìŹ ì
ëĄëí©ëë€.
-* ëȘšëž ì ì„ììì **Edit model card** ëČíŒì íŽëŠí©ëë€.
-
-ëȘšëž ìčŽëì íŹíší ì 볎 ì íì ëí ìąì ìë DistilBert [ëȘšëž ìčŽë](https://huggingface.co/distilbert-base-uncased)넌 ì°žìĄ°íìžì. ëȘšëžì íì ë°ìê”ìŽë ìì Ż ìì ë± `README.md` íìŒìì ì ìŽí ì ìë ë€ë„ž ì”ì
ì ëí ììží ëŽì©ì [ìŹêž°](https://huggingface.co/docs/hub/models-cards) 돞ì넌 ì°žìĄ°íìžì.
diff --git a/docs/source/ko/model_summary.md b/docs/source/ko/model_summary.md
new file mode 100644
index 000000000000..568b9425335d
--- /dev/null
+++ b/docs/source/ko/model_summary.md
@@ -0,0 +1,107 @@
+
+
+# Transformer ëȘšëžê”°[[the-transformer-model-family]]
+
+2017ë
ì ìê°ë [êž°ëłž Transformer](https://arxiv.org/abs/1706.03762) ëȘšëžì ìì°ìŽ ìČ늏(NLP) ìì
ì ëìŽ ìëĄêł í„믞ëĄìŽ ëȘšëžë€ì ìê°ì ìŁŒìì”ëë€. [ëšë°±ì§ ì í ê”ŹìĄ° ììžĄ](https://huggingface.co/blog/deep-learning-with-proteins), [ìčíì ëŹëŠŹêž° íë š](https://huggingface.co/blog/train-decision-transformers), [ìêłìŽ ììžĄ](https://huggingface.co/blog/time-series-transformers) ë±ì ìí ë€ìí ëȘšëžìŽ ìêČšëŹì”ëë€. Transformerì ëłíìŽ ë돎 ë§ìì, í° ê·žëŠŒì ëìčêž° ìœì”ëë€. íì§ë§ ìŹêž° ìë ëȘšë ëȘšëžì êł”í”ì ì êž°ëłž Trasnformer ìí€í
ìČ넌 êž°ë°ìŒëĄ íë€ë ì ì
ëë€. ìŒë¶ ëȘšëžì ìžìœë ëë ëìœëë§ ìŹì©íêł , ë€ë„ž ëȘšëžë€ì ìžìœëì ëìœë넌 ëȘšë ìŹì©íêž°ë í©ëë€. ìŽë êČ Transformer ëȘšëžê”° ëŽ ìì ë ëČšììì ì°šìŽì ì ë¶ë„íêł êČí í멎 ì ì©í ë¶ë„ ìČŽêłë„Œ ì»ì ì ììŒë©°, ìŽì ì ì íŽëłŽì§ ëȘ»í Transformer ëȘšëžë€ ëí ìŽíŽíë ë° ëììŽ ë êČì
ëë€.
+
+êž°ëłž Transformer ëȘšëžì ì”ìíì§ ìê±°ë ëł”ì”ìŽ íìí êČœì°, Hugging Face ê°ìì [ížëì€íŹëšžë ìŽë»êČ ëìíëì?](https://huggingface.co/course/chapter1/4?fw=pt) ì±í°ë„Œ íìžíìžì.
+
+
+ VIDEO
+
+
+## 컎íší° ëčì [[computer-vision]]
+
+
+
+### í©ì±êł± ë€ížìíŹ[[convolutional-network]]
+
+[Vision Transformer](https://arxiv.org/abs/2010.11929)ê° íì„ì±êłŒ íšìšì±ì ì
ìŠíêž° ì êčì§ ì€ë«ëì í©ì±êł± ë€ížìíŹ(CNN)ê° ì»Žíší° ëčì ìì
ì ì§ë°°ì ìž íšëŹë€ììŽìì”ëë€. ê·žëŒìë ë¶ê”Źíêł , ìŽë ë¶ëłì±(translation invariance)êłŒ ê°ì CNNì ì°ìí ë¶ë¶ìŽ ëëëŒì§êž° ë돞ì ëȘëȘ (íčí íčì êłŒì
ììì) Transformer ëȘšëžì ìí€í
ìČì í©ì±êł±ì í”í©íêž°ë íì”ëë€. [ConvNeXt](model_doc/convnext)ë ìŽë° êŽëĄë„Œ ë€ì§ìŽ CNNì íëííêž° ìíŽ Transformerì ëììžì ì°šì©í©ëë€. ì넌 ë€ë©Ž ConvNeXtë êČčìčì§ ìë ìŹëŒìŽë© ì°œ(sliding window)ì ìŹì©íìŹ ìŽëŻžì§ë„Œ íšìčííêł , ë í° ì»€ëëĄ ì ì ìì© íë(global receptive field)넌 íì„ìí”ëë€. ConvNeXtë ëí ë©ëȘšëŠŹ íšìšì ëìŽêł ì±ë„ì í„ììí€êž° ìíŽ ìŹëŹ ë ìŽìŽ ì€êłë„Œ ì ííêž° ë돞ì Transformerì êČŹì€ë§í©ëë€!
+
+### ìžìœë[[cv-encoder]]
+
+[Vision Transformer(ViT)](model_doc/vit)ë í©ì±êł± ìë 컎íší° ëčì ìì
ì ë§ì ìŽìì”ëë€. ViTë íì€ Transformer ìžìœë넌 ìŹì©íì§ë§, ê°ì„ í° íì ì ìŽëŻžì§ë„Œ ìČ늏íë ë°©ììŽìì”ëë€. 돞ì„ì í í°ìŒëĄ ë¶í íë êČìČëŒ ìŽëŻžì§ë„Œ êł ì ë íŹêž°ì íšìčëĄ ë¶í íêł , ìŽë„Œ ìŹì©íìŹ ìëČ ë©ì ìì±í©ëë€. ViTë Transformerì íšìšì ìž ìí€í
ìČ넌 íì©íìŹ íë šì ë ì ì ììì ìŹì©í멎ìë ëčì CNNì ëčêČŹíë êČ°êłŒë„Œ ì
ìŠíì”ëë€. ê·žëŠŹêł ViT넌 ë€ìŽìŽ ë¶í (segmentation)êłŒ ê°ì êł ë°ë ëčì ìì
êłŒ íì§ ìì
ë ë€ëٰ ì ìë ë€ë„ž ëčì ëȘšëžìŽ ë±ì„íì”ëë€.
+
+ìŽëŹí ëȘšëž ì€ íëê° [Swin](model_doc/swin) Transformerì
ëë€. ìŽ ëȘšëžì ìì íŹêž°ì íšìčìì êłìž”ì íčì§ ë§”(CNN đêłŒ ê°ì§ë§ ViTìë ë€ëŠ)ì ë§ë€êł ë êčì ë ìŽìŽì ìžì íšìčì ëłí©í©ëë€. ìŽí
ì
(Attention)ì ì§ì ìëì° ëŽììë§ êłì°ëë©°, ëȘšëžìŽ ë ì íì”í ì ìëëĄ ìŽí
ì
ë ìŽìŽ ê°ì ìëì°ë„Œ ìŽëíë©° ì°êȰì ìì±í©ëë€. Swin Transformerë êłìž”ì íčì§ ë§”ì ìì±í ì ììŒëŻëĄ, ë¶í (segmentation)êłŒ íì§ì ê°ì êł ë°ë ììžĄ ìì
ì ì í©í©ëë€. [SegFormer](model_doc/segformer) ìì Transformer ìžìœë넌 ìŹì©íìŹ êłìž”ì íčì§ ë§”ì ê”Źì¶íì§ë§, ìëšì ê°ëší ë€ìž” íŒì
ížëĄ (MLP) ëìœë넌 ì¶ê°íìŹ ëȘšë íčì§ ë§”ì êȰí©íêł ììžĄì ìíí©ëë€.
+
+BeITì ViTMAEì ê°ì ë€ë„ž ëčì ëȘšëžì BERTì ìŹì íë š ëȘ©í(objective)ìì ìê°ì ì»ìì”ëë€. [BeIT](model_doc/beit)ë *ë§ì€íŹë ìŽëŻžì§ ëȘšëžë§(MIM)*ìŒëĄ ìŹì íë šëë©°, ìŽëŻžì§ íšìčë ììëĄ ë§ì€íčëêł ìŽëŻžì§ë ìê°ì í í°ìŒëĄ í í°íë©ëë€. BeITë ë§ì€íčë íšìčì íŽëčíë ìê°ì í í°ì ììžĄíëëĄ íì”ë©ëë€. [ViTMAE](model_doc/vitmae)ë ëčì·í ìŹì íë š ëȘ©íê° ìì§ë§, ìê°ì í í° ëì íœì
ì ììžĄíŽìŒ íë€ë ì ìŽ ë€ëŠ
ëë€. íčìŽí ì ì ìŽëŻžì§ íšìčì 75%ê° ë§ì€íčëìŽ ìë€ë êČì
ëë€! ëìœëë ë§ì€íčë í í°êłŒ ìžìœë©ë íšìčìì íœì
ì ìŹê”Źì±í©ëë€. ìŹì íë šìŽ ëë멎 ëìœëë íêž°ëêł ìžìœëë ë€ìŽì€ížëŠŒ ìì
ì ìŹì©í ì€ëčê° ë©ëë€.
+
+### ëìœë[[cv-decoder]]
+
+ëë¶ë¶ì ëčì ëȘšëžì ìžìœëì ììĄŽíìŹ ìŽëŻžì§ ííì íì”íêž° ë돞ì ëìœë ì ì© ëčì ëȘšëžì ëë
ëë€. íì§ë§ ìŽëŻžì§ ìì± ë±ì ìŹëĄì êČœì°, GPT-2ì ê°ì í
ì€íž ìì± ëȘšëžìì 볎ìëŻìŽ ëìœëê° ê°ì„ ì í©í©ëë€. [ImageGPT](model_doc/imagegpt)ë GPT-2ì ëìŒí ìí€í
ìČ넌 ìŹì©íì§ë§, ìíì€ì ë€ì í í°ì ììžĄíë ëì ìŽëŻžì§ì ë€ì íœì
ì ììžĄí©ëë€. ImageGPTë ìŽëŻžì§ ìì± ëżë§ ìëëŒ ìŽëŻžì§ ë¶ë„넌 ìíŽ ëŻžìž ìĄ°ì í ìë ìì”ëë€.
+
+### ìžìœë-ëìœë[[cv-encoder-decoder]]
+
+ëčì ëȘšëžì ìŒë°ì ìŒëĄ ìžìœë(백볞ìŒëĄë ìë €ì§)넌 ìŹì©íìŹ ì€ìí ìŽëŻžì§ íčì§ì ì¶ì¶í í, ìŽë„Œ Transformer ëìœëëĄ ì ëŹí©ëë€. [DETR](model_doc/detr)ì ìŹì íë šë ë°±ëłžìŽ ìì§ë§, ê°ìČŽ íì§ë„Œ ìíŽ ìì í Transformer ìžìœë-ëìœë ìí€í
ìČë ìŹì©í©ëë€. ìžìœëë ìŽëŻžì§ ííì íì”íêł ìŽë„Œ ëìœëìì ê°ìČŽ ìżŒëŠŹ(ê° ê°ìČŽ ìżŒëŠŹë ìŽëŻžì§ì ìì ëë ê°ìČŽì ì€ì ì ëêł íì”ë ìëČ ë©)ì êȰí©í©ëë€. DETRì ê° ê°ìČŽ ìżŒëŠŹì ëí ë°ìŽë© ë°ì€ ìąíì íŽëì€ ë ìŽëžì ììžĄí©ëë€.
+
+## ìì°ìŽìČ늏[[natural-language-processing]]
+
+
+
+### ìžìœë[[nlp-encoder]]
+
+[BERT](model_doc/bert)ë ìžìœë ì ì© TransformerëĄ, ë€ë„ž í í°ì ëłŽêł ìì "ë¶ì íì"넌 ì ì§ë„Žë 걞 ë§êž° ìíŽ ì
ë „ìì íčì í í°ì ììëĄ ë§ì€íčí©ëë€. ìŹì íë šì ëȘ©íë 컚í
ì€ížë„Œ êž°ë°ìŒëĄ ë§ì€íčë í í°ì ììžĄíë êČì
ëë€. ìŽë„Œ í”íŽ BERTë ìŒìȘœêłŒ ì€ë„žìȘœ 컚í
ì€ížë„Œ ì¶©ë¶í íì©íìŹ ì
ë „ì ëíŽ ë êčêł íë¶í ííì íì”í ì ìì”ëë€. ê·žëŹë BERTì ìŹì íë š ì ë”ìë ìŹì í ê°ì ì ìŹì§ê° ëšì ììì”ëë€. [RoBERTa](model_doc/roberta)ë ë ꞎ ìê° ëì ë í° ë°°ìčì ëí íë šì íŹíšíêł , ì ìČ늏 ì€ì í ëČë§ ë§ì€íčíë êČìŽ ìëëŒ ê° ìíìì í í°ì ììëĄ ë§ì€íčíêł , ë€ì ëŹžì„ ììžĄ ëȘ©í넌 ì ê±°íë ìëĄìŽ ìŹì íë š ë°©ìì ëì
íšìŒëĄìš ìŽë„Œ ê°ì íì”ëë€.
+
+ì±ë„ ê°ì ì ìí ì ë”ìŒëĄ ëȘšëž íŹêž°ë„Œ í€ì°ë êČìŽ ì§ë°°ì ì
ëë€. íì§ë§ í° ëȘšëžì íë šíë €ë©Ž êłì° ëčì©ìŽ ë§ìŽ ëëë€. êłì° ëčì©ì ì€ìŽë í ê°ì§ ë°©ëČì [DistilBERT](model_doc/distilbert)ì ê°ìŽ ìì ëȘšëžì ìŹì©íë êČì
ëë€. DistilBERTë ìì¶ êž°ëČìž [ì§ì ìŠë„(knowledge distillation)](https://arxiv.org/abs/1503.02531)넌 ìŹì©íìŹ, ê±°ì ëȘšë ìžìŽ ìŽíŽ ë„ë „ì ì ì§í멎ì ë ìì ëČì ì BERT넌 ë§ëëë€.
+
+ê·žëŹë ëë¶ë¶ì Transformer ëȘšëžì ë ë§ì ë§€ê°ëłì넌 ìŹì©íë êČœí„ìŽ ìŽìŽìĄêł , ìŽì ë°ëŒ íë š íšìšì±ì ê°ì íë êČì ì€ì ì ë ìëĄìŽ ëȘšëžìŽ ë±ì„íì”ëë€. [ALBERT](model_doc/albert)ë ë ê°ì§ ë°©ëČìŒëĄ ë§€ê°ëłì ì넌 ì€ìŹ ë©ëȘšëŠŹ ìŹì©ëì ì€ìì”ëë€. ë°ëĄ í° ìŽí넌 ë ê°ì ìì íë ŹëĄ ë¶ëŠŹíë êČêłŒ ë ìŽìŽê° ë§€ê°ëłì넌 êł”ì íëëĄ íë êČì
ëë€. [DeBERTa](model_doc/deberta)ë ëšìŽì ê·ž ììč넌 ë ê°ì ëČĄí°ëĄ ê°ëłì ìŒëĄ ìžìœë©íë ë¶ëŠŹë(disentangled) ìŽí
ì
ë©ì»€ëìŠì ì¶ê°íì”ëë€. ìŽí
ì
ì ëšìŽì ììč ìëČ ë©ì íŹíšíë ëšìŒ ëČĄí° ëì ìŽ ëłëì ëČĄí°ìì êłì°ë©ëë€. [Longformer](model_doc/longformer)ë íčí ìíì€ êžžìŽê° ꞎ 돞ì넌 ìČ늏í ë, ìŽí
ì
ì ë íšìšì ìŒëĄ ë§ëë êČì ì€ì ì ëìì”ëë€. ì§ì(local) ìëì° ìŽí
ì
(ê° í í° ìŁŒëłì êł ì ë ìëì° íŹêž°ììë§ êłì°ëë ìŽí
ì
)êłŒ ì ì(global) ìŽí
ì
(ë¶ë„넌 ìíŽ `[CLS]`ì ê°ì íčì ìì
í í°ìë§ íŽëč)ì ìĄ°í©ì ìŹì©íìŹ ì ìČŽ(full) ìŽí
ì
íë Ź ëì íŹì(sparse) ìŽí
ì
íë Źì ìì±í©ëë€.
+
+### ëìœë[[nlp-decoder]]
+
+[GPT-2](model_doc/gpt2)ë ìíì€ìì ë€ì ëšìŽë„Œ ììžĄíë ëìœë ì ì© Transformerì
ëë€. í í°ì ì€ë„žìȘœìŒëĄ ë§ì€íčíìŹ ëȘšëžìŽ ìŽì í í°ì ëłŽêł "ë¶ì íì"넌 íì§ ëȘ»íëëĄ í©ëë€. GPT-2ë ë°©ëí í
ì€ížì ëíŽ ìŹì íë šíìŹ í
ì€ížê° ìŒë¶ë§ ì ííê±°ë ìŹì€ìž êČœì°ìë ìëčí ë„ìíêČ í
ì€ížë„Œ ìì±í ì ìêČ ëìì”ëë€. íì§ë§ GPT-2ë BERTê° ìŹì íë šìì ê°ë ìë°©í„ ì»ší
ì€ížê° ë¶ìĄ±íêž° ë돞ì íčì ìì
ì ì í©íì§ ììì”ëë€. [XLNET](model_doc/xlnet)ì ìë°©í„ íë šìŽ ê°ë„í permutation language modeling objective(PLM)넌 ìŹì©íìŹ BERTì GPT-2ì ìŹì íë š ëȘ©íì ëí ì„ì ì íšê» ê°ì§êł ìì”ëë€.
+
+GPT-2 ìŽí, ìžìŽ ëȘšëžì ëì± ê±°ëíŽìĄêł íìŹë *ëê·ëȘš ìžìŽ ëȘšëž(LLM)*ëĄ ìë €ì ž ìì”ëë€. ì¶©ë¶í í° ë°ìŽí° ìžížëĄ ìŹì íë šë LLMì íšì·(few-shot) ëë ì ëĄì·(zero-shot) íì”ì ìíí©ëë€. [GPT-J](model_doc/gptj)ë 6B íŹêž°ì ë§€ê°ëłìê° ìêł 400B íŹêž°ì í í°ìŒëĄ íë šë LLMì
ëë€. GPT-Jì ìŽìŽ ëìœë ì ì© ëȘšëžê”°ìž [OPT](model_doc/opt)ê° ë±ì„íìŒë©°, ìŽ ì€ ê°ì„ í° ëȘšëžì 175B íŹêž°ìŽêł 180B íŹêž°ì í í°ìŒëĄ íë šëìì”ëë€. [BLOOM](model_doc/bloom)ì ëčì·í ìêž°ì ì¶ìëììŒë©°, ìŽ ì€ ê°ì„ í° ëȘšëžì 176B íŹêž°ì ë§€ê°ëłìê° ìêł 46ê°ì ìžìŽì 13ê°ì íëĄê·žëë° ìžìŽëĄ ë 366B íŹêž°ì í í°ìŒëĄ íë šëìì”ëë€.
+
+### ìžìœë-ëìœë[[nlp-encoder-decoder]]
+
+[BART](model_doc/bart)ë êž°ëłž Transformer ìí€í
ìČ넌 ì ì§íì§ë§, ìŒë¶ í
ì€íž ì€íŹ(span)ìŽ ëšìŒ `ë§ì€íŹ` í í°ìŒëĄ ëìČŽëë *text infilling* ëłíìŒëĄ ìŹì íë š ëȘ©í넌 ìì í©ëë€. ëìœëë ëłíëì§ ìì í í°(í„í í í°ì ë§ì€íčëš)ì ììžĄíêł ìžìœëì ìë ìí넌 ìŹì©íìŹ ìŽ ìì
ì ëì”ëë€. [Pegasus](model_doc/pegasus)ë BARTì ì ìŹíì§ë§, Pegasusë í
ì€íž ì€íŹ ëì ì ìČŽ 돞ì„ì ë§ì€íčí©ëë€. Pegasusë ë§ì€íŹë ìžìŽ ëȘšëžë§ ìžìë gap sentence generation(GSG)ëĄ ìŹì íë šë©ëë€. GSGë 돞ìì ì€ìí ëŹžì„ ì ìČŽë„Œ ë§ì€íčíìŹ `ë§ì€íŹ` í í°ìŒëĄ ëìČŽíë êČì ëȘ©íëĄ í©ëë€. ëìœëë ëšì 돞ì„ìì ì¶ë „ì ìì±íŽìŒ í©ëë€. [T5](model_doc/t5)ë íčì ì ëìŹë„Œ ìŹì©íìŹ ëȘšë NLP ìì
ì í
ì€íž íŹ í
ì€íž 돞ì ëĄ ëłííë ë íčìí ëȘšëžì
ëë€. ì넌 ë€ìŽ, ì ëìŹ `Summarize:`ì ììœ ìì
ì ëíë
ëë€. T5ë ì§ë(GLUE ë° SuperGLUE) íë šêłŒ ìêž°ì§ë íë š(í í°ì 15%넌 ììëĄ ìíë§íìŹ ì ê±°)ìŒëĄ ìŹì íë šë©ëë€.
+
+## ì€ëì€[[audio]]
+
+
+
+### ìžìœë[[audio-encoder]]
+
+[Wav2Vec2](model_doc/wav2vec2)ë Transformer ìžìœë넌 ìŹì©íìŹ ìëłž ì€ëì€ íí(raw audio waveform)ìì ì§ì ìì± ííì íì”í©ëë€. íì ìì± íí ìžížìì ì€ì ìì± ííì íëłíë ëìĄ° ìì
ìŒëĄ ìŹì íë šë©ëë€. [HuBERT](model_doc/hubert)ë Wav2Vec2ì ì ìŹíì§ë§ íë š êłŒì ìŽ ë€ëŠ
ëë€. íêČ ë ìŽëžìŽ ì ìŹí ì€ëì€ ìžê·žëšŒížê° íŽëŹì€í°ì í ëčëìŽ ìë ëšì(unit)ê° ëë ê”°ì§í(clustering) ëšêłìì ìì±ë©ëë€. ìë ëšìë ììžĄì ìí ìëČ ë©ì ë§€íë©ëë€.
+
+### ìžìœë-ëìœë[[audio-encoder-decoder]]
+
+[Speech2Text](model_doc/speech_to_text)ë ìë ìì± ìžì(ASR) ë° ìì± ëČìì ìíŽ êł ìë ìì± ëȘšëžì
ëë€. ìŽ ëȘšëžì ì€ëì€ ííìì ì¶ì¶í log mel-filter bank íčì§ì ì±ííêł ìêž°íê· ë°©ììŒëĄ ìŹì íë šíìŹ, ì ìŹëłž ëë ëČìì ë§ëëë€. [Whisper](model_doc/whisper)ì ASR ëȘšëžìŽì§ë§, ë€ë„ž ë§ì ìì± ëȘšëžêłŒ ëŹëŠŹ ì ëĄì· ì±ë„ì ìíŽ ëëì âš ë ìŽëžìŽ ì§ì ë âš ì€ëì€ ì ìŹ ë°ìŽí°ì ëíŽ ìŹì íë šë©ëë€. ë°ìŽí° ìžížì í° ëŹ¶ììë ììŽê° ìë ìžìŽë íŹíšëìŽ ììŽì ìììŽ ì ì ìžìŽìë Whisper넌 ìŹì©í ì ìì”ëë€. ê”ŹìĄ°ì ìŒëĄ, Whisperë Speech2Textì ì ìŹí©ëë€. ì€ëì€ ì ížë ìžìœëì ìíŽ ìžìœë©ë log-mel spectrogramìŒëĄ ëłíë©ëë€. ëìœëë ìžìœëì ìë ìíì ìŽì í í°ìŒëĄë¶í° ìêž°íê· ë°©ììŒëĄ ì ìŹë„Œ ìì±í©ëë€.
+
+## ë©í°ëȘšëŹ[[multimodal]]
+
+
+
+### ìžìœë[[mm-encoder]]
+
+[VisualBERT](model_doc/visual_bert)ë BERT ìŽíì ì¶ìë ëčì ìžìŽ ìì
ì ìí ë©í°ëȘšëŹ ëȘšëžì
ëë€. ìŽ ëȘšëžì BERTì ìŹì íë šë ê°ìČŽ íì§ ìì€í
ì êȰí©íìŹ ìŽëŻžì§ íčì§ì ìê° ìëČ ë©ìŒëĄ ì¶ì¶íêł , í
ì€íž ìëČ ë©êłŒ íšê» BERTëĄ ì ëŹí©ëë€. VisualBERTë ë§ì€íčëì§ ìì í
ì€ížì ìê° ìëČ ë©ì êž°ë°ìŒëĄ ë§ì€íčë í
ì€ížë„Œ ììžĄíêł , í
ì€ížê° ìŽëŻžì§ì ìŒìčíëì§ ììžĄíŽìŒ í©ëë€. ViTê° ìŽëŻžì§ ìëČ ë©ì ê”Źíë ë°©ììŽ ë ìŹì êž° ë돞ì, ViTê° ì¶ìë í [ViLT](model_doc/vilt)ë ìí€í
ìČì ViT넌 ì±ííì”ëë€. ìŽëŻžì§ ìëČ ë©ì í
ì€íž ìëČ ë©êłŒ íšê» ìČ늏ë©ëë€. ìŹêž°ìì, ViLTë ìŽëŻžì§ í
ì€íž ë§€ìč, ë§ì€íŹë ìžìŽ ëȘšëžë§, ì ìČŽ ëšìŽ ë§ì€íčì í”íŽ ìŹì íë šë©ëë€.
+
+[CLIP](model_doc/clip)ì ë€ë„ž ì ê·Œ ë°©ìì ìŹì©íìŹ (`ìŽëŻžì§`, `í
ì€íž`)ì ì ììžĄì ìíí©ëë€. (`ìŽëŻžì§`, `í
ì€íž`) ìììì ìŽëŻžì§ì í
ì€íž ìëČ ë© ê°ì ì ìŹë넌 ì”ëííêž° ìíŽ 4ì” ê°ì (`ìŽëŻžì§`, `í
ì€íž`) ì ë°ìŽí° ìžížì ëíŽ ìŽëŻžì§ ìžìœë(ViT)ì í
ì€íž ìžìœë(Transformer)넌 íšê» íë ší©ëë€. ìŹì íë š í, ìì°ìŽë„Œ ìŹì©íìŹ ìŽëŻžì§ê° ìŁŒìŽì§ í
ì€ížë„Œ ììžĄíê±°ë ê·ž ë°ëëĄ ììžĄíëëĄ CLIPì ì§ìí ì ìì”ëë€. [OWL-ViT](model_doc/owlvit)ë CLIPì ì ëĄì· ê°ìČŽ íì§ë„Œ ìí 백볞(backbone)ìŒëĄ ìŹì©íìŹ CLIP ìì ê”Źì¶ë©ëë€. ìŹì íë š í, ê°ìČŽ íì§ í€ëê° ì¶ê°ëìŽ (`íŽëì€`, `ë°ìŽë© ë°ì€`) ìì ëí ì§í©(set) ììžĄì ìíí©ëë€.
+
+### ìžìœë-ëìœë[[mm-encoder-decoder]]
+
+êŽí 돞ì ìžì(OCR)ì ìŽëŻžì§ë„Œ ìŽíŽíêł í
ì€ížë„Œ ìì±íêž° ìíŽ ë€ìí ê”Źì± ìì넌 íìëĄ íë ì í”ì ìž í
ì€íž ìžì ìì
ì
ëë€. [TrOCR](model_doc/trocr)ì ìą
ëšê°(end-to-end) Transformer넌 ìŹì©íìŹ ìŽ íëĄìžì€ë„Œ ê°ìíí©ëë€. ìžìœëë ìŽëŻžì§ ìŽíŽë„Œ ìí ViT ë°©ìì ëȘšëžìŽë©° ìŽëŻžì§ë„Œ êł ì ë íŹêž°ì íšìčëĄ ìČ늏í©ëë€. ëìœëë ìžìœëì ìë ìí넌 ë°ìì ìêž°íê· ë°©ììŒëĄ í
ì€ížë„Œ ìì±í©ëë€. [Donut](model_doc/donut)ì OCR êž°ë° ì ê·Œ ë°©ìì ììĄŽíì§ ìë ë ìŒë°ì ìž ìê° ëŹžì ìŽíŽ ëȘšëžì
ëë€. ìŽ ëȘšëžì Swin Transformer넌 ìžìœëëĄ, ë€ê”ìŽ BART넌 ëìœëëĄ ìŹì©í©ëë€. Donutì ìŽëŻžì§ì í
ì€íž ìŁŒìì êž°ë°ìŒëĄ ë€ì ëšìŽë„Œ ììžĄíìŹ í
ì€ížë„Œ ìœëëĄ ìŹì íë šë©ëë€. ëìœëë í륏íížê° ìŁŒìŽì§ë©Ž í í° ìíì€ë„Œ ìì±í©ëë€. í륏íížë ê° ë€ìŽì€ížëŠŒ ìì
ì ëí íčì í í°ìŒëĄ ííë©ëë€. ì넌 ë€ìŽ, 돞ì íì±(parsing)ìë ìžìœëì ìë ìíì êȰí©ëìŽ ëŹžì넌 ì í ì¶ë „ íì(JSON)ìŒëĄ íì±íë íčì `íì±` í í°ìŽ ìì”ëë€.
+
+## ê°í íì”[[reinforcement-learning]]
+
+
+
+### ëìœë[[rl-decoder]]
+
+Decision ë° Trajectory Transformerë ìí(state), íë(action), 볎ì(reward)ì ìíì€ ëȘšëžë§ 돞ì ëĄ ííí©ëë€. [Decision Transformer](model_doc/decision_transformer)ë êž°ë 볎ì(returns-to-go), êłŒê±° ìí ë° íëì êž°ë°ìŒëĄ 믞ëì ìíë ìì”(return)ìŒëĄ ìŽìŽì§ë ìŒë šì íëì ìì±í©ëë€. ë§ì§ë§ *K* ìê° ì€í
(timestep)ì ëíŽ, ìž ê°ì§ ëȘšëŹëŠŹí°ë ê°ê° í í° ìëČ ë©ìŒëĄ ëłíëêł GPTì ê°ì ëȘšëžì ìíŽ ìČ늏ëìŽ ëŻžëì ìĄì
í í°ì ììžĄí©ëë€. [Trajectory Transformer](model_doc/trajectory_transformer)ë ìí, íë, 볎ìì í í°ííìŹ GPT ìí€í
ìČëĄ ìČ늏í©ëë€. 볎ì ìĄ°ê±Žì ì€ì ì ë Decision Transformerì ëŹëŠŹ Trajectory Transformerë ëč ììč(beam search)ëĄ ëŻžë íëì ìì±í©ëë€.
\ No newline at end of file
diff --git a/docs/source/ko/multilingual.md b/docs/source/ko/multilingual.md
new file mode 100644
index 000000000000..2862bd983887
--- /dev/null
+++ b/docs/source/ko/multilingual.md
@@ -0,0 +1,192 @@
+
+
+# ë€ê”ìŽ ëȘšëž ì¶ëĄ íêž°[[multilingual-models-for-inference]]
+
+[[open-in-colab]]
+
+đ€ Transformersìë ìŹëŹ ìą
ë„ì ë€ê”ìŽ(multilingual) ëȘšëžìŽ ììŒë©°, ëšìŒ ìžìŽ(monolingual) ëȘšëžêłŒ ì¶ëĄ ì ìŹì©ëČìŽ ë€ëŠ
ëë€.
+ê·žë ë€êł íŽì *ëȘšë * ë€ê”ìŽ ëȘšëžì ìŹì©ëČìŽ ë€ë„ž êČì ìëëë€.
+
+[bert-base-multilingual-uncased](https://huggingface.co/bert-base-multilingual-uncased)ì ê°ì ëȘëȘ ëȘšëžì ëšìŒ ìžìŽ ëȘšëžìČëŒ ìŹì©í ì ìì”ëë€.
+ìŽëČ ê°ìŽëìì ë€ê”ìŽ ëȘšëžì ì¶ëĄ ì ìŹì© ë°©ëČì ììëłŒ êČì
ëë€.
+
+## XLM[[xlm]]
+
+XLMìë 10ê°ì§ ìČŽíŹíŹìžíž(checkpoint)ê° ìëë°, ìŽ ì€ íëë§ ëšìŒ ìžìŽì
ëë€.
+ëëšžì§ ìČŽíŹíŹìžíž 9ê°ë ìžìŽ ìëČ ë©ì ìŹì©íë ìČŽíŹíŹìžížì ê·žë ì§ ìì ìČŽíŹíŹìžížì ë ê°ì§ ëČìŁŒëĄ ëë ì ìì”ëë€.
+
+### ìžìŽ ìëČ ë©ì ìŹì©íë XLM[[xlm-with-language-embeddings]]
+
+ë€ì XLM ëȘšëžì ì¶ëĄ ìì ìžìŽ ìëČ ë©ì ìŹì©í©ëë€:
+
+- `xlm-mlm-ende-1024` (ë§ì€íčë ìžìŽ ëȘšëžë§, ììŽ-ë
ìŒìŽ)
+- `xlm-mlm-enfr-1024` (ë§ì€íčë ìžìŽ ëȘšëžë§, ììŽ-íëì€ìŽ)
+- `xlm-mlm-enro-1024` (ë§ì€íčë ìžìŽ ëȘšëžë§, ììŽ-룚ë§ëììŽ)
+- `xlm-mlm-xnli15-1024` (ë§ì€íčë ìžìŽ ëȘšëžë§, XNLI ë°ìŽí° ìžížìì ì êł”íë 15ê° ê”ìŽ)
+- `xlm-mlm-tlm-xnli15-1024` (ë§ì€íčë ìžìŽ ëȘšëžë§ + ëČì, XNLI ë°ìŽí° ìžížìì ì êł”íë 15ê° ê”ìŽ)
+- `xlm-clm-enfr-1024` (Causal language modeling, ììŽ-íëì€ìŽ)
+- `xlm-clm-ende-1024` (Causal language modeling, ììŽ-ë
ìŒìŽ)
+
+ìžìŽ ìëČ ë©ì ëȘšëžì ì ëŹë `input_ids`ì ëìŒí shapeì í
ìëĄ ííë©ëë€.
+ìŽëŹí í
ìì ê°ì ìŹì©ë ìžìŽì ë°ëŒ ë€ë„Žë©° í íŹëìŽì ì `lang2id` ë° `id2lang` ìì±ì ìíŽ ìëłë©ëë€.
+
+ë€ì ìì ììë `xlm-clm-enfr-1024` ìČŽíŹíŹìžíž(ìœì ìžìŽ ëȘšëžë§(causal language modeling), ììŽ-íëì€ìŽ)넌 ê°ì žì”ëë€:
+
+```py
+>>> import torch
+>>> from transformers import XLMTokenizer, XLMWithLMHeadModel
+
+>>> tokenizer = XLMTokenizer.from_pretrained("xlm-clm-enfr-1024")
+>>> model = XLMWithLMHeadModel.from_pretrained("xlm-clm-enfr-1024")
+```
+
+í íŹëìŽì ì `lang2id` ìì±ì ëȘšëžì ìžìŽì íŽëč ID넌 íìí©ëë€:
+
+```py
+>>> print(tokenizer.lang2id)
+{'en': 0, 'fr': 1}
+```
+
+ë€ììŒëĄ, ìì ì
ë „ì ë§ëëë€:
+
+```py
+>>> input_ids = torch.tensor([tokenizer.encode("Wikipedia was used to")]) # ë°°ìč íŹêž°ë 1ì
ëë€
+```
+
+ìžìŽ ID넌 `"en"`ìŒëĄ ì€ì íŽ ìžìŽ ìëČ ë©ì ì ìí©ëë€.
+ìžìŽ ìëČ ë©ì ììŽì ìžìŽ IDìž `0`ìŒëĄ ì±ìì§ í
ìì
ëë€.
+ìŽ í
ìë `input_ids`ì ê°ì íŹêž°ìŹìŒ í©ëë€.
+
+```py
+>>> language_id = tokenizer.lang2id["en"] # 0
+>>> langs = torch.tensor([language_id] * input_ids.shape[1]) # torch.tensor([0, 0, 0, ..., 0])
+
+>>> # (batch_size, sequence_length) shapeì í
ìê° ëëëĄ ë§ëëë€.
+>>> langs = langs.view(1, -1) # ìŽì [1, sequence_length] shapeìŽ ëìì”ëë€(ë°°ìč íŹêž°ë 1ì
ëë€)
+```
+
+ìŽì `input_ids`ì ìžìŽ ìëČ ë©ì ëȘšëžëĄ ì ëŹí©ëë€:
+
+```py
+>>> outputs = model(input_ids, langs=langs)
+```
+
+[run_generation.py](https://github.com/huggingface/transformers/tree/main/examples/pytorch/text-generation/run_generation.py) ì€íŹëŠœížëĄ `xlm-clm` ìČŽíŹíŹìžížë„Œ ìŹì©íŽ í
ì€ížì ìžìŽ ìëČ ë©ì ìì±í ì ìì”ëë€.
+
+### ìžìŽ ìëČ ë©ì ìŹì©íì§ ìë XLM[[xlm-without-language-embeddings]]
+
+ë€ì XLM ëȘšëžì ì¶ëĄ ìì ìžìŽ ìëČ ë©ìŽ íìíì§ ìì”ëë€:
+
+- `xlm-mlm-17-1280` (ë§ì€íčë ìžìŽ ëȘšëžë§, 17ê° ê”ìŽ)
+- `xlm-mlm-100-1280` (ë§ì€íčë ìžìŽ ëȘšëžë§, 100ê° ê”ìŽ)
+
+ìŽì ì XLM ìČŽíŹíŹìžížì ëŹëŠŹ ìŽ ëȘšëžì ìŒë° ëŹžì„ ííì ìŹì©ë©ëë€.
+
+## BERT[[bert]]
+
+ë€ì BERT ëȘšëžì ë€ê”ìŽ íì€íŹì ìŹì©í ì ìì”ëë€:
+
+- `bert-base-multilingual-uncased` (ë§ì€íčë ìžìŽ ëȘšëžë§ + ë€ì ëŹžì„ ììžĄ, 102ê° ê”ìŽ)
+- `bert-base-multilingual-cased` (ë§ì€íčë ìžìŽ ëȘšëžë§ + ë€ì ëŹžì„ ììžĄ, 104ê° ê”ìŽ)
+
+ìŽëŹí ëȘšëžì ì¶ëĄ ìì ìžìŽ ìëČ ë©ìŽ íìíì§ ìì”ëë€.
+돞맄ìì ìžìŽë„Œ ìëłíêł , ìëłë ìžìŽëĄ ì¶ëĄ í©ëë€.
+
+## XLM-RoBERTa[[xlmroberta]]
+
+ë€ì XLM-RoBERTa ëí ë€ê”ìŽ ë€ê”ìŽ íì€íŹì ìŹì©í ì ìì”ëë€:
+
+- `xlm-roberta-base` (ë§ì€íčë ìžìŽ ëȘšëžë§, 100ê° ê”ìŽ)
+- `xlm-roberta-large` (ë§ì€íčë ìžìŽ ëȘšëžë§, 100ê° ê”ìŽ)
+
+XLM-RoBERTaë 100ê° ê”ìŽì ëíŽ ìëĄ ìì±ëêł ì ì ë 2.5TB ê·ëȘšì CommonCrawl ë°ìŽí°ëĄ íì”ëìì”ëë€.
+ìŽì ì êł”ê°ë mBERTë XLMêłŒ ê°ì ë€ê”ìŽ ëȘšëžì ëčíŽ ë¶ë„, ìíì€ ëŒëČšë§, ì§ì ìë”êłŒ ê°ì ë€ìŽì€ížëŠŒ(downstream) ìì
ìì ìŽì ìŽ ìì”ëë€.
+
+## M2M100[[m2m100]]
+
+ë€ì M2M100 ëȘšëž ëí ë€ê”ìŽ ë€ê”ìŽ íì€íŹì ìŹì©í ì ìì”ëë€:
+
+- `facebook/m2m100_418M` (ëČì)
+- `facebook/m2m100_1.2B` (ëČì)
+
+ìŽ ìì ììë `facebook/m2m100_418M` ìČŽíŹíŹìžížë„Œ ê°ì žìì ì€ê”ìŽë„Œ ììŽëĄ ëČìí©ëë€.
+í íŹëìŽì ìì ëČì ëì ìžìŽ(source language)넌 ì€ì í ì ìì”ëë€:
+
+```py
+>>> from transformers import M2M100ForConditionalGeneration, M2M100Tokenizer
+
+>>> en_text = "Do not meddle in the affairs of wizards, for they are subtle and quick to anger."
+>>> chinese_text = "äžèŠææć·«ćž«çäșć, ć çșä»ćæŻćŸźćŠç, ćŸćż«ć°±æçŒæ."
+
+>>> tokenizer = M2M100Tokenizer.from_pretrained("facebook/m2m100_418M", src_lang="zh")
+>>> model = M2M100ForConditionalGeneration.from_pretrained("facebook/m2m100_418M")
+```
+
+돞ì„ì í í°íí©ëë€:
+
+```py
+>>> encoded_zh = tokenizer(chinese_text, return_tensors="pt")
+```
+
+M2M100ì ëČìì ì§ííêž° ìíŽ ìČ« ëČì§žëĄ ìì±ëë í í°ì ëČìí ìžìŽ(target language) IDëĄ ê°ì ì§ì í©ëë€.
+ììŽëĄ ëČìíêž° ìíŽ `generate` ë©ìëìì `forced_bos_token_id`넌 `en`ìŒëĄ ì€ì í©ëë€:
+
+```py
+>>> generated_tokens = model.generate(**encoded_zh, forced_bos_token_id=tokenizer.get_lang_id("en"))
+>>> tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)
+'Do not interfere with the matters of the witches, because they are delicate and will soon be angry.'
+```
+
+## MBart[[mbart]]
+
+ë€ì MBart ëȘšëž ëí ë€ê”ìŽ íì€íŹì ìŹì©í ì ìì”ëë€:
+
+- `facebook/mbart-large-50-one-to-many-mmt` (ìŒëë€ ë€ê”ìŽ ëČì, 50ê° ê”ìŽ)
+- `facebook/mbart-large-50-many-to-many-mmt` (ë€ëë€ ë€ê”ìŽ ëČì, 50ê° ê”ìŽ)
+- `facebook/mbart-large-50-many-to-one-mmt` (ë€ëìŒ ë€ê”ìŽ ëČì, 50ê° ê”ìŽ)
+- `facebook/mbart-large-50` (ë€ê”ìŽ ëČì, 50ê° ê”ìŽ)
+- `facebook/mbart-large-cc25`
+
+ìŽ ìì ììë íëëìŽë„Œ ììŽëĄ ëČìíêž° ìíŽ `facebook/mbart-large-50-many-to-many-mmt` ìČŽíŹíŹìžížë„Œ ê°ì žì”ëë€.
+í íŹëìŽì ìì ëČì ëì ìžìŽ(source language)넌 ì€ì í ì ìì”ëë€:
+
+```py
+>>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
+
+>>> en_text = "Do not meddle in the affairs of wizards, for they are subtle and quick to anger."
+>>> fi_text = "ĂlĂ€ sekaannu velhojen asioihin, sillĂ€ ne ovat hienovaraisia ja nopeasti vihaisia."
+
+>>> tokenizer = AutoTokenizer.from_pretrained("facebook/mbart-large-50-many-to-many-mmt", src_lang="fi_FI")
+>>> model = AutoModelForSeq2SeqLM.from_pretrained("facebook/mbart-large-50-many-to-many-mmt")
+```
+
+돞ì„ì í í°íí©ëë€:
+
+```py
+>>> encoded_en = tokenizer(en_text, return_tensors="pt")
+```
+
+MBartë ëČìì ì§ííêž° ìíŽ ìČ« ëČì§žëĄ ìì±ëë í í°ì ëČìí ìžìŽ(target language) IDëĄ ê°ì ì§ì í©ëë€.
+ììŽëĄ ëČìíêž° ìíŽ `generate` ë©ìëìì `forced_bos_token_id`넌 `en`ìŒëĄ ì€ì í©ëë€:
+
+```py
+>>> generated_tokens = model.generate(**encoded_en, forced_bos_token_id=tokenizer.lang_code_to_id("en_XX"))
+>>> tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)
+"Don't interfere with the wizard's affairs, because they are subtle, will soon get angry."
+```
+
+`facebook/mbart-large-50-many-to-one-mmt` ìČŽíŹíŹìžížë„Œ ìŹì©íêł ìë€ë©Ž, ìČ« ëČì§žëĄ ìì±ëë í í°ì ëČìí ìžìŽ(target language) IDëĄ ê°ì ì§ì í íìë ìì”ëë€.
diff --git a/docs/source/ko/multilingual.mdx b/docs/source/ko/multilingual.mdx
deleted file mode 100644
index 5483ac1318dd..000000000000
--- a/docs/source/ko/multilingual.mdx
+++ /dev/null
@@ -1,188 +0,0 @@
-
-
-# ë€ê”ìŽ ëȘšëž ì¶ëĄ íêž°[[multilingual-models-for-inference]]
-
-[[open-in-colab]]
-
-đ€ Transformersìë ìŹëŹ ìą
ë„ì ë€ê”ìŽ(multilingual) ëȘšëžìŽ ììŒë©°, ëšìŒ ìžìŽ(monolingual) ëȘšëžêłŒ ì¶ëĄ ì ìŹì©ëČìŽ ë€ëŠ
ëë€.
-ê·žë ë€êł íŽì *ëȘšë * ë€ê”ìŽ ëȘšëžì ìŹì©ëČìŽ ë€ë„ž êČì ìëëë€.
-
-[bert-base-multilingual-uncased](https://huggingface.co/bert-base-multilingual-uncased)ì ê°ì ëȘëȘ ëȘšëžì ëšìŒ ìžìŽ ëȘšëžìČëŒ ìŹì©í ì ìì”ëë€.
-ìŽëČ ê°ìŽëìì ë€ê”ìŽ ëȘšëžì ì¶ëĄ ì ìŹì© ë°©ëČì ììëłŒ êČì
ëë€.
-
-## XLM[[xlm]]
-
-XLMìë 10ê°ì§ ìČŽíŹíŹìžíž(checkpoint)ê° ìëë°, ìŽ ì€ íëë§ ëšìŒ ìžìŽì
ëë€.
-ëëšžì§ ìČŽíŹíŹìžíž 9ê°ë ìžìŽ ìëČ ë©ì ìŹì©íë ìČŽíŹíŹìžížì ê·žë ì§ ìì ìČŽíŹíŹìžížì ë ê°ì§ ëČìŁŒëĄ ëë ì ìì”ëë€.
-
-### ìžìŽ ìëČ ë©ì ìŹì©íë XLM[[xlm-with-language-embeddings]]
-
-ë€ì XLM ëȘšëžì ì¶ëĄ ìì ìžìŽ ìëČ ë©ì ìŹì©í©ëë€:
-
-- `xlm-mlm-ende-1024` (ë§ì€íčë ìžìŽ ëȘšëžë§, ììŽ-ë
ìŒìŽ)
-- `xlm-mlm-enfr-1024` (ë§ì€íčë ìžìŽ ëȘšëžë§, ììŽ-íëì€ìŽ)
-- `xlm-mlm-enro-1024` (ë§ì€íčë ìžìŽ ëȘšëžë§, ììŽ-룚ë§ëììŽ)
-- `xlm-mlm-xnli15-1024` (ë§ì€íčë ìžìŽ ëȘšëžë§, XNLI ë°ìŽí° ìžížìì ì êł”íë 15ê° ê”ìŽ)
-- `xlm-mlm-tlm-xnli15-1024` (ë§ì€íčë ìžìŽ ëȘšëžë§ + ëČì, XNLI ë°ìŽí° ìžížìì ì êł”íë 15ê° ê”ìŽ)
-- `xlm-clm-enfr-1024` (Causal language modeling, ììŽ-íëì€ìŽ)
-- `xlm-clm-ende-1024` (Causal language modeling, ììŽ-ë
ìŒìŽ)
-
-ìžìŽ ìëČ ë©ì ëȘšëžì ì ëŹë `input_ids`ì ëìŒí shapeì í
ìëĄ ííë©ëë€.
-ìŽëŹí í
ìì ê°ì ìŹì©ë ìžìŽì ë°ëŒ ë€ë„Žë©° í íŹëìŽì ì `lang2id` ë° `id2lang` ìì±ì ìíŽ ìëłë©ëë€.
-
-ë€ì ìì ììë `xlm-clm-enfr-1024` ìČŽíŹíŹìžíž(ìœì ìžìŽ ëȘšëžë§(causal language modeling), ììŽ-íëì€ìŽ)넌 ê°ì žì”ëë€:
-
-```py
->>> import torch
->>> from transformers import XLMTokenizer, XLMWithLMHeadModel
-
->>> tokenizer = XLMTokenizer.from_pretrained("xlm-clm-enfr-1024")
->>> model = XLMWithLMHeadModel.from_pretrained("xlm-clm-enfr-1024")
-```
-
-í íŹëìŽì ì `lang2id` ìì±ì ëȘšëžì ìžìŽì íŽëč ID넌 íìí©ëë€:
-
-```py
->>> print(tokenizer.lang2id)
-{'en': 0, 'fr': 1}
-```
-
-ë€ììŒëĄ, ìì ì
ë „ì ë§ëëë€:
-
-```py
->>> input_ids = torch.tensor([tokenizer.encode("Wikipedia was used to")]) # ë°°ìč íŹêž°ë 1ì
ëë€
-```
-
-ìžìŽ ID넌 `"en"`ìŒëĄ ì€ì íŽ ìžìŽ ìëČ ë©ì ì ìí©ëë€.
-ìžìŽ ìëČ ë©ì ììŽì ìžìŽ IDìž `0`ìŒëĄ ì±ìì§ í
ìì
ëë€.
-ìŽ í
ìë `input_ids`ì ê°ì íŹêž°ìŹìŒ í©ëë€.
-
-```py
->>> language_id = tokenizer.lang2id["en"] # 0
->>> langs = torch.tensor([language_id] * input_ids.shape[1]) # torch.tensor([0, 0, 0, ..., 0])
-
->>> # (batch_size, sequence_length) shapeì í
ìê° ëëëĄ ë§ëëë€.
->>> langs = langs.view(1, -1) # ìŽì [1, sequence_length] shapeìŽ ëìì”ëë€(ë°°ìč íŹêž°ë 1ì
ëë€)
-```
-
-ìŽì `input_ids`ì ìžìŽ ìëČ ë©ì ëȘšëžëĄ ì ëŹí©ëë€:
-
-```py
->>> outputs = model(input_ids, langs=langs)
-```
-
-[run_generation.py](https://github.com/huggingface/transformers/tree/main/examples/pytorch/text-generation/run_generation.py) ì€íŹëŠœížëĄ `xlm-clm` ìČŽíŹíŹìžížë„Œ ìŹì©íŽ í
ì€ížì ìžìŽ ìëČ ë©ì ìì±í ì ìì”ëë€.
-
-### ìžìŽ ìëČ ë©ì ìŹì©íì§ ìë XLM[[xlm-without-language-embeddings]]
-
-ë€ì XLM ëȘšëžì ì¶ëĄ ìì ìžìŽ ìëČ ë©ìŽ íìíì§ ìì”ëë€:
-
-- `xlm-mlm-17-1280` (ë§ì€íčë ìžìŽ ëȘšëžë§, 17ê° ê”ìŽ)
-- `xlm-mlm-100-1280` (ë§ì€íčë ìžìŽ ëȘšëžë§, 100ê° ê”ìŽ)
-
-ìŽì ì XLM ìČŽíŹíŹìžížì ëŹëŠŹ ìŽ ëȘšëžì ìŒë° ëŹžì„ ííì ìŹì©ë©ëë€.
-
-## BERT[[bert]]
-
-ë€ì BERT ëȘšëžì ë€ê”ìŽ íì€íŹì ìŹì©í ì ìì”ëë€:
-
-- `bert-base-multilingual-uncased` (ë§ì€íčë ìžìŽ ëȘšëžë§ + ë€ì ëŹžì„ ììžĄ, 102ê° ê”ìŽ)
-- `bert-base-multilingual-cased` (ë§ì€íčë ìžìŽ ëȘšëžë§ + ë€ì ëŹžì„ ììžĄ, 104ê° ê”ìŽ)
-
-ìŽëŹí ëȘšëžì ì¶ëĄ ìì ìžìŽ ìëČ ë©ìŽ íìíì§ ìì”ëë€.
-돞맄ìì ìžìŽë„Œ ìëłíêł , ìëłë ìžìŽëĄ ì¶ëĄ í©ëë€.
-
-## XLM-RoBERTa[[xlmroberta]]
-
-ë€ì XLM-RoBERTa ëí ë€ê”ìŽ ë€ê”ìŽ íì€íŹì ìŹì©í ì ìì”ëë€:
-
-- `xlm-roberta-base` (ë§ì€íčë ìžìŽ ëȘšëžë§, 100ê° ê”ìŽ)
-- `xlm-roberta-large` (ë§ì€íčë ìžìŽ ëȘšëžë§, 100ê° ê”ìŽ)
-
-XLM-RoBERTaë 100ê° ê”ìŽì ëíŽ ìëĄ ìì±ëêł ì ì ë 2.5TB ê·ëȘšì CommonCrawl ë°ìŽí°ëĄ íì”ëìì”ëë€.
-ìŽì ì êł”ê°ë mBERTë XLMêłŒ ê°ì ë€ê”ìŽ ëȘšëžì ëčíŽ ë¶ë„, ìíì€ ëŒëČšë§, ì§ì ìë”êłŒ ê°ì ë€ìŽì€ížëŠŒ(downstream) ìì
ìì ìŽì ìŽ ìì”ëë€.
-
-## M2M100[[m2m100]]
-
-ë€ì M2M100 ëȘšëž ëí ë€ê”ìŽ ë€ê”ìŽ íì€íŹì ìŹì©í ì ìì”ëë€:
-
-- `facebook/m2m100_418M` (ëČì)
-- `facebook/m2m100_1.2B` (ëČì)
-
-ìŽ ìì ììë `facebook/m2m100_418M` ìČŽíŹíŹìžížë„Œ ê°ì žìì ì€ê”ìŽë„Œ ììŽëĄ ëČìí©ëë€.
-í íŹëìŽì ìì ëČì ëì ìžìŽ(source language)넌 ì€ì í ì ìì”ëë€:
-
-```py
->>> from transformers import M2M100ForConditionalGeneration, M2M100Tokenizer
-
->>> en_text = "Do not meddle in the affairs of wizards, for they are subtle and quick to anger."
->>> chinese_text = "äžèŠææć·«ćž«çäșć, ć çșä»ćæŻćŸźćŠç, ćŸćż«ć°±æçŒæ."
-
->>> tokenizer = M2M100Tokenizer.from_pretrained("facebook/m2m100_418M", src_lang="zh")
->>> model = M2M100ForConditionalGeneration.from_pretrained("facebook/m2m100_418M")
-```
-
-돞ì„ì í í°íí©ëë€:
-
-```py
->>> encoded_zh = tokenizer(chinese_text, return_tensors="pt")
-```
-
-M2M100ì ëČìì ì§ííêž° ìíŽ ìČ« ëČì§žëĄ ìì±ëë í í°ì ëČìí ìžìŽ(target language) IDëĄ ê°ì ì§ì í©ëë€.
-ììŽëĄ ëČìíêž° ìíŽ `generate` ë©ìëìì `forced_bos_token_id`넌 `en`ìŒëĄ ì€ì í©ëë€:
-
-```py
->>> generated_tokens = model.generate(**encoded_zh, forced_bos_token_id=tokenizer.get_lang_id("en"))
->>> tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)
-'Do not interfere with the matters of the witches, because they are delicate and will soon be angry.'
-```
-
-## MBart[[mbart]]
-
-ë€ì MBart ëȘšëž ëí ë€ê”ìŽ íì€íŹì ìŹì©í ì ìì”ëë€:
-
-- `facebook/mbart-large-50-one-to-many-mmt` (ìŒëë€ ë€ê”ìŽ ëČì, 50ê° ê”ìŽ)
-- `facebook/mbart-large-50-many-to-many-mmt` (ë€ëë€ ë€ê”ìŽ ëČì, 50ê° ê”ìŽ)
-- `facebook/mbart-large-50-many-to-one-mmt` (ë€ëìŒ ë€ê”ìŽ ëČì, 50ê° ê”ìŽ)
-- `facebook/mbart-large-50` (ë€ê”ìŽ ëČì, 50ê° ê”ìŽ)
-- `facebook/mbart-large-cc25`
-
-ìŽ ìì ììë íëëìŽë„Œ ììŽëĄ ëČìíêž° ìíŽ `facebook/mbart-large-50-many-to-many-mmt` ìČŽíŹíŹìžížë„Œ ê°ì žì”ëë€.
-í íŹëìŽì ìì ëČì ëì ìžìŽ(source language)넌 ì€ì í ì ìì”ëë€:
-
-```py
->>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
-
->>> en_text = "Do not meddle in the affairs of wizards, for they are subtle and quick to anger."
->>> fi_text = "ĂlĂ€ sekaannu velhojen asioihin, sillĂ€ ne ovat hienovaraisia ja nopeasti vihaisia."
-
->>> tokenizer = AutoTokenizer.from_pretrained("facebook/mbart-large-50-many-to-many-mmt", src_lang="fi_FI")
->>> model = AutoModelForSeq2SeqLM.from_pretrained("facebook/mbart-large-50-many-to-many-mmt")
-```
-
-돞ì„ì í í°íí©ëë€:
-
-```py
->>> encoded_en = tokenizer(en_text, return_tensors="pt")
-```
-
-MBartë ëČìì ì§ííêž° ìíŽ ìČ« ëČì§žëĄ ìì±ëë í í°ì ëČìí ìžìŽ(target language) IDëĄ ê°ì ì§ì í©ëë€.
-ììŽëĄ ëČìíêž° ìíŽ `generate` ë©ìëìì `forced_bos_token_id`넌 `en`ìŒëĄ ì€ì í©ëë€:
-
-```py
->>> generated_tokens = model.generate(**encoded_en, forced_bos_token_id=tokenizer.lang_code_to_id("en_XX"))
->>> tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)
-"Don't interfere with the wizard's affairs, because they are subtle, will soon get angry."
-```
-
-`facebook/mbart-large-50-many-to-one-mmt` ìČŽíŹíŹìžížë„Œ ìŹì©íêł ìë€ë©Ž, ìČ« ëČì§žëĄ ìì±ëë í í°ì ëČìí ìžìŽ(target language) IDëĄ ê°ì ì§ì í íìë ìì”ëë€.
diff --git a/docs/source/ko/notebooks.mdx b/docs/source/ko/notebooks.mdx
deleted file mode 100644
index ead906183348..000000000000
--- a/docs/source/ko/notebooks.mdx
+++ /dev/null
@@ -1 +0,0 @@
-# ìŽìŹí ëČì ì€ì
ëë€. ìĄ°êž ìŽë° ë§ëì!
\ No newline at end of file
diff --git a/docs/source/ko/pad_truncation.md b/docs/source/ko/pad_truncation.md
new file mode 100644
index 000000000000..6aa8b99b1dfc
--- /dev/null
+++ b/docs/source/ko/pad_truncation.md
@@ -0,0 +1,68 @@
+
+
+# íšë©êłŒ ìëŒëŽêž°[[padding-and-truncation]]
+
+ë°°ìč ì
ë „ì êžžìŽê° ë€ë„ž êČœì°ê° ë§ìì êł ì íŹêž° í
ìëĄ ëłíí ì ìì”ëë€. íšë©êłŒ ìëŒëŽêž°ë ë€ìí êžžìŽì ë°°ìčìì ì§ìŹê°í í
ì넌 ìì±í ì ìëëĄ ìŽ ëŹžì 넌 íŽêȰíë ì ë”ì
ëë€. íšë©ì íčìí **íšë© í í°**ì ì¶ê°íìŹ ì§§ì ìíì€ê° ë°°ìčìì ê°ì„ ꞎ ìíì€ ëë ëȘšëžìì íì©íë ì”ë êžžìŽì ëìŒí êžžìŽë„Œ ê°ëëĄ í©ëë€. ìëŒëŽêž°ë ꞎ ìíì€ë„Œ ìëŒëŽìŽ íšë©êłŒ ë€ë„ž ë°©ììŒëĄ ìíì€ì êžžìŽë„Œ ëìŒíêČ í©ëë€.
+
+ëë¶ë¶ì êČœì° ë°°ìčì ê°ì„ ꞎ ìíì€ì êžžìŽëĄ íšë©íêł ëȘšëžìŽ íì©í ì ìë ì”ë êžžìŽëĄ ìëŒëŽë êČìŽ ì ìëí©ëë€. ê·žëŹë íìíë€ë©Ž APIê° ì§ìíë ë ë§ì ì ë”ì ìŹì©í ì ìì”ëë€. íìí ìžìë `padding`, `truncation`, `max_length` ìž ê°ì§ì
ëë€.
+
+`padding` ìžìë íšë©ì ì ìŽí©ëë€. ë¶ëŠŹìž ëë 돞ììŽìŒ ì ìì”ëë€:
+
+ - `True` ëë `'longest'`: ë°°ìčìì ê°ì„ ꞎ ìíì€ëĄ íšë©í©ëë€(ëšìŒ ìíì€ë§ ì êł”íë êČœì° íšë©ìŽ ì ì©ëì§ ìì”ëë€).
+ - `'max_length'`: `max_length` ìžìê° ì§ì í êžžìŽëĄ íšë©íê±°ë, `max_length`ê° ì êł”ëì§ ìì êČœì°(`max_length=None`) ëȘšëžìì íì©ëë ì”ë êžžìŽëĄ íšë©í©ëë€. ëšìŒ ìíì€ë§ ì êł”íë êČœì°ìë íšë©ìŽ ì ì©ë©ëë€.
+ - `False` ëë `'do_not_pad'`: íšë©ìŽ ì ì©ëì§ ìì”ëë€. ìŽêČìŽ êž°ëłž ëìì
ëë€.
+
+`truncation` ìžìë ìëŒëŒ ë°©ëČì ì í©ëë€. ë¶ëŠŹìž ëë 돞ììŽìŒ ì ìì”ëë€:
+
+ - `True` ëë `longest_first`: `max_length` ìžìê° ì§ì í ì”ë êžžìŽëĄ ìëŒëŽê±°ë,
+ `max_length`ê° ì êł”ëì§ ìì êČœì°(`max_length=None`) ëȘšëžìì íì©ëë ì”ë êžžìŽëĄ ìëŒë
ëë€.
+ ìíì€ ììì ê°ì„ ꞎ ìíì€ì í í°ì ì ì í êžžìŽì ëëŹí ëêčì§ íëì© ì ê±°í©ëë€.
+ - `'only_second'`: `max_length` ìžìê° ì§ì í ì”ë êžžìŽëĄ ìëŒëŽê±°ë,
+ `max_length`ê° ì êł”ëì§ ìì êČœì°(`max_length=None`) ëȘšëžìì íì©ëë ì”ë êžžìŽëĄ ìëŒë
ëë€.
+ ìíì€ ì(ëë ìíì€ ìì ë°°ìč)ê° ì êł”ë êČœì° ìì ë ëČì§ž 돞ì„ë§ ìëŒë
ëë€.
+ - `'only_first'`: `max_length` ìžìê° ì§ì í ì”ë êžžìŽëĄ ìëŒëŽê±°ë,
+ `max_length`ê° ì êł”ëì§ ìì êČœì°(`max_length=None`) ëȘšëžìì íì©ëë ì”ë êžžìŽëĄ ìëŒë
ëë€.
+ ìíì€ ì(ëë ìíì€ ìì ë°°ìč)ê° ì êł”ë êČœì° ìì ìČ« ëČì§ž 돞ì„ë§ ìëŒë
ëë€.
+ - `False` ëë `'do_not_truncate'`: ìëŒëŽêž°ë„Œ ì ì©íì§ ìì”ëë€. ìŽêČìŽ êž°ëłž ëìì
ëë€.
+
+`max_length` ìžìë íšë© ë° ìëŒëŽêž°ë„Œ ì ì©í êžžìŽë„Œ ì ìŽí©ëë€. ìŽ ìžìë ì ì ëë `None`ìŒ ì ììŒë©°, `None`ìŒ êČœì° ëȘšëžìŽ íì©í ì ìë ì”ë êžžìŽëĄ êž°ëłžê°ìŽ ì€ì ë©ëë€. ëȘšëžì íčì í ì”ë ì
ë „ êžžìŽê° ìë êČœì° `max_length`ì ëí ìëŒëŽêž° ëë íšë©ìŽ ëčíì±íë©ëë€.
+
+ë€ì íìë íšë© ë° ìëŒëŽêž°ë„Œ ì€ì íë ê¶ì„ ë°©ëČìŽ ììœëìŽ ìì”ëë€.
+ì
ë „ìŒëĄ ìíì€ ìì ìŹì©íë êČœì°, ë€ì ìì ìì `truncation=True`넌 `['only_first', 'only_second', 'longest_first']`ìì ì íí `STRATEGY`, ìŠ `truncation='only_second'` ëë `truncation='longest_first'`ëĄ ë°êŸžë©Ž ìì ì€ëȘ
í ëëĄ ìì ë ìíì€ê° ì늏ë ë°©ìì ì ìŽí ì ìì”ëë€.
+
+| ìëŒëŽêž° | íšë© | ìŹì© ë°©ëČ |
+|--------------------------------------|-----------------------------------|------------------------------------------------------------------------------------------|
+| ìëŒëŽêž° ìì | íšë© ìì | `tokenizer(batch_sentences)` |
+| | ë°°ìč ëŽ ì”ë êžžìŽëĄ íšë© | `tokenizer(batch_sentences, padding=True)` ëë |
+| | | `tokenizer(batch_sentences, padding='longest')` |
+| | ëȘšëžì ì”ë ì
ë „ êžžìŽëĄ íšë© | `tokenizer(batch_sentences, padding='max_length')` |
+| | íčì êžžìŽëĄ íšë© | `tokenizer(batch_sentences, padding='max_length', max_length=42)` |
+| | ë€ìí êžžìŽëĄ íšë© | `tokenizer(batch_sentences, padding=True, pad_to_multiple_of=8) |
+| ëȘšëžì ì”ë ì
ë „ êžžìŽëĄ ìëŒëŽêž° | íšë© ìì | `tokenizer(batch_sentences, truncation=True)` ëë |
+| | | `tokenizer(batch_sentences, truncation=STRATEGY)` |
+| | ë°°ìč ëŽ ì”ë êžžìŽëĄ íšë© | `tokenizer(batch_sentences, padding=True, truncation=True)` ëë |
+| | | `tokenizer(batch_sentences, padding=True, truncation=STRATEGY)` |
+| | ëȘšëžì ì”ë ì
ë „ êžžìŽëĄ íšë© | `tokenizer(batch_sentences, padding='max_length', truncation=True)` ëë |
+| | | `tokenizer(batch_sentences, padding='max_length', truncation=STRATEGY)` |
+| | íčì êžžìŽëĄ íšë© | ìŹì© ë¶ê° |
+| íčì êžžìŽëĄ ìëŒëŽêž° | íšë© ìì | `tokenizer(batch_sentences, truncation=True, max_length=42)` ëë |
+| | | `tokenizer(batch_sentences, truncation=STRATEGY, max_length=42)` |
+| | ë°°ìč ëŽ ì”ë êžžìŽëĄ íšë© | `tokenizer(batch_sentences, padding=True, truncation=True, max_length=42)` ëë |
+| | | `tokenizer(batch_sentences, padding=True, truncation=STRATEGY, max_length=42)` |
+| | ëȘšëžì ì”ë ì
ë „ êžžìŽëĄ íšë© | ìŹì© ë¶ê° |
+| | íčì êžžìŽëĄ íšë© | `tokenizer(batch_sentences, padding='max_length', truncation=True, max_length=42)` ëë |
+| | | `tokenizer(batch_sentences, padding='max_length', truncation=STRATEGY, max_length=42)` |
diff --git a/docs/source/ko/perf_hardware.md b/docs/source/ko/perf_hardware.md
new file mode 100644
index 000000000000..e715b39487f3
--- /dev/null
+++ b/docs/source/ko/perf_hardware.md
@@ -0,0 +1,156 @@
+
+
+
+# íë šì© ìŹì©ì ë§ì¶€í íëìšìŽ [[custom-hardware-for-training]]
+
+ëȘšëž íë šêłŒ ì¶ëĄ ì ìŹì©íë íëìšìŽë ì±ë„ì í° ìí„ì 믞ìč ì ìì”ëë€. GPUì ëíŽ ììží ììëłŽë €ë©Ž, Tim Dettmerì íë„í ëžëĄê·ž íŹì€ížë„Œ íìžíŽëłŽìžì. [ëžëĄê·ž íŹì€íž ë§íŹ](https://timdettmers.com/2020/09/07/which-gpu-for-deep-learning/) (ììŽëĄ ìì±ëš).
+
+GPU ì€ì ì ëí ì€ì©ì ìž ìĄ°ìžì ìŽíŽëłŽêČ ì”ëë€.
+
+## GPU [[gpu]]
+ë í° ëȘšëžì íë šìíŹ ëë êž°ëłžì ìŒëĄ ìž ê°ì§ ì”ì
ìŽ ìì”ëë€:
+
+- ë í° GPU
+- ë ë§ì GPU
+- ë ë§ì CPU ë° NVMe ([DeepSpeed-Infinity](../en/main_classes/deepspeed#nvme-support)넌 í”í ì€íëĄë(offload))
+
+ì°ì , íëì GPUë§ ìŹì©íë êČœì°ë¶í° ììíŽëŽ
ìë€.
+
+### ì ì êł”êžêłŒ ëê° [[power-and-cooling]]
+
+ëčìŒ êł ì±ë„ GPU넌 ê”Źë§€í êČœì°, ìŹë°ë„ž ì ì êł”êžêłŒ ì¶©ë¶í ëê°ì ì êł”íŽìŒ í©ëë€.
+
+**ì ì êł”êž**:
+
+ìŒë¶ êł ì±ë„ ìëčìì© GPUë 2ê° íčì ê°ëê°ë€ 3ê°ì PCI-E 8í ì ì ììŒìŽ ìì”ëë€. ìčŽëì ìë ììŒ ìë§íŒ ë
늜ì ìž 12V PCI-E 8í ìŒìŽëžìŽ ì°êȰëìŽ ìëì§ íìžíìžì. ê°ì ìŒìŽëžì íìȘœ ëì ìë 2ê°ì ì€í늿(ëë íŒê·ží
ìŒ(pigtail) ìŒìŽëž)ì ìŹì©íì§ ë§ìžì. ìŠ, GPUì 2ê°ì ììŒìŽ ìë€ë©Ž, PSU(ì ì êł”êž ì„ìč)ìì ìčŽëëĄ ì°êȰëë 2ê°ì PCI-E 8í ìŒìŽëžìŽ íìíë©°, ëì 2ê°ì PCI-E 8í 컀ë„í°ê° ìë ìŒìŽëžìŽ íìíì§ ìì”ëë€! ê·žë ì§ ììŒë©Ž ìčŽëì ì ìČŽ ì±ë„ì ì ëëĄ ë°ííì§ ëȘ»í ì ìì”ëë€.
+
+ê°ê°ì PCI-E 8í ì ì ìŒìŽëžì PSU ìȘœì 12V ë ìŒì ì°êȰëìŽìŒ íë©° ì”ë 150Wì ì ë „ì êł”êží ì ìì”ëë€.
+
+ìŒë¶ ë€ë„ž GPUë PCI-E 12í 컀ë„í°ë„Œ ìŹì©íë©°, ìŽëŹí 컀ë„í°ë ì”ë 500W-600Wì ì ë „ì êł”êží ì ìì”ëë€.
+
+ì ê°í GPUë 6í 컀ë„í°ë„Œ ìŹì©íë©°, ì”ë 75Wì ì ë „ì êł”êží©ëë€.
+
+ëí GPUê° ìì ì ìž ì ìì ë°ì ì ìëëĄ êł êž PSU넌 ì ííŽìŒ í©ëë€. ìŒë¶ ì íì§ì PSUë GPUê° ì”êł ì±ë„ìŒëĄ ëìíêž° ìíŽ íìí ì ìì ìì ì ìŒëĄ êł”êžíì§ ëȘ»í ì ìì”ëë€.
+
+ëŹŒëĄ , PSUë GPUì ì ìì êł”êžíêž°ì ì¶©ë¶í ìŹë¶ì ì ë „ ì©ëì ê°ì žìŒ í©ëë€.
+
+**ëê°**:
+
+GPUê° êłŒìŽë멎 ì±ë„ìŽ ì íëêł ì”ë ì±ë„ì ë°ííì§ ëȘ»í ì ììŒë©°, ë돎 ëšê±°ìì§ë©Ž ì€ì§ë ì ìì”ëë€.
+
+GPUê° êłŒìŽë ë ì íí ì ì ìšë넌 ìêž° ìŽë €ì°ë, ìë§ë +80â 믞ë§ìŽë©Ž ìąì§ë§ ë ëźììëĄ ìąì”ëë€. 70â-75â ì ëê° íë„í ìšë ëČìì
ëë€. ì±ë„ ì íê° ë°ìíêž° ììíë ìšëë ëë” 84â-90â ì ëìŒ êČì
ëë€. íì§ë§ ì±ë„ ì í ìŽìžìë ì§ìì ìŒëĄ ë§€ì° ëì ìšëë GPU ìëȘ
ì ëšì¶ìíŹ ì ìì”ëë€.
+
+ìŽìŽì, ìŹëŹ ê°ì GPU넌 ìŹì©í ë ê°ì„ ì€ìí ìžĄë©Ž ì€ íëìž GPU ê° ì°êȰ ë°©ìì ìŽíŽëłŽêČ ì”ëë€.
+
+### ë€ì€ GPU ì°êȰ ë°©ì [[multigpu-connectivity]]
+
+ë€ì€ GPU넌 ìŹì©íë êČœì° GPU ê°ì ì°êȰ ë°©ìì ì ìČŽ íë š ìê°ì í° ìí„ì 믞ìč ì ìì”ëë€. ë§ìœ GPUê° ëìŒí ëŹŒëŠŹì ë
žëì ìì êČœì°, ë€ìêłŒ ê°ìŽ íìží ì ìì”ëë€:
+
+```
+nvidia-smi topo -m
+```
+
+ë§ìœ NVLinkëĄ ì°êȰë ëìŒ GPU íêČœìŽëŒë©Ž, ë€ìêłŒ ê°ì êČ°êłŒë„Œ íìží ì ìì”ëë€:
+
+```
+ GPU0 GPU1 CPU Affinity NUMA Affinity
+GPU0 X NV2 0-23 N/A
+GPU1 NV2 X 0-23 N/A
+```
+
+NVLink넌 ì§ìíì§ ìë ë€ë„ž íêČœì êČœì°ìë ë€ìêłŒ ê°ì êČ°êłŒë„Œ íìží ì ìì”ëë€:
+```
+ GPU0 GPU1 CPU Affinity NUMA Affinity
+GPU0 X PHB 0-11 N/A
+GPU1 PHB X 0-11 N/A
+```
+
+ìŽ êČ°êłŒìë ë€ìêłŒ ê°ì ëČëĄê° íŹíšëìŽ ìì”ëë€:
+
+```
+ X = Self
+ SYS = Connection traversing PCIe as well as the SMP interconnect between NUMA nodes (e.g., QPI/UPI)
+ NODE = Connection traversing PCIe as well as the interconnect between PCIe Host Bridges within a NUMA node
+ PHB = Connection traversing PCIe as well as a PCIe Host Bridge (typically the CPU)
+ PXB = Connection traversing multiple PCIe bridges (without traversing the PCIe Host Bridge)
+ PIX = Connection traversing at most a single PCIe bridge
+ NV# = Connection traversing a bonded set of # NVLinks
+```
+
+ë°ëŒì ìČ« ëČì§ž êČ°êłŒì `NV2`ë GPUê° 2ê°ì NVLinkëĄ ì°êȰëìŽ ìë€ë êČì ëíëŽêł , ë ëČì§ž êČ°êłŒì `PHB`ë ìŒë°ì ìž ìëčìì© PCIe+ëžëŠżì§ ì€ì ì ê°ì§êł ìë€ë êČì ëíë
ëë€.
+
+ì€ì ìì ìŽë€ ì íì ì°êȰ ë°©ìì ê°ì§êł ìëì§ íìžíìžì. ìŒë¶ ì°êȰ ë°©ìì GPU ê° í”ì ì ë ëč 넎êČ ë§ë€ ì ììŒë©°(NVLinkì ê°ìŽ), ìŽë€ ì°êȰ ë°©ìì ë ë늏êČ ë§ë€ ì ìì”ëë€(PHBì ê°ìŽ).
+
+ìŹì©íë íì„ì± ì룚ì
ì ìą
ë„ì ë°ëŒ ì°êȰ ìëê° ìŁŒìí ìí„ì 믞ìč ìë ìêł ëŻžëŻží ìí„ì 믞ìč ìë ìì”ëë€. DDPì ê°ìŽ GPUê° ê±°ì ëêž°ííì§ ììë ëë êČœì°, ì°êȰ ìëê° ëë €ë í° ìí„ì ë°ì§ ìì”ëë€. ë°ë©Ž ZeRO-DPì ê°ìŽ GPUê° í”ì ìŽ ë§ìŽ íìí êČœì°, ë ëč 넞 íë šì ìíŽìë ë ëč 넞 ì°êȰ ìëê° ì€ìí©ëë€.
+
+#### NVLink [[nvlink]]
+
+[NVLink](https://en.wikipedia.org/wiki/NVLink)ë Nvidiaìì ê°ë°í ì ì êž°ë°ì ì§ë Ź ë€ì€ ë ìž ê·Œê±°ëŠŹ í”ì ë§íŹì
ëë€.
+
+ìëĄìŽ ìžëì NVLinkë ë ëč 넞 ëìíì ì êł”í©ëë€. [Nvidia Ampere GA102 GPU Architecture](https://www.nvidia.com/content/dam/en-zz/Solutions/geforce/ampere/pdf/NVIDIA-ampere-GA102-GPU-Architecture-Whitepaper-V1.pdf)ìì ìëì ê°ì ì ëłŽë„Œ íìžíì€ ì ìì”ëë€:
+
+> 3ìžë NVLinkÂź
+> GA102 GPUë 4ê°ì x4 ë§íŹë„Œ íŹíšíë NVIDIAì 3ìžë NVLink ìží°íìŽì€ë„Œ íì©íë©°,
+> ê° ë§íŹë ë ê°ì GPU ê°ì ê° ë°©í„ìŒëĄ ìŽëč 14.0625GBì ëìíì ì êł”í©ëë€.
+> 4ê°ì ë§íŹë ê° ë°©í„ì ìŽëč 56.25GBì ëìíì ì êł”íë©°, ë ê°ì GPU ê°ìë ìŽëč 112.5GBì ìŽ ëìíì ì êł”í©ëë€.
+> ë ê°ì RTX 3090 GPU넌 NVLink넌 ìŹì©íŽ SLIëĄ ì°êȰí ì ìì”ëë€.
+> (3-Way ë° 4-Way SLI ê”Źì±ì ì§ìëì§ ììì ì ìíìžì.)
+
+
+ë°ëŒì `nvidia-smi topo -m`ì êČ°êłŒìì `NVX`ì ê°ìŽ ëììëĄ ë ìąì”ëë€. ìžëë GPU ìí€í
ìČì ë°ëŒ ë€ë„Œ ì ìì”ëë€.
+
+ê·žë ë€ë©Ž, gpt2넌 ìì wikitext ìíëĄ íì”ìí€ë ìì 넌 í”íŽ, NVLinkê° íë šì ìŽë€ ìí„ì 믞ìčëì§ ìŽíŽëłŽêČ ì”ëë€.
+
+êČ°êłŒë ë€ìêłŒ ê°ì”ëë€:
+
+
+| NVlink | Time |
+| ----- | ---: |
+| Y | 101s |
+| N | 131s |
+
+
+NVLink ìŹì© ì íë šìŽ ìœ 23% ë ëč 넎êČ ìëŁëšì íìží ì ìì”ëë€. ë ëČì§ž ëČ€ìčë§íŹììë `NCCL_P2P_DISABLE=1`ì ìŹì©íìŹ NVLink넌 ìŹì©íì§ ìëëĄ ì€ì íì”ëë€.
+
+ì ìČŽ ëČ€ìčë§íŹ ìœëì êČ°êłŒë ë€ìêłŒ ê°ì”ëë€:
+
+```bash
+# DDP w/ NVLink
+
+rm -r /tmp/test-clm; CUDA_VISIBLE_DEVICES=0,1 python -m torch.distributed.launch \
+--nproc_per_node 2 examples/pytorch/language-modeling/run_clm.py --model_name_or_path gpt2 \
+--dataset_name wikitext --dataset_config_name wikitext-2-raw-v1 --do_train \
+--output_dir /tmp/test-clm --per_device_train_batch_size 4 --max_steps 200
+
+{'train_runtime': 101.9003, 'train_samples_per_second': 1.963, 'epoch': 0.69}
+
+# DDP w/o NVLink
+
+rm -r /tmp/test-clm; CUDA_VISIBLE_DEVICES=0,1 NCCL_P2P_DISABLE=1 python -m torch.distributed.launch \
+--nproc_per_node 2 examples/pytorch/language-modeling/run_clm.py --model_name_or_path gpt2 \
+--dataset_name wikitext --dataset_config_name wikitext-2-raw-v1 --do_train
+--output_dir /tmp/test-clm --per_device_train_batch_size 4 --max_steps 200
+
+{'train_runtime': 131.4367, 'train_samples_per_second': 1.522, 'epoch': 0.69}
+```
+
+íëìšìŽ: ê°ê° 2ê°ì TITAN RTX 24GB + 2ê°ì NVLink (`NV2` in `nvidia-smi topo -m`)
+ìíížìšìŽ: `pytorch-1.8-to-be` + `cuda-11.0` / `transformers==4.3.0.dev0`
diff --git a/docs/source/ko/perf_infer_cpu.md b/docs/source/ko/perf_infer_cpu.md
new file mode 100644
index 000000000000..123e56b4f32c
--- /dev/null
+++ b/docs/source/ko/perf_infer_cpu.md
@@ -0,0 +1,73 @@
+
+
+# CPUìì íšìšì ìž ì¶ëĄ íêž° [[efficient-inference-on-cpu]]
+
+ìŽ ê°ìŽëë CPUìì ëê·ëȘš ëȘšëžì íšìšì ìŒëĄ ì¶ëĄ íë ë°©ëČì ì€ì ì ëêł ìì”ëë€.
+
+## ë ëč 넞 ì¶ëĄ ì ìí `BetterTransformer` [[bettertransformer-for-faster-inference]]
+
+ì°ëŠŹë ì”ê·Œ CPUìì í
ì€íž, ìŽëŻžì§ ë° ì€ëì€ ëȘšëžì ëč 넞 ì¶ëĄ ì ìíŽ `BetterTransformer`넌 í”í©íì”ëë€. ìŽ í”í©ì ëí ë ììží ëŽì©ì [ìŽ ëŹžì](https://huggingface.co/docs/optimum/bettertransformer/overview)넌 ì°žìĄ°íìžì.
+
+## PyTorch JIT ëȘšë (TorchScript) [[pytorch-jitmode-torchscript]]
+TorchScriptë PyTorch ìœëìì ì§ë Źíì ì”ì íê° ê°ë„í ëȘšëžì ìì±í ë ì°ì
ëë€. TorchScriptëĄ ë§ë€ìŽì§ íëĄê·žëšì êž°ìĄŽ Python íëĄìžì€ìì ì ì„í ë€, ìą
ìì±ìŽ ìë ìëĄìŽ íëĄìžì€ëĄ ê°ì žìŹ ì ìì”ëë€. PyTorchì êž°ëłž ì€ì ìž `eager` ëȘšëì ëčê”íìë, `jit` ëȘšëë ì°ì°ì êȰí©êłŒ ê°ì ì”ì í ë°©ëČëĄ ì í”íŽ ëȘšëž ì¶ëĄ ìì ëë¶ë¶ ë ëì ì±ë„ì ì êł”í©ëë€.
+
+TorchScriptì ëí ìčì í ìê°ë [PyTorch TorchScript íí 늏ìŒ](https://pytorch.org/tutorials/beginner/Intro_to_TorchScript_tutorial.html#tracing-modules)ì ì°žìĄ°íìžì.
+
+### JIT ëȘšëì íšê»íë IPEX ê·žëí ì”ì í [[ipex-graph-optimization-with-jitmode]]
+IntelÂź Extension for PyTorch(IPEX)ë Transformers êłìŽ ëȘšëžì jit ëȘšëìì ì¶ê°ì ìž ì”ì í넌 ì êł”í©ëë€. jit ëȘšëì ëë¶ìŽ IntelÂź Extension for PyTorch(IPEX)넌 íì©íìêžž ê°ë „í ê¶ì„ë늜ëë€. Transformers ëȘšëžìì ììŁŒ ìŹì©ëë ìŒë¶ ì°ì°ì íšíŽì ìŽëŻž jit ëȘšë ì°ì°ì êȰí©(operator fusion)ì ííëĄ IntelÂź Extension for PyTorch(IPEX)ìì ì§ìëêł ìì”ëë€. Multi-head-attention, Concat Linear, Linear+Add, Linear+Gelu, Add+LayerNorm êČ°í© íšíŽ ë±ìŽ ìŽì© ê°ë„íë©° íì©íì ë ì±ë„ìŽ ì°ìí©ëë€. ì°ì°ì êȰí©ì ìŽì ì ìŹì©ììêČ êł ì€ëí ì ëŹë©ëë€. ë¶ìì ë°ë„Žë©Ž, ì§ì ìë”, í
ì€íž ë¶ë„ ë° í í° ë¶ë„ì ê°ì ê°ì„ ìžêž° ìë NLP íì€íŹ ì€ ìœ 70%ê° ìŽëŹí êČ°í© íšíŽì ìŹì©íìŹ Float32 ì ë°ëì BFloat16 íŒí© ì ë°ë ëȘšëìì ì±ë„ìì ìŽì ì ì»ì ì ìì”ëë€.
+
+[IPEX ê·žëí ì”ì í](https://intel.github.io/intel-extension-for-pytorch/cpu/latest/tutorials/features/graph_optimization.html)ì ëí ììží ì ëłŽë„Œ íìžíìžì.
+
+#### IPEX ì€ìč: [[ipex-installation]]
+
+IPEX ë°°íŹ ìŁŒêž°ë PyTorch넌 ë°ëŒì ìŽëŁšìŽì§ëë€. ììží ì 볎ë [IPEX ì€ìč ë°©ëČ](https://intel.github.io/intel-extension-for-pytorch/)ì íìžíìžì.
+
+### JIT ëȘšë ìŹì©ëČ [[usage-of-jitmode]]
+íê° ëë ììžĄì ìíŽ Trainerìì JIT ëȘšë넌 ìŹì©íë €ë©Ž Trainerì ëȘ
ë č ìžìì `jit_mode_eval`ì ì¶ê°íŽìŒ í©ëë€.
+
+
+
+PyTorchì ëČì ìŽ 1.14.0 ìŽììŽëŒë©Ž, jit ëȘšëë jit.traceìì dict ì
ë „ìŽ ì§ìëëŻëĄ, ëȘšë ëȘšëžì ììžĄêłŒ íê°ê° ê°ì ë ì ìì”ëë€.
+
+PyTorchì ëČì ìŽ 1.14.0 믞ë§ìŽëŒë©Ž, ì§ì ìë” ëȘšëžêłŒ ê°ìŽ forward ë§€ê°ëłìì ììê° jit.traceì íí ì
ë „ ììì ìŒìčíë ëȘšëžì ëìŽ ë ì ìì”ëë€. í
ì€íž ë¶ë„ ëȘšëžêłŒ ê°ìŽ forward ë§€ê°ëłì ììê° jit.traceì íí ì
ë „ ììì ë€ë„ž êČœì°, jit.traceê° ì€íšíë©° ììžê° ë°ìí©ëë€. ìŽë ììžìí©ì ìŹì©ììêČ ìëŠŹêž° ìíŽ LoggingìŽ ìŹì©ë©ëë€.
+
+
+
+[Transformers ì§ì ìë”](https://github.com/huggingface/transformers/tree/main/examples/pytorch/question-answering)ì ìŹì© ìŹëĄ ìì넌 ì°žìĄ°íìžì.
+
+
+- CPUìì jit ëȘšë넌 ìŹì©í ì¶ëĄ :
+python run_qa.py \
+--model_name_or_path csarron/bert-base-uncased-squad-v1 \
+--dataset_name squad \
+--do_eval \
+--max_seq_length 384 \
+--doc_stride 128 \
+--output_dir /tmp/ \
+--no_cuda \
+--jit_mode_eval
+
+- CPUìì IPEXì íšê» jit ëȘšë넌 ìŹì©í ì¶ëĄ :
+python run_qa.py \
+--model_name_or_path csarron/bert-base-uncased-squad-v1 \
+--dataset_name squad \
+--do_eval \
+--max_seq_length 384 \
+--doc_stride 128 \
+--output_dir /tmp/ \
+--no_cuda \
+--use_ipex \
+--jit_mode_eval
diff --git a/docs/source/ko/perf_infer_gpu_many.md b/docs/source/ko/perf_infer_gpu_many.md
new file mode 100644
index 000000000000..3e4542180398
--- /dev/null
+++ b/docs/source/ko/perf_infer_gpu_many.md
@@ -0,0 +1,27 @@
+
+
+# ë€ì€ GPUìì íšìšì ìž ì¶ëĄ [[efficient-inference-on-a-multiple-gpus]]
+
+ìŽ ëŹžììë ë€ì€ GPUìì íšìšì ìŒëĄ ì¶ëĄ íë ë°©ëČì ëí ì ëłŽê° íŹíšëìŽ ìì”ëë€.
+
+
+ì°žêł : ë€ì€ GPU ì€ì ì [ëšìŒ GPU ìčì
](./perf_infer_gpu_one)ìì ì€ëȘ
ë ëë¶ë¶ì ì ë”ì ìŹì©í ì ìì”ëë€. ê·žëŹë ë ëì íì©ì ìíŽ ê°ëší êž°ëČë€ì ìììŒ í©ëë€.
+
+
+
+## ë ëč 넞 ì¶ëĄ ì ìí `BetterTransformer` [[bettertransformer-for-faster-inference]]
+
+ì°ëŠŹë ì”ê·Œ í
ì€íž, ìŽëŻžì§ ë° ì€ëì€ ëȘšëžì ëí ë€ì€ GPUìì ë ëč 넞 ì¶ëĄ ì ìíŽ `BetterTransformer`넌 í”í©íì”ëë€. ììží ëŽì©ì ìŽ í”í©ì ëí [돞ì](https://huggingface.co/docs/optimum/bettertransformer/overview)넌 íìžíììì€.
\ No newline at end of file
diff --git a/docs/source/ko/perf_infer_gpu_one.md b/docs/source/ko/perf_infer_gpu_one.md
new file mode 100644
index 000000000000..73cef858b97d
--- /dev/null
+++ b/docs/source/ko/perf_infer_gpu_one.md
@@ -0,0 +1,184 @@
+
+
+# ëšìŒ GPUìì íšìšì ìž ì¶ëĄ [[efficient-inference-on-a-single-gpu]]
+
+ìŽ ê°ìŽë ìžìë, [ëšìŒ GPUììì íë š ê°ìŽë](perf_train_gpu_one)ì [CPUììì ì¶ëĄ ê°ìŽë](perf_infer_cpu)ììë êŽë š ì ëłŽë„Œ ì°Ÿì ì ìì”ëë€.
+
+## Better Transformer: PyTorch ë€ìŽí°ëž Transformer íšì€ížíšì€ [[better-transformer-pytorchnative-transformer-fastpath]]
+
+PyTorch ë€ìŽí°ëž [`nn.MultiHeadAttention`](https://pytorch.org/blog/a-better-transformer-for-fast-transformer-encoder-inference/) ìŽí
ì
íšì€ížíšì€ìž BetterTransformerë [đ€ Optimum ëŒìŽëžëŹëŠŹ](https://huggingface.co/docs/optimum/bettertransformer/overview)ì í”í©ì í”íŽ Transformersì íšê» ìŹì©í ì ìì”ëë€.
+
+PyTorchì ìŽí
ì
íšì€ížíšì€ë 컀ë íšì êłŒ [ì€ìČ©ë í
ì](https://pytorch.org/docs/stable/nested.html)ì ìŹì©ì í”íŽ ì¶ëĄ ìë넌 ëìŒ ì ìì”ëë€. ììží ëČ€ìčë§íŹë [ìŽ ëžëĄê·ž êž](https://medium.com/pytorch/bettertransformer-out-of-the-box-performance-for-huggingface-transformers-3fbe27d50ab2)ìì íìží ì ìì”ëë€.
+
+[`optimum`](https://github.com/huggingface/optimum) íší€ì§ë„Œ ì€ìčí íìë ì¶ëĄ ì€ Better Transformer넌 ìŹì©í ì ìëëĄ [`~PreTrainedModel.to_bettertransformer`]넌 ížì¶íìŹ êŽë š ëŽë¶ ëȘšëì ëìČŽí©ëë€:
+
+```python
+model = model.to_bettertransformer()
+```
+
+[`~PreTrainedModel.reverse_bettertransformer`] ë©ìëë ì ê·íë transformers ëȘšëžë§ì ìŹì©íêž° ìíŽ ëȘšëžì ì ì„íêž° ì ìëì ëȘšëžë§ìŒëĄ ëìê° ì ìëëĄ íŽì€ëë€:
+
+```python
+model = model.reverse_bettertransformer()
+model.save_pretrained("saved_model")
+```
+
+PyTorch 2.0ë¶í°ë ìŽí
ì
íšì€ížíšì€ê° ìžìœëì ëìœë ëȘšëìì ì§ìë©ëë€. ì§ìëë ìí€í
ìČ ëȘ©ëĄì [ìŹêž°](https://huggingface.co/docs/optimum/bettertransformer/overview#supported-models)ìì íìží ì ìì”ëë€.
+
+## FP4 íŒí© ì ë°ë ì¶ëĄ ì ìí `bitsandbytes` í”í© [[bitsandbytes-integration-for-fp4-mixedprecision-inference]]
+
+`bitsandbytes`넌 ì€ìčí멎 GPUìì ììœêČ ëȘšëžì ìì¶í ì ìì”ëë€. FP4 ììí넌 ìŹì©í멎 ìëì ì ìČŽ ì ë°ë ëČì êłŒ ëčê”íìŹ ëȘšëž íŹêž°ë„Œ ì”ë 8ë°° ì€ìŒ ì ìì”ëë€. ìëìì ììíë ë°©ëČì íìžíìžì.
+
+
+
+ìŽ êž°ë„ì ë€ì€ GPU ì€ì ììë ìŹì©í ì ìì”ëë€.
+
+
+
+### ìê”Ź ìŹí [[requirements-for-fp4-mixedprecision-inference]]
+
+- ì”ì `bitsandbytes` ëŒìŽëžëŹëŠŹ
+`pip install bitsandbytes>=0.39.0`
+
+- ì”ì `accelerate`넌 ìì€ìì ì€ìč
+`pip install git+https://github.com/huggingface/accelerate.git`
+
+- ì”ì `transformers`넌 ìì€ìì ì€ìč
+`pip install git+https://github.com/huggingface/transformers.git`
+
+### FP4 ëȘšëž ì€í - ëšìŒ GPU ì€ì - ëč 넞 ìì [[running-fp4-models-single-gpu-setup-quickstart]]
+
+ë€ì ìœë넌 ì€ííìŹ ëšìŒ GPUìì ëč 넎êČ FP4 ëȘšëžì ì€íí ì ìì”ëë€.
+
+```py
+from transformers import AutoModelForCausalLM
+
+model_name = "bigscience/bloom-2b5"
+model_4bit = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto", load_in_4bit=True)
+```
+`device_map`ì ì í ìŹíì
ëë€. ê·žëŹë `device_map = 'auto'`ëĄ ì€ì íë êČìŽ ìŹì© ê°ë„í 늏ìì€ë„Œ íšìšì ìŒëĄ ëì€íšìčíêž° ë돞ì ì¶ëĄ ì ììŽ ê¶ì„ë©ëë€.
+
+### FP4 ëȘšëž ì€í - ë€ì€ GPU ì€ì [[running-fp4-models-multi-gpu-setup]]
+
+ë€ì€ GPUìì íŒí© 4ëčíž ëȘšëžì ê°ì žì€ë ë°©ëČì ëšìŒ GPU ì€ì êłŒ ëìŒí©ëë€(ëìŒí ëȘ
ë čìŽ ìŹì©):
+```py
+model_name = "bigscience/bloom-2b5"
+model_4bit = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto", load_in_4bit=True)
+```
+íì§ë§ `accelerate`넌 ìŹì©íìŹ ê° GPUì í ëčí GPU RAMì ì ìŽí ì ìì”ëë€. ë€ìêłŒ ê°ìŽ `max_memory` ìžì넌 ìŹì©íìžì:
+
+```py
+max_memory_mapping = {0: "600MB", 1: "1GB"}
+model_name = "bigscience/bloom-3b"
+model_4bit = AutoModelForCausalLM.from_pretrained(
+ model_name, device_map="auto", load_in_4bit=True, max_memory=max_memory_mapping
+)
+```
+ìŽ ìììë ìČ« ëČì§ž GPUê° 600MBì ë©ëȘšëŠŹë„Œ ìŹì©íêł ë ëČì§ž GPUê° 1GB넌 ìŹì©í©ëë€.
+
+### êł êž ìŹì©ëČ [[advanced-usage]]
+
+ìŽ ë°©ëČì ë êł êž ìŹì©ëČì ëíŽìë [ììí](main_classes/quantization) 돞ì íìŽì§ë„Œ ì°žìĄ°íìžì.
+
+## Int8 íŒí© ì ë°ë íë Ź ë¶íŽë„Œ ìí `bitsandbytes` í”í© [[bitsandbytes-integration-for-int8-mixedprecision-matrix-decomposition]]
+
+
+
+ìŽ êž°ë„ì ë€ì€ GPU ì€ì ììë ìŹì©í ì ìì”ëë€.
+
+
+
+[`LLM.int8() : 8-bit Matrix Multiplication for Transformers at Scale`](https://arxiv.org/abs/2208.07339) ë
ŒëŹžìì ì°ëŠŹë ëȘ ì€ì ìœëëĄ Hubì ëȘšë ëȘšëžì ëí Hugging Face í”í©ì ì§ìí©ëë€.
+ìŽ ë°©ëČì `float16` ë° `bfloat16` ê°ì€ìčì ëíŽ `nn.Linear` íŹêž°ë„Œ 2ë°°ëĄ ì€ìŽêł , `float32` ê°ì€ìčì ëíŽ 4ë°°ëĄ ì€ì
ëë€. ìŽë ì ë° ì ë°ëìì ìŽììč넌 ìČ늏íšìŒëĄìš íì§ì ê±°ì ìí„ì 믞ìčì§ ìì”ëë€.
+
+
+
+Int8 íŒí© ì ë°ë íë Ź ë¶íŽë íë Ź êł±ì
ì ë ê°ì ì€ížëŠŒìŒëĄ ë¶ëŠŹí©ëë€: (1) fp16ëĄ êł±íŽì§ë ìČŽêłì ìž íčìŽê° ìŽììč ì€ížëŠŒ íë Ź(0.01%) ë° (2) int8 íë Ź êł±ì
ì ìŒë°ì ìž ì€ížëŠŒ(99.9%). ìŽ ë°©ëČì ìŹì©í멎 ë§€ì° í° ëȘšëžì ëíŽ ììžĄ ì í ììŽ int8 ì¶ëĄ ìŽ ê°ë„í©ëë€.
+ìŽ ë°©ëČì ëí ììží ëŽì©ì [ë
ŒëŹž](https://arxiv.org/abs/2208.07339)ìŽë [í”í©ì êŽí ëžëĄê·ž êž](https://huggingface.co/blog/hf-bitsandbytes-integration)ìì íìží ì ìì”ëë€.
+
+
+
+컀ëì GPU ì ì©ìŒëĄ 컎íìŒëìŽ ìêž° ë돞ì íŒí© 8ëčíž ëȘšëžì ì€ííë €ë©Ž GPUê° íìí©ëë€. ìŽ êž°ë„ì ìŹì©íêž° ì ì ëȘšëžì 1/4(ëë ëȘšëž ê°ì€ìčê° ì ë° ì ë°ëìž êČœì° ì ë°)ì ì ì„í ì¶©ë¶í GPU ë©ëȘšëŠŹê° ìëì§ íìžíìžì.
+ìŽ ëȘšëì ìŹì©íë ë° ëììŽ ëë ëȘ ê°ì§ ì°žêł ìŹíìŽ ìëì ëì ìì”ëë€. ëë [Google colab](#colab-demos)ìì ë°ëȘšë„Œ ë°ëŒí ìë ìì”ëë€.
+
+### ìê”Ź ìŹí [[requirements-for-int8-mixedprecision-matrix-decomposition]]
+
+- `bitsandbytes<0.37.0`ì ìŹì©íë êČœì°, 8ëčíž í
ì ìœìŽ(Turing, Ampere ëë ìŽí ìí€í
ìČ - ì: T4, RTX20s RTX30s, A40-A100)넌 ì§ìíë NVIDIA GPUìì ì€ííëì§ íìžíìžì. `bitsandbytes>=0.37.0`ì ìŹì©íë êČœì°, ëȘšë GPUê° ì§ìë©ëë€.
+- ìŹë°ë„ž ëČì ì `bitsandbytes`넌 ë€ì ëȘ
ë čìŒëĄ ì€ìčíìžì:
+`pip install bitsandbytes>=0.31.5`
+- `accelerate`넌 ì€ìčíìžì
+`pip install accelerate>=0.12.0`
+
+### íŒí© Int8 ëȘšëž ì€í - ëšìŒ GPU ì€ì [[running-mixedint8-models-single-gpu-setup]]
+
+íìí ëŒìŽëžëŹëŠŹë„Œ ì€ìčí í íŒí© 8ëčíž ëȘšëžì ê°ì žì€ë ë°©ëČì ë€ìêłŒ ê°ì”ëë€:
+
+```py
+from transformers import AutoModelForCausalLM
+
+model_name = "bigscience/bloom-2b5"
+model_8bit = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto", load_in_8bit=True)
+```
+
+í
ì€íž ìì±ì êČœì°:
+
+* `pipeline()` íšì ëì ëȘšëžì `generate()` ë©ìë넌 ìŹì©íë êČì ê¶ì„í©ëë€. `pipeline()` íšìëĄë ì¶ëĄ ìŽ ê°ë„íì§ë§, íŒí© 8ëčíž ëȘšëžì ì”ì íëì§ ììêž° ë돞ì `generate()` ë©ìë넌 ìŹì©íë êČëłŽë€ ë늎 ì ìì”ëë€. ëí, nucleus ìíë§êłŒ ê°ì ìŒë¶ ìíë§ ì ë”ì íŒí© 8ëčíž ëȘšëžì ëíŽ `pipeline()` íšììì ì§ìëì§ ìì”ëë€.
+* ì
ë „ì ëȘšëžêłŒ ëìŒí GPUì ë°°ìčíë êČìŽ ìąì”ëë€.
+
+ë€ìì ê°ëší ìì
ëë€:
+
+```py
+from transformers import AutoModelForCausalLM, AutoTokenizer
+
+model_name = "bigscience/bloom-2b5"
+tokenizer = AutoTokenizer.from_pretrained(model_name)
+model_8bit = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto", load_in_8bit=True)
+
+prompt = "Hello, my llama is cute"
+inputs = tokenizer(prompt, return_tensors="pt").to("cuda")
+generated_ids = model.generate(**inputs)
+outputs = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
+```
+
+
+### íŒí© Int8 ëȘšëž ì€í - ë€ì€ GPU ì€ì [[running-mixedint8-models-multi-gpu-setup]]
+
+ë€ì€ GPUìì íŒí© 8ëčíž ëȘšëžì ëĄëíë ë°©ëČì ëšìŒ GPU ì€ì êłŒ ëìŒí©ëë€(ëìŒí ëȘ
ë čìŽ ìŹì©):
+```py
+model_name = "bigscience/bloom-2b5"
+model_8bit = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto", load_in_8bit=True)
+```
+íì§ë§ `accelerate`넌 ìŹì©íìŹ ê° GPUì í ëčí GPU RAMì ì ìŽí ì ìì”ëë€. ë€ìêłŒ ê°ìŽ `max_memory` ìžì넌 ìŹì©íìžì:
+
+```py
+max_memory_mapping = {0: "1GB", 1: "2GB"}
+model_name = "bigscience/bloom-3b"
+model_8bit = AutoModelForCausalLM.from_pretrained(
+ model_name, device_map="auto", load_in_8bit=True, max_memory=max_memory_mapping
+)
+```
+ìŽ ììììë ìČ« ëČì§ž GPUê° 1GBì ë©ëȘšëŠŹë„Œ ìŹì©íêł ë ëČì§ž GPUê° 2GB넌 ìŹì©í©ëë€.
+
+### Colab ë°ëȘš [[colab-demos]]
+
+ìŽ ë°©ëČì ìŹì©í멎 ìŽì ì Google Colabìì ì¶ëĄ í ì ììë ëȘšëžì ëíŽ ì¶ëĄ í ì ìì”ëë€.
+Google Colabìì 8ëčíž ììí넌 ìŹì©íìŹ T5-11b(42GB in fp32)넌 ì€ííë ë°ëȘšë„Œ íìžíìžì:
+
+[](https://colab.research.google.com/drive/1YORPWx4okIHXnjW7MSAidXN29mPVNT7F?usp=sharing)
+
+ëë BLOOM-3Bì ëí ë°ëȘšë„Œ íìžíìžì:
+
+[](https://colab.research.google.com/drive/1qOjXfQIAULfKvZqwCen8-MoWKGdSatZ4?usp=sharing)
\ No newline at end of file
diff --git a/docs/source/ko/perf_train_cpu.md b/docs/source/ko/perf_train_cpu.md
new file mode 100644
index 000000000000..573e7abc9d59
--- /dev/null
+++ b/docs/source/ko/perf_train_cpu.md
@@ -0,0 +1,67 @@
+
+
+# CPUìì íšìšì ìž íë š [[efficient-training-on-cpu]]
+
+ìŽ ê°ìŽëë CPUìì ëê·ëȘš ëȘšëžì íšìšì ìŒëĄ íë šíë ë° ìŽì ì ë§ì¶„ëë€.
+
+## IPEXì íŒí© ì ë°ë [[mixed-precision-with-ipex]]
+
+IPEXë AVX-512 ìŽìì ì§ìíë CPUì ì”ì íëìŽ ììŒë©°, AVX2ë§ ì§ìíë CPUìë êž°ë„ì ìŒëĄ ìëí©ëë€. ë°ëŒì AVX-512 ìŽìì Intel CPU ìžëììë ì±ë„ì ìŽì ìŽ ìì êČìŒëĄ ììëì§ë§, AVX2ë§ ì§ìíë CPU (ì: AMD CPU ëë ì€ëë Intel CPU)ì êČœì°ìë IPEX ìëìì ë ëì ì±ë„ì ëłŽìŒ ì ìì§ë§ ìŽë 볎ì„ëì§ ìì”ëë€. IPEXë Float32ì BFloat16넌 ëȘšë ìŹì©íìŹ CPU íë šì ìí ì±ë„ ì”ì í넌 ì êł”í©ëë€. BFloat16ì ìŹì©ì ë€ì ìčì
ì ìŁŒì ìŽì ì
ëë€.
+
+ì ì ë°ë ë°ìŽí° íì
ìž BFloat16ì 3ìžë XeonÂź Scalable íëĄìžì (ìœëëȘ
: Cooper Lake)ìì AVX512 ëȘ
ë čìŽ ì§í©ì ë€ìŽí°ëžëĄ ì§ìíŽ ììŒë©°, ë€ì ìžëì IntelÂź XeonÂź Scalable íëĄìžììì IntelÂź Advanced Matrix Extensions (IntelÂź AMX) ëȘ
ë čìŽ ì§í©ì ì§ìíìŹ ì±ë„ì íŹêČ í„ììíŹ ìì ì
ëë€. CPU ë°±ìëì ìë íŒí© ì ë°ë êž°ë„ì PyTorch-1.10ë¶í° íì±íëìì”ëë€. ëìì, IntelÂź Extension for PyTorchìì BFloat16ì ëí CPUì ìë íŒí© ì ë°ë ë° ì°ì°ìì BFloat16 ì”ì í넌 ëê·ëȘšëĄ íì±ííêł , PyTorch ë§ì€í° ëžëìčëĄ ë¶ë¶ì ìŒëĄ ì
ì€ížëŠŒì ë°ìíì”ëë€. ìŹì©ìë€ì IPEX ìë íŒí© ì ë°ë넌 ìŹì©íìŹ ë ëì ì±ë„êłŒ ìŹì©ì êČœíì ì»ì ì ìì”ëë€.
+
+[ìë íŒí© ì ë°ë](https://intel.github.io/intel-extension-for-pytorch/cpu/latest/tutorials/features/amp.html)ì ëí ììží ì ëłŽë„Œ íìžíììì€.
+
+### IPEX ì€ìč: [[ipex-installation]]
+
+IPEX 늎늏ì€ë PyTorch넌 ë°ëŒê°ëë€. pip넌 í”íŽ ì€ìčíë €ë©Ž:
+
+| PyTorch Version | IPEX version |
+| :---------------: | :----------: |
+| 1.13 | 1.13.0+cpu |
+| 1.12 | 1.12.300+cpu |
+| 1.11 | 1.11.200+cpu |
+| 1.10 | 1.10.100+cpu |
+
+```
+pip install intel_extension_for_pytorch== -f https://developer.intel.com/ipex-whl-stable-cpu
+```
+
+[IPEX ì€ìč](https://intel.github.io/intel-extension-for-pytorch/cpu/latest/tutorials/installation.html)ì ëí ë ë§ì ì ê·Œ ë°©ëČì íìžíììì€.
+
+### Trainerììì ìŹì©ëČ [[usage-in-trainer]]
+Trainerìì IPEXì ìë íŒí© ì ë°ë넌 íì±ííë €ë©Ž ìŹì©ìë íë š ëȘ
ë č ìžìì `use_ipex`, `bf16`, `no_cuda`넌 ì¶ê°íŽìŒ í©ëë€.
+
+[Transformers ì§ëŹž-ìë”](https://github.com/huggingface/transformers/tree/main/examples/pytorch/question-answering)ì ìŹì© ìŹëĄë„Œ ìŽíŽëłŽêČ ì”ëë€.
+
+- CPUìì BF16 ìë íŒí© ì ë°ë넌 ìŹì©íìŹ IPEXëĄ íë šíêž°:
+ python run_qa.py \
+--model_name_or_path bert-base-uncased \
+--dataset_name squad \
+--do_train \
+--do_eval \
+--per_device_train_batch_size 12 \
+--learning_rate 3e-5 \
+--num_train_epochs 2 \
+--max_seq_length 384 \
+--doc_stride 128 \
+--output_dir /tmp/debug_squad/ \
+--use_ipex \
+--bf16 --no_cuda
+
+### ì€ì” ìì [[practice-example]]
+
+ëžëĄê·ž: [Intel Sapphire RapidsëĄ PyTorch Transformers ê°ìí](https://huggingface.co/blog/intel-sapphire-rapids)
\ No newline at end of file
diff --git a/docs/source/ko/perf_train_cpu_many.md b/docs/source/ko/perf_train_cpu_many.md
new file mode 100644
index 000000000000..47545e845326
--- /dev/null
+++ b/docs/source/ko/perf_train_cpu_many.md
@@ -0,0 +1,134 @@
+
+
+# ë€ì€ CPUìì íšìšì ìŒëĄ íë šíêž° [[efficient-training-on-multiple-cpus]]
+
+íëì CPUìì íë šíë êČìŽ ë돎 ë늎 ëë ë€ì€ CPU넌 ìŹì©í ì ìì”ëë€. ìŽ ê°ìŽëë PyTorch êž°ë°ì DDP넌 ìŹì©íìŹ ë¶ì° CPU íë šì íšìšì ìŒëĄ ìííë ë°©ëČì ëíŽ ì€ëȘ
í©ëë€.
+
+## PyTorchì© IntelÂź oneCCL ë°ìžë© [[intel-oneccl-bindings-for-pytorch]]
+
+[IntelÂź oneCCL](https://github.com/oneapi-src/oneCCL) (collective communications library)ì allreduce, allgather, alltoallêłŒ ê°ì ì§í© í”ì (collective communications)ì ê”Źíí íšìšì ìž ë¶ì° ë„ëŹë íë šì ìí ëŒìŽëžëŹëŠŹì
ëë€. oneCCLì ëí ììží ì 볎ë [oneCCL 돞ì](https://spec.oneapi.com/versions/latest/elements/oneCCL/source/index.html)ì [oneCCL ìŹì](https://spec.oneapi.com/versions/latest/elements/oneCCL/source/index.html)ì ì°žìĄ°íìžì.
+
+`oneccl_bindings_for_pytorch` ëȘšë (`torch_ccl`ì ëČì 1.12 ìŽì ì ìŹì©)ì PyTorch C10D ProcessGroup API넌 ê”Źííë©°, ìžë¶ ProcessGroupëĄ ëì ìŒëĄ ê°ì žìŹ ì ììŒë©° íìŹ Linux íë«íŒììë§ ìëí©ëë€.
+
+[oneccl_bind_pt](https://github.com/intel/torch-ccl)ìì ë ììží ì ëłŽë„Œ íìžíìžì.
+
+### PyTorchì© IntelÂź oneCCL ë°ìžë© ì€ìč: [[intel-oneccl-bindings-for-pytorch-installation]]
+
+ë€ì Python ëČì ì ëí Wheel íìŒì ìŹì©í ì ìì”ëë€.
+
+| Extension Version | Python 3.6 | Python 3.7 | Python 3.8 | Python 3.9 | Python 3.10 |
+| :---------------: | :--------: | :--------: | :--------: | :--------: | :---------: |
+| 1.13.0 | | â | â | â | â |
+| 1.12.100 | | â | â | â | â |
+| 1.12.0 | | â | â | â | â |
+| 1.11.0 | | â | â | â | â |
+| 1.10.0 | â | â | â | â | |
+
+```
+pip install oneccl_bind_pt=={pytorch_version} -f https://developer.intel.com/ipex-whl-stable-cpu
+```
+`{pytorch_version}`ì 1.13.0êłŒ ê°ìŽ PyTorch ëČì ì ëíë
ëë€.
+[oneccl_bind_pt ì€ìč](https://github.com/intel/torch-ccl)ì ëí ë ë§ì ì ê·Œ ë°©ëČì íìžíŽ ëłŽìžì.
+oneCCLêłŒ PyTorchì ëČì ì ìŒìčíŽìŒ í©ëë€.
+
+
+
+oneccl_bindings_for_pytorch 1.12.0 ëČì ì 믞늏 ëčëë Wheel íìŒì PyTorch 1.12.1êłŒ ížíëì§ ìì”ëë€(PyTorch 1.12.0ì©ì
ëë€).
+PyTorch 1.12.1ì oneccl_bindings_for_pytorch 1.12.10 ëČì êłŒ íšê» ìŹì©íŽìŒ í©ëë€.
+
+
+
+## IntelÂź MPI ëŒìŽëžëŹëŠŹ [[intel-mpi-library]]
+ìŽ íì€ êž°ë° MPI ê”Źíì ìŹì©íìŹ IntelÂź ìí€í
ìČìì ì ì°íêł íšìšì ìŽë©° íì„ ê°ë„í íŽëŹì€í° ë©ìì§ì ì êł”íìžì. ìŽ ê”Źì± ììë IntelÂź oneAPI HPC Toolkitì ìŒë¶ì
ëë€.
+
+oneccl_bindings_for_pytorchë MPI ëê”Ź ìžížì íšê» ì€ìčë©ëë€. ìŹì©íêž° ì ì íêČœì ìì€ëĄ ì§ì íŽìŒ í©ëë€.
+
+IntelÂź oneCCL ëČì 1.12.0 ìŽììž êČœì°
+```
+oneccl_bindings_for_pytorch_path=$(python -c "from oneccl_bindings_for_pytorch import cwd; print(cwd)")
+source $oneccl_bindings_for_pytorch_path/env/setvars.sh
+```
+
+IntelÂź oneCCL ëČì ìŽ 1.12.0 믞ë§ìž êČœì°
+```
+torch_ccl_path=$(python -c "import torch; import torch_ccl; import os; print(os.path.abspath(os.path.dirname(torch_ccl.__file__)))")
+source $torch_ccl_path/env/setvars.sh
+```
+
+#### IPEX ì€ìč: [[ipex-installation]]
+
+IPEXë Float32ì BFloat16ì ëȘšë ìŹì©íë CPU íë šì ìí ì±ë„ ì”ì í넌 ì êł”í©ëë€. [single CPU section](./perf_train_cpu)ì ì°žìĄ°íìžì.
+
+
+ìŽìŽì ëì€ë "Trainerììì ìŹì©"ì IntelÂź MPI ëŒìŽëžëŹëŠŹì mpirunì ìëĄ ë€ìì”ëë€.
+
+
+## Trainerììì ìŹì© [[usage-in-trainer]]
+Trainerìì ccl ë°±ìë넌 ìŹì©íìŹ ë©í° CPU ë¶ì° íë šì íì±ííë €ë©Ž ëȘ
ë č ìžìì **`--ddp_backend ccl`**ì ì¶ê°íŽìŒ í©ëë€.
+
+[ì§ì ìë” ìì ](https://github.com/huggingface/transformers/tree/main/examples/pytorch/question-answering)넌 ìŹì©í ì넌 ìŽíŽëłŽêČ ì”ëë€.
+
+
+ë€ì ëȘ
ë čì í Xeon ë
žëìì 2ê°ì íëĄìžì€ëĄ íë šì íì±ííë©°, ê° ììŒëč íëì íëĄìžì€ê° ì€íë©ëë€. OMP_NUM_THREADS/CCL_WORKER_COUNT ëłìë ì”ì ì ì±ë„ì ìíŽ ìĄ°ì í ì ìì”ëë€.
+```shell script
+ export CCL_WORKER_COUNT=1
+ export MASTER_ADDR=127.0.0.1
+ mpirun -n 2 -genv OMP_NUM_THREADS=23 \
+ python3 run_qa.py \
+ --model_name_or_path bert-large-uncased \
+ --dataset_name squad \
+ --do_train \
+ --do_eval \
+ --per_device_train_batch_size 12 \
+ --learning_rate 3e-5 \
+ --num_train_epochs 2 \
+ --max_seq_length 384 \
+ --doc_stride 128 \
+ --output_dir /tmp/debug_squad/ \
+ --no_cuda \
+ --ddp_backend ccl \
+ --use_ipex
+```
+ë€ì ëȘ
ë čì ë ê°ì Xeon(ë
žë0 ë° ë
žë1, ìŁŒ íëĄìžì€ëĄ ë
žë0ì ìŹì©)ìì ìŽ 4ê°ì íëĄìžì€ëĄ íë šì íì±ííë©°, ê° ììŒëč íëì íëĄìžì€ê° ì€íë©ëë€. OMP_NUM_THREADS/CCL_WORKER_COUNT ëłìë ì”ì ì ì±ë„ì ìíŽ ìĄ°ì í ì ìì”ëë€.
+
+ë
žë0ììë ê° ë
žëì IP ìŁŒì넌 íŹíšíë ê”Źì± íìŒ(ì: hostfile)ì ìì±íêł íŽëč ê”Źì± íìŒ êČœëĄë„Œ ìžìëĄ ì ëŹíŽìŒ í©ëë€.
+```shell script
+ cat hostfile
+ xxx.xxx.xxx.xxx #node0 ip
+ xxx.xxx.xxx.xxx #node1 ip
+```
+ìŽì ë
žë0ìì ë€ì ëȘ
ë čì ì€íí멎 **4DDP**ê° ë
žë0 ë° ë
žë1ìì BF16 ìë íŒí© ì ë°ëëĄ íì±íë©ëë€.
+```shell script
+ export CCL_WORKER_COUNT=1
+ export MASTER_ADDR=xxx.xxx.xxx.xxx #node0 ip
+ mpirun -f hostfile -n 4 -ppn 2 \
+ -genv OMP_NUM_THREADS=23 \
+ python3 run_qa.py \
+ --model_name_or_path bert-large-uncased \
+ --dataset_name squad \
+ --do_train \
+ --do_eval \
+ --per_device_train_batch_size 12 \
+ --learning_rate 3e-5 \
+ --num_train_epochs 2 \
+ --max_seq_length 384 \
+ --doc_stride 128 \
+ --output_dir /tmp/debug_squad/ \
+ --no_cuda \
+ --ddp_backend ccl \
+ --use_ipex \
+ --bf16
+```
diff --git a/docs/source/ko/performance.md b/docs/source/ko/performance.md
new file mode 100644
index 000000000000..226bd5f249af
--- /dev/null
+++ b/docs/source/ko/performance.md
@@ -0,0 +1,96 @@
+
+
+# ì±ë„ ë° íì„ì± [[performance-and-scalability]]
+
+ì ì ë í° ê·ëȘšì ížëì€íŹëšž ëȘšëžì íë šíêł íëĄëì
ì ë°°íŹíë ë°ìë ë€ìí ìŽë €ììŽ ë°ëŠ
ëë€. íë š ì€ìë ëȘšëžìŽ ìŹì© ê°ë„í GPU ë©ëȘšëŠŹëłŽë€ ë ë§ì ë©ëȘšëŠŹë„Œ íìëĄ íê±°ë íë š ìëê° ë§€ì° ë늎 ì ììŒë©°, ì¶ëĄ ì ìíŽ ë°°íŹí ëë ì í íêČœìì ìê”Źëë ìČ늏ëìŒëĄ ìžíŽ êłŒë¶íê° ë°ìí ì ìì”ëë€. ìŽ ëŹžìë ìŽëŹí 돞ì 넌 ê·čëł”íêł ìŹì© ìŹëĄì ê°ì„ ì í©í ì€ì ì ì°ŸëëĄ ëìì ìŁŒêž° ìíŽ ì€êłëìì”ëë€. íë šêłŒ ì¶ëĄ ìŒëĄ ê°ìŽë넌 ë¶í íëë°, ìŽë ê°ê° ë€ë„ž 돞ì ì íŽêȰ ë°©ëČìŽ ìêž° ë돞ì
ëë€. ê·žëŠŹêł ê° ê°ìŽëìë ë€ìí ìą
ë„ì íëìšìŽ ì€ì ì ëí ëłëì ê°ìŽëê° ìì”ëë€(ì: íë šì ìí ëšìŒ GPU vs ë€ì€ GPU ëë ì¶ëĄ ì ìí CPU vs GPU).
+
+
+
+ìŽ ëŹžìë ìŹì©ìì ìí©ì ì ì©í ì ìë ë°©ëČë€ì ëí ê°ì ë° ììì ìí ì í©ëë€.
+
+## íë š [[training]]
+
+íšìšì ìž ížëì€íŹëšž ëȘšëž íë šìë GPUë TPUì ê°ì ê°ìêž°ê° íìí©ëë€. ê°ì„ ìŒë°ì ìž êČœì°ë ëšìŒ GPUë§ ìŹì©íë êČœì°ì§ë§, ë€ì€ GPU ë° CPU íë šì ëí ìčì
ë ìì”ëë€(êł§ ë ë§ì ëŽì©ìŽ ì¶ê°ë ìì ).
+
+
+
+ ì°žêł : ëšìŒ GPU ìčì
ìì ìê°ë ëë¶ë¶ì ì ë”(ì: íŒí© ì ë°ë íë š ëë ê·žëŒëìžíž ëì )ì ìŒë°ì ìž ëȘšëž íë šìë ì ì©ëëŻëĄ, ë€ì€ GPUë CPU íë šêłŒ ê°ì ìčì
ì ìŽíŽëłŽêž° ì ì êŒ ì°žêł íìêžž ë°ëëë€.
+
+
+
+### ëšìŒ GPU [[single-gpu]]
+
+ëšìŒ GPUìì ëê·ëȘš ëȘšëžì íë šíë êČì ìŽë €ìž ì ìì§ë§, ìŽë„Œ ê°ë„íêČ íë ìŹëŹ ê°ì§ ëê”Źì ë°©ëČìŽ ìì”ëë€. ìŽ ìčì
ììë íŒí© ì ë°ë íë š, ê·žëŒëìžíž ëì ë° ìČŽíŹíŹìží
, íšìšì ìž ì”í°ë§ìŽì , ì”ì ì ë°°ìč íŹêž°ë„Œ êȰì íêž° ìí ì ë” ë±ì ëíŽ ë
Œìí©ëë€.
+
+[ëšìŒ GPU íë š ìčì
ìŒëĄ ìŽë](perf_train_gpu_one)
+
+### ë€ì€ GPU [[multigpu]]
+
+ëšìŒ GPUìì íë šíë êČìŽ ë돎 ëëŠŹê±°ë ëê·ëȘš ëȘšëžì ì í©íì§ ìì êČœì°ë ìì”ëë€. ë€ì€ GPU ì€ì ìŒëĄ ì ííë êČì ë
ŒëŠŹì ìž ëšêłìŽì§ë§, ìŹëŹ GPUìì í ëČì íë šíë €ë©Ž ê° GPUë§ë€ ëȘšëžì ì ìČŽ ìŹëłžì ëì§, íčì ëȘšëž ììČŽë ìŹëŹ GPUì ë¶ì°íìŹ ëì§ ë± ìëĄìŽ êȰì ì ëŽë €ìŒ í©ëë€. ìŽ ìčì
ììë ë°ìŽí°, í
ì ë° íìŽíëŒìž ëłë Źíì ëíŽ ìŽíŽëŽ
ëë€.
+
+[ë€ì€ GPU íë š ìčì
ìŒëĄ ìŽë](perf_train_gpu_many)
+
+### CPU [[cpu]]
+
+
+[CPU íë š ìčì
ìŒëĄ ìŽë](perf_train_cpu)
+
+
+### TPU [[tpu]]
+
+[_êł§ ì êł”ë ìì _](perf_train_tpu)
+
+### íčìí íëìšìŽ [[specialized-hardware]]
+
+[_êł§ ì êł”ë ìì _](perf_train_special)
+
+## ì¶ëĄ [[inference]]
+
+ì í ë° ìëčì€ íêČœìì ëê·ëȘš ëȘšëžì íšìšì ìŒëĄ ì¶ëĄ íë êČì ëȘšëžì íë šíë êČë§íŒ ìŽë €ìž ì ìì”ëë€. ìŽìŽì§ë ìčì
ììë CPU ë° ëšìŒ/ë€ì€ GPU ì€ì ìì ì¶ëĄ ì ì§ííë ëšêłë„Œ ìŽíŽëŽ
ëë€.
+
+### CPU [[cpu]]
+
+[CPU ì¶ëĄ ìčì
ìŒëĄ ìŽë](perf_infer_cpu)
+
+### ëšìŒ GPU [[single-gpu]]
+
+[ëšìŒ GPU ì¶ëĄ ìčì
ìŒëĄ ìŽë](perf_infer_gpu_one)
+
+### ë€ì€ GPU [[multigpu]]
+
+[ë€ì€ GPU ì¶ëĄ ìčì
ìŒëĄ ìŽë](perf_infer_gpu_many)
+
+### íčìí íëìšìŽ [[specialized-hardware]]
+
+[_êł§ ì êł”ë ìì _](perf_infer_special)
+
+## íëìšìŽ [[hardware]]
+
+íëìšìŽ ìčì
ììë ìì ë§ì ë„ëŹë ì„ëč넌 ê”Źì¶í ë ì ì©í íêłŒ ìë čì ìŽíŽëłŒ ì ìì”ëë€.
+
+[íëìšìŽ ìčì
ìŒëĄ ìŽë](perf_hardware)
+
+
+## êž°ìŹíêž° [[contribute]]
+
+ìŽ ëŹžìë ìì±ëì§ ìì ìíìŽë©°, ì¶ê°íŽìŒ í ëŽì©ìŽë ìì ìŹíìŽ ë§ìŽ ìì”ëë€. ë°ëŒì ì¶ê°íê±°ë ìì í ëŽì©ìŽ ììŒë©Ž ìŁŒì íì§ ë§êł PRì ìŽìŽ ìŁŒìê±°ë, ììží ëŽì©ì ë
Œìíêž° ìíŽ Issue넌 ììíŽ ìŁŒìêž° ë°ëëë€.
+
+Aê° BëłŽë€ ìąë€êł íë êž°ìŹë„Œ í ëë, ìŹí ê°ë„í ëČ€ìčë§íŹì/ëë íŽëč ì 볎ì ì¶ìČ ë§íŹë„Œ íŹíšíŽìŁŒìžì(ëčì ìŒëĄë¶í°ì ì§ì ì ìž ì ëłŽê° ìë êČœì°).
\ No newline at end of file
diff --git a/docs/source/ko/perplexity.md b/docs/source/ko/perplexity.md
new file mode 100644
index 000000000000..72eee0643c33
--- /dev/null
+++ b/docs/source/ko/perplexity.md
@@ -0,0 +1,135 @@
+
+
+# êł ì êžžìŽ ëȘšëžì ííë ìí°(Perplexity)[[perplexity-of-fixedlength-models]]
+
+[[open-in-colab]]
+
+ííë ìí°(Perplexity, PPL)ë ê°ì„ ìŒë°ì ìž ìžìŽ ëȘšëž íê°ì§í ì€ íëì
ëë€.
+ììží ììëłŽêž° ì ì ìŽ íê°ì§íë êł ì ì ìž ìžìŽ ëȘšëž(ìêž°íê· ëë ìžêłŒì ìžìŽ ëȘšëžìŽëŒêł ë íš)ìë§ ì ì©ëë©° BERTì ê°ì ë§ì€íčë ìžìŽ ëȘšëžìë ì ì ì©íì§ ìì”ëë€ (BERTë [summary of the models](../en/model_summary) 돞ì넌 ì°žêł íìžì).
+
+ííë ìí°ë ìíì€ì ìì ëĄê·ž ì°ë(negative log-likelihood, NLL) ê°ì íê· ì ì§ì(exponentiate)넌 ì·ší ê°ìŒëĄ ì ìë©ëë€.
+í í°íë ìíì€ \\(X = (x_0, x_1, \dots, x_t)\\) ê° ìì ë, \\(X\\) ì ííë ìí°ë ìë ììêłŒ ê°ìŽ ê”Źí ì ìì”ëë€.
+
+$$\text{PPL}(X) = \exp \left\{ {-\frac{1}{t}\sum_i^t \log p_\theta (x_i|x_{
+
+ê·žëŹë ëȘšëžì ê·ŒìŹìč넌 ê”Źí ëë ìŒë°ì ìŒëĄ ëȘšëžìŽ ìČ늏í ì ìë í í° ìì ì íìŽ ìì”ëë€.
+ì넌 ë€ìŽ, ê°ì„ í° ëČì ì [GPT-2](model_doc/gpt2)ë í í°ì êžžìŽê° 1024ëĄ êł ì ëìŽ ìì”ëë€.
+ë°ëŒì \\(t\\) ê° 1024ëłŽë€ í° êČœì°ì \\(p_\theta(x_t|x_{
+
+ìŽ ë°©ëČì ê° ë¶ë¶ì ííë ìí°ë„Œ í ëČì íŹìë íšì€ëĄ êłì°í ì ììŽ ëč 넎ì§ë§ ìŒë°ì ìŒëĄ ë ëì(ë ëì) PPLì ì°ì¶í©ëë€.
+ìëí멎 ëë¶ë¶ì ììžĄ ëšêłìì ëȘšëžì 컚í
ì€ížê° ì êž° ë돞ì
ëë€.
+
+ëì , êł ì êžžìŽ ëȘšëžì PPLì ìŹëŒìŽë© ìëì° ì ë”ìŒëĄ íê°íŽìŒ í©ëë€.
+ìŽ ì ë”ìë 컚í
ì€íž ìëì°ì ë°ëł”ì ìŒëĄ ìŹëŒìŽë©íŽ ëȘšëžìŽ ê° ììžĄì ìíí ë ë ë§ì 컚í
ì€ížë„Œ ê°ëëĄ íë ìì
ìŽ íŹíšë©ëë€.
+
+
+
+ìŽë ìíì€ íë„ ì ì€ì ë¶íŽì ë ê°êčìŽ ê·ŒìŹìčìŽë©° ìŒë°ì ìŒëĄ ë ì 늏í ì ì넌 ì°ì¶í©ëë€.
+ëšì ì ë§ëìčì ê° í í°ì ëíŽ ëłëì íŹìë íšì€ê° íìíë€ë êČì
ëë€.
+íì€ì ìŒëĄ ìąì ì ì¶©ìì í ëČì í í í°ì© ìŹëŒìŽë©íë êČìŽ ìëëŒ ë í° ê°êČ©ìŒëĄ 컚í
ì€ížë„Œ ìŽëíë ì€ížëŒìŽëê° ì ì©ë ìŹëŒìŽë© ìëì°ì ìŹì©íë êČì
ëë€.
+ìŽë êČ í멎 êłì°ì íšìŹ ë ëč 넎êČ ì§íí멎ìë ëȘšëžì ê° ëšêłìì ììžĄì ìíí ì ìë ꞎ 컚í
ì€ížë„Œ ì êł”í ì ìì”ëë€.
+
+## ìì : đ€ Transformersìì GPT-2ëĄ ííë ìí°(perplexity) êłì°íêž°[[example-calculating-perplexity-with-gpt2-in-transformers]]
+
+ìŽì GPT-2ëĄ ìì êłŒì ì ìì°íŽ ëłŽêČ ì”ëë€.
+
+```python
+from transformers import GPT2LMHeadModel, GPT2TokenizerFast
+
+device = "cuda"
+model_id = "gpt2-large"
+model = GPT2LMHeadModel.from_pretrained(model_id).to(device)
+tokenizer = GPT2TokenizerFast.from_pretrained(model_id)
+```
+
+WikiText-2 ë°ìŽí° ìžížë„Œ ê°ì žì€êł ëȘ ê°ì§ ìŹëŒìŽë© ìëì° ì ë”ì ìŹì©íŽ ííë ìí°ë„Œ êłì°íŽëłŽêČ ì”ëë€.
+ìŽ ë°ìŽí° ìžížë íŹêž°ê° ìêł íŹìë íšì€ í ëČë§ ìííêž° ë돞ì ì ìČŽ ë°ìŽí° ìžížë„Œ ë©ëȘšëŠŹì ê°ì žì€êł ìžìœë©í ì ìì”ëë€.
+
+```python
+from datasets import load_dataset
+
+test = load_dataset("wikitext", "wikitext-2-raw-v1", split="test")
+encodings = tokenizer("\n\n".join(test["text"]), return_tensors="pt")
+```
+
+đ€ Transformers넌 ìŹì©í멎 ëȘšëžì `labels`ëĄ `input_ids`넌 ì ëŹíŽ ê° í í°ì ëí íê· ìì ì°ë ê°ì ìì€ëĄ ë°íí ì ìì”ëë€.
+íì§ë§ ìŹëŒìŽë© ìëì° ë°©ìì ìŹì©í멎 ê° ë°ëł”ë§ë€ ëȘšëžì ì ëŹíë í í°ìŽ êČčìč©ëë€.
+컚í
ì€ížëĄ ìČ늏íë í í°ì ëí ëĄê·ž ì°ë ê°ìŽ ìì€ì íŹíšëë êČì ìíì§ ìêž° ë돞ì ìŽëŹí í í°ì `input_ids`넌 `-100`ìŒëĄ ì€ì íìŹ ëŹŽìí ì ìì”ëë€.
+
+ë€ìì ì€ížëŒìŽë(stride)넌 `512`ëĄ ìŹì©í ììì
ëë€.
+ìŠ, ëȘšëžìŽ í í í°ì ìĄ°ê±Žë¶ ì°ë ê°ì êłì°í ë 컚í
ì€ížì ì”ìí 512ê°ì í í°ìŽ íŹíšëìŽìë€ë ì믞ì
ëë€ (íŽëč í í° ìì 512ê°ì í í°ìŽ ìë êČœì°).
+
+```python
+import torch
+from tqdm import tqdm
+
+max_length = model.config.n_positions
+stride = 512
+seq_len = encodings.input_ids.size(1)
+
+nlls = []
+prev_end_loc = 0
+for begin_loc in tqdm(range(0, seq_len, stride)):
+ end_loc = min(begin_loc + max_length, seq_len)
+ trg_len = end_loc - prev_end_loc # ë§ì§ë§ 룚íì ì€ížëŒìŽë ê°êłŒ ë€ë„Œ ì ìì
+ input_ids = encodings.input_ids[:, begin_loc:end_loc].to(device)
+ target_ids = input_ids.clone()
+ target_ids[:, :-trg_len] = -100
+
+ with torch.no_grad():
+ outputs = model(input_ids, labels=target_ids)
+
+ # ìì€ì ëȘšë ì íší ë ìŽëžì ëí íê· ê°ì ê”Źíë ê”ì°š ìížëĄíŒ(cross entropy)ëĄ êłì°ë©ëë€.
+ # ëìŽëž ëČ ìŽì§ì ëȘšëžì ëŽë¶ì ìŒëĄ ë ìŽëžì ìŒìȘœìŒëĄ 1ê°ì© ë°êž° ë돞ì, (íìŒ - 1)ê° ë§íŒì ë ìŽëžì ëíŽ ìì€ì êłì°í©ëë€.
+ neg_log_likelihood = outputs.loss
+
+ nlls.append(neg_log_likelihood)
+
+ prev_end_loc = end_loc
+ if end_loc == seq_len:
+ break
+
+ppl = torch.exp(torch.stack(nlls).mean())
+```
+
+ì€ížëŒìŽë넌 ì”ë ì
ë „ êžžìŽì ëìŒíêČ ì€ì í멎 ììì ì€ëȘ
í ì°šì ì±
ìž ëčìŹëŒìŽë© ìëì° ì ë”êłŒ ëìŒí©ëë€.
+ìŒë°ì ìŒëĄ ì€ížëŒìŽëê° ìììëĄ ëȘšëžìŽ ê° ììžĄì í ë ë ë§ì 컚í
ì€ížë„Œ ëłŒ ì ìêČ ëìŽ ííë ìí° ê°ìŽ ìąìì§ëë€.
+
+ìì êłì°ì í í°ìŽ êČčìčì§ ìëëĄ `stride = 1024`ëĄ ì€ì í멎 PPLì `19.44`ëĄ GPT-2 ë
ŒëŹžìì ëłŽêł ë `19.93`êłŒ ê±°ì ëìŒí©ëë€.
+`stride = 512`ëĄ ìŹëŒìŽë© ìëì° ì ë”ì ìŹì©í멎 PPLì `16.45`ëĄ ëšìŽì§ëë€.
+ìŽë ë ìąì ì ììŒ ëżë§ ìëëŒ ìíì€ íë„ ì ì€ì ìë íê· ë¶íŽì ë ê°êčìŽ ë°©ììŒëĄ êłì°ë©ëë€.
\ No newline at end of file
diff --git a/docs/source/ko/philosophy.md b/docs/source/ko/philosophy.md
new file mode 100644
index 000000000000..94b6c46f60e2
--- /dev/null
+++ b/docs/source/ko/philosophy.md
@@ -0,0 +1,66 @@
+
+
+# ìŽë
êłŒ ëȘ©í [[philosophy]]
+
+đ€ Transformersë ë€ìêłŒ ê°ì ëȘ©ì ìŒëĄ ë§ë€ìŽì§ ë
ìì ìž ëŒìŽëžëŹëŠŹì
ëë€:
+
+- ëê·ëȘš Transformers ëȘšëžì ìŹì©íê±°ë ì°ê”Źíê±°ë íì„íë €ë êž°êł íì” ì°ê”Źì ë° ê”ìĄì넌 ìí êČì
ëë€.
+- ëȘšëžì ëŻžìž ìĄ°ì íê±°ë ì ìì©ìŒëĄ ìŹì©íêł ì íë ì€ì ê°ë°ì넌 ìí êČì
ëë€.
+- íčì êž°êł íì” ìì
ì íŽêȰíêž° ìíŽ ìŹì íë šë ëȘšëžì ë€ìŽëĄëíêł ìŹì©íêž°ë§ íë €ë ìì§ëìŽë„Œ ìí êČì
ëë€.
+
+ìŽ ëŒìŽëžëŹëŠŹë ë ê°ì§ ìŁŒì ëȘ©í넌 ê°ì§êł ì€êłëìì”ëë€:
+
+1. ìŹì©íêž° ìœêł ëč 넎êČ ë§ëë êČ:
+
+- íì”íŽìŒ í ìŹì©ì ëì ì¶ìíì ì넌 ì ííì”ëë€. ì€ì ëĄ ê±°ì ì¶ìíê° ììŒë©°, ê° ëȘšëžì ìŹì©íêž° ìíŽ íìí ìž ê°ì§ íì€ íŽëì€ìž [configuration](main_classes/configuration), [models](main_classes/model) ë° ì ìČ늏 íŽëì€ìž ([tokenizer](main_classes/tokenizer)ë NLPì©, [image processor](main_classes/image_processor)ë ëčì ì©, [feature extractor](main_classes/feature_extractor)ë ì€ëì€ì©, [processor](main_classes/processors)ë ë©í°ëȘšëŹ ì
ë „ì©)ë§ ìŹì©í©ëë€.
+- ìŽëŹí íŽëì€ë êł”í”ì ìž `from_pretrained()` ë©ìë넌 ìŹì©íìŹ ëŻžëŠŹ íë šë ìžì€íŽì€ìì ê°ëšíêł í”ìŒë ë°©ììŒëĄ ìŽêž°íí ì ìì”ëë€. ìŽ ë©ìëë 믞늏 íë šë ìČŽíŹíŹìžížìì êŽë š íŽëì€ ìžì€íŽì€ì êŽë š ë°ìŽí°(ê”Źì±ì íìŽíŒíëŒëŻží°, í íŹëìŽì ì ìŽí, ëȘšëžì ê°ì€ìč)넌 (íìí êČœì°) ë€ìŽëĄëíêł ìșìíë©° ê°ì žì”ëë€. ìČŽíŹíŹìžížë [Hugging Face Hub](https://huggingface.co/models)ìì ì êł”ëê±°ë ìŹì©ì ììČŽì ì ì„ë ìČŽíŹíŹìžížìì ì êł”ë©ëë€.
+- ìŽ ìž ê°ì§ êž°ëłž íŽëì€ ìì ëŒìŽëžëŹëŠŹë [`pipeline`] API넌 ì êł”íìŹ ìŁŒìŽì§ ìì
ì ëíŽ ëȘšëžì ëč 넎êČ ì¶ëĄ íë ë° ìŹì©íêł , [`Trainer`]넌 ì êł”íìŹ PyTorch ëȘšëžì ëč 넎êČ íë šíê±°ë ëŻžìž ìĄ°ì í ì ìëëĄ í©ëë€(ëȘšë TensorFlow ëȘšëžì `Keras.fit`êłŒ ížíë©ëë€).
+- êČ°êłŒì ìŒëĄ, ìŽ ëŒìŽëžëŹëŠŹë ì êČœë§ì ê”Źì¶íêž° ìí ëȘšëì ëê”Ź ììê° ìëëë€. ëŒìŽëžëŹëŠŹë„Œ íì„íê±°ë ê”Źì¶íë €ë©Ž ìŒë°ì ìž Python, PyTorch, TensorFlow, Keras ëȘšëì ìŹì©íêł ëŒìŽëžëŹëŠŹì êž°ëłž íŽëì€ë„Œ ììíìŹ ëȘšëž ëĄë© ë° ì ì„êłŒ ê°ì êž°ë„ì ìŹìŹì©í멎 ë©ëë€. ëȘšëžì ëí ìœë© ìČ íì ëíŽ ë ììží ìêł ì¶ë€ë©Ž [Repeat Yourself](https://huggingface.co/blog/transformers-design-philosophy) ëžëĄê·ž êžì íìžíŽëłŽìžì.
+
+2. ìë ëȘšëžêłŒ ê°ë„í í ê·Œì í ì±ë„ì ì êł”íë ì”ì ëȘšëžì ì êł”íë êČ:
+
+- ê° ìí€í
ìČì ëíŽ êł”ì ì ìê° ì êł”í êČ°êłŒë„Œ ìŹííë ì ìŽë í ê°ì§ ìì 넌 ì êł”í©ëë€.
+- ìœëë ìë ìœëì ê°ë„í í ì ìŹíêČ ì ì§ëëŻëĄ PyTorch ìœëë TensorFlow ìœëëĄ ëłíëìŽ *pytorchic*íì§ ìì ì ìêł , ê·ž ë°ëì êČœì°ë ë§ì°Źê°ì§ì
ëë€.
+
+êž°í ëȘ©í ëȘ ê°ì§:
+
+- ëȘšëžì ëŽë¶ë„Œ ê°ë„í ìŒêŽëêČ ë
žì¶ìí€êž°:
+
+ - ì ìČŽ ìë ìíì ìŽí
ì
ê°ì€ìčì ëí ìĄìžì€ë„Œ ëšìŒ API넌 ìŹì©íìŹ ì êł”í©ëë€.
+ - ì ìČ늏 íŽëì€ ë° êž°ëłž ëȘšëž APIë ëȘšëž ê°ì ìœêČ ì íí ì ìëëĄ íì€íëìŽ ìì”ëë€.
+
+- ëŻžìž ìĄ°ì ë° ëȘšëž íìì ìí ì ë§í ëê”Źë€ì ìŁŒêŽì ìŒëĄ ì ííêž°:
+
+ - ëŻžìž ìĄ°ì ì ìíŽ ìŽí ë° ìëČ ë©ì ìëĄìŽ í í°ì ê°ëšíêł ìŒêŽë ë°©ììŒëĄ ì¶ê°íë ë°©ëČì ì êł”í©ëë€.
+ - Transformer í€ë넌 ë§ì€íčíêł ê°ì§ìčêž°íë ê°ëší ë°©ëČì ì êł”í©ëë€.
+
+- PyTorch, TensorFlow 2.0 ë° Flax ê°ì ìœêČ ì íí ì ìëëĄ íìŹ íëì íë ììíŹëĄ íë šíêł ë€ë„ž íë ììíŹëĄ ì¶ëĄ í ì ìêČ í©ëë€.
+
+## ìŁŒì ê°ë
[[main-concepts]]
+
+ìŽ ëŒìŽëžëŹëŠŹë ê° ëȘšëžì ëíŽ ìž ê°ì§ ì íì íŽëì€ë„Œ êž°ë°ìŒëĄ ê”Źì¶ëìì”ëë€:
+
+- **ëȘšëž íŽëì€**ë ëŒìŽëžëŹëŠŹìì ì êł”íë ìŹì íë šë ê°ì€ìčì íšê» ìëíë PyTorch ëȘšëž([torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)), Keras ëȘšëž([tf.keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model)), JAX/Flax ëȘšëž([flax.linen.Module](https://flax.readthedocs.io/en/latest/api_reference/flax.linen.html))ìŒ ì ìì”ëë€.
+- **ê”Źì± íŽëì€**ë ëȘšëžì ê”Źì¶íë ë° íìí íìŽíŒíëŒëŻží°(ì: ë ìŽìŽ ì ë° ìë íŹêž°)넌 ì ì„í©ëë€. ê”Źì± íŽëì€ë„Œ ì§ì ìžì€íŽì€íí íìë ìì”ëë€. íčí, ìì ììŽ êł ìŹì íì”ë ëȘšëžì ìŹì©íë êČœì° ëȘšëžì ìì±í멎 ëȘšëžì ìŒë¶ìž ê”Źì±ì ìëìŒëĄ ìžì€íŽì€íë©ëë€.
+- **ì ìČ늏 íŽëì€**ë ìì ë°ìŽí°ë„Œ ëȘšëžìŽ ìì©íë íììŒëĄ ëłíí©ëë€. [Tokenizer](main_classes/tokenizer)ë ê° ëȘšëžì ìŽí넌 ì ì„íêł , 돞ììŽì í í° ìëČ ë© ìžë±ì€ 늏ì€ížëĄ ìžìœë©íêł ëìœë©íêž° ìí ë©ìë넌 ì êł”í©ëë€. [Image processors](main_classes/image_processor)ë ëčì ì
ë „ì ì ìČ늏íêł , [feature extractors](main_classes/feature_extractor)ë ì€ëì€ ì
ë „ì ì ìČ늏íë©°, [processor](main_classes/processors)ë ë©í°ëȘšëŹ ì
ë „ì ìČ늏í©ëë€.
+
+ëȘšë ìŽëŹí íŽëì€ë ìŹì íë šë ìžì€íŽì€ìì ìžì€íŽì€ííêł ëĄì»ŹëĄ ì ì„íë©°, ìž ê°ì§ ë©ìë넌 ìŹì©íìŹ Hubìì êł”ì í ì ìì”ëë€:
+
+- `from_pretrained()` ë©ìë넌 ìŹì©í멎 ëŒìŽëžëŹëŠŹ ììČŽìì ì êł”íë ìŹì íë šë ëČì (ì§ìëë ëȘšëžì [Model Hub](https://huggingface.co/models)ìì ì°Ÿì ì ìì)ìŽë ìŹì©ìê° ëĄì»ŹëĄ ì ì„í êČœì°(ëë ìëČì ì ì„í êČœì°)ì ëȘšëž, ê”Źì± ë° ì ìČ늏 íŽëì€ë„Œ ìžì€íŽì€íí ì ìì”ëë€.
+- `save_pretrained()` ë©ìë넌 ìŹì©í멎 ëȘšëž, ê”Źì± ë° ì ìČ늏 íŽëì€ë„Œ ëĄì»ŹëĄ ì ì„íìŹ `from_pretrained()`넌 ìŹì©íìŹ ë€ì ê°ì žìŹ ì ìì”ëë€.
+- `push_to_hub()` ë©ìë넌 ìŹì©í멎 ëȘšëž, ê”Źì± ë° ì ìČ늏 íŽëì€ë„Œ Hubì êł”ì íìŹ ëȘšëìêČ ìœêČ ì ê·Œí ì ìì”ëë€.
+
diff --git a/docs/source/ko/pipeline_tutorial.md b/docs/source/ko/pipeline_tutorial.md
new file mode 100644
index 000000000000..4c32db756f0e
--- /dev/null
+++ b/docs/source/ko/pipeline_tutorial.md
@@ -0,0 +1,243 @@
+
+
+# ì¶ëĄ ì ìí Pipeline[[pipelines-for-inference]]
+
+[`pipeline`]ì ìŹì©í멎 ìžìŽ, 컎íší° ëčì , ì€ëì€ ë° ë©í°ëȘšëŹ íì€íŹì ëí ì¶ëĄ ì ìíŽ [Hub](https://huggingface.co/models)ì ìŽë€ ëȘšëžìŽë ìœêČ ìŹì©í ì ìì”ëë€. íčì ë¶ìŒì ëí êČœíìŽ ìê±°ë, ëȘšëžì ìŽëŁšë ìœëê° ì”ìíì§ ìì êČœì°ìë [`pipeline`]ì ìŹì©íŽì ì¶ëĄ í ì ììŽì! ìŽ íí 늏ìŒììë ë€ìì ë°°ì볎êČ ì”ëë€.
+
+* ì¶ëĄ ì ìíŽ [`pipeline`]ì ìŹì©íë ë°©ëČ
+* íčì í íŹëìŽì ëë ëȘšëžì ìŹì©íë ë°©ëČ
+* ìžìŽ, 컎íší° ëčì , ì€ëì€ ë° ë©í°ëȘšëŹ íì€íŹìì [`pipeline`]ì ìŹì©íë ë°©ëČ
+
+
+
+ì§ìíë ëȘšë íì€íŹì ìž ì ìë ë§€ê°ëłì넌 ëŽì ëȘ©ëĄì [`pipeline`] ì€ëȘ
ì넌 ì°žêł íŽìŁŒìžì.
+
+
+
+## Pipeline ìŹì©íêž°[[pipeline-usage]]
+
+ê° íì€íŹë§ë€ êł ì ì [`pipeline`]ìŽ ìì§ë§, ê°ëł íìŽíëŒìžì ëŽêł ìë ì¶ìíë [`pipeline`]넌 ìŹì©íë êČìŽ ìŒë°ì ìŒëĄ ë ê°ëší©ëë€. [`pipeline`]ì íì€íŹì ìë§êČ ì¶ëĄ ìŽ ê°ë„í êž°ëłž ëȘšëžêłŒ ì ìČ늏 íŽëì€ë„Œ ìëìŒëĄ ëĄëí©ëë€.
+
+1. 뚌ì [`pipeline`]ì ìì±íêł íì€íŹë„Œ ì§ì íìžì.
+
+```py
+>>> from transformers import pipeline
+
+>>> generator = pipeline(task="automatic-speech-recognition")
+```
+
+2. ê·žëŠŹêł [`pipeline`]ì ì
ë „ì ëŁìŽìŁŒìžì.
+
+```py
+>>> generator("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac")
+{'text': 'I HAVE A DREAM BUT ONE DAY THIS NATION WILL RISE UP LIVE UP THE TRUE MEANING OF ITS TREES'}
+```
+
+êž°ëíë êČ°êłŒê° ìëê°ì? Hubìì [ê°ì„ ë§ìŽ ë€ìŽëĄëë ìë ìì± ìžì ëȘšëž](https://huggingface.co/models?pipeline_tag=automatic-speech-recognition&sort=downloads)ëĄ ë ëì êČ°êłŒë„Œ ì»ì ì ìëì§ íìžíŽëłŽìžì.
+ë€ìì [openai/whisper-large](https://huggingface.co/openai/whisper-large)ëĄ ìëíŽëłŽêČ ì”ëë€.
+
+```py
+>>> generator = pipeline(model="openai/whisper-large")
+>>> generator("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac")
+{'text': ' I have a dream that one day this nation will rise up and live out the true meaning of its creed.'}
+```
+
+íšìŹ ë ëììĄê”°ì!
+Hubì ëȘšëžë€ì ìŹëŹ ë€ìí ìžìŽì ì 돞ë¶ìŒë„Œ ìì°ë„Žêž° ë돞ì êŒ ìì ì ìžìŽë ë¶ìŒì íčíë ëȘšëžì ì°Ÿì볎ìêž° ë°ëëë€.
+ëžëŒì°ì 넌 ëČìŽë íìììŽ Hubìì ì§ì ëȘšëžì ì¶ë „ì íìžíêł ë€ë„ž ëȘšëžêłŒ ëčê”íŽì ìì ì ìí©ì ë ì í©íì§, ì ë§€í ì
ë „ì ë ì ìČ늏íëì§ë íìží ì ìì”ëë€.
+ë§ìœ ìí©ì ìë§ë ëȘšëžì ìë€ë©Ž ìžì ë ì§ì [íë š](training)ìíŹ ì ìì”ëë€!
+
+ì
ë „ìŽ ìŹëŹ ê° ìë êČœì°, 늏ì€íž ííëĄ ì ëŹí ì ìì”ëë€.
+
+```py
+generator(
+ [
+ "https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac",
+ "https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/1.flac",
+ ]
+)
+```
+
+ì ìČŽ ë°ìŽí°ìžížì ìííê±°ë ìčìëČì ìŹë €ëìŽ ì¶ëĄ ì ìŹì©íêł ì¶ë€ë©Ž, ê° ììž íìŽì§ë„Œ ì°žìĄ°íìžì.
+
+[ë°ìŽí°ìžížìì Pipeline ìŹì©íêž°](#using-pipelines-on-a-dataset)
+
+[ìčìëČìì Pipeline ìŹì©íêž°](./pipeline_webserver)
+
+## ë§€ê°ëłì[[parameters]]
+
+[`pipeline`]ì ë§ì ë§€ê°ëłì넌 ì§ìí©ëë€. íčì íì€íŹì©ìž êČë ìêł , ëČì©ìž êČë ìì”ëë€.
+ìŒë°ì ìŒëĄ ìíë ììčì ìŽëë ë§€ê°ëłì넌 ëŁì ì ìì”ëë€.
+
+```py
+generator(model="openai/whisper-large", my_parameter=1)
+out = generate(...) # This will use `my_parameter=1`.
+out = generate(..., my_parameter=2) # This will override and use `my_parameter=2`.
+out = generate(...) # This will go back to using `my_parameter=1`.
+```
+
+ì€ìí 3ê°ì§ ë§€ê°ëłì넌 ìŽíŽëłŽêČ ì”ëë€.
+
+### êž°êž°(device)[[device]]
+
+`device=n`ìČëŒ êž°êž°ë„Œ ì§ì í멎 íìŽíëŒìžìŽ ìëìŒëĄ íŽëč êž°êž°ì ëȘšëžì ë°°ìčí©ëë€.
+íìŽí ìčììë í
ìíëĄì°ììë ëȘšë ìëí©ëë€.
+
+```py
+generator(model="openai/whisper-large", device=0)
+```
+
+ëȘšëžìŽ GPU íëì ëìê°êž° ëČêČë€ë©Ž, `device_map="auto"`넌 ì§ì íŽì đ€ [Accelerate](https://huggingface.co/docs/accelerate)ê° ëȘšëž ê°ì€ìč넌 ìŽë»êČ ëĄëíêł ì ì„í ì§ ìëìŒëĄ êȰì íëëĄ í ì ìì”ëë€.
+
+```py
+#!pip install accelerate
+generator(model="openai/whisper-large", device_map="auto")
+```
+
+### ë°°ìč ìŹìŽìŠ[[batch-size]]
+
+êž°ëłžì ìŒëĄ íìŽíëŒìžì [ìŹêž°](https://huggingface.co/docs/transformers/main_classes/pipelines#pipeline-batching)ì ëìš ìŽì ëĄ ì¶ëĄ ì ìŒêŽ ìČ늏íì§ ìì”ëë€. ê°ëší ì€ëȘ
íì멎 ìŒêŽ ìČëŠŹê° ë°ëì ë ëč ë„Žì§ ìêł ì€íë € ë ëë €ì§ ìë ìêž° ë돞ì
ëë€.
+
+íì§ë§ ìì ì ìí©ì ì í©íë€ë©Ž, ìŽë êČ ìŹì©íìžì.
+
+```py
+generator(model="openai/whisper-large", device=0, batch_size=2)
+audio_filenames = [f"audio_{i}.flac" for i in range(10)]
+texts = generator(audio_filenames)
+```
+
+íìŽíëŒìž ì ì êł”ë 10ê°ì ì€ëì€ íìŒì ì¶ê°ëĄ ìČ늏íë ìœë ììŽ (ìŒêŽ ìČ늏ì ëłŽë€ íšêłŒì ìž GPU ì) ëȘšëžì 2ê°ì© ì ëŹí©ëë€.
+ì¶ë „ì ìŒêŽ ìČ늏íì§ ììì ëì ëê°ììŒ í©ëë€. íìŽíëŒìžìì ìë넌 ë ëŒ ìë ìë ë°©ëČ ì€ íëìŒ ëżì
ëë€.
+
+íìŽíëŒìžì ìŒêŽ ìČ늏ì ëł”ìĄí ë¶ë¶ì ì€ìŹìŁŒêž°ë í©ëë€. (ì넌 ë€ìŽ êžŽ ì€ëì€ íìŒìČëŒ) ìŹëŹ ë¶ë¶ìŒëĄ ëë ìŒ ëȘšëžìŽ ìČ늏í ì ìë êČì [*chunk batching*](./main_classes/pipelines#pipeline-chunk-batching)ìŽëŒêł íëë°, íìŽíëŒìžì ìŹì©í멎 ìëìŒëĄ ëë ì€ëë€.
+
+### íčì íì€íŹì© ë§€ê°ëłì[[task-specific-parameters]]
+
+ê° íì€íŹë§ë€ ê”Źíí ë ì ì°ì±êłŒ ì”ì
ì ì êł”íêž° ìíŽ íì€íŹì© ë§€ê°ëłìê° ìì”ëë€.
+ì넌 ë€ìŽ [`transformers.AutomaticSpeechRecognitionPipeline.__call__`] ë©ìëìë ëììì ìë§ì ëŁì ë ì ì©í êČ ê°ì `return_timestamps` ë§€ê°ëłìê° ìì”ëë€.
+
+```py
+>>> # Not using whisper, as it cannot provide timestamps.
+>>> generator = pipeline(model="facebook/wav2vec2-large-960h-lv60-self", return_timestamps="word")
+>>> generator("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac")
+{'text': 'I HAVE A DREAM BUT ONE DAY THIS NATION WILL RISE UP AND LIVE OUT THE TRUE MEANING OF ITS CREED', 'chunks': [{'text': 'I', 'timestamp': (1.22, 1.24)}, {'text': 'HAVE', 'timestamp': (1.42, 1.58)}, {'text': 'A', 'timestamp': (1.66, 1.68)}, {'text': 'DREAM', 'timestamp': (1.76, 2.14)}, {'text': 'BUT', 'timestamp': (3.68, 3.8)}, {'text': 'ONE', 'timestamp': (3.94, 4.06)}, {'text': 'DAY', 'timestamp': (4.16, 4.3)}, {'text': 'THIS', 'timestamp': (6.36, 6.54)}, {'text': 'NATION', 'timestamp': (6.68, 7.1)}, {'text': 'WILL', 'timestamp': (7.32, 7.56)}, {'text': 'RISE', 'timestamp': (7.8, 8.26)}, {'text': 'UP', 'timestamp': (8.38, 8.48)}, {'text': 'AND', 'timestamp': (10.08, 10.18)}, {'text': 'LIVE', 'timestamp': (10.26, 10.48)}, {'text': 'OUT', 'timestamp': (10.58, 10.7)}, {'text': 'THE', 'timestamp': (10.82, 10.9)}, {'text': 'TRUE', 'timestamp': (10.98, 11.18)}, {'text': 'MEANING', 'timestamp': (11.26, 11.58)}, {'text': 'OF', 'timestamp': (11.66, 11.7)}, {'text': 'ITS', 'timestamp': (11.76, 11.88)}, {'text': 'CREED', 'timestamp': (12.0, 12.38)}]}
+```
+
+볎ìë€ìíŒ ëȘšëžìŽ í
ì€ížë„Œ ì¶ëĄ í ëżë§ ìëëŒ ê° ëšìŽë„Œ ë§í ìì êčì§ë ì¶ë „íì”ëë€.
+
+íì€íŹë§ë€ ë€ìí ë§€ê°ëłì넌 ê°ì§êł ìëë°ì. ìíë íì€íŹì API넌 ì°žìĄ°íŽì ë°êżëłŒ ì ìë ìŹëŹ ë§€ê°ëłì넌 ìŽíŽëłŽìžì!
+ì§êžêčì§ ë€ë€ëłž [`~transformers.AutomaticSpeechRecognitionPipeline`]ìë `chunk_length_s` ë§€ê°ëłìê° ìì”ëë€. ìíë 1ìê° ë¶ëì ëììì ìë§ ìì
ì í ëìČëŒ, ìŒë°ì ìŒëĄ ëȘšëžìŽ ììČŽì ìŒëĄ ìČ늏í ì ìë ë§€ì° êžŽ ì€ëì€ íìŒì ìČ늏í ë ì ì©íìŁ .
+
+
+ëììŽ ë ë§í ë§€ê°ëłì넌 ì°Ÿì§ ëȘ»íë€ë©Ž ìžì ë ì§ [ììČ](https://github.com/huggingface/transformers/issues/new?assignees=&labels=feature&template=feature-request.yml)íŽìŁŒìžì!
+
+
+## ë°ìŽí°ìžížìì Pipeline ìŹì©íêž°[[using-pipelines-on-a-dataset]]
+
+íìŽíëŒìžì ëê·ëȘš ë°ìŽí°ìžížììë ì¶ëĄ ìì
ì í ì ìì”ëë€. ìŽë ìŽí°ë ìŽí°ë„Œ ìŹì©íë 걞 ì¶ìČë늜ëë€.
+
+```py
+def data():
+ for i in range(1000):
+ yield f"My example {i}"
+
+
+pipe = pipe(model="gpt2", device=0)
+generated_characters = 0
+for out in pipe(data()):
+ generated_characters += len(out["generated_text"])
+```
+
+ìŽí°ë ìŽí° `data()`ë ê° êČ°êłŒë„Œ ížì¶ë§ë€ ìì±íêł , íìŽíëŒìžì ì
ë „ìŽ ìíí ì ìë ìëŁê”ŹìĄ°ìì ìëìŒëĄ ìžìíìŹ GPUìì êž°ìĄŽ ë°ìŽí°ê° ìČ늏ëë ëì ìëĄìŽ ë°ìŽí°ë„Œ ê°ì žì€êž° ììí©ëë€.(ìŽë ëŽë¶ì ìŒëĄ [DataLoader](https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader)넌 ìŹì©íŽì.) ìŽ êłŒì ì ì ìČŽ ë°ìŽí°ìžížë„Œ ë©ëȘšëŠŹì ì ìŹíì§ ìêł ë GPUì ì”ëí ëč 넎êČ ìëĄìŽ ìì
ì êł”êží ì ìêž° ë돞ì ì€ìí©ëë€.
+
+ê·žëŠŹêł ìŒêŽ ìČëŠŹê° ë ëč 넌 ì ìêž° ë돞ì, `batch_size` ë§€ê°ëłì넌 ìĄ°ì íŽëŽë ìąìì.
+
+ë°ìŽí°ìžížë„Œ ìííë ê°ì„ ê°ëší ë°©ëČì đ€ [Datasets](https://github.com/huggingface/datasets/)넌 íì©íë êČìžë°ì.
+
+```py
+# KeyDataset is a util that will just output the item we're interested in.
+from transformers.pipelines.pt_utils import KeyDataset
+
+pipe = pipeline(model="hf-internal-testing/tiny-random-wav2vec2", device=0)
+dataset = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation[:10]")
+
+for out in pipe(KeyDataset(dataset["audio"])):
+ print(out)
+```
+
+
+## ìčìëČìì Pipeline ìŹì©íêž°[[using-pipelines-for-a-webserver]]
+
+
+ì¶ëĄ ìì§ì ë§ëë êłŒì ì ë°ëĄ íìŽì§ë„Œ ìì±í ë§í ëł”ìĄí ìŁŒì ì
ëë€.
+
+
+[Link](./pipeline_webserver)
+
+## ëčì Pipeline[[vision-pipeline]]
+
+ëčì íì€íŹë„Œ ìíŽ [`pipeline`]ì ìŹì©íë ìŒì ê±°ì ëìŒí©ëë€.
+
+íì€íŹë„Œ ì§ì íêł ìŽëŻžì§ë„Œ ë¶ë„êž°ì ì ëŹí멎 ë©ëë€. ìŽëŻžì§ë ìží°ë· ë§íŹ ëë ëĄì»Ź êČœëĄì ííëĄ ì ëŹíŽìŁŒìžì. ì넌 ë€ìŽ ìëì íìë êł ììŽë ìŽë€ ìą
ìžê°ì?
+
+
+
+```py
+>>> from transformers import pipeline
+
+>>> vision_classifier = pipeline(model="google/vit-base-patch16-224")
+>>> preds = vision_classifier(
+... images="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
+... )
+>>> preds = [{"score": round(pred["score"], 4), "label": pred["label"]} for pred in preds]
+>>> preds
+[{'score': 0.4335, 'label': 'lynx, catamount'}, {'score': 0.0348, 'label': 'cougar, puma, catamount, mountain lion, painter, panther, Felis concolor'}, {'score': 0.0324, 'label': 'snow leopard, ounce, Panthera uncia'}, {'score': 0.0239, 'label': 'Egyptian cat'}, {'score': 0.0229, 'label': 'tiger cat'}]
+```
+
+### í
ì€íž Pipeline[[text-pipeline]]
+
+NLP íì€íŹë„Œ ìíŽ [`pipeline`]ì ìŹì©íë ìŒë ê±°ì ëìŒí©ëë€.
+
+```py
+>>> from transformers import pipeline
+
+>>> # This model is a `zero-shot-classification` model.
+>>> # It will classify text, except you are free to choose any label you might imagine
+>>> classifier = pipeline(model="facebook/bart-large-mnli")
+>>> classifier(
+... "I have a problem with my iphone that needs to be resolved asap!!",
+... candidate_labels=["urgent", "not urgent", "phone", "tablet", "computer"],
+... )
+{'sequence': 'I have a problem with my iphone that needs to be resolved asap!!', 'labels': ['urgent', 'phone', 'computer', 'not urgent', 'tablet'], 'scores': [0.504, 0.479, 0.013, 0.003, 0.002]}
+```
+
+### ë©í°ëȘšëŹ Pipeline[[multimodal-pipeline]]
+
+[`pipeline`]ì ìŹëŹ ëȘšëŹëŠŹí°(ììŁŒ: ì€ëì€, ëčëì€, í
ì€ížì ê°ì ë°ìŽí° íí)넌 ì§ìí©ëë€. ììëĄ ìê°ì ì§ììë”(VQA; Visual Question Answering) íì€íŹë í
ì€ížì ìŽëŻžì§ë„Œ ëȘšë ìŹì©í©ëë€. ê·ž ìŽë€ ìŽëŻžì§ ë§íŹë ëŹ»êł ì¶ì ì§ëŹžë ìì ëĄêČ ì ëŹí ì ìì”ëë€. ìŽëŻžì§ë URL ëë ëĄì»Ź êČœëĄì ííëĄ ì ëŹíŽìŁŒìžì.
+
+ì넌 ë€ìŽ ìŽ [ê±°ëëȘ
ìžì ìŹì§](https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png)ìì ê±°ëëȘ
ìžì ëČížë„Œ ëŹ»êł ì¶ë€ë©Ž,
+
+```py
+>>> from transformers import pipeline
+
+>>> vqa = pipeline(model="impira/layoutlm-document-qa")
+>>> vqa(
+... image="https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png",
+... question="What is the invoice number?",
+... )
+[{'score': 0.42514941096305847, 'answer': 'us-001', 'start': 16, 'end': 16}]
+```
diff --git a/docs/source/ko/pipeline_tutorial.mdx b/docs/source/ko/pipeline_tutorial.mdx
deleted file mode 100644
index 769122d3a0ec..000000000000
--- a/docs/source/ko/pipeline_tutorial.mdx
+++ /dev/null
@@ -1,239 +0,0 @@
-
-
-# ì¶ëĄ ì ìí Pipeline[[pipelines-for-inference]]
-
-[`pipeline`]ì ìŹì©í멎 ìžìŽ, 컎íší° ëčì , ì€ëì€ ë° ë©í°ëȘšëŹ íì€íŹì ëí ì¶ëĄ ì ìíŽ [Hub](https://huggingface.co/models)ì ìŽë€ ëȘšëžìŽë ìœêČ ìŹì©í ì ìì”ëë€. íčì ë¶ìŒì ëí êČœíìŽ ìê±°ë, ëȘšëžì ìŽëŁšë ìœëê° ì”ìíì§ ìì êČœì°ìë [`pipeline`]ì ìŹì©íŽì ì¶ëĄ í ì ììŽì! ìŽ íí 늏ìŒììë ë€ìì ë°°ì볎êČ ì”ëë€.
-
-* ì¶ëĄ ì ìíŽ [`pipeline`]ì ìŹì©íë ë°©ëČ
-* íčì í íŹëìŽì ëë ëȘšëžì ìŹì©íë ë°©ëČ
-* ìžìŽ, 컎íší° ëčì , ì€ëì€ ë° ë©í°ëȘšëŹ íì€íŹìì [`pipeline`]ì ìŹì©íë ë°©ëČ
-
-
-
-ì§ìíë ëȘšë íì€íŹì ìž ì ìë ë§€ê°ëłì넌 ëŽì ëȘ©ëĄì [`pipeline`] ì€ëȘ
ì넌 ì°žêł íŽìŁŒìžì.
-
-
-
-## Pipeline ìŹì©íêž°[[pipeline-usage]]
-
-ê° íì€íŹë§ë€ êł ì ì [`pipeline`]ìŽ ìì§ë§, ê°ëł íìŽíëŒìžì ëŽêł ìë ì¶ìíë [`pipeline`]넌 ìŹì©íë êČìŽ ìŒë°ì ìŒëĄ ë ê°ëší©ëë€. [`pipeline`]ì íì€íŹì ìë§êČ ì¶ëĄ ìŽ ê°ë„í êž°ëłž ëȘšëžêłŒ ì ìČ늏 íŽëì€ë„Œ ìëìŒëĄ ëĄëí©ëë€.
-
-1. 뚌ì [`pipeline`]ì ìì±íêł íì€íŹë„Œ ì§ì íìžì.
-
-```py
->>> from transformers import pipeline
-
->>> generator = pipeline(task="automatic-speech-recognition")
-```
-
-2. ê·žëŠŹêł [`pipeline`]ì ì
ë „ì ëŁìŽìŁŒìžì.
-
-```py
->>> generator("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac")
-{'text': 'I HAVE A DREAM BUT ONE DAY THIS NATION WILL RISE UP LIVE UP THE TRUE MEANING OF ITS TREES'}
-```
-
-êž°ëíë êČ°êłŒê° ìëê°ì? Hubìì [ê°ì„ ë§ìŽ ë€ìŽëĄëë ìë ìì± ìžì ëȘšëž](https://huggingface.co/models?pipeline_tag=automatic-speech-recognition&sort=downloads)ëĄ ë ëì êČ°êłŒë„Œ ì»ì ì ìëì§ íìžíŽëłŽìžì.
-ë€ìì [openai/whisper-large](https://huggingface.co/openai/whisper-large)ëĄ ìëíŽëłŽêČ ì”ëë€.
-
-```py
->>> generator = pipeline(model="openai/whisper-large")
->>> generator("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac")
-{'text': ' I have a dream that one day this nation will rise up and live out the true meaning of its creed.'}
-```
-
-íšìŹ ë ëììĄê”°ì!
-Hubì ëȘšëžë€ì ìŹëŹ ë€ìí ìžìŽì ì 돞ë¶ìŒë„Œ ìì°ë„Žêž° ë돞ì êŒ ìì ì ìžìŽë ë¶ìŒì íčíë ëȘšëžì ì°Ÿì볎ìêž° ë°ëëë€.
-ëžëŒì°ì 넌 ëČìŽë íìììŽ Hubìì ì§ì ëȘšëžì ì¶ë „ì íìžíêł ë€ë„ž ëȘšëžêłŒ ëčê”íŽì ìì ì ìí©ì ë ì í©íì§, ì ë§€í ì
ë „ì ë ì ìČ늏íëì§ë íìží ì ìì”ëë€.
-ë§ìœ ìí©ì ìë§ë ëȘšëžì ìë€ë©Ž ìžì ë ì§ì [íë š](training)ìíŹ ì ìì”ëë€!
-
-ì
ë „ìŽ ìŹëŹ ê° ìë êČœì°, 늏ì€íž ííëĄ ì ëŹí ì ìì”ëë€.
-
-```py
-generator(
- [
- "https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac",
- "https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/1.flac",
- ]
-)
-```
-
-ì ìČŽ ë°ìŽí°ìžížì ìííê±°ë ìčìëČì ìŹë €ëìŽ ì¶ëĄ ì ìŹì©íêł ì¶ë€ë©Ž, ê° ììž íìŽì§ë„Œ ì°žìĄ°íìžì.
-
-[ë°ìŽí°ìžížìì Pipeline ìŹì©íêž°](#using-pipelines-on-a-dataset)
-
-[ìčìëČìì Pipeline ìŹì©íêž°](./pipeline_webserver)
-
-## ë§€ê°ëłì[[parameters]]
-
-[`pipeline`]ì ë§ì ë§€ê°ëłì넌 ì§ìí©ëë€. íčì íì€íŹì©ìž êČë ìêł , ëČì©ìž êČë ìì”ëë€.
-ìŒë°ì ìŒëĄ ìíë ììčì ìŽëë ë§€ê°ëłì넌 ëŁì ì ìì”ëë€.
-
-```py
-generator(model="openai/whisper-large", my_parameter=1)
-out = generate(...) # This will use `my_parameter=1`.
-out = generate(..., my_parameter=2) # This will override and use `my_parameter=2`.
-out = generate(...) # This will go back to using `my_parameter=1`.
-```
-
-ì€ìí 3ê°ì§ ë§€ê°ëłì넌 ìŽíŽëłŽêČ ì”ëë€.
-
-### êž°êž°(device)[[device]]
-
-`device=n`ìČëŒ êž°êž°ë„Œ ì§ì í멎 íìŽíëŒìžìŽ ìëìŒëĄ íŽëč êž°êž°ì ëȘšëžì ë°°ìčí©ëë€.
-íìŽí ìčììë í
ìíëĄì°ììë ëȘšë ìëí©ëë€.
-
-```py
-generator(model="openai/whisper-large", device=0)
-```
-
-ëȘšëžìŽ GPU íëì ëìê°êž° ëČêČë€ë©Ž, `device_map="auto"`넌 ì§ì íŽì đ€ [Accelerate](https://huggingface.co/docs/accelerate)ê° ëȘšëž ê°ì€ìč넌 ìŽë»êČ ëĄëíêł ì ì„í ì§ ìëìŒëĄ êȰì íëëĄ í ì ìì”ëë€.
-
-```py
-#!pip install accelerate
-generator(model="openai/whisper-large", device_map="auto")
-```
-
-### ë°°ìč ìŹìŽìŠ[[batch-size]]
-
-êž°ëłžì ìŒëĄ íìŽíëŒìžì [ìŹêž°](https://huggingface.co/docs/transformers/main_classes/pipelines#pipeline-batching)ì ëìš ìŽì ëĄ ì¶ëĄ ì ìŒêŽ ìČ늏íì§ ìì”ëë€. ê°ëší ì€ëȘ
íì멎 ìŒêŽ ìČëŠŹê° ë°ëì ë ëč ë„Žì§ ìêł ì€íë € ë ëë €ì§ ìë ìêž° ë돞ì
ëë€.
-
-íì§ë§ ìì ì ìí©ì ì í©íë€ë©Ž, ìŽë êČ ìŹì©íìžì.
-
-```py
-generator(model="openai/whisper-large", device=0, batch_size=2)
-audio_filenames = [f"audio_{i}.flac" for i in range(10)]
-texts = generator(audio_filenames)
-```
-
-íìŽíëŒìž ì ì êł”ë 10ê°ì ì€ëì€ íìŒì ì¶ê°ëĄ ìČ늏íë ìœë ììŽ (ìŒêŽ ìČ늏ì ëłŽë€ íšêłŒì ìž GPU ì) ëȘšëžì 2ê°ì© ì ëŹí©ëë€.
-ì¶ë „ì ìŒêŽ ìČ늏íì§ ììì ëì ëê°ììŒ í©ëë€. íìŽíëŒìžìì ìë넌 ë ëŒ ìë ìë ë°©ëČ ì€ íëìŒ ëżì
ëë€.
-
-íìŽíëŒìžì ìŒêŽ ìČ늏ì ëł”ìĄí ë¶ë¶ì ì€ìŹìŁŒêž°ë í©ëë€. (ì넌 ë€ìŽ êžŽ ì€ëì€ íìŒìČëŒ) ìŹëŹ ë¶ë¶ìŒëĄ ëë ìŒ ëȘšëžìŽ ìČ늏í ì ìë êČì [*chunk batching*](./main_classes/pipelines#pipeline-chunk-batching)ìŽëŒêł íëë°, íìŽíëŒìžì ìŹì©í멎 ìëìŒëĄ ëë ì€ëë€.
-
-### íčì íì€íŹì© ë§€ê°ëłì[[task-specific-parameters]]
-
-ê° íì€íŹë§ë€ ê”Źíí ë ì ì°ì±êłŒ ì”ì
ì ì êł”íêž° ìíŽ íì€íŹì© ë§€ê°ëłìê° ìì”ëë€.
-ì넌 ë€ìŽ [`transformers.AutomaticSpeechRecognitionPipeline.__call__`] ë©ìëìë ëììì ìë§ì ëŁì ë ì ì©í êČ ê°ì `return_timestamps` ë§€ê°ëłìê° ìì”ëë€.
-
-```py
->>> # Not using whisper, as it cannot provide timestamps.
->>> generator = pipeline(model="facebook/wav2vec2-large-960h-lv60-self", return_timestamps="word")
->>> generator("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac")
-{'text': 'I HAVE A DREAM BUT ONE DAY THIS NATION WILL RISE UP AND LIVE OUT THE TRUE MEANING OF ITS CREED', 'chunks': [{'text': 'I', 'timestamp': (1.22, 1.24)}, {'text': 'HAVE', 'timestamp': (1.42, 1.58)}, {'text': 'A', 'timestamp': (1.66, 1.68)}, {'text': 'DREAM', 'timestamp': (1.76, 2.14)}, {'text': 'BUT', 'timestamp': (3.68, 3.8)}, {'text': 'ONE', 'timestamp': (3.94, 4.06)}, {'text': 'DAY', 'timestamp': (4.16, 4.3)}, {'text': 'THIS', 'timestamp': (6.36, 6.54)}, {'text': 'NATION', 'timestamp': (6.68, 7.1)}, {'text': 'WILL', 'timestamp': (7.32, 7.56)}, {'text': 'RISE', 'timestamp': (7.8, 8.26)}, {'text': 'UP', 'timestamp': (8.38, 8.48)}, {'text': 'AND', 'timestamp': (10.08, 10.18)}, {'text': 'LIVE', 'timestamp': (10.26, 10.48)}, {'text': 'OUT', 'timestamp': (10.58, 10.7)}, {'text': 'THE', 'timestamp': (10.82, 10.9)}, {'text': 'TRUE', 'timestamp': (10.98, 11.18)}, {'text': 'MEANING', 'timestamp': (11.26, 11.58)}, {'text': 'OF', 'timestamp': (11.66, 11.7)}, {'text': 'ITS', 'timestamp': (11.76, 11.88)}, {'text': 'CREED', 'timestamp': (12.0, 12.38)}]}
-```
-
-볎ìë€ìíŒ ëȘšëžìŽ í
ì€ížë„Œ ì¶ëĄ í ëżë§ ìëëŒ ê° ëšìŽë„Œ ë§í ìì êčì§ë ì¶ë „íì”ëë€.
-
-íì€íŹë§ë€ ë€ìí ë§€ê°ëłì넌 ê°ì§êł ìëë°ì. ìíë íì€íŹì API넌 ì°žìĄ°íŽì ë°êżëłŒ ì ìë ìŹëŹ ë§€ê°ëłì넌 ìŽíŽëłŽìžì!
-ì§êžêčì§ ë€ë€ëłž [`~transformers.AutomaticSpeechRecognitionPipeline`]ìë `chunk_length_s` ë§€ê°ëłìê° ìì”ëë€. ìíë 1ìê° ë¶ëì ëììì ìë§ ìì
ì í ëìČëŒ, ìŒë°ì ìŒëĄ ëȘšëžìŽ ììČŽì ìŒëĄ ìČ늏í ì ìë ë§€ì° êžŽ ì€ëì€ íìŒì ìČ늏í ë ì ì©íìŁ .
-
-
-ëììŽ ë ë§í ë§€ê°ëłì넌 ì°Ÿì§ ëȘ»íë€ë©Ž ìžì ë ì§ [ììČ](https://github.com/huggingface/transformers/issues/new?assignees=&labels=feature&template=feature-request.yml)íŽìŁŒìžì!
-
-
-## ë°ìŽí°ìžížìì Pipeline ìŹì©íêž°[[using-pipelines-on-a-dataset]]
-
-íìŽíëŒìžì ëê·ëȘš ë°ìŽí°ìžížììë ì¶ëĄ ìì
ì í ì ìì”ëë€. ìŽë ìŽí°ë ìŽí°ë„Œ ìŹì©íë 걞 ì¶ìČë늜ëë€.
-
-```py
-def data():
- for i in range(1000):
- yield f"My example {i}"
-
-
-pipe = pipe(model="gpt2", device=0)
-generated_characters = 0
-for out in pipe(data()):
- generated_characters += len(out["generated_text"])
-```
-
-ìŽí°ë ìŽí° `data()`ë ê° êČ°êłŒë„Œ ížì¶ë§ë€ ìì±íêł , íìŽíëŒìžì ì
ë „ìŽ ìíí ì ìë ìëŁê”ŹìĄ°ìì ìëìŒëĄ ìžìíìŹ GPUìì êž°ìĄŽ ë°ìŽí°ê° ìČ늏ëë ëì ìëĄìŽ ë°ìŽí°ë„Œ ê°ì žì€êž° ììí©ëë€.(ìŽë ëŽë¶ì ìŒëĄ [DataLoader](https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader)넌 ìŹì©íŽì.) ìŽ êłŒì ì ì ìČŽ ë°ìŽí°ìžížë„Œ ë©ëȘšëŠŹì ì ìŹíì§ ìêł ë GPUì ì”ëí ëč 넎êČ ìëĄìŽ ìì
ì êł”êží ì ìêž° ë돞ì ì€ìí©ëë€.
-
-ê·žëŠŹêł ìŒêŽ ìČëŠŹê° ë ëč 넌 ì ìêž° ë돞ì, `batch_size` ë§€ê°ëłì넌 ìĄ°ì íŽëŽë ìąìì.
-
-ë°ìŽí°ìžížë„Œ ìííë ê°ì„ ê°ëší ë°©ëČì đ€ [Datasets](https://github.com/huggingface/datasets/)넌 íì©íë êČìžë°ì.
-
-```py
-# KeyDataset is a util that will just output the item we're interested in.
-from transformers.pipelines.pt_utils import KeyDataset
-
-pipe = pipeline(model="hf-internal-testing/tiny-random-wav2vec2", device=0)
-dataset = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation[:10]")
-
-for out in pipe(KeyDataset(dataset["audio"])):
- print(out)
-```
-
-
-## ìčìëČìì Pipeline ìŹì©íêž°[[using-pipelines-for-a-webserver]]
-
-
-ì¶ëĄ ìì§ì ë§ëë êłŒì ì ë°ëĄ íìŽì§ë„Œ ìì±í ë§í ëł”ìĄí ìŁŒì ì
ëë€.
-
-
-[Link](./pipeline_webserver)
-
-## ëčì Pipeline[[vision-pipeline]]
-
-ëčì íì€íŹë„Œ ìíŽ [`pipeline`]ì ìŹì©íë ìŒì ê±°ì ëìŒí©ëë€.
-
-íì€íŹë„Œ ì§ì íêł ìŽëŻžì§ë„Œ ë¶ë„êž°ì ì ëŹí멎 ë©ëë€. ìŽëŻžì§ë ìží°ë· ë§íŹ ëë ëĄì»Ź êČœëĄì ííëĄ ì ëŹíŽìŁŒìžì. ì넌 ë€ìŽ ìëì íìë êł ììŽë ìŽë€ ìą
ìžê°ì?
-
-
-
-```py
->>> from transformers import pipeline
-
->>> vision_classifier = pipeline(model="google/vit-base-patch16-224")
->>> preds = vision_classifier(
-... images="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
-... )
->>> preds = [{"score": round(pred["score"], 4), "label": pred["label"]} for pred in preds]
->>> preds
-[{'score': 0.4335, 'label': 'lynx, catamount'}, {'score': 0.0348, 'label': 'cougar, puma, catamount, mountain lion, painter, panther, Felis concolor'}, {'score': 0.0324, 'label': 'snow leopard, ounce, Panthera uncia'}, {'score': 0.0239, 'label': 'Egyptian cat'}, {'score': 0.0229, 'label': 'tiger cat'}]
-```
-
-### í
ì€íž Pipeline[[text-pipeline]]
-
-NLP íì€íŹë„Œ ìíŽ [`pipeline`]ì ìŹì©íë ìŒë ê±°ì ëìŒí©ëë€.
-
-```py
->>> from transformers import pipeline
-
->>> # This model is a `zero-shot-classification` model.
->>> # It will classify text, except you are free to choose any label you might imagine
->>> classifier = pipeline(model="facebook/bart-large-mnli")
->>> classifier(
-... "I have a problem with my iphone that needs to be resolved asap!!",
-... candidate_labels=["urgent", "not urgent", "phone", "tablet", "computer"],
-... )
-{'sequence': 'I have a problem with my iphone that needs to be resolved asap!!', 'labels': ['urgent', 'phone', 'computer', 'not urgent', 'tablet'], 'scores': [0.504, 0.479, 0.013, 0.003, 0.002]}
-```
-
-### ë©í°ëȘšëŹ Pipeline[[multimodal-pipeline]]
-
-[`pipeline`]ì ìŹëŹ ëȘšëŹëŠŹí°(ììŁŒ: ì€ëì€, ëčëì€, í
ì€ížì ê°ì ë°ìŽí° íí)넌 ì§ìí©ëë€. ììëĄ ìê°ì ì§ììë”(VQA; Visual Question Answering) íì€íŹë í
ì€ížì ìŽëŻžì§ë„Œ ëȘšë ìŹì©í©ëë€. ê·ž ìŽë€ ìŽëŻžì§ ë§íŹë ëŹ»êł ì¶ì ì§ëŹžë ìì ëĄêČ ì ëŹí ì ìì”ëë€. ìŽëŻžì§ë URL ëë ëĄì»Ź êČœëĄì ííëĄ ì ëŹíŽìŁŒìžì.
-
-ì넌 ë€ìŽ ìŽ [ê±°ëëȘ
ìžì ìŹì§](https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png)ìì ê±°ëëȘ
ìžì ëČížë„Œ ëŹ»êł ì¶ë€ë©Ž,
-
-```py
->>> from transformers import pipeline
-
->>> vqa = pipeline(model="impira/layoutlm-document-qa")
->>> vqa(
-... image="https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png",
-... question="What is the invoice number?",
-... )
-[{'score': 0.42514941096305847, 'answer': 'us-001', 'start': 16, 'end': 16}]
-```
diff --git a/docs/source/ko/pipeline_webserver.md b/docs/source/ko/pipeline_webserver.md
new file mode 100644
index 000000000000..5e423d1a7c4b
--- /dev/null
+++ b/docs/source/ko/pipeline_webserver.md
@@ -0,0 +1,143 @@
+
+
+# ìč ìëČ넌 ìí íìŽíëŒìž ìŹì©íêž°[[using_pipelines_for_a_webserver]]
+
+
+ì¶ëĄ ìì§ì ë§ëë êČì ëł”ìĄí ìŁŒì ìŽë©°, "ì”ì ì" ì룚ì
ì 돞ì êł”ê°ì ë°ëŒ ëŹëŒì§ ê°ë„ì±ìŽ ëì”ëë€. CPU ëë GPU넌 ìŹì©íëì§ì ë°ëŒ ë€ë„Žêł ëźì ì§ì° ìê°ì ìíëì§, ëì ìČ늏ëì ìíëì§, ë€ìí ëȘšëžì ì§ìí ì ìêžž ìíëì§, íëì íčì ëȘšëžì êł ëëĄ ì”ì ííêžž ìíëì§ ë±ì ë°ëŒ ëŹëŒì§ëë€. ìŽ ìŁŒì 넌 íŽêȰíë ë°©ëČìë ìŹëŹ ê°ì§ê° ììŒëŻëĄ, ìŽ ì„ìì ì ìíë êČì ìČì ìëíŽ ëłŽêž°ì ìąì ì¶ë°ì ìŒ ìë ìì§ë§, ìŽ ì„ì ìœë ìŹëŹë¶ìŽ íìëĄ íë ì”ì ì ì룚ì
ì ìë ì ìì”ëë€.
+
+
+í”ìŹì ìŒëĄ ìŽíŽíŽìŒ í ì ì [dataset](pipeline_tutorial#using-pipelines-on-a-dataset)넌 ë€ëٰ ëì ë§ì°Źê°ì§ëĄ ë°ëł”ì넌 ìŹì© ê°ë„íë€ë êČì
ëë€. ìëí멎, ìč ìëČë êž°ëłžì ìŒëĄ ììČì êž°ë€ëŠŹêł ë€ìŽì€ë ëëĄ ìČ늏íë ìì€í
ìŽêž° ë돞ì
ëë€.
+
+ëłŽí” ìč ìëČë ë€ìí ììČì ëìì ë€ëŁšêž° ìíŽ ë§€ì° ë€ì€íë ê”ŹìĄ°(ë©í° ì€ë ë©, ëčëêž° ë±)넌 ì§ëêł ìì”ëë€. ë°ë©Žì, íìŽíëŒìž(ëë¶ë¶ íìŽíëŒìž ìì ìë ëȘšëž)ì ëłë ŹìČ늏ì ê·žë€ì§ ìąì§ ìì”ëë€. ìëí멎 íìŽíëŒìžì ë§ì RAMì ì°šì§íêž° ë돞ì
ëë€. ë°ëŒì, íìŽíëŒìžìŽ ì€í ì€ìŽê±°ë êłì° ì§ìœì ìž ìì
ì€ìŒ ë ëȘšë ìŹì© ê°ë„í 늏ìì€ë„Œ ì êł”íë êČìŽ ê°ì„ ìąì”ëë€.
+
+ìŽ ëŹžì 넌 ì°ëŠŹë ìč ìëČê° ììČì ë°êł 볎ëŽë ê°ëČŒìŽ ë¶í넌 ìČ늏íêł , ì€ì ìì
ì ìČ늏íë ëšìŒ ì€ë ë넌 ê°ë ë°©ëČìŒëĄ íŽêȰí êČì
ëë€. ìŽ ìì ë `starlette` ëŒìŽëžëŹëŠŹë„Œ ìŹì©í©ëë€.
+ì€ì íë ììíŹë ì€ìíì§ ìì§ë§, ë€ë„ž íë ììíŹë„Œ ìŹì©íë êČœì° ëìŒí íšêłŒë„Œ ëłŽêž° ìíŽì ìœë넌 ìĄ°ì íê±°ë ëłêČœíŽìŒ í ì ìì”ëë€.
+
+`server.py`넌 ìì±íìžì:
+
+```py
+from starlette.applications import Starlette
+from starlette.responses import JSONResponse
+from starlette.routing import Route
+from transformers import pipeline
+import asyncio
+
+
+async def homepage(request):
+ payload = await request.body()
+ string = payload.decode("utf-8")
+ response_q = asyncio.Queue()
+ await request.app.model_queue.put((string, response_q))
+ output = await response_q.get()
+ return JSONResponse(output)
+
+
+async def server_loop(q):
+ pipe = pipeline(model="bert-base-uncased")
+ while True:
+ (string, response_q) = await q.get()
+ out = pipe(string)
+ await response_q.put(out)
+
+
+app = Starlette(
+ routes=[
+ Route("/", homepage, methods=["POST"]),
+ ],
+)
+
+
+@app.on_event("startup")
+async def startup_event():
+ q = asyncio.Queue()
+ app.model_queue = q
+ asyncio.create_task(server_loop(q))
+```
+
+ìŽì ë€ì ëȘ
ë čìŽëĄ ì€íìíŹ ì ìì”ëë€:
+
+```bash
+uvicorn server:app
+```
+
+ìŽì ìżŒëŠŹë„Œ ë ë €ëłŒ ì ìì”ëë€:
+
+```bash
+curl -X POST -d "test [MASK]" http://localhost:8000/
+#[{"score":0.7742936015129089,"token":1012,"token_str":".","sequence":"test."},...]
+```
+
+ì, ìŽì ìč ìëČ넌 ë§ëë ë°©ëČì ëí ìąì ê°ë
ì ìêČ ëìì”ëë€!
+
+ì€ìí ì ì ëȘšëžì **í ëČë§** ê°ì žìšë€ë êČì
ëë€. ë°ëŒì ìč ìëČìë ëȘšëžì ìŹëłžìŽ ìì”ëë€. ìŽë° ë°©ìì ë¶íìí RAMìŽ ìŹì©ëì§ ìì”ëë€. ê·žë° ë€ì í ë©ì»€ëìŠì ìŹì©í멎, ë€ìêłŒ ê°ì
+ëì ë°°ìč넌 ìŹì©íêž° ìíŽ ì¶ëĄ ì ëšêłì ëȘ ê°ì íëȘ©ì ì¶ì íë êČêłŒ ê°ì ë©ì§ ìì
ì í ì ìì”ëë€:
+
+```py
+(string, rq) = await q.get()
+strings = []
+queues = []
+while True:
+ try:
+ (string, rq) = await asyncio.wait_for(q.get(), timeout=0.001) # 1ms
+ except asyncio.exceptions.TimeoutError:
+ break
+ strings.append(string)
+ queues.append(rq)
+strings
+outs = pipe(strings, batch_size=len(strings))
+for rq, out in zip(queues, outs):
+ await rq.put(out)
+```
+
+
+ìì ìœë넌 ìëìí€êž° ì ì ëčì ì ìì€í
ìììŽ ì¶©ë¶íì§ íìžíìžì!
+
+
+ì ìë ìœëë ê°ë
ì±ì ìíŽ ì”ì íëììŒë©°, ì”ìì ìœëë ìëëë€.
+ìČ«ì§ž, ë°°ìč íŹêž° ì íìŽ ììŒë©° ìŽë ìŒë°ì ìŒëĄ ìąì ë°©ììŽ ìëëë€.
+ëì§ž, ëȘšë í ê°ì žì€êž°ìì íììììŽ ìŹì€ì ëëŻëĄ ì¶ëĄ ì ì€ííêž° ì ì 1msëłŽë€ íšìŹ ì€ë êž°ë€ëŠŽ ì ìì”ëë€(ìČ« ëČì§ž ììČì ê·žë§íŒ ì§ì°ìíŽ).
+
+ëšìŒ 1ms êžžìŽì ë°ëëŒìžì ëë ížìŽ ë ìąì”ëë€.
+
+ìŽ ë°©ìì ìŹì©í멎 íê° ëčìŽ ììŽë íì 1ms넌 êž°ë€ëŠŹêČ ë êČì
ëë€.
+íì ì돎êČë ìì ë ì¶ëĄ ì ìíë êČœì°ìë ì”ì ì ë°©ëČìŽ ìë ì ìì”ëë€.
+íì§ë§ ë°°ìč ìì
ìŽ ìŹì©ëĄì ë°ëŒ ì ë§ëĄ ì€ìíë€ë©Ž ìëŻžê° ìì ìë ìì”ëë€.
+ë€ì ë§íì§ë§, ì”ìì ì룚ì
ì ìì”ëë€.
+
+## êł ë €íŽìŒ í ëȘ ê°ì§ ìŹí[[few_things_you_might want_to_consider]]
+
+### ìëŹ íìž[[error_checking]]
+
+íëĄëì
íêČœììë 돞ì ê° ë°ìí ìŹì§ê° ë§ì”ëë€.
+ë©ëȘšëŠŹê° ëȘšìëŒê±°ë, êł”ê°ìŽ ë¶ìĄ±íê±°ë, ëȘšëžì ê°ì žì€ë ë°ì ì€íšíê±°ë, ìżŒëŠŹê° ìëȘ»ëìê±°ë, ìżŒëŠŹë ì ííŽë ëȘšëž ì€ì ìŽ ìëȘ»ëìŽ ì€íì ì€íšíë ë±ë± ë§ì êČœì°ê° ìĄŽìŹí©ëë€.
+
+ìŒë°ì ìŒëĄ ìëČê° ìŹì©ììêČ ì€ë„넌 ì¶ë „íë êČìŽ ìąìŒëŻëĄ
+ì€ë„넌 íìíêž° ìíŽ `try...except` 돞ì ë§ìŽ ì¶ê°íë êČìŽ ìąì”ëë€.
+íì§ë§ 볎ì ìí©ì ë°ëŒ ëȘšë ì€ë„넌 íìíë êČì 볎ìì ìíí ìë ìë€ë ì ì ëȘ
ìŹíŽìŒí©ëë€.
+
+### ìí· ëžë ìŽíč[[circuit_breaking]]
+
+ìč ìëČë ìŒë°ì ìŒëĄ ìí· ëžë ìŽíčì ìíí ë ë ëì ìí©ì ì§ë©Ží©ëë€.
+ìŠ, ìŽë ìëČê° ìżŒëŠŹë„Œ ëŹŽêž°í êž°ë€ëŠŹë ëì êłŒë¶í ìíìŒ ë ì ì í ì€ë„넌 ë°ííë êČì ì믞í©ëë€.
+ìëČê° ë§€ì° ì€ë ìê° ëì ëêž°íê±°ë ì ëčí ìê°ìŽ ì§ë íì 504 ìëŹë„Œ ë°ííë ëì 503 ìëŹë„Œ ëč 넎êČ ë°ííêČ íë êČì
ëë€.
+
+ì ìë ìœëìë ëšìŒ íê° ììŒëŻëĄ ê”Źííêž°ê° ëčê”ì ìœì”ëë€.
+í íŹêž°ë„Œ íìžíë êČì ìč ìëČê° êłŒë¶í ìí íì ìì ë ìëŹë„Œ ë°ííêž° ìí ê°ì„ êž°ìŽì ìž ìì
ì
ëë€.
+
+### ë©ìž ì°ë ë ì°šëš[[blocking_the_main_thread]]
+
+íìŹ PyTorchë ëčëêž° ìČëŠŹë„Œ ì§ìíì§ ììŒë©°, ì€í ì€ìë ë©ìž ì€ë ëê° ì°šëšë©ëë€.
+ë°ëŒì PyTorch넌 ëłëì ì€ë ë/íëĄìžì€ìì ì€ííëëĄ ê°ì íë êČìŽ ìąì”ëë€.
+ìŹêž°ìë ìŽ ìì
ìŽ ìíëì§ ììì”ëë€. ìëí멎 ìœëê° íšìŹ ë ëł”ìĄíêž° ë돞ì
ëë€(ìŁŒëĄ ì€ë ë, ëčëêž° ìČ늏, íê° ìëĄ ì ë§ì§ ìêž° ë돞ì
ëë€).
+íì§ë§ ê¶ê·čì ìŒëĄë ê°ì ìì
ì ìííë êČì
ëë€.
+
+ëšìŒ íëȘ©ì ì¶ëĄ ìŽ ì€ë 걞늰ë€ë©Ž (> 1ìŽ), ë©ìž ì°ë ë넌 ì°šëšíë êČì ì€ìí ì ìì”ëë€. ìëí멎 ìŽ êČœì° ì¶ëĄ ì€ ëȘšë ìżŒëŠŹë ì€ë„넌 ë°êž° ì ì 1ìŽë„Œ êž°ë€ë €ìŒ íêž° ë돞ì
ëë€.
+
+### ëì ë°°ìč[[dynamic_batching]]
+
+ìŒë°ì ìŒëĄ, ë°°ìč ìČëŠŹê° 1ê° íëȘ©ì í ëČì ì ëŹíë êČì ëčíŽ ë°ëì ì±ë„ í„ììŽ ìë êČì ìëëë€(ììží ëŽì©ì [`batching details`](./main_classes/pipelines#pipeline-batching)ì ì°žêł íìžì).
+íì§ë§ ìŹë°ë„ž ì€ì ìì ìŹì©í멎 ë§€ì° íšêłŒì ìŒ ì ìì”ëë€.
+APIìë êž°ëłžì ìŒëĄ ìë ì íì ê°ë„ì±ìŽ ë§€ì° ëêž° ë돞ì ëì ë°°ìč ìČëŠŹê° ìì”ëë€.
+íì§ë§ ë§€ì° í° ëȘšëžìž BLOOM ì¶ëĄ ì êČœì° ëì ë°°ìč ìČ늏ë ëȘšë ìŹëìêČ ì ì í êČœíì ì êł”íë ë° **íì**ì
ëë€.
diff --git a/docs/source/ko/preprocessing.md b/docs/source/ko/preprocessing.md
new file mode 100644
index 000000000000..7a9d2987381c
--- /dev/null
+++ b/docs/source/ko/preprocessing.md
@@ -0,0 +1,539 @@
+
+
+# ì ìČ늏[[preprocess]]
+
+[[open-in-colab]]
+
+ëȘšëžì íë šíë €ë©Ž ë°ìŽí° ìžížë„Œ ëȘšëžì ë§ë ì
ë „ íììŒëĄ ì ìČ늏íŽìŒ í©ëë€. í
ì€íž, ìŽëŻžì§ ëë ì€ëì€ìžì§ êŽêłììŽ ë°ìŽí°ë„Œ í
ì ë°°ìčëĄ ëłííêł ìĄ°ëŠœí íìê° ìì”ëë€. đ€ Transformersë ëȘšëžì ëí ë°ìŽí°ë„Œ ì€ëčíë ë° ëììŽ ëë ìŒë šì ì ìČ늏 íŽëì€ë„Œ ì êł”í©ëë€. ìŽ íí 늏ìŒììë ë€ì ëŽì©ì ë°°ìž ì ìì”ëë€:
+
+* í
ì€ížë [Tokenizer](./main_classes/tokenizer)넌 ìŹì©íìŹ í í° ìíì€ëĄ ëłííêł í í°ì ì«ì ííì ë§ë í í
ìëĄ ìĄ°ëŠœí©ëë€.
+* ìì± ë° ì€ëì€ë [Feature extractor](./main_classes/feature_extractor)넌 ìŹì©íìŹ ì€ëì€ ííìì ìíì€ íčì±ì íì
íìŹ í
ìëĄ ëłíí©ëë€.
+* ìŽëŻžì§ ì
ë „ì [ImageProcessor](./main_classes/image)ì ìŹì©íìŹ ìŽëŻžì§ë„Œ í
ìëĄ ëłíí©ëë€.
+* ë©í°ëȘšëŹ ì
ë „ì [Processor](./main_classes/processors)ì ìŹì©íìŹ í íŹëìŽì ì íčì± ì¶ì¶êž° ëë ìŽëŻžì§ íëĄìžì넌 êȰí©í©ëë€.
+
+
+
+`AutoProcessor`ë **ìžì ë** ìëíìŹ í íŹëìŽì , ìŽëŻžì§ íëĄìžì, íčì± ì¶ì¶êž° ëë íëĄìžì ë± ìŹì© ì€ìž ëȘšëžì ë§ë íŽëì€ë„Œ ìëìŒëĄ ì íí©ëë€.
+
+
+
+ììíêž° ì ì đ€ Datasets넌 ì€ìčíìŹ ì€íì ìŹì©í ë°ìŽí°ë„Œ ë¶ëŹìŹ ì ìì”ëë€:
+
+```bash
+pip install datasets
+```
+
+## ìì°ìŽìČ늏[[natural-language-processing]]
+
+
+
+í
ì€íž ë°ìŽí°ë„Œ ì ìČ늏íêž° ìí êž°ëłž ëê”Źë [tokenizer](main_classes/tokenizer)ì
ëë€. í íŹëìŽì ë ìŒë šì ê·ìčì ë°ëŒ í
ì€ížë„Œ *í í°*ìŒëĄ ëëëë€. í í°ì ì«ìëĄ ëłíëêł í
ìë ëȘšëž ì
ë „ìŽ ë©ëë€. ëȘšëžì íìí ì¶ê° ì
ë „ì í íŹëìŽì ì ìíŽ ì¶ê°ë©ëë€.
+
+
+
+ìŹì íë šë ëȘšëžì ìŹì©í êłíìŽëŒë©Ž ëȘšëžêłŒ íšê» ìŹì íë šë í íŹëìŽì 넌 ìŹì©íë êČìŽ ì€ìí©ëë€. ìŽë êČ í멎 í
ì€ížê° ìŹì íë š ë§ëìčì ëìŒí ë°©ììŒëĄ ë¶í ëêł ìŹì íë š ì€ì ëìŒí íŽëč í í°-ìžë±ì€ ì(ìŒë°ì ìŒëĄ *vocab*ìŽëŒêł íš)ì ìŹì©í©ëë€.
+
+
+
+ììíë €ë©Ž [`AutoTokenizer.from_pretrained`] ë©ìë넌 ìŹì©íìŹ ìŹì íë šë í íŹëìŽì 넌 ë¶ëŹì€ìžì. ëȘšëžêłŒ íšê» ìŹì íë šë *vocab*ì ë€ìŽëĄëí©ëë€:
+
+```py
+>>> from transformers import AutoTokenizer
+
+>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
+```
+
+ê·ž ë€ììŒëĄ í
ì€ížë„Œ í íŹëìŽì ì ëŁìŽìŁŒìžì:
+
+```py
+>>> encoded_input = tokenizer("Do not meddle in the affairs of wizards, for they are subtle and quick to anger.")
+>>> print(encoded_input)
+{'input_ids': [101, 2079, 2025, 19960, 10362, 1999, 1996, 3821, 1997, 16657, 1010, 2005, 2027, 2024, 11259, 1998, 4248, 2000, 4963, 1012, 102],
+ 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}
+```
+
+í íŹëìŽì ë ìž ê°ì§ ì€ìí íëȘ©ì íŹíší ëì
ëëŠŹë„Œ ë°íí©ëë€:
+
+* [input_ids](glossary#input-ids)ë 돞ì„ì ê° í í°ì íŽëčíë ìžë±ì€ì
ëë€.
+* [attention_mask](glossary#attention-mask)ë í í°ì ìČ늏íŽìŒ íëì§ ìŹë¶ë„Œ ëíë
ëë€.
+* [token_type_ids](glossary#token-type-ids)ë ë ê° ìŽìì ìíì€ê° ìì ë í í°ìŽ ìí ìíì€ë„Œ ìëłí©ëë€.
+
+`input_ids`넌 ëìœë©íìŹ ì
ë „ì ë°íí©ëë€:
+
+```py
+>>> tokenizer.decode(encoded_input["input_ids"])
+'[CLS] Do not meddle in the affairs of wizards, for they are subtle and quick to anger. [SEP]'
+```
+
+í íŹëìŽì ê° ë ê°ì íčìí í í°(ë¶ë„ í í° `CLS`ì ë¶í í í° `SEP`)ì 돞ì„ì ì¶ê°íì”ëë€.
+ëȘšë ëȘšëžì íčìí í í°ìŽ íìí êČì ìëì§ë§, íìíë€ë©Ž í íŹëìŽì ê° ìëìŒëĄ ì¶ê°í©ëë€.
+
+ì ìČ늏í 돞ì„ìŽ ìŹëŹ ê° ìë êČœì°ìë 늏ì€ížëĄ í íŹëìŽì ì ì ëŹí©ëë€:
+
+```py
+>>> batch_sentences = [
+... "But what about second breakfast?",
+... "Don't think he knows about second breakfast, Pip.",
+... "What about elevensies?",
+... ]
+>>> encoded_inputs = tokenizer(batch_sentences)
+>>> print(encoded_inputs)
+{'input_ids': [[101, 1252, 1184, 1164, 1248, 6462, 136, 102],
+ [101, 1790, 112, 189, 1341, 1119, 3520, 1164, 1248, 6462, 117, 21902, 1643, 119, 102],
+ [101, 1327, 1164, 5450, 23434, 136, 102]],
+ 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]],
+ 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1],
+ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
+ [1, 1, 1, 1, 1, 1, 1]]}
+```
+
+### íšë©[[pad]]
+
+ëȘšëž ì
ë „ìž í
ìë ëȘšììŽ ê· ìŒíŽìŒ íì§ë§, 돞ì„ì êžžìŽê° íì ê°ì§ë ìêž° ë돞ì 돞ì ê° ë ì ìì”ëë€. íšë©ì ì§§ì 돞ì„ì íčìí *íšë© í í°*ì ì¶ê°íìŹ í
ì넌 ì§ìŹê°í ëȘšììŽ ëëëĄ íë ì ë”ì
ëë€.
+
+`padding` ë§€ê°ëłì넌 `True`ëĄ ì€ì íìŹ ë°°ìč ëŽì ì§§ì ìíì€ë„Œ ê°ì„ ꞎ ìíì€ì ë§ì¶° íšë©í©ëë€.
+
+```py
+>>> batch_sentences = [
+... "But what about second breakfast?",
+... "Don't think he knows about second breakfast, Pip.",
+... "What about elevensies?",
+... ]
+>>> encoded_input = tokenizer(batch_sentences, padding=True)
+>>> print(encoded_input)
+{'input_ids': [[101, 1252, 1184, 1164, 1248, 6462, 136, 102, 0, 0, 0, 0, 0, 0, 0],
+ [101, 1790, 112, 189, 1341, 1119, 3520, 1164, 1248, 6462, 117, 21902, 1643, 119, 102],
+ [101, 1327, 1164, 5450, 23434, 136, 102, 0, 0, 0, 0, 0, 0, 0, 0]],
+ 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
+ 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0],
+ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
+ [1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]]}
+```
+
+êžžìŽê° ì§§ì ìČ« 돞ì„êłŒ ìž ëČì§ž 돞ì„ìŽ ìŽì `0`ìŒëĄ ì±ììĄì”ëë€.
+
+### ìëŒëŽêž°[[truncation]]
+
+ííž, ëëĄë ìíì€ê° ëȘšëžìì ìČ늏íêž°ì ë돎 êžž ìë ìì”ëë€. ìŽ êČœì°, ìíì€ë„Œ ë ì§§êČ ì€ìŒ íìê° ìì”ëë€.
+
+ëȘšëžìì íì©íë ì”ë êžžìŽëĄ ìíì€ë„Œ ìë„Žë €ë©Ž `truncation` ë§€ê°ëłì넌 `True`ëĄ ì€ì íìžì:
+
+```py
+>>> batch_sentences = [
+... "But what about second breakfast?",
+... "Don't think he knows about second breakfast, Pip.",
+... "What about elevensies?",
+... ]
+>>> encoded_input = tokenizer(batch_sentences, padding=True, truncation=True)
+>>> print(encoded_input)
+{'input_ids': [[101, 1252, 1184, 1164, 1248, 6462, 136, 102, 0, 0, 0, 0, 0, 0, 0],
+ [101, 1790, 112, 189, 1341, 1119, 3520, 1164, 1248, 6462, 117, 21902, 1643, 119, 102],
+ [101, 1327, 1164, 5450, 23434, 136, 102, 0, 0, 0, 0, 0, 0, 0, 0]],
+ 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
+ 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0],
+ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
+ [1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]]}
+```
+
+
+
+ë€ìí íšë©êłŒ ìëŒëŽêž° ìžìì ëíŽ ë ììëłŽë €ë©Ž [íšë©êłŒ ìëŒëŽêž°](./pad_truncation) ê°ë
ê°ìŽë넌 íìžíŽëłŽìžì.
+
+
+
+### í
ì ë§ë€êž°[[build-tensors]]
+
+ë§ì§ë§ìŒëĄ, í íŹëìŽì ê° ëȘšëžì êł”êžëë ì€ì í
ì넌 ë°ííëëĄ í©ëë€.
+
+`return_tensors` ë§€ê°ëłì넌 PyTorchì êČœì° `pt`, TensorFlowì êČœì° `tf`ëĄ ì€ì íìžì:
+
+
+
+
+```py
+>>> batch_sentences = [
+... "But what about second breakfast?",
+... "Don't think he knows about second breakfast, Pip.",
+... "What about elevensies?",
+... ]
+>>> encoded_input = tokenizer(batch_sentences, padding=True, truncation=True, return_tensors="pt")
+>>> print(encoded_input)
+{'input_ids': tensor([[101, 1252, 1184, 1164, 1248, 6462, 136, 102, 0, 0, 0, 0, 0, 0, 0],
+ [101, 1790, 112, 189, 1341, 1119, 3520, 1164, 1248, 6462, 117, 21902, 1643, 119, 102],
+ [101, 1327, 1164, 5450, 23434, 136, 102, 0, 0, 0, 0, 0, 0, 0, 0]]),
+ 'token_type_ids': tensor([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]),
+ 'attention_mask': tensor([[1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0],
+ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
+ [1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]])}
+```
+
+
+```py
+>>> batch_sentences = [
+... "But what about second breakfast?",
+... "Don't think he knows about second breakfast, Pip.",
+... "What about elevensies?",
+... ]
+>>> encoded_input = tokenizer(batch_sentences, padding=True, truncation=True, return_tensors="tf")
+>>> print(encoded_input)
+{'input_ids': ,
+ 'token_type_ids': ,
+ 'attention_mask': }
+```
+
+
+
+## ì€ëì€[[audio]]
+
+ì€ëì€ ìì
ì ëȘšëžì ë§ë ë°ìŽí° ìžížë„Œ ì€ëčíêž° ìíŽ [íčì± ì¶ì¶êž°](main_classes/feature_extractor)ê° íìí©ëë€. íčì± ì¶ì¶êž°ë ìì ì€ëì€ ë°ìŽí°ìì íčì±ë„Œ ì¶ì¶íêł ìŽë„Œ í
ìëĄ ëłííë êČìŽ ëȘ©ì ì
ëë€.
+
+ì€ëì€ ë°ìŽí° ìžížì íčì± ì¶ì¶êž°ë„Œ ìŹì©íë ë°©ëČì ëłŽêž° ìíŽ [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) ë°ìŽí° ìžížë„Œ ê°ì žì€ìžì. (ë°ìŽí° ìžížë„Œ ê°ì žì€ë ë°©ëČì đ€ [ë°ìŽí° ìžíž íí 늏ìŒ](https://huggingface.co/docs/datasets/load_hub.html)ìì ììží ì€ëȘ
íêł ìì”ëë€.)
+
+```py
+>>> from datasets import load_dataset, Audio
+
+>>> dataset = load_dataset("PolyAI/minds14", name="en-US", split="train")
+```
+
+`audio` ìŽì ìČ« ëČì§ž ììì ì ê·ŒíìŹ ì
ë „ì ìŽíŽëłŽìžì. `audio` ìŽì ížì¶í멎 ì€ëì€ íìŒì ìëìŒëĄ ê°ì žì€êł 늏ìíë§í©ëë€.
+
+```py
+>>> dataset[0]["audio"]
+{'array': array([ 0. , 0.00024414, -0.00024414, ..., -0.00024414,
+ 0. , 0. ], dtype=float32),
+ 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav',
+ 'sampling_rate': 8000}
+```
+
+ìŽë êČ í멎 ìž ê°ì§ íëȘ©ìŽ ë°íë©ëë€:
+
+* `array`ë 1D ë°°ìŽëĄ ê°ì žìì (íìí êČœì°) 늏ìíë§ë ìì± ì ížì
ëë€.
+* `path`ë ì€ëì€ íìŒì ììč넌 ê°ëŠŹí”ëë€.
+* `sampling_rate`ë ìì± ì ížìì ìŽëč ìžĄì ëë ë°ìŽí° íŹìžíž ì넌 ëíë
ëë€.
+
+ìŽ íí 늏ìŒììë [Wav2Vec2](https://huggingface.co/facebook/wav2vec2-base) ëȘšëžì ìŹì©í©ëë€. ëȘšëž ìčŽë넌 볎멎 Wav2Vec2ê° 16kHz ìíë§ë ìì± ì€ëì€ë„Œ êž°ë°ìŒëĄ ìŹì íë šë êČì ì ì ìì”ëë€.
+ëȘšëžì ìŹì íë šíë ë° ìŹì©ë ë°ìŽí° ìžížì ìíë§ ë ìŽížì ì€ëì€ ë°ìŽí°ì ìíë§ ë ìŽížê° ìŒìčíŽìŒ í©ëë€. ë°ìŽí°ì ìíë§ ë ìŽížê° ë€ë„Žë©Ž ë°ìŽí°ë„Œ 늏ìíë§íŽìŒ í©ëë€.
+
+1. đ€ Datasetsì [`~datasets.Dataset.cast_column`] ë©ìë넌 ìŹì©íìŹ ìíë§ ë ìŽížë„Œ 16kHzëĄ ì
ìíë§íìžì:
+
+```py
+>>> dataset = dataset.cast_column("audio", Audio(sampling_rate=16_000))
+```
+
+2. ì€ëì€ íìŒì 늏ìíë§íêž° ìíŽ `audio` ìŽì ë€ì ížì¶í©ëë€:
+
+```py
+>>> dataset[0]["audio"]
+{'array': array([ 2.3443763e-05, 2.1729663e-04, 2.2145823e-04, ...,
+ 3.8356509e-05, -7.3497440e-06, -2.1754686e-05], dtype=float32),
+ 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav',
+ 'sampling_rate': 16000}
+```
+
+ë€ììŒëĄ, ì
ë „ì ì ê·ííêł íšë©í íčì± ì¶ì¶êž°ë„Œ ê°ì žì€ìžì. í
ì€íž ë°ìŽí°ì êČœì°, ë ì§§ì ìíì€ì ëíŽ `0`ìŽ ì¶ê°ë©ëë€. ì€ëì€ ë°ìŽí°ìë ê°ì ê°ë
ìŽ ì ì©ë©ëë€.
+íčì± ì¶ì¶êž°ë ë°°ìŽì `0`(돔ììŒëĄ íŽì)ì ì¶ê°í©ëë€.
+
+[`AutoFeatureExtractor.from_pretrained`]넌 ìŹì©íìŹ íčì± ì¶ì¶êž°ë„Œ ê°ì žì€ìžì:
+
+```py
+>>> from transformers import AutoFeatureExtractor
+
+>>> feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base")
+```
+
+ì€ëì€ `array`넌 íčì± ì¶ì¶êž°ì ì ëŹíìžì. ëí, ë°ìí ì ìë ìĄ°ì©í ì€ë„(silent errors)넌 ë ì ëëČêč
í ì ìëëĄ íčì± ì¶ì¶êž°ì `sampling_rate` ìžì넌 ì¶ê°íë êČì ê¶ì„í©ëë€.
+
+```py
+>>> audio_input = [dataset[0]["audio"]["array"]]
+>>> feature_extractor(audio_input, sampling_rate=16000)
+{'input_values': [array([ 3.8106556e-04, 2.7506407e-03, 2.8015103e-03, ...,
+ 5.6335266e-04, 4.6588284e-06, -1.7142107e-04], dtype=float32)]}
+```
+
+í íŹëìŽì ì ë§ì°Źê°ì§ëĄ ë°°ìč ëŽìì ê°ëłì ìž ìíì€ë„Œ ìČ늏íêž° ìíŽ íšë© ëë ìëŒëŽêž°ë„Œ ì ì©í ì ìì”ëë€. ìŽ ë ê°ì ì€ëì€ ìíì ìíì€ êžžìŽë„Œ íìžíŽëłŽìžì:
+
+```py
+>>> dataset[0]["audio"]["array"].shape
+(173398,)
+
+>>> dataset[1]["audio"]["array"].shape
+(106496,)
+```
+
+ì€ëì€ ìíì êžžìŽê° ëìŒíëëĄ ë°ìŽí° ìžížë„Œ ì ìČ늏íë íšì넌 ë§ëìžì. ì”ë ìí êžžìŽë„Œ ì§ì í멎 íčì± ì¶ì¶êž°ê° íŽëč êžžìŽì ë§ì¶° ìíì€ë„Œ íšë©íê±°ë ìëŒë
ëë€:
+
+```py
+>>> def preprocess_function(examples):
+... audio_arrays = [x["array"] for x in examples["audio"]]
+... inputs = feature_extractor(
+... audio_arrays,
+... sampling_rate=16000,
+... padding=True,
+... max_length=100000,
+... truncation=True,
+... )
+... return inputs
+```
+
+`preprocess_function`ì ë°ìŽí° ìžížì ìČì ìì ëȘ ê°ì ì ì©íŽëłŽìžì:
+
+```py
+>>> processed_dataset = preprocess_function(dataset[:5])
+```
+
+ìŽì ìí êžžìŽê° ëȘšë ê°êł ì§ì ë ì”ë êžžìŽì ë§êČ ëìì”ëë€. ëëìŽ ì ìČ늏ë ë°ìŽí° ìžížë„Œ ëȘšëžì ì ëŹí ì ìì”ëë€!
+
+```py
+>>> processed_dataset["input_values"][0].shape
+(100000,)
+
+>>> processed_dataset["input_values"][1].shape
+(100000,)
+```
+
+## 컎íší° ëčì [[computer-vision]]
+
+컎íší° ëčì ìì
ì êČœì°, ëȘšëžì ëí ë°ìŽí° ìžížë„Œ ì€ëčíêž° ìíŽ [ìŽëŻžì§ íëĄìžì](main_classes/image_processor)ê° íìí©ëë€.
+ìŽëŻžì§ ì ìČ늏ë ìŽëŻžì§ë„Œ ëȘšëžìŽ ììíë ì
ë „ìŒëĄ ëłííë ìŹëŹ ëšêłëĄ ìŽëŁšìŽì§ëë€.
+ìŽëŹí ëšêłìë íŹêž° ìĄ°ì , ì ê·í, ìì ì±ë 볎ì , ìŽëŻžì§ì í
ì ëłí ë±ìŽ íŹíšë©ëë€.
+
+
+
+ìŽëŻžì§ ì ìČ늏ë ìŽëŻžì§ ìŠê° êž°ëČì ëȘ ê°ì§ ì ì©í ë€ì í ìë ìì”ëë€.
+ìŽëŻžì§ ì ìČ늏 ë° ìŽëŻžì§ ìŠê°ì ëȘšë ìŽëŻžì§ ë°ìŽí°ë„Œ ëłííì§ë§, ìëĄ ë€ë„ž ëȘ©ì ì ê°ì§êł ìì”ëë€:
+
+* ìŽëŻžì§ ìŠê°ì êłŒì í©(over-fitting)ì ë°©ì§íêł ëȘšëžì êČŹêł íš(resiliency)ì ëìŽë ë° ëììŽ ëë ë°©ììŒëĄ ìŽëŻžì§ë„Œ ìì í©ëë€.
+ë°êž°ì ìì ìĄ°ì , ì넎Ʞ, íì , íŹêž° ìĄ°ì , íë/ì¶ì ë± ë€ìí ë°©ëČìŒëĄ ë°ìŽí°ë„Œ ìŠê°í ì ìì”ëë€.
+ê·žëŹë ìŠê°ìŒëĄ ìŽëŻžì§ì ìëŻžê° ë°ëì§ ìëëĄ ìŁŒìíŽìŒ í©ëë€.
+* ìŽëŻžì§ ì ìČ늏ë ìŽëŻžì§ê° ëȘšëžìŽ ììíë ì
ë „ íìêłŒ ìŒìčíëëĄ ëłŽì„í©ëë€.
+컎íší° ëčì ëȘšëžì ëŻžìž ìĄ°ì í ë ìŽëŻžì§ë ëȘšëžìŽ ìŽêž°ì íë šë ëì ì íí ê°ì ë°©ììŒëĄ ì ìČ늏ëìŽìŒ í©ëë€.
+
+ìŽëŻžì§ ìŠê°ìë ìíë ëŒìŽëžëŹëŠŹë„Œ 돎ììŽë ìŹì©í ì ìì”ëë€. ìŽëŻžì§ ì ìČ늏ìë ëȘšëžêłŒ ì°êȰë `ImageProcessor`넌 ìŹì©í©ëë€.
+
+
+
+[food101](https://huggingface.co/datasets/food101) ë°ìŽí° ìžížë„Œ ê°ì žìì 컎íší° ëčì ë°ìŽí° ìžížìì ìŽëŻžì§ íëĄìžì넌 ìŽë»êČ ìŹì©íëì§ ìì볎ìžì.
+ë°ìŽí° ìžížë„Œ ë¶ëŹì€ë ë°©ëČì đ€ [ë°ìŽí° ìžíž íí 늏ìŒ](https://huggingface.co/docs/datasets/load_hub.html)ì ì°žêł íìžì.
+
+
+
+ë°ìŽí° ìžížê° ìëčí íŹêž° ë돞ì đ€ Datasetsì `split` ë§€ê°ëłì넌 ìŹì©íìŹ íë š ìžížìì ìì ìíë§ ê°ì žì€ìžì!
+
+
+
+```py
+>>> from datasets import load_dataset
+
+>>> dataset = load_dataset("food101", split="train[:100]")
+```
+
+ë€ììŒëĄ, đ€ Datasetsì [`image`](https://huggingface.co/docs/datasets/package_reference/main_classes.html?highlight=image#datasets.Image)ëĄ ìŽëŻžì§ë„Œ íìžíŽëłŽìžì:
+
+```py
+>>> dataset[0]["image"]
+```
+
+
+
+
+
+[`AutoImageProcessor.from_pretrained`]ëĄ ìŽëŻžì§ íëĄìžì넌 ê°ì žì€ìžì:
+
+```py
+>>> from transformers import AutoImageProcessor
+
+>>> image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224")
+```
+
+뚌ì ìŽëŻžì§ ìŠê° ëšêłë„Œ ì¶ê°íŽ ëŽ
ìë€. ì돎 ëŒìŽëžëŹëŠŹë ìŹì©íŽë êŽì°źì§ë§, ìŽëČ íí 늏ìŒììë torchvisionì [`transforms`](https://pytorch.org/vision/stable/transforms.html) ëȘšëì ìŹì©íêČ ì”ëë€.
+ë€ë„ž ë°ìŽí° ìŠê° ëŒìŽëžëŹëŠŹë„Œ ìŹì©íŽëłŽêł ì¶ë€ë©Ž, [Albumentations](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification_albumentations.ipynb) ëë [Kornia notebooks](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification_kornia.ipynb)ìì ìŽë»êČ ìŹì©íëì§ ë°°ìž ì ìì”ëë€.
+
+1. [`Compose`](https://pytorch.org/vision/master/generated/torchvision.transforms.Compose.html)ëĄ [`RandomResizedCrop`](https://pytorch.org/vision/main/generated/torchvision.transforms.RandomResizedCrop.html)ì [`ColorJitter`](https://pytorch.org/vision/main/generated/torchvision.transforms.ColorJitter.html) ë± ëłíì ëȘ ê°ì§ ì°êȰíìžì.
+ì°žêł ëĄ íŹêž° ìĄ°ì ì íìí ìŽëŻžì§ì íŹêž° ìê”ŹìŹíì `image_processor`ìì ê°ì žìŹ ì ìì”ëë€.
+ìŒë¶ ëȘšëžì ì íí ëìŽì ëëč넌 ìê”Źíì§ë§, ì ìŒ ì§§ì ëłì êžžìŽ(`shortest_edge`)ë§ ì ìë ëȘšëžë ìì”ëë€.
+
+```py
+>>> from torchvision.transforms import RandomResizedCrop, ColorJitter, Compose
+
+>>> size = (
+... image_processor.size["shortest_edge"]
+... if "shortest_edge" in image_processor.size
+... else (image_processor.size["height"], image_processor.size["width"])
+... )
+
+>>> _transforms = Compose([RandomResizedCrop(size), ColorJitter(brightness=0.5, hue=0.5)])
+```
+
+2. ëȘšëžì ì
ë „ìŒëĄ [`pixel_values`](model_doc/visionencoderdecoder#transformers.VisionEncoderDecoderModel.forward.pixel_values)넌 ë°ì”ëë€.
+`ImageProcessor`ë ìŽëŻžì§ ì ê·í ë° ì ì í í
ì ìì±ì ìČ늏í ì ìì”ëë€.
+ë°°ìč ìŽëŻžì§ì ëí ìŽëŻžì§ ìŠê° ë° ìŽëŻžì§ ì ìČëŠŹë„Œ êȰí©íêł `pixel_values`넌 ìì±íë íšì넌 ë§ëëë€:
+
+```py
+>>> def transforms(examples):
+... images = [_transforms(img.convert("RGB")) for img in examples["image"]]
+... examples["pixel_values"] = image_processor(images, do_resize=False, return_tensors="pt")["pixel_values"]
+... return examples
+```
+
+
+
+ìì ìììë ìŽëŻžì§ ìŠê° ì€ì ìŽëŻžì§ íŹêž°ë„Œ ìĄ°ì íêž° ë돞ì `do_resize=False`ëĄ ì€ì íêł , íŽëč `image_processor`ìì `size` ìì±ì íì©íì”ëë€.
+ìŽëŻžì§ ìŠê° ì€ì ìŽëŻžì§ íŹêž°ë„Œ ìĄ°ì íì§ ìì êČœì° ìŽ ë§€ê°ëłì넌 ìë”íìžì.
+êž°ëłžì ìŒëĄë `ImageProcessor`ê° íŹêž° ìĄ°ì ì ìČ늏í©ëë€.
+
+ìŠê° ëłí êłŒì ìì ìŽëŻžì§ë„Œ ì ê·ííë €ë©Ž `image_processor.image_mean` ë° `image_processor.image_std` ê°ì ìŹì©íìžì.
+
+
+
+3. đ€ Datasetsì [`set_transform`](https://huggingface.co/docs/datasets/process.html#format-transform)넌 ìŹì©íìŹ ì€ìê°ìŒëĄ ëłíì ì ì©í©ëë€:
+
+```py
+>>> dataset.set_transform(transforms)
+```
+
+4. ìŽì ìŽëŻžì§ì ì ê·Œí멎 ìŽëŻžì§ íëĄìžìê° `pixel_values`넌 ì¶ê°í êČì ì ì ìì”ëë€.
+ëëìŽ ìČ늏ë ë°ìŽí° ìžížë„Œ ëȘšëžì ì ëŹí ì ìì”ëë€!
+
+```py
+>>> dataset[0].keys()
+```
+
+ë€ìì ëłíìŽ ì ì©ë íì ìŽëŻžì§ì
ëë€. ìŽëŻžì§ê° 돎ììëĄ ìë €ëê°êł ìì ìì±ìŽ ë€ëŠ
ëë€.
+
+```py
+>>> import numpy as np
+>>> import matplotlib.pyplot as plt
+
+>>> img = dataset[0]["pixel_values"]
+>>> plt.imshow(img.permute(1, 2, 0))
+```
+
+
+
+
+
+
+
+`ImageProcessor`ë ê°ìČŽ ê°ì§, ìë§ší± ìžê·žë©í
ìŽì
(semantic segmentation), ìžì€íŽì€ ìžê·žë©í
ìŽì
(instance segmentation), íëí± ìžê·žë©í
ìŽì
(panoptic segmentation)êłŒ ê°ì ìì
ì ëí íìČ늏 ë°©ëČì ì êł”í©ëë€.
+ìŽëŹí ë°©ëČì ëȘšëžì ìì ì¶ë „ì êČœêł ììë ìžê·žë©í
ìŽì
ë§”êłŒ ê°ì ì믞 ìë ììžĄìŒëĄ ëłííŽì€ëë€.
+
+
+
+### íšë©[[pad]]
+
+ì넌 ë€ìŽ, [DETR](./model_doc/detr)ì ê°ì êČœì°ìë ëȘšëžìŽ íë ší ë íŹêž° ìĄ°ì ìŠê°ì ì ì©í©ëë€.
+ìŽëĄ ìžíŽ ë°°ìč ëŽ ìŽëŻžì§ íŹêž°ê° ëŹëŒì§ ì ìì”ëë€.
+[`DetrImageProcessor`]ì [`DetrImageProcessor.pad`]넌 ìŹì©íêł ìŹì©ì ì ì `collate_fn`ì ì ìíŽì ë°°ìč ìŽëŻžì§ë„Œ ìČ늏í ì ìì”ëë€.
+
+```py
+>>> def collate_fn(batch):
+... pixel_values = [item["pixel_values"] for item in batch]
+... encoding = image_processor.pad(pixel_values, return_tensors="pt")
+... labels = [item["labels"] for item in batch]
+... batch = {}
+... batch["pixel_values"] = encoding["pixel_values"]
+... batch["pixel_mask"] = encoding["pixel_mask"]
+... batch["labels"] = labels
+... return batch
+```
+
+## ë©í°ëȘšëŹ[[multimodal]]
+
+ë©í°ëȘšëŹ ì
ë „ìŽ íìí ìì
ì êČœì°, ëȘšëžì ë°ìŽí° ìžížë„Œ ì€ëčíêž° ìí [íëĄìžì](main_classes/processors)ê° íìí©ëë€.
+íëĄìžìë í íŹëìŽì ì íčì± ì¶ì¶êž°ì ê°ì ë ê°ì§ ìČ늏 ê°ìČŽë„Œ êȰí©í©ëë€.
+
+[LJ Speech](https://huggingface.co/datasets/lj_speech) ë°ìŽí° ìžížë„Œ ê°ì žìì ìë ìì± ìžì(ASR)ì ìí íëĄìžì넌 ìŹì©íë ë°©ëČì íìžíìžì.
+(ë°ìŽí° ìžížë„Œ ê°ì žì€ë ë°©ëČì ëí ììží ëŽì©ì đ€ [ë°ìŽí° ìžíž íí 늏ìŒ](https://huggingface.co/docs/datasets/load_hub.html)ìì ëłŒ ì ìì”ëë€.)
+
+```py
+>>> from datasets import load_dataset
+
+>>> lj_speech = load_dataset("lj_speech", split="train")
+```
+
+ìë ìì± ìžì(ASR)ììë `audio`ì `text`ìë§ ì§ì€í멎 ëëŻëĄ, ë€ë„ž ìŽë€ì ì ê±°í ì ìì”ëë€:
+
+```py
+>>> lj_speech = lj_speech.map(remove_columns=["file", "id", "normalized_text"])
+```
+
+ìŽì `audio`ì `text`ìŽì ìŽíŽëłŽìžì:
+
+```py
+>>> lj_speech[0]["audio"]
+{'array': array([-7.3242188e-04, -7.6293945e-04, -6.4086914e-04, ...,
+ 7.3242188e-04, 2.1362305e-04, 6.1035156e-05], dtype=float32),
+ 'path': '/root/.cache/huggingface/datasets/downloads/extracted/917ece08c95cf0c4115e45294e3cd0dee724a1165b7fc11798369308a465bd26/LJSpeech-1.1/wavs/LJ001-0001.wav',
+ 'sampling_rate': 22050}
+
+>>> lj_speech[0]["text"]
+'Printing, in the only sense with which we are at present concerned, differs from most if not from all the arts and crafts represented in the Exhibition'
+```
+
+êž°ìĄŽì ìŹì íë šë ëȘšëžìì ìŹì©ë ë°ìŽí° ìžížì ìëĄìŽ ì€ëì€ ë°ìŽí° ìžížì ìíë§ ë ìŽížë„Œ ìŒìčìí€êž° ìíŽ ì€ëì€ ë°ìŽí° ìžížì ìíë§ ë ìŽížë„Œ [늏ìíë§](preprocessing#audio)íŽìŒ í©ëë€!
+
+```py
+>>> lj_speech = lj_speech.cast_column("audio", Audio(sampling_rate=16_000))
+```
+
+[`AutoProcessor.from_pretrained`]ëĄ íëĄìžì넌 ê°ì žì€ìžì:
+
+```py
+>>> from transformers import AutoProcessor
+
+>>> processor = AutoProcessor.from_pretrained("facebook/wav2vec2-base-960h")
+```
+
+1. `array`ì ë€ìŽ ìë ì€ëì€ ë°ìŽí°ë„Œ `input_values`ëĄ ëłííêł `text`넌 í í°ííìŹ `labels`ëĄ ëłííë íšì넌 ë§ëëë€.
+ëȘšëžì ì
ë „ì ë€ìêłŒ ê°ì”ëë€:
+
+```py
+>>> def prepare_dataset(example):
+... audio = example["audio"]
+
+... example.update(processor(audio=audio["array"], text=example["text"], sampling_rate=16000))
+
+... return example
+```
+
+2. ìíì `prepare_dataset` íšìì ì ì©íìžì:
+
+```py
+>>> prepare_dataset(lj_speech[0])
+```
+
+ìŽì íëĄìžìê° `input_values`ì `labels`넌 ì¶ê°íêł , ìíë§ ë ìŽížë ìŹë°ë„ŽêČ 16kHzëĄ ë€ìŽìíë§íì”ëë€.
+ëëìŽ ìČ늏ë ë°ìŽí° ìžížë„Œ ëȘšëžì ì ëŹí ì ìì”ëë€!
diff --git a/docs/source/ko/preprocessing.mdx b/docs/source/ko/preprocessing.mdx
deleted file mode 100644
index 6b9aff451003..000000000000
--- a/docs/source/ko/preprocessing.mdx
+++ /dev/null
@@ -1,535 +0,0 @@
-
-
-# ì ìČ늏[[preprocess]]
-
-[[open-in-colab]]
-
-ëȘšëžì íì”íë €ë©Ž ë°ìŽí°ì
ì ëȘšëžì ë§ë ì
ë „ íììŒëĄ ì ìČ늏 íŽìŒ í©ëë€. ë°ìŽí°ê° í
ì€íž, ìŽëŻžì§ ëë ì€ëì€ìžì§ ìŹë¶ì êŽêłììŽ ë°ìŽí°ë„Œ í
ì ë°°ìčëĄ ëłííêł ìĄ°ëŠœí íìê° ìì”ëë€. đ€ Transformersë ëȘšëžì ëí ë°ìŽí°ë„Œ ì€ëčíë ë° ëììŽ ëë ìŒë šì ì ìČ늏 íŽëì€ë„Œ ì êł”í©ëë€. ìŽ íí 늏ìŒììë ë€ì ëŽì©ì ë°°ìž ì ìì”ëë€.
-
-* í
ì€ížë [Tokenizer](./main_classes/tokenizer)넌 ìŹì©íìŹ í
ì€ížë„Œ í í° ìíì€ëĄ ëłííêł í í°ì ì«ì ííì ë§ë í í
ìëĄ ìĄ°ëŠœí©ëë€.
-* ìì± ë° ì€ëì€ë [Feature extractor](./main_classes/feature_extractor)넌 ìŹì©íìŹ ì€ëì€ ííìì ìíì€ íčì±ì íì
íìŹ í
ìëĄ ëłíí©ëë€.
-* ìŽëŻžì§ ì
ë „ì [ImageProcessor](./main_classes/image)ì ìŹì©íìŹ ìŽëŻžì§ë„Œ í
ìëĄ ëłíí©ëë€.
-* ë©í°ëȘšëŹ ì
ë „ì [Processor](./main_classes/processors)ì ìŹì©íìŹ í íŹëìŽì ì íčì± ì¶ì¶êž° ëë ìŽëŻžì§ íëĄìžì넌 êȰí©í©ëë€.
-
-
-
-`AutoProcessor`ë **íì** ìëíë©° í íŹëìŽì , ìŽëŻžì§ íëĄìžì, íčì± ì¶ì¶êž° ëë íëĄìžì ë± ìŹì© ì€ìž ëȘšëžì ë§ë íŽëì€ë„Œ ìëìŒëĄ ì íí©ëë€.
-
-
-
-ììíêž° ì ì đ€ Datasets넌 ì€ìčíìŹ ì€íì ìŹì©í ë°ìŽí°ë„Œ ë¶ëŹìŹ ì ìì”ëë€:
-
-```bash
-pip install datasets
-```
-
-## ìì°ìŽìČ늏[[natural-language-processing]]
-
-
-
-í
ì€íž ë°ìŽí°ë„Œ ì ìČ늏íêž° ìí êž°ëłž ëê”Źë [tokenizer](main_classes/tokenizer)ì
ëë€. í íŹëìŽì ë ìŒë šì ê·ìčì ë°ëŒ í
ì€ížë„Œ *í í°*ìŒëĄ ëëëë€. í í°ì ì«ìëĄ ëłíëêł í
ìë ëȘšëž ì
ë „ìŽ ë©ëë€. ëȘšëžì íìí ì¶ê° ì
ë „ì í íŹëìŽì ì ìíŽ ì¶ê°ë©ëë€.
-
-
-
-ìŹì íë šë ëȘšëžì ìŹì©í êłíìŽëŒë©Ž ëȘšëžêłŒ íšê» ìŹì íë šë í íŹëìŽì 넌 ìŹì©íë êČìŽ ì€ìí©ëë€. ìŽë êČ í멎 í
ì€ížê° ìŹì íë š ë§ëìčì ëìŒí ë°©ììŒëĄ ë¶í ëêł ìŹì íë š ì€ì ëìŒí íŽëč í í°-ìžë±ì€ ì(ìŒë°ì ìŒëĄ *vocab*ìŽëŒêł íš)ì ìŹì©í©ëë€.
-
-
-
-ììíë €ë©Ž [`AutoTokenizer.from_pretrained`] ë©ìë넌 ìŹì©íìŹ ìŹì íë šë í íŹëìŽì 넌 ë¶ëŹì€ìžì. ëȘšëžêłŒ íšê» ìŹì íë šë *vocab*ì ë€ìŽëĄëí©ëë€:
-
-```py
->>> from transformers import AutoTokenizer
-
->>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
-```
-
-ê·ž ë€ììŒëĄ í
ì€ížë„Œ í íŹëìŽì ì ëŁìŽìŁŒìžì:
-
-```py
->>> encoded_input = tokenizer("Do not meddle in the affairs of wizards, for they are subtle and quick to anger.")
->>> print(encoded_input)
-{'input_ids': [101, 2079, 2025, 19960, 10362, 1999, 1996, 3821, 1997, 16657, 1010, 2005, 2027, 2024, 11259, 1998, 4248, 2000, 4963, 1012, 102],
- 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
- 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}
-```
-
-í íŹëìŽì ë ìž ê°ì§ ì€ìí íëȘ©ì íŹíší ìŹì ì ë°íí©ëë€:
-
-* [input_ids](glossary#input-ids)ë 돞ì„ì ê° í í°ì íŽëčíë ìžë±ì€ì
ëë€.
-* [attention_mask](glossary#attention-mask)ë í í°ì ìČ늏íŽìŒ íëì§ ìŹë¶ë„Œ ëíë
ëë€.
-* [token_type_ids](glossary#token-type-ids)ë ë ê° ìŽìì ìíì€ê° ìì ë í í°ìŽ ìí ìíì€ë„Œ ìëłí©ëë€.
-
-`input_ids`넌 ëìœë©íìŹ ì
ë „ì ë°íí©ëë€:
-
-```py
->>> tokenizer.decode(encoded_input["input_ids"])
-'[CLS] Do not meddle in the affairs of wizards, for they are subtle and quick to anger. [SEP]'
-```
-
-í íŹëìŽì ê° ë ê°ì íčìí í í°(ë¶ë„ í í° CLSì ë¶í í í° SEP)ì 돞ì„ì ì¶ê°íì”ëë€.
-ëȘšë ëȘšëžì íčìí í í°ìŽ íìí êČì ìëì§ë§, íìí êČœì° í íŹëìŽì ê° ìëìŒëĄ ì¶ê°í©ëë€.
-
-ì ìČ늏í 돞ì„ìŽ ìŹëŹ ê° ìë êČœì° ìŽë„Œ 늏ì€ížëĄ í íŹëìŽì ì ì ëŹí©ëë€:
-
-```py
->>> batch_sentences = [
-... "But what about second breakfast?",
-... "Don't think he knows about second breakfast, Pip.",
-... "What about elevensies?",
-... ]
->>> encoded_inputs = tokenizer(batch_sentences)
->>> print(encoded_inputs)
-{'input_ids': [[101, 1252, 1184, 1164, 1248, 6462, 136, 102],
- [101, 1790, 112, 189, 1341, 1119, 3520, 1164, 1248, 6462, 117, 21902, 1643, 119, 102],
- [101, 1327, 1164, 5450, 23434, 136, 102]],
- 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0],
- [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
- [0, 0, 0, 0, 0, 0, 0]],
- 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1],
- [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
- [1, 1, 1, 1, 1, 1, 1]]}
-```
-
-### íšë©[[pad]]
-
-ëȘšëž ì
ë „ìž í
ìë ê· ìŒí ëȘšìì ê°ì žìŒ íëë°, 돞ì„ì êžžìŽê° íì ê°ì§ ììì 돞ì ê° ë ì ìì”ëë€. íšë©ì ì§§ì 돞ì„ì íčìí *íšë© í í°*ì ì¶ê°íìŹ í
ìê° ì§ìŹê°í ëȘšììŽ ëëëĄ íë ì ë”ì
ëë€.
-
-`padding` ë§€ê°ëłì넌 `True`ëĄ ì€ì íìŹ ë°°ìčì ì§§ì ìíì€ë„Œ ê°ì„ ꞎ ìíì€ì ìŒìčíëëĄ íšë©í©ëë€.
-
-```py
->>> batch_sentences = [
-... "But what about second breakfast?",
-... "Don't think he knows about second breakfast, Pip.",
-... "What about elevensies?",
-... ]
->>> encoded_input = tokenizer(batch_sentences, padding=True)
->>> print(encoded_input)
-{'input_ids': [[101, 1252, 1184, 1164, 1248, 6462, 136, 102, 0, 0, 0, 0, 0, 0, 0],
- [101, 1790, 112, 189, 1341, 1119, 3520, 1164, 1248, 6462, 117, 21902, 1643, 119, 102],
- [101, 1327, 1164, 5450, 23434, 136, 102, 0, 0, 0, 0, 0, 0, 0, 0]],
- 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
- [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
- [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
- 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0],
- [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
- [1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]]}
-```
-
-êžžìŽê° ì§§ì ìČ« 돞ì„êłŒ ìž ëČì§ž 돞ì„ì ìŽì `0`ìŒëĄ ì±ìì§ëë€.
-
-### ìë”[[truncation]]
-
-ííž, ëëĄë ìíì€ê° ëȘšëžìì ìČ늏íêž°ì ë돎 êžž ìë ìì”ëë€. ìŽ êČœì°, ìíì€ë„Œ ë ì§§ì êžžìŽëĄ ì€ìŒ íìê° ìì”ëë€.
-
-ëȘšëžìì íì©íë ì”ë êžžìŽëĄ ìíì€ë„Œ ìë„Žë €ë©Ž `truncation` ë§€ê°ëłì넌 `True`ëĄ ì€ì íìžì:
-
-```py
->>> batch_sentences = [
-... "But what about second breakfast?",
-... "Don't think he knows about second breakfast, Pip.",
-... "What about elevensies?",
-... ]
->>> encoded_input = tokenizer(batch_sentences, padding=True, truncation=True)
->>> print(encoded_input)
-{'input_ids': [[101, 1252, 1184, 1164, 1248, 6462, 136, 102, 0, 0, 0, 0, 0, 0, 0],
- [101, 1790, 112, 189, 1341, 1119, 3520, 1164, 1248, 6462, 117, 21902, 1643, 119, 102],
- [101, 1327, 1164, 5450, 23434, 136, 102, 0, 0, 0, 0, 0, 0, 0, 0]],
- 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
- [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
- [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
- 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0],
- [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
- [1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]]}
-```
-
-
-
-ë€ìí íšë© ë° ìë” ìžìì ëíŽ ë ììëłŽë €ë©Ž [Padding and truncation](./pad_truncation) ê°ë
ê°ìŽë넌 íìžíŽëłŽìžì.
-
-
-
-### í
ì ë§ë€êž°[[build-tensors]]
-
-ë§ì§ë§ìŒëĄ, í íŹëìŽì ê° ëȘšëžì êł”êžëë ì€ì í
ì넌 ë°ííëëĄ í©ëë€.
-
-`return_tensors` ë§€ê°ëłì넌 PyTorchì êČœì° `pt`, TensorFlowì êČœì° `tf`ëĄ ì€ì íìžì:
-
-
-
-
-```py
->>> batch_sentences = [
-... "But what about second breakfast?",
-... "Don't think he knows about second breakfast, Pip.",
-... "What about elevensies?",
-... ]
->>> encoded_input = tokenizer(batch_sentences, padding=True, truncation=True, return_tensors="pt")
->>> print(encoded_input)
-{'input_ids': tensor([[101, 1252, 1184, 1164, 1248, 6462, 136, 102, 0, 0, 0, 0, 0, 0, 0],
- [101, 1790, 112, 189, 1341, 1119, 3520, 1164, 1248, 6462, 117, 21902, 1643, 119, 102],
- [101, 1327, 1164, 5450, 23434, 136, 102, 0, 0, 0, 0, 0, 0, 0, 0]]),
- 'token_type_ids': tensor([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
- [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
- [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]),
- 'attention_mask': tensor([[1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0],
- [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
- [1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]])}
-```
-
-
-```py
->>> batch_sentences = [
-... "But what about second breakfast?",
-... "Don't think he knows about second breakfast, Pip.",
-... "What about elevensies?",
-... ]
->>> encoded_input = tokenizer(batch_sentences, padding=True, truncation=True, return_tensors="tf")
->>> print(encoded_input)
-{'input_ids': ,
- 'token_type_ids': ,
- 'attention_mask': }
-```
-
-
-
-## ì€ëì€[[audio]]
-
-ì€ëì€ ìì
ìë ë°ìŽí°ì
ì ëȘšëžì ì€ëčíêž° ìíŽ [íčì± ì¶ì¶êž°](main_classes/feature_extractor)ê° íìí©ëë€. íčì± ì¶ì¶êž°ë ìì ì€ëì€ ë°ìŽí°ìì íčì±ë„Œ ì¶ì¶íêł ìŽë„Œ í
ìëĄ ëłííë êČìŽ ëȘ©ì ì
ëë€.
-
-ì€ëì€ ë°ìŽí°ì
ì íčì± ì¶ì¶êž°ë„Œ ìŹì©íë ë°©ëČì ëłŽë €ë©Ž [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) ë°ìŽí°ì
ì ê°ì žì€ìžì. (ë°ìŽí°ì
ì ê°ì žì€ë ë°©ëČì đ€ [ë°ìŽí°ì
íí 늏ìŒ](https://huggingface.co/docs/datasets/load_hub.html)ìì ììží ì€ëȘ
íêł ìì”ëë€.)
-
-```py
->>> from datasets import load_dataset, Audio
-
->>> dataset = load_dataset("PolyAI/minds14", name="en-US", split="train")
-```
-
-`audio` ìŽì ìČ« ëČì§ž ììì ì ê·ŒíìŹ ì
ë „ì ìŽíŽëłŽìžì. `audio` ìŽì ížì¶í멎 ì€ëì€ íìŒì ìëìŒëĄ ê°ì žì€êł 늏ìíë§í©ëë€.
-
-```py
->>> dataset[0]["audio"]
-{'array': array([ 0. , 0.00024414, -0.00024414, ..., -0.00024414,
- 0. , 0. ], dtype=float32),
- 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav',
- 'sampling_rate': 8000}
-```
-
-ìŽë êČ í멎 ìž ê°ì§ íëȘ©ìŽ ë°íë©ëë€:
-
-* `array`ë 1D ë°°ìŽëĄ ê°ì žìì (íìí êČœì°) 늏ìíë§ë ìì± ì ížì
ëë€.
-* `path`ë ì€ëì€ íìŒì ììč넌 ê°ëŠŹí”ëë€.
-* `sampling_rate`ë ìì± ì ížìì ìŽëč ìžĄì ëë ë°ìŽí° íŹìžíž ì넌 ëíë
ëë€.
-
-ìŽ íí 늏ìŒììë [Wav2Vec2](https://huggingface.co/facebook/wav2vec2-base) ëȘšëžì ìŹì©í©ëë€. ëȘšëž ìčŽë넌 볎멎 Wav2Vec2ê° 16kHz ìíë§ë ìì± ì€ëì€ë„Œ êž°ë°ìŒëĄ ìŹì íì”ë êČì ì ì ìì”ëë€.
-ëȘšëžì ìŹì íì”íë ë° ìŹì©ë ë°ìŽí°ì
ì ìíë§ ë ìŽížì ì€ëì€ ë°ìŽí°ì ìíë§ ë ìŽížê° ìŒìčíŽìŒ í©ëë€. ë°ìŽí°ì ìíë§ ë ìŽížê° ë€ë„Žë©Ž ë°ìŽí°ë„Œ 늏ìíë§íŽìŒ í©ëë€.
-
-1. đ€ Datasetsì [`~datasets.Dataset.cast_column`] ë©ìë넌 ìŹì©íìŹ ìíë§ ë ìŽížë„Œ 16kHzëĄ ì
ìíë§íìžì:
-
-```py
->>> dataset = dataset.cast_column("audio", Audio(sampling_rate=16_000))
-```
-
-2. ì€ëì€ íìŒì 늏ìíë§íêž° ìíŽ `audio` ìŽì ë€ì ížì¶í©ëë€:
-
-```py
->>> dataset[0]["audio"]
-{'array': array([ 2.3443763e-05, 2.1729663e-04, 2.2145823e-04, ...,
- 3.8356509e-05, -7.3497440e-06, -2.1754686e-05], dtype=float32),
- 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav',
- 'sampling_rate': 16000}
-```
-
-ë€ììŒëĄ, ì
ë „ì ì ê·ííêł íšë©íë íčì± ì¶ì¶êž°ë„Œ ê°ì žì€ìžì. í
ì€íž ë°ìŽí°ì êČœì°, ë ì§§ì ìíì€ì ëíŽ `0`ìŽ ì¶ê°ë©ëë€. ì€ëì€ ë°ìŽí°ìë ê°ì ê°ë
ìŽ ì ì©ë©ëë€.
-íčì± ì¶ì¶êž°ë ë°°ìŽì ëíŽ `0`(돔ììŒëĄ íŽì)ì ì¶ê°í©ëë€.
-
-[`AutoFeatureExtractor.from_pretrained`]넌 ìŹì©íìŹ íčì± ì¶ì¶êž°ë„Œ ê°ì žì€ìžì:
-
-```py
->>> from transformers import AutoFeatureExtractor
-
->>> feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base")
-```
-
-ì€ëì€ `array`넌 íčì± ì¶ì¶êž°ì ì ëŹíìžì. ëí, íčì± ì¶ì¶êž°ì `sampling_rate` ìžì넌 ì¶ê°íìŹ ë°ìí ì ìë ìĄ°ì©í ì€ë„(silent errors)넌 ë ì ëëČêč
íë êČì ê¶ì„í©ëë€.
-
-```py
->>> audio_input = [dataset[0]["audio"]["array"]]
->>> feature_extractor(audio_input, sampling_rate=16000)
-{'input_values': [array([ 3.8106556e-04, 2.7506407e-03, 2.8015103e-03, ...,
- 5.6335266e-04, 4.6588284e-06, -1.7142107e-04], dtype=float32)]}
-```
-
-í íŹëìŽì ì ë§ì°Źê°ì§ëĄ ë°°ìč ëŽìì ê°ëłì ìž ìíì€ë„Œ ìČ늏íêž° ìíŽ íšë© ëë ìë”ì ì ì©í ì ìì”ëë€. ìŽ ë ê°ì ì€ëì€ ìíì ìíì€ êžžìŽë„Œ íìžíŽëłŽìžì:
-
-```py
->>> dataset[0]["audio"]["array"].shape
-(173398,)
-
->>> dataset[1]["audio"]["array"].shape
-(106496,)
-```
-
-ì€ëì€ ìíì êžžìŽê° ëìŒíëëĄ ë°ìŽí°ì
ì ì ìČ늏íë íšì넌 ë§ë€ìŽ ëłŽìžì. ì”ë ìí êžžìŽë„Œ ì§ì í멎, íčì± ì¶ì¶êž°ê° íŽëč êžžìŽì ë§ì¶° ìíì€ë„Œ íšë©íê±°ë ìë”í©ëë€:
-
-```py
->>> def preprocess_function(examples):
-... audio_arrays = [x["array"] for x in examples["audio"]]
-... inputs = feature_extractor(
-... audio_arrays,
-... sampling_rate=16000,
-... padding=True,
-... max_length=100000,
-... truncation=True,
-... )
-... return inputs
-```
-
-`preprocess_function`ì ë°ìŽí°ì
ì ìČì ëȘ ê°ì§ ìì ì ì ì©íŽëłŽìžì:
-
-```py
->>> processed_dataset = preprocess_function(dataset[:5])
-```
-
-ìŽì ìí êžžìŽê° ëȘšë ê°êł ì§ì ë ì”ë êžžìŽì ë§êČ ëìì”ëë€. ëëìŽ ì ìČ늏ë ë°ìŽí°ì
ì ëȘšëžì ì ëŹí ì ìì”ëë€!
-
-```py
->>> processed_dataset["input_values"][0].shape
-(100000,)
-
->>> processed_dataset["input_values"][1].shape
-(100000,)
-```
-
-## 컎íší° ëčì [[computer-vision]]
-
-컎íší° ëčì ìì
ì êČœì°, ëȘšëžì ëí ë°ìŽí°ì
ì ì€ëčíêž° ìíŽ [ìŽëŻžì§ íëĄìžì](main_classes/image_processor)ê° íìí©ëë€.
-ìŽëŻžì§ ì ìČ늏ë ìŽëŻžì§ë„Œ ëȘšëžìŽ ììíë ì
ë „ìŒëĄ ëłííë ìŹëŹ ëšêłëĄ ìŽëŁšìŽì§ëë€.
-ìŽëŹí ëšêłìë íŹêž° ìĄ°ì , ì ê·í, ìì ì±ë 볎ì , ìŽëŻžì§ì í
ì ëłí ë±ìŽ íŹíšë©ëë€.
-
-
-
-ìŽëŻžì§ ì ìČ늏ë ìŽëŻžì§ ìŠê° êž°ëČì ëȘ ê°ì§ ì ì©í ë€ì í ìë ìì”ëë€.
-ìŽëŻžì§ ì ìČ늏 ë° ìŽëŻžì§ ìŠê°ì ëȘšë ìŽëŻžì§ ë°ìŽí°ë„Œ ëłííì§ë§, ìëĄ ë€ë„ž ëȘ©ì ì ê°ì§êł ìì”ëë€:
-
-* ìŽëŻžì§ ìŠê°ì êłŒì í©(over-fitting)ì ë°©ì§íêł ëȘšëžì êČŹêł ì±(resiliency)ì ëìŽë ë° ëììŽ ëë ë°©ììŒëĄ ìŽëŻžì§ë„Œ ìì í©ëë€.
-ë°êž°ì ìì ìĄ°ì , ì넎Ʞ, íì , íŹêž° ìĄ°ì , íë/ì¶ì ë± ë€ìí ë°©ëČìŒëĄ ë°ìŽí°ë„Œ ìŠê°í ì ìì”ëë€.
-ê·žëŹë ìŠê°ìŒëĄ ìŽëŻžì§ì ìëŻžê° ë°ëì§ ìëëĄ ìŁŒìíŽìŒ í©ëë€.
-* ìŽëŻžì§ ì ìČ늏ë ìŽëŻžì§ê° ëȘšëžìŽ ììíë ì
ë „ íìêłŒ ìŒìčíëëĄ ëłŽì„í©ëë€.
-컎íší° ëčì ëȘšëžì ëŻžìž ìĄ°ì í ë ìŽëŻžì§ë ëȘšëžìŽ ìŽêž°ì íë šë ëì ì íí ê°ì ë°©ììŒëĄ ì ìČ늏ëìŽìŒ í©ëë€.
-
-ìŽëŻžì§ ìŠê°ìë ìíë ëŒìŽëžëŹëŠŹë„Œ ìŹì©í ì ìì”ëë€. ìŽëŻžì§ ì ìČ늏ìë ëȘšëžêłŒ ì°êȰë `ImageProcessor`넌 ìŹì©í©ëë€.
-
-
-
-[food101](https://huggingface.co/datasets/food101) ë°ìŽí°ì
ì ê°ì žìì 컎íší° ëčì ë°ìŽí°ì
ìì ìŽëŻžì§ íëĄìžì넌 ìŽë»êČ ìŹì©íëì§ ìì볎ìžì.
-ë°ìŽí°ì
ë¶ëŹì€ë ë°©ëČì đ€ [ë°ìŽí°ì
íí 늏ìŒ](https://huggingface.co/docs/datasets/load_hub.html)넌 ì°žêł íìžì.
-
-
-
-ë°ìŽí°ì
ìŽ ìëčí íŹêž° ë돞ì đ€ Datasetsì `split` ë§€ê°ëłì넌 ìŹì©íìŹ íì” ë¶í ìì ìì ìíë§ ê°ì žì€ìžì!
-
-
-
-```py
->>> from datasets import load_dataset
-
->>> dataset = load_dataset("food101", split="train[:100]")
-```
-
-ë€ììŒëĄ, đ€ Datasetsì [`image`](https://huggingface.co/docs/datasets/package_reference/main_classes.html?highlight=image#datasets.Image) êž°ë„ìŒëĄ ìŽëŻžì§ë„Œ íìžíŽëłŽìžì:
-
-```py
->>> dataset[0]["image"]
-```
-
-
-
-
-
-[`AutoImageProcessor.from_pretrained`]ëĄ ìŽëŻžì§ íëĄìžì넌 ê°ì žì€ìžì:
-
-```py
->>> from transformers import AutoImageProcessor
-
->>> image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224")
-```
-
-뚌ì ìŽëŻžì§ ìŠê° ëšêłë„Œ ì¶ê°íŽ ëŽ
ìë€. ì돎 ëŒìŽëžëŹëŠŹë ìŹì©íŽë êŽì°źì§ë§, ìŽëČ íí 늏ìŒììë torchvisionì [`transforms`](https://pytorch.org/vision/stable/transforms.html) ëȘšëì ìŹì©íêČ ì”ëë€.
-ë€ë„ž ë°ìŽí° ìŠê° ëŒìŽëžëŹëŠŹë„Œ ìŹì©íë ë°©ëČìŽ ìêł ì¶ë€ë©Ž, [Albumentations](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification_albumentations.ipynb) ëë [Kornia notebooks](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification_kornia.ipynb)ìì ë°°ìž ì ìì”ëë€.
-
-1. [`Compose`](https://pytorch.org/vision/master/generated/torchvision.transforms.Compose.html)ëĄ [`RandomResizedCrop`](https://pytorch.org/vision/main/generated/torchvision.transforms.RandomResizedCrop.html)ì [`ColorJitter`](https://pytorch.org/vision/main/generated/torchvision.transforms.ColorJitter.html) ë±ì ëłíì ëȘ ê°ì§ ì°êȰíìžì.
-ì°žêł ëĄ íŹêž° ìĄ°ì ì íìí ìŽëŻžì§ì íŹêž° ìê”ŹìŹíì `image_processor`ìì ê°ì žìŹ ì ìì”ëë€.
-ìŒë¶ ëȘšëžì ì íí ëìŽì ëëč넌 ìê”Źíì§ë§, ì ìŒ ì§§ì ëłì êžžìŽ(`shortest_edge`)ë§ ì ìë ëȘšëžë ìì”ëë€.
-
-```py
->>> from torchvision.transforms import RandomResizedCrop, ColorJitter, Compose
-
->>> size = (
-... image_processor.size["shortest_edge"]
-... if "shortest_edge" in image_processor.size
-... else (image_processor.size["height"], image_processor.size["width"])
-... )
-
->>> _transforms = Compose([RandomResizedCrop(size), ColorJitter(brightness=0.5, hue=0.5)])
-```
-
-2. ëȘšëžì ì
ë „ìŒëĄ [`pixel_values`](model_doc/visionencoderdecoder#transformers.VisionEncoderDecoderModel.forward.pixel_values)넌 ë°ì”ëë€.
-`ImageProcessor`ë ìŽëŻžì§ ì ê·í ë° ì ì í í
ì ìì±ì ìČ늏í ì ìì”ëë€.
-ë°°ìč ìŽëŻžì§ì ëí ìŽëŻžì§ ìŠê° ë° ìŽëŻžì§ ì ìČëŠŹë„Œ êȰí©íêł `pixel_values`넌 ìì±íë íšì넌 ë§ëëë€:
-
-```py
->>> def transforms(examples):
-... images = [_transforms(img.convert("RGB")) for img in examples["image"]]
-... examples["pixel_values"] = image_processor(images, do_resize=False, return_tensors="pt")["pixel_values"]
-... return examples
-```
-
-
-
-ìì ìììë ìŽëŻžì§ ìŠê° ì€ì ìŽëŻžì§ íŹêž°ë„Œ ìĄ°ì íêž° ë돞ì `do_resize=False`ëĄ ì€ì íêł , íŽëč `image_processor`ìì `size` ìì±ì íì©íì”ëë€.
-ìŽëŻžì§ ìŠê° ì€ì ìŽëŻžì§ íŹêž°ë„Œ ìĄ°ì íì§ ìì êČœì° ìŽ ë§€ê° ëłì넌 ìë”íìžì.
-êž°ëłžì ìŒëĄ `ImageProcessor`ê° íŹêž° ìĄ°ì ì ìČ늏í©ëë€.
-
-ìŠê° ëłí êłŒì ìì ìŽëŻžì§ë„Œ ì ê·ííë €ë©Ž `image_processor.image_mean` ë° `image_processor.image_std` ê°ì ìŹì©íìžì.
-
-
-
-3. đ€ Datasetsì [`set_transform`](https://huggingface.co/docs/datasets/process.html#format-transform)넌 ìŹì©íìŹ ì€ìê°ìŒëĄ ëłíì ì ì©í©ëë€:
-
-```py
->>> dataset.set_transform(transforms)
-```
-
-4. ìŽì ìŽëŻžì§ì ìĄìžì€í멎 ìŽëŻžì§ íëĄìžìê° `pixel_values`넌 ì¶ê°í êČì ì ì ìì”ëë€.
-ëëìŽ ìČ늏ë ë°ìŽí°ì
ì ëȘšëžì ì ëŹí ì ìì”ëë€!
-
-```py
->>> dataset[0].keys()
-```
-
-ë€ìì ëłíìŽ ì ì©ë íì ìŽëŻžì§ì
ëë€. ìŽëŻžì§ê° 돎ììëĄ ìë €ëê°êł ìì ìì±ìŽ ë€ëŠ
ëë€.
-
-```py
->>> import numpy as np
->>> import matplotlib.pyplot as plt
-
->>> img = dataset[0]["pixel_values"]
->>> plt.imshow(img.permute(1, 2, 0))
-```
-
-
-
-
-
-
-
-`ImageProcessor`ë ê°ìČŽ ê°ì§, ìë§ší± ìžê·žë©í
ìŽì
(semantic segmentation), ìžì€íŽì€ ìžê·žë©í
ìŽì
(instance segmentation), íëí± ìžê·žë©í
ìŽì
(panoptic segmentation)êłŒ ê°ì ìì
ì ëí íìČ늏 ë°©ëČì ì êł”í©ëë€.
-ìŽëŹí ë°©ëČì ëȘšëžì ìì ì¶ë „ì êČœêł ììë ìžê·žë©í
ìŽì
ë§”êłŒ ê°ì ì믞 ìë ììžĄìŒëĄ ëłííŽì€ëë€.
-
-
-
-### íšë[[pad]]
-
-ì넌 ë€ìŽ, [DETR](./model_doc/detr)ì ê°ì êČœì°ìë ëȘšëžìŽ íì”í ë íŹêž° ìĄ°ì ìŠê°ì ì ì©í©ëë€.
-ìŽëĄ ìžíŽ ë°°ìč ëŽ ìŽëŻžì§ íŹêž°ê° ë€ë„Œ ì ìì”ëë€.
-[`DetrImageProcessor`]ì [`DetrImageProcessor.pad_and_create_pixel_mask`]넌 ìŹì©íêł ìŹì©ì ì§ì `collate_fn`ì ì ìíŽì ë°°ìč ìŽëŻžì§ë„Œ ìČ늏í ì ìì”ëë€.
-
-```py
->>> def collate_fn(batch):
-... pixel_values = [item["pixel_values"] for item in batch]
-... encoding = image_processor.pad_and_create_pixel_mask(pixel_values, return_tensors="pt")
-... labels = [item["labels"] for item in batch]
-... batch = {}
-... batch["pixel_values"] = encoding["pixel_values"]
-... batch["pixel_mask"] = encoding["pixel_mask"]
-... batch["labels"] = labels
-... return batch
-```
-
-## ë©í°ëȘšëŹ[[multimodal]]
-
-ë©í°ëȘšëŹ ì
ë „ìŽ íìí ìì
ì êČœì°, ëȘšëžì ë°ìŽí°ì
ì ì€ëčíêž° ìí [íëĄìžì](main_classes/processors)ê° íìí©ëë€.
-íëĄìžìë í íŹëìŽì ì íčì± ì¶ì¶êž°ì ê°ì ë ê°ì§ ìČ늏 ê°ìČŽë„Œ êȰí©í©ëë€.
-
-[LJ Speech](https://huggingface.co/datasets/lj_speech) ë°ìŽí°ì
ì ëĄëíìŹ ìë ìì± ìžì(ASR)ì ìí íëĄìžì넌 ìŹì©íë ë°©ëČì íìžíìžì.
-(ë°ìŽí°ì
ì ëĄëíë ë°©ëČì ëí ììží ëŽì©ì đ€ [ë°ìŽí°ì
íí 늏ìŒ](https://huggingface.co/docs/datasets/load_hub.html)ìì ëłŒ ì ìì”ëë€.)
-
-```py
->>> from datasets import load_dataset
-
->>> lj_speech = load_dataset("lj_speech", split="train")
-```
-
-ASRììë `audio`ì `text`ìë§ ì§ì€í멎 ëëŻëĄ, ë€ë„ž ìŽë€ì ì ê±°í ì ìì”ëë€:
-
-```py
->>> lj_speech = lj_speech.map(remove_columns=["file", "id", "normalized_text"])
-```
-
-ìŽì `audio`ì `text`ìŽì ìŽíŽëłŽìžì:
-
-```py
->>> lj_speech[0]["audio"]
-{'array': array([-7.3242188e-04, -7.6293945e-04, -6.4086914e-04, ...,
- 7.3242188e-04, 2.1362305e-04, 6.1035156e-05], dtype=float32),
- 'path': '/root/.cache/huggingface/datasets/downloads/extracted/917ece08c95cf0c4115e45294e3cd0dee724a1165b7fc11798369308a465bd26/LJSpeech-1.1/wavs/LJ001-0001.wav',
- 'sampling_rate': 22050}
-
->>> lj_speech[0]["text"]
-'Printing, in the only sense with which we are at present concerned, differs from most if not from all the arts and crafts represented in the Exhibition'
-```
-
-êž°ìĄŽì ìŹì íì”ë ëȘšëžìì ìŹì©ë ë°ìŽí°ì
êłŒ ìëĄìŽ ì€ëì€ ë°ìŽí°ì
ì ìíë§ ë ìŽížë„Œ ìŒìčìí€êž° ìíŽ ì€ëì€ ë°ìŽí°ì
ì ìíë§ ë ìŽížë„Œ [늏ìíë§](preprocessing#audio)íŽìŒ í©ëë€!
-
-```py
->>> lj_speech = lj_speech.cast_column("audio", Audio(sampling_rate=16_000))
-```
-
-[`AutoProcessor.from_pretrained`]ëĄ íëĄìžì넌 ê°ì žì€ìžì:
-
-```py
->>> from transformers import AutoProcessor
-
->>> processor = AutoProcessor.from_pretrained("facebook/wav2vec2-base-960h")
-```
-
-1. `array`ì ë€ìŽ ìë ì€ëì€ ë°ìŽí°ë„Œ `input_values`ëĄ ëłííêł `text`넌 í í°ííìŹ `labels`ëĄ ëłííë íšì넌 ë§ëëë€.
-ëȘšëžì ì
ë „ì ë€ìêłŒ ê°ì”ëë€:
-
-```py
->>> def prepare_dataset(example):
-... audio = example["audio"]
-
-... example.update(processor(audio=audio["array"], text=example["text"], sampling_rate=16000))
-
-... return example
-```
-
-2. ìíì `prepare_dataset` íšìì ì ì©íìžì:
-
-```py
->>> prepare_dataset(lj_speech[0])
-```
-
-ìŽì íëĄìžìê° `input_values`ì `labels`넌 ì¶ê°íêł , ìíë§ ë ìŽížë ìŹë°ë„ŽêČ 16kHzëĄ ë€ìŽ ìíë§íì”ëë€.
-ëëìŽ ìČ늏ë ë°ìŽí°ì
ì ëȘšëžì ì ëŹí ì ìì”ëë€!
\ No newline at end of file
diff --git a/docs/source/ko/quicktour.md b/docs/source/ko/quicktour.md
new file mode 100644
index 000000000000..a523aa53e01a
--- /dev/null
+++ b/docs/source/ko/quicktour.md
@@ -0,0 +1,551 @@
+
+
+# ëëŹëłŽêž° [[quick-tour]]
+
+[[open-in-colab]]
+
+đ€ Transformers넌 ììíŽëłŽìžì! ê°ë°íŽëłž ì ìŽ ìëëŒë ìœêČ ìœì ì ìëëĄ ì°ìž ìŽ êžì [`pipeline`](./main_classes/pipelines)ì ìŹì©íìŹ ì¶ëĄ íêł , ìŹì íì”ë ëȘšëžêłŒ ì ìČëŠŹêž°ë„Œ [AutoClass](./model_doc/auto)ëĄ ëĄëíêł , PyTorch ëë TensorFlowëĄ ëȘšëžì ëč 넎êČ íì”ìí€ë ë°©ëČì ìê°íŽ ë늎 êČì
ëë€. ëłž ê°ìŽëìì ìê°ëë ê°ë
ì (íčí ìŽëłŽìì êŽì ìŒëĄ) ë ìčì íêČ ì íêł ì¶ë€ë©Ž, íí 늏ìŒìŽë [ìœì€](https://huggingface.co/course/chapter1/1)넌 ì°žìĄ°íꞰ넌 ê¶ì„í©ëë€.
+
+ììíêž° ì ì íìí ëŒìŽëžëŹëŠŹê° ëȘšë ì€ìčëìŽ ìëì§ íìžíìžì:
+
+```bash
+!pip install transformers datasets
+```
+
+ëí ì ížíë ëšžì ëŹë íë ììíŹë„Œ ì€ìčíŽìŒ í©ëë€:
+
+
+
+```bash
+pip install torch
+```
+
+
+```bash
+pip install tensorflow
+```
+
+
+
+## íìŽíëŒìž [[pipeline]]
+
+
+
+[`pipeline`](./main_classes/pipelines)ì ìŹì íë šë ëȘšëžëĄ ì¶ëĄ íêž°ì ê°ì„ ìœêł ëč 넞 ë°©ëČì
ëë€. [`pipeline`]ì ìŹëŹ ëȘšëŹëŠŹí°ìì ë€ìí êłŒì
ì ìœêČ ìČ늏í ì ììŒë©°, ìë íì íìë ëȘ ê°ì§ êłŒì
ì êž°ëłžì ìŒëĄ ì§ìí©ëë€:
+
+
+
+ìŹì© ê°ë„í ìì
ì ì ìČŽ ëȘ©ëĄì [Pipelines API ì°žìĄ°](./main_classes/pipelines)넌 íìžíìžì.
+
+
+
+| **íì€íŹ** | **ì€ëȘ
** | **ëȘšëŹëŠŹí°** | **íìŽíëŒìž ID** |
+|-----------------|----------------------------------------------------------------------|------------------|-----------------------------------------------|
+| í
ì€íž ë¶ë„ | í
ì€ížì ìë§ì ë ìŽëž ë¶ìŽêž° | ìì°ìŽ ìČ늏(NLP) | pipeline(task="sentiment-analysis") |
+| í
ì€íž ìì± | ìŁŒìŽì§ 돞ììŽ ì
ë „êłŒ ìŽìŽì§ë í
ì€íž ìì±íêž° | ìì°ìŽ ìČ늏(NLP) | pipeline(task="text-generation") |
+| ê°ìČŽëȘ
ìžì | 돞ììŽì ê° í í°ë§ë€ ìë§ì ë ìŽëž ë¶ìŽêž° (ìžëŹŒ, ìĄ°ì§, ì„ì ë±ë±) | ìì°ìŽ ìČ늏(NLP) | pipeline(task="ner") |
+| ì§ììë” | ìŁŒìŽì§ ëŹžë§„êłŒ ì§ëŹžì ë°ëŒ ìŹë°ë„ž ëë”íêž° | ìì°ìŽ ìČ늏(NLP) | pipeline(task="question-answering") |
+| ëčìčž ì±ì°êž° | 돞ììŽì ëčìčžì ìë§ì í í° ë§ì¶êž° | ìì°ìŽ ìČ늏(NLP) | pipeline(task="fill-mask") |
+| ììœ | í
ì€ížë 돞ì넌 ììœíêž° | ìì°ìŽ ìČ늏(NLP) | pipeline(task="summarization") |
+| ëČì | í
ì€ížë„Œ í ìžìŽìì ë€ë„ž ìžìŽëĄ ëČìíêž° | ìì°ìŽ ìČ늏(NLP) | pipeline(task="translation") |
+| ìŽëŻžì§ ë¶ë„ | ìŽëŻžì§ì ìë§ì ë ìŽëž ë¶ìŽêž° | 컎íší° ëčì (CV) | pipeline(task="image-classification") |
+| ìŽëŻžì§ ë¶í | ìŽëŻžì§ì íœì
ë§ë€ ë ìŽëž ë¶ìŽêž°(ìë§ší±, íëí± ë° ìžì€íŽì€ ë¶í íŹíš) | 컎íší° ëčì (CV) | pipeline(task="image-segmentation") |
+| ê°ìČŽ íì§ | ìŽëŻžì§ ì ê°ìČŽì êČœêł ìì넌 ê·žëŠŹêł íŽëì€ë„Œ ììžĄíêž° | 컎íší° ëčì (CV) | pipeline(task="object-detection") |
+| ì€ëì€ ë¶ë„ | ì€ëì€ íìŒì ìë§ì ë ìŽëž ë¶ìŽêž° | ì€ëì€ | pipeline(task="audio-classification") |
+| ìë ìì± ìžì | ì€ëì€ íìŒ ì ìì±ì í
ì€ížëĄ ë°êŸžêž° | ì€ëì€ | pipeline(task="automatic-speech-recognition") |
+| ìê° ì§ììë” | ìŁŒìŽì§ ìŽëŻžì§ì ì§ëŹžì ëíŽ ìŹë°ë„ŽêČ ëë”íêž° | ë©í°ëȘšëŹ | pipeline(task="vqa") |
+| 돞ì ì§ììë” | ìŁŒìŽì§ 돞ìì ì§ëŹžì ëíŽ ìŹë°ë„ŽêČ ëë”íêž° | ë©í°ëȘšëŹ | pipeline(task="document-question-answering") |
+| ìŽëŻžì§ ìșĄì
ëŹêž° | ìŁŒìŽì§ ìŽëŻžì§ì ìșĄì
ìì±íêž° | ë©í°ëȘšëŹ | pipeline(task="image-to-text") |
+
+뚌ì [`pipeline`]ì ìžì€íŽì€ë„Œ ìì±íêł ìŹì©í ìì
ì ì§ì í©ëë€. ìŽ ê°ìŽëììë ê°ì ë¶ìì ìíŽ [`pipeline`]ì ìŹì©íë ìì 넌 볎ìŹë늏êČ ì”ëë€:
+
+```py
+>>> from transformers import pipeline
+
+>>> classifier = pipeline("sentiment-analysis")
+```
+
+[`pipeline`]ì ê°ì ë¶ìì ìí [ìŹì íë šë ëȘšëž](https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english)êłŒ í íŹëìŽì 넌 ìëìŒëĄ ë€ìŽëĄëíêł ìșìí©ëë€. ìŽì `classifier`넌 ëì í
ì€ížì ìŹì©í ì ìì”ëë€:
+
+```py
+>>> classifier("We are very happy to show you the đ€ Transformers library.")
+[{'label': 'POSITIVE', 'score': 0.9998}]
+```
+
+ë§ìœ ì
ë „ìŽ ìŹëŹ ê° ìë êČœì°, ì
ë „ì 늏ì€ížëĄ [`pipeline`]ì ì ëŹíìŹ, ìŹì íë šë ëȘšëžì ì¶ë „ì ëì
ëëŠŹëĄ ìŽëŁšìŽì§ 늏ì€íž ííëĄ ë°ì ì ìì”ëë€:
+
+```py
+>>> results = classifier(["We are very happy to show you the đ€ Transformers library.", "We hope you don't hate it."])
+>>> for result in results:
+... print(f"label: {result['label']}, with score: {round(result['score'], 4)}")
+label: POSITIVE, with score: 0.9998
+label: NEGATIVE, with score: 0.5309
+```
+
+[`pipeline`]ì ìŁŒìŽì§ êłŒì
ì êŽêłììŽ ë°ìŽí°ì
ì ë¶ë„Œ ìíí ìë ìì”ëë€. ìŽ ìì ììë ìë ìì± ìžìì êłŒì
ìŒëĄ ì ííŽ ëłŽêČ ì”ëë€:
+
+```py
+>>> import torch
+>>> from transformers import pipeline
+
+>>> speech_recognizer = pipeline("automatic-speech-recognition", model="facebook/wav2vec2-base-960h")
+```
+
+ë°ìŽí°ì
ì ëĄëí ì°šëĄì
ëë€. (ììží ëŽì©ì đ€ Datasets [ììíêž°](https://huggingface.co/docs/datasets/quickstart#audio)ì ì°žìĄ°íìžì) ìŹêž°ììë [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) ë°ìŽí°ì
ì ëĄëíêČ ì”ëë€:
+
+```py
+>>> from datasets import load_dataset, Audio
+
+>>> dataset = load_dataset("PolyAI/minds14", name="en-US", split="train") # doctest: +IGNORE_RESULT
+```
+
+ë°ìŽí°ì
ì ìíë§ ë ìŽížê° êž°ìĄŽ ëȘšëžìž [`facebook/wav2vec2-base-960h`](https://huggingface.co/facebook/wav2vec2-base-960h)ì íë š ëčì ìíë§ ë ìŽížì ìŒìčíëì§ íìžíŽìŒ í©ëë€:
+
+```py
+>>> dataset = dataset.cast_column("audio", Audio(sampling_rate=speech_recognizer.feature_extractor.sampling_rate))
+```
+
+`"audio"` ìŽì ížì¶í멎 ìëìŒëĄ ì€ëì€ íìŒì ê°ì žìì 늏ìíë§í©ëë€. ìČ« 4ê° ìíìì ìì ìšìŽëžíŒ ë°°ìŽì ì¶ì¶íêł íìŽíëŒìžì 늏ì€ížëĄ ì ëŹíìžì:
+
+```py
+>>> result = speech_recognizer(dataset[:4]["audio"])
+>>> print([d["text"] for d in result])
+['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']
+```
+
+ìì±ìŽë ëčì êłŒ ê°ìŽ ì
ë „ìŽ í° ëê·ëȘš ë°ìŽí°ì
ì êČœì°, ëȘšë ì
ë „ì ë©ëȘšëŠŹì ëĄëíë €ë©Ž 늏ì€íž ëì ì ëë ìŽí° ííëĄ ì ëŹíŽìŒ í©ëë€. ììží ëŽì©ì [Pipelines API ì°žìĄ°](./main_classes/pipelines)넌 íìžíìžì.
+
+### íìŽíëŒìžìì ë€ë„ž ëȘšëžêłŒ í íŹëìŽì ìŹì©íêž° [[use-another-model-and-tokenizer-in-the-pipeline]]
+
+[`pipeline`]ì [Hub](https://huggingface.co/models)ì ëȘšë ëȘšëžì ìŹì©í ì ìêž° ë돞ì, [`pipeline`]ì ë€ë„ž ì©ëì ë§êČ ìœêČ ìì í ì ìì”ëë€. ì넌 ë€ìŽ, íëì€ìŽ í
ì€ížë„Œ ìČ늏í ì ìë ëȘšëžì ìŹì©íêž° ìíŽì Hubì í귞넌 ìŹì©íìŹ ì ì í ëȘšëžì íí°ë§í멎 ë©ëë€. íí°ë§ë êČ°êłŒì ìì íëȘ©ìŒëĄë íëì€ìŽ í
ì€ížì ìŹì©í ì ìë ë€ê”ìŽ [BERT ëȘšëž](https://huggingface.co/nlptown/bert-base-multilingual-uncased-sentiment)ìŽ ë°íë©ëë€:
+
+```py
+>>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
+```
+
+
+
+[`AutoModelForSequenceClassification`]êłŒ [`AutoTokenizer`]넌 ìŹì©íìŹ ìŹì íë šë ëȘšëžêłŒ êŽë šë í íŹëìŽì 넌 ëĄëíìžì (ë€ì ìčì
ìì [`AutoClass`]ì ëíŽ ë ììží ìì볎êČ ì”ëë€):
+
+```py
+>>> from transformers import AutoTokenizer, AutoModelForSequenceClassification
+
+>>> model = AutoModelForSequenceClassification.from_pretrained(model_name)
+>>> tokenizer = AutoTokenizer.from_pretrained(model_name)
+```
+
+
+[`TFAutoModelForSequenceClassification`]êłŒ [`AutoTokenizer`]넌 ìŹì©íìŹ ìŹì íë šë ëȘšëžêłŒ êŽë šë í íŹëìŽì 넌 ëĄëíìžì (ë€ì ìčì
ìì [`TFAutoClass`]ì ëíŽ ë ììží ìì볎êČ ì”ëë€):
+
+```py
+>>> from transformers import AutoTokenizer, TFAutoModelForSequenceClassification
+
+>>> model = TFAutoModelForSequenceClassification.from_pretrained(model_name)
+>>> tokenizer = AutoTokenizer.from_pretrained(model_name)
+```
+
+
+
+[`pipeline`]ìì ëȘšëžêłŒ í íŹëìŽì 넌 ì§ì í멎, ìŽì `classifier`넌 íëì€ìŽ í
ì€ížì ì ì©í ì ìì”ëë€:
+
+```py
+>>> classifier = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer)
+>>> classifier("Nous sommes trĂšs heureux de vous prĂ©senter la bibliothĂšque đ€ Transformers.")
+[{'label': '5 stars', 'score': 0.7273}]
+```
+
+ë§ë
í ëȘšëžì ì°Ÿì ì ìë êČœì° ë°ìŽí°ë„Œ êž°ë°ìŒëĄ ìŹì íë šë ëȘšëžì 믞ìžìĄ°ì íŽìŒ í©ëë€. 믞ìžìĄ°ì ë°©ëČì ëí ììží ëŽì©ì [믞ìžìĄ°ì íí 늏ìŒ](./training)ì ì°žìĄ°íìžì. ìŹì íë šë ëȘšëžì 믞ìžìĄ°ì í íìë ëȘšëžì Hubì ì»€ëź€ëí°ì êł”ì íìŹ ëšžì ëŹë ëŻŒìŁŒíì êž°ìŹíŽìŁŒìžì! đ€
+
+## AutoClass [[autoclass]]
+
+
+
+[`AutoModelForSequenceClassification`]êłŒ [`AutoTokenizer`] íŽëì€ë ììì ë€ëŁŹ [`pipeline`]ì êž°ë„ì ê”Źííë ë° ìŹì©ë©ëë€. [AutoClass](./model_doc/auto)ë ìŹì íë šë ëȘšëžì ìí€í
ìČ넌 ìŽëŠìŽë êČœëĄìì ìëìŒëĄ ê°ì žì€ë 'ë°ëĄê°êž°'ì
ëë€. êłŒì
ì ì í©í `AutoClass`넌 ì ííêł íŽëč ì ìČ늏 íŽëì€ë„Œ ì ííêž°ë§ í멎 ë©ëë€.
+
+ìŽì ìčì
ì ìì ëĄ ëìê°ì [`pipeline`]ì êČ°êłŒë„Œ `AutoClass`넌 íì©íŽ ëł”ì íë ë°©ëČì ìŽíŽëłŽêČ ì”ëë€.
+
+### AutoTokenizer [[autotokenizer]]
+
+í íŹëìŽì ë í
ì€ížë„Œ ëȘšëžì ì
ë „ìŒëĄ ìŹì©íêž° ìíŽ ì«ì ë°°ìŽ ííëĄ ì ìČ늏íë ìí ì ëŽëčí©ëë€. í í°í êłŒì ìë ëšìŽë„Œ ìŽëìì ëìì§, ìŽë ìì€êčì§ ëëì§ì ê°ì ìŹëŹ ê·ìčë€ìŽ ìì”ëë€ (í í°íì ëí ììží ëŽì©ì [í íŹëìŽì ììœ](./tokenizer_summary)ì ì°žìĄ°íìžì). ê°ì„ ì€ìí ì ì ëȘšëžìŽ ìŹì íë šë ëȘšëžêłŒ ëìŒí í í°í ê·ìčì ìŹì©íëëĄ ëìŒí ëȘšëž ìŽëŠìŒëĄ í íŹëìŽì 넌 ìžì€íŽì€ííŽìŒ íë€ë êČì
ëë€.
+
+[`AutoTokenizer`]ëĄ í íŹëìŽì 넌 ëĄëíìžì:
+
+```py
+>>> from transformers import AutoTokenizer
+
+>>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
+>>> tokenizer = AutoTokenizer.from_pretrained(model_name)
+```
+
+í
ì€ížë„Œ í íŹëìŽì ì ì ëŹíìžì:
+
+```py
+>>> encoding = tokenizer("We are very happy to show you the đ€ Transformers library.")
+>>> print(encoding)
+{'input_ids': [101, 11312, 10320, 12495, 19308, 10114, 11391, 10855, 10103, 100, 58263, 13299, 119, 102],
+ 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}
+```
+
+í íŹëìŽì ë ë€ìì íŹíší ëì
ëëŠŹë„Œ ë°íí©ëë€:
+
+* [input_ids](./glossary#input-ids): í í°ì ì«ì íí.
+* [attention_mask](.glossary#attention-mask): ìŽë€ í í°ì ìŁŒì넌 êž°ìžìŹìŒ íëì§ë„Œ ëíë
ëë€.
+
+í íŹëìŽì ë ì
ë „ì 늏ì€íž ííëĄë ë°ì ì ììŒë©°, í
ì€ížë„Œ íšë©íêł ìëŒëŽìŽ ìŒì í êžžìŽì 돶ìì ë°íí ìë ìì”ëë€:
+
+
+
+```py
+>>> pt_batch = tokenizer(
+... ["We are very happy to show you the đ€ Transformers library.", "We hope you don't hate it."],
+... padding=True,
+... truncation=True,
+... max_length=512,
+... return_tensors="pt",
+... )
+```
+
+
+```py
+>>> tf_batch = tokenizer(
+... ["We are very happy to show you the đ€ Transformers library.", "We hope you don't hate it."],
+... padding=True,
+... truncation=True,
+... max_length=512,
+... return_tensors="tf",
+... )
+```
+
+
+
+
+
+[ì ìČ늏](./preprocessing) íí 늏ìŒì ì°žìĄ°íì멎 í í°íì ëí ììží ì€ëȘ
êłŒ íšê» ìŽëŻžì§, ì€ëì€ì ë©í°ëȘšëŹ ì
ë „ì ì ìČ늏íêž° ìí [`AutoImageProcessor`]ì [`AutoFeatureExtractor`], [`AutoProcessor`]ì ìŹì©ë°©ëČë ì ì ìì”ëë€.
+
+
+
+### AutoModel [[automodel]]
+
+
+
+đ€ Transformersë ìŹì íë šë ìžì€íŽì€ë„Œ ê°ëšíêł í”í©ë ë°©ëČìŒëĄ ëĄëí ì ìì”ëë€. ìŠ, [`AutoTokenizer`]ìČëŒ [`AutoModel`]ì ëĄëí ì ìì”ëë€. ì ìŒí ì°šìŽì ì êłŒì
ì ìë§ì [`AutoModel`]ì ì ííŽìŒ íë€ë ì ì
ëë€. í
ì€íž (ëë ìíì€) ë¶ë„ì êČœì° [`AutoModelForSequenceClassification`]ì ëĄëíŽìŒ í©ëë€:
+
+```py
+>>> from transformers import AutoModelForSequenceClassification
+
+>>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
+>>> pt_model = AutoModelForSequenceClassification.from_pretrained(model_name)
+```
+
+
+
+[`AutoModel`] íŽëì€ìì ì§ìíë êłŒì
ì ëíŽìë [êłŒì
ììœ](./task_summary)ì ì°žìĄ°íìžì.
+
+
+
+ìŽì ì ìČ늏ë ì
ë „ 돶ìì ì§ì ëȘšëžì ì ëŹíŽìŒ í©ëë€. ìëìČëŒ `**`넌 ìì ë¶ìŹ ëì
ëëŠŹë„Œ íìŽìŁŒë©Ž ë©ëë€:
+
+```py
+>>> pt_outputs = pt_model(**pt_batch)
+```
+
+ëȘšëžì ì”ìą
íì±í íšì ì¶ë „ì `logits` ìì±ì ëŽêČšìì”ëë€. `logits`ì softmax íšì넌 ì ì©íìŹ íë„ ì ì»ì ì ìì”ëë€:
+
+```py
+>>> from torch import nn
+
+>>> pt_predictions = nn.functional.softmax(pt_outputs.logits, dim=-1)
+>>> print(pt_predictions)
+tensor([[0.0021, 0.0018, 0.0115, 0.2121, 0.7725],
+ [0.2084, 0.1826, 0.1969, 0.1755, 0.2365]], grad_fn=)
+```
+
+
+đ€ Transformersë ìŹì íë šë ìžì€íŽì€ë„Œ ê°ëšíêł í”í©ë ë°©ëČìŒëĄ ëĄëí ì ìì”ëë€. ìŠ, [`AutoTokenizer`]ìČëŒ [`TFAutoModel`]ì ëĄëí ì ìì”ëë€. ì ìŒí ì°šìŽì ì êłŒì
ì ìë§ì [`TFAutoModel`]ì ì ííŽìŒ íë€ë ì ì
ëë€. í
ì€íž (ëë ìíì€) ë¶ë„ì êČœì° [`TFAutoModelForSequenceClassification`]ì ëĄëíŽìŒ í©ëë€:
+
+```py
+>>> from transformers import TFAutoModelForSequenceClassification
+
+>>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
+>>> tf_model = TFAutoModelForSequenceClassification.from_pretrained(model_name)
+```
+
+
+
+[`AutoModel`] íŽëì€ìì ì§ìíë êłŒì
ì ëíŽìë [êłŒì
ììœ](./task_summary)ì ì°žìĄ°íìžì.
+
+
+
+ìŽì ì ìČ늏ë ì
ë „ 돶ìì ì§ì ëȘšëžì ì ëŹíŽìŒ í©ëë€. ìëìČëŒ ê·žëëĄ í
ì넌 ì ëŹí멎 ë©ëë€:
+
+```py
+>>> tf_outputs = tf_model(tf_batch)
+```
+
+ëȘšëžì ì”ìą
íì±í íšì ì¶ë „ì `logits` ìì±ì ëŽêČšìì”ëë€. `logits`ì softmax íšì넌 ì ì©íìŹ íë„ ì ì»ì ì ìì”ëë€:
+
+```py
+>>> import tensorflow as tf
+
+>>> tf_predictions = tf.nn.softmax(tf_outputs.logits, axis=-1)
+>>> tf_predictions # doctest: +IGNORE_RESULT
+```
+
+
+
+
+
+ëȘšë đ€ Transformers ëȘšëž(PyTorch ëë TensorFlow)ì (softmaxì ê°ì) ì”ìą
íì±í íšì *ìŽì ì* í
ì넌 ì¶ë „í©ëë€. ìëí멎 ì”ìą
íì±í íšìì ì¶ë „ì ìą
ìą
ìì€ íšì ì¶ë „êłŒ êȰí©ëêž° ë돞ì
ëë€. ëȘšëž ì¶ë „ì íčìí ë°ìŽí° íŽëì€ìŽëŻëĄ IDEìì ìë ìì±ë©ëë€. ëȘšëž ì¶ë „ì ííìŽë ëì
ë늏ìČëŒ ëìíë©° (ì ì, ìŹëŒìŽì€ ëë 돞ììŽëĄ ìžë±ì± ê°ë„), Noneìž ìì±ì 돎ìë©ëë€.
+
+
+
+### ëȘšëž ì ì„íêž° [[save-a-model]]
+
+
+
+믞ìžìĄ°ì ë ëȘšëžì í íŹëìŽì ì íšê» ì ì„íë €ë©Ž [`PreTrainedModel.save_pretrained`]넌 ìŹì©íìžì:
+
+```py
+>>> pt_save_directory = "./pt_save_pretrained"
+>>> tokenizer.save_pretrained(pt_save_directory) # doctest: +IGNORE_RESULT
+>>> pt_model.save_pretrained(pt_save_directory)
+```
+
+ëȘšëžì ë€ì ìŹì©íë €ë©Ž [`PreTrainedModel.from_pretrained`]ëĄ ëȘšëžì ë€ì ëĄëíìžì:
+
+```py
+>>> pt_model = AutoModelForSequenceClassification.from_pretrained("./pt_save_pretrained")
+```
+
+
+믞ìžìĄ°ì ë ëȘšëžì í íŹëìŽì ì íšê» ì ì„íë €ë©Ž [`TFPreTrainedModel.save_pretrained`]넌 ìŹì©íìžì:
+
+```py
+>>> tf_save_directory = "./tf_save_pretrained"
+>>> tokenizer.save_pretrained(tf_save_directory) # doctest: +IGNORE_RESULT
+>>> tf_model.save_pretrained(tf_save_directory)
+```
+
+ëȘšëžì ë€ì ìŹì©íë €ë©Ž [`TFPreTrainedModel.from_pretrained`]ëĄ ëȘšëžì ë€ì ëĄëíìžì:
+
+```py
+>>> tf_model = TFAutoModelForSequenceClassification.from_pretrained("./tf_save_pretrained")
+```
+
+
+
+đ€ Transformersì ë©ì§ êž°ë„ ì€ íëë ëȘšëžì PyTorch ëë TensorFlow ëȘšëžëĄ ì ì„íŽëë€ê° ë€ë„ž íë ììíŹëĄ ë€ì ëĄëí ì ìë ì ì
ëë€. `from_pt` ëë `from_tf` ë§€ê°ëłì넌 ìŹì©íìŹ ëȘšëžì í íë ììíŹìì ë€ë„ž íë ììíŹëĄ ëłíí ì ìì”ëë€:
+
+
+
+```py
+>>> from transformers import AutoModel
+
+>>> tokenizer = AutoTokenizer.from_pretrained(tf_save_directory)
+>>> pt_model = AutoModelForSequenceClassification.from_pretrained(tf_save_directory, from_tf=True)
+```
+
+
+```py
+>>> from transformers import TFAutoModel
+
+>>> tokenizer = AutoTokenizer.from_pretrained(pt_save_directory)
+>>> tf_model = TFAutoModelForSequenceClassification.from_pretrained(pt_save_directory, from_pt=True)
+```
+
+
+
+## 컀ì€í
ëȘšëž ê”Źì¶íêž° [[custom-model-builds]]
+
+ëȘšëžì ê”Źì± íŽëì€ë„Œ ìì íìŹ ëȘšëžì ê”ŹìĄ°ë„Œ ë°êż ì ìì”ëë€. (ìëìž”ìŽë ìŽí
ì
í€ëì ìì ê°ì) ëȘšëžì ìì±ì ê”Źì±ìì ì§ì ëêž° ë돞ì
ëë€. 컀ì€í
ê”Źì± íŽëì€ëĄ ëȘšëžì ë§ë€ë©Ž ìČìë¶í° ììíŽìŒ í©ëë€. ëȘšëž ìì±ì 돎ììëĄ ìŽêž°íëëŻëĄ ì믞 ìë êČ°êłŒë„Œ ì»ìŒë €ë©Ž 뚌ì ëȘšëžì íë šììŒìŒ í©ëë€.
+
+뚌ì [`AutoConfig`]넌 ê°ì žì€êł ìì íêł ì¶ì ìŹì íì”ë ëȘšëžì ëĄëíìžì. [`AutoConfig.from_pretrained`] ëŽë¶ìì (ìŽí
ì
í€ë ìì ê°ìŽ) ëłêČœíë €ë ìì±ë„Œ ì§ì í ì ìì”ëë€:
+
+```py
+>>> from transformers import AutoConfig
+
+>>> my_config = AutoConfig.from_pretrained("distilbert-base-uncased", n_heads=12)
+```
+
+
+
+[`AutoModel.from_config`]넌 ìŹì©íìŹ ë°êŸŒ ê”Źì±ëëĄ ëȘšëžì ìì±íìžì:
+
+```py
+>>> from transformers import AutoModel
+
+>>> my_model = AutoModel.from_config(my_config)
+```
+
+
+[`TFAutoModel.from_config`]넌 ìŹì©íìŹ ë°êŸŒ ê”Źì±ëëĄ ëȘšëžì ìì±íìžì:
+
+```py
+>>> from transformers import TFAutoModel
+
+>>> my_model = TFAutoModel.from_config(my_config)
+```
+
+
+
+컀ì€í
ê”Źì±ì ëí ììží ëŽì©ì [컀ì€í
ìí€í
ìČ ë§ë€êž°](./create_a_model) ê°ìŽë넌 íìžíìžì.
+
+## Trainer - PyTorchì ì”ì íë íë š 룚í [[trainer-a-pytorch-optimized-training-loop]]
+
+ëȘšë ëȘšëžì [`torch.nn.Module`](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)ìŽëŻëĄ ìŒë°ì ìž íë š 룚íìì ìŹì©í ì ìì”ëë€. ì§ì íë š 룚í넌 ìì±í ìë ìì§ë§, đ€ Transformersë PyTorch넌 ìí [`Trainer`] íŽëì€ë„Œ ì êł”í©ëë€. ìŽ íŽëì€ìë êž°ëłž íë š 룚íê° íŹíšëìŽ ììŒë©° ë¶ì° íë š, íŒí© ì ë°ë ë±êłŒ ê°ì êž°ë„ì ì¶ê°ëĄ ì êł”í©ëë€.
+
+êłŒì
ì ë°ëŒ ë€ë„Žì§ë§ ìŒë°ì ìŒëĄ [`Trainer`]ì ë€ì ë§€ê°ëłì넌 ì ëŹí©ëë€:
+
+1. [`PreTrainedModel`] ëë [`torch.nn.Module`](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)ëĄ ììí©ëë€:
+
+ ```py
+ >>> from transformers import AutoModelForSequenceClassification
+
+ >>> model = AutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased")
+ ```
+
+2. [`TrainingArguments`]ë íì”ë„ , ë°°ìč íŹêž°, íë ší ìíŹíŹ ìì ê°ì ëȘšëž íìŽíŒíëŒëŻží°ë„Œ íŹíší©ëë€. íë š ìžì넌 ì§ì íì§ ììŒë©Ž êž°ëłžê°ìŽ ìŹì©ë©ëë€:
+
+ ```py
+ >>> from transformers import TrainingArguments
+
+ >>> training_args = TrainingArguments(
+ ... output_dir="path/to/save/folder/",
+ ... learning_rate=2e-5,
+ ... per_device_train_batch_size=8,
+ ... per_device_eval_batch_size=8,
+ ... num_train_epochs=2,
+ ... )
+ ```
+
+3. í íŹëìŽì , ìŽëŻžì§ íëĄìžì, íčì§ ì¶ì¶êž°(feature extractor) ëë íëĄìžìì ì ìČ늏 íŽëì€ë„Œ ëĄëíìžì:
+
+ ```py
+ >>> from transformers import AutoTokenizer
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
+ ```
+
+4. ë°ìŽí°ì
ì ëĄëíìžì:
+
+ ```py
+ >>> from datasets import load_dataset
+
+ >>> dataset = load_dataset("rotten_tomatoes") # doctest: +IGNORE_RESULT
+ ```
+
+5. ë°ìŽí°ì
ì í í°ííë íšì넌 ìì±íìžì:
+
+ ```py
+ >>> def tokenize_dataset(dataset):
+ ... return tokenizer(dataset["text"])
+ ```
+
+ ê·žëŠŹêł [`~datasets.Dataset.map`]ëĄ ë°ìŽí°ì
ì ìČŽì ì ì©íìžì:
+
+ ```py
+ >>> dataset = dataset.map(tokenize_dataset, batched=True)
+ ```
+
+6. [`DataCollatorWithPadding`]ì ìŹì©íìŹ ë°ìŽí°ì
ì íëłž 돶ìì ë§ëìžì:
+
+ ```py
+ >>> from transformers import DataCollatorWithPadding
+
+ >>> data_collator = DataCollatorWithPadding(tokenizer=tokenizer)
+ ```
+
+ìŽì ìì ëȘšë íŽëì€ë„Œ [`Trainer`]ëĄ ëȘšìŒìžì:
+
+```py
+>>> from transformers import Trainer
+
+>>> trainer = Trainer(
+... model=model,
+... args=training_args,
+... train_dataset=dataset["train"],
+... eval_dataset=dataset["test"],
+... tokenizer=tokenizer,
+... data_collator=data_collator,
+... ) # doctest: +SKIP
+```
+
+ì€ëčê° ëììŒë©Ž [`~Trainer.train`]ì ížì¶íìŹ íë šì ììíìžì:
+
+```py
+>>> trainer.train() # doctest: +SKIP
+```
+
+
+
+ëČììŽë ììœêłŒ ê°ìŽ ìíì€-ìíì€ ëȘšëžì ìŹì©íë êłŒì
ìë [`Seq2SeqTrainer`] ë° [`Seq2SeqTrainingArguments`] íŽëì€ë„Œ ìŹì©íìžì.
+
+
+
+[`Trainer`] ëŽì ë©ìë넌 ìëžíŽëì€ííìŹ íë š 룚í넌 ë°êż ìë ìì”ëë€. ìŽëŹë©Ž ìì€ íšì, ì”í°ë§ìŽì , ì€ìŒì€ëŹì ê°ì êž°ë„ ëí ë°êż ì ìêČ ë©ëë€. ëłêČœ ê°ë„í ë©ìëì ëíŽìë [`Trainer`] 돞ì넌 ì°žêł íìžì.
+
+íë š 룚í넌 ìì íë ë€ë„ž ë°©ëČì [Callbacks](./main_classes/callbacks)넌 ìŹì©íë êČì
ëë€. CallbacksëĄ ë€ë„ž ëŒìŽëžëŹëŠŹì í”í©íêł , íë š 룚í넌 ìČŽíŹíìŹ ì§í ìí©ì ëłŽêł ë°ê±°ë, íë šì ìĄ°êž°ì ì€ëší ì ìì”ëë€. Callbacksì íë š 룚í ììČŽë„Œ ë°êŸžì§ë ìì”ëë€. ìì€ íšìì ê°ì êČì ë°êŸžë €ë©Ž [`Trainer`]넌 ìëžíŽëì€ííŽìŒ í©ëë€.
+
+## TensorFlowëĄ íë šìí€êž° [[train-with-tensorflow]]
+
+ëȘšë ëȘšëžì [`tf.keras.Model`](https://www.tensorflow.org/api_docs/python/tf/keras/Model)ìŽëŻëĄ [Keras](https://keras.io/) API넌 í”íŽ TensorFlowìì íë šìíŹ ì ìì”ëë€. đ€ Transformersë ë°ìŽí°ì
ì ìœêČ `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) ë©ìëëĄ ë°ëĄ íë šì ììí ì ìì”ëë€.
+
+1. [`TFPreTrainedModel`] ëë [`tf.keras.Model`](https://www.tensorflow.org/api_docs/python/tf/keras/Model)ëĄ ììí©ëë€:
+
+ ```py
+ >>> from transformers import TFAutoModelForSequenceClassification
+
+ >>> model = TFAutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased")
+ ```
+
+2. í íŹëìŽì , ìŽëŻžì§ íëĄìžì, íčì§ ì¶ì¶êž°(feature extractor) ëë íëĄìžìì ê°ì ì ìČ늏 íŽëì€ë„Œ ëĄëíìžì:
+
+ ```py
+ >>> from transformers import AutoTokenizer
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
+ ```
+
+3. ë°ìŽí°ì
ì í í°ííë íšì넌 ìì±íìžì:
+
+ ```py
+ >>> def tokenize_dataset(dataset):
+ ... return tokenizer(dataset["text"]) # doctest: +SKIP
+ ```
+
+4. [`~datasets.Dataset.map`]ì ìŹì©íìŹ ì ìČŽ ë°ìŽí°ì
ì í í°í íšì넌 ì ì©íêł , ë°ìŽí°ì
êłŒ í íŹëìŽì 넌 [`~TFPreTrainedModel.prepare_tf_dataset`]ì ì ëŹíìžì. ë°°ìč íŹêž°ë„Œ ëłêČœíê±°ë ë°ìŽí°ì
ì ìì ìë ìì”ëë€:
+
+ ```py
+ >>> dataset = dataset.map(tokenize_dataset) # doctest: +SKIP
+ >>> tf_dataset = model.prepare_tf_dataset(
+ ... dataset["train"], batch_size=16, shuffle=True, tokenizer=tokenizer
+ ... ) # doctest: +SKIP
+ ```
+
+5. ì€ëčëììŒë©Ž `compile` ë° `fit`넌 ížì¶íìŹ íë šì ììíìžì. đ€ Transformersì ëȘšë ëȘšëžì êłŒì
êłŒ êŽë šë êž°ëłž ìì€ íšì넌 ê°ì§êł ììŒëŻëĄ ëȘ
ìì ìŒëĄ ì§ì íì§ ììë ë©ëë€:
+
+ ```py
+ >>> from tensorflow.keras.optimizers import Adam
+
+ >>> model.compile(optimizer=Adam(3e-5)) # No loss argument!
+ >>> model.fit(tf_dataset) # doctest: +SKIP
+ ```
+
+## ë€ì ëšêłë 돎ììžê°ì? [[whats-next]]
+
+đ€ Transformers ëëŹëłŽêž°ë„Œ ëȘšë ìœìŒì
šë€ë©Ž, ê°ìŽë넌 ìŽíŽëłŽêł ë ê”ŹìČŽì ìž êČì ìííë ë°©ëČì ìì볎ìžì. ìŽë„Œí
멎 컀ì€í
ëȘšëž ê”Źì¶íë ë°©ëČ, êłŒì
ì ìë§êČ ëȘšëžì 믞ìžìĄ°ì íë ë°©ëČ, ì€íŹëŠœížëĄ ëȘšëž íë šíë ë°©ëČ ë±ìŽ ìì”ëë€. đ€ Transformers í”ìŹ ê°ë
ì ëíŽ ë ììëłŽë €ë©Ž ì»€íŒ í ì ë€êł ê°ë
ê°ìŽë넌 ìŽíŽëłŽìžì!
\ No newline at end of file
diff --git a/docs/source/ko/quicktour.mdx b/docs/source/ko/quicktour.mdx
deleted file mode 100644
index dc50d6a938fe..000000000000
--- a/docs/source/ko/quicktour.mdx
+++ /dev/null
@@ -1,536 +0,0 @@
-
-
-# ëëŹëłŽêž°[[quick-tour]]
-
-[[open-in-colab]]
-đ€ Transformer넌 ììíŽëŽì! ëëŹëłŽêž°ë ê°ë°ìì ìŒë° ìŹì©ì ëȘšë넌 ìíŽ ì°ìŹìĄì”ëë€. [`pipeline`]ìŒëĄ ì¶ëĄ íë ë°©ëČ, [AutoClass](./model_doc/auto)ëĄ ìŹì íì”ë ëȘšëžêłŒ ì ìČëŠŹêž°ë„Œ ì ìŹíë ë°©ëČêłŒ PyTorch ëë TensorFlowëĄ ì ìíêČ ëȘšëžì íë šìí€ë ë°©ëČì 볎ìŹì€ëë€. êž°ëłžì ë°°ì°êł ì¶ë€ë©Ž íí 늏ìŒìŽë [course](https://huggingface.co/course/chapter1/1)ìì ìŹêž° ìê°ë ê°ë
ì ëí ììží ì€ëȘ
ì íìžíìêžž ê¶ì„í©ëë€.
-
-ììíêž° ì ì íìí ëŒìŽëžëŹëŠŹê° ëȘšë ì€ìčëìŽ ìëì§ íìžíêł ,
-
-```bash
-!pip install transformers datasets
-```
-
-ìąìíë ëšžì ëŹë íë ììíŹë ì€ìčíŽìŒ í©ëë€.
-
-
-
-```bash
-pip install torch
-```
-
-
-```bash
-pip install tensorflow
-```
-
-
-
-## Pipeline (íìŽíëŒìž)
-
-
-
-[`pipeline`]ì ìŹì íì”ë ëȘšëžì ìŹì©íŽ ì¶ëĄ í ë ì ìŒ ìŹìŽ ë°©ëČì
ëë€. ìŹëŹ ëȘšëŹëŠŹí°ì ìë§ì íì€íŹì [`pipeline`]ì ìŠì ìŹì©í ì ìì”ëë€. ì§ìíë íì€íŹì ììë ìë í넌 ì°žêł íìžì.
-
-| **íì€íŹ** | **ì€ëȘ
** | **ëȘšëŹëŠŹí°** | **íìŽíëŒìž ID** |
-|----------------|---------------------------------------------------------------------|------------------|-----------------------------------------------|
-| í
ì€íž ë¶ë„ | í
ì€ížì ìë§ì ëŒëČš ë¶ìŽêž° | ìì°ìŽ ìČ늏(NLP) | pipeline(task="sentiment-analysis") |
-| í
ì€íž ìì± | ìŁŒìŽì§ 돞ììŽ ì
ë „êłŒ ìŽìŽì§ë í
ì€íž ìì±íêž° | ìì°ìŽ ìČ늏(NLP) | pipeline(task="text-generation") |
-| ê°ìČŽëȘ
ìžì | 돞ììŽì ê° í í°ë§ë€ ìë§ì ëŒëČš ë¶ìŽêž° (ìžëŹŒ, ìĄ°ì§, ì„ì ë±ë±) | ìì°ìŽ ìČ늏(NLP) | pipeline(task="ner") |
-| ì§ììë” | ìŁŒìŽì§ ëŹžë§„êłŒ ì§ëŹžì ë°ëŒ ìŹë°ë„ž ëë”íêž° | ìì°ìŽ ìČ늏(NLP) | pipeline(task="question-answering") |
-| ëčìčž ì±ì°êž° | 돞ììŽì ëčìčžì ìë§ì í í° ë§ì¶êž° | ìì°ìŽ ìČ늏(NLP) | pipeline(task="fill-mask") |
-| ììœ | í
ì€ížë 돞ì넌 ììœíêž° | ìì°ìŽ ìČ늏(NLP) | pipeline(task="summarization") |
-| ëČì | í
ì€ížë„Œ í ìžìŽìì ë€ë„ž ìžìŽëĄ ëČìíêž° | ìì°ìŽ ìČ늏(NLP) | pipeline(task="translation") |
-| ìŽëŻžì§ ë¶ë„ | ìŽëŻžì§ì ìë§ì ëŒëČš ë¶ìŽêž° | 컎íší° ëčì (CV) | pipeline(task="image-classification") |
-| ìŽëŻžì§ ë¶í | ìŽëŻžì§ì íœì
ë§ë€ ëŒëČš ë¶ìŽêž°(ìë§ší±, íëí± ë° ìžì€íŽì€ ë¶í íŹíš) | 컎íší° ëčì (CV) | pipeline(task="image-segmentation") |
-| ê°ìČŽ íì§ | ìŽëŻžì§ ì ê°ìČŽì êČœêł ìì넌 ê·žëŠŹêł íŽëì€ë„Œ ììžĄíêž° | 컎íší° ëčì (CV) | pipeline(task="object-detection") |
-| ì€ëì€ ë¶ë„ | ì€ëì€ íìŒì ìë§ì ëŒëČš ë¶ìŽêž° | ì€ëì€ | pipeline(task="audio-classification") |
-| ìë ìì± ìžì | ì€ëì€ íìŒ ì ìì±ì í
ì€ížëĄ ë°êŸžêž° | ì€ëì€ | pipeline(task="automatic-speech-recognition") |
-| ìê° ì§ììë” | ìŁŒìŽì§ ìŽëŻžì§ì ìŽëŻžì§ì ëí ì§ëŹžì ë°ëŒ ìŹë°ë„ŽêČ ëë”íêž° | ë©í°ëȘšëŹ | pipeline(task="vqa") |
-
-뚌ì [`pipeline`]ì ìžì€íŽì€ë„Œ ë§ë€ìŽ ì ì©í íì€íŹë„Œ êł ë„Žìžì. ì íì€íŹë€ì ëȘšë [`pipeline`]ì ìŹì©í ì ìêł , ì§ìíë íì€íŹì ì ìČŽ ëȘ©ëĄì ëłŽë €ë©Ž [pipeline API ë íŒë°ì€](./main_classes/pipelines)넌 íìžíŽìŁŒìžì. ê°ëší ììëĄ ê°ì ë¶ì íì€íŹì [`pipeline`]넌 ì ì©íŽ ëłŽêČ ì”ëë€.
-
-```py
->>> from transformers import pipeline
-
->>> classifier = pipeline("sentiment-analysis")
-```
-
-[`pipeline`]ì êž°ëłž [ìŹì íì”ë ëȘšëž(ììŽ)](https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english)ì ê°ì ë¶ìì íêž° ìí tokenizer넌 ë€ìŽëĄëíêł ìșìíŽëì”ëë€. ìŽì ìíë í
ì€ížì `classifier`넌 ìŹì©í ì ìì”ëë€.
-
-```py
->>> classifier("We are very happy to show you the đ€ Transformers library.")
-[{'label': 'POSITIVE', 'score': 0.9998}]
-```
-
-ì
ë „ìŽ ìŹëŹ ê°ëŒë©Ž, ì
ë „ì [`pipeline`]ì 늏ì€ížëĄ ì ëŹíŽì ëì
ëëŠŹëĄ ë 늏ì€ížë„Œ ë°ì ì ìì”ëë€.
-
-```py
->>> results = classifier(["We are very happy to show you the đ€ Transformers library.", "We hope you don't hate it."])
->>> for result in results:
-... print(f"label: {result['label']}, with score: {round(result['score'], 4)}")
-label: POSITIVE, with score: 0.9998
-label: NEGATIVE, with score: 0.5309
-```
-
-[`pipeline`]ì íčì íì€íŹì© ë°ìŽí°ì
넌 ì ë¶ ìíí ìë ìì”ëë€. ìë ìì± ìžì íì€íŹì ì ì©íŽ ëłŽêČ ì”ëë€.
-
-```py
->>> import torch
->>> from transformers import pipeline
-
->>> speech_recognizer = pipeline("automatic-speech-recognition", model="facebook/wav2vec2-base-960h")
-```
-
-ìŽì ìíí ì€ëì€ ë°ìŽí°ì
넌 ì ìŹíêČ ì”ëë€. (ììží ëŽì©ì đ€ Datasets [ììíêž°](https://huggingface.co/docs/datasets/quickstart#audio)넌 ì°žêł íŽìŁŒìžì) [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) ë°ìŽí°ì
ëĄ íŽëłŒêčì?
-
-```py
->>> from datasets import load_dataset, Audio
-
->>> dataset = load_dataset("PolyAI/minds14", name="en-US", split="train") # doctest: +IGNORE_RESULT
-```
-
-ë°ìŽí°ì
ì ìíë§ ë ìŽížê° [`facebook/wav2vec2-base-960h`](https://huggingface.co/facebook/wav2vec2-base-960h)ì íë š ëčì ìíë§ ë ìŽížì ìŒìčíŽìŒë§ í©ëë€.
-
-```py
->>> dataset = dataset.cast_column("audio", Audio(sampling_rate=speech_recognizer.feature_extractor.sampling_rate))
-```
-
-ì€ëì€ íìŒì `"audio"` ìŽì ížì¶í ë ìëìŒëĄ ì ìŹëêł ë€ì ìíë§ë©ëë€.
-ìČì 4ê° ìíìì ìì±ì ì¶ì¶íìŹ íìŽíëŒìžì 늏ì€íž ííëĄ ì ëŹíŽëłŽêČ ì”ëë€.
-
-```py
->>> result = speech_recognizer(dataset[:4]["audio"])
->>> print([d["text"] for d in result])
-['I WOULD LIKE TO SET UP A JOINT ACCOUNT WITH MY PARTNER HOW DO I PROCEED WITH DOING THAT', "FODING 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 AP SO 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 THURN A JOIN A COUNT']
-```
-
-(ìì±ìŽë ëčì ìČëŒ) ì
ë „ìŽ í° ëê·ëȘš ë°ìŽí°ì
ì êČœì°, ë©ëȘšëŠŹì ì ìŹìí€êž° ìíŽ ëŠŹì€íž ëì ì ëë ìŽí°ëĄ ì
ë „ì ëȘšë ì ëŹí ì ìì”ëë€. ììží ëŽì©ì [pipeline API ë íŒë°ì€](./main_classes/pipelines)넌 íìžíŽìŁŒìžì.
-
-### íìŽíëŒìžìì ë€ë„ž ëȘšëžìŽë tokenizer ìŹì©íë ë°©ëČ[[use-another-model-and-tokenizer-in-the-pipeline]]
-
-[`pipeline`]ì [Hub](https://huggingface.co/models) ì ëȘšë ëȘšëžì ìŹì©í ì ììŽ, ìŒë§ë ì§ [`pipeline`]ì ìŹì©íêł ì¶ìëëĄ ë°êż ì ìì”ëë€. ì넌 ë€ìŽ íëì€ìŽ í
ì€ížë„Œ ë€ëٰ ì ìë ëȘšëžì ë§ëë €ë©Ž, Hubì íê·žëĄ ì ì í ëȘšëžì ì°Ÿì볎ìžì. ìì êČì êČ°êłŒëĄ ëŹ ê°ì ë¶ìì ìíŽ íìžíëë ë€ê”ìŽ [BERT ëȘšëž](https://huggingface.co/nlptown/bert-base-multilingual-uncased-sentiment)ìŽ íëì€ìŽë„Œ ì§ìíëê”°ì.
-
-```py
->>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
-```
-
-
-
-[`AutoModelForSequenceClassification`]êłŒ [`AutoTokenizer`]ëĄ ìŹì íì”ë ëȘšëžêłŒ íšê» ì°êŽë í íŹëìŽì 넌 ë¶ëŹì”ëë€. (`AutoClass`ì ëí ëŽì©ì ë€ì ìčì
ìì ìŽíŽëłŽêČ ì”ëë€)
-
-```py
->>> from transformers import AutoTokenizer, AutoModelForSequenceClassification
-
->>> model = AutoModelForSequenceClassification.from_pretrained(model_name)
->>> tokenizer = AutoTokenizer.from_pretrained(model_name)
-```
-
-
-[`TFAutoModelForSequenceClassification`]êłŒ [`AutoTokenizer`]ëĄ ìŹì íì”ë ëȘšëžêłŒ íšê» ì°êŽë í íŹëìŽì 넌 ë¶ëŹì”ëë€. (`TFAutoClass`ì ëí ëŽì©ì ë€ì ìčì
ìì ìŽíŽëłŽêČ ì”ëë€)
-
-```py
->>> from transformers import AutoTokenizer, TFAutoModelForSequenceClassification
-
->>> model = TFAutoModelForSequenceClassification.from_pretrained(model_name)
->>> tokenizer = AutoTokenizer.from_pretrained(model_name)
-```
-
-
-
-[`pipeline`]ìì ìŹì©í ëȘšëžêłŒ í íŹëìŽì 넌 ì
ë „í멎 ìŽì (ê°ì ë¶ìêž°ìž) `classifier`넌 íëì€ìŽ í
ì€ížì ì ì©í ì ìì”ëë€.
-
-```py
->>> classifier = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer)
->>> classifier("Nous sommes trĂšs heureux de vous prĂ©senter la bibliothĂšque đ€ Transformers.")
-[{'label': '5 stars', 'score': 0.7273}]
-```
-
-íêł ì¶ì êČì ì ì©í ë§ë
í ëȘšëžìŽ ìë€ë©Ž, ê°ì§ ë°ìŽí°ëĄ ìŹì íì”ë ëȘšëžì íìžíëíŽìŒ í©ëë€. ììží ë°©ëČì [íìžíë íí 늏ìŒ](./training)ì ì°žêł íŽìŁŒìžì. ìŹì íì”ë ëȘšëžì íìžíëì ë§ìčì
šìŒë©Ž, ëê”Źë ëšžì ëŹëì í ì ìëëĄ [êł”ì ](./model_sharing)íë êČì êł ë €íŽìŁŒìžì. đ€
-
-## AutoClass
-
-
-
-ëŽë¶ì ìŒëĄ ë€ìŽê°ë©Ž ììì ìŹì©íë [`pipeline`]ì [`AutoModelForSequenceClassification`]êłŒ [`AutoTokenizer`] íŽëì€ëĄ ìëí©ëë€. [AutoClass](./model_doc/auto)ë ìŽëŠìŽë êČœëĄë„Œ ë°ìŒë©Ž ê·žì ìë§ë ìŹì íì”ë ëȘšëžì ê°ì žì€ë 'ë°ëĄê°êž°'ëŒêł ëłŒ ì ìëë°ì. ìíë íì€íŹì ì ìČ늏ì ì í©í `AutoClass`넌 êł ë„Žêž°ë§ í멎 ë©ëë€.
-
-ì ì ìŹì©íë ììëĄ ëìê°ì `AutoClass`ëĄ [`pipeline`]êłŒ ëìŒí êČ°êłŒë„Œ ì»ì ì ìë ë°©ëČì ìì볎êČ ì”ëë€.
-
-### AutoTokenizer
-
-í íŹëìŽì ë ì ìČëŠŹë„Œ ëŽëčíë©°, í
ì€ížë„Œ ëȘšëžìŽ ë°ì ì«ì ë°°ìŽëĄ ë°êżëë€. í í°í êłŒì ìë ëšìŽë„Œ ìŽëìì ëìì§, ìŒë§íŒ ëëì§ ë±ì íŹíší ìŹëŹ ê·ìčìŽ ìì”ëë€. ììží ëŽì©ì [í íŹëìŽì ììœ](./tokenizer_summary)넌 íìžíŽìŁŒìžì. ì ìŒ ì€ìí ì ì ëȘšëžìŽ íë šëì ëì ëìŒí í í°í ê·ìčì ì°ëëĄ ëìŒí ëȘšëž ìŽëŠìŒëĄ í íŹëìŽì ìžì€íŽì€ë„Œ ë§ë€ìŽìŒ í©ëë€.
-
-[`AutoTokenizer`]ëĄ í íŹëìŽì 넌 ë¶ëŹì€êł ,
-
-```py
->>> from transformers import AutoTokenizer
-
->>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
->>> tokenizer = AutoTokenizer.from_pretrained(model_name)
-```
-
-í íŹëìŽì ì í
ì€ížë„Œ ì êł”íìžì.
-
-```py
->>> encoding = tokenizer("We are very happy to show you the đ€ Transformers library.")
->>> print(encoding)
-{'input_ids': [101, 11312, 10320, 12495, 19308, 10114, 11391, 10855, 10103, 100, 58263, 13299, 119, 102],
- 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
- 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}
-```
-
-ê·žëŹë©Ž ë€ìì íŹíší ëì
ëëŠŹê° ë°íë©ëë€.
-
-* [input_ids](./glossary#input-ids): ì«ìëĄ ííë í í°ë€
-* [attention_mask](.glossary#attention-mask): ìŁŒìí í í°ë€
-
-í íŹëìŽì ë ì
ë „ì 늏ì€ížëĄë ë°ì ì ììŒë©°, í
ì€ížë„Œ íšëíê±°ë ìëŒëŽìŽ ê· ìŒí êžžìŽì ë°°ìč넌 ë°íí ìë ìì”ëë€.
-
-
-
-```py
->>> pt_batch = tokenizer(
-... ["We are very happy to show you the đ€ Transformers library.", "We hope you don't hate it."],
-... padding=True,
-... truncation=True,
-... max_length=512,
-... return_tensors="pt",
-... )
-```
-
-
-```py
->>> tf_batch = tokenizer(
-... ["We are very happy to show you the đ€ Transformers library.", "We hope you don't hate it."],
-... padding=True,
-... truncation=True,
-... max_length=512,
-... return_tensors="tf",
-... )
-```
-
-
-
-
-
-[ì ìČ늏](./preprocessing) íí 늏ìŒì 볎ì멎 í í°íì ëí ììží ì€ëȘ
êłŒ íšê» ìŽëŻžì§, ì€ëì€ì ë©í°ëȘšëŹ ì
ë „ì ì ìČ늏íêž° ìí [`AutoFeatureExtractor`]êłŒ [`AutoProcessor`]ì ìŹì©ë°©ëČë ì ì ìì”ëë€.
-
-
-
-### AutoModel
-
-
-
-đ€ TransformersëĄ ìŹì íì”ë ìžì€íŽì€ë„Œ ê°ëšíêł í”ìŒë ë°©ììŒëĄ ë¶ëŹìŹ ì ìì”ëë€. ìŽëŹë©Ž [`AutoTokenizer`]ìČëŒ [`AutoModel`]ë ë¶ëŹìŹ ì ìêČ ë©ëë€. ì ìŒí ì°šìŽì ì íì€íŹì ì í©í [`AutoModel`]ì ì ííŽìŒ íë€ë ì ì
ëë€. í
ì€íž(ëë ìíì€) ë¶ë„ì êČœì° [`AutoModelForSequenceClassification`]ì ë¶ëŹììŒ í©ëë€.
-
-```py
->>> from transformers import AutoModelForSequenceClassification
-
->>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
->>> pt_model = AutoModelForSequenceClassification.from_pretrained(model_name)
-```
-
-
-
-[`AutoModel`] íŽëì€ìì ì§ìíë íì€íŹë€ì [íì€íŹ ì 늏](./task_summary) 돞ì넌 ì°žêł íŽìŁŒìžì.
-
-
-
-ìŽì ì ìČ늏ë ì
ë „ ë°°ìč넌 ëȘšëžëĄ ì§ì 볎ëŽìŒ í©ëë€. ìëìČëŒ `**`넌 ìì ë¶ìŹ ëì
ëëŠŹë„Œ íìŽìŁŒêž°ë§ í멎 ë©ëë€.
-
-```py
->>> pt_outputs = pt_model(**pt_batch)
-```
-
-ëȘšëžì activation êČ°êłŒë `logits` ìì±ì ëŽêČšìì”ëë€. `logits`ì Softmax íšì넌 ì ì©íŽì íë„ ííëĄ ë°ìŒìžì.
-
-```py
->>> from torch import nn
-
->>> pt_predictions = nn.functional.softmax(pt_outputs.logits, dim=-1)
->>> print(pt_predictions)
-tensor([[0.0021, 0.0018, 0.0115, 0.2121, 0.7725],
- [0.2084, 0.1826, 0.1969, 0.1755, 0.2365]], grad_fn=)
-```
-
-
-đ€ Transformersë ìŹì íì”ë ìžì€íŽì€ë„Œ ê°ëšíêł í”ìŒë ë°©ììŒëĄ ë¶ëŹìŹ ì ìì”ëë€. ìŽëŹë©Ž [`AutoTokenizer`]ìČëŒ [`TFAutoModel`]ë ë¶ëŹìŹ ì ìêČ ë©ëë€. ì ìŒí ì°šìŽì ì íì€íŹì ì í©í [`TFAutoModel`]넌 ì ííŽìŒ íë€ë ì ì
ëë€. í
ì€íž(ëë ìíì€) ë¶ë„ì êČœì° [`TFAutoModelForSequenceClassification`]ì ë¶ëŹììŒ í©ëë€.
-
-```py
->>> from transformers import TFAutoModelForSequenceClassification
-
->>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
->>> tf_model = TFAutoModelForSequenceClassification.from_pretrained(model_name)
-```
-
-
-
-[`AutoModel`] íŽëì€ìì ì§ìíë íì€íŹë€ì [íì€íŹ ì 늏](./task_summary) 돞ì넌 ì°žêł íŽìŁŒìžì.
-
-
-
-ìŽì ì ìČ늏ë ì
ë „ ë°°ìč넌 ëȘšëžëĄ ì§ì 볎ëŽìŒ í©ëë€. ëì
ë늏ì í€ë„Œ í
ìì ì§ì ëŁìŽìŁŒêž°ë§ í멎 ë©ëë€.
-
-```py
->>> tf_outputs = tf_model(tf_batch)
-```
-
-ëȘšëžì activation êČ°êłŒë `logits` ìì±ì ëŽêČšìì”ëë€. `logits`ì Softmax íšì넌 ì ì©íŽì íë„ ííëĄ ë°ìŒìžì.
-
-```py
->>> import tensorflow as tf
-
->>> tf_predictions = tf.nn.softmax(tf_outputs.logits, axis=-1)
->>> tf_predictions # doctest: +IGNORE_RESULT
-```
-
-
-
-
-
-ëȘšë (PyTorch ëë TensorFlow) đ€ Transformers ëȘšëžì (softmax ë±ì) ì”ìą
activation íšì *ìŽì ì* í
ì넌 ëŽëì”ëë€. ìëí멎 ì”ìą
activation íšì넌 ìą
ìą
loss íšìì ëìŒìíêž° ë돞ì
ëë€. ëȘšëž ì¶ë „ì íčì ë°ìŽí° íŽëì€ìŽëŻëĄ íŽëč ìì±ì IDEìì ìëìŒëĄ ìì±ë©ëë€. ëȘšëž ì¶ë „ì íí ëë (ì ì, ìŹëŒìŽì€ ëë 돞ììŽëĄ ìžë±ì±íë) ëì
ë늏 ííëĄ ìŁŒìŽì§êł ìŽë° êČœì° Noneìž ìì±ì 돎ìë©ëë€.
-
-
-
-### ëȘšëž ì ì„íêž°[[save-a-model]]
-
-
-
-ëȘšëžì íìžíëí ë€ìë [`PreTrainedModel.save_pretrained`]ëĄ ëȘšëžì í íŹëìŽì ì íšê» ì ì„í ì ìì”ëë€.
-
-```py
->>> pt_save_directory = "./pt_save_pretrained"
->>> tokenizer.save_pretrained(pt_save_directory) # doctest: +IGNORE_RESULT
->>> pt_model.save_pretrained(pt_save_directory)
-```
-
-ëȘšëžì ë€ì ìŹì©í ëë [`PreTrainedModel.from_pretrained`]ëĄ ë€ì ë¶ëŹì€ë©Ž ë©ëë€.
-
-```py
->>> pt_model = AutoModelForSequenceClassification.from_pretrained("./pt_save_pretrained")
-```
-
-
-ëȘšëžì íìžíëí ë€ìë [`TFPreTrainedModel.save_pretrained`]ëĄ ëȘšëžì í íŹëìŽì ì íšê» ì ì„í ì ìì”ëë€.
-
-```py
->>> tf_save_directory = "./tf_save_pretrained"
->>> tokenizer.save_pretrained(tf_save_directory) # doctest: +IGNORE_RESULT
->>> tf_model.save_pretrained(tf_save_directory)
-```
-
-ëȘšëžì ë€ì ìŹì©í ëë [`TFPreTrainedModel.from_pretrained`]ëĄ ë€ì ë¶ëŹì€ë©Ž ë©ëë€.
-
-```py
->>> tf_model = TFAutoModelForSequenceClassification.from_pretrained("./tf_save_pretrained")
-```
-
-
-
-đ€ Transformers êž°ë„ ì€ íčí ìŹëŻžìë í ê°ì§ë ëȘšëžì ì ì„íêł PyTorchë TensorFlow ëȘšëžëĄ ë€ì ë¶ëŹìŹ ì ìë êž°ë„ì
ëë€. 'from_pt' ëë 'from_tf' ë§€ê°ëłì넌 ìŹì©íŽ ëȘšëžì êž°ìĄŽêłŒ ë€ë„ž íë ììíŹëĄ ëłíìíŹ ì ìì”ëë€.
-
-
-
-```py
->>> from transformers import AutoModel
-
->>> tokenizer = AutoTokenizer.from_pretrained(tf_save_directory)
->>> pt_model = AutoModelForSequenceClassification.from_pretrained(tf_save_directory, from_tf=True)
-```
-
-
-```py
->>> from transformers import TFAutoModel
-
->>> tokenizer = AutoTokenizer.from_pretrained(pt_save_directory)
->>> tf_model = TFAutoModelForSequenceClassification.from_pretrained(pt_save_directory, from_pt=True)
-```
-
-
-
-## 컀ì€í
ëȘšëž ê”Źì¶íêž°[[custom-model-builds]]
-
-ëȘšëžì ê”Źì± íŽëì€ë„Œ ìì íìŹ ëȘšëžì ê”ŹìĄ°ë„Œ ë°êż ì ìì”ëë€. ìëìž”, ìŽí
ì
í€ë ìì ê°ì ëȘšëžì ìì±ì ê”Źì±ìì ì§ì í©ëë€. 컀ì€í
ê”Źì± íŽëì€ìì ëȘšëžì ë§ë€ë©Ž ìČìë¶í° ììíŽìŒ í©ëë€. ëȘšëž ìì±ì ëë€íêČ ìŽêž°íëëŻëĄ ì믞 ìë êČ°êłŒë„Œ ì»ìŒë €ë©Ž 뚌ì ëȘšëžì íë šìíŹ íìê° ìì”ëë€.
-
-뚌ì [`AutoConfig`]넌 ìíŹížíêł , ìì íêł ì¶ì ìŹì íì”ë ëȘšëžì ë¶ëŹì€ìžì. [`AutoConfig.from_pretrained`]ìì ìŽí
ì
í€ë ì ê°ì ìì±ì ëłêČœí ì ìì”ëë€.
-
-```py
->>> from transformers import AutoConfig
-
->>> my_config = AutoConfig.from_pretrained("distilbert-base-uncased", n_heads=12)
-```
-
-
-
-[`AutoModel.from_config`]넌 ìŹì©íìŹ ì»€ì€í
ê”Źì±ëëĄ ëȘšëžì ìì±í©ëë€.
-
-```py
->>> from transformers import AutoModel
-
->>> my_model = AutoModel.from_config(my_config)
-```
-
-
-[`TFAutoModel.from_config`]넌 ìŹì©íìŹ ì»€ì€í
ê”Źì±ëëĄ ëȘšëžì ìì±í©ëë€.
-
-```py
->>> from transformers import TFAutoModel
-
->>> my_model = TFAutoModel.from_config(my_config)
-```
-
-
-
-컀ì€í
ê”Źì±ì ìì±íë ë°©ëČì ëí ììží ëŽì©ì [컀ì€í
ìí€í
ìČ ë§ë€êž°](./create_a_model) ê°ìŽë넌 ì°žêł íìžì.
-
-## Trainer - PyTorchì ì”ì íë íë š ë°ëł” 룚í[[trainer-a-pytorch-optimized-training-loop]]
-
-ëȘšë ëȘšëžì [`torch.nn.Module`](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)ìŽìŽì ëë€ìì íë š ë°ëł” 룚íì ìŹì©í ì ìì”ëë€. ìŹì©ìê° ì§ì íë š ë°ëł” 룚í넌 ìì±íŽë ëì§ë§, đ€ Transformersë PyTorchì© [`Trainer`] íŽëì€ë„Œ ì êł”í©ëë€. êž°ëłžì ìž íë š ë°í 룚íê° íŹíšëìŽ ìêł , ë¶ì° íë šìŽë íŒí© ì ë°ë ë±ì ì¶ê° êž°ë„ë ìì”ëë€.
-
-íì€íŹì ë°ëŒ ë€ë„Žì§ë§, ìŒë°ì ìŒëĄ ë€ì ë§€ê°ëłì넌 [`Trainer`]ì ì ëŹí êČì
ëë€.
-
-1. [`PreTrainedModel`] ëë [`torch.nn.Module`](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)ëĄ ììí©ëë€.
-
- ```py
- >>> from transformers import AutoModelForSequenceClassification
-
- >>> model = AutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased")
- ```
-
-2. [`TrainingArguments`]ëĄ íì”ë„ , ë°°ìč íŹêž°ë íë ší epoch ìì ê°ìŽ ëȘšëžì íìŽíŒíëŒëŻží°ë„Œ ìĄ°ì í©ëë€. êž°ëłžê°ì íë š ìžì넌 ì í ì§ì íì§ ìì êČœì° ìŹì©ë©ëë€.
-
- ```py
- >>> from transformers import TrainingArguments
-
- >>> training_args = TrainingArguments(
- ... output_dir="path/to/save/folder/",
- ... learning_rate=2e-5,
- ... per_device_train_batch_size=8,
- ... per_device_eval_batch_size=8,
- ... num_train_epochs=2,
- ... )
- ```
-
-3. í íŹëìŽì , íčì§ì¶ì¶êž°(feature extractor), ì ìČëŠŹêž°(processor) íŽëì€ ë±ìŒëĄ ì ìČëŠŹë„Œ ìíí©ëë€.
-
- ```py
- >>> from transformers import AutoTokenizer
-
- >>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
- ```
-
-4. ë°ìŽí°ì
넌 ì ìŹí©ëë€.
-
- ```py
- >>> from datasets import load_dataset
-
- >>> dataset = load_dataset("rotten_tomatoes") # doctest: +IGNORE_RESULT
- ```
-
-5. ë°ìŽí°ì
ì í í°ííë íšì넌 ë§ë€êł [`~datasets.Dataset.map`]ìŒëĄ ì ìČŽ ë°ìŽí°ì
ì ì ì©ìí”ëë€.
-
- ```py
- >>> def tokenize_dataset(dataset):
- ... return tokenizer(dataset["text"])
-
-
- >>> dataset = dataset.map(tokenize_dataset, batched=True)
- ```
-
-6. [`DataCollatorWithPadding`]ëĄ ë°ìŽí°ì
ìŒëĄë¶í° íëłžìŒëĄ ìŒì ë°°ìč넌 ë§ëëë€.
-
- ```py
- >>> from transformers import DataCollatorWithPadding
-
- >>> data_collator = DataCollatorWithPadding(tokenizer=tokenizer)
- ```
-
-ìŽì ìì ëȘšë íŽëì€ë„Œ [`Trainer`]ëĄ ëȘšìŒìžì.
-
-```py
->>> from transformers import Trainer
-
->>> trainer = Trainer(
-... model=model,
-... args=training_args,
-... train_dataset=dataset["train"],
-... eval_dataset=dataset["test"],
-... tokenizer=tokenizer,
-... data_collator=data_collator,
-... ) # doctest: +SKIP
-```
-
-ì€ëčëììŒë©Ž [`~Trainer.train`]ìŒëĄ íë šì ììíìžì.
-
-```py
->>> trainer.train() # doctest: +SKIP
-```
-
-
-
-sequence-to-sequence ëȘšëžì ìŹì©íë (ëČììŽë ììœ ê°ì) íì€íŹì êČœì° [`Seq2SeqTrainer`]ì [`Seq2SeqTrainingArguments`] íŽëì€ë„Œ ëì ìŹì©íìêž° ë°ëëë€.
-
-
-
-[`Trainer`] ëŽë¶ì ë©ìë넌 ê”Źí ìì(subclassing)íŽì íë š ë°ëł” 룚í넌 ê°ìĄ°í ìë ìì”ëë€. ìŽëŹë©Ž loss íšì, optimizer, scheduler ë±ì êž°ë„ë ê°ìĄ°í ì ìì”ëë€. ìŽë€ ë©ìë넌 ê”Źí ììí ì ìëì§ ììëłŽë €ë©Ž [`Trainer`]넌 ì°žêł íìžì.
-
-íë š ë°ëł” 룚í넌 ê°ìĄ°íë ë€ë„ž ë°©ëČì [Callbacks](./main_classes/callbacks)넌 ìŹì©íë êČì
ëë€. CallbacksëĄ ë€ë„ž ëŒìŽëžëŹëŠŹì í”í©íêł , íë š ë°ëł” 룚í넌 ììëĄ ìČŽíŹíìŹ ì§í ìí©ì ëłŽêł ë°ê±°ë, íë šì ìĄ°êž°ì ì€ëší ì ìì”ëë€. Callbacksì íë š ë°ëł” 룚í ììČŽë„Œ ì í ìì íì§ ìì”ëë€. ë§ìœ loss íšì ë±ì ê°ìĄ°íêł ì¶ë€ë©Ž [`Trainer`]넌 ê”Źí ììíŽìŒë§ í©ëë€.
-
-## TensorFlowëĄ íë šìí€êž°[[train-with-tensorflow]]
-
-ëȘšë ëȘšëžì [`tf.keras.Model`](https://www.tensorflow.org/api_docs/python/tf/keras/Model)ìŽìŽì [Keras](https://keras.io/) API넌 í”íŽ TensorFlowìì íë šìíŹ ì ìì”ëë€. đ€ Transformersìì ë°ìŽí°ì
넌 `tf.data.Dataset` ííëĄ ìœêČ ì ìŹí ì ìë [`~TFPreTrainedModel.prepare_tf_dataset`] ë©ìë넌 ì êł”íêž° ë돞ì, Kerasì [`compile`](https://keras.io/api/models/model_training_apis/#compile-method) ë° [`fit`](https://www.tensorflow.org/api_docs/python/tf/keras/Model) ë©ìëëĄ ìŠì íë šì ììí ì ìì”ëë€.
-
-1. [`TFPreTrainedModel`] ëë [`tf.keras.Model`](https://www.tensorflow.org/api_docs/python/tf/keras/Model)ëĄ ììí©ëë€.
-
- ```py
- >>> from transformers import TFAutoModelForSequenceClassification
-
- >>> model = TFAutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased")
- ```
-
-2. í íŹëìŽì , íčì§ì¶ì¶êž°(feature extractor), ì ìČëŠŹêž°(processor) íŽëì€ ë±ìŒëĄ ì ìČëŠŹë„Œ ìíí©ëë€.
-
- ```py
- >>> from transformers import AutoTokenizer
-
- >>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
- ```
-
-3. ë°ìŽí°ì
ì í í°ííë íšì넌 ë§ëëë€.
-
- ```py
- >>> def tokenize_dataset(dataset):
- ... return tokenizer(dataset["text"]) # doctest: +SKIP
- ```
-
-4. [`~datasets.Dataset.map`]ìŒëĄ ì ìČŽ ë°ìŽí°ì
ì ì íšì넌 ì ì©ìíš ë€ì, ë°ìŽí°ì
êłŒ í íŹëìŽì 넌 [`~TFPreTrainedModel.prepare_tf_dataset`]ëĄ ì ëŹí©ëë€. ë°°ìč íŹêž°ë„Œ ëłêČœíŽëłŽê±°ë ë°ìŽí°ì
넌 ììŽëŽë ìąì”ëë€.
-
- ```py
- >>> dataset = dataset.map(tokenize_dataset) # doctest: +SKIP
- >>> tf_dataset = model.prepare_tf_dataset(
- ... dataset, batch_size=16, shuffle=True, tokenizer=tokenizer
- ... ) # doctest: +SKIP
- ```
-
-5. ì€ëčëììŒë©Ž `compile`êłŒ `fit`ìŒëĄ íë šì ììíìžì.
-
- ```py
- >>> from tensorflow.keras.optimizers import Adam
-
- >>> model.compile(optimizer=Adam(3e-5))
- >>> model.fit(dataset) # doctest: +SKIP
- ```
-
-## ìŽì ëŹŽìŒ í멎 ë êčì?[[whats-next]]
-
-đ€ Transformers ëëŹëłŽêž°ë„Œ ëȘšë ìœìŒì
šë€ë©Ž, ê°ìŽë넌 í”íŽ íčì êž°ì ì ë°°ìž ì ììŽì. ì넌 ë€ìŽ ì»€ì€í
ëȘšëžì ìì±íë ë°©ëČ, íì€íŹì© ëȘšëžì íìžíëíë ë°©ëČ, ì€íŹëŠœížëĄ ëȘšëžì íë šìí€ë ë°©ëČ ë±ìŽ ìì”ëë€. đ€ Transformersì í”ìŹ ê°ë
ì ëíŽ ììží ììëłŽë €ë©Ž ì»€íŒ í ìì ë§ì ë€ ê°ë
ê°ìŽë넌 ìŽíŽëłŽì
ë ìąì”ëë€!
diff --git a/docs/source/ko/run_scripts.md b/docs/source/ko/run_scripts.md
new file mode 100644
index 000000000000..c1af1677183b
--- /dev/null
+++ b/docs/source/ko/run_scripts.md
@@ -0,0 +1,375 @@
+
+
+# ì€íŹëŠœížëĄ ì€ííêž°[[train-with-a-script]]
+
+đ€ Transformers ë
žížë¶êłŒ íšê» [PyTorch](https://github.com/huggingface/transformers/tree/main/examples/pytorch), [TensorFlow](https://github.com/huggingface/transformers/tree/main/examples/tensorflow), ëë [JAX/Flax](https://github.com/huggingface/transformers/tree/main/examples/flax)넌 ìŹì©íŽ íčì íì€íŹì ëí ëȘšëžì íë šíë ë°©ëČì 볎ìŹìŁŒë ìì ì€íŹëŠœížë ìì”ëë€.
+
+ëí [ì°ê”Ź íëĄì íž](https://github.com/huggingface/transformers/tree/main/examples/research_projects) ë° [ë ê±°ì ìì ](https://github.com/huggingface/transformers/tree/main/examples/legacy)ìì ëë¶ë¶ ì»€ëź€ëí°ìì ì êł”í ì€íŹëŠœížë„Œ ì°Ÿì ì ìì”ëë€.
+ìŽëŹí ì€íŹëŠœížë ì ê·čì ìŒëĄ ì ì§ êŽëŠŹëì§ ììŒë©° ì”ì ëČì ì ëŒìŽëžëŹëŠŹì ížíëì§ ìì ê°ë„ì±ìŽ ëì íčì ëČì ì đ€ Transformers넌 íìëĄ í©ëë€.
+
+ìì ì€íŹëŠœížê° ëȘšë 돞ì ìì ë°ëĄ ìëíë êČì ìëë©°, íŽêȰíë €ë 돞ì ì ë§êČ ì€íŹëŠœížë„Œ ëłêČœíŽìŒ í ìë ìì”ëë€.
+ìŽë„Œ ìíŽ ëë¶ë¶ì ì€íŹëŠœížìë ë°ìŽí° ì ìČ늏 ë°©ëČìŽ ëìììŽ íìì ë°ëŒ ìì í ì ìì”ëë€.
+
+ìì ì€íŹëŠœížì ê”Źííêł ì¶ì êž°ë„ìŽ ììŒë©Ž pull request넌 ì ì¶íêž° ì ì [íŹëŒ](https://discuss.huggingface.co/) ëë [ìŽì](https://github.com/huggingface/transformers/issues)ìì ë
ŒìíŽ ìŁŒìžì.
+ëČê·ž ìì ì íìíì§ë§ ê°ë
ì±ì íŹìí멎ìêčì§ ë ë§ì êž°ë„ì ì¶ê°íë pull requestë ëłí©(merge)íì§ ìì ê°ë„ì±ìŽ ëì”ëë€.
+
+ìŽ ê°ìŽëììë [PyTorch](https://github.com/huggingface/transformers/tree/main/examples/pytorch/summarization) ë° [TensorFlow](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/summarization)ìì ììœ íë šíë
+ ì€íŹëŠœíž ìì 넌 ì€ííë ë°©ëČì ì€ëȘ
í©ëë€.
+íčëłí ì€ëȘ
ìŽ ìë í ëȘšë ìì ë ë íë ììíŹ ëȘšëìì ìëí êČìŒëĄ ììë©ëë€.
+
+## ì€ì íêž°[[setup]]
+
+ì”ì ëČì ì ìì ì€íŹëŠœížë„Œ ì±êł”ì ìŒëĄ ì€ííë €ë©Ž ì ê°ì íêČœìì **ìì€ëĄë¶í° đ€ Transformers넌 ì€ìč**íŽìŒ í©ëë€:
+
+```bash
+git clone https://github.com/huggingface/transformers
+cd transformers
+pip install .
+```
+
+ìŽì ëČì ì ìì ì€íŹëŠœížë„Œ ëłŽë €ë©Ž ìë í êžì íŽëŠíìžì:
+
+
+ ìŽì ëČì ì đ€ Transformers ìì
+
+
+
+ê·žëŠŹêł ë€ìêłŒ ê°ìŽ ëł”ì (clone)íŽìš đ€ Transformers ëČì ì íčì ëČì (ì: v3.5.1)ìŒëĄ ì ííìžì:
+
+```bash
+git checkout tags/v3.5.1
+```
+
+ìŹë°ë„ž ëŒìŽëžëŹëŠŹ ëČì ì ì€ì í í ìíë ìì íŽëëĄ ìŽëíìŹ ìì ëłëĄ ëŒìŽëžëŹëŠŹì ëí ìê”Ź ìŹí(requirements)ì ì€ìčí©ëë€:
+
+```bash
+pip install -r requirements.txt
+```
+
+## ì€íŹëŠœíž ì€ííêž°[[run-a-script]]
+
+
+
+ìì ì€íŹëŠœížë đ€ [Datasets](https://huggingface.co/docs/datasets/) ëŒìŽëžëŹëŠŹìì ë°ìŽí° ìžížë„Œ ë€ìŽëĄëíêł ì ìČ늏í©ëë€.
+ê·žë° ë€ì ì€íŹëŠœížë ììœ êž°ë„ì ì§ìíë ìí€í
ìČìì [Trainer](https://huggingface.co/docs/transformers/main_classes/trainer)넌 ìŹì©íìŹ ë°ìŽí° ìžížë„Œ ëŻžìž ìĄ°ì í©ëë€.
+ë€ì ìë [CNN/DailyMail](https://huggingface.co/datasets/cnn_dailymail) ë°ìŽí° ìžížìì [T5-small](https://huggingface.co/t5-small)ì ëŻžìž ìĄ°ì í©ëë€.
+T5 ëȘšëžì íë š ë°©ìì ë°ëŒ ì¶ê° `source_prefix` ìžìê° íìíë©°, ìŽ í륏íížë ììœ ìì
ìì T5ì ìë €ì€ëë€.
+
+```bash
+python examples/pytorch/summarization/run_summarization.py \
+ --model_name_or_path t5-small \
+ --do_train \
+ --do_eval \
+ --dataset_name cnn_dailymail \
+ --dataset_config "3.0.0" \
+ --source_prefix "summarize: " \
+ --output_dir /tmp/tst-summarization \
+ --per_device_train_batch_size=4 \
+ --per_device_eval_batch_size=4 \
+ --overwrite_output_dir \
+ --predict_with_generate
+```
+
+
+ìì ì€íŹëŠœížë đ€ [Datasets](https://huggingface.co/docs/datasets/) ëŒìŽëžëŹëŠŹìì ë°ìŽí° ìžížë„Œ ë€ìŽëĄëíêł ì ìČ늏í©ëë€.
+ê·žë° ë€ì ì€íŹëŠœížë ììœ êž°ë„ì ì§ìíë ìí€í
ìČìì Keras넌 ìŹì©íìŹ ë°ìŽí° ìžížë„Œ ëŻžìž ìĄ°ì í©ëë€.
+ë€ì ìë [CNN/DailyMail](https://huggingface.co/datasets/cnn_dailymail) ë°ìŽí° ìžížìì [T5-small](https://huggingface.co/t5-small)ì ëŻžìž ìĄ°ì í©ëë€.
+T5 ëȘšëžì íë š ë°©ìì ë°ëŒ ì¶ê° `source_prefix` ìžìê° íìíë©°, ìŽ í륏íížë ììœ ìì
ìì T5ì ìë €ì€ëë€.
+```bash
+python examples/tensorflow/summarization/run_summarization.py \
+ --model_name_or_path t5-small \
+ --dataset_name cnn_dailymail \
+ --dataset_config "3.0.0" \
+ --output_dir /tmp/tst-summarization \
+ --per_device_train_batch_size 8 \
+ --per_device_eval_batch_size 16 \
+ --num_train_epochs 3 \
+ --do_train \
+ --do_eval
+```
+
+
+
+## íŒí© ì ë°ë(mixed precision)ëĄ ë¶ì° íë šíêž°[[distributed-training-and-mixed-precision]]
+
+[Trainer](https://huggingface.co/docs/transformers/main_classes/trainer) íŽëì€ë ë¶ì° íë šêłŒ íŒí© ì ë°ë(mixed precision)넌 ì§ìíëŻëĄ ì€íŹëŠœížììë ìŹì©í ì ìì”ëë€.
+ìŽ ë ê°ì§ êž°ë„ì ëȘšë íì±ííë €ë©Ž ë€ì ë ê°ì§ë„Œ ì€ì íŽìŒ í©ëë€:
+
+- `fp16` ìžì넌 ì¶ê°íŽ íŒí© ì ë°ë(mixed precision)넌 íì±íí©ëë€.
+- `nproc_per_node` ìžì넌 ì¶ê°íŽ ìŹì©í GPU ê°ì넌 ì€ì í©ëë€.
+
+```bash
+python -m torch.distributed.launch \
+ --nproc_per_node 8 pytorch/summarization/run_summarization.py \
+ --fp16 \
+ --model_name_or_path t5-small \
+ --do_train \
+ --do_eval \
+ --dataset_name cnn_dailymail \
+ --dataset_config "3.0.0" \
+ --source_prefix "summarize: " \
+ --output_dir /tmp/tst-summarization \
+ --per_device_train_batch_size=4 \
+ --per_device_eval_batch_size=4 \
+ --overwrite_output_dir \
+ --predict_with_generate
+```
+
+TensorFlow ì€íŹëŠœížë ë¶ì° íë šì ìíŽ [`MirroredStrategy`](https://www.tensorflow.org/guide/distributed_training#mirroredstrategy)넌 íì©íë©°, íë š ì€íŹëŠœížì ìžì넌 ì¶ê°í íìê° ìì”ëë€.
+ë€ì€ GPU íêČœìŽëŒë©Ž, TensorFlow ì€íŹëŠœížë êž°ëłžì ìŒëĄ ìŹëŹ ê°ì GPU넌 ìŹì©í©ëë€.
+
+## TPU ììì ì€íŹëŠœíž ì€ííêž°[[run-a-script-on-a-tpu]]
+
+
+
+Tensor Processing Units (TPUs)ë ì±ë„ì ê°ìííêž° ìíŽ íčëłí ì€êłëìì”ëë€.
+PyTorchë [XLA](https://www.tensorflow.org/xla) ë„ëŹë 컎íìŒëŹì íšê» TPU넌 ì§ìí©ëë€(ììží ëŽì©ì [ìŹêž°](https://github.com/pytorch/xla/blob/master/README.md) ì°žìĄ°).
+TPU넌 ìŹì©íë €ë©Ž `xla_spawn.py` ì€íŹëŠœížë„Œ ì€ííêł `num_cores` ìžì넌 ìŹì©íìŹ ìŹì©íë €ë TPU ìœìŽ ì넌 ì€ì í©ëë€.
+
+```bash
+python xla_spawn.py --num_cores 8 \
+ summarization/run_summarization.py \
+ --model_name_or_path t5-small \
+ --do_train \
+ --do_eval \
+ --dataset_name cnn_dailymail \
+ --dataset_config "3.0.0" \
+ --source_prefix "summarize: " \
+ --output_dir /tmp/tst-summarization \
+ --per_device_train_batch_size=4 \
+ --per_device_eval_batch_size=4 \
+ --overwrite_output_dir \
+ --predict_with_generate
+```
+
+
+Tensor Processing Units (TPUs)ë ì±ë„ì ê°ìííêž° ìíŽ íčëłí ì€êłëìì”ëë€.
+TensorFlow ì€íŹëŠœížë TPU넌 íë šì ìŹì©íêž° ìíŽ [`TPUStrategy`](https://www.tensorflow.org/guide/distributed_training#tpustrategy)넌 íì©í©ëë€.
+TPU넌 ìŹì©íë €ë©Ž TPU 늏ìì€ì ìŽëŠì `tpu` ìžìì ì ëŹí©ëë€.
+
+```bash
+python run_summarization.py \
+ --tpu name_of_tpu_resource \
+ --model_name_or_path t5-small \
+ --dataset_name cnn_dailymail \
+ --dataset_config "3.0.0" \
+ --output_dir /tmp/tst-summarization \
+ --per_device_train_batch_size 8 \
+ --per_device_eval_batch_size 16 \
+ --num_train_epochs 3 \
+ --do_train \
+ --do_eval
+```
+
+
+
+## đ€ AccelerateëĄ ì€íŹëŠœíž ì€ííêž°[[run-a-script-with-accelerate]]
+
+đ€ [Accelerate](https://huggingface.co/docs/accelerate)ë PyTorch íë š êłŒì ì ëí ìì í ê°ìì±ì ì ì§í멎ì ìŹëŹ ì íì ì€ì (CPU ì ì©, ë€ì€ GPU, TPU)ìì ëȘšëžì íë ší ì ìë í”í© ë°©ëČì ì êł”íë PyTorch ì ì© ëŒìŽëžëŹëŠŹì
ëë€.
+đ€ Accelerateê° ì€ìčëìŽ ìëì§ íìžíìžì:
+
+> ì°žêł : Accelerateë ëč 넎êČ ê°ë° ì€ìŽëŻëĄ ì€íŹëŠœížë„Œ ì€ííë €ë©Ž accelerate넌 ì€ìčíŽìŒ í©ëë€.
+```bash
+pip install git+https://github.com/huggingface/accelerate
+```
+
+`run_summarization.py` ì€íŹëŠœíž ëì `run_summarization_no_trainer.py` ì€íŹëŠœížë„Œ ìŹì©íŽìŒ í©ëë€.
+đ€ Accelerate íŽëì€ê° ì§ìëë ì€íŹëŠœížë íŽëì `task_no_trainer.py` íìŒìŽ ìì”ëë€.
+ë€ì ëȘ
ë čì ì€ííìŹ ê”Źì± íìŒì ìì±íêł ì ì„í©ëë€:
+```bash
+accelerate config
+```
+
+ì€ì ì í
ì€ížíìŹ ìŹë°ë„ŽêČ ê”Źì±ëìëì§ íìží©ëë€:
+
+```bash
+accelerate test
+```
+
+ìŽì íë šì ììí ì€ëčê° ëìì”ëë€:
+
+```bash
+accelerate launch run_summarization_no_trainer.py \
+ --model_name_or_path t5-small \
+ --dataset_name cnn_dailymail \
+ --dataset_config "3.0.0" \
+ --source_prefix "summarize: " \
+ --output_dir ~/tmp/tst-summarization
+```
+
+## ìŹì©ì ì ì ë°ìŽí° ìžíž ìŹì©íêž°[[use-a-custom-dataset]]
+
+ììœ ì€íŹëŠœížë ìŹì©ì ì§ì ë°ìŽí° ìžížê° CSV ëë JSON íìŒìž êČœì° ì§ìí©ëë€.
+ìŹì©ì ì§ì ë°ìŽí° ìžížë„Œ ìŹì©íë êČœì°ìë ëȘ ê°ì§ ì¶ê° ìžì넌 ì§ì íŽìŒ í©ëë€:
+
+- `train_file`êłŒ `validation_file`ì íë š ë° êČìŠ íìŒì êČœëĄë„Œ ì§ì í©ëë€.
+- `text_column`ì ììœí ì
ë „ í
ì€ížì
ëë€.
+- `summary_column`ì ì¶ë „í ëì í
ì€ížì
ëë€.
+
+ìŹì©ì ì§ì ë°ìŽí° ìžížë„Œ ìŹì©íë ììœ ì€íŹëŠœížë ë€ìêłŒ ê°ì”ëë€:
+
+```bash
+python examples/pytorch/summarization/run_summarization.py \
+ --model_name_or_path t5-small \
+ --do_train \
+ --do_eval \
+ --train_file path_to_csv_or_jsonlines_file \
+ --validation_file path_to_csv_or_jsonlines_file \
+ --text_column text_column_name \
+ --summary_column summary_column_name \
+ --source_prefix "summarize: " \
+ --output_dir /tmp/tst-summarization \
+ --overwrite_output_dir \
+ --per_device_train_batch_size=4 \
+ --per_device_eval_batch_size=4 \
+ --predict_with_generate
+```
+
+## ì€íŹëŠœíž í
ì€ížíêž°[[test-a-script]]
+
+ì ìČŽ ë°ìŽí° ìžížë„Œ ëììŒëĄ íë šì ìëŁíëë° êœ€ ì€ë ìê°ìŽ ê±žëŠŹêž° ë돞ì, ìì ë°ìŽí° ìžížìì ëȘšë êČìŽ ììëëĄ ì€íëëì§ íìžíë êČìŽ ìąì”ëë€.
+
+ë€ì ìžì넌 ìŹì©íìŹ ë°ìŽí° ìžížë„Œ ì”ë ìí ìëĄ ìëŒë
ëë€:
+- `max_train_samples`
+- `max_eval_samples`
+- `max_predict_samples`
+
+```bash
+python examples/pytorch/summarization/run_summarization.py \
+ --model_name_or_path t5-small \
+ --max_train_samples 50 \
+ --max_eval_samples 50 \
+ --max_predict_samples 50 \
+ --do_train \
+ --do_eval \
+ --dataset_name cnn_dailymail \
+ --dataset_config "3.0.0" \
+ --source_prefix "summarize: " \
+ --output_dir /tmp/tst-summarization \
+ --per_device_train_batch_size=4 \
+ --per_device_eval_batch_size=4 \
+ --overwrite_output_dir \
+ --predict_with_generate
+```
+
+ëȘšë ìì ì€íŹëŠœížê° `max_predict_samples` ìžì넌 ì§ìíì§ë ìì”ëë€.
+ì€íŹëŠœížê° ìŽ ìžì넌 ì§ìíëì§ íì€íì§ ìì êČœì° `-h` ìžì넌 ì¶ê°íìŹ íìžíìžì:
+
+```bash
+examples/pytorch/summarization/run_summarization.py -h
+```
+
+## ìČŽíŹíŹìžíž(checkpoint)ìì íë š ìŽìŽì íêž°[[resume-training-from-checkpoint]]
+
+ë ë€ë„ž ì ì©í ì”ì
ì ìŽì ìČŽíŹíŹìžížìì íë šì ìŹê°íë êČì
ëë€.
+ìŽë êČ í멎 íë šìŽ ì€ëšëëëŒë ìČìë¶í° ë€ì ììíì§ ìêł ì€ëší ë¶ë¶ë¶í° ë€ì ììí ì ìì”ëë€.
+ìČŽíŹíŹìžížìì íë šì ìŹê°íë ë°©ëČìë ë ê°ì§ê° ìì”ëë€.
+
+ìČ« ëČì§žë `output_dir previous_output_dir` ìžì넌 ìŹì©íìŹ `output_dir`ì ì ì„ë ì”ì ìČŽíŹíŹìžížë¶í° íë šì ìŹê°íë ë°©ëČì
ëë€.
+ìŽ êČœì° `overwrite_output_dir`ì ì ê±°íŽìŒ í©ëë€:
+```bash
+python examples/pytorch/summarization/run_summarization.py
+ --model_name_or_path t5-small \
+ --do_train \
+ --do_eval \
+ --dataset_name cnn_dailymail \
+ --dataset_config "3.0.0" \
+ --source_prefix "summarize: " \
+ --output_dir /tmp/tst-summarization \
+ --per_device_train_batch_size=4 \
+ --per_device_eval_batch_size=4 \
+ --output_dir previous_output_dir \
+ --predict_with_generate
+```
+
+ë ëČì§žë `resume_from_checkpoint path_to_specific_checkpoint` ìžì넌 ìŹì©íìŹ íčì ìČŽíŹíŹìžíž íŽëìì íë šì ìŹê°íë ë°©ëČì
ëë€.
+
+```bash
+python examples/pytorch/summarization/run_summarization.py
+ --model_name_or_path t5-small \
+ --do_train \
+ --do_eval \
+ --dataset_name cnn_dailymail \
+ --dataset_config "3.0.0" \
+ --source_prefix "summarize: " \
+ --output_dir /tmp/tst-summarization \
+ --per_device_train_batch_size=4 \
+ --per_device_eval_batch_size=4 \
+ --overwrite_output_dir \
+ --resume_from_checkpoint path_to_specific_checkpoint \
+ --predict_with_generate
+```
+
+## ëȘšëž êł”ì íêž°[[share-your-model]]
+
+ëȘšë ì€íŹëŠœížë ì”ìą
ëȘšëžì [Model Hub](https://huggingface.co/models)ì ì
ëĄëí ì ìì”ëë€.
+ììíêž° ì ì Hugging Faceì ëĄê·žìžíëì§ íìžíìžì:
+```bash
+huggingface-cli login
+```
+
+ê·žë° ë€ì ì€íŹëŠœížì `push_to_hub` ìžì넌 ì¶ê°í©ëë€.
+ìŽ ìžìë Hugging Face ìŹì©ì ìŽëŠêłŒ `output_dir`ì ì§ì ë íŽë ìŽëŠìŒëĄ ì ì„ì넌 ìì±í©ëë€.
+
+ì ì„ìì íčì ìŽëŠì ì§ì íë €ë©Ž `push_to_hub_model_id` ìžì넌 ìŹì©íìŹ ì¶ê°í©ëë€.
+ì ì„ìë ë€ìì€íìŽì€ ìëì ìëìŒëĄ ëìŽë©ëë€.
+ë€ì ìë íčì ì ì„ì ìŽëŠìŒëĄ ëȘšëžì ì
ëĄëíë ë°©ëČì
ëë€:
+
+```bash
+python examples/pytorch/summarization/run_summarization.py
+ --model_name_or_path t5-small \
+ --do_train \
+ --do_eval \
+ --dataset_name cnn_dailymail \
+ --dataset_config "3.0.0" \
+ --source_prefix "summarize: " \
+ --push_to_hub \
+ --push_to_hub_model_id finetuned-t5-cnn_dailymail \
+ --output_dir /tmp/tst-summarization \
+ --per_device_train_batch_size=4 \
+ --per_device_eval_batch_size=4 \
+ --overwrite_output_dir \
+ --predict_with_generate
+```
\ No newline at end of file
diff --git a/docs/source/ko/run_scripts.mdx b/docs/source/ko/run_scripts.mdx
deleted file mode 100644
index e829198b36fe..000000000000
--- a/docs/source/ko/run_scripts.mdx
+++ /dev/null
@@ -1,371 +0,0 @@
-
-
-# ì€íŹëŠœížëĄ ì€ííêž°[[train-with-a-script]]
-
-đ€ Transformers ë
žížë¶êłŒ íšê» [PyTorch](https://github.com/huggingface/transformers/tree/main/examples/pytorch), [TensorFlow](https://github.com/huggingface/transformers/tree/main/examples/tensorflow), ëë [JAX/Flax](https://github.com/huggingface/transformers/tree/main/examples/flax)넌 ìŹì©íŽ íčì íì€íŹì ëí ëȘšëžì íë šíë ë°©ëČì 볎ìŹìŁŒë ìì ì€íŹëŠœížë ìì”ëë€.
-
-ëí [ì°ê”Ź íëĄì íž](https://github.com/huggingface/transformers/tree/main/examples/research_projects) ë° [ë ê±°ì ìì ](https://github.com/huggingface/transformers/tree/main/examples/legacy)ìì ëë¶ë¶ ì»€ëź€ëí°ìì ì êł”í ì€íŹëŠœížë„Œ ì°Ÿì ì ìì”ëë€.
-ìŽëŹí ì€íŹëŠœížë ì ê·čì ìŒëĄ ì ì§ êŽëŠŹëì§ ììŒë©° ì”ì ëČì ì ëŒìŽëžëŹëŠŹì ížíëì§ ìì ê°ë„ì±ìŽ ëì íčì ëČì ì đ€ Transformers넌 íìëĄ í©ëë€.
-
-ìì ì€íŹëŠœížê° ëȘšë 돞ì ìì ë°ëĄ ìëíë êČì ìëë©°, íŽêȰíë €ë 돞ì ì ë§êČ ì€íŹëŠœížë„Œ ëłêČœíŽìŒ í ìë ìì”ëë€.
-ìŽë„Œ ìíŽ ëë¶ë¶ì ì€íŹëŠœížìë ë°ìŽí° ì ìČ늏 ë°©ëČìŽ ëìììŽ íìì ë°ëŒ ìì í ì ìì”ëë€.
-
-ìì ì€íŹëŠœížì ê”Źííêł ì¶ì êž°ë„ìŽ ììŒë©Ž pull request넌 ì ì¶íêž° ì ì [íŹëŒ](https://discuss.huggingface.co/) ëë [ìŽì](https://github.com/huggingface/transformers/issues)ìì ë
ŒìíŽ ìŁŒìžì.
-ëČê·ž ìì ì íìíì§ë§ ê°ë
ì±ì íŹìí멎ìêčì§ ë ë§ì êž°ë„ì ì¶ê°íë pull requestë ëłí©(merge)íì§ ìì ê°ë„ì±ìŽ ëì”ëë€.
-
-ìŽ ê°ìŽëììë [PyTorch](https://github.com/huggingface/transformers/tree/main/examples/pytorch/summarization) ë° [TensorFlow](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/summarization)ìì ììœ íë šíë
- ì€íŹëŠœíž ìì 넌 ì€ííë ë°©ëČì ì€ëȘ
í©ëë€.
-íčëłí ì€ëȘ
ìŽ ìë í ëȘšë ìì ë ë íë ììíŹ ëȘšëìì ìëí êČìŒëĄ ììë©ëë€.
-
-## ì€ì íêž°[[setup]]
-
-ì”ì ëČì ì ìì ì€íŹëŠœížë„Œ ì±êł”ì ìŒëĄ ì€ííë €ë©Ž ì ê°ì íêČœìì **ìì€ëĄë¶í° đ€ Transformers넌 ì€ìč**íŽìŒ í©ëë€:
-
-```bash
-git clone https://github.com/huggingface/transformers
-cd transformers
-pip install .
-```
-
-ìŽì ëČì ì ìì ì€íŹëŠœížë„Œ ëłŽë €ë©Ž ìë í êžì íŽëŠíìžì:
-
-
- ìŽì ëČì ì đ€ Transformers ìì
-
-
-
-ê·žëŠŹêł ë€ìêłŒ ê°ìŽ ëł”ì (clone)íŽìš đ€ Transformers ëČì ì íčì ëČì (ì: v3.5.1)ìŒëĄ ì ííìžì:
-
-```bash
-git checkout tags/v3.5.1
-```
-
-ìŹë°ë„ž ëŒìŽëžëŹëŠŹ ëČì ì ì€ì í í ìíë ìì íŽëëĄ ìŽëíìŹ ìì ëłëĄ ëŒìŽëžëŹëŠŹì ëí ìê”Ź ìŹí(requirements)ì ì€ìčí©ëë€:
-
-```bash
-pip install -r requirements.txt
-```
-
-## ì€íŹëŠœíž ì€ííêž°[[run-a-script]]
-
-
-
-ìì ì€íŹëŠœížë đ€ [Datasets](https://huggingface.co/docs/datasets/) ëŒìŽëžëŹëŠŹìì ë°ìŽí° ìžížë„Œ ë€ìŽëĄëíêł ì ìČ늏í©ëë€.
-ê·žë° ë€ì ì€íŹëŠœížë ììœ êž°ë„ì ì§ìíë ìí€í
ìČìì [Trainer](https://huggingface.co/docs/transformers/main_classes/trainer)넌 ìŹì©íìŹ ë°ìŽí° ìžížë„Œ ëŻžìž ìĄ°ì í©ëë€.
-ë€ì ìë [CNN/DailyMail](https://huggingface.co/datasets/cnn_dailymail) ë°ìŽí° ìžížìì [T5-small](https://huggingface.co/t5-small)ì ëŻžìž ìĄ°ì í©ëë€.
-T5 ëȘšëžì íë š ë°©ìì ë°ëŒ ì¶ê° `source_prefix` ìžìê° íìíë©°, ìŽ í륏íížë ììœ ìì
ìì T5ì ìë €ì€ëë€.
-
-```bash
-python examples/pytorch/summarization/run_summarization.py \
- --model_name_or_path t5-small \
- --do_train \
- --do_eval \
- --dataset_name cnn_dailymail \
- --dataset_config "3.0.0" \
- --source_prefix "summarize: " \
- --output_dir /tmp/tst-summarization \
- --per_device_train_batch_size=4 \
- --per_device_eval_batch_size=4 \
- --overwrite_output_dir \
- --predict_with_generate
-```
-
-
-ìì ì€íŹëŠœížë đ€ [Datasets](https://huggingface.co/docs/datasets/) ëŒìŽëžëŹëŠŹìì ë°ìŽí° ìžížë„Œ ë€ìŽëĄëíêł ì ìČ늏í©ëë€.
-ê·žë° ë€ì ì€íŹëŠœížë ììœ êž°ë„ì ì§ìíë ìí€í
ìČìì Keras넌 ìŹì©íìŹ ë°ìŽí° ìžížë„Œ ëŻžìž ìĄ°ì í©ëë€.
-ë€ì ìë [CNN/DailyMail](https://huggingface.co/datasets/cnn_dailymail) ë°ìŽí° ìžížìì [T5-small](https://huggingface.co/t5-small)ì ëŻžìž ìĄ°ì í©ëë€.
-T5 ëȘšëžì íë š ë°©ìì ë°ëŒ ì¶ê° `source_prefix` ìžìê° íìíë©°, ìŽ í륏íížë ììœ ìì
ìì T5ì ìë €ì€ëë€.
-```bash
-python examples/tensorflow/summarization/run_summarization.py \
- --model_name_or_path t5-small \
- --dataset_name cnn_dailymail \
- --dataset_config "3.0.0" \
- --output_dir /tmp/tst-summarization \
- --per_device_train_batch_size 8 \
- --per_device_eval_batch_size 16 \
- --num_train_epochs 3 \
- --do_train \
- --do_eval
-```
-
-
-
-## íŒí© ì ë°ë(mixed precision)ëĄ ë¶ì° íë šíêž°[[distributed-training-and-mixed-precision]]
-
-[Trainer](https://huggingface.co/docs/transformers/main_classes/trainer) íŽëì€ë ë¶ì° íë šêłŒ íŒí© ì ë°ë(mixed precision)넌 ì§ìíëŻëĄ ì€íŹëŠœížììë ìŹì©í ì ìì”ëë€.
-ìŽ ë ê°ì§ êž°ë„ì ëȘšë íì±ííë €ë©Ž ë€ì ë ê°ì§ë„Œ ì€ì íŽìŒ í©ëë€:
-
-- `fp16` ìžì넌 ì¶ê°íŽ íŒí© ì ë°ë(mixed precision)넌 íì±íí©ëë€.
-- `nproc_per_node` ìžì넌 ì¶ê°íŽ ìŹì©í GPU ê°ì넌 ì€ì í©ëë€.
-
-```bash
-python -m torch.distributed.launch \
- --nproc_per_node 8 pytorch/summarization/run_summarization.py \
- --fp16 \
- --model_name_or_path t5-small \
- --do_train \
- --do_eval \
- --dataset_name cnn_dailymail \
- --dataset_config "3.0.0" \
- --source_prefix "summarize: " \
- --output_dir /tmp/tst-summarization \
- --per_device_train_batch_size=4 \
- --per_device_eval_batch_size=4 \
- --overwrite_output_dir \
- --predict_with_generate
-```
-
-TensorFlow ì€íŹëŠœížë ë¶ì° íë šì ìíŽ [`MirroredStrategy`](https://www.tensorflow.org/guide/distributed_training#mirroredstrategy)넌 íì©íë©°, íë š ì€íŹëŠœížì ìžì넌 ì¶ê°í íìê° ìì”ëë€.
-ë€ì€ GPU íêČœìŽëŒë©Ž, TensorFlow ì€íŹëŠœížë êž°ëłžì ìŒëĄ ìŹëŹ ê°ì GPU넌 ìŹì©í©ëë€.
-
-## TPU ììì ì€íŹëŠœíž ì€ííêž°[[run-a-script-on-a-tpu]]
-
-
-
-Tensor Processing Units (TPUs)ë ì±ë„ì ê°ìííêž° ìíŽ íčëłí ì€êłëìì”ëë€.
-PyTorchë [XLA](https://www.tensorflow.org/xla) ë„ëŹë 컎íìŒëŹì íšê» TPU넌 ì§ìí©ëë€(ììží ëŽì©ì [ìŹêž°](https://github.com/pytorch/xla/blob/master/README.md) ì°žìĄ°).
-TPU넌 ìŹì©íë €ë©Ž `xla_spawn.py` ì€íŹëŠœížë„Œ ì€ííêł `num_cores` ìžì넌 ìŹì©íìŹ ìŹì©íë €ë TPU ìœìŽ ì넌 ì€ì í©ëë€.
-
-```bash
-python xla_spawn.py --num_cores 8 \
- summarization/run_summarization.py \
- --model_name_or_path t5-small \
- --do_train \
- --do_eval \
- --dataset_name cnn_dailymail \
- --dataset_config "3.0.0" \
- --source_prefix "summarize: " \
- --output_dir /tmp/tst-summarization \
- --per_device_train_batch_size=4 \
- --per_device_eval_batch_size=4 \
- --overwrite_output_dir \
- --predict_with_generate
-```
-
-
-Tensor Processing Units (TPUs)ë ì±ë„ì ê°ìííêž° ìíŽ íčëłí ì€êłëìì”ëë€.
-TensorFlow ì€íŹëŠœížë TPU넌 íë šì ìŹì©íêž° ìíŽ [`TPUStrategy`](https://www.tensorflow.org/guide/distributed_training#tpustrategy)넌 íì©í©ëë€.
-TPU넌 ìŹì©íë €ë©Ž TPU 늏ìì€ì ìŽëŠì `tpu` ìžìì ì ëŹí©ëë€.
-
-```bash
-python run_summarization.py \
- --tpu name_of_tpu_resource \
- --model_name_or_path t5-small \
- --dataset_name cnn_dailymail \
- --dataset_config "3.0.0" \
- --output_dir /tmp/tst-summarization \
- --per_device_train_batch_size 8 \
- --per_device_eval_batch_size 16 \
- --num_train_epochs 3 \
- --do_train \
- --do_eval
-```
-
-
-
-## đ€ AccelerateëĄ ì€íŹëŠœíž ì€ííêž°[[run-a-script-with-accelerate]]
-
-đ€ [Accelerate](https://huggingface.co/docs/accelerate)ë PyTorch íë š êłŒì ì ëí ìì í ê°ìì±ì ì ì§í멎ì ìŹëŹ ì íì ì€ì (CPU ì ì©, ë€ì€ GPU, TPU)ìì ëȘšëžì íë ší ì ìë í”í© ë°©ëČì ì êł”íë PyTorch ì ì© ëŒìŽëžëŹëŠŹì
ëë€.
-đ€ Accelerateê° ì€ìčëìŽ ìëì§ íìžíìžì:
-
-> ì°žêł : Accelerateë ëč 넎êČ ê°ë° ì€ìŽëŻëĄ ì€íŹëŠœížë„Œ ì€ííë €ë©Ž accelerate넌 ì€ìčíŽìŒ í©ëë€.
-```bash
-pip install git+https://github.com/huggingface/accelerate
-```
-
-`run_summarization.py` ì€íŹëŠœíž ëì `run_summarization_no_trainer.py` ì€íŹëŠœížë„Œ ìŹì©íŽìŒ í©ëë€.
-đ€ Accelerate íŽëì€ê° ì§ìëë ì€íŹëŠœížë íŽëì `task_no_trainer.py` íìŒìŽ ìì”ëë€.
-ë€ì ëȘ
ë čì ì€ííìŹ ê”Źì± íìŒì ìì±íêł ì ì„í©ëë€:
-```bash
-accelerate config
-```
-
-ì€ì ì í
ì€ížíìŹ ìŹë°ë„ŽêČ ê”Źì±ëìëì§ íìží©ëë€:
-
-```bash
-accelerate test
-```
-
-ìŽì íë šì ììí ì€ëčê° ëìì”ëë€:
-
-```bash
-accelerate launch run_summarization_no_trainer.py \
- --model_name_or_path t5-small \
- --dataset_name cnn_dailymail \
- --dataset_config "3.0.0" \
- --source_prefix "summarize: " \
- --output_dir ~/tmp/tst-summarization
-```
-
-## ìŹì©ì ì ì ë°ìŽí° ìžíž ìŹì©íêž°[[use-a-custom-dataset]]
-
-ììœ ì€íŹëŠœížë ìŹì©ì ì§ì ë°ìŽí° ìžížê° CSV ëë JSON íìŒìž êČœì° ì§ìí©ëë€.
-ìŹì©ì ì§ì ë°ìŽí° ìžížë„Œ ìŹì©íë êČœì°ìë ëȘ ê°ì§ ì¶ê° ìžì넌 ì§ì íŽìŒ í©ëë€:
-
-- `train_file`êłŒ `validation_file`ì íë š ë° êČìŠ íìŒì êČœëĄë„Œ ì§ì í©ëë€.
-- `text_column`ì ììœí ì
ë „ í
ì€ížì
ëë€.
-- `summary_column`ì ì¶ë „í ëì í
ì€ížì
ëë€.
-
-ìŹì©ì ì§ì ë°ìŽí° ìžížë„Œ ìŹì©íë ììœ ì€íŹëŠœížë ë€ìêłŒ ê°ì”ëë€:
-
-```bash
-python examples/pytorch/summarization/run_summarization.py \
- --model_name_or_path t5-small \
- --do_train \
- --do_eval \
- --train_file path_to_csv_or_jsonlines_file \
- --validation_file path_to_csv_or_jsonlines_file \
- --text_column text_column_name \
- --summary_column summary_column_name \
- --source_prefix "summarize: " \
- --output_dir /tmp/tst-summarization \
- --overwrite_output_dir \
- --per_device_train_batch_size=4 \
- --per_device_eval_batch_size=4 \
- --predict_with_generate
-```
-
-## ì€íŹëŠœíž í
ì€ížíêž°[[test-a-script]]
-
-ì ìČŽ ë°ìŽí° ìžížë„Œ ëììŒëĄ íë šì ìëŁíëë° êœ€ ì€ë ìê°ìŽ ê±žëŠŹêž° ë돞ì, ìì ë°ìŽí° ìžížìì ëȘšë êČìŽ ììëëĄ ì€íëëì§ íìžíë êČìŽ ìąì”ëë€.
-
-ë€ì ìžì넌 ìŹì©íìŹ ë°ìŽí° ìžížë„Œ ì”ë ìí ìëĄ ìëŒë
ëë€:
-- `max_train_samples`
-- `max_eval_samples`
-- `max_predict_samples`
-
-```bash
-python examples/pytorch/summarization/run_summarization.py \
- --model_name_or_path t5-small \
- --max_train_samples 50 \
- --max_eval_samples 50 \
- --max_predict_samples 50 \
- --do_train \
- --do_eval \
- --dataset_name cnn_dailymail \
- --dataset_config "3.0.0" \
- --source_prefix "summarize: " \
- --output_dir /tmp/tst-summarization \
- --per_device_train_batch_size=4 \
- --per_device_eval_batch_size=4 \
- --overwrite_output_dir \
- --predict_with_generate
-```
-
-ëȘšë ìì ì€íŹëŠœížê° `max_predict_samples` ìžì넌 ì§ìíì§ë ìì”ëë€.
-ì€íŹëŠœížê° ìŽ ìžì넌 ì§ìíëì§ íì€íì§ ìì êČœì° `-h` ìžì넌 ì¶ê°íìŹ íìžíìžì:
-
-```bash
-examples/pytorch/summarization/run_summarization.py -h
-```
-
-## ìČŽíŹíŹìžíž(checkpoint)ìì íë š ìŽìŽì íêž°[[resume-training-from-checkpoint]]
-
-ë ë€ë„ž ì ì©í ì”ì
ì ìŽì ìČŽíŹíŹìžížìì íë šì ìŹê°íë êČì
ëë€.
-ìŽë êČ í멎 íë šìŽ ì€ëšëëëŒë ìČìë¶í° ë€ì ììíì§ ìêł ì€ëší ë¶ë¶ë¶í° ë€ì ììí ì ìì”ëë€.
-ìČŽíŹíŹìžížìì íë šì ìŹê°íë ë°©ëČìë ë ê°ì§ê° ìì”ëë€.
-
-ìČ« ëČì§žë `output_dir previous_output_dir` ìžì넌 ìŹì©íìŹ `output_dir`ì ì ì„ë ì”ì ìČŽíŹíŹìžížë¶í° íë šì ìŹê°íë ë°©ëČì
ëë€.
-ìŽ êČœì° `overwrite_output_dir`ì ì ê±°íŽìŒ í©ëë€:
-```bash
-python examples/pytorch/summarization/run_summarization.py
- --model_name_or_path t5-small \
- --do_train \
- --do_eval \
- --dataset_name cnn_dailymail \
- --dataset_config "3.0.0" \
- --source_prefix "summarize: " \
- --output_dir /tmp/tst-summarization \
- --per_device_train_batch_size=4 \
- --per_device_eval_batch_size=4 \
- --output_dir previous_output_dir \
- --predict_with_generate
-```
-
-ë ëČì§žë `resume_from_checkpoint path_to_specific_checkpoint` ìžì넌 ìŹì©íìŹ íčì ìČŽíŹíŹìžíž íŽëìì íë šì ìŹê°íë ë°©ëČì
ëë€.
-
-```bash
-python examples/pytorch/summarization/run_summarization.py
- --model_name_or_path t5-small \
- --do_train \
- --do_eval \
- --dataset_name cnn_dailymail \
- --dataset_config "3.0.0" \
- --source_prefix "summarize: " \
- --output_dir /tmp/tst-summarization \
- --per_device_train_batch_size=4 \
- --per_device_eval_batch_size=4 \
- --overwrite_output_dir \
- --resume_from_checkpoint path_to_specific_checkpoint \
- --predict_with_generate
-```
-
-## ëȘšëž êł”ì íêž°[[share-your-model]]
-
-ëȘšë ì€íŹëŠœížë ì”ìą
ëȘšëžì [Model Hub](https://huggingface.co/models)ì ì
ëĄëí ì ìì”ëë€.
-ììíêž° ì ì Hugging Faceì ëĄê·žìžíëì§ íìžíìžì:
-```bash
-huggingface-cli login
-```
-
-ê·žë° ë€ì ì€íŹëŠœížì `push_to_hub` ìžì넌 ì¶ê°í©ëë€.
-ìŽ ìžìë Hugging Face ìŹì©ì ìŽëŠêłŒ `output_dir`ì ì§ì ë íŽë ìŽëŠìŒëĄ ì ì„ì넌 ìì±í©ëë€.
-
-ì ì„ìì íčì ìŽëŠì ì§ì íë €ë©Ž `push_to_hub_model_id` ìžì넌 ìŹì©íìŹ ì¶ê°í©ëë€.
-ì ì„ìë ë€ìì€íìŽì€ ìëì ìëìŒëĄ ëìŽë©ëë€.
-ë€ì ìë íčì ì ì„ì ìŽëŠìŒëĄ ëȘšëžì ì
ëĄëíë ë°©ëČì
ëë€:
-
-```bash
-python examples/pytorch/summarization/run_summarization.py
- --model_name_or_path t5-small \
- --do_train \
- --do_eval \
- --dataset_name cnn_dailymail \
- --dataset_config "3.0.0" \
- --source_prefix "summarize: " \
- --push_to_hub \
- --push_to_hub_model_id finetuned-t5-cnn_dailymail \
- --output_dir /tmp/tst-summarization \
- --per_device_train_batch_size=4 \
- --per_device_eval_batch_size=4 \
- --overwrite_output_dir \
- --predict_with_generate
-```
\ No newline at end of file
diff --git a/docs/source/ko/sagemaker.md b/docs/source/ko/sagemaker.md
new file mode 100644
index 000000000000..f612435d3c1a
--- /dev/null
+++ b/docs/source/ko/sagemaker.md
@@ -0,0 +1,29 @@
+
+
+# Amazon SageMakerìì íì” ì€ííêž°[[run-training-on-amazon-sagemaker]]
+
+돞ìê° [hf.co/docs/sagemaker](https://huggingface.co/docs/sagemaker)ëĄ ìŽëëìì”ëë€. ìŽ íìŽì§ë `transformers` 5.0 ìì ìì ë ìì ì
ëë€.
+
+### ëȘ©ì°š[[table-of-content]]
+
+- [Train Hugging Face models on Amazon SageMaker with the SageMaker Python SDK](https://huggingface.co/docs/sagemaker/train)
+- [Deploy Hugging Face models to Amazon SageMaker with the SageMaker Python SDK](https://huggingface.co/docs/sagemaker/inference)
+- [Frequently Asked Questions](https://huggingface.co/docs/sagemaker/faq)
diff --git a/docs/source/ko/sagemaker.mdx b/docs/source/ko/sagemaker.mdx
deleted file mode 100644
index 882dc2fd778e..000000000000
--- a/docs/source/ko/sagemaker.mdx
+++ /dev/null
@@ -1,25 +0,0 @@
-
-
-# Amazon SageMakerìì íì” ì€ííêž°[[run-training-on-amazon-sagemaker]]
-
-돞ìê° [hf.co/docs/sagemaker](https://huggingface.co/docs/sagemaker)ëĄ ìŽëëìì”ëë€. ìŽ íìŽì§ë `transformers` 5.0 ìì ìì ë ìì ì
ëë€.
-
-### ëȘ©ì°š[[table-of-content]]
-
-- [Train Hugging Face models on Amazon SageMaker with the SageMaker Python SDK](https://huggingface.co/docs/sagemaker/train)
-- [Deploy Hugging Face models to Amazon SageMaker with the SageMaker Python SDK](https://huggingface.co/docs/sagemaker/inference)
-- [Frequently Asked Questions](https://huggingface.co/docs/sagemaker/faq)
diff --git a/docs/source/ko/serialization.md b/docs/source/ko/serialization.md
new file mode 100644
index 000000000000..0cbcf005e3ac
--- /dev/null
+++ b/docs/source/ko/serialization.md
@@ -0,0 +1,181 @@
+
+
+# ONNXëĄ ëŽëłŽëŽêž° [[export-to-onnx]]
+
+đ€ Transformers ëȘšëžì ì í íêČœìì ë°°íŹíêž° ìíŽìë ëȘšëžì ì§ë Źíë íììŒëĄ ëŽëłŽëŽêł íčì ë°íìêłŒ íëìšìŽìì ëĄëíêł ì€íí ì ììŒë©Ž ì ì©í©ëë€.
+
+đ€ Optimumì Transformersì íì„ìŒëĄ, PyTorch ëë TensorFlowìì ëȘšëžì ONNXì TFLiteì ê°ì ì§ë Źíë íììŒëĄ ëŽëłŽëŒ ì ìëëĄ íë `exporters` ëȘšëì í”íŽ ì êł”ë©ëë€. đ€ Optimumì ëí ì±ë„ ì”ì í ëê”Ź ìžížë„Œ ì êł”íìŹ íčì íëìšìŽìì ëȘšëžì íë šíêł ì€íí ë ì”ë íšìšì±ì ëŹì±í ì ìì”ëë€.
+
+ìŽ ìëŽìë đ€ Optimumì ìŹì©íìŹ đ€ Transformers ëȘšëžì ONNXëĄ ëŽëłŽëŽë ë°©ëČì 볎ìŹì€ëë€. TFLiteëĄ ëȘšëžì ëŽëłŽëŽë ìëŽìë [TFLiteëĄ ëŽëłŽëŽêž° íìŽì§](tflite)넌 ì°žìĄ°íìžì.
+
+## ONNXëĄ ëŽëłŽëŽêž° [[export-to-onnx]]
+
+[ONNX (Open Neural Network eXchange)](http://onnx.ai)ë PyTorchì TensorFlow넌 íŹíší ë€ìí íë ììíŹìì ìŹìž” íì” ëȘšëžì ëíëŽë ë° ìŹì©ëë êł”í” ì°ì°ì ìžížì êł”í” íìŒ íìì ì ìíë ì€í íì€ì
ëë€. ëȘšëžìŽ ONNX íììŒëĄ ëŽëłŽëŽì§ë©Ž ìŽëŹí ì°ì°ì넌 ìŹì©íìŹ ì êČœë§ì í”íŽ ë°ìŽí°ê° í넎ë íëŠì ëíëŽë êłì° ê·žëí(ìŒë°ì ìŒëĄ _ì€ê° íí_ìŽëŒêł íš)ê° ê”Źì±ë©ëë€.
+
+íì€íë ì°ì°ìì ë°ìŽí° ì íì ê°ì§ ê·žëí넌 ë
žì¶íšìŒëĄìš, ONNXë íë ììíŹ ê°ì ìœêČ ì íí ì ìì”ëë€. ì넌 ë€ìŽ, PyTorchìì íë šë ëȘšëžì ONNX íììŒëĄ ëŽëłŽëŽêł TensorFlowìì ê°ì žìŹ ì ìì”ëë€(ê·ž ë°ëë ê°ë„í©ëë€).
+
+ONNX íììŒëĄ ëŽëłŽëž ëȘšëžì ë€ìêłŒ ê°ìŽ ìŹì©í ì ìì”ëë€:
+- [ê·žëí ì”ì í](https://huggingface.co/docs/optimum/onnxruntime/usage_guides/optimization) ë° [ììí](https://huggingface.co/docs/optimum/onnxruntime/usage_guides/quantization)ì ê°ì êž°ëČì ìŹì©íìŹ ì¶ëĄ ì ìíŽ ì”ì íë©ëë€.
+- ONNX Runtimeì í”íŽ ì€íí ì ìì”ëë€. [`ORTModelForXXX` íŽëì€ë€](https://huggingface.co/docs/optimum/onnxruntime/package_reference/modeling_ort)ì í”íŽ ëìŒí `AutoModel` API넌 ë°ëŠ
ëë€. ìŽ APIë đ€ Transformersìì ìŹì©íë êČêłŒ ëìŒí©ëë€.
+- [ì”ì íë ì¶ëĄ íìŽíëŒìž](https://huggingface.co/docs/optimum/main/en/onnxruntime/usage_guides/pipelines)ì ìŹì©í ì ìì”ëë€. ìŽë đ€ Transformersì [`pipeline`] íšìì ëìŒí API넌 ê°ì§êł ìì”ëë€.
+
+đ€ Optimumì ê”Źì± ê°ìČŽë„Œ íì©íìŹ ONNX ëŽëłŽëŽêž°ë„Œ ì§ìí©ëë€. ìŽëŹí ê”Źì± ê°ìČŽë ìŹëŹ ëȘšëž ìí€í
ìČì ëíŽ ëŻžëŠŹ ì€ëčëìŽ ììŒë©° ë€ë„ž ìí€í
ìČì ìœêČ íì„í ì ìëëĄ ì€êłëìì”ëë€.
+
+믞늏 ì€ëčë ê”Źì± ëȘ©ëĄì [đ€ Optimum 돞ì](https://huggingface.co/docs/optimum/exporters/onnx/overview)넌 ì°žìĄ°íìžì.
+
+đ€ Transformers ëȘšëžì ONNXëĄ ëŽëłŽëŽë ë ê°ì§ ë°©ëČìŽ ìì”ëë€. ìŹêž°ìì ë ê°ì§ ë°©ëČì ëȘšë 볎ìŹì€ëë€:
+
+- đ€ Optimumì ìŹì©íìŹ CLIëĄ ëŽëłŽëŽêž°
+- `optimum.onnxruntime`ì ìŹì©íìŹ đ€ OptimumìŒëĄ ONNXëĄ ëŽëłŽëŽêž°
+
+### CLI넌 ìŹì©íìŹ đ€ Transformers ëȘšëžì ONNXëĄ ëŽëłŽëŽêž° [[exporting-a-transformers-model-to-onnx-with-cli]]
+
+đ€ Transformers ëȘšëžì ONNXëĄ ëŽëłŽëŽë €ë©Ž 뚌ì ì¶ê° ìą
ìì±ì ì€ìčíìžì:
+
+```bash
+pip install optimum[exporters]
+```
+
+ìŹì© ê°ë„í ëȘšë ìžì넌 íìžíë €ë©Ž [đ€ Optimum 돞ì](https://huggingface.co/docs/optimum/exporters/onnx/usage_guides/export_a_model#exporting-a-model-to-onnx-using-the-cli)넌 ì°žìĄ°íê±°ë ëȘ
ë čì€ìì ëìë§ì 볎ìžì.
+
+```bash
+optimum-cli export onnx --help
+```
+
+ì넌 ë€ìŽ, đ€ Hubìì `distilbert-base-uncased-distilled-squad`ì ê°ì ëȘšëžì ìČŽíŹíŹìžížë„Œ ëŽëłŽëŽë €ë©Ž ë€ì ëȘ
ë čì ì€ííìžì:
+
+```bash
+optimum-cli export onnx --model distilbert-base-uncased-distilled-squad distilbert_base_uncased_squad_onnx/
+```
+
+ìì ê°ìŽ ì§í ìí©ì ëíëŽë ëĄê·žê° íìëêł êČ°êłŒìž `model.onnx`ê° ì ì„ë ììčê° íìë©ëë€.
+
+```bash
+Validating ONNX model distilbert_base_uncased_squad_onnx/model.onnx...
+ -[â] ONNX model output names match reference model (start_logits, end_logits)
+ - Validating ONNX Model output "start_logits":
+ -[â] (2, 16) matches (2, 16)
+ -[â] all values close (atol: 0.0001)
+ - Validating ONNX Model output "end_logits":
+ -[â] (2, 16) matches (2, 16)
+ -[â] all values close (atol: 0.0001)
+The ONNX export succeeded and the exported model was saved at: distilbert_base_uncased_squad_onnx
+```
+
+ìì ìì ë đ€ Hubìì ìČŽíŹíŹìžížë„Œ ëŽëłŽëŽë êČì ì€ëȘ
í©ëë€. ëĄì»Ź ëȘšëžì ëŽëłŽëŒ ëìë ëȘšëžì ê°ì€ìčì í íŹëìŽì íìŒì ëìŒí ëë í 늏(`local_path`)ì ì ì„íëì§ íìžíìžì. CLI넌 ìŹì©í ëìë đ€ Hubì ìČŽíŹíŹìžíž ìŽëŠ ëì `model` ìžìì `local_path`넌 ì ëŹíêł `--task` ìžì넌 ì êł”íìžì. ì§ìëë ìì
ì ëȘ©ëĄì [đ€ Optimum 돞ì](https://huggingface.co/docs/optimum/exporters/task_manager)넌 ì°žìĄ°íìžì. `task` ìžìê° ì êł”ëì§ ììŒë©Ž ìì
ì íčíë í€ë ììŽ ëȘšëž ìí€í
ìČëĄ êž°ëłž ì€ì ë©ëë€.
+
+```bash
+optimum-cli export onnx --model local_path --task question-answering distilbert_base_uncased_squad_onnx/
+```
+
+ê·ž êČ°êłŒëĄ ìì±ë `model.onnx` íìŒì ONNX íì€ì ì§ìíë ë§ì [ê°ìêž°](https://onnx.ai/supported-tools.html#deployModel) ì€ íëìì ì€íí ì ìì”ëë€. ì넌 ë€ìŽ, [ONNX Runtime](https://onnxruntime.ai/)ì ìŹì©íìŹ ëȘšëžì ëĄëíêł ì€íí ì ìì”ëë€:
+
+```python
+>>> from transformers import AutoTokenizer
+>>> from optimum.onnxruntime import ORTModelForQuestionAnswering
+
+>>> tokenizer = AutoTokenizer.from_pretrained("distilbert_base_uncased_squad_onnx")
+>>> model = ORTModelForQuestionAnswering.from_pretrained("distilbert_base_uncased_squad_onnx")
+>>> inputs = tokenizer("What am I using?", "Using DistilBERT with ONNX Runtime!", return_tensors="pt")
+>>> outputs = model(**inputs)
+```
+
+Hubì TensorFlow ìČŽíŹíŹìžížì ëíŽìë ëìŒí íëĄìžì€ê° ì ì©ë©ëë€. ì넌 ë€ìŽ, [Keras organization](https://huggingface.co/keras-io)ìì ììí TensorFlow ìČŽíŹíŹìžížë„Œ ëŽëłŽëŽë ë°©ëČì ë€ìêłŒ ê°ì”ëë€:
+
+```bash
+optimum-cli export onnx --model keras-io/transformers-qa distilbert_base_cased_squad_onnx/
+```
+
+### `optimum.onnxruntime`ì ìŹì©íìŹ đ€ Transformers ëȘšëžì ONNXëĄ ëŽëłŽëŽêž° [[exporting-a-transformers-model-to-onnx-with-optimumonnxruntime]]
+
+CLI ëì ì `optimum.onnxruntime`ì ìŹì©íìŹ íëĄê·žëë° ë°©ììŒëĄ đ€ Transformers ëȘšëžì ONNXëĄ ëŽëłŽëŒ ìë ìì”ëë€. ë€ìêłŒ ê°ìŽ ì§ííìžì:
+
+```python
+>>> from optimum.onnxruntime import ORTModelForSequenceClassification
+>>> from transformers import AutoTokenizer
+
+>>> model_checkpoint = "distilbert_base_uncased_squad"
+>>> save_directory = "onnx/"
+
+>>> # Load a model from transformers and export it to ONNX
+>>> ort_model = ORTModelForSequenceClassification.from_pretrained(model_checkpoint, export=True)
+>>> tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)
+
+>>> # Save the onnx model and tokenizer
+>>> ort_model.save_pretrained(save_directory)
+>>> tokenizer.save_pretrained(save_directory)
+```
+
+### ì§ìëì§ ìë ìí€í
ìČì ëȘšëž ëŽëłŽëŽêž° [[exporting-a-model-for-an-unsupported-architecture]]
+
+íìŹ ëŽëłŽëŒ ì ìë ëȘšëžì ì§ìíêž° ìíŽ êž°ìŹíë €ë©Ž, 뚌ì [`optimum.exporters.onnx`](https://huggingface.co/docs/optimum/exporters/onnx/overview)ìì ì§ìëëì§ íìží í ì§ìëì§ ìë êČœì°ìë [đ€ Optimumì êž°ìŹ](https://huggingface.co/docs/optimum/exporters/onnx/usage_guides/contribute)íìžì.
+
+### `transformers.onnx`넌 ìŹì©íìŹ ëȘšëž ëŽëłŽëŽêž° [[exporting-a-model-with-transformersonnx]]
+
+
+
+`tranformers.onnx`ë ë ìŽì ì ì§ëì§ ìì”ëë€. ììì ì€ëȘ
í ëëĄ đ€ Optimumì ìŹì©íìŹ ëȘšëžì ëŽëłŽëŽìžì. ìŽ ìčì
ì í„í ëČì ìì ì ê±°ë ìì ì
ëë€.
+
+
+
+đ€ Transformers ëȘšëžì ONNXëĄ ëŽëłŽëŽë €ë©Ž ì¶ê° ìą
ìì±ì ì€ìčíìžì:
+
+```bash
+pip install transformers[onnx]
+```
+
+`transformers.onnx` íší€ì§ë„Œ Python ëȘšëëĄ ìŹì©íìŹ ì€ëčë ê”Źì±ì ìŹì©íìŹ ìČŽíŹíŹìžížë„Œ ëŽëłŽë
ëë€:
+
+```bash
+python -m transformers.onnx --model=distilbert-base-uncased onnx/
+```
+
+ìŽë êČ í멎 `--model` ìžìì ì ìë ìČŽíŹíŹìžížì ONNX ê·žëíê° ëŽëłŽëŽì§ëë€. đ€ Hubìì ì êł”íë ìČŽíŹíŹìžížë ëĄì»Źì ì ì„ë ìČŽíŹíŹìžížë„Œ ì ëŹí ì ìì”ëë€. êČ°êłŒëĄ ìì±ë `model.onnx` íìŒì ONNX íì€ì ì§ìíë ë§ì ê°ìêž° ì€ íëìì ì€íí ì ìì”ëë€. ì넌 ë€ìŽ, ë€ìêłŒ ê°ìŽ ONNX Runtimeì ìŹì©íìŹ ëȘšëžì ëĄëíêł ì€íí ì ìì”ëë€:
+
+```python
+>>> from transformers import AutoTokenizer
+>>> from onnxruntime import InferenceSession
+
+>>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
+>>> session = InferenceSession("onnx/model.onnx")
+>>> # ONNX Runtime expects NumPy arrays as input
+>>> inputs = tokenizer("Using DistilBERT with ONNX Runtime!", return_tensors="np")
+>>> outputs = session.run(output_names=["last_hidden_state"], input_feed=dict(inputs))
+```
+
+íìí ì¶ë „ ìŽëŠ(ì: `["last_hidden_state"]`)ì ê° ëȘšëžì ONNX ê”Źì±ì íìžíìŹ ì»ì ì ìì”ëë€. ì넌 ë€ìŽ, DistilBERTì êČœì° ë€ìêłŒ ê°ì”ëë€:
+
+```python
+>>> from transformers.models.distilbert import DistilBertConfig, DistilBertOnnxConfig
+
+>>> config = DistilBertConfig()
+>>> onnx_config = DistilBertOnnxConfig(config)
+>>> print(list(onnx_config.outputs.keys()))
+["last_hidden_state"]
+```
+
+Hubì TensorFlow ìČŽíŹíŹìžížì ëíŽìë ëìŒí íëĄìžì€ê° ì ì©ë©ëë€. ì넌 ë€ìŽ, ë€ìêłŒ ê°ìŽ ììí TensorFlow ìČŽíŹíŹìžížë„Œ ëŽëłŽë
ëë€:
+
+```bash
+python -m transformers.onnx --model=keras-io/transformers-qa onnx/
+```
+
+ëĄì»Źì ì ì„ë ëȘšëžì ëŽëłŽëŽë €ë©Ž ëȘšëžì ê°ì€ìč íìŒêłŒ í íŹëìŽì íìŒì ëìŒí ëë í 늏ì ì ì„í ë€ì, transformers.onnx íší€ì§ì --model ìžì넌 ìíë ëë í ëŠŹëĄ ì§ì íìŹ ONNXëĄ ëŽëłŽë
ëë€:
+
+```bash
+python -m transformers.onnx --model=local-pt-checkpoint onnx/
+```
\ No newline at end of file
diff --git a/docs/source/ko/serialization.mdx b/docs/source/ko/serialization.mdx
deleted file mode 100644
index a72a9472ebc8..000000000000
--- a/docs/source/ko/serialization.mdx
+++ /dev/null
@@ -1,451 +0,0 @@
-
-
-# ONNXëĄ ëŽëłŽëŽêž°[[export-to-onnx]]
-
-íëĄëì
íêČœì đ€ Transformers ëȘšëžì ë°°íŹí ëìë íčì ë°íì ë° íëìšìŽ ìì ìŹëŠŹêł ì€íí ì ìëëĄ ì§ë Źíë íììŒëĄ ëŽëłŽëŽêž°ë„Œ ê¶ì„í©ëë€. ìŽ ê°ìŽëììë đ€ Transformers ëȘšëžì [ONNX (Open Neural Network eXchange)](http://onnx.ai)ëĄ ëŽëłŽëŽë ë°©ëČì ìëŽí©ëë€.
-
-ONNXë ë„ëŹë ëȘšëžì íííêž° ìí êł”í” íìŒ íìêłŒ ì°ì°ìë€ì ì ìíë ê°ë°©í íì€ìŒëĄìš PyTorch, TensorFlow ë± ë€ìí íë ììíŹìì ì§ìë©ëë€. ëȘšëžì ONNX íììŒëĄ ëŽëłŽëŽë©Ž, (ëłŽí” _ì€ê° íí (Intermediate Representation; IR)_ìŽëŒêł ë¶ëŠŹë) êłì° ê·žëíê° ê”Źì±ë©ëë€. êłì° ê·žëíë ì êČœë§ì í”íŽ ë°ìŽí°ê° í넎ë ë°©ì, ìŠ ìŽë€ ì°ì°ìŽ ìŽë ë¶ë¶ì ìŹì©ëìëì§ë„Œ ëíë
ëë€.
-
-íì€ ì°ì° ë° ë°ìŽí° íìì ìŹì©íìŹ ê·žëí넌 ë
žì¶íêž° ë돞ì ONNX넌 ìŹì©í멎 íë ììíŹ ê° ì íìŽ ìŹìì§ëë€. ì넌 ë€ìŽ, PyTorchìì íë šë ëȘšëžì ONNX íììŒëĄ ëŽëłŽëž ë€, TensorFlowìì ê°ì žìŹ ì ìì”ëë€. ëŹŒëĄ ê·ž ë°ëë ê°ë„í©ëë€.
-
-đ€ Transformersë ëȘšëž ìČŽíŹíŹìžížë„Œ ONNX ê·žëíëĄ ëłíí ì ìêČ íŽìŁŒë [`transformers.onnx`](main_classes/onnx) íší€ì§ë„Œ ì êł”í©ëë€. ìŽê±ž ê°ë„ìŒ íë ê”Źì± ê°ìČŽë ìŹëŹ ëȘšëž ìí€í
ìČ넌 ëììŒëĄ 믞늏 ì ìëìŽ ììŒë©°, ë€ë„ž ìí€í
ìČëĄë ìœêČ íì„í ì ìëëĄ ì€êłëìì”ëë€.
-
-
-
-đ€ Optimumìì [`optimum.exporters.onnx` íší€ì§](https://huggingface.co/docs/optimum/exporters/onnx/usage_guides/export_a_model)넌 ìŹì©íìŹ đ€ Transformers ëȘšëžì ëŽëłŽëŒ ìë ìì”ëë€.
-
-ëȘšëžì ëŽëłŽëž í ë€ìêłŒ ê°ìŽ ìŹì©ë ì ìì”ëë€:
-
-- ììí ë° ê·žëí ì”ì íì ê°ì êž°ì ì í”íŽ ì¶ëĄ ì ì”ì íí©ëë€.
-- [`ORTModelForXXX` íŽëì€](https://huggingface.co/docs/optimum/onnxruntime/package_reference/modeling_ort)넌 í”íŽ ONNX ë°íììì ì€íí©ëë€. ìŽ íŽëì€ë€ì đ€ Transformersìì ìŹì©íë `AutoModel` APIì ëìŒí©ëë€.
-- [ì”ì íë ì¶ëĄ íìŽíëŒìž](https://huggingface.co/docs/optimum/main/en/onnxruntime/usage_guides/pipelines) ìì ì€íí©ëë€. ìŽ íìŽíëŒìžì đ€ Transformersì [`pipeline`] íšìì ëìŒí API넌 ê°ì”ëë€.
-
-ìŽëŹí êž°ë„ì ëȘšë ìŽíŽëłŽë €ë©Ž [đ€ Optimum ëŒìŽëžëŹëŠŹ](https://github.com/huggingface/optimum)넌 íìžíìžì.
-
-
-
-믞늏 ì ìë ê”Źì±ìë ë€ì ìí€í
ìČê° íŹíšë©ëë€:
-
-
-
-- ALBERT
-- BART
-- BEiT
-- BERT
-- BigBird
-- BigBird-Pegasus
-- Blenderbot
-- BlenderbotSmall
-- BLOOM
-- CamemBERT
-- Chinese-CLIP
-- CLIP
-- CodeGen
-- Conditional DETR
-- ConvBERT
-- ConvNeXT
-- Data2VecText
-- Data2VecVision
-- DeBERTa
-- DeBERTa-v2
-- DeiT
-- DETR
-- DistilBERT
-- EfficientNet
-- ELECTRA
-- ERNIE
-- FlauBERT
-- GPT Neo
-- GPT-J
-- GPT-Sw3
-- GroupViT
-- I-BERT
-- ImageGPT
-- LayoutLM
-- LayoutLMv3
-- LeViT
-- Longformer
-- LongT5
-- M2M100
-- Marian
-- mBART
-- MEGA
-- MobileBERT
-- MobileNetV1
-- MobileNetV2
-- MobileViT
-- MT5
-- OpenAI GPT-2
-- OWL-ViT
-- Perceiver
-- PLBart
-- PoolFormer
-- RemBERT
-- ResNet
-- RoBERTa
-- RoBERTa-PreLayerNorm
-- RoFormer
-- SegFormer
-- SqueezeBERT
-- Swin Transformer
-- T5
-- Table Transformer
-- Vision Encoder decoder
-- ViT
-- Whisper
-- X-MOD
-- XLM
-- XLM-RoBERTa
-- XLM-RoBERTa-XL
-- YOLOS
-
-ììŒëĄì ë ìčì
ììë ìë ëŽì©ì ìŽíŽëłŽêČ ì”ëë€:
-
-* `transformers.onnx` íší€ì§ë„Œ ìŹì©íìŹ ì§ìëë ëȘšëž ëŽëłŽëŽêž°
-* ì§ìëì§ ìë ìí€í
ìČ넌 ìíŽ ìŹì©ì ì ì ëȘšëž ëŽëłŽëŽêž°
-
-## ëȘšëžì ONNXëĄ ëŽëłŽëŽêž°[[exporting-a-model-to-onnx]]
-
-
-
-ìŽì ëȘšëžì ëŽëłŽëŒ ë [`optimum.exporters.onnx`](https://huggingface.co/docs/optimum/main/en/exporters/onnx/usage_guides/export_a_model#exporting-a-model-to-onnx-using-the-cli)넌 ìŹì©íëëĄ ê¶ì„í©ëë€. `transformers.onnx`ì ë§€ì° ì ìŹíë ê±±ì íì§ ë§ìžì!
-
-
-
-đ€ Transformers ëȘšëžì ONNXëĄ ëŽëłŽëŽë €ë©Ž 뚌ì ëȘ ê°ì§ ì¶ê° ìą
ìì±ì ì€ìčíŽìŒí©ëë€:
-
-```bash
-pip install transformers[onnx]
-```
-
-`transformers.onnx` íší€ì§ë ë€ìêłŒ ê°ìŽ Python ëȘšëëĄ ìŹì©í ì ìì”ëë€:
-
-```bash
-python -m transformers.onnx --help
-
-usage: Hugging Face Transformers ONNX exporter [-h] -m MODEL [--feature {causal-lm, ...}] [--opset OPSET] [--atol ATOL] output
-
-positional arguments:
- output Path indicating where to store generated ONNX model.
-
-optional arguments:
- -h, --help show this help message and exit
- -m MODEL, --model MODEL
- Model ID on huggingface.co or path on disk to load model from.
- --feature {causal-lm, ...}
- The type of features to export the model with.
- --opset OPSET ONNX opset version to export the model with.
- --atol ATOL Absolute difference tolerance when validating the model.
-```
-
-ë€ìêłŒ ê°ìŽ ëŻžëŠŹ ì ìë ê”Źì±ì ìŹì©íìŹ ìČŽíŹíŹìžížë„Œ ëŽëłŽëŒ ì ìì”ëë€:
-
-```bash
-python -m transformers.onnx --model=distilbert-base-uncased onnx/
-```
-
-ë€ìêłŒ ê°ì ëĄê·žê° íìëìŽìŒí©ëë€:
-
-```bash
-Validating ONNX model...
- -[â] ONNX model output names match reference model ({'last_hidden_state'})
- - Validating ONNX Model output "last_hidden_state":
- -[â] (2, 8, 768) matches (2, 8, 768)
- -[â] all values close (atol: 1e-05)
-All good, model saved at: onnx/model.onnx
-```
-
-ìŽë êČ `--model` ìžìëĄ ì ìë ìČŽíŹíŹìžížì ONNX ê·žëí넌 ëŽëłŽë
ëë€. ììììë `distilbert-base-uncased`ìŽì§ë§, Hugging Face Hubìì ê°ì žìê±°ë ëĄì»Źì ì ì„ë ìČŽíŹíŹìžížë€ ëȘšë ê°ë„í©ëë€.
-
-êČ°êłŒëĄ ëìš `model.onnx` íìŒì ONNX íì€ì ì§ìíë [ë€ìí ê°ìêž°](https://onnx.ai/supported-tools.html#deployModel) ì€ íëìì ì€íí ì ìì”ëë€. ì넌 ë€ìŽ, ë€ìêłŒ ê°ìŽ [ONNX Runtime](https://onnxruntime.ai/)ìì ëȘšëžì ê°ì žì€êł ì€íí ì ìì”ëë€:
-
-```python
->>> from transformers import AutoTokenizer
->>> from onnxruntime import InferenceSession
-
->>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
->>> session = InferenceSession("onnx/model.onnx")
->>> # ONNX Runtime expects NumPy arrays as input
->>> inputs = tokenizer("Using DistilBERT with ONNX Runtime!", return_tensors="np")
->>> outputs = session.run(output_names=["last_hidden_state"], input_feed=dict(inputs))
-```
-
-`["last_hidden_state"]`ì ê°ì íìí ì¶ë „ ìŽëŠì ê° ëȘšëžì ONNX ê”Źì±ì ìŽíŽëłŽë©Ž ì»ì ì ìì”ëë€. ì넌 ë€ìŽ, DistilBERTì êČœì° ë€ìêłŒ ê°ì”ëë€:
-
-```python
->>> from transformers.models.distilbert import DistilBertConfig, DistilBertOnnxConfig
-
->>> config = DistilBertConfig()
->>> onnx_config = DistilBertOnnxConfig(config)
->>> print(list(onnx_config.outputs.keys()))
-["last_hidden_state"]
-```
-
-Hubì TensorFlow ìČŽíŹíŹìžížì êČœì°ìë êłŒì ì ëìŒí©ëë€. ì넌 ë€ìŽ, ë€ìêłŒ ê°ìŽ [Keras organization](https://huggingface.co/keras-io)ìì TensorFlow ìČŽíŹíŹìžížë„Œ ëŽëłŽëŒ ì ìì”ëë€:
-
-```bash
-python -m transformers.onnx --model=keras-io/transformers-qa onnx/
-```
-
-ëĄì»Źì ì ì„ë ëȘšëžì ëŽëłŽëŽë €ë©Ž ëȘšëžì ê°ì€ìč ë° í íŹëìŽì íìŒìŽ ì ì„ë ëë í ëŠŹê° íìí©ëë€. ì넌 ë€ìŽ, ë€ìêłŒ ê°ìŽ ìČŽíŹíŹìžížë„Œ ê°ì žì€êł ì ì„í ì ìì”ëë€:
-
-
-```python
->>> from transformers import AutoTokenizer, AutoModelForSequenceClassification
-
->>> # Load tokenizer and PyTorch weights form the Hub
->>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
->>> pt_model = AutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased")
->>> # Save to disk
->>> tokenizer.save_pretrained("local-pt-checkpoint")
->>> pt_model.save_pretrained("local-pt-checkpoint")
-```
-
-ìČŽíŹíŹìžížë„Œ ì ì„í í, `transformers.onnx` íší€ì§ì `--model` ìžì넌 ìíë ëë í ëŠŹëĄ ì§ì íìŹ ONNXëĄ ëŽëłŽëŒ ì ìì”ëë€:
-
-```bash
-python -m transformers.onnx --model=local-pt-checkpoint onnx/
-```
-
-```python
->>> from transformers import AutoTokenizer, TFAutoModelForSequenceClassification
-
->>> # Load tokenizer and TensorFlow weights from the Hub
->>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
->>> tf_model = TFAutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased")
->>> # Save to disk
->>> tokenizer.save_pretrained("local-tf-checkpoint")
->>> tf_model.save_pretrained("local-tf-checkpoint")
-```
-
-ìČŽíŹíŹìžížë„Œ ì ì„í í, `transformers.onnx` íší€ì§ì `--model` ìžì넌 ìíë ëë í ëŠŹëĄ ì§ì íìŹ ONNXëĄ ëŽëłŽëŒ ì ìì”ëë€:
-
-```bash
-python -m transformers.onnx --model=local-tf-checkpoint onnx/
-```
-
-
-## ë€ë„ž ëȘšëž ìì
ì ëí êž°ë„ ì í[[selecting-features-for-different-model-tasks]]
-
-
-
-ìŽì ëȘšëžì ëŽëłŽëŒ ë `optimum.exporters.onnx`넌 ìŹì©íëëĄ ê¶ì„í©ëë€. ìì
ì ì ííë ë°©ëČì ììëłŽë €ë©Ž [đ€ Optimum 돞ì](https://huggingface.co/docs/optimum/main/en/exporters/onnx/usage_guides/export_a_model#selecting-a-task)넌 íìžíìžì.
-
-
-
-ë€ë„ž ì íì íì€íŹì ë§ì¶°ì ëȘšëžì ëŽëłŽëŒ ì ìëëĄ ëŻžëŠŹ ì ìë ê”Źì±ë§ë€ ìŒë šì _êž°ë„_ìŽ íŹíšëìŽ ìì”ëë€. ìë íì ëì ìëëëĄ ê° êž°ë„ì ë€ë„ž `AutoClass`ì ì°êŽëìŽ ìì”ëë€.
-
-| Feature | Auto Class |
-| ------------------------------------ | ------------------------------------ |
-| `causal-lm`, `causal-lm-with-past` | `AutoModelForCausalLM` |
-| `default`, `default-with-past` | `AutoModel` |
-| `masked-lm` | `AutoModelForMaskedLM` |
-| `question-answering` | `AutoModelForQuestionAnswering` |
-| `seq2seq-lm`, `seq2seq-lm-with-past` | `AutoModelForSeq2SeqLM` |
-| `sequence-classification` | `AutoModelForSequenceClassification` |
-| `token-classification` | `AutoModelForTokenClassification` |
-
-ê° ê”Źì±ìì [`~transformers.onnx.FeaturesManager`]넌 í”íŽ ì§ìëë êž°ë„ ëȘ©ëĄì ì°Ÿì ì ìì”ëë€. ì넌 ë€ìŽ, DistilBERTì êČœì° ë€ìêłŒ ê°ì”ëë€:
-
-```python
->>> from transformers.onnx.features import FeaturesManager
-
->>> distilbert_features = list(FeaturesManager.get_supported_features_for_model_type("distilbert").keys())
->>> print(distilbert_features)
-["default", "masked-lm", "causal-lm", "sequence-classification", "token-classification", "question-answering"]
-```
-
-ê·žë° ë€ì `transformers.onnx` íší€ì§ì `--feature` ìžìì ìŽëŹí êž°ë„ ì€ íë넌 ì ëŹí ì ìì”ëë€. ì넌 ë€ìŽ, í
ì€íž ë¶ë„ ëȘšëžì ëŽëłŽëŽë €ë©Ž ë€ìêłŒ ê°ìŽ Hubìì ëŻžìž ìĄ°ì ë ëȘšëžì ì ííêł ì€íí ì ìì”ëë€:
-
-```bash
-python -m transformers.onnx --model=distilbert-base-uncased-finetuned-sst-2-english \
- --feature=sequence-classification onnx/
-```
-
-ë€ìêłŒ ê°ì ëĄê·žê° íìë©ëë€:
-
-```bash
-Validating ONNX model...
- -[â] ONNX model output names match reference model ({'logits'})
- - Validating ONNX Model output "logits":
- -[â] (2, 2) matches (2, 2)
- -[â] all values close (atol: 1e-05)
-All good, model saved at: onnx/model.onnx
-```
-
-ìŽë ëŻžìž ìĄ°ì ë ëȘšëžì ì¶ë „ëȘ
ì ìŽì ì `distilbert-base-uncased` ìČŽíŹíŹìžížìì 뎀ë `last_hidden_state`ì ëŹëŠŹ `logits`ì
ëë€. ìíì€ ë¶ë„넌 ìíŽ ëŻžìž ìĄ°ì ëìêž° ë돞ì ììëëĄ ì
ëë€.
-
-
-
-`with-past` ì 믞ìŹë„Œ ê°ì§ êž°ë„(ì: `causal-lm-with-past`)ì 믞늏 êłì°ë ìšêČšì§ ìí(hidden states; ìŽí
ì
ëžëĄ ì í€-ê° ì)넌 ìŹì©íìŹ ëč 넞 ìêž° íê· ëìœë©ìŽ ê°ë„í ëȘšëž íŽëì€ë€ì
ëë€.
-
-
-
-
-
-`VisionEncoderDecoder` ì í ëȘšëžì êČœì°, ìžìœë ë° ëìœë ë¶ë¶ì ê°ê° `encoder_model.onnx` ë° `decoder_model.onnx`ëŒë ë ê°ì ONNX íìŒëĄ ë¶ëŠŹíìŹ ëŽëłŽë
ëë€.
-
-
-
-
-## ì§ìëì§ ìë ìí€í
ìČ넌 ìí ëȘšëž ëŽëłŽëŽêž°[[exporting-a-model-for-an-unsupported-architecture]]
-
-
-
-íìŹ ëŽëłŽëŒ ì ìë ëȘšëžì ì§ìíëëĄ êž°ìŹíë €ë©Ž 뚌ì [`optimum.exporters.onnx`](https://huggingface.co/docs/optimum/main/en/exporters/onnx/package_reference/configuration#supported-architectures)ìì ì§ìëëì§ íìžíêł ì§ìëì§ ìë êČœì° [đ€ Optimumì êž°ìŹ](https://huggingface.co/docs/optimum/main/en/exporters/onnx/usage_guides/contribute)íìžì.
-
-
-
-ëŒìŽëžëŹëŠŹìì ì§ì ì§ìíì§ ìë ìí€í
ìČì ëȘšëžì ëŽëłŽëŽë €ë©Ž ìž ê°ì§ ìŁŒì ëšêłë„Œ ê±°ìłìŒ í©ëë€:
-
-1. ìŹì©ì ì ì ONNX ê”Źì±ì ê”Źííêž°
-2. ëȘšëžì ONNXëĄ ëŽëłŽëŽêž°
-3. PyTorch ë° ëŽëłŽëž ëȘšëžì ì¶ë „ êČìŠíêž°
-
-ìŽ ìčì
ììë DistilBERTê° ìŽë»êČ ê”Źíëìëì§ ê° ëšêłë§ë€ ììží ìŽíŽëłŽêČ ì”ëë€.
-
-### ìŹì©ì ì ì ONNX ê”Źì±ì ê”Źííêž°[[implementing-a-custom-onnx-configuration]]
-
-ONNX ê”Źì± ê°ìČŽë¶í° ììíŽ ëŽ
ìë€. ëŽëłŽëŽë €ë ëȘšëž ìí€í
ìČ ì íì ë°ëŒ ììíŽìŒíë ìž ê°ì§ ì¶ì íŽëì€ë„Œ ì êł”í©ëë€:
-
-* ìžìœë êž°ë° ëȘšëžì [`~onnx.config.OnnxConfig`]넌 ììí©ëë€.
-* ëìœë êž°ë° ëȘšëžì [`~onnx.config.OnnxConfigWithPast`]넌 ììí©ëë€.
-* ìžìœë-ëìœë ëȘšëžì [`~onnx.config.OnnxSeq2SeqConfigWithPast`]넌 ììí©ëë€.
-
-
-
-ìŹì©ì ì ì ONNX ê”Źì±ì ê”Źííë ìąì ë°©ëČì ëčì·í ìí€í
ìČì `configuration_.py` íìŒìì êž°ìĄŽ ê”Źíì íìžíë êČì
ëë€.
-
-
-
-DistilBERTë ìžìœë êž°ë° ëȘšëžìŽëŻëĄ íŽëč ê”Źì±ì `OnnxConfig`넌 ììí©ëë€.
-
-```python
->>> from typing import Mapping, OrderedDict
->>> from transformers.onnx import OnnxConfig
-
-
->>> class DistilBertOnnxConfig(OnnxConfig):
-... @property
-... def inputs(self) -> Mapping[str, Mapping[int, str]]:
-... return OrderedDict(
-... [
-... ("input_ids", {0: "batch", 1: "sequence"}),
-... ("attention_mask", {0: "batch", 1: "sequence"}),
-... ]
-... )
-```
-
-ê° ê”Źì± ê°ìČŽë `inputs` ìì±ì ê”Źííêł ë§€íì ë°ííŽìŒ í©ëë€. ë§€íì í€ë ìì ì
ë „ì íŽëčíêł ê°ì íŽëč ì
ë „ì ì¶ì ëíë
ëë€. DistilBERTì êČœì° `input_ids` ë° `attention_mask` ë ê°ì ì
ë „ìŽ íìíë°ì. ë ì
ë „ ëȘšë `(batch_size, sequence_length)`ì ëìŒí ì°šììŽêž° ë돞ì ê”Źì±ììë ëê°ì ì¶ì ìŹì©í©ëë€.
-
-
-
-`DistilBertOnnxConfig`ì `inputs` ìì±ìŽ `OrderedDict`ëŒë êČì ì ìíìžì. ìŽë êČ í멎 ì
ë „ìŽ ê·žëí넌 ë°ëŒ í넌 ë `PreTrainedModel.forward()` ë©ìë ì ìë§ì ìëì ìž ììčì ìëëĄ ëłŽì„í©ëë€. ìŹì©ì ì ì ONNX ê”Źì±ì ê”Źíí ëë `inputs` ë° `outputs` ìì±ìŒëĄ `OrderedDict`넌 ìŹì©íë êČì ê¶ì„í©ëë€.
-
-
-
-ONNX ê”Źì±ì ê”Źíí íìë ë€ìêłŒ ê°ìŽ êž°ëłž ëȘšëžì ê”Źì±ì ì êł”íìŹ ìžì€íŽì€í í ì ìì”ëë€:
-
-```python
->>> from transformers import AutoConfig
-
->>> config = AutoConfig.from_pretrained("distilbert-base-uncased")
->>> onnx_config = DistilBertOnnxConfig(config)
-```
-
-êČ°êłŒ ê°ìČŽìë ìŹëŹ ê°ì§ ì ì©í ìì±ìŽ ìì”ëë€. ì넌 ë€ìŽ ONNXëĄ ëŽëłŽëŒ ë ì°ìŒ ONNX ì°ì°ì ì§í©ì ëłŒ ì ìì”ëë€:
-
-```python
->>> print(onnx_config.default_onnx_opset)
-11
-```
-
-ë€ìêłŒ ê°ìŽ ëȘšëžì ì°êȰë ì¶ë „ì ëłŒ ìë ìì”ëë€:
-
-```python
->>> print(onnx_config.outputs)
-OrderedDict([("last_hidden_state", {0: "batch", 1: "sequence"})])
-```
-
-ì¶ë „ ìì±ìŽ ì
ë „êłŒ ëìŒí ê”ŹìĄ°ìì ì ìíìžì. ê° ì¶ë „ì ìŽëŠêłŒ ì°šììŽ `OrderedDict`ì í€-ê°ìŒëĄ ì ì„ëìŽ ìì”ëë€. ì¶ë „ ê”ŹìĄ°ë ê”Źì±ì ìŽêž°íí ë ì íí êž°ë„êłŒ êŽë šìŽ ìì”ëë€. êž°ëłžì ìŒëĄ ONNX ê”Źì±ì `AutoModel` íŽëì€ëĄ ê°ì žìš ëȘšëžì ëŽëłŽëŒ ë ì°ìŽë `default` êž°ë„ìŒëĄ ìŽêž°íë©ëë€. ë€ë„ž íì€íŹë„Œ ìíŽ ëȘšëžì ëŽëłŽëŽë €ë©Ž ONNX ê”Źì±ì ìŽêž°íí ë `task` ìžìì ë€ë„ž êž°ë„ì ëŁìŒë©Ž ë©ëë€. ì넌 ë€ìŽ, ìíì€ ë¶ë„ ëšêłë„Œ ë§ë¶ìž DistilBERT넌 ëŽëłŽëŽë €ë©Ž, ìŽë êČ íŽëłŒ ì ìì”ëë€:
-
-```python
->>> from transformers import AutoConfig
-
->>> config = AutoConfig.from_pretrained("distilbert-base-uncased")
->>> onnx_config_for_seq_clf = DistilBertOnnxConfig(config, task="sequence-classification")
->>> print(onnx_config_for_seq_clf.outputs)
-OrderedDict([('logits', {0: 'batch'})])
-```
-
-
-
-[`~onnx.config.OnnxConfig`]ë ë€ë„ž ê”Źì± íŽëì€ì ì°êȰë ëȘšë êž°ëłž ìì± ë° ë©ìëë íìì ë°ëŒ ëȘšë ìŹì ìí ì ìì”ëë€. êł êž ìì ëĄ [`BartOnnxConfig`]넌 íìžíìžì.
-
-
-
-### ëȘšëž ëŽëłŽëŽêž°[[exporting-the-model]]
-
-ONNX ê”Źì±ì ê”Źííë€ë©Ž, ë€ì ëšêłë ëȘšëžì ëŽëłŽëŽë êČì
ëë€. ìŽì `transformers.onnx` íší€ì§ìì ì êł”íë `export()` íšì넌 ìŽíŽëłŽêČ ì”ëë€. ìŽ íšìë ONNX ê”Źì±, êž°ëłž ëȘšëž, í íŹëìŽì , ê·žëŠŹêł ëŽëłŽëŒ íìŒì êČœëĄë„Œ ì
ë „ìŒëĄ ë°ì”ëë€:
-
-```python
->>> from pathlib import Path
->>> from transformers.onnx import export
->>> from transformers import AutoTokenizer, AutoModel
-
->>> onnx_path = Path("model.onnx")
->>> model_ckpt = "distilbert-base-uncased"
->>> base_model = AutoModel.from_pretrained(model_ckpt)
->>> tokenizer = AutoTokenizer.from_pretrained(model_ckpt)
-
->>> onnx_inputs, onnx_outputs = export(tokenizer, base_model, onnx_config, onnx_config.default_onnx_opset, onnx_path)
-```
-
-`export()` íšìê° ë°ííë `onnx_inputs`ì `onnx_outputs`ë ê”Źì±ì `inputs`ì `outputs` ìì±ìì ì ìë í€ ëȘ©ëĄì
ëë€. ëȘšëžì ëŽëłŽëž í ë€ìêłŒ ê°ìŽ ëȘšëžìŽ ì ê”Źì±ëìŽ ìëì§ í
ì€íží ì ìì”ëë€:
-
-```python
->>> import onnx
-
->>> onnx_model = onnx.load("model.onnx")
->>> onnx.checker.check_model(onnx_model)
-```
-
-
-
-ëȘšëž íŹêž°ê° 2GBëłŽë€ í° êČœì° ëŽëłŽëŽë ì€ì ìŹëŹ ì¶ê° íìŒë€ìŽ ìì±ëë êČì ëłŒ ì ìì”ëë€. ìŹì€ ONNXë ëȘšëžì ì ì„íêž° ìíŽ [Protocol Buffers](https://developers.google.com/protocol-buffers/)넌 ìŹì©íëë°, ëČíŒë 2GBì íŹêž° ì íìŽ ìêž° ë돞ì _ìì°ì€ëŹìŽ_ ìŒì
ëë€. ìžë¶ ë°ìŽí°ë„Œ ìŹì©íìŹ ëȘšëžì ê°ì žì€ë ë°©ëČì [ONNX 돞ì](https://github.com/onnx/onnx/blob/master/docs/ExternalData.md)넌 ì°žìĄ°íìžì.
-
-
-
-### ëȘšëžì ì¶ë „ êČìŠíêž°[[validating-the-model-outputs]]
-
-ë§ì§ë§ ëšêłë êž°ìĄŽ ëȘšëžêłŒ ëŽëłŽëž ëȘšëžì ì¶ë „ìŽ ìŒì í ì€ì°š ëČì ëŽìì ëìŒíë€ë êČì êČìŠíë êČì
ëë€. ê·žëŹë €ë©Ž `transformers.onnx` íší€ì§ìì ì êł”íë `validate_model_outputs()` íšì넌 ìŹì©í ì ìì”ëë€:
-
-```python
->>> from transformers.onnx import validate_model_outputs
-
->>> validate_model_outputs(
-... onnx_config, tokenizer, base_model, onnx_path, onnx_outputs, onnx_config.atol_for_validation
-... )
-```
-
-ìŽ íšìë [`~transformers.onnx.OnnxConfig.generate_dummy_inputs`] ë©ìëëĄ êž°ìĄŽ ë° ëŽëłŽëž ëȘšëžì ì
ë „ì ìì±íë©°, êČìŠì ìŹì©ë ì€ì°š ëČìë ê”Źì±ìì ì ìí ì ìì”ëë€. ìŒë°ì ìŒëĄë 1e-6ìì 1e-4 ëČì ëŽìì í©ìíì§ë§, 1e-3ëłŽë€ ìë€ë©Ž 돞ì ìì ê°ë„ì±ìŽ ëì”ëë€.
-
-## đ€ Transformersì ì ê”Źì± ì¶ê°íêž°[[contributing-a-new-configuration-to-transformers]]
-
-믞늏 ì ìë ê”Źì±ì ì«ì넌 ëëŠŹë €êł ë
žë „íêł ììŒë©°, ì»€ëź€ëí°ì êž°ìŹë„Œ íìí©ëë€! ëŒìŽëžëŹëŠŹì ëčì ë§ì ê”Źì±ì ì¶ê°íë €ë©Ž ë€ì ëšêłë„Œ êž°ì”íŽìŁŒìžì:
-
-* `configuration_.py` íìŒì ONNX ê”Źì±ì ê”Źííìžì.
-* [`~onnx.features.FeatureManager`]ì ëȘšëž ìí€í
ìČ ë° íŽëč êž°ë„ì íŹíšíìžì.
-* `test_onnx_v2.py`ì í
ì€ížì ëȘšëž ìí€í
ìČ넌 ì¶ê°íìžì.
-
-ìì§ ê°ìŽ ì ìĄíì ë€ë©Ž, [IBERT ê”Źì±](https://github.com/huggingface/transformers/pull/14868/files)ìŽ ìŽë»êČ êž°ìŹëìëì§ íìžíŽëłŽìžì.
diff --git a/docs/source/ko/task_summary.md b/docs/source/ko/task_summary.md
new file mode 100644
index 000000000000..dbebf38760a6
--- /dev/null
+++ b/docs/source/ko/task_summary.md
@@ -0,0 +1,341 @@
+
+
+# đ€ TransformersëĄ í ì ìë êČ[[what__transformers_can_do]]
+
+đ€ Transformersë ìì°ìŽìČ늏(NLP), 컎íší° ëčì , ì€ëì€ ë° ìì± ìČ늏 ìì
ì ëí ìŹì íë šë ì”ìČšëš ëȘšëž ëŒìŽëžëŹëŠŹì
ëë€.
+ìŽ ëŒìŽëžëŹëŠŹë ížëì€íŹëšž ëȘšëžëżë§ ìëëŒ ì»Žíší° ëčì ìì
ì ìí íëì ìž í©ì±êł± ì êČœë§êłŒ ê°ì ížëì€íŹëšžê° ìë ëȘšëžë íŹíšíêł ìì”ëë€.
+
+ì€ë§íží°, ì±, í
ë ëčì êłŒ ê°ì ì€ëë ê°ì„ ìžêž° ìë ìëčì ì íì ìŽíŽëłŽë©Ž, ë„ëŹë êž°ì ìŽ ê·ž ë€ì ìŹì©ëêł ìì íë„ ìŽ ëì”ëë€.
+ì€ë§íží°ìŒëĄ ìŽŹìí ìŹì§ìì ë°°êČœ ê°ìČŽë„Œ ì ê±°íêł ì¶ë€ë©Ž ìŽë»êČ í êčì? ìŽë íëí± ìžê·žë©í
ìŽì
ìì
ì ìì
ëë€(ìì§ ìŽêČ ëŹŽììžì§ ëȘšë„žë€ë©Ž, ë€ì ìčì
ìì ì€ëȘ
íêČ ì”ëë€!).
+
+ìŽ íìŽì§ë ë€ìí ìì± ë° ì€ëì€, 컎íší° ëčì , NLP ìì
ì đ€ Transformers ëŒìŽëžëŹëŠŹë„Œ íì©íìŹ ë€ëŁšë ê°ëší ìì 넌 3ì€ì ìœëëĄ ì êł”í©ëë€.
+
+## ì€ëì€[[audio]]
+
+
+ìì± ë° ì€ëì€ ìČ늏 ìì
ì ë€ë„ž ëȘšëŹëŠŹí°ì ìœê° ë€ëŠ
ëë€. ìŽë ìŁŒëĄ ì€ëì€ê° ì°ìì ìž ì ížëĄ ì
ë „ëêž° ë돞ì
ëë€.
+í
ì€ížì ëŹëŠŹ ìëłž ì€ëì€ íí(waveform)ì 돞ì„ìŽ ëšìŽëĄ ëë ì§ë êČìČëŒ êčëíêČ ìŽì°ì ìž ëŹ¶ììŒëĄ ëë ì ìì”ëë€.
+ìŽë„Œ ê·čëł”íêž° ìíŽ ìëłž ì€ëì€ ì ížë ìŒì í ê°êČ©ìŒëĄ ìíë§ë©ëë€. íŽëč ê°êČ© ëŽìì ë ë§ì ìíì ì·ší êČœì° ìíë§ë„ ìŽ ëìì§ë©°, ì€ëì€ë ìëłž ì€ëì€ ìì€ì ë ê°êčìì§ëë€.
+
+êłŒê±°ì ì ê·Œ ë°©ìì ì€ëì€ìì ì ì©í íčì§ì ì¶ì¶íêž° ìíŽ ì€ëì€ë„Œ ì ìČ늏íë êČìŽìì”ëë€.
+íì§ë§ íìŹë ìëłž ì€ëì€ ííì íčì± ìžìœëì ì§ì ëŁìŽì ì€ëì€ íí(representation)ì ì¶ì¶íë êČìŽ ë ìŒë°ì ì
ëë€.
+ìŽë êČ í멎 ì ìČ늏 ëšêłê° ëšìíŽì§êł ëȘšëžìŽ ê°ì„ ì€ìí íčì§ì íì”í ì ìì”ëë€.
+
+### ì€ëì€ ë¶ë„[[audio_classification]]
+
+
+ì€ëì€ ë¶ë„ë ì€ëì€ ë°ìŽí°ì 믞늏 ì ìë íŽëì€ ì§í©ì ë ìŽëžì ì§ì íë ìì
ì
ëë€. ìŽë ë§ì ê”ŹìČŽì ìž ìì© íëĄê·žëšì íŹíší ëì ëČìŁŒì
ëë€.
+
+ìŒë¶ ììë ë€ìêłŒ ê°ì”ëë€:
+
+* ìí„ ì„멎 ë¶ë„: ì€ëì€ì ì„멎 ë ìŽëž("ìŹëŹŽì€", "íŽëł", "êČœêž°ì„")ì ì§ì í©ëë€.
+* ìí„ ìŽëČ€íž ê°ì§: ì€ëì€ì ì늏 ìŽëČ€íž ë ìŽëž("ì°š êČœì ", "êł ë ìžìì늏", "ì 늏 íì")ì ì§ì í©ëë€.
+* íêč
: ìŹëŹ ê°ì§ ì늏(ì ì§ì ê·, íìììì íì ìëł)ê° íŹíšë ì€ëì€ì ë ìŽëžì ì§ì í©ëë€.
+* ìì
ë¶ë„: ìì
ì ì„넎 ë ìŽëž("ë©í", "íí©", "컚ížëŠŹ")ì ì§ì í©ëë€.
+
+```py
+>>> from transformers import pipeline
+
+>>> classifier = pipeline(task="audio-classification", model="superb/hubert-base-superb-er")
+>>> preds = classifier("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac")
+>>> preds = [{"score": round(pred["score"], 4), "label": pred["label"]} for pred in preds]
+>>> preds
+[{'score': 0.4532, 'label': 'hap'},
+ {'score': 0.3622, 'label': 'sad'},
+ {'score': 0.0943, 'label': 'neu'},
+ {'score': 0.0903, 'label': 'ang'}]
+```
+
+### ìë ìì± ìžì[[automatic_speech_recognition]]
+
+
+ìë ìì± ìžì(ASR)ì ìì±ì í
ì€ížëĄ ëłííë ìì
ì
ëë€.
+ìì±ì ìžê°ì ìì°ì€ëŹìŽ ììŹìí” ííìŽêž° ë돞ì ASRì ê°ì„ ìŒë°ì ìž ì€ëì€ ìì
ì€ íëì
ëë€.
+ì€ëë ASR ìì€í
ì ì€íŒì»€, ì í ë° ìëì°šì ê°ì "ì€ë§íž" êž°ì ì íì ëŽì„ëìŽ ìì”ëë€.
+ì°ëŠŹë ê°ì ëčììêČ ìì
ìŹì, ì늌 ì€ì ë° ë ìš ì ëłŽë„Œ ììČí ì ìì”ëë€.
+
+íì§ë§ ížëì€íŹëšž ìí€í
ìČê° íŽêȰíë ë° ëìì ì€ í”ìŹ ëì êłŒì ì€ íëë ììŽ ë°ìŽí° ììŽ ì ì ìžìŽ(low-resource language)ì ëí êČì
ëë€. ëëì ìì± ë°ìŽí°ëĄ ìŹì íë ší í ë°ìŽí° ììŽ ì ì ìžìŽìì ë ìŽëžìŽ ì§ì ë ìì± ë°ìŽí° 1ìê°ë§ìŒëĄ ëȘšëžì ëŻžìž ìĄ°ì í멎 ìŽì ì 100ë°° ë§ì ë ìŽëžìŽ ì§ì ë ë°ìŽí°ëĄ íë šë ASR ìì€í
ëłŽë€ íšìŹ ë ëì íì§ì êČ°êłŒë„Œ ì»ì ì ìì”ëë€.
+```py
+>>> from transformers import pipeline
+
+>>> transcriber = pipeline(task="automatic-speech-recognition", model="openai/whisper-small")
+>>> transcriber("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac")
+{'text': ' I have a dream that one day this nation will rise up and live out the true meaning of its creed.'}
+```
+
+## 컎íší° ëčì [[computer_vision]]
+
+컎íší° ëčì ìì
ì€ ê°ì„ ìŽêž°ì ì±êł”ì ìž ìì
ì€ íëë [í©ì±êł± ì êČœë§(CNN)](glossary#convolution)ì ìŹì©íìŹ ì°ížëČíž ì«ì ìŽëŻžì§ë„Œ ìžìíë êČìŽìì”ëë€. ìŽëŻžì§ë íœì
ëĄ ê”Źì±ëìŽ ììŒë©° ê° íœì
ì ì«ì ê°ìŒëĄ ííë©ëë€. ìŽëĄìš ìŽëŻžì§ë„Œ íœì
ê°ì íë ŹëĄ ëíëŽë êČìŽ ìŹìì§ëë€. íčì í íœì
ê°ì ìĄ°í©ì ìŽëŻžì§ì ììì ì믞í©ëë€.
+
+컎íší° ëčì ìì
ì ìŒë°ì ìŒëĄ ë€ì ë ê°ì§ ë°©ëČìŒëĄ ì ê·Œ ê°ë„í©ëë€:
+
+1. í©ì±êł±ì ìŹì©íìŹ ìŽëŻžì§ì ëźì ìì€ íčì§ìì ëì ìì€ì ì¶ìì ìž ììêčì§ êłìž”ì ìŒëĄ íì”í©ëë€.
+
+2. ìŽëŻžì§ë„Œ íšìčëĄ ëëêł ížëì€íŹëšžë„Œ ìŹì©íìŹ ì ì§ì ìŒëĄ ê° ìŽëŻžì§ íšìčê° ìëĄ ìŽë í ë°©ììŒëĄ ì°êŽëìŽ ìŽëŻžì§ë„Œ íì±íëì§ íì”í©ëë€. `CNN`ìì ì ížíë ìí„ì ì ê·ŒëČêłŒë ëŹëŠŹ, ìŽ ë°©ìì í늿í ìŽëŻžì§ëĄ ìŽìì ê·žëŠŹêł ì ì§ì ìŒëĄ ì ëȘ
í ìŽëŻžì§ëĄ ë§ë€ìŽê°ë êČêłŒ ì ìŹí©ëë€.
+
+### ìŽëŻžì§ ë¶ë„[[image_classification]]
+
+
+ìŽëŻžì§ ë¶ë„ë í ê°ì ì ìČŽ ìŽëŻžì§ì 믞늏 ì ìë íŽëì€ ì§í©ì ë ìŽëžì ì§ì íë ìì
ì
ëë€.
+
+ëë¶ë¶ì ë¶ë„ ìì
êłŒ ë§ì°Źê°ì§ëĄ, ìŽëŻžì§ ë¶ë„ìë ë€ìí ì€ì©ì ìž ì©ëê° ììŒë©°, ìŒë¶ ììë ë€ìêłŒ ê°ì”ëë€:
+
+
+* ìëŁ: ì§ëłì ê°ì§íê±°ë íì 걎ê°ì ëȘšëí°ë§íêž° ìíŽ ìëŁ ìŽëŻžì§ì ë ìŽëžì ì§ì í©ëë€.
+* íêČœ: ìì± ìŽëŻžì§ë„Œ ë¶ë„íìŹ ì°ëŠŒ ëČì±ë„Œ ê°ìíêł ìŒì ì§ì êŽëŠŹë„Œ ìí ì ëłŽë„Œ ì êł”íê±°ë ì°ë¶ì ê°ì§í©ëë€.
+* ëì
: ìëŹŒ ìŽëŻžì§ë„Œ ë¶ë„íìŹ ìëŹŒ 걎ê°ì íìžíê±°ë ìì± ìŽëŻžì§ë„Œ ë¶ë„íìŹ í ì§ ìŽì© êŽì°°ì ìŹì©í©ëë€.
+* ìíí: ëëŹŒìŽë ìëŹŒ ìą
ìŽëŻžì§ë„Œ ë¶ë„íìŹ ìŒì ëëŹŒ ê°ìČŽê”°ì ìĄ°ìŹíê±°ë 멞ìą
ìêž°ì ìČí ìą
ì ì¶ì í©ëë€.
+
+```py
+>>> from transformers import pipeline
+
+>>> classifier = pipeline(task="image-classification")
+>>> preds = classifier(
+... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
+... )
+>>> preds = [{"score": round(pred["score"], 4), "label": pred["label"]} for pred in preds]
+>>> print(*preds, sep="\n")
+{'score': 0.4335, 'label': 'lynx, catamount'}
+{'score': 0.0348, 'label': 'cougar, puma, catamount, mountain lion, painter, panther, Felis concolor'}
+{'score': 0.0324, 'label': 'snow leopard, ounce, Panthera uncia'}
+{'score': 0.0239, 'label': 'Egyptian cat'}
+{'score': 0.0229, 'label': 'tiger cat'}
+```
+
+### ê°ìČŽ íì§[[object_detection]]
+
+
+ìŽëŻžì§ ë¶ë„ì ëŹëŠŹ ê°ìČŽ íì§ë ìŽëŻžì§ ëŽìì ìŹëŹ ê°ìČŽë„Œ ìëłíêł ë°ìŽë© ë°ì€ëĄ ì ìë ê°ìČŽì ììč넌 íì
í©ëë€.
+
+ê°ìČŽ íì§ì ëȘ ê°ì§ ìì© ììë ë€ìêłŒ ê°ì”ëë€:
+
+* ììš ìŁŒí ì°šë: ë€ë„ž ì°šë, 볎íì ë° ì ížë±êłŒ ê°ì ìŒìì ìž ê”í” ê°ìČŽë„Œ ê°ì§í©ëë€.
+* ìêČ© ê°ì§: ìŹë ëȘšëí°ë§, ëì êłí ë° êž°ì ììžĄ ë±ì ìíí©ëë€.
+* êČ°íš íì§: ê±ŽëŹŒì ê· ìŽìŽë ê”ŹìĄ°ì ìì, ì ìĄ° êČ°íš ë±ì íì§í©ëë€.
+
+
+```py
+>>> from transformers import pipeline
+
+>>> detector = pipeline(task="object-detection")
+>>> preds = detector(
+... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
+... )
+>>> preds = [{"score": round(pred["score"], 4), "label": pred["label"], "box": pred["box"]} for pred in preds]
+>>> preds
+[{'score': 0.9865,
+ 'label': 'cat',
+ 'box': {'xmin': 178, 'ymin': 154, 'xmax': 882, 'ymax': 598}}]
+```
+
+### ìŽëŻžì§ ë¶í [[image_segmentation]]
+
+
+ìŽëŻžì§ ë¶í ì íœì
ì°šìì ìì
ìŒëĄ, ìŽëŻžì§ ëŽì ëȘšë íœì
ì íŽëì€ì í ëčí©ëë€. ìŽë ê°ìČŽ íì§ì ë€ëŠ
ëë€. ê°ìČŽ íì§ë ë°ìŽë© ë°ì€ë„Œ ìŹì©íìŹ ìŽëŻžì§ ëŽì ê°ìČŽë„Œ ë ìŽëžë§íêł ììžĄíë ë°ë©Ž, ë¶í ì ë ìžë¶íë ìì
ì
ëë€. ë¶í ì íœì
ìì€ìì ê°ìČŽë„Œ ê°ì§í ì ìì”ëë€.
+
+ìŽëŻžì§ ë¶í ìë ìŹëŹ ì íìŽ ìì”ëë€:
+
+* ìžì€íŽì€ ë¶í : ê°ìČŽì íŽëì€ë„Œ ë ìŽëžë§íë êČ ìžìë, ê°ìČŽì ê° ê”Źë¶ë ìžì€íŽì€ìë ë ìŽëžì ì§ì í©ëë€ ("ê°-1", "ê°-2" ë±).
+* íëí± ë¶í : ì믞ì ë¶í êłŒ ìžì€íŽì€ ë¶í ì ìĄ°í©ì
ëë€. ê° íœì
ì ì믞ì íŽëì€ëĄ ë ìŽëžë§íë **ëìì** ê°ìČŽì ê°ê° ê”Źë¶ë ìžì€íŽì€ëĄë ë ìŽëžì ì§ì í©ëë€.
+
+ë¶í ìì
ì ììš ìŁŒí ì°šëìì ì ì©íë©°, ìŁŒëł íêČœì íœì
ìì€ ì§ë넌 ìì±íìŹ ëłŽíìì ë€ë„ž ì°šë ìŁŒëłìì ìì íêČ íìí ì ìì”ëë€. ëí ìëŁ ììììë ì ì©í©ëë€. ë¶í ìì
ìŽ íœì
ìì€ìì ê°ìČŽë„Œ ê°ì§í ì ìêž° ë돞ì ëčì ìì ìž ìžíŹë ì„êž°ì íčì§ì ìëłíë ë° ëììŽ ë ì ìì”ëë€. ìŽëŻžì§ ë¶í ì ìë„ ê°ì ìì°©ìŽë ìčŽë©ëŒë„Œ í”íŽ ì€ì ìžêłì ê°ì ê°ìČŽë„Œ ë§ìì ìŠê° íì€ êČœíì ë§ëë ë± ì ì ìê±°ë ë¶ìŒììë ìŹì©ë ì ìì”ëë€.
+
+```py
+>>> from transformers import pipeline
+
+>>> segmenter = pipeline(task="image-segmentation")
+>>> preds = segmenter(
+... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
+... )
+>>> preds = [{"score": round(pred["score"], 4), "label": pred["label"]} for pred in preds]
+>>> print(*preds, sep="\n")
+{'score': 0.9879, 'label': 'LABEL_184'}
+{'score': 0.9973, 'label': 'snow'}
+{'score': 0.9972, 'label': 'cat'}
+```
+
+### êčìŽ ì¶ì [[depth_estimation]]
+
+êčìŽ ì¶ì ì ìčŽë©ëŒëĄë¶í° ìŽëŻžì§ ëŽë¶ì ê° íœì
ì ê±°ëŠŹë„Œ ììžĄí©ëë€. ìŽ ì»Žíší° ëčì ìì
ì íčí ì„멎 ìŽíŽì ìŹê”Źì±ì ì€ìí©ëë€. ì넌 ë€ìŽ, ììš ìŁŒí ì°šëì 볎íì, ê”í” íì§í ë° ë€ë„ž ì°šëêłŒ ê°ì ê°ìČŽìì ê±°ëŠŹë„Œ ìŽíŽíìŹ ì„ì ëŹŒêłŒ ì¶©ëì íŒíŽìŒ í©ëë€. êčìŽ ì 볎ë ëí 2D ìŽëŻžì§ìì 3D ííì ê”Źì±íë ë° ëììŽ ëë©° ìëŹŒíì ê”ŹìĄ°ë ê±ŽëŹŒì êł íì§ 3D ííì ìì±íë ë° ìŹì©ë ì ìì”ëë€.
+
+êčìŽ ì¶ì ìë ë ê°ì§ ì ê·Œ ë°©ììŽ ìì”ëë€:
+
+* ì€í
ë ì€: ìœê° ë€ë„ž ê°ëìì ìŽŹìë ëìŒí ìŽëŻžì§ ë ì„ì ëčê”íìŹ êčìŽë„Œ ì¶ì í©ëë€.
+* ëšì: ëšìŒ ìŽëŻžì§ìì êčìŽë„Œ ì¶ì í©ëë€.
+
+
+```py
+>>> from transformers import pipeline
+
+>>> depth_estimator = pipeline(task="depth-estimation")
+>>> preds = depth_estimator(
+... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
+... )
+```
+
+## ìì°ìŽìČ늏[[natural_language_processing]]
+
+í
ì€ížë ìžê°ìŽ ììŹ ìí”íë ìì°ì€ëŹìŽ ë°©ì ì€ íëìŽêž° ë돞ì ìì°ìŽìČ늏 ìì ê°ì„ ìŒë°ì ìž ìì
ì í ì€ íëì
ëë€. ëȘšëžìŽ ìžìíë íììŒëĄ í
ì€ížë„Œ ëłííë €ë©Ž í í°ííŽìŒ í©ëë€. ìŽë í
ì€íž ìíì€ë„Œ ê°ëł ëšìŽ ëë íì ëšìŽ(í í°)ëĄ ë¶í í ë€ì ìŽëŹí í í°ì ì«ìëĄ ëłííë êČì ì믞í©ëë€. êČ°êłŒì ìŒëĄ í
ì€íž ìíì€ë„Œ ì«ì ìíì€ëĄ ííí ì ììŒë©°, ì«ì ìíì€ë„Œ ë€ìí ìì°ìŽìČ늏 ìì
ì íŽêȰíêž° ìí ëȘšëžì ì
ë „í ì ìì”ëë€!
+
+### í
ì€íž ë¶ë„[[text_classification]]
+
+ë€ë„ž ëȘšëŹëŠŹí°ììì ë¶ë„ ìì
êłŒ ë§ì°Źê°ì§ëĄ í
ì€íž ë¶ë„ë 믞늏 ì ìë íŽëì€ ì§í©ìì í
ì€íž ìíì€(ëŹžì„ ìì€, ëšëœ ëë 돞ì ë±)ì ë ìŽëžì ì§ì í©ëë€. í
ì€íž ë¶ë„ìë ë€ìí ì€ì©ì ìž ìì© ìŹëĄê° ììŒë©°, ìŒë¶ ììë ë€ìêłŒ ê°ì”ëë€:
+
+* ê°ì± ë¶ì: í
ì€ížë„Œ `êžì ` ëë `ë¶ì `êłŒ ê°ì ìŽë€ ê·čì±ì ë°ëŒ ë ìŽëžë§íìŹ ì ìč, êžì”, ë§ìŒí
êłŒ ê°ì ë¶ìŒìì ììŹ êȰì ì ì ëłŽë„Œ ì êł”íêł ì§ìí ì ìì”ëë€.
+* ìœí
ìž ë¶ë„: í
ì€ížë„Œ ìŁŒì ì ë°ëŒ ë ìŽëžë§(ë ìš, ì€íŹìž , êžì” ë±)íìŹ ëŽì€ ë° ìì
믞ëìŽ íŒëìì ì ëłŽë„Œ ê”Źì±íêł íí°ë§íë ë° ëììŽ ë ì ìì”ëë€.
+
+```py
+>>> from transformers import pipeline
+
+>>> classifier = pipeline(task="sentiment-analysis")
+>>> preds = classifier("Hugging Face is the best thing since sliced bread!")
+>>> preds = [{"score": round(pred["score"], 4), "label": pred["label"]} for pred in preds]
+>>> preds
+[{'score': 0.9991, 'label': 'POSITIVE'}]
+```
+
+### í í° ë¶ë„[[token_classification]]
+
+ëȘšë ìì°ìŽìČ늏 ìì
ììë í
ì€ížê° ê°ëł ëšìŽë íì ëšìŽëĄ ë¶ëŠŹëìŽ ì ìČ늏ë©ëë€. ë¶ëŠŹë ëšìŽë„Œ [í í°](/glossary#token)ìŽëŒêł í©ëë€. í í° ë¶ë„ë ê° í í°ì 믞늏 ì ìë íŽëì€ ì§í©ì ë ìŽëžì í ëčí©ëë€.
+
+í í° ë¶ë„ì ë ê°ì§ ìŒë°ì ìž ì íì ë€ìêłŒ ê°ì”ëë€:
+
+* ê°ìČŽëȘ
ìžì (NER): í í°ì ìĄ°ì§, ìžëŹŒ, ììč ëë ë ì§ì ê°ì ê°ìČŽ ëČìŁŒì ë°ëŒ ë ìŽëžë§í©ëë€. NERì íčí ì ì ìČŽíì ìž íêČœìì ì ì ì, ëšë°±ì§ ë° ìœëŹŒ ìŽëŠì ë ìŽëžì ì§ì íë ë° ë늏 ìŹì©ë©ëë€.
+* íìŹ íêč
(POS): ëȘ
ìŹ, ëìŹ, íì©ìŹì ê°ì íìŹì ë°ëŒ í í°ì ë ìŽëžì í ëčí©ëë€. POSë ëČì ìì€í
ìŽ ëìŒí ëšìŽê° 돞ëČì ìŒëĄ ìŽë»êČ ë€ë„žì§ ìŽíŽíë ë° ëììŽ ë©ëë€ (ëȘ
ìŹëĄ ìŹì©ëë "bank(ìí)"êłŒ ëìŹëĄ ìŹì©ëë "bank(ìêžì ììčíë€)"êłŒ ê°ì êČœì°).
+
+
+```py
+>>> from transformers import pipeline
+
+>>> classifier = pipeline(task="ner")
+>>> preds = classifier("Hugging Face is a French company based in New York City.")
+>>> preds = [
+... {
+... "entity": pred["entity"],
+... "score": round(pred["score"], 4),
+... "index": pred["index"],
+... "word": pred["word"],
+... "start": pred["start"],
+... "end": pred["end"],
+... }
+... for pred in preds
+... ]
+>>> print(*preds, sep="\n")
+{'entity': 'I-ORG', 'score': 0.9968, 'index': 1, 'word': 'Hu', 'start': 0, 'end': 2}
+{'entity': 'I-ORG', 'score': 0.9293, 'index': 2, 'word': '##gging', 'start': 2, 'end': 7}
+{'entity': 'I-ORG', 'score': 0.9763, 'index': 3, 'word': 'Face', 'start': 8, 'end': 12}
+{'entity': 'I-MISC', 'score': 0.9983, 'index': 6, 'word': 'French', 'start': 18, 'end': 24}
+{'entity': 'I-LOC', 'score': 0.999, 'index': 10, 'word': 'New', 'start': 42, 'end': 45}
+{'entity': 'I-LOC', 'score': 0.9987, 'index': 11, 'word': 'York', 'start': 46, 'end': 50}
+{'entity': 'I-LOC', 'score': 0.9992, 'index': 12, 'word': 'City', 'start': 51, 'end': 55}
+```
+
+### ì§ììë”[[question_answering]]
+
+ì§ììë”ì ë íëì í í° ì°šìì ìì
ìŒëĄ, ëŹžë§„ìŽ ìì ë(ê°ë°©í ëë©ìž)ì ëŹžë§„ìŽ ìì ë(íìí ëë©ìž) ì§ëŹžì ëí ë”ëłì ë°íí©ëë€. ìŽ ìì
ì ê°ì ëčììêČ ìëčìŽ ìì
ì€ìžì§ì ê°ì ì§ëŹžì í ëë§ë€ ë°ìí ì ìì”ëë€. êł ê° ì§ì ëë êž°ì ì§ìì ì êł”íê±°ë êČì ìì§ìŽ ììČí ì ëłŽë„Œ êČìíë ë° ëìì ì€ ì ìì”ëë€.
+
+ì§ëŹž ë”ëłìë ìŒë°ì ìŒëĄ ë ê°ì§ ì íìŽ ìì”ëë€:
+
+* ì¶ì¶í: ì§ëŹžêłŒ ëŹžë§„ìŽ ìŁŒìŽìĄì ë, ëȘšëžìŽ ìŁŒìŽì§ 돞맄ì ìŒë¶ìì ê°ì žìš í
ì€ížì ëČì넌 ë”ëłìŒëĄ í©ëë€.
+* ìì±í: ì§ëŹžêłŒ ëŹžë§„ìŽ ìŁŒìŽìĄì ë, ìŁŒìŽì§ 돞맄ì í”íŽ ë”ëłì ìì±í©ëë€. ìŽ ì ê·Œ ë°©ìì [`QuestionAnsweringPipeline`] ëì [`Text2TextGenerationPipeline`]ì í”íŽ ìČ늏ë©ëë€.
+
+```py
+>>> from transformers import pipeline
+
+>>> question_answerer = pipeline(task="question-answering")
+>>> preds = question_answerer(
+... question="What is the name of the repository?",
+... context="The name of the repository is huggingface/transformers",
+... )
+>>> print(
+... f"score: {round(preds['score'], 4)}, start: {preds['start']}, end: {preds['end']}, answer: {preds['answer']}"
+... )
+score: 0.9327, start: 30, end: 54, answer: huggingface/transformers
+```
+
+### ììœ[[summarization]]
+
+ììœì ìëłž 돞ìì ìëŻžë„Œ ì”ëí ëłŽìĄŽí멎ì ꞎ 돞ì넌 ì§§ì 돞ìëĄ ë§ëë ìì
ì
ëë€. ììœì `sequence-to-sequence` ìì
ì
ëë€. ì
ë „ëłŽë€ ì§§ì í
ì€íž ìíì€ë„Œ ì¶ë „í©ëë€. ììœ ìì
ì ë
ìê° ì„돞 돞ìë€ì ìŁŒì íŹìžížë„Œ ëč 넎êČ ìŽíŽíë ë° ëìì ì€ ì ìì”ëë€. ì
ëČì, ëČë„ ë° êžì” 돞ì, íčí ë° êłŒí ë
ŒëŹžì ììœ ìì
ìŽ ë
ìì ìê°ì ì ìœíêł ë
ì ëłŽìĄ° ëê”ŹëĄ ìŹì©ë ì ìë ëȘ ê°ì§ ììì
ëë€.
+
+ì§ëŹž ë”ëłêłŒ ë§ì°Źê°ì§ëĄ ììœìë ë ê°ì§ ì íìŽ ìì”ëë€:
+
+* ì¶ì¶í: ìëłž í
ì€ížìì ê°ì„ ì€ìí 돞ì„ì ìëłíêł ì¶ì¶í©ëë€.
+* ìì±í: ìëłž í
ì€ížìì ëȘ©í ììœì ìì±í©ëë€. ì
ë „ 돞ìì ìë ìëĄìŽ ëšìŽë„Œ íŹíší ìë ìì”ëë€. [`SummarizationPipeline`]ì ìì±í ì ê·Œ ë°©ìì ìŹì©í©ëë€.
+
+```py
+>>> from transformers import pipeline
+
+>>> summarizer = pipeline(task="summarization")
+>>> summarizer(
+... "In this work, we presented the Transformer, the first sequence transduction model based entirely on attention, replacing the recurrent layers most commonly used in encoder-decoder architectures with multi-headed self-attention. For translation tasks, the Transformer can be trained significantly faster than architectures based on recurrent or convolutional layers. On both WMT 2014 English-to-German and WMT 2014 English-to-French translation tasks, we achieve a new state of the art. In the former task our best model outperforms even all previously reported ensembles."
+... )
+[{'summary_text': ' The Transformer is the first sequence transduction model based entirely on attention . It replaces the recurrent layers most commonly used in encoder-decoder architectures with multi-headed self-attention . For translation tasks, the Transformer can be trained significantly faster than architectures based on recurrent or convolutional layers .'}]
+```
+
+### ëČì[[translation]]
+
+ëČìì í ìžìŽëĄ ë í
ì€íž ìíì€ë„Œ ë€ë„ž ìžìŽëĄ ëłííë ìì
ì
ëë€. ìŽë ìëĄ ë€ë„ž ë°°êČœì ê°ì§ ìŹëë€ìŽ ìëĄ ìí”íë ë° ëìì ìŁŒë ì€ìí ìí ì í©ëë€. ë ëì ëì€ìêČ ìœí
ìž ë„Œ ëČìíìŹ ì ëŹíê±°ë, ìëĄìŽ ìžìŽë„Œ ë°°ì°ë ë° ëììŽ ëë íì” ëê”Źê° ë ìë ìì”ëë€. ììœêłŒ ë§ì°Źê°ì§ëĄ, ëČìì `sequence-to-sequence` ìì
ì
ëë€. ìŠ, ëȘšëžì ì
ë „ ìíì€ë„Œ ë°ìì ì¶ë „ìŽ ëë ëȘ©í ìíì€ë„Œ ë°íí©ëë€.
+
+ìŽêž°ì ëČì ëȘšëžì ëë¶ë¶ ëšìŒ ìžìŽëĄ ìŽëŁšìŽì ž ììì§ë§, ì”ê·Œìë ë§ì ìžìŽ ì ê°ì ëČìì ìíí ì ìë ë€ì€ ìžìŽ ëȘšëžì ëí êŽìŹìŽ ëìì§êł ìì”ëë€.
+
+```py
+>>> from transformers import pipeline
+
+>>> text = "translate English to French: Hugging Face is a community-based open-source platform for machine learning."
+>>> translator = pipeline(task="translation", model="t5-small")
+>>> translator(text)
+[{'translation_text': "Hugging Face est une tribune communautaire de l'apprentissage des machines."}]
+```
+
+### ìžìŽ ëȘšëžë§[[language_modeling]]
+
+ìžìŽ ëȘšëžë§ì í
ì€íž ìíì€ìì ëšìŽë„Œ ììžĄíë ìì
ì
ëë€. ìŹì íë šë ìžìŽ ëȘšëžì ë§ì ë€ë„ž íì ìì
ì ë°ëŒ ëŻžìž ìĄ°ì ë ì ìêž° ë돞ì ë§€ì° ìžêž° ìë ìì°ìŽìČ늏 ìì
ìŽ ëìì”ëë€. ì”ê·Œìë ì ëĄ ì·(zero-shot) ëë íš ì·(few-shot) íì”ìŽ ê°ë„í ëê·ëȘš ìžìŽ ëȘšëž(Large Language Models, LLM)ì ëí ë§ì êŽìŹìŽ ë°ìíêł ìì”ëë€. ìŽë ëȘšëžìŽ ëȘ
ìì ìŒëĄ íë šëì§ ìì ìì
ë íŽêȰí ì ìë€ë êČì ì믞í©ëë€! ìžìŽ ëȘšëžì ì ì°œíêł ì€ëë „ ìë í
ì€ížë„Œ ìì±íë ë° ìŹì©ë ì ìì§ë§, í
ì€ížê° íì ì ííì§ë ìì ì ììŒëŻëĄ ìŁŒìê° íìí©ëë€.
+
+ìžìŽ ëȘšëžë§ìë ë ê°ì§ ì íìŽ ìì”ëë€:
+
+* ìžêłŒì ìžìŽ ëȘšëžë§: ìŽ ëȘšëžì ëȘ©ì ì ìíì€ìì ë€ì í í°ì ììžĄíë êČìŽë©°, 믞ë í í°ìŽ ë§ì€íč ë©ëë€.
+ ```py
+ >>> from transformers import pipeline
+
+ >>> prompt = "Hugging Face is a community-based open-source platform for machine learning."
+ >>> generator = pipeline(task="text-generation")
+ >>> generator(prompt) # doctest: +SKIP
+ ```
+
+* ë§ì€íčë ìžìŽ ëȘšëžë§: ìŽ ëȘšëžì ëȘ©ì ì ìíì€ ëŽì ë§ì€íčë í í°ì ììžĄíë êČìŽë©°, ìíì€ ëŽì ëȘšë í í°ì ëí ì ê·ŒìŽ ì êł”ë©ëë€.
+
+ ```py
+ >>> text = "Hugging Face is a community-based open-source for machine learning."
+ >>> fill_mask = pipeline(task="fill-mask")
+ >>> preds = fill_mask(text, top_k=1)
+ >>> preds = [
+ ... {
+ ... "score": round(pred["score"], 4),
+ ... "token": pred["token"],
+ ... "token_str": pred["token_str"],
+ ... "sequence": pred["sequence"],
+ ... }
+ ... for pred in preds
+ ... ]
+ >>> preds
+ [{'score': 0.2236,
+ 'token': 1761,
+ 'token_str': ' platform',
+ 'sequence': 'Hugging Face is a community-based open-source platform for machine learning.'}]
+ ```
+
+ìŽ íìŽì§ë„Œ í”íŽ ê° ëȘšëŹëŠŹí°ì ë€ìí ìì
ì íêłŒ ê° ìì
ì ì€ì©ì ì€ìì±ì ëíŽ ì¶ê°ì ìž ë°°êČœ ì ëłŽë„Œ ì»ìŒì
šêž°ë„Œ ë°ëëë€. ë€ì [ìčì
](tasks_explained)ììë đ€ Transformerê° ìŽëŹí ìì
ì íŽêȰíë **ë°©ëČ**ì ëíŽ ììëłŽì€ ì ìì”ëë€.
\ No newline at end of file
diff --git a/docs/source/ko/tasks/asr.md b/docs/source/ko/tasks/asr.md
new file mode 100644
index 000000000000..47a568ecf02b
--- /dev/null
+++ b/docs/source/ko/tasks/asr.md
@@ -0,0 +1,380 @@
+
+
+# ìë ìì± ìžì[[automatic-speech-recognition]]
+
+[[open-in-colab]]
+
+
+
+ìë ìì± ìžì(Automatic Speech Recognition, ASR)ì ìì± ì ížë„Œ í
ì€ížëĄ ëłííìŹ ìì± ì
ë „ ìíì€ë„Œ í
ì€íž ì¶ë „ì ë§€íí©ëë€.
+Siriì Alexaì ê°ì ê°ì ìŽìì€íŽížë ASR ëȘšëžì ìŹì©íìŹ ìŒìì ìŒëĄ ìŹì©ì넌 ëêł ììŒë©°, íì ì€ ëŒìŽëž ìșĄì
ë° ë©ëȘš ìì±êłŒ ê°ì ì ì©í ìŹì©ì ìčíì ìì© íëĄê·žëšë ë§ìŽ ìì”ëë€.
+
+ìŽ ê°ìŽëìì ìê°í ëŽì©ì ìëì ê°ì”ëë€:
+
+1. [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) ë°ìŽí° ìžížìì [Wav2Vec2](https://huggingface.co/facebook/wav2vec2-base)넌 ëŻžìž ìĄ°ì íìŹ ì€ëì€ë„Œ í
ì€ížëĄ ëłíí©ëë€.
+2. ëŻžìž ìĄ°ì í ëȘšëžì ì¶ëĄ ì ìŹì©í©ëë€.
+
+
+ìŽ íí 늏ìŒìì ì€ëȘ
íë ìì
ì ë€ì ëȘšëž ìí€í
ìČì ìíŽ ì§ìë©ëë€:
+
+
+
+[Data2VecAudio](../model_doc/data2vec-audio), [Hubert](../model_doc/hubert), [M-CTC-T](../model_doc/mctct), [SEW](../model_doc/sew), [SEW-D](../model_doc/sew-d), [UniSpeech](../model_doc/unispeech), [UniSpeechSat](../model_doc/unispeech-sat), [Wav2Vec2](../model_doc/wav2vec2), [Wav2Vec2-Conformer](../model_doc/wav2vec2-conformer), [WavLM](../model_doc/wavlm)
+
+
+
+
+
+ììíêž° ì ì íìí ëȘšë ëŒìŽëžëŹëŠŹê° ì€ìčëìŽ ìëì§ íìžíìžì:
+
+```bash
+pip install transformers datasets evaluate jiwer
+```
+
+Hugging Face êłì ì ëĄê·žìží멎 ëȘšëžì ì
ëĄëíêł ì»€ëź€ëí°ì êł”ì í ì ìì”ëë€. í í°ì ì
ë „íìŹ ëĄê·žìžíìžì.
+
+```py
+>>> from huggingface_hub import notebook_login
+
+>>> notebook_login()
+```
+
+## MInDS-14 ë°ìŽí° ìžíž ê°ì žì€êž°[[load-minds-14-dataset]]
+
+뚌ì , đ€ Datasets ëŒìŽëžëŹëŠŹìì [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) ë°ìŽí° ìžížì ìŒë¶ë¶ì ê°ì žì€ìžì.
+ìŽë êČ í멎 ì ìČŽ ë°ìŽí° ìžížì ëí íë šì ìê°ì ë€ìŽêž° ì ì ëȘšë êČìŽ ìëíëì§ ì€ííêł êČìŠí ì ìì”ëë€.
+
+```py
+>>> from datasets import load_dataset, Audio
+
+>>> minds = load_dataset("PolyAI/minds14", name="en-US", split="train[:100]")
+```
+
+[`~Dataset.train_test_split`] ë©ìë넌 ìŹì©íìŹ ë°ìŽí° ìžížì `train`ì íë š ìžížì í
ì€íž ìžížëĄ ëëìžì:
+
+```py
+>>> minds = minds.train_test_split(test_size=0.2)
+```
+
+ê·žëŠŹêł ë°ìŽí° ìžížë„Œ íìžíìžì:
+
+```py
+>>> minds
+DatasetDict({
+ train: Dataset({
+ features: ['path', 'audio', 'transcription', 'english_transcription', 'intent_class', 'lang_id'],
+ num_rows: 16
+ })
+ test: Dataset({
+ features: ['path', 'audio', 'transcription', 'english_transcription', 'intent_class', 'lang_id'],
+ num_rows: 4
+ })
+})
+```
+
+ë°ìŽí° ìžížìë `lang_id`ì `english_transcription`êłŒ ê°ì ì ì©í ì ëłŽê° ë§ìŽ íŹíšëìŽ ìì§ë§, ìŽ ê°ìŽëììë `audio`ì `transcription`ì ìŽì ì ë§ì¶ êČì
ëë€. ë€ë„ž ìŽì [`~datasets.Dataset.remove_columns`] ë©ìë넌 ìŹì©íìŹ ì ê±°íìžì:
+
+```py
+>>> minds = minds.remove_columns(["english_transcription", "intent_class", "lang_id"])
+```
+
+ìì넌 ë€ì íëČ íìžíŽëłŽìžì:
+
+```py
+>>> minds["train"][0]
+{'audio': {'array': array([-0.00024414, 0. , 0. , ..., 0.00024414,
+ 0.00024414, 0.00024414], dtype=float32),
+ 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~APP_ERROR/602ba9e2963e11ccd901cd4f.wav',
+ 'sampling_rate': 8000},
+ 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~APP_ERROR/602ba9e2963e11ccd901cd4f.wav',
+ 'transcription': "hi I'm trying to use the banking app on my phone and currently my checking and savings account balance is not refreshing"}
+```
+
+ë ê°ì íëê° ìì”ëë€:
+
+- `audio`: ì€ëì€ íìŒì ê°ì žì€êł 늏ìíë§íêž° ìíŽ ížì¶íŽìŒ íë ìì± ì ížì 1ì°šì `array(ë°°ìŽ)`
+- `transcription`: ëȘ©í í
ì€íž
+
+## ì ìČ늏[[preprocess]]
+
+ë€ììŒëĄ ì€ëì€ ì ížë„Œ ìČ늏íêž° ìí Wav2Vec2 íëĄìžì넌 ê°ì žì”ëë€:
+
+```py
+>>> from transformers import AutoProcessor
+
+>>> processor = AutoProcessor.from_pretrained("facebook/wav2vec2-base")
+```
+
+MInDS-14 ë°ìŽí° ìžížì ìíë§ ë ìŽížë 8000kHzìŽëŻëĄ([ë°ìŽí° ìžíž ìčŽë](https://huggingface.co/datasets/PolyAI/minds14)ìì íìž), ìŹì íë šë Wav2Vec2 ëȘšëžì ìŹì©íë €ë©Ž ë°ìŽí° ìžížë„Œ 16000kHzëĄ ëŠŹìíë§íŽìŒ í©ëë€:
+
+```py
+>>> minds = minds.cast_column("audio", Audio(sampling_rate=16_000))
+>>> minds["train"][0]
+{'audio': {'array': array([-2.38064706e-04, -1.58618059e-04, -5.43987835e-06, ...,
+ 2.78103951e-04, 2.38446111e-04, 1.18740834e-04], dtype=float32),
+ 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~APP_ERROR/602ba9e2963e11ccd901cd4f.wav',
+ 'sampling_rate': 16000},
+ 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~APP_ERROR/602ba9e2963e11ccd901cd4f.wav',
+ 'transcription': "hi I'm trying to use the banking app on my phone and currently my checking and savings account balance is not refreshing"}
+```
+
+ìì 'transcription'ìì ëłŒ ì ìëŻìŽ í
ì€ížë ë돞ìì ì돞ìê° ììŹ ìì”ëë€. Wav2Vec2 í íŹëìŽì ë ë돞ì 돞ìì ëíŽìë§ íë šëìŽ ììŒëŻëĄ í
ì€ížê° í íŹëìŽì ì ìŽíì ìŒìčíëì§ íìžíŽìŒ í©ëë€:
+
+```py
+>>> def uppercase(example):
+... return {"transcription": example["transcription"].upper()}
+
+
+>>> minds = minds.map(uppercase)
+```
+
+ìŽì ë€ì ìì
ì ìíí ì ìČ늏 íšì넌 ë§ë€ìŽëłŽêČ ì”ëë€:
+
+1. `audio` ìŽì ížì¶íìŹ ì€ëì€ íìŒì ê°ì žì€êł 늏ìíë§í©ëë€.
+2. ì€ëì€ íìŒìì `input_values`넌 ì¶ì¶íêł íëĄìžìëĄ `transcription` ìŽì í í°íí©ëë€.
+
+```py
+>>> def prepare_dataset(batch):
+... audio = batch["audio"]
+... batch = processor(audio["array"], sampling_rate=audio["sampling_rate"], text=batch["transcription"])
+... batch["input_length"] = len(batch["input_values"][0])
+... return batch
+```
+
+ì ìČŽ ë°ìŽí° ìžížì ì ìČ늏 íšì넌 ì ì©íë €ë©Ž đ€ Datasets [`~datasets.Dataset.map`] íšì넌 ìŹì©íìžì. `num_proc` ë§€ê°ëłì넌 ìŹì©íìŹ íëĄìžì€ ì넌 ë늏멎 `map`ì ìë넌 ëìŒ ì ìì”ëë€. [`~datasets.Dataset.remove_columns`] ë©ìë넌 ìŹì©íìŹ íìíì§ ìì ìŽì ì ê±°íìžì:
+
+```py
+>>> encoded_minds = minds.map(prepare_dataset, remove_columns=minds.column_names["train"], num_proc=4)
+```
+
+đ€ Transformersìë ìë ìì± ìžìì© ë°ìŽí° ìœë ìŽí°ê° ììŒëŻëĄ ìì ë°°ìč넌 ìì±íë €ë©Ž [`DataCollatorWithPadding`]ì ìĄ°ì íŽìŒ í©ëë€. ìŽë êČ í멎 ë°ìŽí° ìœë ìŽí°ë í
ì€ížì ë ìŽëžì ë°°ìčìì ê°ì„ ꞎ ììì êžžìŽì ëì ìŒëĄ íšë©íìŹ êžžìŽë„Œ ê· ìŒíêČ í©ëë€. `tokenizer` íšììì `padding=True`넌 ì€ì íìŹ í
ì€ížë„Œ íšë©í ì ìì§ë§, ëì íšë©ìŽ ë íšìšì ì
ëë€.
+
+ë€ë„ž ë°ìŽí° ìœë ìŽí°ì ëŹëŠŹ ìŽ íčì ë°ìŽí° ìœë ìŽí°ë `input_values`ì `labels`ì ëíŽ ë€ë„ž íšë© ë°©ëČì ì ì©íŽìŒ í©ëë€.
+
+```py
+>>> import torch
+
+>>> from dataclasses import dataclass, field
+>>> from typing import Any, Dict, List, Optional, Union
+
+
+>>> @dataclass
+... class DataCollatorCTCWithPadding:
+... processor: AutoProcessor
+... padding: Union[bool, str] = "longest"
+
+... def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:
+... # ì
ë „êłŒ ë ìŽëžì ë¶í í©ëë€
+... # êžžìŽê° ë€ë„Žêł , ê°ê° ë€ë„ž íšë© ë°©ëČì ìŹì©íŽìŒ íêž° ë돞ì
ëë€
+... input_features = [{"input_values": feature["input_values"][0]} for feature in features]
+... label_features = [{"input_ids": feature["labels"]} for feature in features]
+
+... batch = self.processor.pad(input_features, padding=self.padding, return_tensors="pt")
+
+... labels_batch = self.processor.pad(labels=label_features, padding=self.padding, return_tensors="pt")
+
+... # íšë©ì ëíŽ ìì€ì ì ì©íì§ ìëëĄ -100ìŒëĄ ëìČŽí©ëë€
+... labels = labels_batch["input_ids"].masked_fill(labels_batch.attention_mask.ne(1), -100)
+
+... batch["labels"] = labels
+
+... return batch
+```
+
+ìŽì `DataCollatorForCTCWithPadding`ì ìžì€íŽì€íí©ëë€:
+
+```py
+>>> data_collator = DataCollatorCTCWithPadding(processor=processor, padding="longest")
+```
+
+## íê°íêž°[[evaluate]]
+
+íë š ì€ì íê° ì§í넌 íŹíší멎 ëȘšëžì ì±ë„ì íê°íë ë° ëììŽ ëë êČœì°ê° ë§ì”ëë€. đ€ [Evaluate](https://huggingface.co/docs/evaluate/index) ëŒìŽëžëŹëŠŹë„Œ ìŹì©í멎 íê° ë°©ëČì ëč 넎êČ ë¶ëŹìŹ ì ìì”ëë€.
+ìŽ ìì
ììë [ëšìŽ ì€ë„ìš(Word Error Rate, WER)](https://huggingface.co/spaces/evaluate-metric/wer) íê° ì§í넌 ê°ì žì”ëë€.
+(íê° ì§í넌 ë¶ëŹì€êł êłì°íë ë°©ëČì đ€ Evaluate [ëëŹëłŽêž°](https://huggingface.co/docs/evaluate/a_quick_tour)넌 ì°žìĄ°íìžì):
+
+```py
+>>> import evaluate
+
+>>> wer = evaluate.load("wer")
+```
+
+ê·žë° ë€ì ììžĄê°êłŒ ë ìŽëžì [`~evaluate.EvaluationModule.compute`]ì ì ëŹíìŹ WERì êłì°íë íšì넌 ë§ëëë€:
+
+```py
+>>> import numpy as np
+
+
+>>> def compute_metrics(pred):
+... pred_logits = pred.predictions
+... pred_ids = np.argmax(pred_logits, axis=-1)
+
+... pred.label_ids[pred.label_ids == -100] = processor.tokenizer.pad_token_id
+
+... pred_str = processor.batch_decode(pred_ids)
+... label_str = processor.batch_decode(pred.label_ids, group_tokens=False)
+
+... wer = wer.compute(predictions=pred_str, references=label_str)
+
+... return {"wer": wer}
+```
+
+ìŽì `compute_metrics` íšì넌 ìŹì©í ì€ëčê° ëììŒë©°, íë šì ì€ì í ë ìŽ íšìëĄ ëëììŹ êČì
ëë€.
+
+## íë šíêž°[[train]]
+
+
+
+
+
+[`Trainer`]ëĄ ëȘšëžì ëŻžìž ìĄ°ì íë êČìŽ ì”ìíì§ ìë€ë©Ž, [ìŹêž°](../training#train-with-pytorch-trainer)ìì êž°ëłž íí 늏ìŒì íìžíŽëłŽìžì!
+
+
+
+ìŽì ëȘšëž íë šì ììí ì€ëčê° ëìì”ëë€! [`AutoModelForCTC`]ëĄ Wav2Vec2넌 ê°ì žì€ìžì. `ctc_loss_reduction` ë§€ê°ëłìëĄ CTC ìì€ì ì ì©í ì¶ì(reduction) ë°©ëČì ì§ì íìžì. êž°ëłžê°ìž í©êł ëì íê· ì ìŹì©íë êČìŽ ë ìąì êČœì°ê° ë§ì”ëë€:
+
+```py
+>>> from transformers import AutoModelForCTC, TrainingArguments, Trainer
+
+>>> model = AutoModelForCTC.from_pretrained(
+... "facebook/wav2vec2-base",
+... ctc_loss_reduction="mean",
+... pad_token_id=processor.tokenizer.pad_token_id,
+... )
+```
+
+ìŽì ìž ëšêłë§ ëšìì”ëë€:
+
+1. [`TrainingArguments`]ìì íë š íìŽíŒíëŒëŻží°ë„Œ ì ìíìžì. `output_dir`ì ëȘšëžì ì ì„í êČœëĄë„Œ ì§ì íë ì ìŒí íì ë§€ê°ëłìì
ëë€. `push_to_hub=True`넌 ì€ì íìŹ ëȘšëžì Hubì ì
ëĄë í ì ìì”ëë€(ëȘšëžì ì
ëĄëíë €ë©Ž Hugging Faceì ëĄê·žìžíŽìŒ í©ëë€). [`Trainer`]ë ê° ìíë§ë€ WERì íê°íêł íë š ìČŽíŹíŹìžížë„Œ ì ì„í©ëë€.
+2. ëȘšëž, ë°ìŽí° ìžíž, í íŹëìŽì , ë°ìŽí° ìœë ìŽí°, `compute_metrics` íšìì íšê» [`Trainer`]ì íë š ìžì넌 ì ëŹíìžì.
+3. [`~Trainer.train`]ì ížì¶íìŹ ëȘšëžì ëŻžìž ìĄ°ì íìžì.
+
+```py
+>>> training_args = TrainingArguments(
+... output_dir="my_awesome_asr_mind_model",
+... per_device_train_batch_size=8,
+... gradient_accumulation_steps=2,
+... learning_rate=1e-5,
+... warmup_steps=500,
+... max_steps=2000,
+... gradient_checkpointing=True,
+... fp16=True,
+... group_by_length=True,
+... evaluation_strategy="steps",
+... per_device_eval_batch_size=8,
+... save_steps=1000,
+... eval_steps=1000,
+... logging_steps=25,
+... load_best_model_at_end=True,
+... metric_for_best_model="wer",
+... greater_is_better=False,
+... push_to_hub=True,
+... )
+
+>>> trainer = Trainer(
+... model=model,
+... args=training_args,
+... train_dataset=encoded_minds["train"],
+... eval_dataset=encoded_minds["test"],
+... tokenizer=processor.feature_extractor,
+... data_collator=data_collator,
+... compute_metrics=compute_metrics,
+... )
+
+>>> trainer.train()
+```
+
+íë šìŽ ìëŁë멎 ëȘšëê° ëȘšëžì ìŹì©í ì ìëëĄ [`~transformers.Trainer.push_to_hub`] ë©ìë넌 ìŹì©íìŹ ëȘšëžì Hubì êł”ì íìžì:
+
+```py
+>>> trainer.push_to_hub()
+```
+
+
+
+
+
+ìë ìì± ìžìì ìíŽ ëȘšëžì ëŻžìž ìĄ°ì íë ë ììží ìì ë ììŽ ìë ìì± ìžìì ìí [ëžëĄê·ž íŹì€íž](https://huggingface.co/blog/fine-tune-wav2vec2-english)ì ë€ê”ìŽ ìë ìì± ìžìì ìí [íŹì€íž](https://huggingface.co/blog/fine-tune-xlsr-wav2vec2)넌 ì°žìĄ°íìžì.
+
+
+
+## ì¶ëĄ íêž°[[inference]]
+
+ìąìì, ìŽì ëȘšëžì ëŻžìž ìĄ°ì íìŒë ì¶ëĄ ì ìŹì©í ì ìì”ëë€!
+
+ì¶ëĄ ì ìŹì©í ì€ëì€ íìŒì ê°ì žì€ìžì. íìí êČœì° ì€ëì€ íìŒì ìíë§ ëčìšì ëȘšëžì ìíë§ ë ìŽížì ë§êČ ëŠŹìíë§íë êČì ìì§ ë§ìžì!
+
+```py
+>>> from datasets import load_dataset, Audio
+
+>>> dataset = load_dataset("PolyAI/minds14", "en-US", split="train")
+>>> dataset = dataset.cast_column("audio", Audio(sampling_rate=16000))
+>>> sampling_rate = dataset.features["audio"].sampling_rate
+>>> audio_file = dataset[0]["audio"]["path"]
+```
+
+ì¶ëĄ ì ìíŽ ëŻžìž ìĄ°ì ë ëȘšëžì ìííŽëłŽë ê°ì„ ê°ëší ë°©ëČì [`pipeline`]ì ìŹì©íë êČì
ëë€. ëȘšëžì ìŹì©íìŹ ìë ìì± ìžìì ìí `pipeline`ì ìžì€íŽì€ííêł ì€ëì€ íìŒì ì ëŹíìžì:
+
+```py
+>>> from transformers import pipeline
+
+>>> transcriber = pipeline("automatic-speech-recognition", model="stevhliu/my_awesome_asr_minds_model")
+>>> transcriber(audio_file)
+{'text': 'I WOUD LIKE O SET UP JOINT ACOUNT WTH Y PARTNER'}
+```
+
+
+
+í
ì€ížëĄ ëłíë êČ°êłŒê° êœ€ êŽì°źì§ë§ ë ìąì ìë ìì”ëë€! ë ëì êČ°êłŒë„Œ ì»ìŒë €ë©Ž ë ë§ì ìì ëĄ ëȘšëžì ëŻžìž ìĄ°ì íìžì!
+
+
+
+`pipeline`ì êČ°êłŒë„Œ ìëìŒëĄ ìŹíí ìë ìì”ëë€:
+
+
+
+ì€ëì€ íìŒêłŒ í
ì€ížë„Œ ì ìČ늏íêł PyTorch í
ìëĄ `input`ì ë°íí íëĄìžì넌 ê°ì žì€ìžì:
+
+```py
+>>> from transformers import AutoProcessor
+
+>>> processor = AutoProcessor.from_pretrained("stevhliu/my_awesome_asr_mind_model")
+>>> inputs = processor(dataset[0]["audio"]["array"], sampling_rate=sampling_rate, return_tensors="pt")
+```
+
+ì
ë „ì ëȘšëžì ì ëŹíêł ëĄì§ì ë°ííìžì:
+
+```py
+>>> from transformers import AutoModelForCTC
+
+>>> model = AutoModelForCTC.from_pretrained("stevhliu/my_awesome_asr_mind_model")
+>>> with torch.no_grad():
+... logits = model(**inputs).logits
+```
+
+ê°ì„ ëì íë„ ì `input_ids`넌 ììžĄíêł , íëĄìžì넌 ìŹì©íìŹ ììžĄë `input_ids`넌 ë€ì í
ì€ížëĄ ëìœë©íìžì:
+
+```py
+>>> import torch
+
+>>> predicted_ids = torch.argmax(logits, dim=-1)
+>>> transcription = processor.batch_decode(predicted_ids)
+>>> transcription
+['I WOUL LIKE O SET UP JOINT ACOUNT WTH Y PARTNER']
+```
+
+
\ No newline at end of file
diff --git a/docs/source/ko/tasks/document_question_answering.md b/docs/source/ko/tasks/document_question_answering.md
new file mode 100644
index 000000000000..b9e98f3bf672
--- /dev/null
+++ b/docs/source/ko/tasks/document_question_answering.md
@@ -0,0 +1,482 @@
+
+
+# 돞ì ì§ì ìë”(Document Question Answering) [[document_question_answering]]
+
+[[open-in-colab]]
+
+돞ì ìê°ì ì§ì ìë”(Document Visual Question Answering)ìŽëŒêł ë íë
+돞ì ì§ì ìë”(Document Question Answering)ì 돞ì ìŽëŻžì§ì ëí ì§ëŹžì ë”ëłì ìŁŒë íì€íŹì
ëë€.
+ìŽ íì€íŹë„Œ ì§ìíë ëȘšëžì ì
ë „ì ìŒë°ì ìŒëĄ ìŽëŻžì§ì ì§ëŹžì ìĄ°í©ìŽêł , ì¶ë „ì ìì°ìŽëĄ ë ë”ëłì
ëë€. ìŽëŹí ëȘšëžì í
ì€íž, ëšìŽì ììč(ë°ìŽë© ë°ì€), ìŽëŻžì§ ë± ë€ìí ëȘšëŹëŠŹí°ë„Œ íì©í©ëë€.
+
+ìŽ ê°ìŽëë ë€ì ëŽì©ì ì€ëȘ
í©ëë€:
+
+- [DocVQA dataset](https://huggingface.co/datasets/nielsr/docvqa_1200_examples_donut)ì ìŹì©íŽ [LayoutLMv2](../model_doc/layoutlmv2) ëŻžìž ìĄ°ì íêž°
+- ì¶ëĄ ì ìíŽ ëŻžìž ìĄ°ì ë ëȘšëžì ìŹì©íêž°
+
+
+
+ìŽ íí 늏ìŒìì ì€ëȘ
íë íì€íŹë ë€ìêłŒ ê°ì ëȘšëž ìí€í
ìČìì ì§ìë©ëë€:
+
+
+
+[LayoutLM](../model_doc/layoutlm), [LayoutLMv2](../model_doc/layoutlmv2), [LayoutLMv3](../model_doc/layoutlmv3)
+
+
+
+
+
+LayoutLMv2ë í í°ì ë§ì§ë§ ìëìž” ìì ì§ì ìë” í€ë넌 ì¶ê°íŽ ë”ëłì ìì í í°êłŒ ë í í°ì ììč넌 ììžĄíšìŒëĄìš 돞ì ì§ì ìë” íì€íŹë„Œ íŽêȰí©ëë€. ìŠ, ëŹžë§„ìŽ ìŁŒìŽìĄì ë ì§ëŹžì ë”íë ì ëłŽë„Œ ì¶ì¶íë ì¶ì¶í ì§ì ìë”(Extractive question answering)ìŒëĄ 돞ì 넌 ìČ늏í©ëë€.
+돞맄ì OCR ìì§ì ì¶ë „ìì ê°ì žì€ë©°, ìŹêž°ìë Googleì Tesseract넌 ìŹì©í©ëë€.
+
+ììíêž° ì ì íìí ëŒìŽëžëŹëŠŹê° ëȘšë ì€ìčëìŽ ìëì§ íìžíìžì. LayoutLMv2ë detectron2, torchvision ë° í
ìëížë„Œ íìëĄ í©ëë€.
+
+```bash
+pip install -q transformers datasets
+```
+
+```bash
+pip install 'git+https://github.com/facebookresearch/detectron2.git'
+pip install torchvision
+```
+
+```bash
+sudo apt install tesseract-ocr
+pip install -q pytesseract
+```
+
+íìí ëŒìŽëžëŹëŠŹë€ì ëȘšë ì€ìčí í ë°íìì ë€ì ììí©ëë€.
+
+ì»€ëź€ëí°ì ëčì ì ëȘšëžì êł”ì íë êČì ê¶ì„í©ëë€. Hugging Face êłì ì ëĄê·žìžíŽì ëȘšëžì đ€ Hubì ì
ëĄëíìžì.
+í륏íížê° ì€íë멎, ëĄê·žìžì ìíŽ í í°ì ì
ë „íìžì:
+
+```py
+>>> from huggingface_hub import notebook_login
+
+>>> notebook_login()
+```
+
+ëȘ ê°ì§ ì ì ëłì넌 ì ìíŽ ëłŽêČ ì”ëë€.
+
+```py
+>>> model_checkpoint = "microsoft/layoutlmv2-base-uncased"
+>>> batch_size = 4
+```
+
+## ë°ìŽí° ë¶ëŹì€êž° [[load-the-data]]
+
+ìŽ ê°ìŽëììë đ€ Hubìì ì°Ÿì ì ìë ì ìČ늏ë DocVQAì ìì ìíì ìŹì©í©ëë€.
+DocVQAì ì ìČŽ ë°ìŽí° ìžížë„Œ ìŹì©íêł ì¶ë€ë©Ž, [DocVQA homepage](https://rrc.cvc.uab.es/?ch=17)ì ê°ì
í ë€ìŽëĄë í ì ìì”ëë€. ì ìČŽ ë°ìŽí° ìžížë„Œ ë€ìŽëĄë íë€ë©Ž, ìŽ ê°ìŽë넌 êłì ì§ííêž° ìíŽ [đ€ datasetì íìŒì ê°ì žì€ë ë°©ëČ](https://huggingface.co/docs/datasets/loading#local-and-remote-files)ì íìžíìžì.
+
+```py
+>>> from datasets import load_dataset
+
+>>> dataset = load_dataset("nielsr/docvqa_1200_examples")
+>>> dataset
+DatasetDict({
+ train: Dataset({
+ features: ['id', 'image', 'query', 'answers', 'words', 'bounding_boxes', 'answer'],
+ num_rows: 1000
+ })
+ test: Dataset({
+ features: ['id', 'image', 'query', 'answers', 'words', 'bounding_boxes', 'answer'],
+ num_rows: 200
+ })
+})
+```
+
+볎ìë€ìíŒ, ë°ìŽí° ìžížë ìŽëŻž íë š ìžížì í
ì€íž ìžížëĄ ëëìŽì ž ìì”ëë€. 돎ììëĄ ìì 넌 ìŽíŽëłŽë©Žì íčì±ì íìžíŽëłŽìžì.
+
+```py
+>>> dataset["train"].features
+```
+
+ê° íëê° ëíëŽë ëŽì©ì ë€ìêłŒ ê°ì”ëë€:
+* `id`: ìì ì id
+* `image`: 돞ì ìŽëŻžì§ë„Œ íŹíšíë PIL.Image.Image ê°ìČŽ
+* `query`: ì§ëŹž 돞ììŽ - ìŹëŹ ìžìŽì ìì°ìŽëĄ ë ì§ëŹž
+* `answers`: ìŹëìŽ ìŁŒìì ëš ì ë” ëŠŹì€íž
+* `words` and `bounding_boxes`: OCRì êČ°êłŒê°ë€ìŽë©° ìŽ ê°ìŽëììë ìŹì©íì§ ìì ìì
+* `answer`: ë€ë„ž ëȘšëžêłŒ ìŒìčíë ë”ëłìŽë©° ìŽ ê°ìŽëììë ìŹì©íì§ ìì ìì
+
+ììŽëĄ ë ì§ëŹžë§ ëšêž°êł ë€ë„ž ëȘšëžì ëí ììžĄì íŹíšíë `answer` íčì±ì ìì íêČ ì”ëë€.
+ê·žëŠŹêł ìŁŒì ìì±ìê° ì êł”í ë°ìŽí° ìžížìì ìČ« ëČì§ž ë”ëłì ê°ì žì”ëë€. ëë 돎ììëĄ ìíì ì¶ì¶í ìë ìì”ëë€.
+
+```py
+>>> updated_dataset = dataset.map(lambda example: {"question": example["query"]["en"]}, remove_columns=["query"])
+>>> updated_dataset = updated_dataset.map(
+... lambda example: {"answer": example["answers"][0]}, remove_columns=["answer", "answers"]
+... )
+```
+
+ìŽ ê°ìŽëìì ìŹì©íë LayoutLMv2 ìČŽíŹíŹìžížë `max_position_embeddings = 512`ëĄ íë šëìì”ëë€(ìŽ ì 볎ë [ìČŽíŹíŹìžížì `config.json` íìŒ](https://huggingface.co/microsoft/layoutlmv2-base-uncased/blob/main/config.json#L18)ìì íìží ì ìì”ëë€).
+ë°ëĄ ìì 넌 ìëŒëŒ ìë ìì§ë§, ꞎ 돞ìì ëì ë”ëłìŽ ììŽ ì늏ë ìí©ì íŒíêž° ìíŽ ìŹêž°ìë ìëČ ë©ìŽ 512ëłŽë€ êžžìŽì§ ê°ë„ì±ìŽ ìë ëȘ ê°ì§ ìì 넌 ì ê±°íêČ ì”ëë€.
+ë°ìŽí° ìžížì ìë ëë¶ë¶ì 돞ìê° êžŽ êČœì° ìŹëŒìŽë© ìëì° ë°©ëČì ìŹì©í ì ìì”ëë€ - ììží ëŽì©ì íìžíêł ì¶ìŒë©Ž ìŽ [ë
žížë¶](https://github.com/huggingface/notebooks/blob/main/examples/question_answering.ipynb)ì íìžíìžì.
+
+```py
+>>> updated_dataset = updated_dataset.filter(lambda x: len(x["words"]) + len(x["question"].split()) < 512)
+```
+
+ìŽ ìì ìì ìŽ ë°ìŽí° ìžížì OCR íčì±ë ì ê±°íŽ ëłŽêČ ì”ëë€. OCR íčì±ì ë€ë„ž ëȘšëžì ëŻžìž ìĄ°ì íêž° ìí êČìŒëĄ, ìŽ ê°ìŽëìì ìŹì©íë ëȘšëžì ì
ë „ ìê”Ź ìŹíêłŒ ìŒìčíì§ ìêž° ë돞ì ìŽ íčì±ì ìŹì©íêž° ìíŽìë ìŒë¶ ìČëŠŹê° íìí©ëë€.
+ëì , ìëłž ë°ìŽí°ì [`LayoutLMv2Processor`]넌 ìŹì©íìŹ OCR ë° í í°í넌 ëȘšë ìíí ì ìì”ëë€.
+ìŽë êČ í멎 ëȘšëžìŽ ìê”Źíë ì
ë „ì ì»ì ì ìì”ëë€.
+ìŽëŻžì§ë„Œ ìëìŒëĄ ìČ늏íë €ë©Ž, [`LayoutLMv2` model documentation](../model_doc/layoutlmv2)ìì ëȘšëžìŽ ìê”Źíë ì
ë „ íŹë§·ì íìžíŽëłŽìžì.
+
+```py
+>>> updated_dataset = updated_dataset.remove_columns("words")
+>>> updated_dataset = updated_dataset.remove_columns("bounding_boxes")
+```
+
+ë§ì§ë§ìŒëĄ, ë°ìŽí° íìì ìëŁíêž° ìíŽ ìŽëŻžì§ ìì넌 ìŽíŽëŽ
ìë€.
+
+```py
+>>> updated_dataset["train"][11]["image"]
+```
+
+
+
+
+
+## ë°ìŽí° ì ìČ늏 [[preprocess-the-data]]
+
+
+돞ì ì§ì ìë” íì€íŹë ë©í°ëȘšëŹ íì€íŹìŽë©°, ê° ëȘšëŹëŠŹí°ì ì
ë „ìŽ ëȘšëžì ìê”Źì ë§êČ ì ìČ늏 ëìëì§ íìžíŽìŒ í©ëë€.
+ìŽëŻžì§ ë°ìŽí°ë„Œ ìČ늏í ì ìë ìŽëŻžì§ íëĄìžìì í
ì€íž ë°ìŽí°ë„Œ ìžìœë©í ì ìë í íŹëìŽì 넌 êȰí©í [`LayoutLMv2Processor`]넌 ê°ì žì€ë êČë¶í° ììíŽ ëłŽêČ ì”ëë€.
+
+```py
+>>> from transformers import AutoProcessor
+
+>>> processor = AutoProcessor.from_pretrained(model_checkpoint)
+```
+
+### 돞ì ìŽëŻžì§ ì ìČ늏 [[preprocessing-document-images]]
+
+뚌ì , íëĄìžìì `image_processor`넌 ìŹì©íŽ ëȘšëžì ëí 돞ì ìŽëŻžì§ë„Œ ì€ëčíŽ ëłŽêČ ì”ëë€.
+êž°ëłžê°ìŒëĄ, ìŽëŻžì§ íëĄìžìë ìŽëŻžì§ íŹêž°ë„Œ 224x224ëĄ ìĄ°ì íêł ìì ì±ëì ììê° ìŹë°ë„žì§ íìží í ëšìŽì ì ê·íë ë°ìŽë© ë°ì€ë„Œ ì»êž° ìíŽ í
ìëížë„Œ ìŹì©íŽ OCR넌 ì ì©í©ëë€.
+ìŽ íí 늏ìŒìì ì°ëŠŹê° íìí êČêłŒ êž°ëłžê°ì ìì í ëìŒí©ëë€. ìŽëŻžì§ ë°°ìčì êž°ëłž ìŽëŻžì§ ìČëŠŹë„Œ ì ì©íêł OCRì êČ°êłŒë„Œ ëłííë íšì넌 ìì±í©ëë€.
+
+```py
+>>> image_processor = processor.image_processor
+
+
+>>> def get_ocr_words_and_boxes(examples):
+... images = [image.convert("RGB") for image in examples["image"]]
+... encoded_inputs = image_processor(images)
+
+... examples["image"] = encoded_inputs.pixel_values
+... examples["words"] = encoded_inputs.words
+... examples["boxes"] = encoded_inputs.boxes
+
+... return examples
+```
+
+ìŽ ì ìČëŠŹë„Œ ë°ìŽí° ìžíž ì ìČŽì ëč 넎êČ ì ì©íë €ë©Ž [`~datasets.Dataset.map`]넌 ìŹì©íìžì.
+
+```py
+>>> dataset_with_ocr = updated_dataset.map(get_ocr_words_and_boxes, batched=True, batch_size=2)
+```
+
+### í
ì€íž ë°ìŽí° ì ìČ늏 [[preprocessing-text-data]]
+
+ìŽëŻžì§ì OCRì ì ì©íìŒë©Ž ë°ìŽí° ìžížì í
ì€íž ë¶ë¶ì ëȘšëžì ë§êČ ìžìœë©íŽìŒ í©ëë€.
+ìŽ ìžìœë©ìë ìŽì ëšêłìì ê°ì žìš ëšìŽì ë°ì€ë„Œ í í° ìì€ì `input_ids`, `attention_mask`, `token_type_ids` ë° `bbox`ëĄ ëłííë ìì
ìŽ íŹíšë©ëë€.
+í
ì€ížë„Œ ì ìČ늏íë €ë©Ž íëĄìžìì `tokenizer`ê° íìí©ëë€.
+
+```py
+>>> tokenizer = processor.tokenizer
+```
+
+ììì ìžêží ì ìČ늏 ìžìë ëȘšëžì ìíŽ ë ìŽëžì ì¶ê°íŽìŒ í©ëë€. đ€ Transformersì `xxxForQuestionAnswering` ëȘšëžì êČœì°, ë ìŽëžì `start_positions`ì `end_positions`ëĄ ê”Źì±ëë©° ìŽë€ í í°ìŽ ë”ëłì ììêłŒ ëì ìëì§ë„Œ ëíë
ëë€.
+
+ë ìŽëž ì¶ê°ë„Œ ìíŽì, 뚌ì ë í° ëŠŹì€íž(ëšìŽ ëŠŹì€íž)ìì íì 늏ì€íž(ëšìŽëĄ ë¶í ë ë”ëł)ì ì°Ÿì ì ìë íŹíŒ íšì넌 ì ìí©ëë€.
+
+ìŽ íšìë `words_list`ì `answer_list`, ìŽë êČ ë 늏ì€ížë„Œ ì
ë „ìŒëĄ ë°ì”ëë€.
+ê·žë° ë€ì `words_list`넌 ë°ëł”íìŹ `words_list`ì íìŹ ëšìŽ(words_list[i])ê° `answer_list`ì ìČ« ëČì§ž ëšìŽ(answer_list[0])ì ê°ìì§,
+íìŹ ëšìŽìì ììíŽ `answer_list`ì ê°ì êžžìŽë§íŒì `words_list`ì íì 늏ì€ížê° `answer_list`ì ìŒìčíëì§ íìží©ëë€.
+ìŽ ìĄ°ê±ŽìŽ ì°žìŽëŒë©Ž ìŒìčíë íëȘ©ì ë°êČŹíìì ì믞íë©°, íšìë ìŒìč íëȘ©, ìì ìžë±ì€(idx) ë° ìą
ëŁ ìžë±ì€(idx + len(answer_list) - 1)넌 êž°ëĄí©ëë€. ìŒìčíë íëȘ©ìŽ ë ê° ìŽì ë°êČŹë멎 íšìë ìČ« ëČì§ž íëȘ©ë§ ë°íí©ëë€. ìŒìčíë íëȘ©ìŽ ìë€ë©Ž íšìë (`None`, 0, 0)ì ë°íí©ëë€.
+
+```py
+>>> def subfinder(words_list, answer_list):
+... matches = []
+... start_indices = []
+... end_indices = []
+... for idx, i in enumerate(range(len(words_list))):
+... if words_list[i] == answer_list[0] and words_list[i : i + len(answer_list)] == answer_list:
+... matches.append(answer_list)
+... start_indices.append(idx)
+... end_indices.append(idx + len(answer_list) - 1)
+... if matches:
+... return matches[0], start_indices[0], end_indices[0]
+... else:
+... return None, 0, 0
+```
+
+ìŽ íšìê° ìŽë»êČ ì ë”ì ììč넌 ì°Ÿëì§ ì€ëȘ
íêž° ìíŽ ë€ì ìì ìì íšì넌 ìŹì©íŽ ëłŽêČ ì”ëë€:
+
+```py
+>>> example = dataset_with_ocr["train"][1]
+>>> words = [word.lower() for word in example["words"]]
+>>> match, word_idx_start, word_idx_end = subfinder(words, example["answer"].lower().split())
+>>> print("Question: ", example["question"])
+>>> print("Words:", words)
+>>> print("Answer: ", example["answer"])
+>>> print("start_index", word_idx_start)
+>>> print("end_index", word_idx_end)
+Question: Who is in cc in this letter?
+Words: ['wie', 'baw', 'brown', '&', 'williamson', 'tobacco', 'corporation', 'research', '&', 'development', 'internal', 'correspondence', 'to:', 'r.', 'h.', 'honeycutt', 'ce:', 't.f.', 'riehl', 'from:', '.', 'c.j.', 'cook', 'date:', 'may', '8,', '1995', 'subject:', 'review', 'of', 'existing', 'brainstorming', 'ideas/483', 'the', 'major', 'function', 'of', 'the', 'product', 'innovation', 'graup', 'is', 'to', 'develop', 'marketable', 'nove!', 'products', 'that', 'would', 'be', 'profitable', 'to', 'manufacture', 'and', 'sell.', 'novel', 'is', 'defined', 'as:', 'of', 'a', 'new', 'kind,', 'or', 'different', 'from', 'anything', 'seen', 'or', 'known', 'before.', 'innovation', 'is', 'defined', 'as:', 'something', 'new', 'or', 'different', 'introduced;', 'act', 'of', 'innovating;', 'introduction', 'of', 'new', 'things', 'or', 'methods.', 'the', 'products', 'may', 'incorporate', 'the', 'latest', 'technologies,', 'materials', 'and', 'know-how', 'available', 'to', 'give', 'then', 'a', 'unique', 'taste', 'or', 'look.', 'the', 'first', 'task', 'of', 'the', 'product', 'innovation', 'group', 'was', 'to', 'assemble,', 'review', 'and', 'categorize', 'a', 'list', 'of', 'existing', 'brainstorming', 'ideas.', 'ideas', 'were', 'grouped', 'into', 'two', 'major', 'categories', 'labeled', 'appearance', 'and', 'taste/aroma.', 'these', 'categories', 'are', 'used', 'for', 'novel', 'products', 'that', 'may', 'differ', 'from', 'a', 'visual', 'and/or', 'taste/aroma', 'point', 'of', 'view', 'compared', 'to', 'canventional', 'cigarettes.', 'other', 'categories', 'include', 'a', 'combination', 'of', 'the', 'above,', 'filters,', 'packaging', 'and', 'brand', 'extensions.', 'appearance', 'this', 'category', 'is', 'used', 'for', 'novel', 'cigarette', 'constructions', 'that', 'yield', 'visually', 'different', 'products', 'with', 'minimal', 'changes', 'in', 'smoke', 'chemistry', 'two', 'cigarettes', 'in', 'cne.', 'emulti-plug', 'te', 'build', 'yaur', 'awn', 'cigarette.', 'eswitchable', 'menthol', 'or', 'non', 'menthol', 'cigarette.', '*cigarettes', 'with', 'interspaced', 'perforations', 'to', 'enable', 'smoker', 'to', 'separate', 'unburned', 'section', 'for', 'future', 'smoking.', '«short', 'cigarette,', 'tobacco', 'section', '30', 'mm.', '«extremely', 'fast', 'buming', 'cigarette.', '«novel', 'cigarette', 'constructions', 'that', 'permit', 'a', 'significant', 'reduction', 'iretobacco', 'weight', 'while', 'maintaining', 'smoking', 'mechanics', 'and', 'visual', 'characteristics.', 'higher', 'basis', 'weight', 'paper:', 'potential', 'reduction', 'in', 'tobacco', 'weight.', '«more', 'rigid', 'tobacco', 'column;', 'stiffing', 'agent', 'for', 'tobacco;', 'e.g.', 'starch', '*colored', 'tow', 'and', 'cigarette', 'papers;', 'seasonal', 'promotions,', 'e.g.', 'pastel', 'colored', 'cigarettes', 'for', 'easter', 'or', 'in', 'an', 'ebony', 'and', 'ivory', 'brand', 'containing', 'a', 'mixture', 'of', 'all', 'black', '(black', 'paper', 'and', 'tow)', 'and', 'ail', 'white', 'cigarettes.', '499150498']
+Answer: T.F. Riehl
+start_index 17
+end_index 18
+```
+
+ííž, ì ìì ê° ìžìœë©ë멎 ë€ìêłŒ ê°ìŽ íìë©ëë€:
+
+```py
+>>> encoding = tokenizer(example["question"], example["words"], example["boxes"])
+>>> tokenizer.decode(encoding["input_ids"])
+[CLS] who is in cc in this letter? [SEP] wie baw brown & williamson tobacco corporation research & development ...
+```
+
+ìŽì ìžìœë©ë ì
ë „ìì ì ë”ì ììč넌 ì°ŸììŒ í©ëë€.
+* `token_type_ids`ë ìŽë€ í í°ìŽ ì§ëŹžì ìíëì§, ê·žëŠŹêł ìŽë€ í í°ìŽ ëŹžìì ëšìŽì íŹíšëëì§ë„Œ ìë €ì€ëë€.
+* `tokenizer.cls_token_id` ì
ë „ì ìì ë¶ë¶ì ìë íčì í í°ì ì°Ÿë ë° ëìì ì€ëë€.
+* `word_ids`ë ìëłž `words`ìì ì°Ÿì ë”ëłì ì ìČŽ ìžìœë©ë ì
ë „ì ëìŒí ë”êłŒ ìŒìčìí€êł ìžìœë©ë ì
ë „ìì ë”ëłì ìì/ë ììč넌 êȰì í©ëë€.
+
+ì ëŽì©ë€ì ìŒëì ëêł ë°ìŽí° ìžíž ìì ì ë°°ìč넌 ìžìœë©íë íšì넌 ë§ë€ìŽ ëłŽêČ ì”ëë€:
+
+```py
+>>> def encode_dataset(examples, max_length=512):
+... questions = examples["question"]
+... words = examples["words"]
+... boxes = examples["boxes"]
+... answers = examples["answer"]
+
+... # ìì ë°°ìč넌 ìžìœë©íêł start_positionsì end_positions넌 ìŽêž°íí©ëë€
+... encoding = tokenizer(questions, words, boxes, max_length=max_length, padding="max_length", truncation=True)
+... start_positions = []
+... end_positions = []
+
+... # ë°°ìčì ìì 넌 ë°ëł”í©ëë€
+... for i in range(len(questions)):
+... cls_index = encoding["input_ids"][i].index(tokenizer.cls_token_id)
+
+... # ìì ì wordsìì ë”ëłì ììč넌 ì°Ÿì”ëë€
+... words_example = [word.lower() for word in words[i]]
+... answer = answers[i]
+... match, word_idx_start, word_idx_end = subfinder(words_example, answer.lower().split())
+
+... if match:
+... # ìŒìčíë íëȘ©ì ë°êČŹí멎, `token_type_ids`넌 ìŹì©íŽ ìžìœë©ìì ëšìŽê° ììíë ììč넌 ì°Ÿì”ëë€
+... token_type_ids = encoding["token_type_ids"][i]
+... token_start_index = 0
+... while token_type_ids[token_start_index] != 1:
+... token_start_index += 1
+
+... token_end_index = len(encoding["input_ids"][i]) - 1
+... while token_type_ids[token_end_index] != 1:
+... token_end_index -= 1
+
+... word_ids = encoding.word_ids(i)[token_start_index : token_end_index + 1]
+... start_position = cls_index
+... end_position = cls_index
+
+... # wordsì ë”ëł ììčì ìŒìčí ëêčì§ word_ids넌 ë°ëł”íêł `token_start_index`넌 ë늜ëë€
+... # ìŒìčí멎 `token_start_index`넌 ìžìœë©ìì ë”ëłì `start_position`ìŒëĄ ì ì„í©ëë€
+... for id in word_ids:
+... if id == word_idx_start:
+... start_position = token_start_index
+... else:
+... token_start_index += 1
+
+... # ëčì·íêČ, ëìì ììíŽ `word_ids`넌 ë°ëł”íë©° ë”ëłì `end_position`ì ì°Ÿì”ëë€
+... for id in word_ids[::-1]:
+... if id == word_idx_end:
+... end_position = token_end_index
+... else:
+... token_end_index -= 1
+
+... start_positions.append(start_position)
+... end_positions.append(end_position)
+
+... else:
+... start_positions.append(cls_index)
+... end_positions.append(cls_index)
+
+... encoding["image"] = examples["image"]
+... encoding["start_positions"] = start_positions
+... encoding["end_positions"] = end_positions
+
+... return encoding
+```
+
+ìŽì ìŽ ì ìČ늏 íšìê° ììŒë ì ìČŽ ë°ìŽí° ìžížë„Œ ìžìœë©í ì ìì”ëë€:
+
+```py
+>>> encoded_train_dataset = dataset_with_ocr["train"].map(
+... encode_dataset, batched=True, batch_size=2, remove_columns=dataset_with_ocr["train"].column_names
+... )
+>>> encoded_test_dataset = dataset_with_ocr["test"].map(
+... encode_dataset, batched=True, batch_size=2, remove_columns=dataset_with_ocr["test"].column_names
+... )
+```
+
+ìžìœë©ë ë°ìŽí° ìžížì íčì±ìŽ ìŽë»êČ ìêČŒëì§ íìžíŽ ëłŽêČ ì”ëë€:
+
+```py
+>>> encoded_train_dataset.features
+{'image': Sequence(feature=Sequence(feature=Sequence(feature=Value(dtype='uint8', id=None), length=-1, id=None), length=-1, id=None), length=-1, id=None),
+ 'input_ids': Sequence(feature=Value(dtype='int32', id=None), length=-1, id=None),
+ 'token_type_ids': Sequence(feature=Value(dtype='int8', id=None), length=-1, id=None),
+ 'attention_mask': Sequence(feature=Value(dtype='int8', id=None), length=-1, id=None),
+ 'bbox': Sequence(feature=Sequence(feature=Value(dtype='int64', id=None), length=-1, id=None), length=-1, id=None),
+ 'start_positions': Value(dtype='int64', id=None),
+ 'end_positions': Value(dtype='int64', id=None)}
+```
+
+## íê° [[evaluation]]
+
+돞ì ì§ì ìë”ì íê°íë €ë©Ž ìëčí ìì íìČëŠŹê° íìí©ëë€. ìê°ìŽ ë돎 ë§ìŽ ê±žëŠŹì§ ìëëĄ ìŽ ê°ìŽëììë íê° ëšêłë„Œ ìë”í©ëë€.
+[`Trainer`]ê° íë š êłŒì ìì íê° ìì€(evaluation loss)ì êłì êłì°íêž° ë돞ì ëȘšëžì ì±ë„ì ëë”ì ìŒëĄ ì ì ìì”ëë€.
+ì¶ì¶ì (Extractive) ì§ì ìë”ì ëłŽí” F1/exact match ë°©ëČì ìŹì©íŽ íê°ë©ëë€.
+ì§ì ê”ŹííŽëłŽêł ì¶ìŒìë€ë©Ž, Hugging Face courseì [Question Answering chapter](https://huggingface.co/course/chapter7/7?fw=pt#postprocessing)ì ì°žêł íìžì.
+
+## íë š [[train]]
+
+ì¶íí©ëë€! ìŽ ê°ìŽëì ê°ì„ ìŽë €ìŽ ë¶ë¶ì ì±êł”ì ìŒëĄ ìČ늏íìŒë ìŽì ëë§ì ëȘšëžì íë ší ì€ëčê° ëìì”ëë€.
+íë šì ë€ìêłŒ ê°ì ëšêłëĄ ìŽëŁšìŽì ž ìì”ëë€:
+* ì ìČ늏ììì ëìŒí ìČŽíŹíŹìžížë„Œ ìŹì©íêž° ìíŽ [`AutoModelForDocumentQuestionAnswering`]ìŒëĄ ëȘšëžì ê°ì žì”ëë€.
+* [`TrainingArguments`]ëĄ íë š íìŽíŒíëŒëŻží°ë„Œ ì í©ëë€.
+* ìì 넌 ë°°ìč ìČ늏íë íšì넌 ì ìí©ëë€. ìŹêž°ìë [`DefaultDataCollator`]ê° ì ëčí©ëë€.
+* ëȘšëž, ë°ìŽí° ìžíž, ë°ìŽí° ìœë ìŽí°(Data collator)ì íšê» [`Trainer`]ì íë š ìžìë€ì ì ëŹí©ëë€.
+* [`~Trainer.train`]ì ížì¶íŽì ëȘšëžì ëŻžìž ìĄ°ì í©ëë€.
+
+```py
+>>> from transformers import AutoModelForDocumentQuestionAnswering
+
+>>> model = AutoModelForDocumentQuestionAnswering.from_pretrained(model_checkpoint)
+```
+
+[`TrainingArguments`]ìì `output_dir`ì ìŹì©íìŹ ëȘšëžì ì ì„í ììč넌 ì§ì íêł , ì ì í íìŽíŒíëŒëŻží°ë„Œ ì€ì í©ëë€.
+ëȘšëžì ì»€ëź€ëí°ì êł”ì íë €ë©Ž `push_to_hub`넌 `True`ëĄ ì€ì íìžì (ëȘšëžì ì
ëĄëíë €ë©Ž Hugging Faceì ëĄê·žìžíŽìŒ í©ëë€).
+ìŽ êČœì° `output_dir`ì ëȘšëžì ìČŽíŹíŹìžížë„Œ ížìí ë íŹì§í 늏ì ìŽëŠìŽ ë©ëë€.
+
+```py
+>>> from transformers import TrainingArguments
+
+>>> # ëłžìžì ë íŹì§í 늏 IDëĄ ë°êŸžìžì
+>>> repo_id = "MariaK/layoutlmv2-base-uncased_finetuned_docvqa"
+
+>>> training_args = TrainingArguments(
+... output_dir=repo_id,
+... per_device_train_batch_size=4,
+... num_train_epochs=20,
+... save_steps=200,
+... logging_steps=50,
+... evaluation_strategy="steps",
+... learning_rate=5e-5,
+... save_total_limit=2,
+... remove_unused_columns=False,
+... push_to_hub=True,
+... )
+```
+
+ê°ëší ë°ìŽí° ìœë ìŽí°ë„Œ ì ìíìŹ ìì 넌 íšê» ë°°ìčí©ëë€.
+
+```py
+>>> from transformers import DefaultDataCollator
+
+>>> data_collator = DefaultDataCollator()
+```
+
+ë§ì§ë§ìŒëĄ, ëȘšë êČì í êłłì ëȘšì [`~Trainer.train`]ì ížì¶í©ëë€:
+
+```py
+>>> from transformers import Trainer
+
+>>> trainer = Trainer(
+... model=model,
+... args=training_args,
+... data_collator=data_collator,
+... train_dataset=encoded_train_dataset,
+... eval_dataset=encoded_test_dataset,
+... tokenizer=processor,
+... )
+
+>>> trainer.train()
+```
+
+ì”ìą
ëȘšëžì đ€ Hubì ì¶ê°íë €ë©Ž, ëȘšëž ìčŽë넌 ìì±íêł `push_to_hub`넌 ížì¶í©ëë€:
+
+```py
+>>> trainer.create_model_card()
+>>> trainer.push_to_hub()
+```
+
+## ì¶ëĄ [[inference]]
+
+ìŽì LayoutLMv2 ëȘšëžì ëŻžìž ìĄ°ì íêł đ€ Hubì ì
ëĄëíìŒë ì¶ëĄ ìë ìŹì©í ì ìì”ëë€.
+ì¶ëĄ ì ìíŽ ëŻžìž ìĄ°ì ë ëȘšëžì ìŹì©íŽ ëłŽë ê°ì„ ê°ëší ë°©ëČì [`Pipeline`]ì ìŹì©íë êČ ì
ëë€.
+
+ì넌 ë€ìŽ ëłŽêČ ì”ëë€:
+```py
+>>> example = dataset["test"][2]
+>>> question = example["query"]["en"]
+>>> image = example["image"]
+>>> print(question)
+>>> print(example["answers"])
+'Who is âpresidingâ TRRF GENERAL SESSION (PART 1)?'
+['TRRF Vice President', 'lee a. waller']
+```
+
+ê·ž ë€ì, ëȘšëžëĄ 돞ì ì§ì ìë”ì íêž° ìíŽ íìŽíëŒìžì ìžì€íŽì€ííêł ìŽëŻžì§ + ì§ëŹž ìĄ°í©ì ì ëŹí©ëë€.
+
+```py
+>>> from transformers import pipeline
+
+>>> qa_pipeline = pipeline("document-question-answering", model="MariaK/layoutlmv2-base-uncased_finetuned_docvqa")
+>>> qa_pipeline(image, question)
+[{'score': 0.9949808120727539,
+ 'answer': 'Lee A. Waller',
+ 'start': 55,
+ 'end': 57}]
+```
+
+ìíë€ë©Ž íìŽíëŒìžì êČ°êłŒë„Œ ìëìŒëĄ ëł”ì í ìë ìì”ëë€:
+1. ìŽëŻžì§ì ì§ëŹžì ê°ì žì ëȘšëžì íëĄìžì넌 ìŹì©íŽ ëȘšëžì ë§êČ ì€ëčí©ëë€.
+2. ëȘšëžì í”íŽ êČ°êłŒ ëë ì ìČëŠŹë„Œ ì ëŹí©ëë€.
+3. ëȘšëžì ìŽë€ í í°ìŽ ë”ëłì ììì ìëì§, ìŽë€ í í°ìŽ ë”ëłìŽ ëì ìëì§ë„Œ ëíëŽë `start_logits`ì `end_logits`넌 ë°íí©ëë€. ë ë€ (batch_size, sequence_length) íí넌 ê°ì”ëë€.
+4. `start_logits`ì `end_logits`ì ë§ì§ë§ ì°šìì ì”ëëĄ ë§ëë ê°ì ì°Ÿì ìì `start_idx`ì `end_idx`넌 ì»ì”ëë€.
+5. í íŹëìŽì ëĄ ë”ëłì ëìœë©í©ëë€.
+
+```py
+>>> import torch
+>>> from transformers import AutoProcessor
+>>> from transformers import AutoModelForDocumentQuestionAnswering
+
+>>> processor = AutoProcessor.from_pretrained("MariaK/layoutlmv2-base-uncased_finetuned_docvqa")
+>>> model = AutoModelForDocumentQuestionAnswering.from_pretrained("MariaK/layoutlmv2-base-uncased_finetuned_docvqa")
+
+>>> with torch.no_grad():
+... encoding = processor(image.convert("RGB"), question, return_tensors="pt")
+... outputs = model(**encoding)
+... start_logits = outputs.start_logits
+... end_logits = outputs.end_logits
+... predicted_start_idx = start_logits.argmax(-1).item()
+... predicted_end_idx = end_logits.argmax(-1).item()
+
+>>> processor.tokenizer.decode(encoding.input_ids.squeeze()[predicted_start_idx : predicted_end_idx + 1])
+'lee a. waller'
+```
\ No newline at end of file
diff --git a/docs/source/ko/tasks/image_captioning.md b/docs/source/ko/tasks/image_captioning.md
new file mode 100644
index 000000000000..0521db0dc9ab
--- /dev/null
+++ b/docs/source/ko/tasks/image_captioning.md
@@ -0,0 +1,281 @@
+
+
+
+# ìŽëŻžì§ ìșĄì
ë[[image-captioning]]
+
+[[open-in-colab]]
+
+ìŽëŻžì§ ìșĄì
ë(Image captioning)ì ìŁŒìŽì§ ìŽëŻžì§ì ëí ìșĄì
ì ììžĄíë ìì
ì
ëë€.
+ìŽëŻžì§ ìșĄì
ëì ìê° ì„ì ìžìŽ ë€ìí ìí©ì íìíë ë° ëìì ì€ ì ìëëĄ ìê° ì„ì ìžì ëłŽìĄ°íë ë± ì€ìíìì íí íì©ë©ëë€.
+ë°ëŒì ìŽëŻžì§ ìșĄì
ëì ìŽëŻžì§ë„Œ ì€ëȘ
íšìŒëĄìš ìŹëë€ì ìœí
ìž ì ê·Œì±ì ê°ì íë ë° ëììŽ ë©ëë€.
+
+ìŽ ê°ìŽëììë ìê°í ëŽì©ì ìëì ê°ì”ëë€:
+
+* ìŽëŻžì§ ìșĄì
ë ëȘšëžì íìžíëí©ëë€.
+* íìžíëë ëȘšëžì ì¶ëĄ ì ìŹì©í©ëë€.
+
+ììíêž° ì ì íìí ëȘšë ëŒìŽëžëŹëŠŹê° ì€ìčëìŽ ìëì§ íìžíìžì:
+
+```bash
+pip install transformers datasets evaluate -q
+pip install jiwer -q
+```
+
+Hugging Face êłì ì ëĄê·žìží멎 ëȘšëžì ì
ëĄëíêł ì»€ëź€ëí°ì êł”ì í ì ìì”ëë€.
+í í°ì ì
ë „íìŹ ëĄê·žìžíìžì.
+
+
+```python
+from huggingface_hub import notebook_login
+
+notebook_login()
+```
+
+## íŹìŒëȘŹ BLIP ìșĄì
ë°ìŽí°ìžíž ê°ì žì€êž°[[load-the-pokmon-blip-captions-dataset]]
+
+{ìŽëŻžì§-ìșĄì
} ììŒëĄ ê”Źì±ë ë°ìŽí°ìžížë„Œ ê°ì žì€ë €ë©Ž đ€ Dataset ëŒìŽëžëŹëŠŹë„Œ ìŹì©í©ëë€.
+PyTorchìì ìì ë§ì ìŽëŻžì§ ìșĄì
ë°ìŽí°ìžížë„Œ ë§ë€ë €ë©Ž [ìŽ ë
žížë¶](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/GIT/Fine_tune_GIT_on_an_image_captioning_dataset.ipynb)ì ì°žìĄ°íìžì.
+
+
+```python
+from datasets import load_dataset
+
+ds = load_dataset("lambdalabs/pokemon-blip-captions")
+ds
+```
+```bash
+DatasetDict({
+ train: Dataset({
+ features: ['image', 'text'],
+ num_rows: 833
+ })
+})
+```
+
+ìŽ ë°ìŽí°ìžížë `image`ì `text`ëŒë ë íčì±ì ê°ì§êł ìì”ëë€.
+
+
+
+ë§ì ìŽëŻžì§ ìșĄì
ë°ìŽí°ìžížìë ìŽëŻžì§ëč ìŹëŹ ê°ì ìșĄì
ìŽ íŹíšëìŽ ìì”ëë€.
+ìŽëŹí êČœì°, ìŒë°ì ìŒëĄ íì” ì€ì ìŹì© ê°ë„í ìșĄì
ì€ìì 돎ììëĄ ìíì ì¶ì¶í©ëë€.
+
+
+
+[~datasets.Dataset.train_test_split] ë©ìë넌 ìŹì©íìŹ ë°ìŽí°ìžížì íì” ë¶í ì íì” ë° í
ì€íž ìžížëĄ ëëëë€:
+
+
+```python
+ds = ds["train"].train_test_split(test_size=0.1)
+train_ds = ds["train"]
+test_ds = ds["test"]
+```
+
+íì” ìžížì ìí ëȘ ê°ë„Œ ìê°ííŽ ëŽ
ìë€.
+Let's visualize a couple of samples from the training set.
+
+
+```python
+from textwrap import wrap
+import matplotlib.pyplot as plt
+import numpy as np
+
+
+def plot_images(images, captions):
+ plt.figure(figsize=(20, 20))
+ for i in range(len(images)):
+ ax = plt.subplot(1, len(images), i + 1)
+ caption = captions[i]
+ caption = "\n".join(wrap(caption, 12))
+ plt.title(caption)
+ plt.imshow(images[i])
+ plt.axis("off")
+
+
+sample_images_to_visualize = [np.array(train_ds[i]["image"]) for i in range(5)]
+sample_captions = [train_ds[i]["text"] for i in range(5)]
+plot_images(sample_images_to_visualize, sample_captions)
+```
+
+
+
+
+
+## ë°ìŽí°ìžíž ì ìČ늏[[preprocess-the-dataset]]
+
+ë°ìŽí°ìžížìë ìŽëŻžì§ì í
ì€ížëŒë ë ê°ì§ ìììŽ ìêž° ë돞ì, ì ìČ늏 íìŽíëŒìžìì ìŽëŻžì§ì ìșĄì
ì ëȘšë ì ìČ늏í©ëë€.
+
+ì ìČ늏 ìì
ì ìíŽ, íìžíëíë €ë ëȘšëžì ì°êȰë íëĄìžì íŽëì€ë„Œ ê°ì žì”ëë€.
+
+```python
+from transformers import AutoProcessor
+
+checkpoint = "microsoft/git-base"
+processor = AutoProcessor.from_pretrained(checkpoint)
+```
+
+íëĄìžìë ëŽë¶ì ìŒëĄ íŹêž° ìĄ°ì ë° íœì
íŹêž° ìĄ°ì ì íŹíší ìŽëŻžì§ ì ìČëŠŹë„Œ ìííêł ìșĄì
ì í í°íí©ëë€.
+
+```python
+def transforms(example_batch):
+ images = [x for x in example_batch["image"]]
+ captions = [x for x in example_batch["text"]]
+ inputs = processor(images=images, text=captions, padding="max_length")
+ inputs.update({"labels": inputs["input_ids"]})
+ return inputs
+
+
+train_ds.set_transform(transforms)
+test_ds.set_transform(transforms)
+```
+
+ë°ìŽí°ìžížê° ì€ëčëììŒë ìŽì íìžíëì ìíŽ ëȘšëžì ì€ì í ì ìì”ëë€.
+
+## êž°ëłž ëȘšëž ê°ì žì€êž°[[load-a-base-model]]
+
+["microsoft/git-base"](https://huggingface.co/microsoft/git-base)넌 [`AutoModelForCausalLM`](https://huggingface.co/docs/transformers/model_doc/auto#transformers.AutoModelForCausalLM) ê°ìČŽëĄ ê°ì žì”ëë€.
+
+
+```python
+from transformers import AutoModelForCausalLM
+
+model = AutoModelForCausalLM.from_pretrained(checkpoint)
+```
+
+## íê°[[evaluate]]
+
+ìŽëŻžì§ ìșĄì
ëȘšëžì ìŒë°ì ìŒëĄ [Rouge ì ì](https://huggingface.co/spaces/evaluate-metric/rouge) ëë [ëšìŽ ì€ë„ìš(Word Error Rate)](https://huggingface.co/spaces/evaluate-metric/wer)ëĄ íê°í©ëë€.
+ìŽ ê°ìŽëììë ëšìŽ ì€ë„ìš(WER)ì ìŹì©í©ëë€.
+
+ìŽë„Œ ìíŽ đ€ Evaluate ëŒìŽëžëŹëŠŹë„Œ ìŹì©í©ëë€.
+WERì ì ìŹì ì í ìŹí ë° êž°í 돞ì ì ì [ìŽ ê°ìŽë](https://huggingface.co/spaces/evaluate-metric/wer)넌 ì°žìĄ°íìžì.
+
+
+```python
+from evaluate import load
+import torch
+
+wer = load("wer")
+
+
+def compute_metrics(eval_pred):
+ logits, labels = eval_pred
+ predicted = logits.argmax(-1)
+ decoded_labels = processor.batch_decode(labels, skip_special_tokens=True)
+ decoded_predictions = processor.batch_decode(predicted, skip_special_tokens=True)
+ wer_score = wer.compute(predictions=decoded_predictions, references=decoded_labels)
+ return {"wer_score": wer_score}
+```
+
+## íì”![[train!]]
+
+ìŽì ëȘšëž íìžíëì ììí ì€ëčê° ëìì”ëë€. ìŽë„Œ ìíŽ đ€ [`Trainer`]넌 ìŹì©í©ëë€.
+
+뚌ì , [`TrainingArguments`]넌 ìŹì©íìŹ íì” ìžì넌 ì ìí©ëë€.
+
+
+```python
+from transformers import TrainingArguments, Trainer
+
+model_name = checkpoint.split("/")[1]
+
+training_args = TrainingArguments(
+ output_dir=f"{model_name}-pokemon",
+ learning_rate=5e-5,
+ num_train_epochs=50,
+ fp16=True,
+ per_device_train_batch_size=32,
+ per_device_eval_batch_size=32,
+ gradient_accumulation_steps=2,
+ save_total_limit=3,
+ evaluation_strategy="steps",
+ eval_steps=50,
+ save_strategy="steps",
+ save_steps=50,
+ logging_steps=50,
+ remove_unused_columns=False,
+ push_to_hub=True,
+ label_names=["labels"],
+ load_best_model_at_end=True,
+)
+```
+
+íì” ìžì넌 ë°ìŽí°ìžíž, ëȘšëžêłŒ íšê» đ€ Trainerì ì ëŹí©ëë€.
+
+```python
+trainer = Trainer(
+ model=model,
+ args=training_args,
+ train_dataset=train_ds,
+ eval_dataset=test_ds,
+ compute_metrics=compute_metrics,
+)
+```
+
+íì”ì ììíë €ë©Ž [`Trainer`] ê°ìČŽìì [`~Trainer.train`]ì ížì¶íêž°ë§ í멎 ë©ëë€.
+
+```python
+trainer.train()
+```
+
+íì”ìŽ ì§íë멎ì íì” ìì€ìŽ ìííêČ ê°ìíë êČì ëłŒ ì ìì”ëë€.
+
+íì”ìŽ ìëŁë멎 ëȘšë ìŹëìŽ ëȘšëžì ìŹì©í ì ìëëĄ [`~Trainer.push_to_hub`] ë©ìë넌 ìŹì©íìŹ ëȘšëžì íëžì êł”ì íìžì:
+
+
+```python
+trainer.push_to_hub()
+```
+
+## ì¶ëĄ [[inference]]
+
+`test_ds`ìì ìí ìŽëŻžì§ë„Œ ê°ì žì ëȘšëžì í
ì€íží©ëë€.
+
+
+```python
+from PIL import Image
+import requests
+
+url = "https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/pokemon.png"
+image = Image.open(requests.get(url, stream=True).raw)
+image
+```
+
+
+
+
+
+ëȘšëžì ìŹì©í ìŽëŻžì§ë„Œ ì€ëčí©ëë€.
+
+```python
+device = "cuda" if torch.cuda.is_available() else "cpu"
+
+inputs = processor(images=image, return_tensors="pt").to(device)
+pixel_values = inputs.pixel_values
+```
+
+[`generate`]넌 ížì¶íêł ììžĄì ëìœë©í©ëë€.
+
+```python
+generated_ids = model.generate(pixel_values=pixel_values, max_length=50)
+generated_caption = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
+print(generated_caption)
+```
+```bash
+a drawing of a pink and blue pokemon
+```
+
+íìžíëë ëȘšëžìŽ êœ€ êŽì°źì ìșĄì
ì ìì±í êČ ê°ì”ëë€!
diff --git a/docs/source/ko/tasks/image_captioning.mdx b/docs/source/ko/tasks/image_captioning.mdx
deleted file mode 100644
index a7c317a7979c..000000000000
--- a/docs/source/ko/tasks/image_captioning.mdx
+++ /dev/null
@@ -1,277 +0,0 @@
-
-
-
-# ìŽëŻžì§ ìșĄì
ë[[image-captioning]]
-
-[[open-in-colab]]
-
-ìŽëŻžì§ ìșĄì
ë(Image captioning)ì ìŁŒìŽì§ ìŽëŻžì§ì ëí ìșĄì
ì ììžĄíë ìì
ì
ëë€.
-ìŽëŻžì§ ìșĄì
ëì ìê° ì„ì ìžìŽ ë€ìí ìí©ì íìíë ë° ëìì ì€ ì ìëëĄ ìê° ì„ì ìžì ëłŽìĄ°íë ë± ì€ìíìì íí íì©ë©ëë€.
-ë°ëŒì ìŽëŻžì§ ìșĄì
ëì ìŽëŻžì§ë„Œ ì€ëȘ
íšìŒëĄìš ìŹëë€ì ìœí
ìž ì ê·Œì±ì ê°ì íë ë° ëììŽ ë©ëë€.
-
-ìŽ ê°ìŽëììë ìê°í ëŽì©ì ìëì ê°ì”ëë€:
-
-* ìŽëŻžì§ ìșĄì
ë ëȘšëžì íìžíëí©ëë€.
-* íìžíëë ëȘšëžì ì¶ëĄ ì ìŹì©í©ëë€.
-
-ììíêž° ì ì íìí ëȘšë ëŒìŽëžëŹëŠŹê° ì€ìčëìŽ ìëì§ íìžíìžì:
-
-```bash
-pip install transformers datasets evaluate -q
-pip install jiwer -q
-```
-
-Hugging Face êłì ì ëĄê·žìží멎 ëȘšëžì ì
ëĄëíêł ì»€ëź€ëí°ì êł”ì í ì ìì”ëë€.
-í í°ì ì
ë „íìŹ ëĄê·žìžíìžì.
-
-
-```python
-from huggingface_hub import notebook_login
-
-notebook_login()
-```
-
-## íŹìŒëȘŹ BLIP ìșĄì
ë°ìŽí°ìžíž ê°ì žì€êž°[[load-the-pokmon-blip-captions-dataset]]
-
-{ìŽëŻžì§-ìșĄì
} ììŒëĄ ê”Źì±ë ë°ìŽí°ìžížë„Œ ê°ì žì€ë €ë©Ž đ€ Dataset ëŒìŽëžëŹëŠŹë„Œ ìŹì©í©ëë€.
-PyTorchìì ìì ë§ì ìŽëŻžì§ ìșĄì
ë°ìŽí°ìžížë„Œ ë§ë€ë €ë©Ž [ìŽ ë
žížë¶](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/GIT/Fine_tune_GIT_on_an_image_captioning_dataset.ipynb)ì ì°žìĄ°íìžì.
-
-
-```python
-from datasets import load_dataset
-
-ds = load_dataset("lambdalabs/pokemon-blip-captions")
-ds
-```
-```bash
-DatasetDict({
- train: Dataset({
- features: ['image', 'text'],
- num_rows: 833
- })
-})
-```
-
-ìŽ ë°ìŽí°ìžížë `image`ì `text`ëŒë ë íčì±ì ê°ì§êł ìì”ëë€.
-
-
-
-ë§ì ìŽëŻžì§ ìșĄì
ë°ìŽí°ìžížìë ìŽëŻžì§ëč ìŹëŹ ê°ì ìșĄì
ìŽ íŹíšëìŽ ìì”ëë€.
-ìŽëŹí êČœì°, ìŒë°ì ìŒëĄ íì” ì€ì ìŹì© ê°ë„í ìșĄì
ì€ìì 돎ììëĄ ìíì ì¶ì¶í©ëë€.
-
-
-
-[~datasets.Dataset.train_test_split] ë©ìë넌 ìŹì©íìŹ ë°ìŽí°ìžížì íì” ë¶í ì íì” ë° í
ì€íž ìžížëĄ ëëëë€:
-
-
-```python
-ds = ds["train"].train_test_split(test_size=0.1)
-train_ds = ds["train"]
-test_ds = ds["test"]
-```
-
-íì” ìžížì ìí ëȘ ê°ë„Œ ìê°ííŽ ëŽ
ìë€.
-Let's visualize a couple of samples from the training set.
-
-
-```python
-from textwrap import wrap
-import matplotlib.pyplot as plt
-import numpy as np
-
-
-def plot_images(images, captions):
- plt.figure(figsize=(20, 20))
- for i in range(len(images)):
- ax = plt.subplot(1, len(images), i + 1)
- caption = captions[i]
- caption = "\n".join(wrap(caption, 12))
- plt.title(caption)
- plt.imshow(images[i])
- plt.axis("off")
-
-
-sample_images_to_visualize = [np.array(train_ds[i]["image"]) for i in range(5)]
-sample_captions = [train_ds[i]["text"] for i in range(5)]
-plot_images(sample_images_to_visualize, sample_captions)
-```
-
-
-
-
-
-## ë°ìŽí°ìžíž ì ìČ늏[[preprocess-the-dataset]]
-
-ë°ìŽí°ìžížìë ìŽëŻžì§ì í
ì€ížëŒë ë ê°ì§ ìììŽ ìêž° ë돞ì, ì ìČ늏 íìŽíëŒìžìì ìŽëŻžì§ì ìșĄì
ì ëȘšë ì ìČ늏í©ëë€.
-
-ì ìČ늏 ìì
ì ìíŽ, íìžíëíë €ë ëȘšëžì ì°êȰë íëĄìžì íŽëì€ë„Œ ê°ì žì”ëë€.
-
-```python
-from transformers import AutoProcessor
-
-checkpoint = "microsoft/git-base"
-processor = AutoProcessor.from_pretrained(checkpoint)
-```
-
-íëĄìžìë ëŽë¶ì ìŒëĄ íŹêž° ìĄ°ì ë° íœì
íŹêž° ìĄ°ì ì íŹíší ìŽëŻžì§ ì ìČëŠŹë„Œ ìííêł ìșĄì
ì í í°íí©ëë€.
-
-```python
-def transforms(example_batch):
- images = [x for x in example_batch["image"]]
- captions = [x for x in example_batch["text"]]
- inputs = processor(images=images, text=captions, padding="max_length")
- inputs.update({"labels": inputs["input_ids"]})
- return inputs
-
-
-train_ds.set_transform(transforms)
-test_ds.set_transform(transforms)
-```
-
-ë°ìŽí°ìžížê° ì€ëčëììŒë ìŽì íìžíëì ìíŽ ëȘšëžì ì€ì í ì ìì”ëë€.
-
-## êž°ëłž ëȘšëž ê°ì žì€êž°[[load-a-base-model]]
-
-["microsoft/git-base"](https://huggingface.co/microsoft/git-base)넌 [`AutoModelForCausalLM`](https://huggingface.co/docs/transformers/model_doc/auto#transformers.AutoModelForCausalLM) ê°ìČŽëĄ ê°ì žì”ëë€.
-
-
-```python
-from transformers import AutoModelForCausalLM
-
-model = AutoModelForCausalLM.from_pretrained(checkpoint)
-```
-
-## íê°[[evaluate]]
-
-ìŽëŻžì§ ìșĄì
ëȘšëžì ìŒë°ì ìŒëĄ [Rouge ì ì](https://huggingface.co/spaces/evaluate-metric/rouge) ëë [ëšìŽ ì€ë„ìš(Word Error Rate)](https://huggingface.co/spaces/evaluate-metric/wer)ëĄ íê°í©ëë€.
-ìŽ ê°ìŽëììë ëšìŽ ì€ë„ìš(WER)ì ìŹì©í©ëë€.
-
-ìŽë„Œ ìíŽ đ€ Evaluate ëŒìŽëžëŹëŠŹë„Œ ìŹì©í©ëë€.
-WERì ì ìŹì ì í ìŹí ë° êž°í 돞ì ì ì [ìŽ ê°ìŽë](https://huggingface.co/spaces/evaluate-metric/wer)넌 ì°žìĄ°íìžì.
-
-
-```python
-from evaluate import load
-import torch
-
-wer = load("wer")
-
-
-def compute_metrics(eval_pred):
- logits, labels = eval_pred
- predicted = logits.argmax(-1)
- decoded_labels = processor.batch_decode(labels, skip_special_tokens=True)
- decoded_predictions = processor.batch_decode(predicted, skip_special_tokens=True)
- wer_score = wer.compute(predictions=decoded_predictions, references=decoded_labels)
- return {"wer_score": wer_score}
-```
-
-## íì”![[train!]]
-
-ìŽì ëȘšëž íìžíëì ììí ì€ëčê° ëìì”ëë€. ìŽë„Œ ìíŽ đ€ [`Trainer`]넌 ìŹì©í©ëë€.
-
-뚌ì , [`TrainingArguments`]넌 ìŹì©íìŹ íì” ìžì넌 ì ìí©ëë€.
-
-
-```python
-from transformers import TrainingArguments, Trainer
-
-model_name = checkpoint.split("/")[1]
-
-training_args = TrainingArguments(
- output_dir=f"{model_name}-pokemon",
- learning_rate=5e-5,
- num_train_epochs=50,
- fp16=True,
- per_device_train_batch_size=32,
- per_device_eval_batch_size=32,
- gradient_accumulation_steps=2,
- save_total_limit=3,
- evaluation_strategy="steps",
- eval_steps=50,
- save_strategy="steps",
- save_steps=50,
- logging_steps=50,
- remove_unused_columns=False,
- push_to_hub=True,
- label_names=["labels"],
- load_best_model_at_end=True,
-)
-```
-
-íì” ìžì넌 ë°ìŽí°ìžíž, ëȘšëžêłŒ íšê» đ€ Trainerì ì ëŹí©ëë€.
-
-```python
-trainer = Trainer(
- model=model,
- args=training_args,
- train_dataset=train_ds,
- eval_dataset=test_ds,
- compute_metrics=compute_metrics,
-)
-```
-
-íì”ì ììíë €ë©Ž [`Trainer`] ê°ìČŽìì [`~Trainer.train`]ì ížì¶íêž°ë§ í멎 ë©ëë€.
-
-```python
-trainer.train()
-```
-
-íì”ìŽ ì§íë멎ì íì” ìì€ìŽ ìííêČ ê°ìíë êČì ëłŒ ì ìì”ëë€.
-
-íì”ìŽ ìëŁë멎 ëȘšë ìŹëìŽ ëȘšëžì ìŹì©í ì ìëëĄ [`~Trainer.push_to_hub`] ë©ìë넌 ìŹì©íìŹ ëȘšëžì íëžì êł”ì íìžì:
-
-
-```python
-trainer.push_to_hub()
-```
-
-## ì¶ëĄ [[inference]]
-
-`test_ds`ìì ìí ìŽëŻžì§ë„Œ ê°ì žì ëȘšëžì í
ì€íží©ëë€.
-
-
-```python
-from PIL import Image
-import requests
-
-url = "https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/pokemon.png"
-image = Image.open(requests.get(url, stream=True).raw)
-image
-```
-
-
-
-
-
-ëȘšëžì ìŹì©í ìŽëŻžì§ë„Œ ì€ëčí©ëë€.
-
-```python
-device = "cuda" if torch.cuda.is_available() else "cpu"
-
-inputs = processor(images=image, return_tensors="pt").to(device)
-pixel_values = inputs.pixel_values
-```
-
-[`generate`]넌 ížì¶íêł ììžĄì ëìœë©í©ëë€.
-
-```python
-generated_ids = model.generate(pixel_values=pixel_values, max_length=50)
-generated_caption = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
-print(generated_caption)
-```
-```bash
-a drawing of a pink and blue pokemon
-```
-
-íìžíëë ëȘšëžìŽ êœ€ êŽì°źì ìșĄì
ì ìì±í êČ ê°ì”ëë€!
diff --git a/docs/source/ko/tasks/image_classification.md b/docs/source/ko/tasks/image_classification.md
new file mode 100644
index 000000000000..031e01ea5c5a
--- /dev/null
+++ b/docs/source/ko/tasks/image_classification.md
@@ -0,0 +1,546 @@
+
+
+# ìŽëŻžì§ ë¶ë„[[image-classification]]
+
+[[open-in-colab]]
+
+
+
+ìŽëŻžì§ ë¶ë„ë ìŽëŻžì§ì ë ìŽëž ëë íŽëì€ë„Œ í ëčí©ëë€. í
ì€íž ëë ì€ëì€ ë¶ë„ì ëŹëŠŹ ì
ë „ì
+ìŽëŻžì§ë„Œ ê”Źì±íë íœì
ê°ì
ëë€. ìŽëŻžì§ ë¶ë„ìë ìì°ìŹíŽ í íŒíŽ ê°ì§, ëìëŹŒ ê±Žê° ëȘšëí°ë§, ìëŁ ìŽëŻžì§ìì ì§ëłì ì§í êČìŹ ì§ì ë±
+ë€ìí ìì© ìŹëĄê° ìì”ëë€.
+
+ìŽ ê°ìŽëììë ë€ìì ì€ëȘ
í©ëë€:
+
+1. [Food-101](https://huggingface.co/datasets/food101) ë°ìŽí° ìžížìì [ViT](model_doc/vit)넌 ëŻžìž ìĄ°ì íìŹ ìŽëŻžì§ìì ìí íëȘ©ì ë¶ë„í©ëë€.
+2. ì¶ëĄ ì ìíŽ ëŻžìž ìĄ°ì ëȘšëžì ìŹì©í©ëë€.
+
+
+ìŽ íí 늏ìŒìì ì€ëȘ
íë ìì
ì ë€ì ëȘšëž ìí€í
ìČì ìíŽ ì§ìë©ëë€:
+
+
+
+[BEiT](../model_doc/beit), [BiT](../model_doc/bit), [ConvNeXT](../model_doc/convnext), [ConvNeXTV2](../model_doc/convnextv2), [CvT](../model_doc/cvt), [Data2VecVision](../model_doc/data2vec-vision), [DeiT](../model_doc/deit), [DiNAT](../model_doc/dinat), [EfficientFormer](../model_doc/efficientformer), [EfficientNet](../model_doc/efficientnet), [FocalNet](../model_doc/focalnet), [ImageGPT](../model_doc/imagegpt), [LeViT](../model_doc/levit), [MobileNetV1](../model_doc/mobilenet_v1), [MobileNetV2](../model_doc/mobilenet_v2), [MobileViT](../model_doc/mobilevit), [NAT](../model_doc/nat), [Perceiver](../model_doc/perceiver), [PoolFormer](../model_doc/poolformer), [RegNet](../model_doc/regnet), [ResNet](../model_doc/resnet), [SegFormer](../model_doc/segformer), [Swin Transformer](../model_doc/swin), [Swin Transformer V2](../model_doc/swinv2), [VAN](../model_doc/van), [ViT](../model_doc/vit), [ViT Hybrid](../model_doc/vit_hybrid), [ViTMSN](../model_doc/vit_msn)
+
+
+
+
+ììíêž° ì ì, íìí ëȘšë ëŒìŽëžëŹëŠŹê° ì€ìčëìŽ ìëì§ íìžíìžì:
+
+```bash
+pip install transformers datasets evaluate
+```
+
+Hugging Face êłì ì ëĄê·žìžíìŹ ëȘšëžì ì
ëĄëíêł ì»€ëź€ëí°ì êł”ì íë êČì ê¶ì„í©ëë€. ë©ìì§ê° íìë멎, í í°ì ì
ë „íìŹ ëĄê·žìžíìžì:
+
+```py
+>>> from huggingface_hub import notebook_login
+
+>>> notebook_login()
+```
+
+## Food-101 ë°ìŽí° ìžíž ê°ì žì€êž°[[load-food101-dataset]]
+
+đ€ Datasets ëŒìŽëžëŹëŠŹìì Food-101 ë°ìŽí° ìžížì ë ìì ë¶ë¶ ì§í©ì ê°ì žì€ë êČìŒëĄ ììí©ëë€. ìŽë êČ í멎 ì ìČŽ ë°ìŽí° ìžížì ëí
+íë šì ë§ì ìê°ì í ì íêž° ì ì ì€íì í”íŽ ëȘšë êČìŽ ì ëëĄ ìëíëì§ íìží ì ìì”ëë€.
+
+```py
+>>> from datasets import load_dataset
+
+>>> food = load_dataset("food101", split="train[:5000]")
+```
+
+ë°ìŽí° ìžížì `train`ì [`~datasets.Dataset.train_test_split`] ë©ìë넌 ìŹì©íìŹ íë š ë° í
ì€íž ìžížëĄ ë¶í íìžì:
+
+```py
+>>> food = food.train_test_split(test_size=0.2)
+```
+
+ê·žëŠŹêł ìì넌 ìŽíŽëłŽìžì:
+
+```py
+>>> food["train"][0]
+{'image': ,
+ 'label': 79}
+```
+
+ë°ìŽí° ìžížì ê° ìì ìë ë ê°ì íëê° ìì”ëë€:
+
+- `image`: ìí íëȘ©ì PIL ìŽëŻžì§
+- `label`: ìí íëȘ©ì ë ìŽëž íŽëì€
+
+ëȘšëžìŽ ë ìŽëž IDìì ë ìŽëž ìŽëŠì ìœêČ ê°ì žìŹ ì ìëëĄ
+ë ìŽëž ìŽëŠì ì ìëĄ ë§€ííêł , ì ì넌 ë ìŽëž ìŽëŠìŒëĄ ë§€ííë ìŹì ì ë§ëìžì:
+
+```py
+>>> labels = food["train"].features["label"].names
+>>> label2id, id2label = dict(), dict()
+>>> for i, label in enumerate(labels):
+... label2id[label] = str(i)
+... id2label[str(i)] = label
+```
+
+ìŽì ë ìŽëž ID넌 ë ìŽëž ìŽëŠìŒëĄ ëłíí ì ìì”ëë€:
+
+```py
+>>> id2label[str(79)]
+'prime_rib'
+```
+
+## ì ìČ늏[[preprocess]]
+
+ë€ì ëšêłë ìŽëŻžì§ë„Œ í
ìëĄ ìČ늏íêž° ìíŽ ViT ìŽëŻžì§ íëĄìžì넌 ê°ì žì€ë êČì
ëë€:
+
+```py
+>>> from transformers import AutoImageProcessor
+
+>>> checkpoint = "google/vit-base-patch16-224-in21k"
+>>> image_processor = AutoImageProcessor.from_pretrained(checkpoint)
+```
+
+
+
+ìŽëŻžì§ì ëȘ ê°ì§ ìŽëŻžì§ ëłíì ì ì©íìŹ êłŒì í©ì ëíŽ ëȘšëžì ë êČŹêł íêČ ë§ëëë€. ìŹêž°ì Torchvisionì [`transforms`](https://pytorch.org/vision/stable/transforms.html) ëȘšëì ìŹì©íì§ë§, ìíë ìŽëŻžì§ ëŒìŽëžëŹëŠŹë„Œ ìŹì©í ìë ìì”ëë€.
+
+ìŽëŻžì§ì ìì ë¶ë¶ì íŹëĄíêł íŹêž°ë„Œ ìĄ°ì í ë€ì, ìŽëŻžì§ íê· êłŒ íì€ ížì°šëĄ ì ê·ííìžì:
+
+```py
+>>> from torchvision.transforms import RandomResizedCrop, Compose, Normalize, ToTensor
+
+>>> normalize = Normalize(mean=image_processor.image_mean, std=image_processor.image_std)
+>>> size = (
+... image_processor.size["shortest_edge"]
+... if "shortest_edge" in image_processor.size
+... else (image_processor.size["height"], image_processor.size["width"])
+... )
+>>> _transforms = Compose([RandomResizedCrop(size), ToTensor(), normalize])
+```
+
+ê·žë° ë€ì ì ìČ늏 íšì넌 ë§ë€ìŽ ëłíì ì ì©íêł ìŽëŻžì§ì `pixel_values`(ëȘšëžì ëí ì
ë „)넌 ë°ííìžì:
+
+```py
+>>> def transforms(examples):
+... examples["pixel_values"] = [_transforms(img.convert("RGB")) for img in examples["image"]]
+... del examples["image"]
+... return examples
+```
+
+ì ìČŽ ë°ìŽí° ìžížì ì ìČ늏 êž°ë„ì ì ì©íë €ë©Ž đ€ Datasets [`~datasets.Dataset.with_transform`]ì ìŹì©í©ëë€. ë°ìŽí° ìžížì ìì넌 ê°ì žìŹ ë ëłíìŽ ìŠì ì ì©ë©ëë€:
+
+```py
+>>> food = food.with_transform(transforms)
+```
+
+ìŽì [`DefaultDataCollator`]넌 ìŹì©íìŹ ìì ë°°ìč넌 ë§ëëë€. đ€ Transformersì ë€ë„ž ë°ìŽí° ìœë ìŽí°ì ëŹëŠŹ, `DefaultDataCollator`ë íšë©êłŒ ê°ì ì¶ê°ì ìž ì ìČëŠŹë„Œ ì ì©íì§ ìì”ëë€.
+
+```py
+>>> from transformers import DefaultDataCollator
+
+>>> data_collator = DefaultDataCollator()
+```
+
+
+
+
+
+
+
+êłŒì í©ì ë°©ì§íêł ëȘšëžì ëłŽë€ êČŹêł íêČ ë§ë€êž° ìíŽ ë°ìŽí° ìžížì íë š ë¶ë¶ì ë°ìŽí° ìŠê°ì ì¶ê°í©ëë€.
+ìŹêž°ì Keras ì ìČ늏 ë ìŽìŽëĄ íë š ë°ìŽí°ì ëí ëłí(ë°ìŽí° ìŠê° íŹíš)êłŒ
+êČìŠ ë°ìŽí°ì ëí ëłí(ì€ì íŹëĄí, íŹêž° ìĄ°ì , ì ê·íë§)ì ì ìí©ëë€.
+`tf.image` ëë ë€ë„ž ìíë ëŒìŽëžëŹëŠŹë„Œ ìŹì©í ì ìì”ëë€.
+
+```py
+>>> from tensorflow import keras
+>>> from tensorflow.keras import layers
+
+>>> size = (image_processor.size["height"], image_processor.size["width"])
+
+>>> train_data_augmentation = keras.Sequential(
+... [
+... layers.RandomCrop(size[0], size[1]),
+... layers.Rescaling(scale=1.0 / 127.5, offset=-1),
+... layers.RandomFlip("horizontal"),
+... layers.RandomRotation(factor=0.02),
+... layers.RandomZoom(height_factor=0.2, width_factor=0.2),
+... ],
+... name="train_data_augmentation",
+... )
+
+>>> val_data_augmentation = keras.Sequential(
+... [
+... layers.CenterCrop(size[0], size[1]),
+... layers.Rescaling(scale=1.0 / 127.5, offset=-1),
+... ],
+... name="val_data_augmentation",
+... )
+```
+
+ë€ììŒëĄ í ëČì íëì ìŽëŻžì§ê° ìëëŒ ìŽëŻžì§ ë°°ìčì ì ì í ëłíì ì ì©íë íšì넌 ë§ëëë€.
+
+```py
+>>> import numpy as np
+>>> import tensorflow as tf
+>>> from PIL import Image
+
+
+>>> def convert_to_tf_tensor(image: Image):
+... np_image = np.array(image)
+... tf_image = tf.convert_to_tensor(np_image)
+... # `expand_dims()` is used to add a batch dimension since
+... # the TF augmentation layers operates on batched inputs.
+... return tf.expand_dims(tf_image, 0)
+
+
+>>> def preprocess_train(example_batch):
+... """Apply train_transforms across a batch."""
+... images = [
+... train_data_augmentation(convert_to_tf_tensor(image.convert("RGB"))) for image in example_batch["image"]
+... ]
+... example_batch["pixel_values"] = [tf.transpose(tf.squeeze(image)) for image in images]
+... return example_batch
+
+
+... def preprocess_val(example_batch):
+... """Apply val_transforms across a batch."""
+... images = [
+... val_data_augmentation(convert_to_tf_tensor(image.convert("RGB"))) for image in example_batch["image"]
+... ]
+... example_batch["pixel_values"] = [tf.transpose(tf.squeeze(image)) for image in images]
+... return example_batch
+```
+
+đ€ Datasets [`~datasets.Dataset.set_transform`]넌 ìŹì©íìŹ ìŠì ëłíì ì ì©íìžì:
+
+```py
+food["train"].set_transform(preprocess_train)
+food["test"].set_transform(preprocess_val)
+```
+
+ì”ìą
ì ìČ늏 ëšêłëĄ `DefaultDataCollator`넌 ìŹì©íìŹ ìì ë°°ìč넌 ë§ëëë€. đ€ Transformersì ë€ë„ž ë°ìŽí° ìœë ìŽí°ì ëŹëŠŹ
+`DefaultDataCollator`ë íšë©êłŒ ê°ì ì¶ê° ì ìČëŠŹë„Œ ì ì©íì§ ìì”ëë€.
+
+```py
+>>> from transformers import DefaultDataCollator
+
+>>> data_collator = DefaultDataCollator(return_tensors="tf")
+```
+
+
+
+## íê°[[evaluate]]
+
+íë š ì€ì íê° ì§í넌 íŹíší멎 ëȘšëžì ì±ë„ì íê°íë ë° ëììŽ ëë êČœì°ê° ë§ì”ëë€.
+đ€ [Evaluate](https://huggingface.co/docs/evaluate/index) ëŒìŽëžëŹëŠŹëĄ íê° ë°©ëČì ëč 넎êČ ê°ì žìŹ ì ìì”ëë€. ìŽ ìì
ììë
+[accuracy](https://huggingface.co/spaces/evaluate-metric/accuracy) íê° ì§í넌 ê°ì žì”ëë€. (đ€ Evaluate [ëč 넞 ëëŹëłŽêž°](https://huggingface.co/docs/evaluate/a_quick_tour)넌 ì°žìĄ°íìŹ íê° ì§í넌 ê°ì žì€êł êłì°íë ë°©ëČì ëíŽ ììží ìì볎ìžì):
+
+```py
+>>> import evaluate
+
+>>> accuracy = evaluate.load("accuracy")
+```
+
+ê·žë° ë€ì ììžĄêłŒ ë ìŽëžì [`~evaluate.EvaluationModule.compute`]ì ì ëŹíìŹ ì íë넌 êłì°íë íšì넌 ë§ëëë€:
+
+```py
+>>> import numpy as np
+
+
+>>> def compute_metrics(eval_pred):
+... predictions, labels = eval_pred
+... predictions = np.argmax(predictions, axis=1)
+... return accuracy.compute(predictions=predictions, references=labels)
+```
+
+ìŽì `compute_metrics` íšì넌 ìŹì©í ì€ëčê° ëììŒë©°, íë šì ì€ì í멎 ìŽ íšìëĄ ëëììŹ êČì
ëë€.
+
+## íë š[[train]]
+
+
+
+
+
+[`Trainer`]넌 ìŹì©íìŹ ëȘšëžì ëŻžìž ìĄ°ì íë ë°©ëČì ì”ìíì§ ìì êČœì°, [ìŹêž°](../training#train-with-pytorch-trainer)ìì êž°ëłž íí 늏ìŒì íìžíìžì!
+
+
+
+ìŽì ëȘšëžì íë šìíŹ ì€ëčê° ëìì”ëë€! [`AutoModelForImageClassification`]ëĄ ViT넌 ê°ì žì”ëë€. ììëë ë ìŽëž ì, ë ìŽëž ë§€í ë° ë ìŽëž ì넌 ì§ì íìžì:
+
+```py
+>>> from transformers import AutoModelForImageClassification, TrainingArguments, Trainer
+
+>>> model = AutoModelForImageClassification.from_pretrained(
+... checkpoint,
+... num_labels=len(labels),
+... id2label=id2label,
+... label2id=label2id,
+... )
+```
+
+ìŽì ìž ëšêłë§ ê±°ìč멎 ëì
ëë€:
+
+1. [`TrainingArguments`]ìì íë š íìŽíŒíëŒëŻží°ë„Œ ì ìíìžì. `image` ìŽìŽ ìì ëêž° ë돞ì 믞ìŹì© ìŽì ì ê±°íì§ ìë êČìŽ ì€ìí©ëë€. `image` ìŽìŽ ììŒë©Ž `pixel_values`ì ìì±í ì ìì”ëë€. ìŽ ëìì ë°©ì§íë €ë©Ž `remove_unused_columns=False`ëĄ ì€ì íìžì! ë€ë„ž ì ìŒí íì ë§€ê°ëłìë ëȘšëž ì ì„ ììč넌 ì§ì íë `output_dir`ì
ëë€. `push_to_hub=True`ëĄ ì€ì í멎 ìŽ ëȘšëžì íëžì ížìí©ëë€(ëȘšëžì ì
ëĄëíë €ë©Ž Hugging Faceì ëĄê·žìžíŽìŒ í©ëë€). ê° ìíìŽ ëë ëë§ë€, [`Trainer`]ê° ì íë넌 íê°íêł íë š ìČŽíŹíŹìžížë„Œ ì ì„í©ëë€.
+2. [`Trainer`]ì ëȘšëž, ë°ìŽí° ìžíž, í íŹëìŽì , ë°ìŽí° ìœë ìŽí° ë° `compute_metrics` íšìì íšê» íë š ìžì넌 ì ëŹíìžì.
+3. [`~Trainer.train`]ì ížì¶íìŹ ëȘšëžì ëŻžìž ìĄ°ì íìžì.
+
+```py
+>>> training_args = TrainingArguments(
+... output_dir="my_awesome_food_model",
+... remove_unused_columns=False,
+... evaluation_strategy="epoch",
+... save_strategy="epoch",
+... learning_rate=5e-5,
+... per_device_train_batch_size=16,
+... gradient_accumulation_steps=4,
+... per_device_eval_batch_size=16,
+... num_train_epochs=3,
+... warmup_ratio=0.1,
+... logging_steps=10,
+... load_best_model_at_end=True,
+... metric_for_best_model="accuracy",
+... push_to_hub=True,
+... )
+
+>>> trainer = Trainer(
+... model=model,
+... args=training_args,
+... data_collator=data_collator,
+... train_dataset=food["train"],
+... eval_dataset=food["test"],
+... tokenizer=image_processor,
+... compute_metrics=compute_metrics,
+... )
+
+>>> trainer.train()
+```
+
+íë šìŽ ìëŁë멎, ëȘšë ìŹëìŽ ëȘšëžì ìŹì©í ì ìëëĄ [`~transformers.Trainer.push_to_hub`] ë©ìëëĄ ëȘšëžì íëžì êł”ì íìžì:
+
+```py
+>>> trainer.push_to_hub()
+```
+
+
+
+
+
+
+
+
+Keras넌 ìŹì©íìŹ ëȘšëžì ëŻžìž ìĄ°ì íë ë°©ëČì ì”ìíì§ ìì êČœì°, 뚌ì [êž°ëłž íí 늏ìŒ](./training#train-a-tensorflow-model-with-keras)ì íìžíìžì!
+
+
+
+TensorFlowìì ëȘšëžì ëŻžìž ìĄ°ì íë €ë©Ž ë€ì ëšêłë„Œ ë°ë„Žìžì:
+1. íë š íìŽíŒíëŒëŻží°ë„Œ ì ìíêł ì”í°ë§ìŽì ì íì”ë„ ì€ìŒì„Žì ì€ì í©ëë€.
+2. ìŹì íë šë ëȘšëžì ìžì€íŽì€íí©ëë€.
+3. đ€ Datasetì `tf.data.Dataset`ìŒëĄ ëłíí©ëë€.
+4. ëȘšëžì 컎íìŒí©ëë€.
+5. ìœë°±ì ì¶ê°íêł íë šì ìííêž° ìíŽ `fit()` ë©ìë넌 ìŹì©í©ëë€.
+6. ì»€ëź€ëí°ì êł”ì íêž° ìíŽ ëȘšëžì đ€ Hubì ì
ëĄëí©ëë€.
+
+íìŽíŒíëŒëŻží°, ì”í°ë§ìŽì ë° íì”ë„ ì€ìŒì„Žì ì ìíë êČìŒëĄ ììí©ëë€:
+
+```py
+>>> from transformers import create_optimizer
+
+>>> batch_size = 16
+>>> num_epochs = 5
+>>> num_train_steps = len(food["train"]) * num_epochs
+>>> learning_rate = 3e-5
+>>> weight_decay_rate = 0.01
+
+>>> optimizer, lr_schedule = create_optimizer(
+... init_lr=learning_rate,
+... num_train_steps=num_train_steps,
+... weight_decay_rate=weight_decay_rate,
+... num_warmup_steps=0,
+... )
+```
+
+ê·žë° ë€ì ë ìŽëž ë§€íêłŒ íšê» [`TFAuto ModelForImageClassification`]ìŒëĄ ViT넌 ê°ì žì”ëë€:
+
+```py
+>>> from transformers import TFAutoModelForImageClassification
+
+>>> model = TFAutoModelForImageClassification.from_pretrained(
+... checkpoint,
+... id2label=id2label,
+... label2id=label2id,
+... )
+```
+
+ë°ìŽí° ìžížë„Œ [`~datasets.Dataset.to_tf_dataset`]ì `data_collator`넌 ìŹì©íìŹ `tf.data.Dataset` íììŒëĄ ëłííìžì:
+
+```py
+>>> # converting our train dataset to tf.data.Dataset
+>>> tf_train_dataset = food["train"].to_tf_dataset(
+... columns="pixel_values", label_cols="label", shuffle=True, batch_size=batch_size, collate_fn=data_collator
+... )
+
+>>> # converting our test dataset to tf.data.Dataset
+>>> tf_eval_dataset = food["test"].to_tf_dataset(
+... columns="pixel_values", label_cols="label", shuffle=True, batch_size=batch_size, collate_fn=data_collator
+... )
+```
+
+`compile()`넌 ìŹì©íìŹ íë š ëȘšëžì ê”Źì±íìžì:
+
+```py
+>>> from tensorflow.keras.losses import SparseCategoricalCrossentropy
+
+>>> loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
+>>> model.compile(optimizer=optimizer, loss=loss)
+```
+
+ììžĄìì ì íë넌 êłì°íêł ëȘšëžì đ€ HubëĄ ížìíë €ë©Ž [Keras callbacks](../main_classes/keras_callbacks)넌 ìŹì©íìžì.
+`compute_metrics` íšì넌 [KerasMetricCallback](../main_classes/keras_callbacks#transformers.KerasMetricCallback)ì ì ëŹíêł ,
+[PushToHubCallback](../main_classes/keras_callbacks#transformers.PushToHubCallback)ì ìŹì©íìŹ ëȘšëžì ì
ëĄëí©ëë€:
+
+```py
+>>> from transformers.keras_callbacks import KerasMetricCallback, PushToHubCallback
+
+>>> metric_callback = KerasMetricCallback(metric_fn=compute_metrics, eval_dataset=tf_eval_dataset)
+>>> push_to_hub_callback = PushToHubCallback(
+... output_dir="food_classifier",
+... tokenizer=image_processor,
+... save_strategy="no",
+... )
+>>> callbacks = [metric_callback, push_to_hub_callback]
+```
+
+ìŽì ëȘšëžì íë ší ì€ëčê° ëìì”ëë€! íë š ë° êČìŠ ë°ìŽí° ìžíž, ìí ìì íšê» `fit()`ì ížì¶íêł ,
+ìœë°±ì ìŹì©íìŹ ëȘšëžì ëŻžìž ìĄ°ì í©ëë€:
+
+```py
+>>> model.fit(tf_train_dataset, validation_data=tf_eval_dataset, epochs=num_epochs, callbacks=callbacks)
+Epoch 1/5
+250/250 [==============================] - 313s 1s/step - loss: 2.5623 - val_loss: 1.4161 - accuracy: 0.9290
+Epoch 2/5
+250/250 [==============================] - 265s 1s/step - loss: 0.9181 - val_loss: 0.6808 - accuracy: 0.9690
+Epoch 3/5
+250/250 [==============================] - 252s 1s/step - loss: 0.3910 - val_loss: 0.4303 - accuracy: 0.9820
+Epoch 4/5
+250/250 [==============================] - 251s 1s/step - loss: 0.2028 - val_loss: 0.3191 - accuracy: 0.9900
+Epoch 5/5
+250/250 [==============================] - 238s 949ms/step - loss: 0.1232 - val_loss: 0.3259 - accuracy: 0.9890
+```
+
+ì¶íí©ëë€! ëȘšëžì ëŻžìž ìĄ°ì íêł đ€ Hubì êł”ì íì”ëë€. ìŽì ì¶ëĄ ì ìŹì©í ì ìì”ëë€!
+
+
+
+
+
+
+ìŽëŻžì§ ë¶ë„넌 ìí ëȘšëžì ëŻžìž ìĄ°ì íë ììží ìì ë ë€ì [PyTorch notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb)ì ì°žìĄ°íìžì.
+
+
+
+## ì¶ëĄ [[inference]]
+
+ìąìì, ìŽì ëȘšëžì ëŻžìž ìĄ°ì íìŒë ì¶ëĄ ì ìŹì©í ì ìì”ëë€!
+
+ì¶ëĄ ì ìííêł ì íë ìŽëŻžì§ë„Œ ê°ì žìëŽ
ìë€:
+
+```py
+>>> ds = load_dataset("food101", split="validation[:10]")
+>>> image = ds["image"][0]
+```
+
+
+
+
+
+ëŻžìž ìĄ°ì ëȘšëžëĄ ì¶ëĄ ì ìëíë ê°ì„ ê°ëší ë°©ëČì [`pipeline`]ì ìŹì©íë êČì
ëë€. ëȘšëžëĄ ìŽëŻžì§ ë¶ë„넌 ìí `pipeline`ì ìžì€íŽì€ííêł ìŽëŻžì§ë„Œ ì ëŹí©ëë€:
+
+```py
+>>> from transformers import pipeline
+
+>>> classifier = pipeline("image-classification", model="my_awesome_food_model")
+>>> classifier(image)
+[{'score': 0.31856709718704224, 'label': 'beignets'},
+ {'score': 0.015232225880026817, 'label': 'bruschetta'},
+ {'score': 0.01519392803311348, 'label': 'chicken_wings'},
+ {'score': 0.013022331520915031, 'label': 'pork_chop'},
+ {'score': 0.012728818692266941, 'label': 'prime_rib'}]
+```
+
+ìíë€ë©Ž, `pipeline`ì êČ°êłŒë„Œ ìëìŒëĄ ëł”ì í ìë ìì”ëë€:
+
+
+
+ìŽëŻžì§ë„Œ ì ìČ늏íêž° ìíŽ ìŽëŻžì§ íëĄìžì넌 ê°ì žì€êł `input`ì PyTorch í
ìëĄ ë°íí©ëë€:
+
+```py
+>>> from transformers import AutoImageProcessor
+>>> import torch
+
+>>> image_processor = AutoImageProcessor.from_pretrained("my_awesome_food_model")
+>>> inputs = image_processor(image, return_tensors="pt")
+```
+
+ì
ë „ì ëȘšëžì ì ëŹíêł logitsì ë°íí©ëë€:
+
+```py
+>>> from transformers import AutoModelForImageClassification
+
+>>> model = AutoModelForImageClassification.from_pretrained("my_awesome_food_model")
+>>> with torch.no_grad():
+... logits = model(**inputs).logits
+```
+
+íë„ ìŽ ê°ì„ ëì ììžĄ ë ìŽëžì ê°ì žì€êł , ëȘšëžì `id2label` ë§€íì ìŹì©íìŹ ë ìŽëžëĄ ëłíí©ëë€:
+
+```py
+>>> predicted_label = logits.argmax(-1).item()
+>>> model.config.id2label[predicted_label]
+'beignets'
+```
+
+
+
+
+
+ìŽëŻžì§ë„Œ ì ìČ늏íêž° ìíŽ ìŽëŻžì§ íëĄìžì넌 ê°ì žì€êł `input`ì TensorFlow í
ìëĄ ë°íí©ëë€:
+
+```py
+>>> from transformers import AutoImageProcessor
+
+>>> image_processor = AutoImageProcessor.from_pretrained("MariaK/food_classifier")
+>>> inputs = image_processor(image, return_tensors="tf")
+```
+
+ì
ë „ì ëȘšëžì ì ëŹíêł logitsì ë°íí©ëë€:
+
+```py
+>>> from transformers import TFAutoModelForImageClassification
+
+>>> model = TFAutoModelForImageClassification.from_pretrained("MariaK/food_classifier")
+>>> logits = model(**inputs).logits
+```
+
+íë„ ìŽ ê°ì„ ëì ììžĄ ë ìŽëžì ê°ì žì€êł , ëȘšëžì `id2label` ë§€íì ìŹì©íìŹ ë ìŽëžëĄ ëłíí©ëë€:
+
+```py
+>>> predicted_class_id = int(tf.math.argmax(logits, axis=-1)[0])
+>>> model.config.id2label[predicted_class_id]
+'beignets'
+```
+
+
+
diff --git a/docs/source/ko/tasks/image_classification.mdx b/docs/source/ko/tasks/image_classification.mdx
deleted file mode 100644
index 3815f8708e75..000000000000
--- a/docs/source/ko/tasks/image_classification.mdx
+++ /dev/null
@@ -1,542 +0,0 @@
-
-
-# ìŽëŻžì§ ë¶ë„[[image-classification]]
-
-[[open-in-colab]]
-
-
-
-ìŽëŻžì§ ë¶ë„ë ìŽëŻžì§ì ë ìŽëž ëë íŽëì€ë„Œ í ëčí©ëë€. í
ì€íž ëë ì€ëì€ ë¶ë„ì ëŹëŠŹ ì
ë „ì
-ìŽëŻžì§ë„Œ ê”Źì±íë íœì
ê°ì
ëë€. ìŽëŻžì§ ë¶ë„ìë ìì°ìŹíŽ í íŒíŽ ê°ì§, ëìëŹŒ ê±Žê° ëȘšëí°ë§, ìëŁ ìŽëŻžì§ìì ì§ëłì ì§í êČìŹ ì§ì ë±
-ë€ìí ìì© ìŹëĄê° ìì”ëë€.
-
-ìŽ ê°ìŽëììë ë€ìì ì€ëȘ
í©ëë€:
-
-1. [Food-101](https://huggingface.co/datasets/food101) ë°ìŽí° ìžížìì [ViT](model_doc/vit)넌 ëŻžìž ìĄ°ì íìŹ ìŽëŻžì§ìì ìí íëȘ©ì ë¶ë„í©ëë€.
-2. ì¶ëĄ ì ìíŽ ëŻžìž ìĄ°ì ëȘšëžì ìŹì©í©ëë€.
-
-
-ìŽ íí 늏ìŒìì ì€ëȘ
íë ìì
ì ë€ì ëȘšëž ìí€í
ìČì ìíŽ ì§ìë©ëë€:
-
-
-
-[BEiT](../model_doc/beit), [BiT](../model_doc/bit), [ConvNeXT](../model_doc/convnext), [ConvNeXTV2](../model_doc/convnextv2), [CvT](../model_doc/cvt), [Data2VecVision](../model_doc/data2vec-vision), [DeiT](../model_doc/deit), [DiNAT](../model_doc/dinat), [EfficientFormer](../model_doc/efficientformer), [EfficientNet](../model_doc/efficientnet), [FocalNet](../model_doc/focalnet), [ImageGPT](../model_doc/imagegpt), [LeViT](../model_doc/levit), [MobileNetV1](../model_doc/mobilenet_v1), [MobileNetV2](../model_doc/mobilenet_v2), [MobileViT](../model_doc/mobilevit), [NAT](../model_doc/nat), [Perceiver](../model_doc/perceiver), [PoolFormer](../model_doc/poolformer), [RegNet](../model_doc/regnet), [ResNet](../model_doc/resnet), [SegFormer](../model_doc/segformer), [Swin Transformer](../model_doc/swin), [Swin Transformer V2](../model_doc/swinv2), [VAN](../model_doc/van), [ViT](../model_doc/vit), [ViT Hybrid](../model_doc/vit_hybrid), [ViTMSN](../model_doc/vit_msn)
-
-
-
-
-ììíêž° ì ì, íìí ëȘšë ëŒìŽëžëŹëŠŹê° ì€ìčëìŽ ìëì§ íìžíìžì:
-
-```bash
-pip install transformers datasets evaluate
-```
-
-Hugging Face êłì ì ëĄê·žìžíìŹ ëȘšëžì ì
ëĄëíêł ì»€ëź€ëí°ì êł”ì íë êČì ê¶ì„í©ëë€. ë©ìì§ê° íìë멎, í í°ì ì
ë „íìŹ ëĄê·žìžíìžì:
-
-```py
->>> from huggingface_hub import notebook_login
-
->>> notebook_login()
-```
-
-## Food-101 ë°ìŽí° ìžíž ê°ì žì€êž°[[load-food101-dataset]]
-
-đ€ Datasets ëŒìŽëžëŹëŠŹìì Food-101 ë°ìŽí° ìžížì ë ìì ë¶ë¶ ì§í©ì ê°ì žì€ë êČìŒëĄ ììí©ëë€. ìŽë êČ í멎 ì ìČŽ ë°ìŽí° ìžížì ëí
-íë šì ë§ì ìê°ì í ì íêž° ì ì ì€íì í”íŽ ëȘšë êČìŽ ì ëëĄ ìëíëì§ íìží ì ìì”ëë€.
-
-```py
->>> from datasets import load_dataset
-
->>> food = load_dataset("food101", split="train[:5000]")
-```
-
-ë°ìŽí° ìžížì `train`ì [`~datasets.Dataset.train_test_split`] ë©ìë넌 ìŹì©íìŹ íë š ë° í
ì€íž ìžížëĄ ë¶í íìžì:
-
-```py
->>> food = food.train_test_split(test_size=0.2)
-```
-
-ê·žëŠŹêł ìì넌 ìŽíŽëłŽìžì:
-
-```py
->>> food["train"][0]
-{'image': ,
- 'label': 79}
-```
-
-ë°ìŽí° ìžížì ê° ìì ìë ë ê°ì íëê° ìì”ëë€:
-
-- `image`: ìí íëȘ©ì PIL ìŽëŻžì§
-- `label`: ìí íëȘ©ì ë ìŽëž íŽëì€
-
-ëȘšëžìŽ ë ìŽëž IDìì ë ìŽëž ìŽëŠì ìœêČ ê°ì žìŹ ì ìëëĄ
-ë ìŽëž ìŽëŠì ì ìëĄ ë§€ííêł , ì ì넌 ë ìŽëž ìŽëŠìŒëĄ ë§€ííë ìŹì ì ë§ëìžì:
-
-```py
->>> labels = food["train"].features["label"].names
->>> label2id, id2label = dict(), dict()
->>> for i, label in enumerate(labels):
-... label2id[label] = str(i)
-... id2label[str(i)] = label
-```
-
-ìŽì ë ìŽëž ID넌 ë ìŽëž ìŽëŠìŒëĄ ëłíí ì ìì”ëë€:
-
-```py
->>> id2label[str(79)]
-'prime_rib'
-```
-
-## ì ìČ늏[[preprocess]]
-
-ë€ì ëšêłë ìŽëŻžì§ë„Œ í
ìëĄ ìČ늏íêž° ìíŽ ViT ìŽëŻžì§ íëĄìžì넌 ê°ì žì€ë êČì
ëë€:
-
-```py
->>> from transformers import AutoImageProcessor
-
->>> checkpoint = "google/vit-base-patch16-224-in21k"
->>> image_processor = AutoImageProcessor.from_pretrained(checkpoint)
-```
-
-
-
-ìŽëŻžì§ì ëȘ ê°ì§ ìŽëŻžì§ ëłíì ì ì©íìŹ êłŒì í©ì ëíŽ ëȘšëžì ë êČŹêł íêČ ë§ëëë€. ìŹêž°ì Torchvisionì [`transforms`](https://pytorch.org/vision/stable/transforms.html) ëȘšëì ìŹì©íì§ë§, ìíë ìŽëŻžì§ ëŒìŽëžëŹëŠŹë„Œ ìŹì©í ìë ìì”ëë€.
-
-ìŽëŻžì§ì ìì ë¶ë¶ì íŹëĄíêł íŹêž°ë„Œ ìĄ°ì í ë€ì, ìŽëŻžì§ íê· êłŒ íì€ ížì°šëĄ ì ê·ííìžì:
-
-```py
->>> from torchvision.transforms import RandomResizedCrop, Compose, Normalize, ToTensor
-
->>> normalize = Normalize(mean=image_processor.image_mean, std=image_processor.image_std)
->>> size = (
-... image_processor.size["shortest_edge"]
-... if "shortest_edge" in image_processor.size
-... else (image_processor.size["height"], image_processor.size["width"])
-... )
->>> _transforms = Compose([RandomResizedCrop(size), ToTensor(), normalize])
-```
-
-ê·žë° ë€ì ì ìČ늏 íšì넌 ë§ë€ìŽ ëłíì ì ì©íêł ìŽëŻžì§ì `pixel_values`(ëȘšëžì ëí ì
ë „)넌 ë°ííìžì:
-
-```py
->>> def transforms(examples):
-... examples["pixel_values"] = [_transforms(img.convert("RGB")) for img in examples["image"]]
-... del examples["image"]
-... return examples
-```
-
-ì ìČŽ ë°ìŽí° ìžížì ì ìČ늏 êž°ë„ì ì ì©íë €ë©Ž đ€ Datasets [`~datasets.Dataset.with_transform`]ì ìŹì©í©ëë€. ë°ìŽí° ìžížì ìì넌 ê°ì žìŹ ë ëłíìŽ ìŠì ì ì©ë©ëë€:
-
-```py
->>> food = food.with_transform(transforms)
-```
-
-ìŽì [`DefaultDataCollator`]넌 ìŹì©íìŹ ìì ë°°ìč넌 ë§ëëë€. đ€ Transformersì ë€ë„ž ë°ìŽí° ìœë ìŽí°ì ëŹëŠŹ, `DefaultDataCollator`ë íšë©êłŒ ê°ì ì¶ê°ì ìž ì ìČëŠŹë„Œ ì ì©íì§ ìì”ëë€.
-
-```py
->>> from transformers import DefaultDataCollator
-
->>> data_collator = DefaultDataCollator()
-```
-
-
-
-
-
-
-
-êłŒì í©ì ë°©ì§íêł ëȘšëžì ëłŽë€ êČŹêł íêČ ë§ë€êž° ìíŽ ë°ìŽí° ìžížì íë š ë¶ë¶ì ë°ìŽí° ìŠê°ì ì¶ê°í©ëë€.
-ìŹêž°ì Keras ì ìČ늏 ë ìŽìŽëĄ íë š ë°ìŽí°ì ëí ëłí(ë°ìŽí° ìŠê° íŹíš)êłŒ
-êČìŠ ë°ìŽí°ì ëí ëłí(ì€ì íŹëĄí, íŹêž° ìĄ°ì , ì ê·íë§)ì ì ìí©ëë€.
-`tf.image` ëë ë€ë„ž ìíë ëŒìŽëžëŹëŠŹë„Œ ìŹì©í ì ìì”ëë€.
-
-```py
->>> from tensorflow import keras
->>> from tensorflow.keras import layers
-
->>> size = (image_processor.size["height"], image_processor.size["width"])
-
->>> train_data_augmentation = keras.Sequential(
-... [
-... layers.RandomCrop(size[0], size[1]),
-... layers.Rescaling(scale=1.0 / 127.5, offset=-1),
-... layers.RandomFlip("horizontal"),
-... layers.RandomRotation(factor=0.02),
-... layers.RandomZoom(height_factor=0.2, width_factor=0.2),
-... ],
-... name="train_data_augmentation",
-... )
-
->>> val_data_augmentation = keras.Sequential(
-... [
-... layers.CenterCrop(size[0], size[1]),
-... layers.Rescaling(scale=1.0 / 127.5, offset=-1),
-... ],
-... name="val_data_augmentation",
-... )
-```
-
-ë€ììŒëĄ í ëČì íëì ìŽëŻžì§ê° ìëëŒ ìŽëŻžì§ ë°°ìčì ì ì í ëłíì ì ì©íë íšì넌 ë§ëëë€.
-
-```py
->>> import numpy as np
->>> import tensorflow as tf
->>> from PIL import Image
-
-
->>> def convert_to_tf_tensor(image: Image):
-... np_image = np.array(image)
-... tf_image = tf.convert_to_tensor(np_image)
-... # `expand_dims()` is used to add a batch dimension since
-... # the TF augmentation layers operates on batched inputs.
-... return tf.expand_dims(tf_image, 0)
-
-
->>> def preprocess_train(example_batch):
-... """Apply train_transforms across a batch."""
-... images = [
-... train_data_augmentation(convert_to_tf_tensor(image.convert("RGB"))) for image in example_batch["image"]
-... ]
-... example_batch["pixel_values"] = [tf.transpose(tf.squeeze(image)) for image in images]
-... return example_batch
-
-
-... def preprocess_val(example_batch):
-... """Apply val_transforms across a batch."""
-... images = [
-... val_data_augmentation(convert_to_tf_tensor(image.convert("RGB"))) for image in example_batch["image"]
-... ]
-... example_batch["pixel_values"] = [tf.transpose(tf.squeeze(image)) for image in images]
-... return example_batch
-```
-
-đ€ Datasets [`~datasets.Dataset.set_transform`]넌 ìŹì©íìŹ ìŠì ëłíì ì ì©íìžì:
-
-```py
-food["train"].set_transform(preprocess_train)
-food["test"].set_transform(preprocess_val)
-```
-
-ì”ìą
ì ìČ늏 ëšêłëĄ `DefaultDataCollator`넌 ìŹì©íìŹ ìì ë°°ìč넌 ë§ëëë€. đ€ Transformersì ë€ë„ž ë°ìŽí° ìœë ìŽí°ì ëŹëŠŹ
-`DefaultDataCollator`ë íšë©êłŒ ê°ì ì¶ê° ì ìČëŠŹë„Œ ì ì©íì§ ìì”ëë€.
-
-```py
->>> from transformers import DefaultDataCollator
-
->>> data_collator = DefaultDataCollator(return_tensors="tf")
-```
-
-
-
-## íê°[[evaluate]]
-
-íë š ì€ì íê° ì§í넌 íŹíší멎 ëȘšëžì ì±ë„ì íê°íë ë° ëììŽ ëë êČœì°ê° ë§ì”ëë€.
-đ€ [Evaluate](https://huggingface.co/docs/evaluate/index) ëŒìŽëžëŹëŠŹëĄ íê° ë°©ëČì ëč 넎êČ ê°ì žìŹ ì ìì”ëë€. ìŽ ìì
ììë
-[accuracy](https://huggingface.co/spaces/evaluate-metric/accuracy) íê° ì§í넌 ê°ì žì”ëë€. (đ€ Evaluate [ëč 넞 ëëŹëłŽêž°](https://huggingface.co/docs/evaluate/a_quick_tour)넌 ì°žìĄ°íìŹ íê° ì§í넌 ê°ì žì€êł êłì°íë ë°©ëČì ëíŽ ììží ìì볎ìžì):
-
-```py
->>> import evaluate
-
->>> accuracy = evaluate.load("accuracy")
-```
-
-ê·žë° ë€ì ììžĄêłŒ ë ìŽëžì [`~evaluate.EvaluationModule.compute`]ì ì ëŹíìŹ ì íë넌 êłì°íë íšì넌 ë§ëëë€:
-
-```py
->>> import numpy as np
-
-
->>> def compute_metrics(eval_pred):
-... predictions, labels = eval_pred
-... predictions = np.argmax(predictions, axis=1)
-... return accuracy.compute(predictions=predictions, references=labels)
-```
-
-ìŽì `compute_metrics` íšì넌 ìŹì©í ì€ëčê° ëììŒë©°, íë šì ì€ì í멎 ìŽ íšìëĄ ëëììŹ êČì
ëë€.
-
-## íë š[[train]]
-
-
-
-
-
-[`Trainer`]넌 ìŹì©íìŹ ëȘšëžì ëŻžìž ìĄ°ì íë ë°©ëČì ì”ìíì§ ìì êČœì°, [ìŹêž°](../training#train-with-pytorch-trainer)ìì êž°ëłž íí 늏ìŒì íìžíìžì!
-
-
-
-ìŽì ëȘšëžì íë šìíŹ ì€ëčê° ëìì”ëë€! [`AutoModelForImageClassification`]ëĄ ViT넌 ê°ì žì”ëë€. ììëë ë ìŽëž ì, ë ìŽëž ë§€í ë° ë ìŽëž ì넌 ì§ì íìžì:
-
-```py
->>> from transformers import AutoModelForImageClassification, TrainingArguments, Trainer
-
->>> model = AutoModelForImageClassification.from_pretrained(
-... checkpoint,
-... num_labels=len(labels),
-... id2label=id2label,
-... label2id=label2id,
-... )
-```
-
-ìŽì ìž ëšêłë§ ê±°ìč멎 ëì
ëë€:
-
-1. [`TrainingArguments`]ìì íë š íìŽíŒíëŒëŻží°ë„Œ ì ìíìžì. `image` ìŽìŽ ìì ëêž° ë돞ì 믞ìŹì© ìŽì ì ê±°íì§ ìë êČìŽ ì€ìí©ëë€. `image` ìŽìŽ ììŒë©Ž `pixel_values`ì ìì±í ì ìì”ëë€. ìŽ ëìì ë°©ì§íë €ë©Ž `remove_unused_columns=False`ëĄ ì€ì íìžì! ë€ë„ž ì ìŒí íì ë§€ê°ëłìë ëȘšëž ì ì„ ììč넌 ì§ì íë `output_dir`ì
ëë€. `push_to_hub=True`ëĄ ì€ì í멎 ìŽ ëȘšëžì íëžì ížìí©ëë€(ëȘšëžì ì
ëĄëíë €ë©Ž Hugging Faceì ëĄê·žìžíŽìŒ í©ëë€). ê° ìíìŽ ëë ëë§ë€, [`Trainer`]ê° ì íë넌 íê°íêł íë š ìČŽíŹíŹìžížë„Œ ì ì„í©ëë€.
-2. [`Trainer`]ì ëȘšëž, ë°ìŽí° ìžíž, í íŹëìŽì , ë°ìŽí° ìœë ìŽí° ë° `compute_metrics` íšìì íšê» íë š ìžì넌 ì ëŹíìžì.
-3. [`~Trainer.train`]ì ížì¶íìŹ ëȘšëžì ëŻžìž ìĄ°ì íìžì.
-
-```py
->>> training_args = TrainingArguments(
-... output_dir="my_awesome_food_model",
-... remove_unused_columns=False,
-... evaluation_strategy="epoch",
-... save_strategy="epoch",
-... learning_rate=5e-5,
-... per_device_train_batch_size=16,
-... gradient_accumulation_steps=4,
-... per_device_eval_batch_size=16,
-... num_train_epochs=3,
-... warmup_ratio=0.1,
-... logging_steps=10,
-... load_best_model_at_end=True,
-... metric_for_best_model="accuracy",
-... push_to_hub=True,
-... )
-
->>> trainer = Trainer(
-... model=model,
-... args=training_args,
-... data_collator=data_collator,
-... train_dataset=food["train"],
-... eval_dataset=food["test"],
-... tokenizer=image_processor,
-... compute_metrics=compute_metrics,
-... )
-
->>> trainer.train()
-```
-
-íë šìŽ ìëŁë멎, ëȘšë ìŹëìŽ ëȘšëžì ìŹì©í ì ìëëĄ [`~transformers.Trainer.push_to_hub`] ë©ìëëĄ ëȘšëžì íëžì êł”ì íìžì:
-
-```py
->>> trainer.push_to_hub()
-```
-
-
-
-
-
-
-
-
-Keras넌 ìŹì©íìŹ ëȘšëžì ëŻžìž ìĄ°ì íë ë°©ëČì ì”ìíì§ ìì êČœì°, 뚌ì [êž°ëłž íí 늏ìŒ](./training#train-a-tensorflow-model-with-keras)ì íìžíìžì!
-
-
-
-TensorFlowìì ëȘšëžì ëŻžìž ìĄ°ì íë €ë©Ž ë€ì ëšêłë„Œ ë°ë„Žìžì:
-1. íë š íìŽíŒíëŒëŻží°ë„Œ ì ìíêł ì”í°ë§ìŽì ì íì”ë„ ì€ìŒì„Žì ì€ì í©ëë€.
-2. ìŹì íë šë ëȘšëžì ìžì€íŽì€íí©ëë€.
-3. đ€ Datasetì `tf.data.Dataset`ìŒëĄ ëłíí©ëë€.
-4. ëȘšëžì 컎íìŒí©ëë€.
-5. ìœë°±ì ì¶ê°íêł íë šì ìííêž° ìíŽ `fit()` ë©ìë넌 ìŹì©í©ëë€.
-6. ì»€ëź€ëí°ì êł”ì íêž° ìíŽ ëȘšëžì đ€ Hubì ì
ëĄëí©ëë€.
-
-íìŽíŒíëŒëŻží°, ì”í°ë§ìŽì ë° íì”ë„ ì€ìŒì„Žì ì ìíë êČìŒëĄ ììí©ëë€:
-
-```py
->>> from transformers import create_optimizer
-
->>> batch_size = 16
->>> num_epochs = 5
->>> num_train_steps = len(food["train"]) * num_epochs
->>> learning_rate = 3e-5
->>> weight_decay_rate = 0.01
-
->>> optimizer, lr_schedule = create_optimizer(
-... init_lr=learning_rate,
-... num_train_steps=num_train_steps,
-... weight_decay_rate=weight_decay_rate,
-... num_warmup_steps=0,
-... )
-```
-
-ê·žë° ë€ì ë ìŽëž ë§€íêłŒ íšê» [`TFAuto ModelForImageClassification`]ìŒëĄ ViT넌 ê°ì žì”ëë€:
-
-```py
->>> from transformers import TFAutoModelForImageClassification
-
->>> model = TFAutoModelForImageClassification.from_pretrained(
-... checkpoint,
-... id2label=id2label,
-... label2id=label2id,
-... )
-```
-
-ë°ìŽí° ìžížë„Œ [`~datasets.Dataset.to_tf_dataset`]ì `data_collator`넌 ìŹì©íìŹ `tf.data.Dataset` íììŒëĄ ëłííìžì:
-
-```py
->>> # converting our train dataset to tf.data.Dataset
->>> tf_train_dataset = food["train"].to_tf_dataset(
-... columns="pixel_values", label_cols="label", shuffle=True, batch_size=batch_size, collate_fn=data_collator
-... )
-
->>> # converting our test dataset to tf.data.Dataset
->>> tf_eval_dataset = food["test"].to_tf_dataset(
-... columns="pixel_values", label_cols="label", shuffle=True, batch_size=batch_size, collate_fn=data_collator
-... )
-```
-
-`compile()`넌 ìŹì©íìŹ íë š ëȘšëžì ê”Źì±íìžì:
-
-```py
->>> from tensorflow.keras.losses import SparseCategoricalCrossentropy
-
->>> loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
->>> model.compile(optimizer=optimizer, loss=loss)
-```
-
-ììžĄìì ì íë넌 êłì°íêł ëȘšëžì đ€ HubëĄ ížìíë €ë©Ž [Keras callbacks](../main_classes/keras_callbacks)넌 ìŹì©íìžì.
-`compute_metrics` íšì넌 [KerasMetricCallback](../main_classes/keras_callbacks#transformers.KerasMetricCallback)ì ì ëŹíêł ,
-[PushToHubCallback](../main_classes/keras_callbacks#transformers.PushToHubCallback)ì ìŹì©íìŹ ëȘšëžì ì
ëĄëí©ëë€:
-
-```py
->>> from transformers.keras_callbacks import KerasMetricCallback, PushToHubCallback
-
->>> metric_callback = KerasMetricCallback(metric_fn=compute_metrics, eval_dataset=tf_eval_dataset)
->>> push_to_hub_callback = PushToHubCallback(
-... output_dir="food_classifier",
-... tokenizer=image_processor,
-... save_strategy="no",
-... )
->>> callbacks = [metric_callback, push_to_hub_callback]
-```
-
-ìŽì ëȘšëžì íë ší ì€ëčê° ëìì”ëë€! íë š ë° êČìŠ ë°ìŽí° ìžíž, ìí ìì íšê» `fit()`ì ížì¶íêł ,
-ìœë°±ì ìŹì©íìŹ ëȘšëžì ëŻžìž ìĄ°ì í©ëë€:
-
-```py
->>> model.fit(tf_train_dataset, validation_data=tf_eval_dataset, epochs=num_epochs, callbacks=callbacks)
-Epoch 1/5
-250/250 [==============================] - 313s 1s/step - loss: 2.5623 - val_loss: 1.4161 - accuracy: 0.9290
-Epoch 2/5
-250/250 [==============================] - 265s 1s/step - loss: 0.9181 - val_loss: 0.6808 - accuracy: 0.9690
-Epoch 3/5
-250/250 [==============================] - 252s 1s/step - loss: 0.3910 - val_loss: 0.4303 - accuracy: 0.9820
-Epoch 4/5
-250/250 [==============================] - 251s 1s/step - loss: 0.2028 - val_loss: 0.3191 - accuracy: 0.9900
-Epoch 5/5
-250/250 [==============================] - 238s 949ms/step - loss: 0.1232 - val_loss: 0.3259 - accuracy: 0.9890
-```
-
-ì¶íí©ëë€! ëȘšëžì ëŻžìž ìĄ°ì íêł đ€ Hubì êł”ì íì”ëë€. ìŽì ì¶ëĄ ì ìŹì©í ì ìì”ëë€!
-
-
-
-
-
-
-ìŽëŻžì§ ë¶ë„넌 ìí ëȘšëžì ëŻžìž ìĄ°ì íë ììží ìì ë ë€ì [PyTorch notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb)ì ì°žìĄ°íìžì.
-
-
-
-## ì¶ëĄ [[inference]]
-
-ìąìì, ìŽì ëȘšëžì ëŻžìž ìĄ°ì íìŒë ì¶ëĄ ì ìŹì©í ì ìì”ëë€!
-
-ì¶ëĄ ì ìííêł ì íë ìŽëŻžì§ë„Œ ê°ì žìëŽ
ìë€:
-
-```py
->>> ds = load_dataset("food101", split="validation[:10]")
->>> image = ds["image"][0]
-```
-
-
-
-
-
-ëŻžìž ìĄ°ì ëȘšëžëĄ ì¶ëĄ ì ìëíë ê°ì„ ê°ëší ë°©ëČì [`pipeline`]ì ìŹì©íë êČì
ëë€. ëȘšëžëĄ ìŽëŻžì§ ë¶ë„넌 ìí `pipeline`ì ìžì€íŽì€ííêł ìŽëŻžì§ë„Œ ì ëŹí©ëë€:
-
-```py
->>> from transformers import pipeline
-
->>> classifier = pipeline("image-classification", model="my_awesome_food_model")
->>> classifier(image)
-[{'score': 0.31856709718704224, 'label': 'beignets'},
- {'score': 0.015232225880026817, 'label': 'bruschetta'},
- {'score': 0.01519392803311348, 'label': 'chicken_wings'},
- {'score': 0.013022331520915031, 'label': 'pork_chop'},
- {'score': 0.012728818692266941, 'label': 'prime_rib'}]
-```
-
-ìíë€ë©Ž, `pipeline`ì êČ°êłŒë„Œ ìëìŒëĄ ëł”ì í ìë ìì”ëë€:
-
-
-
-ìŽëŻžì§ë„Œ ì ìČ늏íêž° ìíŽ ìŽëŻžì§ íëĄìžì넌 ê°ì žì€êł `input`ì PyTorch í
ìëĄ ë°íí©ëë€:
-
-```py
->>> from transformers import AutoImageProcessor
->>> import torch
-
->>> image_processor = AutoImageProcessor.from_pretrained("my_awesome_food_model")
->>> inputs = image_processor(image, return_tensors="pt")
-```
-
-ì
ë „ì ëȘšëžì ì ëŹíêł logitsì ë°íí©ëë€:
-
-```py
->>> from transformers import AutoModelForImageClassification
-
->>> model = AutoModelForImageClassification.from_pretrained("my_awesome_food_model")
->>> with torch.no_grad():
-... logits = model(**inputs).logits
-```
-
-íë„ ìŽ ê°ì„ ëì ììžĄ ë ìŽëžì ê°ì žì€êł , ëȘšëžì `id2label` ë§€íì ìŹì©íìŹ ë ìŽëžëĄ ëłíí©ëë€:
-
-```py
->>> predicted_label = logits.argmax(-1).item()
->>> model.config.id2label[predicted_label]
-'beignets'
-```
-
-
-
-
-
-ìŽëŻžì§ë„Œ ì ìČ늏íêž° ìíŽ ìŽëŻžì§ íëĄìžì넌 ê°ì žì€êł `input`ì TensorFlow í
ìëĄ ë°íí©ëë€:
-
-```py
->>> from transformers import AutoImageProcessor
-
->>> image_processor = AutoImageProcessor.from_pretrained("MariaK/food_classifier")
->>> inputs = image_processor(image, return_tensors="tf")
-```
-
-ì
ë „ì ëȘšëžì ì ëŹíêł logitsì ë°íí©ëë€:
-
-```py
->>> from transformers import TFAutoModelForImageClassification
-
->>> model = TFAutoModelForImageClassification.from_pretrained("MariaK/food_classifier")
->>> logits = model(**inputs).logits
-```
-
-íë„ ìŽ ê°ì„ ëì ììžĄ ë ìŽëžì ê°ì žì€êł , ëȘšëžì `id2label` ë§€íì ìŹì©íìŹ ë ìŽëžëĄ ëłíí©ëë€:
-
-```py
->>> predicted_class_id = int(tf.math.argmax(logits, axis=-1)[0])
->>> model.config.id2label[predicted_class_id]
-'beignets'
-```
-
-
-
diff --git a/docs/source/ko/tasks/language_modeling.md b/docs/source/ko/tasks/language_modeling.md
new file mode 100644
index 000000000000..ba540825c295
--- /dev/null
+++ b/docs/source/ko/tasks/language_modeling.md
@@ -0,0 +1,417 @@
+
+
+# ìžêłŒ ìžìŽ ëȘšëžë§[[causal-language-modeling]]
+
+[[open-in-colab]]
+
+ìžìŽ ëȘšëžë§ì ìžêłŒì ìžìŽ ëȘšëžë§êłŒ ë§ì€íŹë ìžìŽ ëȘšëžë§, ë ê°ì§ ì íìŒëĄ ëë©ëë€. ìŽ ê°ìŽëììë ìžêłŒì ìžìŽ ëȘšëžë§ì ì€ëȘ
í©ëë€.
+ìžêłŒ ìžìŽ ëȘšëžì í
ì€íž ìì±ì ììŁŒ ìŹì©ë©ëë€. ë ì°œìì ìž ë°©í„ìŒëĄ ìì©í ì ìì”ëë€.
+ì§ì ìŹì©íë©° ìŹëŻžìë íê”Źë„Œ íŽëłŽê±°ë, Copilot ëë CodeParrotì ê°ì ì§ë„í ìœë© ìŽìì€íŽížì êž°ë°ìŽ ëêž°ë í©ëë€.
+
+
+
+ìžêłŒ ìžìŽ ëȘšëžë§ì í í° ìíì€ìì ë€ì í í°ì ììžĄíë©°, ëȘšëžì ìŒìȘœì í í°ìë§ ì ê·Œí ì ìì”ëë€.
+ìŽë ëȘšëžìŽ ëŻžëì í í°ì ëłŒ ì ìë€ë êČì ì믞í©ëë€. ìžêłŒ ìžìŽ ëȘšëžì ìëĄ GPT-2ê° ììŁ .
+
+ìŽ ê°ìŽëììë ë€ì ìì
ì ìííë ë°©ëČì ìëŽí©ëë€:
+
+1. [DistilGPT2](https://huggingface.co/distilgpt2) ëȘšëžì [ELI5](https://huggingface.co/datasets/eli5) ë°ìŽí° ìžížì [r/askscience](https://www.reddit.com/r/askscience/) íì ì§í©ìŒëĄ ëŻžìž ìĄ°ì
+2. ëŻžìž ìĄ°ì ë ëȘšëžì ì¶ëĄ ì ìŹì©
+
+
+ìŽ ìëŽìì ëšêłì ëìŒí ë°©ëČìŒëĄ ìžêłŒ ìžìŽ ëȘšëžë§ì ìíŽ ë€ë„ž ìí€í
ìČ넌 ëŻžìž ìĄ°ì í ì ìì”ëë€.
+ë€ì ìí€í
ìČ ì€ íë넌 ì ííìžì:
+
+
+[BART](../model_doc/bart), [BERT](../model_doc/bert), [Bert Generation](../model_doc/bert-generation), [BigBird](../model_doc/big_bird), [BigBird-Pegasus](../model_doc/bigbird_pegasus), [BioGpt](../model_doc/biogpt), [Blenderbot](../model_doc/blenderbot), [BlenderbotSmall](../model_doc/blenderbot-small), [BLOOM](../model_doc/bloom), [CamemBERT](../model_doc/camembert), [CodeGen](../model_doc/codegen), [CPM-Ant](../model_doc/cpmant), [CTRL](../model_doc/ctrl), [Data2VecText](../model_doc/data2vec-text), [ELECTRA](../model_doc/electra), [ERNIE](../model_doc/ernie), [GIT](../model_doc/git), [GPT-Sw3](../model_doc/gpt-sw3), [OpenAI GPT-2](../model_doc/gpt2), [GPTBigCode](../model_doc/gpt_bigcode), [GPT Neo](../model_doc/gpt_neo), [GPT NeoX](../model_doc/gpt_neox), [GPT NeoX Japanese](../model_doc/gpt_neox_japanese), [GPT-J](../model_doc/gptj), [LLaMA](../model_doc/llama), [Marian](../model_doc/marian), [mBART](../model_doc/mbart), [MEGA](../model_doc/mega), [Megatron-BERT](../model_doc/megatron-bert), [MVP](../model_doc/mvp), [OpenLlama](../model_doc/open-llama), [OpenAI GPT](../model_doc/openai-gpt), [OPT](../model_doc/opt), [Pegasus](../model_doc/pegasus), [PLBart](../model_doc/plbart), [ProphetNet](../model_doc/prophetnet), [QDQBert](../model_doc/qdqbert), [Reformer](../model_doc/reformer), [RemBERT](../model_doc/rembert), [RoBERTa](../model_doc/roberta), [RoBERTa-PreLayerNorm](../model_doc/roberta-prelayernorm), [RoCBert](../model_doc/roc_bert), [RoFormer](../model_doc/roformer), [RWKV](../model_doc/rwkv), [Speech2Text2](../model_doc/speech_to_text_2), [Transformer-XL](../model_doc/transfo-xl), [TrOCR](../model_doc/trocr), [XGLM](../model_doc/xglm), [XLM](../model_doc/xlm), [XLM-ProphetNet](../model_doc/xlm-prophetnet), [XLM-RoBERTa](../model_doc/xlm-roberta), [XLM-RoBERTa-XL](../model_doc/xlm-roberta-xl), [XLNet](../model_doc/xlnet), [X-MOD](../model_doc/xmod)
+
+
+
+
+
+
+ììíêž° ì ì íìí ëŒìŽëžëŹëŠŹê° ëȘšë ì€ìčëìŽ ìëì§ íìžíìžì:
+
+```bash
+pip install transformers datasets evaluate
+```
+
+ì»€ëź€ëí°ì ëȘšëžì ì
ëĄëíêł êł”ì íêž° ìíŽ Hugging Face êłì ì ëĄê·žìžíë êČì ê¶ì„í©ëë€. ìëŠŒìŽ íìë멎 í í°ì ì
ë „íìŹ ëĄê·žìžíìžì:
+
+```py
+>>> from huggingface_hub import notebook_login
+
+>>> notebook_login()
+```
+
+## ELI5 ë°ìŽí° ìžíž ë¶ëŹì€êž°[[load-eli5-dataset]]
+
+뚌ì , đ€ Datasets ëŒìŽëžëŹëŠŹìì r/askscienceì ìì íì ì§í©ìž ELI5 ë°ìŽí° ìžížë„Œ ë¶ëŹì”ëë€.
+ìŽë„Œ í”íŽ ì ìČŽ ë°ìŽí° ìžížìì íì”íë ë° ë ë§ì ìê°ì íŹìíêž° ì ì, ì€ííŽëŽìŒëĄìš ëȘšë êČìŽ ìëíëì§ íìží ì ìì”ëë€.
+
+```py
+>>> from datasets import load_dataset
+
+>>> eli5 = load_dataset("eli5", split="train_asks[:5000]")
+```
+
+ë°ìŽí° ìžížì `train_asks` ë¶í ì [`~datasets.Dataset.train_test_split`] ë©ìë넌 ìŹì©íìŹ íì” ë° í
ì€íž ìžížëĄ ë¶í í©ëë€:
+
+```py
+>>> eli5 = eli5.train_test_split(test_size=0.2)
+```
+
+ê·žë° ë€ì ìì 넌 ìŽíŽëłŽìžì:
+
+```py
+>>> eli5["train"][0]
+{'answers': {'a_id': ['c3d1aib', 'c3d4lya'],
+ 'score': [6, 3],
+ 'text': ["The velocity needed to remain in orbit is equal to the square root of Newton's constant times the mass of earth divided by the distance from the center of the earth. I don't know the altitude of that specific mission, but they're usually around 300 km. That means he's going 7-8 km/s.\n\nIn space there are no other forces acting on either the shuttle or the guy, so they stay in the same position relative to each other. If he were to become unable to return to the ship, he would presumably run out of oxygen, or slowly fall into the atmosphere and burn up.",
+ "Hope you don't mind me asking another question, but why aren't there any stars visible in this photo?"]},
+ 'answers_urls': {'url': []},
+ 'document': '',
+ 'q_id': 'nyxfp',
+ 'selftext': '_URL_0_\n\nThis was on the front page earlier and I have a few questions about it. Is it possible to calculate how fast the astronaut would be orbiting the earth? Also how does he stay close to the shuttle so that he can return safely, i.e is he orbiting at the same speed and can therefore stay next to it? And finally if his propulsion system failed, would he eventually re-enter the atmosphere and presumably die?',
+ 'selftext_urls': {'url': ['http://apod.nasa.gov/apod/image/1201/freeflyer_nasa_3000.jpg']},
+ 'subreddit': 'askscience',
+ 'title': 'Few questions about this space walk photograph.',
+ 'title_urls': {'url': []}}
+```
+
+ë§ì ëłŽìŒ ì ìì§ë§, ì€ì ëĄë `text` íëë§ ì€ìí©ëë€. ìžìŽ ëȘšëžë§ ìì
ì ì„ì ì ë ìŽëžìŽ íìíì§ ìë€ë êČì
ëë€. ë€ì ëšìŽ *ììČŽê°* ë ìŽëžì
ëë€. (ìŽë êČ ë ìŽëžì ì êł”íì§ ììë ëë íì”ì ëčì§ë íì”ìŽëŒêł ìŒì»«ì”ëë€)
+
+## ì ìČ늏[[preprocess]]
+
+
+
+ë€ì ëšêłë `text` íë넌 ì ìČ늏íêž° ìíŽ DistilGPT2 í íŹëìŽì 넌 ë¶ëŹì€ë êČì
ëë€.
+
+```py
+>>> from transformers import AutoTokenizer
+
+>>> tokenizer = AutoTokenizer.from_pretrained("distilgpt2")
+```
+
+ìì ìì ìì ì ì ìëŻìŽ, `text` íëë `answers` ìëì ì€ìČ©ëìŽ ìì”ëë€. ë°ëŒì [`flatten`](https://huggingface.co/docs/datasets/process.html#flatten) ë©ìë넌 ìŹì©íìŹ ì€ìČ© ê”ŹìĄ°ìì `text` íì íë넌 ì¶ì¶íŽìŒ í©ëë€.
+
+```py
+>>> eli5 = eli5.flatten()
+>>> eli5["train"][0]
+{'answers.a_id': ['c3d1aib', 'c3d4lya'],
+ 'answers.score': [6, 3],
+ 'answers.text': ["The velocity needed to remain in orbit is equal to the square root of Newton's constant times the mass of earth divided by the distance from the center of the earth. I don't know the altitude of that specific mission, but they're usually around 300 km. That means he's going 7-8 km/s.\n\nIn space there are no other forces acting on either the shuttle or the guy, so they stay in the same position relative to each other. If he were to become unable to return to the ship, he would presumably run out of oxygen, or slowly fall into the atmosphere and burn up.",
+ "Hope you don't mind me asking another question, but why aren't there any stars visible in this photo?"],
+ 'answers_urls.url': [],
+ 'document': '',
+ 'q_id': 'nyxfp',
+ 'selftext': '_URL_0_\n\nThis was on the front page earlier and I have a few questions about it. Is it possible to calculate how fast the astronaut would be orbiting the earth? Also how does he stay close to the shuttle so that he can return safely, i.e is he orbiting at the same speed and can therefore stay next to it? And finally if his propulsion system failed, would he eventually re-enter the atmosphere and presumably die?',
+ 'selftext_urls.url': ['http://apod.nasa.gov/apod/image/1201/freeflyer_nasa_3000.jpg'],
+ 'subreddit': 'askscience',
+ 'title': 'Few questions about this space walk photograph.',
+ 'title_urls.url': []}
+```
+
+ê° íì íëë ìŽì `answers` ì ëìŹë„Œ ê°ì§ ëłëì ìŽëĄ ëëììŒë©°, `text` íëë ìŽì 늏ì€ížì
ëë€. ê° ëŹžì„ì ê°ëłì ìŒëĄ í í°ííë ëì , 뚌ì 늏ì€ížë„Œ 돞ììŽëĄ ëłííìŹ íêșŒëČì í í°íí ì ìì”ëë€.
+
+ë€ìì 돞ììŽ ëŠŹì€ížë„Œ êȰí©íêł êČ°êłŒë„Œ í í°ííë ìČ« ëČì§ž ì ìČ늏 íšìì
ëë€:
+
+```py
+>>> def preprocess_function(examples):
+... return tokenizer([" ".join(x) for x in examples["answers.text"]])
+```
+
+ìŽ ì ìČ늏 íšì넌 ì ìČŽ ë°ìŽí° ìžížì ì ì©íë €ë©Ž đ€ Datasets [`~datasets.Dataset.map`] ë©ìë넌 ìŹì©íìžì. `batched=True`ëĄ ì€ì íìŹ ë°ìŽí°ì
ì ìŹëŹ ìì넌 í ëČì ìČ늏íêł , `num_proc`넌 ìŠê°ììŒ íëĄìžì€ ì넌 ë늎 ì ìì”ëë€. íì ìë ìŽì ì ê±°íìžì:
+
+```py
+>>> tokenized_eli5 = eli5.map(
+... preprocess_function,
+... batched=True,
+... num_proc=4,
+... remove_columns=eli5["train"].column_names,
+... )
+```
+
+ìŽì ë°ìŽí° ìžížë ìíì€ê° í í°íëì§ë§, ìŒë¶ ìíì€ë ëȘšëžì ì”ë ì
ë „ êžžìŽëłŽë€ êžž ì ìì”ëë€.
+
+ìŽì ë ëČì§ž ì ìČ늏 íšì넌 ìŹì©íìŹ
+- ëȘšë ìíì€ë„Œ ì°êȰíêł ,
+- `block_size`ëĄ ì ìë êžžìŽëĄ ì°êȰë ìíì€ë„Œ ìŹëŹ ê°ì ì§§ì 돶ììŒëĄ ëëëë€. ìŽ ê°ì ì”ë ì
ë „ êžžìŽì GPU RAMì êł ë €íŽ ì¶©ë¶í ì§§ììŒ í©ëë€.
+
+```py
+>>> block_size = 128
+
+
+>>> def group_texts(examples):
+... # Concatenate all texts.
+... concatenated_examples = {k: sum(examples[k], []) for k in examples.keys()}
+... total_length = len(concatenated_examples[list(examples.keys())[0]])
+... # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can
+... # customize this part to your needs.
+... if total_length >= block_size:
+... total_length = (total_length // block_size) * block_size
+... # Split by chunks of block_size.
+... result = {
+... k: [t[i : i + block_size] for i in range(0, total_length, block_size)]
+... for k, t in concatenated_examples.items()
+... }
+... result["labels"] = result["input_ids"].copy()
+... return result
+```
+
+ì ìČŽ ë°ìŽí° ìžížì `group_texts` íšì넌 ì ì©íìžì:
+
+```py
+>>> lm_dataset = tokenized_eli5.map(group_texts, batched=True, num_proc=4)
+```
+
+ê·žë° ë€ì [`DataCollatorForLanguageModeling`]ì ìŹì©íìŹ ìì ì ë°°ìč넌 ë§ëëë€. ë°ìŽí° ìžíž ì ìČŽë„Œ ì”ë êžžìŽëĄ íšë©íë êČ볎ë€, ì·ší© ëšêłìì ê° ë°°ìčì ì”ë êžžìŽëĄ 돞ì„ì *ëì ìŒëĄ íšë©*íë êČìŽ ë íšìšì ì
ëë€.
+
+
+
+íšë© í í°ìŒëĄ ìą
êȰ í í°ì ìŹì©íêł `mlm=False`ëĄ ì€ì íìžì. ìŽë êČ í멎 ì
ë „ì ì€ë„žìȘœìŒëĄ í ìčžì© ìííží ê°ì ë ìŽëžëĄ ìŹì©í©ëë€:
+
+```py
+>>> from transformers import DataCollatorForLanguageModeling
+
+>>> tokenizer.pad_token = tokenizer.eos_token
+>>> data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False)
+```
+
+
+
+íšë© í í°ìŒëĄ ìą
êȰ í í°ì ìŹì©íêł `mlm=False`ëĄ ì€ì íìžì. ìŽë êČ í멎 ì
ë „ì ì€ë„žìȘœìŒëĄ í ìčžì© ìííží ê°ì ë ìŽëžëĄ ìŹì©í©ëë€:
+
+```py
+>>> from transformers import DataCollatorForLanguageModeling
+
+>>> data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False, return_tensors="tf")
+```
+
+
+
+
+
+## íë š[[train]]
+
+
+
+
+
+[`Trainer`]넌 ìŹì©íìŹ ëȘšëžì ëŻžìž ìĄ°ì íë ë°©ëČì ì ëȘšë„Žì ë€ë©Ž [êž°ëłž íí 늏ìŒ](../training#train-with-pytorch-trainer)ì íìžíŽëłŽìžì!
+
+
+
+ìŽì ëȘšëžì íë šíêž° ì€ëčê° ëìì”ëë€! [`AutoModelForCausalLM`]넌 ìŹì©íìŹ DistilGPT2넌 ë¶ëŹì”ëë€:
+
+```py
+>>> from transformers import AutoModelForCausalLM, TrainingArguments, Trainer
+
+>>> model = AutoModelForCausalLM.from_pretrained("distilgpt2")
+```
+
+ìŹêž°êčì§ ì§íí멎 ìž ëšêłë§ ëšìì”ëë€:
+
+1. [`TrainingArguments`]ìì íë š íìŽíŒíëŒëŻží°ë„Œ ì ìíìžì. `output_dir`ì ì ìŒí íì ë§€ê°ëłìëĄ, ëȘšëžì ì ì„í ììč넌 ì§ì í©ëë€. (뚌ì Hugging Faceì ëĄê·žìž íì) `push_to_hub=True`ëĄ ì€ì íìŹ ìŽ ëȘšëžì íëžì ì
ëĄëí ì ìì”ëë€.
+2. íë š ìžì넌 [`Trainer`]ì ëȘšëž, ë°ìŽí° ìžíž ë° ë°ìŽí° ìœë ìŽí°ì íšê» ì ëŹíìžì.
+3. [`~Trainer.train`]ì ížì¶íìŹ ëȘšëžì ëŻžìž ìĄ°ì íìžì.
+
+```py
+>>> training_args = TrainingArguments(
+... output_dir="my_awesome_eli5_clm-model",
+... evaluation_strategy="epoch",
+... learning_rate=2e-5,
+... weight_decay=0.01,
+... push_to_hub=True,
+... )
+
+>>> trainer = Trainer(
+... model=model,
+... args=training_args,
+... train_dataset=lm_dataset["train"],
+... eval_dataset=lm_dataset["test"],
+... data_collator=data_collator,
+... )
+
+>>> trainer.train()
+```
+
+íë šìŽ ìëŁë멎 [`~transformers.Trainer.evaluate`] ë©ìë넌 ìŹì©íìŹ ëȘšëžì íê°íêł íŒíë ìí°ë„Œ ì»ì ì ìì”ëë€:
+
+```py
+>>> import math
+
+>>> eval_results = trainer.evaluate()
+>>> print(f"Perplexity: {math.exp(eval_results['eval_loss']):.2f}")
+Perplexity: 49.61
+```
+
+ê·žë° ë€ì [`~transformers.Trainer.push_to_hub`] ë©ìë넌 ìŹì©íìŹ ëȘšëžì íëžì êł”ì íìžì. ìŽë êČ í멎 ëê”Źë ëȘšëžì ìŹì©í ì ìì”ëë€:
+
+```py
+>>> trainer.push_to_hub()
+```
+
+
+
+
+Keras넌 ìŹì©íìŹ ëȘšëžì ëŻžìž ìĄ°ì íë ë°©ëČì ì”ìíì§ ìë€ë©Ž [êž°ëłž íí 늏ìŒ](../training#train-a-tensorflow-model-with-keras)ì íìžíŽëłŽìžì!
+
+
+TensorFlowìì ëȘšëžì ëŻžìž ìĄ°ì íë €ë©Ž, 뚌ì ì”í°ë§ìŽì íšì, íì”ë„ ì€ìŒì€ ë° ìŒë¶ íë š íìŽíŒíëŒëŻží°ë„Œ ì€ì íìžì:
+
+```py
+>>> from transformers import create_optimizer, AdamWeightDecay
+
+>>> optimizer = AdamWeightDecay(learning_rate=2e-5, weight_decay_rate=0.01)
+```
+
+ê·žë° ë€ì [`TFAutoModelForCausalLM`]넌 ìŹì©íìŹ DistilGPT2넌 ë¶ëŹì”ëë€:
+
+```py
+>>> from transformers import TFAutoModelForCausalLM
+
+>>> model = TFAutoModelForCausalLM.from_pretrained("distilgpt2")
+```
+
+[`~transformers.TFPreTrainedModel.prepare_tf_dataset`]ì ìŹì©íìŹ ë°ìŽí° ìžížë„Œ `tf.data.Dataset` íììŒëĄ ëłííìžì:
+
+```py
+>>> tf_train_set = model.prepare_tf_dataset(
+... lm_dataset["train"],
+... shuffle=True,
+... batch_size=16,
+... collate_fn=data_collator,
+... )
+
+>>> tf_test_set = model.prepare_tf_dataset(
+... lm_dataset["test"],
+... shuffle=False,
+... batch_size=16,
+... collate_fn=data_collator,
+... )
+```
+
+[`compile`](https://keras.io/api/models/model_training_apis/#compile-method)ì ìŹì©íìŹ ëȘšëžì íë šíêž° ìíŽ ê”Źì±íìžì. Transformers ëȘšëžì ëȘšë êž°ëłžì ìž ìì
êŽë š ìì€ íšì넌 ê°ì§êł ììŒëŻëĄ, ìíë€ë©Ž ëłëëĄ ì§ì íì§ ììë ë©ëë€:
+
+```py
+>>> import tensorflow as tf
+
+>>> model.compile(optimizer=optimizer) # ëłëëĄ loss ìžì넌 ëŁì§ ìììŽì!
+```
+
+[`~transformers.PushToHubCallback`]ìì ëȘšëžêłŒ í íŹëìŽì 넌 ì
ëĄëí ììč넌 ì§ì í ì ìì”ëë€:
+
+```py
+>>> from transformers.keras_callbacks import PushToHubCallback
+
+>>> callback = PushToHubCallback(
+... output_dir="my_awesome_eli5_clm-model",
+... tokenizer=tokenizer,
+... )
+```
+
+ë§ì§ë§ìŒëĄ, ëȘšëžì íë šíêž° ìíŽ [`fit`](https://keras.io/api/models/model_training_apis/#fit-method)ì ížì¶íìžì. íë š ë°ìŽí° ìžíž, êČìŠ ë°ìŽí° ìžíž, ìí ì ë° ìœë°±ì ì ëŹíìžì:
+
+```py
+>>> model.fit(x=tf_train_set, validation_data=tf_test_set, epochs=3, callbacks=[callback])
+```
+
+íë šìŽ ìëŁë멎 ëȘšëžìŽ ìëìŒëĄ íëžì ì
ëĄëëìŽ ëȘšëê° ìŹì©í ì ìì”ëë€!
+
+
+
+
+
+ìžêłŒ ìžìŽ ëȘšëžë§ì ìíŽ ëȘšëžì ëŻžìž ìĄ°ì íë ë ììží ìì ë íŽëčíë [PyTorch ë
žížë¶](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling.ipynb) ëë [TensorFlow ë
žížë¶](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling-tf.ipynb)ì ì°žìĄ°íìžì.
+
+
+
+## ì¶ëĄ [[inference]]
+
+ìąìì, ìŽì ëȘšëžì ëŻžìž ìĄ°ì íìŒëŻëĄ ì¶ëĄ ì ìŹì©í ì ìì”ëë€!
+
+ìì±í í
ì€ížë„Œ ìí í륏íížë„Œ ë§ë€ìŽëłŽìžì:
+
+```py
+>>> prompt = "Somatic hypermutation allows the immune system to"
+```
+
+ì¶ëĄ ì ìíŽ ëŻžìž ìĄ°ì ë ëȘšëžì ê°ëší ìŹì©íë ê°ì„ ê°ëší ë°©ëČì [`pipeline`]ìì ìŹì©íë êČì
ëë€. ëȘšëžêłŒ íšê» í
ì€íž ìì±ì ìí `pipeline`ì ìžì€íŽì€ííêł í
ì€ížë„Œ ì ëŹíìžì:
+
+```py
+>>> from transformers import pipeline
+
+>>> generator = pipeline("text-generation", model="my_awesome_eli5_clm-model")
+>>> generator(prompt)
+[{'generated_text': "Somatic hypermutation allows the immune system to be able to effectively reverse the damage caused by an infection.\n\n\nThe damage caused by an infection is caused by the immune system's ability to perform its own self-correcting tasks."}]
+```
+
+
+
+í
ì€ížë„Œ í í°ííêł `input_ids`넌 PyTorch í
ìëĄ ë°ííìžì:
+
+```py
+>>> from transformers import AutoTokenizer
+
+>>> tokenizer = AutoTokenizer.from_pretrained("my_awesome_eli5_clm-model")
+>>> inputs = tokenizer(prompt, return_tensors="pt").input_ids
+```
+
+[`~transformers.generation_utils.GenerationMixin.generate`] ë©ìë넌 ìŹì©íìŹ í
ì€ížë„Œ ìì±íìžì. ìì±ì ì ìŽíë ë€ìí í
ì€íž ìì± ì ë”êłŒ ë§€ê°ëłìì ëí ììží ëŽì©ì [í
ì€íž ìì± ì ë”](../generation_strategies) íìŽì§ë„Œ íìžíìžì.
+
+```py
+>>> from transformers import AutoModelForCausalLM
+
+>>> model = AutoModelForCausalLM.from_pretrained("my_awesome_eli5_clm-model")
+>>> outputs = model.generate(inputs, max_new_tokens=100, do_sample=True, top_k=50, top_p=0.95)
+```
+
+ìì±ë í í° ID넌 ë€ì í
ì€ížëĄ ëìœë©íìžì:
+
+```py
+>>> tokenizer.batch_decode(outputs, skip_special_tokens=True)
+["Somatic hypermutation allows the immune system to react to drugs with the ability to adapt to a different environmental situation. In other words, a system of 'hypermutation' can help the immune system to adapt to a different environmental situation or in some cases even a single life. In contrast, researchers at the University of Massachusetts-Boston have found that 'hypermutation' is much stronger in mice than in humans but can be found in humans, and that it's not completely unknown to the immune system. A study on how the immune system"]
+```
+
+
+í
ì€ížë„Œ í í°ííêł `input_ids`넌 TensorFlow í
ìëĄ ë°ííìžì:
+
+```py
+>>> from transformers import AutoTokenizer
+
+>>> tokenizer = AutoTokenizer.from_pretrained("my_awesome_eli5_clm-model")
+>>> inputs = tokenizer(prompt, return_tensors="tf").input_ids
+```
+
+[`~transformers.generation_tf_utils.TFGenerationMixin.generate`] ë©ìë넌 ìŹì©íìŹ ììœì ìì±íìžì. ìì±ì ì ìŽíë ë€ìí í
ì€íž ìì± ì ë”êłŒ ë§€ê°ëłìì ëí ììží ëŽì©ì [í
ì€íž ìì± ì ë”](../generation_strategies) íìŽì§ë„Œ íìžíìžì.
+
+```py
+>>> from transformers import TFAutoModelForCausalLM
+
+>>> model = TFAutoModelForCausalLM.from_pretrained("my_awesome_eli5_clm-model")
+>>> outputs = model.generate(input_ids=inputs, max_new_tokens=100, do_sample=True, top_k=50, top_p=0.95)
+```
+
+ìì±ë í í° ID넌 ë€ì í
ì€ížëĄ ëìœë©íìžì:
+
+```py
+>>> tokenizer.batch_decode(outputs, skip_special_tokens=True)
+['Somatic hypermutation allows the immune system to detect the presence of other viruses as they become more prevalent. Therefore, researchers have identified a high proportion of human viruses. The proportion of virus-associated viruses in our study increases with age. Therefore, we propose a simple algorithm to detect the presence of these new viruses in our samples as a sign of improved immunity. A first study based on this algorithm, which will be published in Science on Friday, aims to show that this finding could translate into the development of a better vaccine that is more effective for']
+```
+
+
diff --git a/docs/source/ko/tasks/masked_language_modeling.md b/docs/source/ko/tasks/masked_language_modeling.md
new file mode 100644
index 000000000000..d22d439dbd51
--- /dev/null
+++ b/docs/source/ko/tasks/masked_language_modeling.md
@@ -0,0 +1,448 @@
+
+
+# ë§ì€íčë ìžìŽ ëȘšëžë§(Masked language modeling)[[masked-language-modeling]]
+
+[[open-in-colab]]
+
+
+
+ë§ì€íčë ìžìŽ ëȘšëžë§ì ìíì€ìì ë§ì€íčë í í°ì ììžĄíë©°, ëȘšëžì ìë°©í„ìŒëĄ í í°ì ìĄìžì€í ì ìì”ëë€.
+ìŠ, ëȘšëžì í í°ì ìŒìȘœêłŒ ì€ë„žìȘœ ììȘœìì ì ê·Œí ì ìì”ëë€.
+ë§ì€íčë ìžìŽ ëȘšëžë§ì ì ìČŽ ìíì€ì ëí 돞맄ì ìŽíŽê° íìí ìì
ì ì í©íë©°, BERTê° ê·ž ìì íŽëčí©ëë€.
+
+ìŽëČ ê°ìŽëìì ë€ëٰ ëŽì©ì ë€ìêłŒ ê°ì”ëë€:
+
+1. [ELI5](https://huggingface.co/datasets/eli5) ë°ìŽí° ìžížìì [r/askscience](https://www.reddit.com/r/askscience/) ë¶ë¶ì ìŹì©íŽ [DistilRoBERTa](https://huggingface.co/distilroberta-base) ëȘšëžì ëŻžìž ìĄ°ì í©ëë€.
+2. ì¶ëĄ ìì ì§ì ëŻžìž ìĄ°ì í ëȘšëžì ìŹì©í©ëë€.
+
+
+ìŽëČ ê°ìŽëìììČëŒ ë€ë„ž ìí€í
ìČ넌 ëŻžìž ìĄ°ì íŽ ë§ì€íčë ìžìŽ ëȘšëžë§ì í ì ìì”ëë€.
+
+ë€ì ìí€í
ìł ì€ íë넌 ì ííìžì:
+
+
+
+[ALBERT](../model_doc/albert), [BART](../model_doc/bart), [BERT](../model_doc/bert), [BigBird](../model_doc/big_bird), [CamemBERT](../model_doc/camembert), [ConvBERT](../model_doc/convbert), [Data2VecText](../model_doc/data2vec-text), [DeBERTa](../model_doc/deberta), [DeBERTa-v2](../model_doc/deberta-v2), [DistilBERT](../model_doc/distilbert), [ELECTRA](../model_doc/electra), [ERNIE](../model_doc/ernie), [ESM](../model_doc/esm), [FlauBERT](../model_doc/flaubert), [FNet](../model_doc/fnet), [Funnel Transformer](../model_doc/funnel), [I-BERT](../model_doc/ibert), [LayoutLM](../model_doc/layoutlm), [Longformer](../model_doc/longformer), [LUKE](../model_doc/luke), [mBART](../model_doc/mbart), [MEGA](../model_doc/mega), [Megatron-BERT](../model_doc/megatron-bert), [MobileBERT](../model_doc/mobilebert), [MPNet](../model_doc/mpnet), [MVP](../model_doc/mvp), [Nezha](../model_doc/nezha), [Nyströmformer](../model_doc/nystromformer), [Perceiver](../model_doc/perceiver), [QDQBert](../model_doc/qdqbert), [Reformer](../model_doc/reformer), [RemBERT](../model_doc/rembert), [RoBERTa](../model_doc/roberta), [RoBERTa-PreLayerNorm](../model_doc/roberta-prelayernorm), [RoCBert](../model_doc/roc_bert), [RoFormer](../model_doc/roformer), [SqueezeBERT](../model_doc/squeezebert), [TAPAS](../model_doc/tapas), [Wav2Vec2](../model_doc/wav2vec2), [XLM](../model_doc/xlm), [XLM-RoBERTa](../model_doc/xlm-roberta), [XLM-RoBERTa-XL](../model_doc/xlm-roberta-xl), [X-MOD](../model_doc/xmod), [YOSO](../model_doc/yoso)
+
+
+
+
+
+ììíêž° ì ì íìí ëŒìŽëžëŹëŠŹê° ëȘšë ì€ìčëìŽ ìëì§ íìžíìžì:
+
+```bash
+pip install transformers datasets evaluate
+```
+
+Hugging Face êłì ì ëĄê·žìžíìŹ ëȘšëžì ì
ëĄëíêł ì»€ëź€ëí°ìì êł”ì 넌 ê¶ì„í©ëë€. ë©ìì§ê° íìë멎(When prompted) í í°ì ì
ë „íìŹ ëĄê·žìží©ëë€:
+
+```py
+>>> from huggingface_hub import notebook_login
+
+>>> notebook_login()
+```
+
+## ELI5 ë°ìŽí° ìžíž ê°ì žì€êž°[[load-eli5-dataset]]
+
+뚌ì đ€ Datasets ëŒìŽëžëŹëŠŹìì ELI5 ë°ìŽí° ìžížì r/askscience ì€ ìŒë¶ë§ ê°ì žì”ëë€.
+ìŽë êČ í멎 ì ìČŽ ë°ìŽí° ìžíž íì”ì ë ë§ì ìê°ì í ì íêž° ì ì ëȘšë êČìŽ ìëíëì§ ì€ííêł íìží ì ìì”ëë€.
+
+```py
+>>> from datasets import load_dataset
+
+>>> eli5 = load_dataset("eli5", split="train_asks[:5000]")
+```
+
+ë°ìŽí° ìžížì `train_asks`넌 [`~datasets.Dataset.train_test_split`] ë©ìë넌 ìŹì©íŽ íë š ë°ìŽí°ì í
ì€íž ë°ìŽí°ëĄ ë¶í í©ëë€:
+
+```py
+>>> eli5 = eli5.train_test_split(test_size=0.2)
+```
+
+ê·žëŠŹêł ìë ìì넌 ìŽíŽëłŽìžì:
+
+```py
+>>> eli5["train"][0]
+{'answers': {'a_id': ['c3d1aib', 'c3d4lya'],
+ 'score': [6, 3],
+ 'text': ["The velocity needed to remain in orbit is equal to the square root of Newton's constant times the mass of earth divided by the distance from the center of the earth. I don't know the altitude of that specific mission, but they're usually around 300 km. That means he's going 7-8 km/s.\n\nIn space there are no other forces acting on either the shuttle or the guy, so they stay in the same position relative to each other. If he were to become unable to return to the ship, he would presumably run out of oxygen, or slowly fall into the atmosphere and burn up.",
+ "Hope you don't mind me asking another question, but why aren't there any stars visible in this photo?"]},
+ 'answers_urls': {'url': []},
+ 'document': '',
+ 'q_id': 'nyxfp',
+ 'selftext': '_URL_0_\n\nThis was on the front page earlier and I have a few questions about it. Is it possible to calculate how fast the astronaut would be orbiting the earth? Also how does he stay close to the shuttle so that he can return safely, i.e is he orbiting at the same speed and can therefore stay next to it? And finally if his propulsion system failed, would he eventually re-enter the atmosphere and presumably die?',
+ 'selftext_urls': {'url': ['http://apod.nasa.gov/apod/image/1201/freeflyer_nasa_3000.jpg']},
+ 'subreddit': 'askscience',
+ 'title': 'Few questions about this space walk photograph.',
+ 'title_urls': {'url': []}}
+```
+
+ë§ì ëłŽìŒ ì ìì§ë§ ì€ì ëĄë `text` íëìë§ ì§ì€í멎 ë©ëë€.
+ìžìŽ ëȘšëžë§ ìì
ì ë©ì§ ì ì (ëčì§ë íì”ìŒëĄ) *ë€ì ëšìŽê° ë ìŽëž*ìŽêž° ë돞ì ë ìŽëžìŽ ë°ëĄ íìíì§ ìì”ëë€.
+
+## ì ìČ늏[[preprocess]]
+
+
+
+ë§ì€íčë ìžìŽ ëȘšëžë§ì ìíŽ, ë€ì ëšêłëĄ DistilRoBERTa í íŹëìŽì 넌 ê°ì žìì `text` íì íë넌 ìČ늏í©ëë€:
+
+```py
+>>> from transformers import AutoTokenizer
+
+>>> tokenizer = AutoTokenizer.from_pretrained("distilroberta-base")
+```
+
+ìì ìì ììì ë§ì°Źê°ì§ëĄ, `text` íëë `answers` ìì ì€ìČ©ëìŽ ìì”ëë€.
+ë°ëŒì ì€ìČ©ë ê”ŹìĄ°ìì [`flatten`](https://huggingface.co/docs/datasets/process.html#flatten) ë©ìë넌 ìŹì©íìŹ `text` íì íë넌 ì¶ì¶í©ëë€:
+
+```py
+>>> eli5 = eli5.flatten()
+>>> eli5["train"][0]
+{'answers.a_id': ['c3d1aib', 'c3d4lya'],
+ 'answers.score': [6, 3],
+ 'answers.text': ["The velocity needed to remain in orbit is equal to the square root of Newton's constant times the mass of earth divided by the distance from the center of the earth. I don't know the altitude of that specific mission, but they're usually around 300 km. That means he's going 7-8 km/s.\n\nIn space there are no other forces acting on either the shuttle or the guy, so they stay in the same position relative to each other. If he were to become unable to return to the ship, he would presumably run out of oxygen, or slowly fall into the atmosphere and burn up.",
+ "Hope you don't mind me asking another question, but why aren't there any stars visible in this photo?"],
+ 'answers_urls.url': [],
+ 'document': '',
+ 'q_id': 'nyxfp',
+ 'selftext': '_URL_0_\n\nThis was on the front page earlier and I have a few questions about it. Is it possible to calculate how fast the astronaut would be orbiting the earth? Also how does he stay close to the shuttle so that he can return safely, i.e is he orbiting at the same speed and can therefore stay next to it? And finally if his propulsion system failed, would he eventually re-enter the atmosphere and presumably die?',
+ 'selftext_urls.url': ['http://apod.nasa.gov/apod/image/1201/freeflyer_nasa_3000.jpg'],
+ 'subreddit': 'askscience',
+ 'title': 'Few questions about this space walk photograph.',
+ 'title_urls.url': []}
+```
+
+ìŽì ê° íì íëë `answers` ì ëìŹ(prefix)ëĄ íìë ëëĄ ëłëì ìŽìŽ ëêł , `text` íëë ìŽì 늏ì€ížê° ëìì”ëë€.
+ê° ëŹžì„ì ê°ëłì ìŒëĄ í í°ííë ëì 늏ì€ížë„Œ 돞ììŽëĄ ëłííìŹ íëČì í í°íí ì ìì”ëë€.
+
+ë€ìì ê° ìì ì ëíŽ ëŹžììŽëĄ ìŽëŁšìŽì§ 늏ì€ížë„Œ `join`íêł êČ°êłŒë„Œ í í°ííë ìČ« ëČì§ž ì ìČ늏 íšìì
ëë€:
+
+```py
+>>> def preprocess_function(examples):
+... return tokenizer([" ".join(x) for x in examples["answers.text"]])
+```
+
+ìŽ ì ìČ늏 íšì넌 ì ìČŽ ë°ìŽí° ìžížì ì ì©íêž° ìíŽ đ€ Datasets [`~datasets.Dataset.map`] ë©ìë넌 ìŹì©í©ëë€.
+ë°ìŽí° ìžížì ìŹëŹ ìì넌 í ëČì ìČ늏íëëĄ `batched=True`넌 ì€ì íêł `num_proc`ëĄ ìČ늏 íì넌 ë늏멎 `map` íšìì ìë넌 ëìŒ ì ìì”ëë€.
+íìíì§ ìì ìŽì ì ê±°í©ëë€:
+
+```py
+>>> tokenized_eli5 = eli5.map(
+... preprocess_function,
+... batched=True,
+... num_proc=4,
+... remove_columns=eli5["train"].column_names,
+... )
+```
+
+ìŽ ë°ìŽí° ìžížìë í í° ìíì€ê° íŹíšëìŽ ìì§ë§ ìŽ ì€ ìŒë¶ë ëȘšëžì ì”ë ì
ë „ êžžìŽëłŽë€ êčëë€.
+
+ìŽì ë ëČì§ž ì ìČ늏 íšì넌 ìŹì©íŽ
+- ëȘšë ìíì€ë„Œ ì°êȰíêł
+- ì°êȰë ìíì€ë„Œ ì ìí `block_size` ëłŽë€ ë ì§§ì ë©ìŽëŠŹëĄ ë¶í íëë°, ìŽ ë©ìŽëŠŹë ëȘšëžì ì”ë ì
ë „ êžžìŽëłŽë€ ì§§êł GPU RAMìŽ ìì©í ì ìë êžžìŽìŹìŒ í©ëë€.
+
+
+```py
+>>> block_size = 128
+
+
+>>> def group_texts(examples):
+... # Concatenate all texts.
+... concatenated_examples = {k: sum(examples[k], []) for k in examples.keys()}
+... total_length = len(concatenated_examples[list(examples.keys())[0]])
+... # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can
+... # customize this part to your needs.
+... if total_length >= block_size:
+... total_length = (total_length // block_size) * block_size
+... # Split by chunks of block_size.
+... result = {
+... k: [t[i : i + block_size] for i in range(0, total_length, block_size)]
+... for k, t in concatenated_examples.items()
+... }
+... result["labels"] = result["input_ids"].copy()
+... return result
+```
+
+ì ìČŽ ë°ìŽí° ìžížì `group_texts` íšì넌 ì ì©í©ëë€:
+
+```py
+>>> lm_dataset = tokenized_eli5.map(group_texts, batched=True, num_proc=4)
+```
+
+ìŽì [`DataCollatorForLanguageModeling`]ì ìŹì©íìŹ ë°ìŽí° ìì ì ë°°ìč넌 ìì±í©ëë€.
+ë°ìŽí° ìžíž ì ìČŽë„Œ ì”ë êžžìŽëĄ íšë©íë êČëłŽë€ collation ëšêłìì ë§€ ë°°ìčìììì ì”ë êžžìŽëĄ 돞ì„ì *ëì ìŒëĄ íšë©*íë êČìŽ ë íšìšì ì
ëë€.
+
+
+
+
+ìíì€ ë í í°ì íšë© í í°ìŒëĄ ìŹì©íêł ë°ìŽí°ë„Œ ë°ëł”í ëë§ë€ í í°ì 돎ììëĄ ë§ì€íčíëëĄ `mlm_-probability`넌 ì§ì í©ëë€:
+
+```py
+>>> from transformers import DataCollatorForLanguageModeling
+
+>>> tokenizer.pad_token = tokenizer.eos_token
+>>> data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm_probability=0.15)
+```
+
+
+
+ìíì€ ë í í°ì íšë© í í°ìŒëĄ ìŹì©íêł ë°ìŽí°ë„Œ ë°ëł”í ëë§ë€ í í°ì 돎ììëĄ ë§ì€íčíëëĄ `mlm_-probability`넌 ì§ì í©ëë€:
+
+```py
+>>> from transformers import DataCollatorForLanguageModeling
+
+>>> data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm_probability=0.15, return_tensors="tf")
+```
+
+
+
+## íë š[[train]]
+
+
+
+
+
+[`Trainer`]ëĄ ëȘšëžì ëŻžìž ìĄ°ì íë ë° ì”ìíì§ ìë€ë©Ž êž°ëłž íí ëŠŹìŒ [ìŹêž°](../training#train-with-pytorch-trainer)넌 ìŽíŽëłŽìžì!
+
+
+ìŽì ëȘšëž íë šì ììí ì€ëčê° ëìì”ëë€! [`AutoModelForMaskedLM`]넌 ìŹì©íŽ DistilRoBERTa ëȘšëžì ê°ì žì”ëë€:
+
+```py
+>>> from transformers import AutoModelForMaskedLM
+
+>>> model = AutoModelForMaskedLM.from_pretrained("distilroberta-base")
+```
+
+ìŽì ìž ëšêłê° ëšìì”ëë€:
+
+1. [`TrainingArguments`]ì íë š íìŽíŒíëŒëŻží°ë„Œ ì ìí©ëë€. ëȘšëž ì ì„ ììč넌 ì§ì íë `output_dir`ì ì ìŒí íì íëŒëŻží°ì
ëë€. `push_to_hub=True`넌 ì€ì íìŹ ìŽ ëȘšëžì Hubì ì
ëĄëí©ëë€ (ëȘšëžì ì
ëĄëíë €ë©Ž Hugging Faceì ëĄê·žìžíŽìŒ í©ëë€).
+2. ëȘšëž, ë°ìŽí° ìžíž ë° ë°ìŽí° ìœë ìŽí°(collator)ì íšê» íë š ìžì넌 [`Trainer`]ì ì ëŹí©ëë€.
+3. [`~Trainer.train`]ì ížì¶íìŹ ëȘšëžì ëŻžìž ìĄ°ì í©ëë€.
+
+```py
+>>> training_args = TrainingArguments(
+... output_dir="my_awesome_eli5_mlm_model",
+... evaluation_strategy="epoch",
+... learning_rate=2e-5,
+... num_train_epochs=3,
+... weight_decay=0.01,
+... push_to_hub=True,
+... )
+
+>>> trainer = Trainer(
+... model=model,
+... args=training_args,
+... train_dataset=lm_dataset["train"],
+... eval_dataset=lm_dataset["test"],
+... data_collator=data_collator,
+... )
+
+>>> trainer.train()
+```
+
+íë šìŽ ìëŁë멎 [`~transformers.Trainer.evaluate`] ë©ìë넌 ìŹì©íìŹ ííë ìí°(perplexity)넌 êłì°íêł ëȘšëžì íê°í©ëë€:
+
+```py
+>>> import math
+
+>>> eval_results = trainer.evaluate()
+>>> print(f"Perplexity: {math.exp(eval_results['eval_loss']):.2f}")
+Perplexity: 8.76
+```
+
+ê·žëŠŹêł [`~transformers.Trainer.push_to_hub`] ë©ìë넌 ìŹì©íŽ ë€ë„ž ìŹëë€ìŽ ìŹì©í ì ìëëĄ, HubëĄ ëȘšëžì ì
ëĄëí©ëë€.
+
+```py
+>>> trainer.push_to_hub()
+```
+
+
+
+
+KerasëĄ ëȘšëžì ëŻžìž ìĄ°ì íë ë° ì”ìíì§ ìë€ë©Ž êž°ëłž íí ëŠŹìŒ [ìŹêž°](../training#train-a-tensorflow-model-with-keras)넌 ìŽíŽëłŽìžì!
+
+
+TensorFlowëĄ ëȘšëžì ëŻžìž ìĄ°ì íêž° ìíŽìë ì”í°ë§ìŽì (optimizer) íšì ì€ì , íì”ë„ (learning rate) ì€ìŒì„Žë§, íë š íìŽíŒíëŒëŻží° ì€ì ë¶í° ììíìžì:
+
+```py
+>>> from transformers import create_optimizer, AdamWeightDecay
+
+>>> optimizer = AdamWeightDecay(learning_rate=2e-5, weight_decay_rate=0.01)
+```
+
+ë€ììŒëĄ [`TFAutoModelForMaskedLM`]넌 ìŹì©íŽ DistilRoBERTa ëȘšëžì ê°ì žì”ëë€:
+
+```py
+>>> from transformers import TFAutoModelForMaskedLM
+
+>>> model = TFAutoModelForMaskedLM.from_pretrained("distilroberta-base")
+```
+
+[`~transformers.TFPreTrainedModel.prepare_tf_dataset`] ë©ìë넌 ìŹì©íŽ ë°ìŽí° ìžížë„Œ `tf.data.Dataset` íììŒëĄ ëłííìžì:
+
+```py
+>>> tf_train_set = model.prepare_tf_dataset(
+... lm_dataset["train"],
+... shuffle=True,
+... batch_size=16,
+... collate_fn=data_collator,
+... )
+
+>>> tf_test_set = model.prepare_tf_dataset(
+... lm_dataset["test"],
+... shuffle=False,
+... batch_size=16,
+... collate_fn=data_collator,
+... )
+```
+
+[`compile`](https://keras.io/api/models/model_training_apis/#compile-method) ë©ìë넌 í”íŽ ëȘšëž íë šì ê”Źì±í©ëë€:
+
+```py
+>>> import tensorflow as tf
+
+>>> model.compile(optimizer=optimizer)
+```
+
+ìŽë ì
ëĄëí ëȘšëžêłŒ í íŹëìŽì ì ììč넌 [`~transformers.PushToHubCallback`]ì ì§ì íìŹ ìíí ì ìì”ëë€:
+
+```py
+>>> from transformers.keras_callbacks import PushToHubCallback
+
+>>> callback = PushToHubCallback(
+... output_dir="my_awesome_eli5_mlm_model",
+... tokenizer=tokenizer,
+... )
+```
+
+ëëìŽ ëȘšëžì íë ší ì€ëčê° ëìì”ëë€!
+ëȘšëžì ëŻžìž ìĄ°ì í ë íë š ë° êČìŠ ë°ìŽí° ìžíž, ìíŹíŹ ì, ìœë°±ìŽ íŹíšë [`fit`](https://keras.io/api/models/model_training_apis/#fit-method)ì ížì¶í©ëë€:
+
+```py
+>>> model.fit(x=tf_train_set, validation_data=tf_test_set, epochs=3, callbacks=[callback])
+```
+
+íë šìŽ ìëŁë멎, ìëìŒëĄ HubëĄ ì
ëĄëëìŽ ëê”Źë ìŹì©í ì ìì”ëë€!
+
+
+
+
+
+ë§ì€íčë ìžìŽ ëȘšëžë§ì ìíŽ ëȘšëžì ëŻžìž ìĄ°ì íë ë°©ëČì ëí ëłŽë€ ìŹìž”ì ìž ìì ë
+[PyTorch notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling.ipynb)
+ëë [TensorFlow notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling-tf.ipynb)ì ì°žìĄ°íìžì.
+
+
+## ì¶ëĄ [[inference]]
+
+ì§êžêčì§ ëȘšëž ëŻžìž ìĄ°ì ì ì íìŒë, ì¶ëĄ ì ìŹì©í ì ìì”ëë€!
+
+ëȘšëžìŽ ëčìčžì ì±ìž í
ì€ížë„Œ ì€íì
í í°(special token)ìž `` í í°ìŒëĄ íìí©ëë€:
+
+
+```py
+>>> text = "The Milky Way is a galaxy."
+```
+ì¶ëĄ ì ìíŽ ëŻžìž ìĄ°ì í ëȘšëžì í
ì€ížíë ê°ì„ ê°ëší ë°©ëČì [`pipeline`]ìì ìŹì©íë êČì
ëë€.
+`fill-mask`íì€íŹëĄ `pipeline`ì ìžì€íŽì€ííêł í
ì€ížë„Œ ì ëŹí©ëë€.
+`top_k` ë§€ê°ëłì넌 ìŹì©íìŹ ë°ííë ììžĄì ì넌 ì§ì í ì ìì”ëë€:
+
+```py
+>>> from transformers import pipeline
+
+>>> mask_filler = pipeline("fill-mask", "stevhliu/my_awesome_eli5_mlm_model")
+>>> mask_filler(text, top_k=3)
+[{'score': 0.5150994658470154,
+ 'token': 21300,
+ 'token_str': ' spiral',
+ 'sequence': 'The Milky Way is a spiral galaxy.'},
+ {'score': 0.07087188959121704,
+ 'token': 2232,
+ 'token_str': ' massive',
+ 'sequence': 'The Milky Way is a massive galaxy.'},
+ {'score': 0.06434620916843414,
+ 'token': 650,
+ 'token_str': ' small',
+ 'sequence': 'The Milky Way is a small galaxy.'}]
+```
+
+
+
+í
ì€ížë„Œ í í°ííêł `input_ids`넌 PyTorch í
ì ííëĄ ë°íí©ëë€.
+ëí, `` í í°ì ììč넌 ì§ì íŽìŒ í©ëë€:
+```py
+>>> from transformers import AutoTokenizer
+
+>>> tokenizer = AutoTokenizer.from_pretrained("my_awesome_eli5_mlm_model")
+>>> inputs = tokenizer(text, return_tensors="pt")
+>>> mask_token_index = torch.where(inputs["input_ids"] == tokenizer.mask_token_id)[1]
+```
+
+ëȘšëžì `inputs`넌 ì
ë „íêł , ë§ì€íčë í í°ì `logits`넌 ë°íí©ëë€:
+
+```py
+>>> from transformers import AutoModelForMaskedLM
+
+>>> model = AutoModelForMaskedLM.from_pretrained("stevhliu/my_awesome_eli5_mlm_model")
+>>> logits = model(**inputs).logits
+>>> mask_token_logits = logits[0, mask_token_index, :]
+```
+
+ê·žë° ë€ì ê°ì„ ëì íë„ ì ê°ì§ ë§ì€íŹ í í° 3ê°ë„Œ ë°ííêł , ì¶ë „í©ëë€:
+```py
+>>> top_3_tokens = torch.topk(mask_token_logits, 3, dim=1).indices[0].tolist()
+
+>>> for token in top_3_tokens:
+... print(text.replace(tokenizer.mask_token, tokenizer.decode([token])))
+The Milky Way is a spiral galaxy.
+The Milky Way is a massive galaxy.
+The Milky Way is a small galaxy.
+```
+
+
+í
ì€ížë„Œ í í°ííêł `input_ids`넌 TensorFlow í
ì ííëĄ ë°íí©ëë€.
+ëí, `` í í°ì ììč넌 ì§ì íŽìŒ í©ëë€:
+```py
+>>> from transformers import AutoTokenizer
+
+>>> tokenizer = AutoTokenizer.from_pretrained("my_awesome_eli5_mlm_model")
+>>> inputs = tokenizer(text, return_tensors="tf")
+>>> mask_token_index = tf.where(inputs["input_ids"] == tokenizer.mask_token_id)[0, 1]
+```
+
+ëȘšëžì `inputs`넌 ì
ë „íêł , ë§ì€íčë í í°ì `logits`넌 ë°íí©ëë€:
+
+```py
+>>> from transformers import TFAutoModelForMaskedLM
+
+>>> model = TFAutoModelForMaskedLM.from_pretrained("stevhliu/my_awesome_eli5_mlm_model")
+>>> logits = model(**inputs).logits
+>>> mask_token_logits = logits[0, mask_token_index, :]
+```
+
+ê·žë° ë€ì ê°ì„ ëì íë„ ì ê°ì§ ë§ì€íŹ í í° 3ê°ë„Œ ë°ííêł , ì¶ë „í©ëë€:
+```py
+>>> top_3_tokens = tf.math.top_k(mask_token_logits, 3).indices.numpy()
+
+>>> for token in top_3_tokens:
+... print(text.replace(tokenizer.mask_token, tokenizer.decode([token])))
+The Milky Way is a spiral galaxy.
+The Milky Way is a massive galaxy.
+The Milky Way is a small galaxy.
+```
+
+
diff --git a/docs/source/ko/tasks/masked_language_modeling.mdx b/docs/source/ko/tasks/masked_language_modeling.mdx
deleted file mode 100644
index 9eb375d3b8fb..000000000000
--- a/docs/source/ko/tasks/masked_language_modeling.mdx
+++ /dev/null
@@ -1,444 +0,0 @@
-
-
-# ë§ì€íčë ìžìŽ ëȘšëžë§(Masked language modeling)[[masked-language-modeling]]
-
-[[open-in-colab]]
-
-
-
-ë§ì€íčë ìžìŽ ëȘšëžë§ì ìíì€ìì ë§ì€íčë í í°ì ììžĄíë©°, ëȘšëžì ìë°©í„ìŒëĄ í í°ì ìĄìžì€í ì ìì”ëë€.
-ìŠ, ëȘšëžì í í°ì ìŒìȘœêłŒ ì€ë„žìȘœ ììȘœìì ì ê·Œí ì ìì”ëë€.
-ë§ì€íčë ìžìŽ ëȘšëžë§ì ì ìČŽ ìíì€ì ëí 돞맄ì ìŽíŽê° íìí ìì
ì ì í©íë©°, BERTê° ê·ž ìì íŽëčí©ëë€.
-
-ìŽëČ ê°ìŽëìì ë€ëٰ ëŽì©ì ë€ìêłŒ ê°ì”ëë€:
-
-1. [ELI5](https://huggingface.co/datasets/eli5) ë°ìŽí° ìžížìì [r/askscience](https://www.reddit.com/r/askscience/) ë¶ë¶ì ìŹì©íŽ [DistilRoBERTa](https://huggingface.co/distilroberta-base) ëȘšëžì ëŻžìž ìĄ°ì í©ëë€.
-2. ì¶ëĄ ìì ì§ì ëŻžìž ìĄ°ì í ëȘšëžì ìŹì©í©ëë€.
-
-
-ìŽëČ ê°ìŽëìììČëŒ ë€ë„ž ìí€í
ìČ넌 ëŻžìž ìĄ°ì íŽ ë§ì€íčë ìžìŽ ëȘšëžë§ì í ì ìì”ëë€.
-
-ë€ì ìí€í
ìł ì€ íë넌 ì ííìžì:
-
-
-
-[ALBERT](../model_doc/albert), [BART](../model_doc/bart), [BERT](../model_doc/bert), [BigBird](../model_doc/big_bird), [CamemBERT](../model_doc/camembert), [ConvBERT](../model_doc/convbert), [Data2VecText](../model_doc/data2vec-text), [DeBERTa](../model_doc/deberta), [DeBERTa-v2](../model_doc/deberta-v2), [DistilBERT](../model_doc/distilbert), [ELECTRA](../model_doc/electra), [ERNIE](../model_doc/ernie), [ESM](../model_doc/esm), [FlauBERT](../model_doc/flaubert), [FNet](../model_doc/fnet), [Funnel Transformer](../model_doc/funnel), [I-BERT](../model_doc/ibert), [LayoutLM](../model_doc/layoutlm), [Longformer](../model_doc/longformer), [LUKE](../model_doc/luke), [mBART](../model_doc/mbart), [MEGA](../model_doc/mega), [Megatron-BERT](../model_doc/megatron-bert), [MobileBERT](../model_doc/mobilebert), [MPNet](../model_doc/mpnet), [MVP](../model_doc/mvp), [Nezha](../model_doc/nezha), [Nyströmformer](../model_doc/nystromformer), [Perceiver](../model_doc/perceiver), [QDQBert](../model_doc/qdqbert), [Reformer](../model_doc/reformer), [RemBERT](../model_doc/rembert), [RoBERTa](../model_doc/roberta), [RoBERTa-PreLayerNorm](../model_doc/roberta-prelayernorm), [RoCBert](../model_doc/roc_bert), [RoFormer](../model_doc/roformer), [SqueezeBERT](../model_doc/squeezebert), [TAPAS](../model_doc/tapas), [Wav2Vec2](../model_doc/wav2vec2), [XLM](../model_doc/xlm), [XLM-RoBERTa](../model_doc/xlm-roberta), [XLM-RoBERTa-XL](../model_doc/xlm-roberta-xl), [X-MOD](../model_doc/xmod), [YOSO](../model_doc/yoso)
-
-
-
-
-
-ììíêž° ì ì íìí ëŒìŽëžëŹëŠŹê° ëȘšë ì€ìčëìŽ ìëì§ íìžíìžì:
-
-```bash
-pip install transformers datasets evaluate
-```
-
-Hugging Face êłì ì ëĄê·žìžíìŹ ëȘšëžì ì
ëĄëíêł ì»€ëź€ëí°ìì êł”ì 넌 ê¶ì„í©ëë€. ë©ìì§ê° íìë멎(When prompted) í í°ì ì
ë „íìŹ ëĄê·žìží©ëë€:
-
-```py
->>> from huggingface_hub import notebook_login
-
->>> notebook_login()
-```
-
-## ELI5 ë°ìŽí° ìžíž ê°ì žì€êž°[[load-eli5-dataset]]
-
-뚌ì đ€ Datasets ëŒìŽëžëŹëŠŹìì ELI5 ë°ìŽí° ìžížì r/askscience ì€ ìŒë¶ë§ ê°ì žì”ëë€.
-ìŽë êČ í멎 ì ìČŽ ë°ìŽí° ìžíž íì”ì ë ë§ì ìê°ì í ì íêž° ì ì ëȘšë êČìŽ ìëíëì§ ì€ííêł íìží ì ìì”ëë€.
-
-```py
->>> from datasets import load_dataset
-
->>> eli5 = load_dataset("eli5", split="train_asks[:5000]")
-```
-
-ë°ìŽí° ìžížì `train_asks`넌 [`~datasets.Dataset.train_test_split`] ë©ìë넌 ìŹì©íŽ íë š ë°ìŽí°ì í
ì€íž ë°ìŽí°ëĄ ë¶í í©ëë€:
-
-```py
->>> eli5 = eli5.train_test_split(test_size=0.2)
-```
-
-ê·žëŠŹêł ìë ìì넌 ìŽíŽëłŽìžì:
-
-```py
->>> eli5["train"][0]
-{'answers': {'a_id': ['c3d1aib', 'c3d4lya'],
- 'score': [6, 3],
- 'text': ["The velocity needed to remain in orbit is equal to the square root of Newton's constant times the mass of earth divided by the distance from the center of the earth. I don't know the altitude of that specific mission, but they're usually around 300 km. That means he's going 7-8 km/s.\n\nIn space there are no other forces acting on either the shuttle or the guy, so they stay in the same position relative to each other. If he were to become unable to return to the ship, he would presumably run out of oxygen, or slowly fall into the atmosphere and burn up.",
- "Hope you don't mind me asking another question, but why aren't there any stars visible in this photo?"]},
- 'answers_urls': {'url': []},
- 'document': '',
- 'q_id': 'nyxfp',
- 'selftext': '_URL_0_\n\nThis was on the front page earlier and I have a few questions about it. Is it possible to calculate how fast the astronaut would be orbiting the earth? Also how does he stay close to the shuttle so that he can return safely, i.e is he orbiting at the same speed and can therefore stay next to it? And finally if his propulsion system failed, would he eventually re-enter the atmosphere and presumably die?',
- 'selftext_urls': {'url': ['http://apod.nasa.gov/apod/image/1201/freeflyer_nasa_3000.jpg']},
- 'subreddit': 'askscience',
- 'title': 'Few questions about this space walk photograph.',
- 'title_urls': {'url': []}}
-```
-
-ë§ì ëłŽìŒ ì ìì§ë§ ì€ì ëĄë `text` íëìë§ ì§ì€í멎 ë©ëë€.
-ìžìŽ ëȘšëžë§ ìì
ì ë©ì§ ì ì (ëčì§ë íì”ìŒëĄ) *ë€ì ëšìŽê° ë ìŽëž*ìŽêž° ë돞ì ë ìŽëžìŽ ë°ëĄ íìíì§ ìì”ëë€.
-
-## ì ìČ늏[[preprocess]]
-
-
-
-ë§ì€íčë ìžìŽ ëȘšëžë§ì ìíŽ, ë€ì ëšêłëĄ DistilRoBERTa í íŹëìŽì 넌 ê°ì žìì `text` íì íë넌 ìČ늏í©ëë€:
-
-```py
->>> from transformers import AutoTokenizer
-
->>> tokenizer = AutoTokenizer.from_pretrained("distilroberta-base")
-```
-
-ìì ìì ììì ë§ì°Źê°ì§ëĄ, `text` íëë `answers` ìì ì€ìČ©ëìŽ ìì”ëë€.
-ë°ëŒì ì€ìČ©ë ê”ŹìĄ°ìì [`flatten`](https://huggingface.co/docs/datasets/process.html#flatten) ë©ìë넌 ìŹì©íìŹ `text` íì íë넌 ì¶ì¶í©ëë€:
-
-```py
->>> eli5 = eli5.flatten()
->>> eli5["train"][0]
-{'answers.a_id': ['c3d1aib', 'c3d4lya'],
- 'answers.score': [6, 3],
- 'answers.text': ["The velocity needed to remain in orbit is equal to the square root of Newton's constant times the mass of earth divided by the distance from the center of the earth. I don't know the altitude of that specific mission, but they're usually around 300 km. That means he's going 7-8 km/s.\n\nIn space there are no other forces acting on either the shuttle or the guy, so they stay in the same position relative to each other. If he were to become unable to return to the ship, he would presumably run out of oxygen, or slowly fall into the atmosphere and burn up.",
- "Hope you don't mind me asking another question, but why aren't there any stars visible in this photo?"],
- 'answers_urls.url': [],
- 'document': '',
- 'q_id': 'nyxfp',
- 'selftext': '_URL_0_\n\nThis was on the front page earlier and I have a few questions about it. Is it possible to calculate how fast the astronaut would be orbiting the earth? Also how does he stay close to the shuttle so that he can return safely, i.e is he orbiting at the same speed and can therefore stay next to it? And finally if his propulsion system failed, would he eventually re-enter the atmosphere and presumably die?',
- 'selftext_urls.url': ['http://apod.nasa.gov/apod/image/1201/freeflyer_nasa_3000.jpg'],
- 'subreddit': 'askscience',
- 'title': 'Few questions about this space walk photograph.',
- 'title_urls.url': []}
-```
-
-ìŽì ê° íì íëë `answers` ì ëìŹ(prefix)ëĄ íìë ëëĄ ëłëì ìŽìŽ ëêł , `text` íëë ìŽì 늏ì€ížê° ëìì”ëë€.
-ê° ëŹžì„ì ê°ëłì ìŒëĄ í í°ííë ëì 늏ì€ížë„Œ 돞ììŽëĄ ëłííìŹ íëČì í í°íí ì ìì”ëë€.
-
-ë€ìì ê° ìì ì ëíŽ ëŹžììŽëĄ ìŽëŁšìŽì§ 늏ì€ížë„Œ `join`íêł êČ°êłŒë„Œ í í°ííë ìČ« ëČì§ž ì ìČ늏 íšìì
ëë€:
-
-```py
->>> def preprocess_function(examples):
-... return tokenizer([" ".join(x) for x in examples["answers.text"]])
-```
-
-ìŽ ì ìČ늏 íšì넌 ì ìČŽ ë°ìŽí° ìžížì ì ì©íêž° ìíŽ đ€ Datasets [`~datasets.Dataset.map`] ë©ìë넌 ìŹì©í©ëë€.
-ë°ìŽí° ìžížì ìŹëŹ ìì넌 í ëČì ìČ늏íëëĄ `batched=True`넌 ì€ì íêł `num_proc`ëĄ ìČ늏 íì넌 ë늏멎 `map` íšìì ìë넌 ëìŒ ì ìì”ëë€.
-íìíì§ ìì ìŽì ì ê±°í©ëë€:
-
-```py
->>> tokenized_eli5 = eli5.map(
-... preprocess_function,
-... batched=True,
-... num_proc=4,
-... remove_columns=eli5["train"].column_names,
-... )
-```
-
-ìŽ ë°ìŽí° ìžížìë í í° ìíì€ê° íŹíšëìŽ ìì§ë§ ìŽ ì€ ìŒë¶ë ëȘšëžì ì”ë ì
ë „ êžžìŽëłŽë€ êčëë€.
-
-ìŽì ë ëČì§ž ì ìČ늏 íšì넌 ìŹì©íŽ
-- ëȘšë ìíì€ë„Œ ì°êȰíêł
-- ì°êȰë ìíì€ë„Œ ì ìí `block_size` ëłŽë€ ë ì§§ì ë©ìŽëŠŹëĄ ë¶í íëë°, ìŽ ë©ìŽëŠŹë ëȘšëžì ì”ë ì
ë „ êžžìŽëłŽë€ ì§§êł GPU RAMìŽ ìì©í ì ìë êžžìŽìŹìŒ í©ëë€.
-
-
-```py
->>> block_size = 128
-
-
->>> def group_texts(examples):
-... # Concatenate all texts.
-... concatenated_examples = {k: sum(examples[k], []) for k in examples.keys()}
-... total_length = len(concatenated_examples[list(examples.keys())[0]])
-... # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can
-... # customize this part to your needs.
-... if total_length >= block_size:
-... total_length = (total_length // block_size) * block_size
-... # Split by chunks of block_size.
-... result = {
-... k: [t[i : i + block_size] for i in range(0, total_length, block_size)]
-... for k, t in concatenated_examples.items()
-... }
-... result["labels"] = result["input_ids"].copy()
-... return result
-```
-
-ì ìČŽ ë°ìŽí° ìžížì `group_texts` íšì넌 ì ì©í©ëë€:
-
-```py
->>> lm_dataset = tokenized_eli5.map(group_texts, batched=True, num_proc=4)
-```
-
-ìŽì [`DataCollatorForLanguageModeling`]ì ìŹì©íìŹ ë°ìŽí° ìì ì ë°°ìč넌 ìì±í©ëë€.
-ë°ìŽí° ìžíž ì ìČŽë„Œ ì”ë êžžìŽëĄ íšë©íë êČëłŽë€ collation ëšêłìì ë§€ ë°°ìčìììì ì”ë êžžìŽëĄ 돞ì„ì *ëì ìŒëĄ íšë©*íë êČìŽ ë íšìšì ì
ëë€.
-
-
-
-
-ìíì€ ë í í°ì íšë© í í°ìŒëĄ ìŹì©íêł ë°ìŽí°ë„Œ ë°ëł”í ëë§ë€ í í°ì 돎ììëĄ ë§ì€íčíëëĄ `mlm_-probability`넌 ì§ì í©ëë€:
-
-```py
->>> from transformers import DataCollatorForLanguageModeling
-
->>> tokenizer.pad_token = tokenizer.eos_token
->>> data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm_probability=0.15)
-```
-
-
-
-ìíì€ ë í í°ì íšë© í í°ìŒëĄ ìŹì©íêł ë°ìŽí°ë„Œ ë°ëł”í ëë§ë€ í í°ì 돎ììëĄ ë§ì€íčíëëĄ `mlm_-probability`넌 ì§ì í©ëë€:
-
-```py
->>> from transformers import DataCollatorForLanguageModeling
-
->>> data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm_probability=0.15, return_tensors="tf")
-```
-
-
-
-## íë š[[train]]
-
-
-
-
-
-[`Trainer`]ëĄ ëȘšëžì ëŻžìž ìĄ°ì íë ë° ì”ìíì§ ìë€ë©Ž êž°ëłž íí ëŠŹìŒ [ìŹêž°](../training#train-with-pytorch-trainer)넌 ìŽíŽëłŽìžì!
-
-
-ìŽì ëȘšëž íë šì ììí ì€ëčê° ëìì”ëë€! [`AutoModelForMaskedLM`]넌 ìŹì©íŽ DistilRoBERTa ëȘšëžì ê°ì žì”ëë€:
-
-```py
->>> from transformers import AutoModelForMaskedLM
-
->>> model = AutoModelForMaskedLM.from_pretrained("distilroberta-base")
-```
-
-ìŽì ìž ëšêłê° ëšìì”ëë€:
-
-1. [`TrainingArguments`]ì íë š íìŽíŒíëŒëŻží°ë„Œ ì ìí©ëë€. ëȘšëž ì ì„ ììč넌 ì§ì íë `output_dir`ì ì ìŒí íì íëŒëŻží°ì
ëë€. `push_to_hub=True`넌 ì€ì íìŹ ìŽ ëȘšëžì Hubì ì
ëĄëí©ëë€ (ëȘšëžì ì
ëĄëíë €ë©Ž Hugging Faceì ëĄê·žìžíŽìŒ í©ëë€).
-2. ëȘšëž, ë°ìŽí° ìžíž ë° ë°ìŽí° ìœë ìŽí°(collator)ì íšê» íë š ìžì넌 [`Trainer`]ì ì ëŹí©ëë€.
-3. [`~Trainer.train`]ì ížì¶íìŹ ëȘšëžì ëŻžìž ìĄ°ì í©ëë€.
-
-```py
->>> training_args = TrainingArguments(
-... output_dir="my_awesome_eli5_mlm_model",
-... evaluation_strategy="epoch",
-... learning_rate=2e-5,
-... num_train_epochs=3,
-... weight_decay=0.01,
-... push_to_hub=True,
-... )
-
->>> trainer = Trainer(
-... model=model,
-... args=training_args,
-... train_dataset=lm_dataset["train"],
-... eval_dataset=lm_dataset["test"],
-... data_collator=data_collator,
-... )
-
->>> trainer.train()
-```
-
-íë šìŽ ìëŁë멎 [`~transformers.Trainer.evaluate`] ë©ìë넌 ìŹì©íìŹ ííë ìí°(perplexity)넌 êłì°íêł ëȘšëžì íê°í©ëë€:
-
-```py
->>> import math
-
->>> eval_results = trainer.evaluate()
->>> print(f"Perplexity: {math.exp(eval_results['eval_loss']):.2f}")
-Perplexity: 8.76
-```
-
-ê·žëŠŹêł [`~transformers.Trainer.push_to_hub`] ë©ìë넌 ìŹì©íŽ ë€ë„ž ìŹëë€ìŽ ìŹì©í ì ìëëĄ, HubëĄ ëȘšëžì ì
ëĄëí©ëë€.
-
-```py
->>> trainer.push_to_hub()
-```
-
-
-
-
-KerasëĄ ëȘšëžì ëŻžìž ìĄ°ì íë ë° ì”ìíì§ ìë€ë©Ž êž°ëłž íí ëŠŹìŒ [ìŹêž°](../training#train-a-tensorflow-model-with-keras)넌 ìŽíŽëłŽìžì!
-
-
-TensorFlowëĄ ëȘšëžì ëŻžìž ìĄ°ì íêž° ìíŽìë ì”í°ë§ìŽì (optimizer) íšì ì€ì , íì”ë„ (learning rate) ì€ìŒì„Žë§, íë š íìŽíŒíëŒëŻží° ì€ì ë¶í° ììíìžì:
-
-```py
->>> from transformers import create_optimizer, AdamWeightDecay
-
->>> optimizer = AdamWeightDecay(learning_rate=2e-5, weight_decay_rate=0.01)
-```
-
-ë€ììŒëĄ [`TFAutoModelForMaskedLM`]넌 ìŹì©íŽ DistilRoBERTa ëȘšëžì ê°ì žì”ëë€:
-
-```py
->>> from transformers import TFAutoModelForMaskedLM
-
->>> model = TFAutoModelForMaskedLM.from_pretrained("distilroberta-base")
-```
-
-[`~transformers.TFPreTrainedModel.prepare_tf_dataset`] ë©ìë넌 ìŹì©íŽ ë°ìŽí° ìžížë„Œ `tf.data.Dataset` íììŒëĄ ëłííìžì:
-
-```py
->>> tf_train_set = model.prepare_tf_dataset(
-... lm_dataset["train"],
-... shuffle=True,
-... batch_size=16,
-... collate_fn=data_collator,
-... )
-
->>> tf_test_set = model.prepare_tf_dataset(
-... lm_dataset["test"],
-... shuffle=False,
-... batch_size=16,
-... collate_fn=data_collator,
-... )
-```
-
-[`compile`](https://keras.io/api/models/model_training_apis/#compile-method) ë©ìë넌 í”íŽ ëȘšëž íë šì ê”Źì±í©ëë€:
-
-```py
->>> import tensorflow as tf
-
->>> model.compile(optimizer=optimizer)
-```
-
-ìŽë ì
ëĄëí ëȘšëžêłŒ í íŹëìŽì ì ììč넌 [`~transformers.PushToHubCallback`]ì ì§ì íìŹ ìíí ì ìì”ëë€:
-
-```py
->>> from transformers.keras_callbacks import PushToHubCallback
-
->>> callback = PushToHubCallback(
-... output_dir="my_awesome_eli5_mlm_model",
-... tokenizer=tokenizer,
-... )
-```
-
-ëëìŽ ëȘšëžì íë ší ì€ëčê° ëìì”ëë€!
-ëȘšëžì ëŻžìž ìĄ°ì í ë íë š ë° êČìŠ ë°ìŽí° ìžíž, ìíŹíŹ ì, ìœë°±ìŽ íŹíšë [`fit`](https://keras.io/api/models/model_training_apis/#fit-method)ì ížì¶í©ëë€:
-
-```py
->>> model.fit(x=tf_train_set, validation_data=tf_test_set, epochs=3, callbacks=[callback])
-```
-
-íë šìŽ ìëŁë멎, ìëìŒëĄ HubëĄ ì
ëĄëëìŽ ëê”Źë ìŹì©í ì ìì”ëë€!
-
-
-
-
-
-ë§ì€íčë ìžìŽ ëȘšëžë§ì ìíŽ ëȘšëžì ëŻžìž ìĄ°ì íë ë°©ëČì ëí ëłŽë€ ìŹìž”ì ìž ìì ë
-[PyTorch notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling.ipynb)
-ëë [TensorFlow notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling-tf.ipynb)ì ì°žìĄ°íìžì.
-
-
-## ì¶ëĄ [[inference]]
-
-ì§êžêčì§ ëȘšëž ëŻžìž ìĄ°ì ì ì íìŒë, ì¶ëĄ ì ìŹì©í ì ìì”ëë€!
-
-ëȘšëžìŽ ëčìčžì ì±ìž í
ì€ížë„Œ ì€íì
í í°(special token)ìž `` í í°ìŒëĄ íìí©ëë€:
-
-
-```py
->>> text = "The Milky Way is a galaxy."
-```
-ì¶ëĄ ì ìíŽ ëŻžìž ìĄ°ì í ëȘšëžì í
ì€ížíë ê°ì„ ê°ëší ë°©ëČì [`pipeline`]ìì ìŹì©íë êČì
ëë€.
-`fill-mask`íì€íŹëĄ `pipeline`ì ìžì€íŽì€ííêł í
ì€ížë„Œ ì ëŹí©ëë€.
-`top_k` ë§€ê°ëłì넌 ìŹì©íìŹ ë°ííë ììžĄì ì넌 ì§ì í ì ìì”ëë€:
-
-```py
->>> from transformers import pipeline
-
->>> mask_filler = pipeline("fill-mask", "stevhliu/my_awesome_eli5_mlm_model")
->>> mask_filler(text, top_k=3)
-[{'score': 0.5150994658470154,
- 'token': 21300,
- 'token_str': ' spiral',
- 'sequence': 'The Milky Way is a spiral galaxy.'},
- {'score': 0.07087188959121704,
- 'token': 2232,
- 'token_str': ' massive',
- 'sequence': 'The Milky Way is a massive galaxy.'},
- {'score': 0.06434620916843414,
- 'token': 650,
- 'token_str': ' small',
- 'sequence': 'The Milky Way is a small galaxy.'}]
-```
-
-
-
-í
ì€ížë„Œ í í°ííêł `input_ids`넌 PyTorch í
ì ííëĄ ë°íí©ëë€.
-ëí, `` í í°ì ììč넌 ì§ì íŽìŒ í©ëë€:
-```py
->>> from transformers import AutoTokenizer
-
->>> tokenizer = AutoTokenizer.from_pretrained("my_awesome_eli5_mlm_model")
->>> inputs = tokenizer(text, return_tensors="pt")
->>> mask_token_index = torch.where(inputs["input_ids"] == tokenizer.mask_token_id)[1]
-```
-
-ëȘšëžì `inputs`넌 ì
ë „íêł , ë§ì€íčë í í°ì `logits`넌 ë°íí©ëë€:
-
-```py
->>> from transformers import AutoModelForMaskedLM
-
->>> model = AutoModelForMaskedLM.from_pretrained("stevhliu/my_awesome_eli5_mlm_model")
->>> logits = model(**inputs).logits
->>> mask_token_logits = logits[0, mask_token_index, :]
-```
-
-ê·žë° ë€ì ê°ì„ ëì íë„ ì ê°ì§ ë§ì€íŹ í í° 3ê°ë„Œ ë°ííêł , ì¶ë „í©ëë€:
-```py
->>> top_3_tokens = torch.topk(mask_token_logits, 3, dim=1).indices[0].tolist()
-
->>> for token in top_3_tokens:
-... print(text.replace(tokenizer.mask_token, tokenizer.decode([token])))
-The Milky Way is a spiral galaxy.
-The Milky Way is a massive galaxy.
-The Milky Way is a small galaxy.
-```
-
-
-í
ì€ížë„Œ í í°ííêł `input_ids`넌 TensorFlow í
ì ííëĄ ë°íí©ëë€.
-ëí, `` í í°ì ììč넌 ì§ì íŽìŒ í©ëë€:
-```py
->>> from transformers import AutoTokenizer
-
->>> tokenizer = AutoTokenizer.from_pretrained("my_awesome_eli5_mlm_model")
->>> inputs = tokenizer(text, return_tensors="tf")
->>> mask_token_index = tf.where(inputs["input_ids"] == tokenizer.mask_token_id)[0, 1]
-```
-
-ëȘšëžì `inputs`넌 ì
ë „íêł , ë§ì€íčë í í°ì `logits`넌 ë°íí©ëë€:
-
-```py
->>> from transformers import TFAutoModelForMaskedLM
-
->>> model = TFAutoModelForMaskedLM.from_pretrained("stevhliu/my_awesome_eli5_mlm_model")
->>> logits = model(**inputs).logits
->>> mask_token_logits = logits[0, mask_token_index, :]
-```
-
-ê·žë° ë€ì ê°ì„ ëì íë„ ì ê°ì§ ë§ì€íŹ í í° 3ê°ë„Œ ë°ííêł , ì¶ë „í©ëë€:
-```py
->>> top_3_tokens = tf.math.top_k(mask_token_logits, 3).indices.numpy()
-
->>> for token in top_3_tokens:
-... print(text.replace(tokenizer.mask_token, tokenizer.decode([token])))
-The Milky Way is a spiral galaxy.
-The Milky Way is a massive galaxy.
-The Milky Way is a small galaxy.
-```
-
-
diff --git a/docs/source/ko/tasks/monocular_depth_estimation.md b/docs/source/ko/tasks/monocular_depth_estimation.md
new file mode 100644
index 000000000000..e02dd5466b7d
--- /dev/null
+++ b/docs/source/ko/tasks/monocular_depth_estimation.md
@@ -0,0 +1,149 @@
+
+
+# ëšìŒ ìì êž°ë° êčìŽ ì¶ì [[depth-estimation-pipeline]]
+
+ëšìŒ ìì êž°ë° êčìŽ ì¶ì ì í ì„멎ì ëšìŒ ìŽëŻžì§ìì ì„멎ì êčìŽ ì ëłŽë„Œ ììžĄíë 컎íší° ëčì ìì
ì
ëë€.
+ìŠ, ëšìŒ ìčŽë©ëŒ ìì ì ì„멎ì ìë ëŹŒìČŽì ê±°ëŠŹë„Œ ììžĄíë êłŒì ì
ëë€.
+
+ëšìŒ ìì êž°ë° êčìŽ ì¶ì ì 3D ìŹê”Źì±, ìŠê° íì€, ììš ìŁŒí, ëĄëŽ êł”í ë± ë€ìí ë¶ìŒìì ìì©ë©ëë€.
+ìĄ°ëȘ
ìĄ°ê±Ž, ê°ë €ì§, í
ì€ìČì ê°ì ììì ìí„ì ë°ì ì ìë ì„멎 ëŽ ëŹŒìČŽì íŽëč êčìŽ ì 볎 ê°ì ëł”ìĄí êŽêłë„Œ ëȘšëžìŽ ìŽíŽíŽìŒ íëŻëĄ êčë€ëĄìŽ ìì
ì
ëë€.
+
+
+
+ìŽ íí 늏ìŒìì ë€ëŁšë ìì
ì ë€ì ëȘšëž ìí€í
ìČìì ì§ìë©ëë€:
+
+
+
+[DPT](../model_doc/dpt), [GLPN](../model_doc/glpn)
+
+
+
+
+
+ìŽëČ ê°ìŽëìì ë°°ìž ëŽì©ì ë€ìêłŒ ê°ì”ëë€:
+
+* êčìŽ ì¶ì íìŽíëŒìž ë§ë€êž°
+* ì§ì êčìŽ ì¶ì ì¶ëĄ íêž°
+
+ììíêž° ì ì, íìí ëȘšë ëŒìŽëžëŹëŠŹê° ì€ìčëìŽ ìëì§ íìžíìžì:
+
+```bash
+pip install -q transformers
+```
+
+## êčìŽ ì¶ì íìŽíëŒìž[[depth-estimation-inference-by-hand]]
+
+êčìŽ ì¶ì ì ì¶ëĄ íë ê°ì„ ê°ëší ë°©ëČì íŽëč êž°ë„ì ì êł”íë [`pipeline`]ì ìŹì©íë êČì
ëë€.
+[Hugging Face Hub ìČŽíŹíŹìžíž](https://huggingface.co/models?pipeline_tag=depth-estimation&sort=downloads)ìì íìŽíëŒìžì ìŽêž°íí©ëë€:
+
+```py
+>>> from transformers import pipeline
+
+>>> checkpoint = "vinvino02/glpn-nyu"
+>>> depth_estimator = pipeline("depth-estimation", model=checkpoint)
+```
+
+
+ë€ììŒëĄ, ë¶ìí ìŽëŻžì§ë„Œ í ì„ ì ííìžì:
+
+```py
+>>> from PIL import Image
+>>> import requests
+
+>>> url = "https://unsplash.com/photos/HwBAsSbPBDU/download?ixid=MnwxMjA3fDB8MXxzZWFyY2h8MzR8fGNhciUyMGluJTIwdGhlJTIwc3RyZWV0fGVufDB8MHx8fDE2Nzg5MDEwODg&force=true&w=640"
+>>> image = Image.open(requests.get(url, stream=True).raw)
+>>> image
+```
+
+
+
+
+
+ìŽëŻžì§ë„Œ íìŽíëŒìžìŒëĄ ì ëŹí©ëë€.
+
+```py
+>>> predictions = depth_estimator(image)
+```
+
+íìŽíëŒìžì ë ê°ì íëȘ©ì ê°ì§ë ëì
ëëŠŹë„Œ ë°íí©ëë€.
+ìČ« ëČì§žë `predicted_depth`ëĄ ê° íœì
ì êčìŽë„Œ 믞í°ëĄ ííí ê°ì ê°ì§ë í
ìì
ëë€.
+ë ëČì§žë `depth`ëĄ êčìŽ ì¶ì êČ°êłŒë„Œ ìê°ííë PIL ìŽëŻžì§ì
ëë€.
+
+ìŽì ìê°íí êČ°êłŒë„Œ ìŽíŽëłŽêČ ì”ëë€:
+
+```py
+>>> predictions["depth"]
+```
+
+
+
+
+
+## ì§ì êčìŽ ì¶ì ì¶ëĄ íêž°[[depth-estimation-inference-by-hand]]
+
+ìŽì êčìŽ ì¶ì íìŽíëŒìž ìŹì©ëČì ìŽíŽëłŽììŒë ëìŒí êČ°êłŒë„Œ ëł”ì íë ë°©ëČì ìŽíŽëłŽêČ ì”ëë€.
+[Hugging Face Hub ìČŽíŹíŹìžíž](https://huggingface.co/models?pipeline_tag=depth-estimation&sort=downloads)ìì ëȘšëžêłŒ êŽë š íëĄìžì넌 ê°ì žì€ë êČë¶í° ììí©ëë€.
+ìŹêž°ì ìŽì ì ìŹì©í ìČŽíŹíŹìžížì ëìŒí êČì ìŹì©í©ëë€:
+
+```py
+>>> from transformers import AutoImageProcessor, AutoModelForDepthEstimation
+
+>>> checkpoint = "vinvino02/glpn-nyu"
+
+>>> image_processor = AutoImageProcessor.from_pretrained(checkpoint)
+>>> model = AutoModelForDepthEstimation.from_pretrained(checkpoint)
+```
+
+íìí ìŽëŻžì§ ëłíì ìČ늏íë `image_processor`넌 ìŹì©íìŹ ëȘšëžì ëí ìŽëŻžì§ ì
ë „ì ì€ëčí©ëë€.
+`image_processor`ë íŹêž° ìĄ°ì ë° ì ê·í ë± íìí ìŽëŻžì§ ëłíì ìČ늏í©ëë€:
+
+```py
+>>> pixel_values = image_processor(image, return_tensors="pt").pixel_values
+```
+
+ì€ëčí ì
ë „ì ëȘšëžëĄ ì ëŹí©ëë€:
+
+```py
+>>> import torch
+
+>>> with torch.no_grad():
+... outputs = model(pixel_values)
+... predicted_depth = outputs.predicted_depth
+```
+
+êČ°êłŒë„Œ ìê°íí©ëë€:
+
+```py
+>>> import numpy as np
+
+>>> # ìëłž ìŹìŽìŠëĄ ëł”ì
+>>> prediction = torch.nn.functional.interpolate(
+... predicted_depth.unsqueeze(1),
+... size=image.size[::-1],
+... mode="bicubic",
+... align_corners=False,
+... ).squeeze()
+>>> output = prediction.numpy()
+
+>>> formatted = (output * 255 / np.max(output)).astype("uint8")
+>>> depth = Image.fromarray(formatted)
+>>> depth
+```
+
+
+
+
diff --git a/docs/source/ko/tasks/multiple_choice.md b/docs/source/ko/tasks/multiple_choice.md
new file mode 100644
index 000000000000..c174ca632f69
--- /dev/null
+++ b/docs/source/ko/tasks/multiple_choice.md
@@ -0,0 +1,465 @@
+
+
+# ê°êŽì 돞ì [[multiple-choice]]
+
+[[open-in-colab]]
+
+ê°êŽì êłŒì ë ëŹžë§„êłŒ íšê» ìŹëŹ ê°ì í볎 ë”ëłìŽ ì êł”ëêł ëȘšëžìŽ ì ë”ì ì ííëëĄ íì”ëë€ë ì ì ì ìží멎 ì§ììë”êłŒ ì ìŹí©ëë€.
+
+ì§ííë ë°©ëČì ìëì ê°ì”ëë€:
+
+1. [SWAG](https://huggingface.co/datasets/swag) ë°ìŽí° ìžížì 'regular' ê”Źì±ìŒëĄ [BERT](https://huggingface.co/bert-base-uncased)넌 ëŻžìž ìĄ°ì íìŹ ìŹëŹ ì”ì
êłŒ ìŒë¶ 컚í
ì€ížê° ìŁŒìŽìĄì ë ê°ì„ ì í©í ë”ì ì íí©ëë€.
+2. ì¶ëĄ ì ëŻžìž ìĄ°ì ë ëȘšëžì ìŹì©í©ëë€.
+
+
+ìŽ íí 늏ìŒìì ì€ëȘ
íë ìì
ì ë€ì ëȘšëž ìí€í
ìČìì ì§ìë©ëë€:
+
+
+
+[ALBERT](../model_doc/albert), [BERT](../model_doc/bert), [BigBird](../model_doc/big_bird), [CamemBERT](../model_doc/camembert), [CANINE](../model_doc/canine), [ConvBERT](../model_doc/convbert), [Data2VecText](../model_doc/data2vec-text), [DeBERTa-v2](../model_doc/deberta-v2), [DistilBERT](../model_doc/distilbert), [ELECTRA](../model_doc/electra), [ERNIE](../model_doc/ernie), [ErnieM](../model_doc/ernie_m), [FlauBERT](../model_doc/flaubert), [FNet](../model_doc/fnet), [Funnel Transformer](../model_doc/funnel), [I-BERT](../model_doc/ibert), [Longformer](../model_doc/longformer), [LUKE](../model_doc/luke), [MEGA](../model_doc/mega), [Megatron-BERT](../model_doc/megatron-bert), [MobileBERT](../model_doc/mobilebert), [MPNet](../model_doc/mpnet), [Nezha](../model_doc/nezha), [Nyströmformer](../model_doc/nystromformer), [QDQBert](../model_doc/qdqbert), [RemBERT](../model_doc/rembert), [RoBERTa](../model_doc/roberta), [RoBERTa-PreLayerNorm](../model_doc/roberta-prelayernorm), [RoCBert](../model_doc/roc_bert), [RoFormer](../model_doc/roformer), [SqueezeBERT](../model_doc/squeezebert), [XLM](../model_doc/xlm), [XLM-RoBERTa](../model_doc/xlm-roberta), [XLM-RoBERTa-XL](../model_doc/xlm-roberta-xl), [XLNet](../model_doc/xlnet), [X-MOD](../model_doc/xmod), [YOSO](../model_doc/yoso)
+
+
+
+
+
+ììíêž° ì ì íìí ëŒìŽëžëŹëŠŹê° ëȘšë ì€ìčëìŽ ìëì§ íìžíìžì:
+
+```bash
+pip install transformers datasets evaluate
+```
+
+ëȘšëžì ì
ëĄëíêł ì»€ëź€ëí°ì êł”ì í ì ìëëĄ íêč
íìŽì€ êłì ì ëĄê·žìžíë êČìŽ ìąì”ëë€. ë©ìì§ê° íìë멎 í í°ì ì
ë „íìŹ ëĄê·žìží©ëë€:
+
+```py
+>>> from huggingface_hub import notebook_login
+
+>>> notebook_login()
+```
+
+## SWAG ë°ìŽí° ìžíž ê°ì žì€êž°[[load-swag-dataset]]
+
+뚌ì đ€ Datasets ëŒìŽëžëŹëŠŹìì SWAG ë°ìŽí°ì
ì 'ìŒë°' ê”Źì±ì ê°ì žì”ëë€:
+
+```py
+>>> from datasets import load_dataset
+
+>>> swag = load_dataset("swag", "regular")
+```
+
+ìŽì ë°ìŽí°ë„Œ ìŽíŽëŽ
ëë€:
+
+```py
+>>> swag["train"][0]
+{'ending0': 'passes by walking down the street playing their instruments.',
+ 'ending1': 'has heard approaching them.',
+ 'ending2': "arrives and they're outside dancing and asleep.",
+ 'ending3': 'turns the lead singer watches the performance.',
+ 'fold-ind': '3416',
+ 'gold-source': 'gold',
+ 'label': 0,
+ 'sent1': 'Members of the procession walk down the street holding small horn brass instruments.',
+ 'sent2': 'A drum line',
+ 'startphrase': 'Members of the procession walk down the street holding small horn brass instruments. A drum line',
+ 'video-id': 'anetv_jkn6uvmqwh4'}
+```
+
+ìŹêž°ìë ë§ì íëê° ìë êČìČëŒ ëłŽìŽì§ë§ ì€ì ëĄë ë§€ì° ê°ëší©ëë€:
+
+- `sent1` ë° `sent2`: ìŽ íëë 돞ì„ìŽ ìŽë»êČ ììëëì§ ëłŽìŹìŁŒë©°, ìŽ ë íë넌 í©ìč멎 `ìì ê”Źì (startphrase)` íëê° ë©ëë€.
+- `ìą
ëŁ ê”Źì (ending)`: 돞ì„ìŽ ìŽë»êČ ëë ì ìëì§ì ëí ê°ë„í ìą
ëŁ ê”Źì 넌 ì ìíì§ë§ ê·ž ì€ íëë§ ì ë”ì
ëë€.
+- `ë ìŽëž(label)`: ìŹë°ë„ž ëŹžì„ ìą
ëŁ ê”Źì ì ìëłí©ëë€.
+
+## ì ìČ늏[[preprocess]]
+
+ë€ì ëšêłë 돞ì„ì ììêłŒ ë€ ê°ì§ ê°ë„í ê”Źì ì ìČ늏íêž° ìíŽ BERT í íŹëìŽì 넌 ë¶ëŹì”ëë€:
+
+```py
+>>> from transformers import AutoTokenizer
+
+>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
+```
+
+ìì±íë €ë ì ìČ늏 íšìë ë€ìêłŒ ê°ììŒ í©ëë€:
+
+1. `sent1` íë넌 ë€ ê° ëł”ìŹí ë€ì ê°ê°ì `sent2`ì êȰí©íìŹ ëŹžì„ìŽ ììëë ë°©ìì ìŹíí©ëë€.
+2. `sent2`넌 ë€ ê°ì§ ê°ë„í ëŹžì„ ê”Źì ê°ê°êłŒ êȰí©í©ëë€.
+3. ìŽ ë ëȘ©ëĄì í í°íí ì ìëëĄ ííí(flatten)íêł , ê° ìì ì íŽëčíë `input_ids`, `attention_mask` ë° `labels` íë넌 ê°ëëĄ ë€ì°šìí(unflatten) í©ëë€.
+
+```py
+>>> ending_names = ["ending0", "ending1", "ending2", "ending3"]
+
+
+>>> def preprocess_function(examples):
+... first_sentences = [[context] * 4 for context in examples["sent1"]]
+... question_headers = examples["sent2"]
+... second_sentences = [
+... [f"{header} {examples[end][i]}" for end in ending_names] for i, header in enumerate(question_headers)
+... ]
+
+... first_sentences = sum(first_sentences, [])
+... second_sentences = sum(second_sentences, [])
+
+... tokenized_examples = tokenizer(first_sentences, second_sentences, truncation=True)
+... return {k: [v[i : i + 4] for i in range(0, len(v), 4)] for k, v in tokenized_examples.items()}
+```
+
+ì ìČŽ ë°ìŽí° ì§í©ì ì ìČ늏 êž°ë„ì ì ì©íë €ë©Ž đ€ Datasets [`~datasets.Dataset.map`] ë©ìë넌 ìŹì©í©ëë€. `batched=True`넌 ì€ì íìŹ ë°ìŽí° ì§í©ì ìŹëŹ ìì넌 í ëČì ìČ늏í멎 `map` íšìì ìë넌 ëìŒ ì ìì”ëë€:
+
+```py
+tokenized_swag = swag.map(preprocess_function, batched=True)
+```
+
+đ€ Transformersìë ê°êŽìì© ë°ìŽí° ìœë ìŽí°ê° ììŒëŻëĄ ìì ë°°ìč넌 ë§ë€ë €ë©Ž [`DataCollatorWithPadding`]ì ìĄ°ì íŽìŒ í©ëë€. ë°ìŽí° ì ë Ź ì€ì ì ìČŽ ë°ìŽí° ì§í©ì ì”ë êžžìŽëĄ íšë©íë ëì ë°°ìč ì€ ê°ì„ ꞎ êžžìŽëĄ 돞ì„ì *ëì íšë©*íë êČìŽ ë íšìšì ì
ëë€.
+
+`DataCollatorForMultipleChoice`ë ëȘšë ëȘšëž ì
ë „ì ííííêł íšë©ì ì ì©íë©° ê·ž êČ°êłŒë„Œ êČ°êłŒë„Œ ë€ì°šìíí©ëë€:
+
+
+
+```py
+>>> from dataclasses import dataclass
+>>> from transformers.tokenization_utils_base import PreTrainedTokenizerBase, PaddingStrategy
+>>> from typing import Optional, Union
+>>> import torch
+
+
+>>> @dataclass
+... class DataCollatorForMultipleChoice:
+... """
+... Data collator that will dynamically pad the inputs for multiple choice received.
+... """
+
+... tokenizer: PreTrainedTokenizerBase
+... padding: Union[bool, str, PaddingStrategy] = True
+... max_length: Optional[int] = None
+... pad_to_multiple_of: Optional[int] = None
+
+... def __call__(self, features):
+... label_name = "label" if "label" in features[0].keys() else "labels"
+... labels = [feature.pop(label_name) for feature in features]
+... batch_size = len(features)
+... num_choices = len(features[0]["input_ids"])
+... flattened_features = [
+... [{k: v[i] for k, v in feature.items()} for i in range(num_choices)] for feature in features
+... ]
+... flattened_features = sum(flattened_features, [])
+
+... batch = self.tokenizer.pad(
+... flattened_features,
+... padding=self.padding,
+... max_length=self.max_length,
+... pad_to_multiple_of=self.pad_to_multiple_of,
+... return_tensors="pt",
+... )
+
+... batch = {k: v.view(batch_size, num_choices, -1) for k, v in batch.items()}
+... batch["labels"] = torch.tensor(labels, dtype=torch.int64)
+... return batch
+```
+
+
+```py
+>>> from dataclasses import dataclass
+>>> from transformers.tokenization_utils_base import PreTrainedTokenizerBase, PaddingStrategy
+>>> from typing import Optional, Union
+>>> import tensorflow as tf
+
+
+>>> @dataclass
+... class DataCollatorForMultipleChoice:
+... """
+... Data collator that will dynamically pad the inputs for multiple choice received.
+... """
+
+... tokenizer: PreTrainedTokenizerBase
+... padding: Union[bool, str, PaddingStrategy] = True
+... max_length: Optional[int] = None
+... pad_to_multiple_of: Optional[int] = None
+
+... def __call__(self, features):
+... label_name = "label" if "label" in features[0].keys() else "labels"
+... labels = [feature.pop(label_name) for feature in features]
+... batch_size = len(features)
+... num_choices = len(features[0]["input_ids"])
+... flattened_features = [
+... [{k: v[i] for k, v in feature.items()} for i in range(num_choices)] for feature in features
+... ]
+... flattened_features = sum(flattened_features, [])
+
+... batch = self.tokenizer.pad(
+... flattened_features,
+... padding=self.padding,
+... max_length=self.max_length,
+... pad_to_multiple_of=self.pad_to_multiple_of,
+... return_tensors="tf",
+... )
+
+... batch = {k: tf.reshape(v, (batch_size, num_choices, -1)) for k, v in batch.items()}
+... batch["labels"] = tf.convert_to_tensor(labels, dtype=tf.int64)
+... return batch
+```
+
+
+
+## íê° íêž°[[evaluate]]
+
+íë š ì€ì ë©ížëŠì íŹíší멎 ëȘšëžì ì±ë„ì íê°íë ë° ëììŽ ëë êČœì°ê° ë§ì”ëë€. đ€[Evaluate](https://huggingface.co/docs/evaluate/index) ëŒìŽëžëŹëŠŹë„Œ ìŹì©íìŹ íê° ë°©ëČì ëč 넎êČ ê°ì žìŹ ì ìì”ëë€. ìŽ ìì
ììë [accuracy](https://huggingface.co/spaces/evaluate-metric/accuracy) ì§í넌 ê°ì žì”ëë€(đ€ Evaluate [ëëŹëłŽêž°](https://huggingface.co/docs/evaluate/a_quick_tour)넌 ì°žìĄ°íìŹ ì§í넌 ê°ì žì€êł êłì°íë ë°©ëČì ëíŽ ììží ìì볎ìžì):
+
+```py
+>>> import evaluate
+
+>>> accuracy = evaluate.load("accuracy")
+```
+
+ê·žëŠŹêł ììžĄêłŒ ë ìŽëžì [`~evaluate.EvaluationModule.compute`]ì ì ëŹíìŹ ì íë넌 êłì°íë íšì넌 ë§ëëë€:
+
+```py
+>>> import numpy as np
+
+
+>>> def compute_metrics(eval_pred):
+... predictions, labels = eval_pred
+... predictions = np.argmax(predictions, axis=1)
+... return accuracy.compute(predictions=predictions, references=labels)
+```
+
+ìŽì `compute_metrics` íšì넌 ìŹì©í ì€ëčê° ëììŒë©°, íë šì ì€ì í ë ìŽ íšìëĄ ëìê°êČ ë©ëë€.
+
+## íë š íêž°[[train]]
+
+
+
+
+
+[`Trainer`]ëĄ ëȘšëžì ëŻžìž ìĄ°ì íë ë° ì”ìíì§ ìë€ë©Ž êž°ëłž íí ëŠŹìŒ [ìŹêž°](../training#train-with-pytorch-trainer)넌 ìŽíŽëłŽìžì!
+
+
+
+ìŽì ëȘšëž íë šì ììí ì€ëčê° ëìì”ëë€! [`AutoModelForMultipleChoice`]ëĄ BERT넌 ëĄëí©ëë€:
+
+```py
+>>> from transformers import AutoModelForMultipleChoice, TrainingArguments, Trainer
+
+>>> model = AutoModelForMultipleChoice.from_pretrained("bert-base-uncased")
+```
+
+ìŽì ìž ëšêłë§ ëšìì”ëë€:
+
+1. íë š íìŽíŒíëŒëŻží°ë„Œ [`TrainingArguments`]ì ì ìí©ëë€. ì ìŒí íì ë§€ê°ëłìë ëȘšëžì ì ì„í ììč넌 ì§ì íë `output_dir`ì
ëë€. `push_to_hub=True`넌 ì€ì íìŹ ìŽ ëȘšëžì íëžì ížìí©ëë€(ëȘšëžì ì
ëĄëíë €ë©Ž íêč
íìŽì€ì ëĄê·žìžíŽìŒ í©ëë€). ê° ìíìŽ ëë ëë§ë€ [`Trainer`]ê° ì íë넌 íê°íêł íë š ìČŽíŹíŹìžížë„Œ ì ì„í©ëë€.
+2. ëȘšëž, ë°ìŽí° ìžíž, í íŹëìŽì , ë°ìŽí° ìœë ìŽí°, `compute_metrics` íšìì íšê» íë š ìžì넌 [`Trainer`]ì ì ëŹí©ëë€.
+3. [`~Trainer.train`]ì ìŹì©íìŹ ëȘšëžì ëŻžìž ìĄ°ì í©ëë€.
+
+```py
+>>> training_args = TrainingArguments(
+... output_dir="my_awesome_swag_model",
+... evaluation_strategy="epoch",
+... save_strategy="epoch",
+... load_best_model_at_end=True,
+... learning_rate=5e-5,
+... per_device_train_batch_size=16,
+... per_device_eval_batch_size=16,
+... num_train_epochs=3,
+... weight_decay=0.01,
+... push_to_hub=True,
+... )
+
+>>> trainer = Trainer(
+... model=model,
+... args=training_args,
+... train_dataset=tokenized_swag["train"],
+... eval_dataset=tokenized_swag["validation"],
+... tokenizer=tokenizer,
+... data_collator=DataCollatorForMultipleChoice(tokenizer=tokenizer),
+... compute_metrics=compute_metrics,
+... )
+
+>>> trainer.train()
+```
+
+íë šìŽ ìëŁë멎 ëȘšë ìŹëìŽ ëȘšëžì ìŹì©í ì ìëëĄ [`~transformers.Trainer.push_to_hub`] ë©ìë넌 ìŹì©íìŹ ëȘšëžì íëžì êł”ì íìžì:
+
+```py
+>>> trainer.push_to_hub()
+```
+
+
+
+
+KerasëĄ ëȘšëžì ëŻžìž ìĄ°ì íë ë° ì”ìíì§ ìë€ë©Ž êž°ëłž íí ëŠŹìŒ [ìŹêž°](../training#train-a-tensorflow-model-with-keras)넌 ìŽíŽëłŽìêž° ë°ëëë€!
+
+
+TensorFlowìì ëȘšëžì ëŻžìž ìĄ°ì íë €ë©Ž ì”ì í íšì, íì”ë„ ì€ìŒì„Ž ë° ëȘ ê°ì§ íì” íìŽíŒíëŒëŻží°ë„Œ ì€ì íë êČë¶í° ììíìžì:
+
+```py
+>>> from transformers import create_optimizer
+
+>>> batch_size = 16
+>>> num_train_epochs = 2
+>>> total_train_steps = (len(tokenized_swag["train"]) // batch_size) * num_train_epochs
+>>> optimizer, schedule = create_optimizer(init_lr=5e-5, num_warmup_steps=0, num_train_steps=total_train_steps)
+```
+
+ê·žëŠŹêł [`TFAutoModelForMultipleChoice`]ëĄ BERT넌 ê°ì žìŹ ì ìì”ëë€:
+
+```py
+>>> from transformers import TFAutoModelForMultipleChoice
+
+>>> model = TFAutoModelForMultipleChoice.from_pretrained("bert-base-uncased")
+```
+
+[`~transformers.TFPreTrainedModel.prepare_tf_dataset`]ì ìŹì©íìŹ ë°ìŽí° ìžížë„Œ `tf.data.Dataset` íììŒëĄ ëłíí©ëë€:
+
+```py
+>>> data_collator = DataCollatorForMultipleChoice(tokenizer=tokenizer)
+>>> tf_train_set = model.prepare_tf_dataset(
+... tokenized_swag["train"],
+... shuffle=True,
+... batch_size=batch_size,
+... collate_fn=data_collator,
+... )
+
+>>> tf_validation_set = model.prepare_tf_dataset(
+... tokenized_swag["validation"],
+... shuffle=False,
+... batch_size=batch_size,
+... collate_fn=data_collator,
+... )
+```
+
+[`compile`](https://keras.io/api/models/model_training_apis/#compile-method)ì ìŹì©íìŹ íë š ëȘšëžì ê”Źì±í©ëë€:
+
+```py
+>>> model.compile(optimizer=optimizer)
+```
+
+íë šì ììíêž° ì ì ì€ì íŽìŒ í ë§ì§ë§ ë ê°ì§ë ììžĄì ì íë넌 êłì°íêł ëȘšëžì íëžëĄ ížìíë ë°©ëČì ì êł”íë êČì
ëë€. ìŽ ë ê°ì§ ìì
ì ëȘšë [Keras ìœë°±](../main_classes/keras_callbacks)ì ìŹì©íìŹ ìíí ì ìì”ëë€.
+
+`compute_metrics`íšì넌 [`~transformers.KerasMetricCallback`]ì ì ëŹíìžì:
+
+```py
+>>> from transformers.keras_callbacks import KerasMetricCallback
+
+>>> metric_callback = KerasMetricCallback(metric_fn=compute_metrics, eval_dataset=tf_validation_set)
+```
+
+ëȘšëžêłŒ í íŹëìŽì 넌 ì
ëĄëí ììč넌 [`~transformers.PushToHubCallback`]ìì ì§ì íìžì:
+
+```py
+>>> from transformers.keras_callbacks import PushToHubCallback
+
+>>> push_to_hub_callback = PushToHubCallback(
+... output_dir="my_awesome_model",
+... tokenizer=tokenizer,
+... )
+```
+
+ê·žëŠŹêł ìœë°±ì íšê» 돶ì”ëë€:
+
+```py
+>>> callbacks = [metric_callback, push_to_hub_callback]
+```
+
+ìŽì ëȘšëž íë šì ììí©ëë€! íë š ë° êČìŠ ë°ìŽí° ìžíž, ìí ì, ìœë°±ì ìŹì©íìŹ [`fit`](https://keras.io/api/models/model_training_apis/#fit-method)ì ížì¶íêł ëȘšëžì ëŻžìž ìĄ°ì í©ëë€:
+
+```py
+>>> model.fit(x=tf_train_set, validation_data=tf_validation_set, epochs=2, callbacks=callbacks)
+```
+
+íë šìŽ ìëŁë멎 ëȘšëžìŽ ìëìŒëĄ íëžì ì
ëĄëëìŽ ëê”Źë ìŹì©í ì ìì”ëë€!
+
+
+
+
+
+
+ê°êŽì ëȘšëžì ëŻžìž ìĄ°ì íë ë°©ëČì ëí ëłŽë€ ìŹìž”ì ìž ìë ìë 돞ì넌 ì°žìĄ°íìžì.
+[PyTorch notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/multiple_choice.ipynb)
+ëë [TensorFlow notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/multiple_choice-tf.ipynb).
+
+
+
+## ì¶ëĄ íêž°[[inference]]
+
+ìŽì ëȘšëžì ëŻžìž ìĄ°ì íìŒë ì¶ëĄ ì ìŹì©í ì ìì”ëë€!
+
+í
ì€ížì ë ê°ì í볎 ë”ìì ìì±í©ëë€:
+
+```py
+>>> prompt = "France has a bread law, Le Décret Pain, with strict rules on what is allowed in a traditional baguette."
+>>> candidate1 = "The law does not apply to croissants and brioche."
+>>> candidate2 = "The law applies to baguettes."
+```
+
+
+
+ê° í륏íížì í볎 ë”ëł ìì í í°ííìŹ PyTorch í
ì넌 ë°íí©ëë€. ëí `labels`ì ìì±íŽìŒ í©ëë€:
+
+```py
+>>> from transformers import AutoTokenizer
+
+>>> tokenizer = AutoTokenizer.from_pretrained("my_awesome_swag_model")
+>>> inputs = tokenizer([[prompt, candidate1], [prompt, candidate2]], return_tensors="pt", padding=True)
+>>> labels = torch.tensor(0).unsqueeze(0)
+```
+
+ì
ë „êłŒ ë ìŽëžì ëȘšëžì ì ëŹíêł `logits`ì ë°íí©ëë€:
+
+```py
+>>> from transformers import AutoModelForMultipleChoice
+
+>>> model = AutoModelForMultipleChoice.from_pretrained("my_awesome_swag_model")
+>>> outputs = model(**{k: v.unsqueeze(0) for k, v in inputs.items()}, labels=labels)
+>>> logits = outputs.logits
+```
+
+ê°ì„ ëì íë„ ì ê°ì§ íŽëì€ë„Œ ê°ì žì”ëë€:
+
+```py
+>>> predicted_class = logits.argmax().item()
+>>> predicted_class
+'0'
+```
+
+
+ê° í륏íížì í볎 ë”ì ìì í í°ííìŹ í
ìíëĄ í
ì넌 ë°íí©ëë€:
+
+```py
+>>> from transformers import AutoTokenizer
+
+>>> tokenizer = AutoTokenizer.from_pretrained("my_awesome_swag_model")
+>>> inputs = tokenizer([[prompt, candidate1], [prompt, candidate2]], return_tensors="tf", padding=True)
+```
+
+ëȘšëžì ì
ë „ì ì ëŹíêł `logits`넌 ë°íí©ëë€:
+
+```py
+>>> from transformers import TFAutoModelForMultipleChoice
+
+>>> model = TFAutoModelForMultipleChoice.from_pretrained("my_awesome_swag_model")
+>>> inputs = {k: tf.expand_dims(v, 0) for k, v in inputs.items()}
+>>> outputs = model(inputs)
+>>> logits = outputs.logits
+```
+
+ê°ì„ ëì íë„ ì ê°ì§ íŽëì€ë„Œ ê°ì žì”ëë€:
+
+```py
+>>> predicted_class = int(tf.math.argmax(logits, axis=-1)[0])
+>>> predicted_class
+'0'
+```
+
+
diff --git a/docs/source/ko/tasks/object_detection.md b/docs/source/ko/tasks/object_detection.md
new file mode 100644
index 000000000000..ca384d038162
--- /dev/null
+++ b/docs/source/ko/tasks/object_detection.md
@@ -0,0 +1,588 @@
+
+
+# ê°ìČŽ íì§ [[object-detection]]
+
+[[open-in-colab]]
+
+ê°ìČŽ íì§ë ìŽëŻžì§ìì ìžì€íŽì€(ì: ìŹë, ê±ŽëŹŒ ëë ìëì°š)넌 ê°ì§íë 컎íší° ëčì ìì
ì
ëë€. ê°ìČŽ íì§ ëȘšëžì ìŽëŻžì§ë„Œ ì
ë „ìŒëĄ ë°êł íì§ë ë°ìŽë© ë°ì€ì ìąíì êŽë šë ë ìŽëžì ì¶ë „í©ëë€.
+íëì ìŽëŻžì§ìë ìŹëŹ ê°ìČŽê° ìì ì ììŒë©° ê°ê°ì ììČŽì ìž ë°ìŽë© ë°ì€ì ë ìŽëžì ê°ì§ ì ìì”ëë€(ì: ì°šì ê±ŽëŹŒìŽ ìë ìŽëŻžì§).
+ëí ê° ê°ìČŽë ìŽëŻžì§ì ë€ë„ž ë¶ë¶ì ìĄŽìŹí ì ìì”ëë€(ì: ìŽëŻžì§ì ìŹëŹ ëì ì°šê° ìì ì ìì).
+ìŽ ìì
ì 볎íì, ëëĄ íì§í, ì ížë±êłŒ ê°ì êČë€ì ê°ì§íë ììš ìŁŒíì ìŒë°ì ìŒëĄ ìŹì©ë©ëë€.
+ë€ë„ž ìì© ë¶ìŒëĄë ìŽëŻžì§ ëŽ ê°ìČŽ ì êłì° ë° ìŽëŻžì§ êČì ë±ìŽ ìì”ëë€.
+
+ìŽ ê°ìŽëìì ë€ìì ë°°ìž êČì
ëë€:
+
+ 1. í©ì±êł± 백볞(ìží ë°ìŽí°ì íčì±ì ì¶ì¶íë í©ì±êł± ë€ížìíŹ)êłŒ ìžìœë-ëìœë ížëì€íŹëšž ëȘšëžì êȰí©í [DETR](https://huggingface.co/docs/transformers/model_doc/detr) ëȘšëžì [CPPE-5](https://huggingface.co/datasets/cppe-5) ë°ìŽí° ìžížì ëíŽ ëŻžìžìĄ°ì íêž°
+ 2. 믞ìžìĄ°ì í ëȘšëžì ì¶ëĄ ì ìŹì©íêž°.
+
+
+ìŽ íí 늏ìŒì íì€íŹë ë€ì ëȘšëž ìí€í
ìČìì ì§ìë©ëë€:
+
+
+
+[Conditional DETR](../model_doc/conditional_detr), [Deformable DETR](../model_doc/deformable_detr), [DETA](../model_doc/deta), [DETR](../model_doc/detr), [Table Transformer](../model_doc/table-transformer), [YOLOS](../model_doc/yolos)
+
+
+
+
+
+ììíêž° ì ì íìí ëȘšë ëŒìŽëžëŹëŠŹê° ì€ìčëìŽ ìëì§ íìžíìžì:
+```bash
+pip install -q datasets transformers evaluate timm albumentations
+```
+
+íêč
íìŽì€ íëžìì ë°ìŽí° ìžížë„Œ ê°ì žì€êž° ìí đ€ DatasetsêłŒ ëȘšëžì íì”íêž° ìí đ€ Transformers, ë°ìŽí°ë„Œ ìŠê°íêž° ìí `albumentations`넌 ìŹì©í©ëë€.
+DETR ëȘšëžì í©ì±êł± 백볞ì ê°ì žì€êž° ìíŽìë íìŹ `timm`ìŽ íìí©ëë€.
+
+ì»€ëź€ëí°ì ëȘšëžì ì
ëĄëíêł êł”ì í ì ìëëĄ Hugging Face êłì ì ëĄê·žìžíë êČì ê¶ì„í©ëë€. í륏íížê° ëíë멎 í í°ì ì
ë „íìŹ ëĄê·žìžíìžì:
+
+```py
+>>> from huggingface_hub import notebook_login
+
+>>> notebook_login()
+```
+
+## CPPE-5 ë°ìŽí° ìžíž ê°ì žì€êž° [[load-the-CPPE-5-dataset]]
+
+[CPPE-5](https://huggingface.co/datasets/cppe-5) ë°ìŽí° ìžížë COVID-19 ëì í ìí©ìì ìëŁ ì 돞ìžë „ ëłŽíž ì„ëč(PPE)넌 ìëłíë ìŽë
ží
ìŽì
ìŽ íŹíšë ìŽëŻžì§ë„Œ ëŽêł ìì”ëë€.
+
+ë°ìŽí° ìžížë„Œ ê°ì žì€ìžì:
+
+```py
+>>> from datasets import load_dataset
+
+>>> cppe5 = load_dataset("cppe-5")
+>>> cppe5
+DatasetDict({
+ train: Dataset({
+ features: ['image_id', 'image', 'width', 'height', 'objects'],
+ num_rows: 1000
+ })
+ test: Dataset({
+ features: ['image_id', 'image', 'width', 'height', 'objects'],
+ num_rows: 29
+ })
+})
+```
+
+ìŽ ë°ìŽí° ìžížë íì” ìžíž ìŽëŻžì§ 1,000ê°ì í
ì€íž ìžíž ìŽëŻžì§ 29ê°ë„Œ ê°êł ìì”ëë€.
+
+ë°ìŽí°ì ì”ìíŽì§êž° ìíŽ, ììê° ìŽë»êČ ê”Źì±ëìŽ ìëì§ ìŽíŽëłŽìžì.
+
+```py
+>>> cppe5["train"][0]
+{'image_id': 15,
+ 'image': ,
+ 'width': 943,
+ 'height': 663,
+ 'objects': {'id': [114, 115, 116, 117],
+ 'area': [3796, 1596, 152768, 81002],
+ 'bbox': [[302.0, 109.0, 73.0, 52.0],
+ [810.0, 100.0, 57.0, 28.0],
+ [160.0, 31.0, 248.0, 616.0],
+ [741.0, 68.0, 202.0, 401.0]],
+ 'category': [4, 4, 0, 0]}}
+```
+
+ë°ìŽí° ìžížì ìë ììë ë€ìì ììì ê°ì§êł ìì”ëë€:
+
+- `image_id`: ìì ìŽëŻžì§ id
+- `image`: ìŽëŻžì§ë„Œ íŹíšíë `PIL.Image.Image` ê°ìČŽ
+- `width`: ìŽëŻžì§ì ëëč
+- `height`: ìŽëŻžì§ì ëìŽ
+- `objects`: ìŽëŻžì§ ìì ê°ìČŽë€ì ë°ìŽë© ë°ì€ ë©íë°ìŽí°ë„Œ íŹíšíë ëì
ë늏:
+ - `id`: ìŽë
ží
ìŽì
id
+ - `area`: ë°ìŽë© ë°ì€ì 멎ì
+ - `bbox`: ê°ìČŽì ë°ìŽë© ë°ì€ ([COCO íŹë§·](https://albumentations.ai/docs/getting_started/bounding_boxes_augmentation/#coco)ìŒëĄ)
+ - `category`: ê°ìČŽì ìčŽí
êł ëŠŹ, ê°ë„í ê°ìŒëĄë `Coverall (0)`, `Face_Shield (1)`, `Gloves (2)`, `Goggles (3)` ë° `Mask (4)` ê° íŹíšë©ëë€.
+
+`bbox` íëê° DETR ëȘšëžìŽ ìê”Źíë COCO íìì ë°ë„žë€ë êČì ì ì ìì”ëë€.
+ê·žëŹë `objects` ëŽë¶ì íë ê·žëŁčì DETRìŽ ìê”Źíë ìŽë
ží
ìŽì
íìêłŒ ë€ëŠ
ëë€. ë°ëŒì ìŽ ë°ìŽí°ë„Œ íì”ì ìŹì©íêž° ì ì ì ìČëŠŹë„Œ ì ì©íŽìŒ í©ëë€.
+
+ë°ìŽí°ë„Œ ë ì ìŽíŽíêž° ìíŽì ë°ìŽí° ìžížìì í ê°ì§ ìì넌 ìê°ííìžì.
+
+```py
+>>> import numpy as np
+>>> import os
+>>> from PIL import Image, ImageDraw
+
+>>> image = cppe5["train"][0]["image"]
+>>> annotations = cppe5["train"][0]["objects"]
+>>> draw = ImageDraw.Draw(image)
+
+>>> categories = cppe5["train"].features["objects"].feature["category"].names
+
+>>> id2label = {index: x for index, x in enumerate(categories, start=0)}
+>>> label2id = {v: k for k, v in id2label.items()}
+
+>>> for i in range(len(annotations["id"])):
+... box = annotations["bbox"][i - 1]
+... class_idx = annotations["category"][i - 1]
+... x, y, w, h = tuple(box)
+... draw.rectangle((x, y, x + w, y + h), outline="red", width=1)
+... draw.text((x, y), id2label[class_idx], fill="white")
+
+>>> image
+```
+
+
+
+
+
+ë°ìŽë© ë°ì€ì ì°êȰë ë ìŽëžì ìê°ííë €ë©Ž ë°ìŽí° ìžížì ë©í ë°ìŽí°, íčí `category` íëìì ë ìŽëžì ê°ì žììŒ í©ëë€.
+ëí ë ìŽëž ID넌 ë ìŽëž íŽëì€ì ë§€ííë `id2label`êłŒ ë°ëëĄ ë§€ííë `label2id` ëì
ëëŠŹë„Œ ë§ë€ìŽìŒ í©ëë€.
+ëȘšëžì ì€ì í ë ìŽëŹí ë§€íì ìŹì©í ì ìì”ëë€. ìŽëŹí ë§€íì íêč
íìŽì€ íëžìì ëȘšëžì êł”ì íì ë ë€ë„ž ìŹëë€ìŽ ìŹìŹì©í ì ìì”ëë€.
+
+ë°ìŽí°ë„Œ ë ì ìŽíŽíêž° ìí ì”ìą
ëšêłëĄ, ì ìŹì ìž ëŹžì 넌 ì°Ÿì볎ìžì.
+ê°ìČŽ ê°ì§ë„Œ ìí ë°ìŽí° ìžížìì ììŁŒ ë°ìíë 돞ì ì€ íëë ë°ìŽë© ë°ì€ê° ìŽëŻžì§ì ê°ì„ìëŠŹë„Œ ëìŽê°ë êČì
ëë€.
+ìŽëŹí ë°ìŽë© ë°ì€ë„Œ "ëìŽê°ë êČ(run away)"ì íë š ì€ì ì€ë„넌 ë°ììíŹ ì ìêž°ì ìŽ ëšêłìì ìČ늏íŽìŒ í©ëë€.
+ìŽ ë°ìŽí° ìžížìë ê°ì 돞ì ê° ìë ëȘ ê°ì§ ìê° ìì”ëë€. ìŽ ê°ìŽëììë ê°ëšíêČíêž° ìíŽ ë°ìŽí°ìì ìŽëŹí ìŽëŻžì§ë„Œ ì ê±°í©ëë€.
+
+```py
+>>> remove_idx = [590, 821, 822, 875, 876, 878, 879]
+>>> keep = [i for i in range(len(cppe5["train"])) if i not in remove_idx]
+>>> cppe5["train"] = cppe5["train"].select(keep)
+```
+
+## ë°ìŽí° ì ìČ늏íêž° [[preprocess-the-data]]
+
+ëȘšëžì ëŻžìž ìĄ°ì íë €ë©Ž, 믞늏 íì”ë ëȘšëžìì ìŹì©í ì ìČ늏 ë°©ìêłŒ ì ííêČ ìŒìčíëëĄ ìŹì©í ë°ìŽí°ë„Œ ì ìČ늏íŽìŒ í©ëë€.
+[`AutoImageProcessor`]ë ìŽëŻžì§ ë°ìŽí°ë„Œ ìČ늏íìŹ DETR ëȘšëžìŽ íì”ì ìŹì©í ì ìë `pixel_values`, `pixel_mask`, ê·žëŠŹêł `labels`넌 ìì±íë ìì
ì ëŽëčí©ëë€.
+ìŽ ìŽëŻžì§ íëĄìžììë ê±±ì íì§ ììë ëë ëȘ ê°ì§ ìì±ìŽ ìì”ëë€:
+
+- `image_mean = [0.485, 0.456, 0.406 ]`
+- `image_std = [0.229, 0.224, 0.225]`
+
+
+ìŽ ê°ë€ì ëȘšëž ìŹì íë š ì€ ìŽëŻžì§ë„Œ ì ê·ííë ë° ìŹì©ëë íê· êłŒ íì€ ížì°šì
ëë€.
+ìŽ ê°ë€ì ì¶ëĄ ëë ìŹì íë šë ìŽëŻžì§ ëȘšëžì ìžë°íêČ ìĄ°ì í ë ëł”ì íŽìŒ íë ì€ìí ê°ì
ëë€.
+
+ìŹì íë šë ëȘšëžêłŒ ëìŒí ìČŽíŹíŹìžížìì ìŽëŻžì§ íëĄìžì넌 ìžì€íŽì€íí©ëë€.
+
+```py
+>>> from transformers import AutoImageProcessor
+
+>>> checkpoint = "facebook/detr-resnet-50"
+>>> image_processor = AutoImageProcessor.from_pretrained(checkpoint)
+```
+
+`image_processor`ì ìŽëŻžì§ë„Œ ì ëŹíêž° ì ì, ë°ìŽí° ìžížì ë ê°ì§ ì ìČëŠŹë„Œ ì ì©íŽìŒ í©ëë€:
+
+- ìŽëŻžì§ ìŠê°
+- DETR ëȘšëžì ìê”Źì ë§êČ ìŽë
ží
ìŽì
ì ë€ì íŹë§·í
+
+ìČ«ì§žëĄ, ëȘšëžìŽ íì” ë°ìŽí°ì êłŒì í© ëì§ ìëëĄ ë°ìŽí° ìŠê° ëŒìŽëžëŹëŠŹ ì€ ìëŹŽê±°ë ìŹì©íìŹ ëłíì ì ì©í ì ìì”ëë€. ìŹêž°ììë [Albumentations](https://albumentations.ai/docs/) ëŒìŽëžëŹëŠŹë„Œ ìŹì©í©ëë€...
+ìŽ ëŒìŽëžëŹëŠŹë ëłíì ìŽëŻžì§ì ì ì©íêł ë°ìŽë© ë°ì€ë„Œ ì ì íêČ ì
ë°ìŽížíëëĄ ëłŽì„í©ëë€.
+đ€ Datasets ëŒìŽëžëŹëŠŹ 돞ììë [ê°ìČŽ íì§ë„Œ ìíŽ ìŽëŻžì§ë„Œ 볎ê°íë ë°©ëČì ëí ììží ê°ìŽë](https://huggingface.co/docs/datasets/object_detection)ê° ììŒë©°,
+ìŽ ìì ì ì íí ëìŒí ë°ìŽí° ìžížë„Œ ìŹì©í©ëë€. ìŹêž°ìë ê° ìŽëŻžì§ë„Œ (480, 480) íŹêž°ëĄ ìĄ°ì íêł , ìąì°ëĄ ë€ì§êł , ë°êž°ë„Œ ëìŽë ëìŒí ì ê·ŒëČì ì ì©í©ëë€:
+
+
+```py
+>>> import albumentations
+>>> import numpy as np
+>>> import torch
+
+>>> transform = albumentations.Compose(
+... [
+... albumentations.Resize(480, 480),
+... albumentations.HorizontalFlip(p=1.0),
+... albumentations.RandomBrightnessContrast(p=1.0),
+... ],
+... bbox_params=albumentations.BboxParams(format="coco", label_fields=["category"]),
+... )
+```
+
+ìŽëŻžì§ íëĄìžìë ìŽë
ží
ìŽì
ìŽ ë€ìêłŒ ê°ì íììŒ êČìŒëĄ ììí©ëë€: `{'image_id': int, 'annotations': List[Dict]}`, ìŹêž°ì ê° ëì
ë늏ë COCO ê°ìČŽ ìŽë
ží
ìŽì
ì
ëë€. ëšìŒ ìì ì ëíŽ ìŽë
ží
ìŽì
ì íìì ë€ì ì§ì íë íšì넌 ì¶ê°íŽ ëłŽêČ ì”ëë€:
+
+```py
+>>> def formatted_anns(image_id, category, area, bbox):
+... annotations = []
+... for i in range(0, len(category)):
+... new_ann = {
+... "image_id": image_id,
+... "category_id": category[i],
+... "isCrowd": 0,
+... "area": area[i],
+... "bbox": list(bbox[i]),
+... }
+... annotations.append(new_ann)
+
+... return annotations
+```
+
+ìŽì ìŽëŻžì§ì ìŽë
ží
ìŽì
ì ìČ늏 ëłíì êȰí©íìŹ ìì ë°°ìčì ìŹì©í ì ìì”ëë€:
+
+```py
+>>> # transforming a batch
+>>> def transform_aug_ann(examples):
+... image_ids = examples["image_id"]
+... images, bboxes, area, categories = [], [], [], []
+... for image, objects in zip(examples["image"], examples["objects"]):
+... image = np.array(image.convert("RGB"))[:, :, ::-1]
+... out = transform(image=image, bboxes=objects["bbox"], category=objects["category"])
+
+... area.append(objects["area"])
+... images.append(out["image"])
+... bboxes.append(out["bboxes"])
+... categories.append(out["category"])
+
+... targets = [
+... {"image_id": id_, "annotations": formatted_anns(id_, cat_, ar_, box_)}
+... for id_, cat_, ar_, box_ in zip(image_ids, categories, area, bboxes)
+... ]
+
+... return image_processor(images=images, annotations=targets, return_tensors="pt")
+```
+
+ìŽì ëšêłìì ë§ë ì ìČ늏 íšì넌 đ€ Datasetsì [`~datasets.Dataset.with_transform`] ë©ìë넌 ìŹì©íìŹ ë°ìŽí° ìžíž ì ìČŽì ì ì©í©ëë€.
+ìŽ ë©ìëë ë°ìŽí° ìžížì ìì넌 ê°ì žìŹ ëë§ë€ ì ìČ늏 íšì넌 ì ì©í©ëë€.
+
+ìŽ ìì ììë ì ìČ늏 í ë°ìŽí° ìžížìì ìì íë넌 ê°ì žìì ëłí í ëȘšììŽ ìŽë»êČ ëëì§ íìžíŽ ëłŒ ì ìì”ëë€.
+ìŽë, `pixel_values` í
ì, `pixel_mask` í
ì, ê·žëŠŹêł `labels`ëĄ ê”Źì±ë í
ìê° ììŽìŒ í©ëë€.
+
+```py
+>>> cppe5["train"] = cppe5["train"].with_transform(transform_aug_ann)
+>>> cppe5["train"][15]
+{'pixel_values': tensor([[[ 0.9132, 0.9132, 0.9132, ..., -1.9809, -1.9809, -1.9809],
+ [ 0.9132, 0.9132, 0.9132, ..., -1.9809, -1.9809, -1.9809],
+ [ 0.9132, 0.9132, 0.9132, ..., -1.9638, -1.9638, -1.9638],
+ ...,
+ [-1.5699, -1.5699, -1.5699, ..., -1.9980, -1.9980, -1.9980],
+ [-1.5528, -1.5528, -1.5528, ..., -1.9980, -1.9809, -1.9809],
+ [-1.5528, -1.5528, -1.5528, ..., -1.9980, -1.9809, -1.9809]],
+
+ [[ 1.3081, 1.3081, 1.3081, ..., -1.8431, -1.8431, -1.8431],
+ [ 1.3081, 1.3081, 1.3081, ..., -1.8431, -1.8431, -1.8431],
+ [ 1.3081, 1.3081, 1.3081, ..., -1.8256, -1.8256, -1.8256],
+ ...,
+ [-1.3179, -1.3179, -1.3179, ..., -1.8606, -1.8606, -1.8606],
+ [-1.3004, -1.3004, -1.3004, ..., -1.8606, -1.8431, -1.8431],
+ [-1.3004, -1.3004, -1.3004, ..., -1.8606, -1.8431, -1.8431]],
+
+ [[ 1.4200, 1.4200, 1.4200, ..., -1.6476, -1.6476, -1.6476],
+ [ 1.4200, 1.4200, 1.4200, ..., -1.6476, -1.6476, -1.6476],
+ [ 1.4200, 1.4200, 1.4200, ..., -1.6302, -1.6302, -1.6302],
+ ...,
+ [-1.0201, -1.0201, -1.0201, ..., -1.5604, -1.5604, -1.5604],
+ [-1.0027, -1.0027, -1.0027, ..., -1.5604, -1.5430, -1.5430],
+ [-1.0027, -1.0027, -1.0027, ..., -1.5604, -1.5430, -1.5430]]]),
+ 'pixel_mask': tensor([[1, 1, 1, ..., 1, 1, 1],
+ [1, 1, 1, ..., 1, 1, 1],
+ [1, 1, 1, ..., 1, 1, 1],
+ ...,
+ [1, 1, 1, ..., 1, 1, 1],
+ [1, 1, 1, ..., 1, 1, 1],
+ [1, 1, 1, ..., 1, 1, 1]]),
+ '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])}}
+```
+
+ê°ê°ì ìŽëŻžì§ë„Œ ì±êł”ì ìŒëĄ ìŠê°íêł ìŽëŻžì§ì ìŽë
ží
ìŽì
ì ì€ëčíì”ëë€.
+ê·žëŹë ì ìČ늏ë ìì§ ëëì§ ììì”ëë€. ë§ì§ë§ ëšêłëĄ, ìŽëŻžì§ë„Œ ë°°ìčëĄ ë§ë€ ìŹì©ì ì ì `collate_fn`ì ìì±í©ëë€.
+íŽëč ë°°ìčìì ê°ì„ í° ìŽëŻžì§ì ìŽëŻžì§(íìŹ `pixel_values` ìž)넌 íšëíêł , ì€ì íœì
(1)êłŒ íšë©(0)ì ëíëŽêž° ìíŽ ê·žì íŽëčíë ìëĄìŽ `pixel_mask`넌 ìì±íŽìŒ í©ëë€.
+
+```py
+>>> def collate_fn(batch):
+... pixel_values = [item["pixel_values"] for item in batch]
+... encoding = image_processor.pad(pixel_values, return_tensors="pt")
+... labels = [item["labels"] for item in batch]
+... batch = {}
+... batch["pixel_values"] = encoding["pixel_values"]
+... batch["pixel_mask"] = encoding["pixel_mask"]
+... batch["labels"] = labels
+... return batch
+```
+
+## DETR ëȘšëž íì”ìí€êž° [[training-the-DETR-model]]
+
+ìŽì ìčì
ìì ëë¶ë¶ì ìì
ì ìííìŹ ìŽì ëȘšëžì íì”í ì€ëčê° ëìì”ëë€!
+ìŽ ë°ìŽí° ìžížì ìŽëŻžì§ë 늏ìŹìŽìŠ íìë ìŹì í ì©ëìŽ íŹêž° ë돞ì, ìŽ ëȘšëžì ëŻžìž ìĄ°ì íë €ë©Ž ì ìŽë íëì GPUê° íìí©ëë€.
+
+íì”ì ë€ìì ëšêłë„Œ ìíí©ëë€:
+
+1. [`AutoModelForObjectDetection`]ì ìŹì©íìŹ ì ìČ늏ì ëìŒí ìČŽíŹíŹìžížë„Œ ìŹì©íìŹ ëȘšëžì ê°ì žì”ëë€.
+2. [`TrainingArguments`]ìì íì” íìŽíŒíëŒëŻží°ë„Œ ì ìí©ëë€.
+3. ëȘšëž, ë°ìŽí° ìžíž, ìŽëŻžì§ íëĄìžì ë° ë°ìŽí° ìœë ìŽí°ì íšê» [`Trainer`]ì íë š ìžì넌 ì ëŹí©ëë€.
+4. [`~Trainer.train`]넌 ížì¶íìŹ ëȘšëžì ëŻžìž ìĄ°ì í©ëë€.
+
+ì ìČ늏ì ìŹì©í ìČŽíŹíŹìžížì ëìŒí ìČŽíŹíŹìžížìì ëȘšëžì ê°ì žìŹ ë, ë°ìŽí° ìžížì ë©íë°ìŽí°ìì ë§ë `label2id`ì `id2label` ë§€íì ì ëŹíŽìŒ í©ëë€.
+ëí, `ignore_mismatched_sizes=True`넌 ì§ì íìŹ êž°ìĄŽ ë¶ë„ í€ë(ëȘšëžìì ë¶ë„ì ìŹì©ëë ë§ì§ë§ ë ìŽìŽ)넌 ì ë¶ë„ í€ëëĄ ëìČŽí©ëë€.
+
+```py
+>>> from transformers import AutoModelForObjectDetection
+
+>>> model = AutoModelForObjectDetection.from_pretrained(
+... checkpoint,
+... id2label=id2label,
+... label2id=label2id,
+... ignore_mismatched_sizes=True,
+... )
+```
+
+[`TrainingArguments`]ìì `output_dir`ì ìŹì©íìŹ ëȘšëžì ì ì„í ììč넌 ì§ì í ë€ì, íìì ë°ëŒ íìŽíŒíëŒëŻží°ë„Œ ê”Źì±íìžì.
+ìŹì©íì§ ìë ìŽì ì ê±°íì§ ìëëĄ ìŁŒìíŽìŒ í©ëë€. ë§ìœ `remove_unused_columns`ê° `True`ìŒ êČœì° ìŽëŻžì§ ìŽìŽ ìì ë©ëë€.
+ìŽëŻžì§ ìŽìŽ ìë êČœì° `pixel_values`넌 ìì±í ì ìêž° ë돞ì `remove_unused_columns`넌 `False`ëĄ ì€ì íŽìŒ í©ëë€.
+ëȘšëžì Hubì ì
ëĄëíìŹ êł”ì íë €ë©Ž `push_to_hub`넌 `True`ëĄ ì€ì íììì€(íêč
íìŽì€ì ëĄê·žìžíìŹ ëȘšëžì ì
ëĄëíŽìŒ í©ëë€).
+
+
+```py
+>>> from transformers import TrainingArguments
+
+>>> training_args = TrainingArguments(
+... output_dir="detr-resnet-50_finetuned_cppe5",
+... per_device_train_batch_size=8,
+... num_train_epochs=10,
+... fp16=True,
+... save_steps=200,
+... logging_steps=50,
+... learning_rate=1e-5,
+... weight_decay=1e-4,
+... save_total_limit=2,
+... remove_unused_columns=False,
+... push_to_hub=True,
+... )
+```
+
+ë§ì§ë§ìŒëĄ `model`, `training_args`, `collate_fn`, `image_processor`ì ë°ìŽí° ìžíž(`cppe5`)넌 ëȘšë ê°ì žìš í, [`~transformers.Trainer.train`]넌 ížì¶í©ëë€.
+
+```py
+>>> from transformers import Trainer
+
+>>> trainer = Trainer(
+... model=model,
+... args=training_args,
+... data_collator=collate_fn,
+... train_dataset=cppe5["train"],
+... tokenizer=image_processor,
+... )
+
+>>> trainer.train()
+```
+
+`training_args`ìì `push_to_hub`넌 `True`ëĄ ì€ì í êČœì°, íì” ìČŽíŹíŹìžížë íêč
íìŽì€ íëžì ì
ëĄëë©ëë€.
+íì” ìëŁ í, [`~transformers.Trainer.push_to_hub`] ë©ìë넌 ížì¶íìŹ ì”ìą
ëȘšëžì íêč
íìŽì€ íëžì ì
ëĄëí©ëë€.
+
+```py
+>>> trainer.push_to_hub()
+```
+
+## íê°íêž° [[evaluate]]
+
+ê°ìČŽ íì§ ëȘšëžì ìŒë°ì ìŒëĄ ìŒë šì COCO-ì€íìŒ ì§í ëĄ íê°ë©ëë€.
+êž°ìĄŽì ê”Źíë íê° ì§í ì€ íë넌 ìŹì©í ìë ìì§ë§, ìŹêž°ììë íêč
íìŽì€ íëžì ížìí ì”ìą
ëȘšëžì íê°íë ë° `torchvision`ìì ì êł”íë íê° ì§í넌 ìŹì©í©ëë€.
+
+`torchvision` íê°ì(evaluator)넌 ìŹì©íë €ë©Ž ì€ìžĄê°ìž COCO ë°ìŽí° ìžížë„Œ ì€ëčíŽìŒ í©ëë€.
+COCO ë°ìŽí° ìžížë„Œ ëčëíë APIë ë°ìŽí°ë„Œ íčì íììŒëĄ ì ì„íŽìŒ íëŻëĄ, 뚌ì ìŽëŻžì§ì ìŽë
ží
ìŽì
ì ëì€íŹì ì ì„íŽìŒ í©ëë€.
+íì”ì ìíŽ ë°ìŽí°ë„Œ ì€ëčí ëì ë§ì°Źê°ì§ëĄ, cppe5["test"]ììì ìŽë
ží
ìŽì
ì íŹë§·ì ë§ì¶°ìŒ í©ëë€. ê·žëŹë ìŽëŻžì§ë ê·žëëĄ ì ì§íŽìŒ í©ëë€.
+
+íê° ëšêłë ìœê°ì ìì
ìŽ íìíì§ë§, íŹêČ ìž ê°ì§ ìŁŒì ëšêłëĄ ëë ì ìì”ëë€.
+뚌ì , `cppe5["test"]` ìžížë„Œ ì€ëčí©ëë€: ìŽë
ží
ìŽì
ì íŹë§·ì ë§êČ ë§ë€êł ë°ìŽí°ë„Œ ëì€íŹì ì ì„í©ëë€.
+
+```py
+>>> import json
+
+
+>>> # format annotations the same as for training, no need for data augmentation
+>>> def val_formatted_anns(image_id, objects):
+... annotations = []
+... for i in range(0, len(objects["id"])):
+... new_ann = {
+... "id": objects["id"][i],
+... "category_id": objects["category"][i],
+... "iscrowd": 0,
+... "image_id": image_id,
+... "area": objects["area"][i],
+... "bbox": objects["bbox"][i],
+... }
+... annotations.append(new_ann)
+
+... return annotations
+
+
+>>> # Save images and annotations into the files torchvision.datasets.CocoDetection expects
+>>> def save_cppe5_annotation_file_images(cppe5):
+... output_json = {}
+... path_output_cppe5 = f"{os.getcwd()}/cppe5/"
+
+... if not os.path.exists(path_output_cppe5):
+... os.makedirs(path_output_cppe5)
+
+... path_anno = os.path.join(path_output_cppe5, "cppe5_ann.json")
+... categories_json = [{"supercategory": "none", "id": id, "name": id2label[id]} for id in id2label]
+... output_json["images"] = []
+... output_json["annotations"] = []
+... for example in cppe5:
+... ann = val_formatted_anns(example["image_id"], example["objects"])
+... output_json["images"].append(
+... {
+... "id": example["image_id"],
+... "width": example["image"].width,
+... "height": example["image"].height,
+... "file_name": f"{example['image_id']}.png",
+... }
+... )
+... output_json["annotations"].extend(ann)
+... output_json["categories"] = categories_json
+
+... with open(path_anno, "w") as file:
+... json.dump(output_json, file, ensure_ascii=False, indent=4)
+
+... for im, img_id in zip(cppe5["image"], cppe5["image_id"]):
+... path_img = os.path.join(path_output_cppe5, f"{img_id}.png")
+... im.save(path_img)
+
+... return path_output_cppe5, path_anno
+```
+
+ë€ììŒëĄ, `cocoevaluator`ì íšê» ìŹì©í ì ìë `CocoDetection` íŽëì€ì ìžì€íŽì€ë„Œ ì€ëčí©ëë€.
+
+```py
+>>> import torchvision
+
+
+>>> class CocoDetection(torchvision.datasets.CocoDetection):
+... def __init__(self, img_folder, image_processor, ann_file):
+... super().__init__(img_folder, ann_file)
+... self.image_processor = image_processor
+
+... def __getitem__(self, idx):
+... # read in PIL image and target in COCO format
+... img, target = super(CocoDetection, self).__getitem__(idx)
+
+... # preprocess image and target: converting target to DETR format,
+... # resizing + normalization of both image and target)
+... image_id = self.ids[idx]
+... target = {"image_id": image_id, "annotations": target}
+... encoding = self.image_processor(images=img, annotations=target, return_tensors="pt")
+... pixel_values = encoding["pixel_values"].squeeze() # remove batch dimension
+... target = encoding["labels"][0] # remove batch dimension
+
+... return {"pixel_values": pixel_values, "labels": target}
+
+
+>>> im_processor = AutoImageProcessor.from_pretrained("devonho/detr-resnet-50_finetuned_cppe5")
+
+>>> path_output_cppe5, path_anno = save_cppe5_annotation_file_images(cppe5["test"])
+>>> test_ds_coco_format = CocoDetection(path_output_cppe5, im_processor, path_anno)
+```
+
+ë§ì§ë§ìŒëĄ, íê° ì§í넌 ê°ì žìì íê°ë„Œ ì€íí©ëë€.
+
+```py
+>>> import evaluate
+>>> from tqdm import tqdm
+
+>>> model = AutoModelForObjectDetection.from_pretrained("devonho/detr-resnet-50_finetuned_cppe5")
+>>> module = evaluate.load("ybelkada/cocoevaluate", coco=test_ds_coco_format.coco)
+>>> val_dataloader = torch.utils.data.DataLoader(
+... test_ds_coco_format, batch_size=8, shuffle=False, num_workers=4, collate_fn=collate_fn
+... )
+
+>>> with torch.no_grad():
+... for idx, batch in enumerate(tqdm(val_dataloader)):
+... pixel_values = batch["pixel_values"]
+... pixel_mask = batch["pixel_mask"]
+
+... labels = [
+... {k: v for k, v in t.items()} for t in batch["labels"]
+... ] # these are in DETR format, resized + normalized
+
+... # forward pass
+... outputs = model(pixel_values=pixel_values, pixel_mask=pixel_mask)
+
+... orig_target_sizes = torch.stack([target["orig_size"] for target in labels], dim=0)
+... results = im_processor.post_process(outputs, orig_target_sizes) # convert outputs of model to COCO api
+
+... module.add(prediction=results, reference=labels)
+... del batch
+
+>>> results = module.compute()
+>>> print(results)
+Accumulating evaluation results...
+DONE (t=0.08s).
+IoU metric: bbox
+ Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.352
+ Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.681
+ Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.292
+ Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.168
+ Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.208
+ Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.429
+ Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.274
+ Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.484
+ Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.501
+ Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.191
+ Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.323
+ Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.590
+```
+
+ìŽëŹí êČ°êłŒë [`~transformers.TrainingArguments`]ì íìŽíŒíëŒëŻží°ë„Œ ìĄ°ì íìŹ ëì± ê°ì ë ì ìì”ëë€. íëČ ìëíŽ ëłŽìžì!
+
+## ì¶ëĄ íêž° [[inference]]
+
+DETR ëȘšëžì ëŻžìž ìĄ°ì ë° íê°íêł , íêč
íìŽì€ íëžì ì
ëĄë íìŒëŻëĄ ì¶ëĄ ì ìŹì©í ì ìì”ëë€.
+
+ëŻžìž ìĄ°ì ë ëȘšëžì ì¶ëĄ ì ìŹì©íë ê°ì„ ê°ëší ë°©ëČì [`pipeline`]ìì ëȘšëžì ìŹì©íë êČì
ëë€.
+ëȘšëžêłŒ íšê» ê°ìČŽ íì§ë„Œ ìí íìŽíëŒìžì ìžì€íŽì€ííêł , ìŽëŻžì§ë„Œ ì ëŹíìžì:
+
+```py
+>>> from transformers import pipeline
+>>> import requests
+
+>>> url = "https://i.imgur.com/2lnWoly.jpg"
+>>> image = Image.open(requests.get(url, stream=True).raw)
+
+>>> obj_detector = pipeline("object-detection", model="devonho/detr-resnet-50_finetuned_cppe5")
+>>> obj_detector(image)
+```
+
+ë§ìœ ìíë€ë©Ž ìëìŒëĄ `pipeline`ì êČ°êłŒë„Œ ìŹíí ì ìì”ëë€:
+
+```py
+>>> image_processor = AutoImageProcessor.from_pretrained("devonho/detr-resnet-50_finetuned_cppe5")
+>>> model = AutoModelForObjectDetection.from_pretrained("devonho/detr-resnet-50_finetuned_cppe5")
+
+>>> with torch.no_grad():
+... inputs = image_processor(images=image, return_tensors="pt")
+... outputs = model(**inputs)
+... target_sizes = torch.tensor([image.size[::-1]])
+... results = image_processor.post_process_object_detection(outputs, threshold=0.5, target_sizes=target_sizes)[0]
+
+>>> for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
+... box = [round(i, 2) for i in box.tolist()]
+... print(
+... f"Detected {model.config.id2label[label.item()]} with confidence "
+... f"{round(score.item(), 3)} at location {box}"
+... )
+Detected Coverall with confidence 0.566 at location [1215.32, 147.38, 4401.81, 3227.08]
+Detected Mask with confidence 0.584 at location [2449.06, 823.19, 3256.43, 1413.9]
+```
+
+êČ°êłŒë„Œ ìê°ííêČ ì”ëë€:
+```py
+>>> draw = ImageDraw.Draw(image)
+
+>>> for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
+... box = [round(i, 2) for i in box.tolist()]
+... x, y, x2, y2 = tuple(box)
+... draw.rectangle((x, y, x2, y2), outline="red", width=1)
+... draw.text((x, y), model.config.id2label[label.item()], fill="white")
+
+>>> image
+```
+
+
+
+
diff --git a/docs/source/ko/tasks/question_answering.md b/docs/source/ko/tasks/question_answering.md
new file mode 100644
index 000000000000..4b218ccce214
--- /dev/null
+++ b/docs/source/ko/tasks/question_answering.md
@@ -0,0 +1,428 @@
+
+
+# ì§ì ìë”(Question Answering)[[question-answering]]
+
+[[open-in-colab]]
+
+
+
+ì§ì ìë” íì€íŹë ìŁŒìŽì§ ì§ëŹžì ëí ë”ëłì ì êł”í©ëë€. Alexa, Siri ëë GoogleêłŒ ê°ì ê°ì ëčììêČ ë ìšê° ìŽë€ì§ ëŹŒìŽëłž ì ìŽ ìë€ë©Ž ì§ì ìë” ëȘšëžì ìŹì©íŽëłž ì ìŽ ìì êČì
ëë€. ì§ì ìë” íì€íŹìë ìŒë°ì ìŒëĄ ë ê°ì§ ì íìŽ ìì”ëë€.
+
+- ì¶ì¶ì (Extractive) ì§ì ìë”: ìŁŒìŽì§ 돞맄ìì ë”ëłì ì¶ì¶í©ëë€.
+- ìì±ì (Abstractive) ì§ì ìë”: 돞맄ìì ì§ëŹžì ìŹë°ë„ŽêČ ë”íë ë”ëłì ìì±í©ëë€.
+
+ìŽ ê°ìŽëë ë€ìêłŒ ê°ì ë°©ëČë€ì 볎ìŹì€ëë€.
+
+1. ì¶ì¶ì ì§ì ìë”ì íêž° ìíŽ [SQuAD](https://huggingface.co/datasets/squad) ë°ìŽí° ìžížìì [DistilBERT](https://huggingface.co/distilbert-base-uncased) ëŻžìž ìĄ°ì íêž°
+2. ì¶ëĄ ì ëŻžìž ìĄ°ì ë ëȘšëž ìŹì©íêž°
+
+
+ìŽ íí 늏ìŒìì ì€ëȘ
íë íì€íŹë ë€ìêłŒ ê°ì ëȘšëž ìí€í
ìČìì ì§ìë©ëë€.
+
+
+
+[ALBERT](../model_doc/albert), [BART](../model_doc/bart), [BERT](../model_doc/bert), [BigBird](../model_doc/big_bird), [BigBird-Pegasus](../model_doc/bigbird_pegasus), [BLOOM](../model_doc/bloom), [CamemBERT](../model_doc/camembert), [CANINE](../model_doc/canine), [ConvBERT](../model_doc/convbert), [Data2VecText](../model_doc/data2vec-text), [DeBERTa](../model_doc/deberta), [DeBERTa-v2](../model_doc/deberta-v2), [DistilBERT](../model_doc/distilbert), [ELECTRA](../model_doc/electra), [ERNIE](../model_doc/ernie), [ErnieM](../model_doc/ernie_m), [FlauBERT](../model_doc/flaubert), [FNet](../model_doc/fnet), [Funnel Transformer](../model_doc/funnel), [GPT-J](../model_doc/gptj), [I-BERT](../model_doc/ibert), [LayoutLMv2](../model_doc/layoutlmv2), [LayoutLMv3](../model_doc/layoutlmv3), [LED](../model_doc/led), [LiLT](../model_doc/lilt), [Longformer](../model_doc/longformer), [LUKE](../model_doc/luke), [LXMERT](../model_doc/lxmert), [MarkupLM](../model_doc/markuplm), [mBART](../model_doc/mbart), [MEGA](../model_doc/mega), [Megatron-BERT](../model_doc/megatron-bert), [MobileBERT](../model_doc/mobilebert), [MPNet](../model_doc/mpnet), [MVP](../model_doc/mvp), [Nezha](../model_doc/nezha), [Nyströmformer](../model_doc/nystromformer), [OPT](../model_doc/opt), [QDQBert](../model_doc/qdqbert), [Reformer](../model_doc/reformer), [RemBERT](../model_doc/rembert), [RoBERTa](../model_doc/roberta), [RoBERTa-PreLayerNorm](../model_doc/roberta-prelayernorm), [RoCBert](../model_doc/roc_bert), [RoFormer](../model_doc/roformer), [Splinter](../model_doc/splinter), [SqueezeBERT](../model_doc/squeezebert), [XLM](../model_doc/xlm), [XLM-RoBERTa](../model_doc/xlm-roberta), [XLM-RoBERTa-XL](../model_doc/xlm-roberta-xl), [XLNet](../model_doc/xlnet), [X-MOD](../model_doc/xmod), [YOSO](../model_doc/yoso)
+
+
+
+
+
+
+ììíêž° ì ì, íìí ëŒìŽëžëŹëŠŹê° ëȘšë ì€ìčëìŽ ìëì§ íìžíìžì:
+
+```bash
+pip install transformers datasets evaluate
+```
+
+ìŹëŹë¶ì ëȘšëžì ì
ëĄëíêł ì»€ëź€ëí°ì êł”ì í ì ìëëĄ Hugging Face êłì ì ëĄê·žìžíë êČìŽ ìąì”ëë€. ë©ìì§ê° íìë멎 í í°ì ì
ë „íŽì ëĄê·žìží©ëë€:
+
+```py
+>>> from huggingface_hub import notebook_login
+
+>>> notebook_login()
+```
+
+## SQuAD ë°ìŽí° ìžíž ê°ì žì€êž°[[load-squad-dataset]]
+
+뚌ì đ€ Datasets ëŒìŽëžëŹëŠŹìì SQuAD ë°ìŽí° ìžížì ìŒë¶ë„Œ ê°ì žì”ëë€. ìŽë êČ í멎 ì ìČŽ ë°ìŽí° ìžížëĄ íë šíë©° ë ë§ì ìê°ì í ì íêž° ì ì ëȘšë êČìŽ ì ìëíëì§ ì€ííêł íìží ì ìì”ëë€.
+
+```py
+>>> from datasets import load_dataset
+
+>>> squad = load_dataset("squad", split="train[:5000]")
+```
+
+ë°ìŽí° ìžížì ë¶í ë `train`ì [`~datasets.Dataset.train_test_split`] ë©ìë넌 ìŹì©íŽ íë š ë°ìŽí° ìžížì í
ì€íž ë°ìŽí° ìžížëĄ ëëìŽì€ëë€:
+
+```py
+>>> squad = squad.train_test_split(test_size=0.2)
+```
+
+ê·žëŠŹêł ëì ììëĄ ë°ìŽí°ë„Œ íë ìŽíŽëŽ
ëë€:
+
+```py
+>>> squad["train"][0]
+{'answers': {'answer_start': [515], 'text': ['Saint Bernadette Soubirous']},
+ '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.',
+ 'id': '5733be284776f41900661182',
+ 'question': 'To whom did the Virgin Mary allegedly appear in 1858 in Lourdes France?',
+ 'title': 'University_of_Notre_Dame'
+}
+```
+
+ìŽ ì€ìì ëȘ ê°ì§ ì€ìí íëȘ©ìŽ ìì”ëë€:
+
+- `answers`: ë”ì í í°ì ìì ììčì ë”ì í
ì€íž
+- `context`: ëȘšëžìŽ ë”ì ì¶ì¶íëë° íìí ë°°êČœ ì§ì
+- `question`: ëȘšëžìŽ ë”íŽìŒ íë ì§ëŹž
+
+## ì ìČ늏[[preprocess]]
+
+
+
+ë€ì ëšêłììë `question` ë° `context` íëȘ©ì ìČ늏íêž° ìíŽ DistilBERT í íŹëìŽì 넌 ê°ì žì”ëë€:
+
+```py
+>>> from transformers import AutoTokenizer
+
+>>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
+```
+
+ì§ì ìë” íì€íŹì êŽë šíŽì íčí ì ìíŽìŒí ëȘ ê°ì§ ì ìČ늏 ëšêłê° ìì”ëë€:
+
+1. ë°ìŽí° ìžížì ìŒë¶ ìì ìë ëȘšëžì ì”ë ì
ë „ êžžìŽë„Œ ìŽêłŒíë ë§€ì° êžŽ `context`ê° ìì ì ìì”ëë€. ꞎ ìíì€ë„Œ ë€ëŁšêž° ìíŽìë, `truncation="only_second"`ëĄ ì€ì íŽ `context`ë§ ìëŒëŽë©Ž ë©ëë€.
+2. ê·ž ë€ì, `return_offset_mapping=True`ëĄ ì€ì íŽ ë”ëłì ììêłŒ ìą
ëŁ ììč넌 ìëì `context`ì ë§€íí©ëë€.
+3. ë§€íì ìëŁí멎, ìŽì ë”ëłìì ìì í í°êłŒ ìą
ëŁ í í°ì ì°Ÿì ì ìì”ëë€. ì€íì
ì ìŽë ë¶ë¶ìŽ `question`êłŒ `context`ì íŽëčíëì§ ì°Ÿì ì ìëëĄ [`~tokenizers.Encoding.sequence_ids`] ë©ìë넌 ìŹì©íìžì.
+
+ë€ìì `answer`ì ìì í í°êłŒ ìą
ëŁ í í°ì ìëŒëŽì `context`ì ë§€ííë íšì넌 ë§ëë ë°©ëČì
ëë€:
+
+```py
+>>> def preprocess_function(examples):
+... questions = [q.strip() for q in examples["question"]]
+... inputs = tokenizer(
+... questions,
+... examples["context"],
+... max_length=384,
+... truncation="only_second",
+... return_offsets_mapping=True,
+... padding="max_length",
+... )
+
+... offset_mapping = inputs.pop("offset_mapping")
+... answers = examples["answers"]
+... start_positions = []
+... end_positions = []
+
+... for i, offset in enumerate(offset_mapping):
+... answer = answers[i]
+... start_char = answer["answer_start"][0]
+... end_char = answer["answer_start"][0] + len(answer["text"][0])
+... sequence_ids = inputs.sequence_ids(i)
+
+... # Find the start and end of the context
+... idx = 0
+... while sequence_ids[idx] != 1:
+... idx += 1
+... context_start = idx
+... while sequence_ids[idx] == 1:
+... idx += 1
+... context_end = idx - 1
+
+... # If the answer is not fully inside the context, label it (0, 0)
+... if offset[context_start][0] > end_char or offset[context_end][1] < start_char:
+... start_positions.append(0)
+... end_positions.append(0)
+... else:
+... # Otherwise it's the start and end token positions
+... idx = context_start
+... while idx <= context_end and offset[idx][0] <= start_char:
+... idx += 1
+... start_positions.append(idx - 1)
+
+... idx = context_end
+... while idx >= context_start and offset[idx][1] >= end_char:
+... idx -= 1
+... end_positions.append(idx + 1)
+
+... inputs["start_positions"] = start_positions
+... inputs["end_positions"] = end_positions
+... return inputs
+```
+
+ëȘšë ë°ìŽí° ìžížì ì ìČëŠŹë„Œ ì ì©íë €ë©Ž, đ€ Datasets [`~datasets.Dataset.map`] íšì넌 ìŹì©íìžì. `batched=True`ëĄ ì€ì íŽ ë°ìŽí° ìžížì ìŹëŹ ììë€ì í ëČì ìČ늏í멎 `map` íšìì ìë넌 ëč 넎êČ í ì ìì”ëë€. íìíì§ ìì ìŽì ëȘšë ì ê±°í©ëë€:
+
+```py
+>>> tokenized_squad = squad.map(preprocess_function, batched=True, remove_columns=squad["train"].column_names)
+```
+
+ìŽì [`DefaultDataCollator`]넌 ìŽì©íŽ ìì ë°°ìč넌 ìì±í©ëë€. đ€ Transformersì ë€ë„ž ë°ìŽí° ìœë ìŽí°(data collator)ì ëŹëŠŹ, [`DefaultDataCollator`]ë íšë©êłŒ ê°ì ì¶ê° ì ìČëŠŹë„Œ ì ì©íì§ ìì”ëë€:
+
+
+
+```py
+>>> from transformers import DefaultDataCollator
+
+>>> data_collator = DefaultDataCollator()
+```
+
+
+```py
+>>> from transformers import DefaultDataCollator
+
+>>> data_collator = DefaultDataCollator(return_tensors="tf")
+```
+
+
+
+## íë š[[train]]
+
+
+
+
+
+[`Trainer`]넌 ìŽì©íŽ ëȘšëžì ëŻžìž ìĄ°ì íë êČì ì”ìíì§ ìë€ë©Ž, [ìŹêž°](../training#train-with-pytorch-trainer)ìì êž°ìŽ íí 늏ìŒì ìŽíŽëłŽìžì!
+
+
+
+ìŽì ëȘšëž íë šì ììí ì€ëčê° ëìì”ëë€! [`AutoModelForQuestionAnswering`]ìŒëĄ DistilBERT넌 ê°ì žì”ëë€:
+
+```py
+>>> from transformers import AutoModelForQuestionAnswering, TrainingArguments, Trainer
+
+>>> model = AutoModelForQuestionAnswering.from_pretrained("distilbert-base-uncased")
+```
+
+ìŽì ìž ëšêłë§ ëšìì”ëë€:
+
+1. [`TrainingArguments`]ìì íë š íìŽíŒíëŒëŻží°ë„Œ ì í©ëë€. êŒ íìí ë§€ê°ëłìë ëȘšëžì ì ì„í ììč넌 ì§ì íë `output_dir` ì
ëë€. `push_to_hub=True`ëĄ ì€ì íŽì ìŽ ëȘšëžì HubëĄ ížìí©ëë€ (ëȘšëžì ì
ëĄëíë €ë©Ž Hugging Faceì ëĄê·žìžíŽìŒ í©ëë€).
+2. ëȘšëž, ë°ìŽí° ìžíž, í íŹëìŽì , ë°ìŽí° ìœë ìŽí°ì íšê» [`Trainer`]ì íë š ìžìë€ì ì ëŹí©ëë€.
+3. [`~Trainer.train`]ì ížì¶íŽì ëȘšëžì ëŻžìž ìĄ°ì í©ëë€.
+
+```py
+>>> training_args = TrainingArguments(
+... output_dir="my_awesome_qa_model",
+... evaluation_strategy="epoch",
+... learning_rate=2e-5,
+... per_device_train_batch_size=16,
+... per_device_eval_batch_size=16,
+... num_train_epochs=3,
+... weight_decay=0.01,
+... push_to_hub=True,
+... )
+
+>>> trainer = Trainer(
+... model=model,
+... args=training_args,
+... train_dataset=tokenized_squad["train"],
+... eval_dataset=tokenized_squad["test"],
+... tokenizer=tokenizer,
+... data_collator=data_collator,
+... )
+
+>>> trainer.train()
+```
+
+íë šìŽ ìëŁë멎, [`~transformers.Trainer.push_to_hub`] ë§€ìë넌 ìŹì©íŽ ëȘšëžì Hubì êł”ì íŽì ëȘšë ìŹëë€ìŽ ìŹì©í ì ìêČ êł”ì íŽìŁŒìžì:
+
+```py
+>>> trainer.push_to_hub()
+```
+
+
+
+
+KerasëĄ ëȘšëžì ëŻžìž ìĄ°ì íë êČì ì”ìíì§ ìë€ë©Ž, [ìŹêž°](../training#train-a-tensorflow-model-with-keras)ìì êž°ìŽ íí 늏ìŒì ìŽíŽëłŽìžì!
+
+
+TensorFlow넌 ìŽì©í ëȘšëžì ëŻžìž ìĄ°ì íë €ë©Ž ì”í°ë§ìŽì íšì, íì”ë„ ì€ìŒì„Ž ë° ëȘ ê°ì§ íë š íìŽíŒíëŒëŻží°ë„Œ ì€ì íë êČë¶í° ììíŽìŒí©ëë€:
+
+```py
+>>> from transformers import create_optimizer
+
+>>> batch_size = 16
+>>> num_epochs = 2
+>>> total_train_steps = (len(tokenized_squad["train"]) // batch_size) * num_epochs
+>>> optimizer, schedule = create_optimizer(
+... init_lr=2e-5,
+... num_warmup_steps=0,
+... num_train_steps=total_train_steps,
+... )
+```
+
+ê·ž ë€ì [`TFAutoModelForQuestionAnswering`]ìŒëĄ DistilBERT넌 ê°ì žì”ëë€:
+
+```py
+>>> from transformers import TFAutoModelForQuestionAnswering
+
+>>> model = TFAutoModelForQuestionAnswering("distilbert-base-uncased")
+```
+
+[`~transformers.TFPreTrainedModel.prepare_tf_dataset`]ì ìŹì©íŽì ë°ìŽí° ìžížë„Œ `tf.data.Dataset` íììŒëĄ ëłíí©ëë€:
+
+```py
+>>> tf_train_set = model.prepare_tf_dataset(
+... tokenized_squad["train"],
+... shuffle=True,
+... batch_size=16,
+... collate_fn=data_collator,
+... )
+
+>>> tf_validation_set = model.prepare_tf_dataset(
+... tokenized_squad["test"],
+... shuffle=False,
+... batch_size=16,
+... collate_fn=data_collator,
+... )
+```
+
+[`compile`](https://keras.io/api/models/model_training_apis/#compile-method)ëĄ íë ší ëȘšëžì ì€ì í©ëë€:
+
+```py
+>>> import tensorflow as tf
+
+>>> model.compile(optimizer=optimizer)
+```
+
+ë§ì§ë§ìŒëĄ ëȘšëžì HubëĄ ížìí ë°©ëČì ì€ì í©ëë€. [`~transformers.PushToHubCallback`]ìì ëȘšëžêłŒ í íŹëìŽì 넌 ížìí êČœëĄë„Œ ì€ì í©ëë€:
+
+```py
+>>> from transformers.keras_callbacks import PushToHubCallback
+
+>>> callback = PushToHubCallback(
+... output_dir="my_awesome_qa_model",
+... tokenizer=tokenizer,
+... )
+```
+
+ëëìŽ ëȘšëž íë šì ììí ì€ëčê° ëìì”ëë€! íë š ë°ìŽí° ìžížì íê° ë°ìŽí° ìžíž, ìí ì, ìœë°±ì ì€ì í í [`fit`](https://keras.io/api/models/model_training_apis/#fit-method)ì ìŽì©íŽ ëȘšëžì ëŻžìž ìĄ°ì í©ëë€:
+
+```py
+>>> model.fit(x=tf_train_set, validation_data=tf_validation_set, epochs=3, callbacks=[callback])
+```
+íë šìŽ ìëŁë멎 ëȘšëžìŽ ìëìŒëĄ Hubì ì
ëĄëëìŽ ëê”Źë ìŹì©í ì ìì”ëë€!
+
+
+
+
+
+ì§ì ìë”ì ìíŽ ëȘšëžì ëŻžìž ìĄ°ì íë ë°©ëČì ëí ë ììží ììë [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)ì ì°žìĄ°íìžì.
+
+
+
+## íê°[[evaluate]]
+
+ì§ì ìë”ì íê°íë €ë©Ž ìëčí ìì íìČëŠŹê° íìí©ëë€. ìê°ìŽ ë돎 ë§ìŽ ê±žëŠŹì§ ìëëĄ ìŽ ê°ìŽëììë íê° ëšêłë„Œ ìë”í©ëë€. [`Trainer`]ë íë š êłŒì ìì íê° ìì€(evaluation loss)ì êłì êłì°íêž° ë돞ì ëȘšëžì ì±ë„ì ëë”ì ìŒëĄ ì ì ìì”ëë€.
+
+ìê°ì ìŹì ê° ìêł ì§ì ìë” ëȘšëžì íê°íë ë°©ëČì êŽìŹìŽ ìë€ë©Ž đ€ Hugging Face Courseì [Question answering](https://huggingface.co/course/chapter7/7?fw=pt#postprocessing) ì±í°ë„Œ ìŽíŽëłŽìžì!
+
+## ì¶ëĄ [[inference]]
+
+ìŽì ëȘšëžì ëŻžìž ìĄ°ì íìŒë ì¶ëĄ ì ìŹì©í ì ìì”ëë€!
+
+ì§ëŹžêłŒ ëȘšëžìŽ ììžĄíêž° ìíë 돞맄(context)넌 ìê°íŽëłŽìžì:
+
+```py
+>>> question = "How many programming languages does BLOOM support?"
+>>> context = "BLOOM has 176 billion parameters and can generate text in 46 languages natural languages and 13 programming languages."
+```
+
+ì¶ëĄ ì ìíŽ ëŻžìž ìĄ°ì í ëȘšëžì í
ì€ížíë ê°ì„ ìŹìŽ ë°©ëČì [`pipeline`]ì ìŹì©íë êČ ì
ëë€. ëȘšëžì ìŹì©íŽ ì§ì ìë”ì íêž° ìíŽì `pipeline`ì ìžì€íŽì€ííêł í
ì€ížë„Œ ì
ë „í©ëë€:
+
+```py
+>>> from transformers import pipeline
+
+>>> question_answerer = pipeline("question-answering", model="my_awesome_qa_model")
+>>> question_answerer(question=question, context=context)
+{'score': 0.2058267742395401,
+ 'start': 10,
+ 'end': 95,
+ 'answer': '176 billion parameters and can generate text in 46 languages natural languages and 13'}
+```
+
+ìíë€ë©Ž `pipeline`ì êČ°êłŒë„Œ ì§ì ëł”ì í ìë ìì”ëë€:
+
+
+
+í
ì€ížë„Œ í í°ííŽì PyTorch í
ì넌 ë°íí©ëë€:
+
+```py
+>>> from transformers import AutoTokenizer
+
+>>> tokenizer = AutoTokenizer.from_pretrained("my_awesome_qa_model")
+>>> inputs = tokenizer(question, context, return_tensors="pt")
+```
+
+ëȘšëžì ì
ë „ì ì ëŹíêł `logits`ì ë°íí©ëë€:
+
+```py
+>>> from transformers import AutoModelForQuestionAnswering
+
+>>> model = AutoModelForQuestionAnswering.from_pretrained("my_awesome_qa_model")
+>>> with torch.no_grad():
+... outputs = model(**inputs)
+```
+
+ëȘšëžì ì¶ë „ìì ìì ë° ìą
ëŁ ììčê° ìŽëì§ ê°ì„ ëì íë„ ì ì»ì”ëë€:
+
+```py
+>>> answer_start_index = outputs.start_logits.argmax()
+>>> answer_end_index = outputs.end_logits.argmax()
+```
+
+ììžĄë í í°ì íŽë
íŽì ë”ì ì»ì”ëë€:
+
+```py
+>>> predict_answer_tokens = inputs.input_ids[0, answer_start_index : answer_end_index + 1]
+>>> tokenizer.decode(predict_answer_tokens)
+'176 billion parameters and can generate text in 46 languages natural languages and 13'
+```
+
+
+í
ì€ížë„Œ í í°ííŽì TensorFlow í
ì넌 ë°íí©ëë€:
+
+```py
+>>> from transformers import AutoTokenizer
+
+>>> tokenizer = AutoTokenizer.from_pretrained("my_awesome_qa_model")
+>>> inputs = tokenizer(question, text, return_tensors="tf")
+```
+
+ëȘšëžì ì
ë „ì ì ëŹíêł `logits`ì ë°íí©ëë€:
+
+```py
+>>> from transformers import TFAutoModelForQuestionAnswering
+
+>>> model = TFAutoModelForQuestionAnswering.from_pretrained("my_awesome_qa_model")
+>>> outputs = model(**inputs)
+```
+
+ëȘšëžì ì¶ë „ìì ìì ë° ìą
ëŁ ììčê° ìŽëì§ ê°ì„ ëì íë„ ì ì»ì”ëë€:
+
+```py
+>>> answer_start_index = int(tf.math.argmax(outputs.start_logits, axis=-1)[0])
+>>> answer_end_index = int(tf.math.argmax(outputs.end_logits, axis=-1)[0])
+```
+
+ììžĄë í í°ì íŽë
íŽì ë”ì ì»ì”ëë€:
+
+```py
+>>> predict_answer_tokens = inputs.input_ids[0, answer_start_index : answer_end_index + 1]
+>>> tokenizer.decode(predict_answer_tokens)
+'176 billion parameters and can generate text in 46 languages natural languages and 13'
+```
+
+
diff --git a/docs/source/ko/tasks/question_answering.mdx b/docs/source/ko/tasks/question_answering.mdx
deleted file mode 100644
index 602d1b71be0a..000000000000
--- a/docs/source/ko/tasks/question_answering.mdx
+++ /dev/null
@@ -1,424 +0,0 @@
-
-
-# ì§ì ìë”(Question Answering)[[question-answering]]
-
-[[open-in-colab]]
-
-
-
-ì§ì ìë” íì€íŹë ìŁŒìŽì§ ì§ëŹžì ëí ë”ëłì ì êł”í©ëë€. Alexa, Siri ëë GoogleêłŒ ê°ì ê°ì ëčììêČ ë ìšê° ìŽë€ì§ ëŹŒìŽëłž ì ìŽ ìë€ë©Ž ì§ì ìë” ëȘšëžì ìŹì©íŽëłž ì ìŽ ìì êČì
ëë€. ì§ì ìë” íì€íŹìë ìŒë°ì ìŒëĄ ë ê°ì§ ì íìŽ ìì”ëë€.
-
-- ì¶ì¶ì (Extractive) ì§ì ìë”: ìŁŒìŽì§ 돞맄ìì ë”ëłì ì¶ì¶í©ëë€.
-- ìì±ì (Abstractive) ì§ì ìë”: 돞맄ìì ì§ëŹžì ìŹë°ë„ŽêČ ë”íë ë”ëłì ìì±í©ëë€.
-
-ìŽ ê°ìŽëë ë€ìêłŒ ê°ì ë°©ëČë€ì 볎ìŹì€ëë€.
-
-1. ì¶ì¶ì ì§ì ìë”ì íêž° ìíŽ [SQuAD](https://huggingface.co/datasets/squad) ë°ìŽí° ìžížìì [DistilBERT](https://huggingface.co/distilbert-base-uncased) ëŻžìž ìĄ°ì íêž°
-2. ì¶ëĄ ì ëŻžìž ìĄ°ì ë ëȘšëž ìŹì©íêž°
-
-
-ìŽ íí 늏ìŒìì ì€ëȘ
íë íì€íŹë ë€ìêłŒ ê°ì ëȘšëž ìí€í
ìČìì ì§ìë©ëë€.
-
-
-
-[ALBERT](../model_doc/albert), [BART](../model_doc/bart), [BERT](../model_doc/bert), [BigBird](../model_doc/big_bird), [BigBird-Pegasus](../model_doc/bigbird_pegasus), [BLOOM](../model_doc/bloom), [CamemBERT](../model_doc/camembert), [CANINE](../model_doc/canine), [ConvBERT](../model_doc/convbert), [Data2VecText](../model_doc/data2vec-text), [DeBERTa](../model_doc/deberta), [DeBERTa-v2](../model_doc/deberta-v2), [DistilBERT](../model_doc/distilbert), [ELECTRA](../model_doc/electra), [ERNIE](../model_doc/ernie), [ErnieM](../model_doc/ernie_m), [FlauBERT](../model_doc/flaubert), [FNet](../model_doc/fnet), [Funnel Transformer](../model_doc/funnel), [GPT-J](../model_doc/gptj), [I-BERT](../model_doc/ibert), [LayoutLMv2](../model_doc/layoutlmv2), [LayoutLMv3](../model_doc/layoutlmv3), [LED](../model_doc/led), [LiLT](../model_doc/lilt), [Longformer](../model_doc/longformer), [LUKE](../model_doc/luke), [LXMERT](../model_doc/lxmert), [MarkupLM](../model_doc/markuplm), [mBART](../model_doc/mbart), [MEGA](../model_doc/mega), [Megatron-BERT](../model_doc/megatron-bert), [MobileBERT](../model_doc/mobilebert), [MPNet](../model_doc/mpnet), [MVP](../model_doc/mvp), [Nezha](../model_doc/nezha), [Nyströmformer](../model_doc/nystromformer), [OPT](../model_doc/opt), [QDQBert](../model_doc/qdqbert), [Reformer](../model_doc/reformer), [RemBERT](../model_doc/rembert), [RoBERTa](../model_doc/roberta), [RoBERTa-PreLayerNorm](../model_doc/roberta-prelayernorm), [RoCBert](../model_doc/roc_bert), [RoFormer](../model_doc/roformer), [Splinter](../model_doc/splinter), [SqueezeBERT](../model_doc/squeezebert), [XLM](../model_doc/xlm), [XLM-RoBERTa](../model_doc/xlm-roberta), [XLM-RoBERTa-XL](../model_doc/xlm-roberta-xl), [XLNet](../model_doc/xlnet), [X-MOD](../model_doc/xmod), [YOSO](../model_doc/yoso)
-
-
-
-
-
-
-ììíêž° ì ì, íìí ëŒìŽëžëŹëŠŹê° ëȘšë ì€ìčëìŽ ìëì§ íìžíìžì:
-
-```bash
-pip install transformers datasets evaluate
-```
-
-ìŹëŹë¶ì ëȘšëžì ì
ëĄëíêł ì»€ëź€ëí°ì êł”ì í ì ìëëĄ Hugging Face êłì ì ëĄê·žìžíë êČìŽ ìąì”ëë€. ë©ìì§ê° íìë멎 í í°ì ì
ë „íŽì ëĄê·žìží©ëë€:
-
-```py
->>> from huggingface_hub import notebook_login
-
->>> notebook_login()
-```
-
-## SQuAD ë°ìŽí° ìžíž ê°ì žì€êž°[[load-squad-dataset]]
-
-뚌ì đ€ Datasets ëŒìŽëžëŹëŠŹìì SQuAD ë°ìŽí° ìžížì ìŒë¶ë„Œ ê°ì žì”ëë€. ìŽë êČ í멎 ì ìČŽ ë°ìŽí° ìžížëĄ íë šíë©° ë ë§ì ìê°ì í ì íêž° ì ì ëȘšë êČìŽ ì ìëíëì§ ì€ííêł íìží ì ìì”ëë€.
-
-```py
->>> from datasets import load_dataset
-
->>> squad = load_dataset("squad", split="train[:5000]")
-```
-
-ë°ìŽí° ìžížì ë¶í ë `train`ì [`~datasets.Dataset.train_test_split`] ë©ìë넌 ìŹì©íŽ íë š ë°ìŽí° ìžížì í
ì€íž ë°ìŽí° ìžížëĄ ëëìŽì€ëë€:
-
-```py
->>> squad = squad.train_test_split(test_size=0.2)
-```
-
-ê·žëŠŹêł ëì ììëĄ ë°ìŽí°ë„Œ íë ìŽíŽëŽ
ëë€:
-
-```py
->>> squad["train"][0]
-{'answers': {'answer_start': [515], 'text': ['Saint Bernadette Soubirous']},
- '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.',
- 'id': '5733be284776f41900661182',
- 'question': 'To whom did the Virgin Mary allegedly appear in 1858 in Lourdes France?',
- 'title': 'University_of_Notre_Dame'
-}
-```
-
-ìŽ ì€ìì ëȘ ê°ì§ ì€ìí íëȘ©ìŽ ìì”ëë€:
-
-- `answers`: ë”ì í í°ì ìì ììčì ë”ì í
ì€íž
-- `context`: ëȘšëžìŽ ë”ì ì¶ì¶íëë° íìí ë°°êČœ ì§ì
-- `question`: ëȘšëžìŽ ë”íŽìŒ íë ì§ëŹž
-
-## ì ìČ늏[[preprocess]]
-
-
-
-ë€ì ëšêłììë `question` ë° `context` íëȘ©ì ìČ늏íêž° ìíŽ DistilBERT í íŹëìŽì 넌 ê°ì žì”ëë€:
-
-```py
->>> from transformers import AutoTokenizer
-
->>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
-```
-
-ì§ì ìë” íì€íŹì êŽë šíŽì íčí ì ìíŽìŒí ëȘ ê°ì§ ì ìČ늏 ëšêłê° ìì”ëë€:
-
-1. ë°ìŽí° ìžížì ìŒë¶ ìì ìë ëȘšëžì ì”ë ì
ë „ êžžìŽë„Œ ìŽêłŒíë ë§€ì° êžŽ `context`ê° ìì ì ìì”ëë€. ꞎ ìíì€ë„Œ ë€ëŁšêž° ìíŽìë, `truncation="only_second"`ëĄ ì€ì íŽ `context`ë§ ìëŒëŽë©Ž ë©ëë€.
-2. ê·ž ë€ì, `return_offset_mapping=True`ëĄ ì€ì íŽ ë”ëłì ììêłŒ ìą
ëŁ ììč넌 ìëì `context`ì ë§€íí©ëë€.
-3. ë§€íì ìëŁí멎, ìŽì ë”ëłìì ìì í í°êłŒ ìą
ëŁ í í°ì ì°Ÿì ì ìì”ëë€. ì€íì
ì ìŽë ë¶ë¶ìŽ `question`êłŒ `context`ì íŽëčíëì§ ì°Ÿì ì ìëëĄ [`~tokenizers.Encoding.sequence_ids`] ë©ìë넌 ìŹì©íìžì.
-
-ë€ìì `answer`ì ìì í í°êłŒ ìą
ëŁ í í°ì ìëŒëŽì `context`ì ë§€ííë íšì넌 ë§ëë ë°©ëČì
ëë€:
-
-```py
->>> def preprocess_function(examples):
-... questions = [q.strip() for q in examples["question"]]
-... inputs = tokenizer(
-... questions,
-... examples["context"],
-... max_length=384,
-... truncation="only_second",
-... return_offsets_mapping=True,
-... padding="max_length",
-... )
-
-... offset_mapping = inputs.pop("offset_mapping")
-... answers = examples["answers"]
-... start_positions = []
-... end_positions = []
-
-... for i, offset in enumerate(offset_mapping):
-... answer = answers[i]
-... start_char = answer["answer_start"][0]
-... end_char = answer["answer_start"][0] + len(answer["text"][0])
-... sequence_ids = inputs.sequence_ids(i)
-
-... # Find the start and end of the context
-... idx = 0
-... while sequence_ids[idx] != 1:
-... idx += 1
-... context_start = idx
-... while sequence_ids[idx] == 1:
-... idx += 1
-... context_end = idx - 1
-
-... # If the answer is not fully inside the context, label it (0, 0)
-... if offset[context_start][0] > end_char or offset[context_end][1] < start_char:
-... start_positions.append(0)
-... end_positions.append(0)
-... else:
-... # Otherwise it's the start and end token positions
-... idx = context_start
-... while idx <= context_end and offset[idx][0] <= start_char:
-... idx += 1
-... start_positions.append(idx - 1)
-
-... idx = context_end
-... while idx >= context_start and offset[idx][1] >= end_char:
-... idx -= 1
-... end_positions.append(idx + 1)
-
-... inputs["start_positions"] = start_positions
-... inputs["end_positions"] = end_positions
-... return inputs
-```
-
-ëȘšë ë°ìŽí° ìžížì ì ìČëŠŹë„Œ ì ì©íë €ë©Ž, đ€ Datasets [`~datasets.Dataset.map`] íšì넌 ìŹì©íìžì. `batched=True`ëĄ ì€ì íŽ ë°ìŽí° ìžížì ìŹëŹ ììë€ì í ëČì ìČ늏í멎 `map` íšìì ìë넌 ëč 넎êČ í ì ìì”ëë€. íìíì§ ìì ìŽì ëȘšë ì ê±°í©ëë€:
-
-```py
->>> tokenized_squad = squad.map(preprocess_function, batched=True, remove_columns=squad["train"].column_names)
-```
-
-ìŽì [`DefaultDataCollator`]넌 ìŽì©íŽ ìì ë°°ìč넌 ìì±í©ëë€. đ€ Transformersì ë€ë„ž ë°ìŽí° ìœë ìŽí°(data collator)ì ëŹëŠŹ, [`DefaultDataCollator`]ë íšë©êłŒ ê°ì ì¶ê° ì ìČëŠŹë„Œ ì ì©íì§ ìì”ëë€:
-
-
-
-```py
->>> from transformers import DefaultDataCollator
-
->>> data_collator = DefaultDataCollator()
-```
-
-
-```py
->>> from transformers import DefaultDataCollator
-
->>> data_collator = DefaultDataCollator(return_tensors="tf")
-```
-
-
-
-## íë š[[train]]
-
-
-
-
-
-[`Trainer`]넌 ìŽì©íŽ ëȘšëžì ëŻžìž ìĄ°ì íë êČì ì”ìíì§ ìë€ë©Ž, [ìŹêž°](../training#train-with-pytorch-trainer)ìì êž°ìŽ íí 늏ìŒì ìŽíŽëłŽìžì!
-
-
-
-ìŽì ëȘšëž íë šì ììí ì€ëčê° ëìì”ëë€! [`AutoModelForQuestionAnswering`]ìŒëĄ DistilBERT넌 ê°ì žì”ëë€:
-
-```py
->>> from transformers import AutoModelForQuestionAnswering, TrainingArguments, Trainer
-
->>> model = AutoModelForQuestionAnswering.from_pretrained("distilbert-base-uncased")
-```
-
-ìŽì ìž ëšêłë§ ëšìì”ëë€:
-
-1. [`TrainingArguments`]ìì íë š íìŽíŒíëŒëŻží°ë„Œ ì í©ëë€. êŒ íìí ë§€ê°ëłìë ëȘšëžì ì ì„í ììč넌 ì§ì íë `output_dir` ì
ëë€. `push_to_hub=True`ëĄ ì€ì íŽì ìŽ ëȘšëžì HubëĄ ížìí©ëë€ (ëȘšëžì ì
ëĄëíë €ë©Ž Hugging Faceì ëĄê·žìžíŽìŒ í©ëë€).
-2. ëȘšëž, ë°ìŽí° ìžíž, í íŹëìŽì , ë°ìŽí° ìœë ìŽí°ì íšê» [`Trainer`]ì íë š ìžìë€ì ì ëŹí©ëë€.
-3. [`~Trainer.train`]ì ížì¶íŽì ëȘšëžì ëŻžìž ìĄ°ì í©ëë€.
-
-```py
->>> training_args = TrainingArguments(
-... output_dir="my_awesome_qa_model",
-... evaluation_strategy="epoch",
-... learning_rate=2e-5,
-... per_device_train_batch_size=16,
-... per_device_eval_batch_size=16,
-... num_train_epochs=3,
-... weight_decay=0.01,
-... push_to_hub=True,
-... )
-
->>> trainer = Trainer(
-... model=model,
-... args=training_args,
-... train_dataset=tokenized_squad["train"],
-... eval_dataset=tokenized_squad["test"],
-... tokenizer=tokenizer,
-... data_collator=data_collator,
-... )
-
->>> trainer.train()
-```
-
-íë šìŽ ìëŁë멎, [`~transformers.Trainer.push_to_hub`] ë§€ìë넌 ìŹì©íŽ ëȘšëžì Hubì êł”ì íŽì ëȘšë ìŹëë€ìŽ ìŹì©í ì ìêČ êł”ì íŽìŁŒìžì:
-
-```py
->>> trainer.push_to_hub()
-```
-
-
-
-
-KerasëĄ ëȘšëžì ëŻžìž ìĄ°ì íë êČì ì”ìíì§ ìë€ë©Ž, [ìŹêž°](../training#train-a-tensorflow-model-with-keras)ìì êž°ìŽ íí 늏ìŒì ìŽíŽëłŽìžì!
-
-
-TensorFlow넌 ìŽì©í ëȘšëžì ëŻžìž ìĄ°ì íë €ë©Ž ì”í°ë§ìŽì íšì, íì”ë„ ì€ìŒì„Ž ë° ëȘ ê°ì§ íë š íìŽíŒíëŒëŻží°ë„Œ ì€ì íë êČë¶í° ììíŽìŒí©ëë€:
-
-```py
->>> from transformers import create_optimizer
-
->>> batch_size = 16
->>> num_epochs = 2
->>> total_train_steps = (len(tokenized_squad["train"]) // batch_size) * num_epochs
->>> optimizer, schedule = create_optimizer(
-... init_lr=2e-5,
-... num_warmup_steps=0,
-... num_train_steps=total_train_steps,
-... )
-```
-
-ê·ž ë€ì [`TFAutoModelForQuestionAnswering`]ìŒëĄ DistilBERT넌 ê°ì žì”ëë€:
-
-```py
->>> from transformers import TFAutoModelForQuestionAnswering
-
->>> model = TFAutoModelForQuestionAnswering("distilbert-base-uncased")
-```
-
-[`~transformers.TFPreTrainedModel.prepare_tf_dataset`]ì ìŹì©íŽì ë°ìŽí° ìžížë„Œ `tf.data.Dataset` íììŒëĄ ëłíí©ëë€:
-
-```py
->>> tf_train_set = model.prepare_tf_dataset(
-... tokenized_squad["train"],
-... shuffle=True,
-... batch_size=16,
-... collate_fn=data_collator,
-... )
-
->>> tf_validation_set = model.prepare_tf_dataset(
-... tokenized_squad["test"],
-... shuffle=False,
-... batch_size=16,
-... collate_fn=data_collator,
-... )
-```
-
-[`compile`](https://keras.io/api/models/model_training_apis/#compile-method)ëĄ íë ší ëȘšëžì ì€ì í©ëë€:
-
-```py
->>> import tensorflow as tf
-
->>> model.compile(optimizer=optimizer)
-```
-
-ë§ì§ë§ìŒëĄ ëȘšëžì HubëĄ ížìí ë°©ëČì ì€ì í©ëë€. [`~transformers.PushToHubCallback`]ìì ëȘšëžêłŒ í íŹëìŽì 넌 ížìí êČœëĄë„Œ ì€ì í©ëë€:
-
-```py
->>> from transformers.keras_callbacks import PushToHubCallback
-
->>> callback = PushToHubCallback(
-... output_dir="my_awesome_qa_model",
-... tokenizer=tokenizer,
-... )
-```
-
-ëëìŽ ëȘšëž íë šì ììí ì€ëčê° ëìì”ëë€! íë š ë°ìŽí° ìžížì íê° ë°ìŽí° ìžíž, ìí ì, ìœë°±ì ì€ì í í [`fit`](https://keras.io/api/models/model_training_apis/#fit-method)ì ìŽì©íŽ ëȘšëžì ëŻžìž ìĄ°ì í©ëë€:
-
-```py
->>> model.fit(x=tf_train_set, validation_data=tf_validation_set, epochs=3, callbacks=[callback])
-```
-íë šìŽ ìëŁë멎 ëȘšëžìŽ ìëìŒëĄ Hubì ì
ëĄëëìŽ ëê”Źë ìŹì©í ì ìì”ëë€!
-
-
-
-
-
-ì§ì ìë”ì ìíŽ ëȘšëžì ëŻžìž ìĄ°ì íë ë°©ëČì ëí ë ììží ììë [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)ì ì°žìĄ°íìžì.
-
-
-
-## íê°[[evaluate]]
-
-ì§ì ìë”ì íê°íë €ë©Ž ìëčí ìì íìČëŠŹê° íìí©ëë€. ìê°ìŽ ë돎 ë§ìŽ ê±žëŠŹì§ ìëëĄ ìŽ ê°ìŽëììë íê° ëšêłë„Œ ìë”í©ëë€. [`Trainer`]ë íë š êłŒì ìì íê° ìì€(evaluation loss)ì êłì êłì°íêž° ë돞ì ëȘšëžì ì±ë„ì ëë”ì ìŒëĄ ì ì ìì”ëë€.
-
-ìê°ì ìŹì ê° ìêł ì§ì ìë” ëȘšëžì íê°íë ë°©ëČì êŽìŹìŽ ìë€ë©Ž đ€ Hugging Face Courseì [Question answering](https://huggingface.co/course/chapter7/7?fw=pt#postprocessing) ì±í°ë„Œ ìŽíŽëłŽìžì!
-
-## ì¶ëĄ [[inference]]
-
-ìŽì ëȘšëžì ëŻžìž ìĄ°ì íìŒë ì¶ëĄ ì ìŹì©í ì ìì”ëë€!
-
-ì§ëŹžêłŒ ëȘšëžìŽ ììžĄíêž° ìíë 돞맄(context)넌 ìê°íŽëłŽìžì:
-
-```py
->>> question = "How many programming languages does BLOOM support?"
->>> context = "BLOOM has 176 billion parameters and can generate text in 46 languages natural languages and 13 programming languages."
-```
-
-ì¶ëĄ ì ìíŽ ëŻžìž ìĄ°ì í ëȘšëžì í
ì€ížíë ê°ì„ ìŹìŽ ë°©ëČì [`pipeline`]ì ìŹì©íë êČ ì
ëë€. ëȘšëžì ìŹì©íŽ ì§ì ìë”ì íêž° ìíŽì `pipeline`ì ìžì€íŽì€ííêł í
ì€ížë„Œ ì
ë „í©ëë€:
-
-```py
->>> from transformers import pipeline
-
->>> question_answerer = pipeline("question-answering", model="my_awesome_qa_model")
->>> question_answerer(question=question, context=context)
-{'score': 0.2058267742395401,
- 'start': 10,
- 'end': 95,
- 'answer': '176 billion parameters and can generate text in 46 languages natural languages and 13'}
-```
-
-ìíë€ë©Ž `pipeline`ì êČ°êłŒë„Œ ì§ì ëł”ì í ìë ìì”ëë€:
-
-
-
-í
ì€ížë„Œ í í°ííŽì PyTorch í
ì넌 ë°íí©ëë€:
-
-```py
->>> from transformers import AutoTokenizer
-
->>> tokenizer = AutoTokenizer.from_pretrained("my_awesome_qa_model")
->>> inputs = tokenizer(question, context, return_tensors="pt")
-```
-
-ëȘšëžì ì
ë „ì ì ëŹíêł `logits`ì ë°íí©ëë€:
-
-```py
->>> from transformers import AutoModelForQuestionAnswering
-
->>> model = AutoModelForQuestionAnswering.from_pretrained("my_awesome_qa_model")
->>> with torch.no_grad():
-... outputs = model(**inputs)
-```
-
-ëȘšëžì ì¶ë „ìì ìì ë° ìą
ëŁ ììčê° ìŽëì§ ê°ì„ ëì íë„ ì ì»ì”ëë€:
-
-```py
->>> answer_start_index = outputs.start_logits.argmax()
->>> answer_end_index = outputs.end_logits.argmax()
-```
-
-ììžĄë í í°ì íŽë
íŽì ë”ì ì»ì”ëë€:
-
-```py
->>> predict_answer_tokens = inputs.input_ids[0, answer_start_index : answer_end_index + 1]
->>> tokenizer.decode(predict_answer_tokens)
-'176 billion parameters and can generate text in 46 languages natural languages and 13'
-```
-
-
-í
ì€ížë„Œ í í°ííŽì TensorFlow í
ì넌 ë°íí©ëë€:
-
-```py
->>> from transformers import AutoTokenizer
-
->>> tokenizer = AutoTokenizer.from_pretrained("my_awesome_qa_model")
->>> inputs = tokenizer(question, text, return_tensors="tf")
-```
-
-ëȘšëžì ì
ë „ì ì ëŹíêł `logits`ì ë°íí©ëë€:
-
-```py
->>> from transformers import TFAutoModelForQuestionAnswering
-
->>> model = TFAutoModelForQuestionAnswering.from_pretrained("my_awesome_qa_model")
->>> outputs = model(**inputs)
-```
-
-ëȘšëžì ì¶ë „ìì ìì ë° ìą
ëŁ ììčê° ìŽëì§ ê°ì„ ëì íë„ ì ì»ì”ëë€:
-
-```py
->>> answer_start_index = int(tf.math.argmax(outputs.start_logits, axis=-1)[0])
->>> answer_end_index = int(tf.math.argmax(outputs.end_logits, axis=-1)[0])
-```
-
-ììžĄë í í°ì íŽë
íŽì ë”ì ì»ì”ëë€:
-
-```py
->>> predict_answer_tokens = inputs.input_ids[0, answer_start_index : answer_end_index + 1]
->>> tokenizer.decode(predict_answer_tokens)
-'176 billion parameters and can generate text in 46 languages natural languages and 13'
-```
-
-
diff --git a/docs/source/ko/tasks/sequence_classification.md b/docs/source/ko/tasks/sequence_classification.md
new file mode 100644
index 000000000000..bc364d3199e2
--- /dev/null
+++ b/docs/source/ko/tasks/sequence_classification.md
@@ -0,0 +1,395 @@
+
+
+# í
ì€íž ë¶ë„[[text-classification]]
+
+[[open-in-colab]]
+
+
+
+í
ì€íž ë¶ë„ë ìì°ìŽ ìČ늏ì ìŒìą
ìŒëĄ, í
ì€ížì ë ìŽëž ëë íŽëì€ë„Œ ì§ì íë ìì
ì
ëë€. ë§ì ëêž°ì
ìŽ ë€ìí ì€ì©ì ìž ìì© ë¶ìŒìì í
ì€íž ë¶ë„넌 ìŽìíêł ìì”ëë€. ê°ì„ ìžêž° ìë í
ì€íž ë¶ë„ íí ì€ íëë ê°ì± ë¶ììŒëĄ, í
ì€íž ìíì€ì đ êžì , đ ë¶ì ëë đ ì€ëŠœêłŒ ê°ì ë ìŽëžì ì§ì í©ëë€.
+
+ìŽ ê°ìŽëìì íì”í ëŽì©ì:
+
+1. [IMDb](https://huggingface.co/datasets/imdb) ë°ìŽí°ì
ìì [DistilBERT](https://huggingface.co/distilbert-base-uncased)넌 íìž íëíìŹ ìí ëŠŹë·°ê° êžì ì ìžì§ ë¶ì ì ìžì§ íëší©ëë€.
+2. ì¶ëĄ ì ìíŽ íìž íë ëȘšëžì ìŹì©í©ëë€.
+
+
+ìŽ íí 늏ìŒìì ì€ëȘ
íë ìì
ì ë€ì ëȘšëž ìí€í
ìČì ìíŽ ì§ìë©ëë€:
+
+
+
+[ALBERT](../model_doc/albert), [BART](../model_doc/bart), [BERT](../model_doc/bert), [BigBird](../model_doc/big_bird), [BigBird-Pegasus](../model_doc/bigbird_pegasus), [BLOOM](../model_doc/bloom), [CamemBERT](../model_doc/camembert), [CANINE](../model_doc/canine), [ConvBERT](../model_doc/convbert), [CTRL](../model_doc/ctrl), [Data2VecText](../model_doc/data2vec-text), [DeBERTa](../model_doc/deberta), [DeBERTa-v2](../model_doc/deberta-v2), [DistilBERT](../model_doc/distilbert), [ELECTRA](../model_doc/electra), [ERNIE](../model_doc/ernie), [ErnieM](../model_doc/ernie_m), [ESM](../model_doc/esm), [FlauBERT](../model_doc/flaubert), [FNet](../model_doc/fnet), [Funnel Transformer](../model_doc/funnel), [GPT-Sw3](../model_doc/gpt-sw3), [OpenAI GPT-2](../model_doc/gpt2), [GPT Neo](../model_doc/gpt_neo), [GPT-J](../model_doc/gptj), [I-BERT](../model_doc/ibert), [LayoutLM](../model_doc/layoutlm), [LayoutLMv2](../model_doc/layoutlmv2), [LayoutLMv3](../model_doc/layoutlmv3), [LED](../model_doc/led), [LiLT](../model_doc/lilt), [LLaMA](../model_doc/llama), [Longformer](../model_doc/longformer), [LUKE](../model_doc/luke), [MarkupLM](../model_doc/markuplm), [mBART](../model_doc/mbart), [MEGA](../model_doc/mega), [Megatron-BERT](../model_doc/megatron-bert), [MobileBERT](../model_doc/mobilebert), [MPNet](../model_doc/mpnet), [MVP](../model_doc/mvp), [Nezha](../model_doc/nezha), [Nyströmformer](../model_doc/nystromformer), [OpenAI GPT](../model_doc/openai-gpt), [OPT](../model_doc/opt), [Perceiver](../model_doc/perceiver), [PLBart](../model_doc/plbart), [QDQBert](../model_doc/qdqbert), [Reformer](../model_doc/reformer), [RemBERT](../model_doc/rembert), [RoBERTa](../model_doc/roberta), [RoBERTa-PreLayerNorm](../model_doc/roberta-prelayernorm), [RoCBert](../model_doc/roc_bert), [RoFormer](../model_doc/roformer), [SqueezeBERT](../model_doc/squeezebert), [TAPAS](../model_doc/tapas), [Transformer-XL](../model_doc/transfo-xl), [XLM](../model_doc/xlm), [XLM-RoBERTa](../model_doc/xlm-roberta), [XLM-RoBERTa-XL](../model_doc/xlm-roberta-xl), [XLNet](../model_doc/xlnet), [X-MOD](../model_doc/xmod), [YOSO](../model_doc/yoso)
+
+
+
+
+
+
+ììíêž° ì ì, íìí ëȘšë ëŒìŽëžëŹëŠŹê° ì€ìčëìŽ ìëì§ íìžíìžì:
+
+```bash
+pip install transformers datasets evaluate
+```
+
+Hugging Face êłì ì ëĄê·žìžíìŹ ëȘšëžì ì
ëĄëíêł ì»€ëź€ëí°ì êł”ì íë êČì ê¶ì„í©ëë€. ë©ìì§ê° íìë멎, í í°ì ì
ë „íìŹ ëĄê·žìžíìžì:
+
+```py
+>>> from huggingface_hub import notebook_login
+
+>>> notebook_login()
+```
+
+## IMDb ë°ìŽí°ì
ê°ì žì€êž°[[load-imdb-dataset]]
+
+뚌ì đ€ Datasets ëŒìŽëžëŹëŠŹìì IMDb ë°ìŽí°ì
ì ê°ì žì”ëë€:
+
+```py
+>>> from datasets import load_dataset
+
+>>> imdb = load_dataset("imdb")
+```
+
+ê·žë° ë€ì ìì넌 ìŽíŽëŽ
ìë€:
+
+```py
+>>> imdb["test"][0]
+{
+ "label": 0,
+ "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.",
+}
+```
+
+ìŽ ë°ìŽí°ì
ìë ë ê°ì§ íëê° ìì”ëë€:
+
+- `text`: ìí 늏뷰 í
ì€íž
+- `label`: `0`ì ë¶ì ì ìž ëŠŹë·°, `1`ì êžì ì ìž ëŠŹë·°ë„Œ ëíë
ëë€.
+
+## ì ìČ늏[[preprocess]]
+
+ë€ì ëšêłë DistilBERT í íŹëìŽì 넌 ê°ì žìì `text` íë넌 ì ìČ늏íë êČì
ëë€:
+
+```py
+>>> from transformers import AutoTokenizer
+
+>>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
+```
+
+`text`넌 í í°ííêł ìíì€ê° DistilBERTì ì”ë ì
ë „ êžžìŽëłŽë€ êžžì§ ìëëĄ ì넎Ʞ ìí ì ìČ늏 íšì넌 ìì±íìžì:
+
+```py
+>>> def preprocess_function(examples):
+... return tokenizer(examples["text"], truncation=True)
+```
+
+ì ìČŽ ë°ìŽí°ì
ì ì ìČ늏 íšì넌 ì ì©íë €ë©Ž, đ€ Datasets [`~datasets.Dataset.map`] íšì넌 ìŹì©íìžì. ë°ìŽí°ì
ì ìŹëŹ ìì넌 í ëČì ìČ늏íêž° ìíŽ `batched=True`ëĄ ì€ì íšìŒëĄìš ë°ìŽí°ì
`map`넌 ë ëč 넎êČ ìČ늏í ì ìì”ëë€:
+
+```py
+tokenized_imdb = imdb.map(preprocess_function, batched=True)
+```
+
+ìŽì [`DataCollatorWithPadding`]넌 ìŹì©íìŹ ìì ë°°ìč넌 ë§ë€ìŽëŽ
ìë€. ë°ìŽí°ì
ì ìČŽë„Œ ì”ë êžžìŽëĄ íšë©íë ëì , *ëì íšë©*ì ìŹì©íìŹ ë°°ìčìì ê°ì„ ꞎ êžžìŽì ë§êČ ëŹžì„ì íšë©íë êČìŽ íšìšì ì
ëë€.
+
+
+
+```py
+>>> from transformers import DataCollatorWithPadding
+
+>>> data_collator = DataCollatorWithPadding(tokenizer=tokenizer)
+```
+
+
+```py
+>>> from transformers import DataCollatorWithPadding
+
+>>> data_collator = DataCollatorWithPadding(tokenizer=tokenizer, return_tensors="tf")
+```
+
+
+
+## íê°íêž°[[evaluate]]
+
+íë š ì€ ëȘšëžì ì±ë„ì íê°íêž° ìíŽ ë©ížëŠì íŹíšíë êČìŽ ì ì©í©ëë€. đ€ [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)넌 ì°žìĄ°íìžì):
+
+```py
+>>> import evaluate
+
+>>> accuracy = evaluate.load("accuracy")
+```
+
+ê·žë° ë€ì `compute_metrics` íšì넌 ë§ë€ìŽì ììžĄêłŒ ë ìŽëžì êłì°íìŹ ì íë넌 êłì°íëëĄ [`~evaluate.EvaluationModule.compute`]넌 ížì¶í©ëë€:
+
+```py
+>>> import numpy as np
+
+
+>>> def compute_metrics(eval_pred):
+... predictions, labels = eval_pred
+... predictions = np.argmax(predictions, axis=1)
+... return accuracy.compute(predictions=predictions, references=labels)
+```
+
+ìŽì `compute_metrics` íšìë ì€ëčëìêł , íë š êłŒì ì ì€ì í ë ë€ì ìŽíŽëłŒ ìì ì
ëë€.
+
+## íë š[[train]]
+
+ëȘšëžì íë šíêž° ì ì, `id2label`ì `label2id`넌 ìŹì©íìŹ ììëë idì ë ìŽëžì ë§”ì ìì±íìžì:
+
+```py
+>>> id2label = {0: "NEGATIVE", 1: "POSITIVE"}
+>>> label2id = {"NEGATIVE": 0, "POSITIVE": 1}
+```
+
+
+
+
+
+[`Trainer`]넌 ìŹì©íìŹ ëȘšëžì íìž íëíë ë°©ëČì ì”ìíì§ ìì êČœì°, [ìŹêž°](../training#train-with-pytorch-trainer)ì êž°ëłž íí 늏ìŒì íìžíìžì!
+
+
+
+ìŽì ëȘšëžì íë šìíŹ ì€ëčê° ëìì”ëë€! [`AutoModelForSequenceClassification`]ëĄ DistilBERT넌 ê°ìłì€êł ììëë ë ìŽëž ìì ë ìŽëž ë§€íì ì§ì íìžì:
+
+```py
+>>> from transformers import AutoModelForSequenceClassification, TrainingArguments, Trainer
+
+>>> model = AutoModelForSequenceClassification.from_pretrained(
+... "distilbert-base-uncased", num_labels=2, id2label=id2label, label2id=label2id
+... )
+```
+
+ìŽì ìž ëšêłë§ ê±°ìč멎 ëì
ëë€:
+
+1. [`TrainingArguments`]ìì íìŽíŒíëŒëŻží°ë„Œ ì ìíìžì. `output_dir`ë ëȘšëžì ì ì„í ììč넌 ì§ì íë ì ìŒí íëŒëŻží°ì
ëë€. ìŽ ëȘšëžì Hubì ì
ëĄëíêž° ìíŽ `push_to_hub=True`넌 ì€ì í©ëë€. (ëȘšëžì ì
ëĄëíêž° ìíŽ Hugging Faceì ëĄê·žìžíŽìŒí©ëë€.) ê° ìíìŽ ëë ëë§ë€, [`Trainer`]ë ì íë넌 íê°íêł íë š ìČŽíŹíŹìžížë„Œ ì ì„í©ëë€.
+2. [`Trainer`]ì íë š ìžìì ëȘšëž, ë°ìŽí°ì
, í íŹëìŽì , ë°ìŽí° ìì§êž° ë° `compute_metrics` íšì넌 ì ëŹíìžì.
+3. [`~Trainer.train`]넌 ížì¶íìŹ ëȘšëžì íìž íëíìžì.
+
+```py
+>>> training_args = TrainingArguments(
+... output_dir="my_awesome_model",
+... learning_rate=2e-5,
+... per_device_train_batch_size=16,
+... per_device_eval_batch_size=16,
+... num_train_epochs=2,
+... weight_decay=0.01,
+... evaluation_strategy="epoch",
+... save_strategy="epoch",
+... load_best_model_at_end=True,
+... push_to_hub=True,
+... )
+
+>>> trainer = Trainer(
+... model=model,
+... args=training_args,
+... train_dataset=tokenized_imdb["train"],
+... eval_dataset=tokenized_imdb["test"],
+... tokenizer=tokenizer,
+... data_collator=data_collator,
+... compute_metrics=compute_metrics,
+... )
+
+>>> trainer.train()
+```
+
+
+
+[`Trainer`]ë `tokenizer`넌 ì ëŹí멎 êž°ëłžì ìŒëĄ ëì ë§€íì ì ì©í©ëë€. ìŽ êČœì°, ëȘ
ìì ìŒëĄ ë°ìŽí° ìì§êž°ë„Œ ì§ì í íìê° ìì”ëë€.
+
+
+
+íë šìŽ ìëŁë멎, [`~transformers.Trainer.push_to_hub`] ë©ìë넌 ìŹì©íìŹ ëȘšëžì Hubì êł”ì í ì ìì”ëë€.
+
+```py
+>>> trainer.push_to_hub()
+```
+
+
+
+
+Keras넌 ìŹì©íìŹ ëȘšëžì íìž íëíë ë°©ëČì ì”ìíì§ ìì êČœì°, [ìŹêž°](../training#train-a-tensorflow-model-with-keras)ì êž°ëłž íí 늏ìŒì íìžíìžì!
+
+
+TensorFlowìì ëȘšëžì íìž íëíë €ë©Ž, 뚌ì ì”í°ë§ìŽì íšìì íì”ë„ ì€ìŒì„Ž, ê·žëŠŹêł ìŒë¶ íë š íìŽíŒíëŒëŻží°ë„Œ ì€ì íŽìŒ í©ëë€:
+
+```py
+>>> from transformers import create_optimizer
+>>> import tensorflow as tf
+
+>>> batch_size = 16
+>>> num_epochs = 5
+>>> batches_per_epoch = len(tokenized_imdb["train"]) // batch_size
+>>> total_train_steps = int(batches_per_epoch * num_epochs)
+>>> optimizer, schedule = create_optimizer(init_lr=2e-5, num_warmup_steps=0, num_train_steps=total_train_steps)
+```
+
+ê·žë° ë€ì [`TFAutoModelForSequenceClassification`]ì ìŹì©íìŹ DistilBERT넌 ëĄëíêł , ììëë ë ìŽëž ìì ë ìŽëž ë§€íì ëĄëí ì ìì”ëë€:
+
+```py
+>>> from transformers import TFAutoModelForSequenceClassification
+
+>>> model = TFAutoModelForSequenceClassification.from_pretrained(
+... "distilbert-base-uncased", num_labels=2, id2label=id2label, label2id=label2id
+... )
+```
+
+[`~transformers.TFPreTrainedModel.prepare_tf_dataset`]ì ìŹì©íìŹ ë°ìŽí°ì
ì `tf.data.Dataset` íììŒëĄ ëłíí©ëë€:
+
+```py
+>>> tf_train_set = model.prepare_tf_dataset(
+... tokenized_imdb["train"],
+... shuffle=True,
+... batch_size=16,
+... collate_fn=data_collator,
+... )
+
+>>> tf_validation_set = model.prepare_tf_dataset(
+... tokenized_imdb["test"],
+... shuffle=False,
+... batch_size=16,
+... collate_fn=data_collator,
+... )
+```
+
+[`compile`](https://keras.io/api/models/model_training_apis/#compile-method)넌 ìŹì©íìŹ íë ší ëȘšëžì ê”Źì±í©ëë€:
+
+```py
+>>> import tensorflow as tf
+
+>>> model.compile(optimizer=optimizer)
+```
+
+íë šì ììíêž° ì ì ì€ì íŽìŒí ë§ì§ë§ ë ê°ì§ë ììžĄìì ì íë넌 êłì°íêł , ëȘšëžì Hubì ì
ëĄëí ë°©ëČì ì êł”íë êČì
ëë€. ëȘšë [Keras callbacks](../main_classes/keras_callbacks)넌 ìŹì©íìŹ ìíë©ëë€.
+
+[`~transformers.KerasMetricCallback`]ì `compute_metrics`넌 ì ëŹíìŹ ì íë넌 ëì
ëë€.
+
+```py
+>>> from transformers.keras_callbacks import KerasMetricCallback
+
+>>> metric_callback = KerasMetricCallback(metric_fn=compute_metrics, eval_dataset=tf_validation_set)
+```
+
+[`~transformers.PushToHubCallback`]ìì ëȘšëžêłŒ í íŹëìŽì 넌 ì
ëĄëí ììč넌 ì§ì í©ëë€:
+
+```py
+>>> from transformers.keras_callbacks import PushToHubCallback
+
+>>> push_to_hub_callback = PushToHubCallback(
+... output_dir="my_awesome_model",
+... tokenizer=tokenizer,
+... )
+```
+
+ê·žë° ë€ì ìœë°±ì íšê» 돶ì”ëë€:
+
+```py
+>>> callbacks = [metric_callback, push_to_hub_callback]
+```
+
+ëëìŽ, ëȘšëž íë šì ììí ì€ëčê° ëìì”ëë€! [`fit`](https://keras.io/api/models/model_training_apis/#fit-method)ì íë š ë°ìŽí°ì
, êČìŠ ë°ìŽí°ì
, ìíì ì ë° ìœë°±ì ì ëŹíìŹ íìž íëí©ëë€:
+
+```py
+>>> model.fit(x=tf_train_set, validation_data=tf_validation_set, epochs=3, callbacks=callbacks)
+```
+
+íë šìŽ ìëŁë멎, ëȘšëžìŽ ìëìŒëĄ Hubì ì
ëĄëëìŽ ëȘšë ìŹëìŽ ìŹì©í ì ìì”ëë€!
+
+
+
+
+
+í
ì€íž ë¶ë„넌 ìí ëȘšëžì íìž íëíë ììží ìì ë ë€ì [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)넌 ì°žìĄ°íìžì.
+
+
+
+## ì¶ëĄ [[inference]]
+
+ìąìì, ìŽì ëȘšëžì íìž íëíìŒë ì¶ëĄ ì ìŹì©í ì ìì”ëë€!
+
+ì¶ëĄ ì ìííêł ì íë í
ì€ížë„Œ ê°ì žìëŽ
ìë€:
+
+```py
+>>> text = "This was a masterpiece. Not completely faithful to the books, but enthralling from beginning to end. Might be my favorite of the three."
+```
+
+íìž íëë ëȘšëžëĄ ì¶ëĄ ì ìëíë ê°ì„ ê°ëší ë°©ëČì [`pipeline`]넌 ìŹì©íë êČì
ëë€. ëȘšëžëĄ ê°ì ë¶ìì ìí `pipeline`ì ìžì€íŽì€ííêł , í
ì€ížë„Œ ì ëŹíŽëłŽìžì:
+
+```py
+>>> from transformers import pipeline
+
+>>> classifier = pipeline("sentiment-analysis", model="stevhliu/my_awesome_model")
+>>> classifier(text)
+[{'label': 'POSITIVE', 'score': 0.9994940757751465}]
+```
+
+ìíë€ë©Ž, `pipeline`ì êČ°êłŒë„Œ ìëìŒëĄ ëł”ì í ìë ìì”ëë€.
+
+
+
+í
ì€ížë„Œ í í°ííêł PyTorch í
ì넌 ë°íí©ëë€.
+
+```py
+>>> from transformers import AutoTokenizer
+
+>>> tokenizer = AutoTokenizer.from_pretrained("stevhliu/my_awesome_model")
+>>> inputs = tokenizer(text, return_tensors="pt")
+```
+
+ì
ë „ì ëȘšëžì ì ëŹíêł `logits`ì ë°íí©ëë€:
+
+```py
+>>> from transformers import AutoModelForSequenceClassification
+
+>>> model = AutoModelForSequenceClassification.from_pretrained("stevhliu/my_awesome_model")
+>>> with torch.no_grad():
+... logits = model(**inputs).logits
+```
+
+ê°ì„ ëì íë„ ì ê°ì§ íŽëì€ë„Œ ëȘšëžì `id2label` ë§€íì ìŹì©íìŹ í
ì€íž ë ìŽëžëĄ ëłíí©ëë€:
+
+```py
+>>> predicted_class_id = logits.argmax().item()
+>>> model.config.id2label[predicted_class_id]
+'POSITIVE'
+```
+
+
+í
ì€ížë„Œ í í°ííêł TensorFlow í
ì넌 ë°íí©ëë€:
+
+```py
+>>> from transformers import AutoTokenizer
+
+>>> tokenizer = AutoTokenizer.from_pretrained("stevhliu/my_awesome_model")
+>>> inputs = tokenizer(text, return_tensors="tf")
+```
+
+ì
ë „ê°ì ëȘšëžì ì ëŹíêł `logits`ì ë°íí©ëë€:
+
+```py
+>>> from transformers import TFAutoModelForSequenceClassification
+
+>>> model = TFAutoModelForSequenceClassification.from_pretrained("stevhliu/my_awesome_model")
+>>> logits = model(**inputs).logits
+```
+
+ê°ì„ ëì íë„ ì ê°ì§ íŽëì€ë„Œ ëȘšëžì `id2label` ë§€íì ìŹì©íìŹ í
ì€íž ë ìŽëžëĄ ëłíí©ëë€:
+
+```py
+>>> predicted_class_id = int(tf.math.argmax(logits, axis=-1)[0])
+>>> model.config.id2label[predicted_class_id]
+'POSITIVE'
+```
+
+
diff --git a/docs/source/ko/tasks/sequence_classification.mdx b/docs/source/ko/tasks/sequence_classification.mdx
deleted file mode 100644
index 32cf216d7b4c..000000000000
--- a/docs/source/ko/tasks/sequence_classification.mdx
+++ /dev/null
@@ -1,391 +0,0 @@
-
-
-# í
ì€íž ë¶ë„[[text-classification]]
-
-[[open-in-colab]]
-
-
-
-í
ì€íž ë¶ë„ë ìì°ìŽ ìČ늏ì ìŒìą
ìŒëĄ, í
ì€ížì ë ìŽëž ëë íŽëì€ë„Œ ì§ì íë ìì
ì
ëë€. ë§ì ëêž°ì
ìŽ ë€ìí ì€ì©ì ìž ìì© ë¶ìŒìì í
ì€íž ë¶ë„넌 ìŽìíêł ìì”ëë€. ê°ì„ ìžêž° ìë í
ì€íž ë¶ë„ íí ì€ íëë ê°ì± ë¶ììŒëĄ, í
ì€íž ìíì€ì đ êžì , đ ë¶ì ëë đ ì€ëŠœêłŒ ê°ì ë ìŽëžì ì§ì í©ëë€.
-
-ìŽ ê°ìŽëìì íì”í ëŽì©ì:
-
-1. [IMDb](https://huggingface.co/datasets/imdb) ë°ìŽí°ì
ìì [DistilBERT](https://huggingface.co/distilbert-base-uncased)넌 íìž íëíìŹ ìí ëŠŹë·°ê° êžì ì ìžì§ ë¶ì ì ìžì§ íëší©ëë€.
-2. ì¶ëĄ ì ìíŽ íìž íë ëȘšëžì ìŹì©í©ëë€.
-
-
-ìŽ íí 늏ìŒìì ì€ëȘ
íë ìì
ì ë€ì ëȘšëž ìí€í
ìČì ìíŽ ì§ìë©ëë€:
-
-
-
-[ALBERT](../model_doc/albert), [BART](../model_doc/bart), [BERT](../model_doc/bert), [BigBird](../model_doc/big_bird), [BigBird-Pegasus](../model_doc/bigbird_pegasus), [BLOOM](../model_doc/bloom), [CamemBERT](../model_doc/camembert), [CANINE](../model_doc/canine), [ConvBERT](../model_doc/convbert), [CTRL](../model_doc/ctrl), [Data2VecText](../model_doc/data2vec-text), [DeBERTa](../model_doc/deberta), [DeBERTa-v2](../model_doc/deberta-v2), [DistilBERT](../model_doc/distilbert), [ELECTRA](../model_doc/electra), [ERNIE](../model_doc/ernie), [ErnieM](../model_doc/ernie_m), [ESM](../model_doc/esm), [FlauBERT](../model_doc/flaubert), [FNet](../model_doc/fnet), [Funnel Transformer](../model_doc/funnel), [GPT-Sw3](../model_doc/gpt-sw3), [OpenAI GPT-2](../model_doc/gpt2), [GPT Neo](../model_doc/gpt_neo), [GPT-J](../model_doc/gptj), [I-BERT](../model_doc/ibert), [LayoutLM](../model_doc/layoutlm), [LayoutLMv2](../model_doc/layoutlmv2), [LayoutLMv3](../model_doc/layoutlmv3), [LED](../model_doc/led), [LiLT](../model_doc/lilt), [LLaMA](../model_doc/llama), [Longformer](../model_doc/longformer), [LUKE](../model_doc/luke), [MarkupLM](../model_doc/markuplm), [mBART](../model_doc/mbart), [MEGA](../model_doc/mega), [Megatron-BERT](../model_doc/megatron-bert), [MobileBERT](../model_doc/mobilebert), [MPNet](../model_doc/mpnet), [MVP](../model_doc/mvp), [Nezha](../model_doc/nezha), [Nyströmformer](../model_doc/nystromformer), [OpenAI GPT](../model_doc/openai-gpt), [OPT](../model_doc/opt), [Perceiver](../model_doc/perceiver), [PLBart](../model_doc/plbart), [QDQBert](../model_doc/qdqbert), [Reformer](../model_doc/reformer), [RemBERT](../model_doc/rembert), [RoBERTa](../model_doc/roberta), [RoBERTa-PreLayerNorm](../model_doc/roberta-prelayernorm), [RoCBert](../model_doc/roc_bert), [RoFormer](../model_doc/roformer), [SqueezeBERT](../model_doc/squeezebert), [TAPAS](../model_doc/tapas), [Transformer-XL](../model_doc/transfo-xl), [XLM](../model_doc/xlm), [XLM-RoBERTa](../model_doc/xlm-roberta), [XLM-RoBERTa-XL](../model_doc/xlm-roberta-xl), [XLNet](../model_doc/xlnet), [X-MOD](../model_doc/xmod), [YOSO](../model_doc/yoso)
-
-
-
-
-
-
-ììíêž° ì ì, íìí ëȘšë ëŒìŽëžëŹëŠŹê° ì€ìčëìŽ ìëì§ íìžíìžì:
-
-```bash
-pip install transformers datasets evaluate
-```
-
-Hugging Face êłì ì ëĄê·žìžíìŹ ëȘšëžì ì
ëĄëíêł ì»€ëź€ëí°ì êł”ì íë êČì ê¶ì„í©ëë€. ë©ìì§ê° íìë멎, í í°ì ì
ë „íìŹ ëĄê·žìžíìžì:
-
-```py
->>> from huggingface_hub import notebook_login
-
->>> notebook_login()
-```
-
-## IMDb ë°ìŽí°ì
ê°ì žì€êž°[[load-imdb-dataset]]
-
-뚌ì đ€ Datasets ëŒìŽëžëŹëŠŹìì IMDb ë°ìŽí°ì
ì ê°ì žì”ëë€:
-
-```py
->>> from datasets import load_dataset
-
->>> imdb = load_dataset("imdb")
-```
-
-ê·žë° ë€ì ìì넌 ìŽíŽëŽ
ìë€:
-
-```py
->>> imdb["test"][0]
-{
- "label": 0,
- "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.",
-}
-```
-
-ìŽ ë°ìŽí°ì
ìë ë ê°ì§ íëê° ìì”ëë€:
-
-- `text`: ìí 늏뷰 í
ì€íž
-- `label`: `0`ì ë¶ì ì ìž ëŠŹë·°, `1`ì êžì ì ìž ëŠŹë·°ë„Œ ëíë
ëë€.
-
-## ì ìČ늏[[preprocess]]
-
-ë€ì ëšêłë DistilBERT í íŹëìŽì 넌 ê°ì žìì `text` íë넌 ì ìČ늏íë êČì
ëë€:
-
-```py
->>> from transformers import AutoTokenizer
-
->>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
-```
-
-`text`넌 í í°ííêł ìíì€ê° DistilBERTì ì”ë ì
ë „ êžžìŽëłŽë€ êžžì§ ìëëĄ ì넎Ʞ ìí ì ìČ늏 íšì넌 ìì±íìžì:
-
-```py
->>> def preprocess_function(examples):
-... return tokenizer(examples["text"], truncation=True)
-```
-
-ì ìČŽ ë°ìŽí°ì
ì ì ìČ늏 íšì넌 ì ì©íë €ë©Ž, đ€ Datasets [`~datasets.Dataset.map`] íšì넌 ìŹì©íìžì. ë°ìŽí°ì
ì ìŹëŹ ìì넌 í ëČì ìČ늏íêž° ìíŽ `batched=True`ëĄ ì€ì íšìŒëĄìš ë°ìŽí°ì
`map`넌 ë ëč 넎êČ ìČ늏í ì ìì”ëë€:
-
-```py
-tokenized_imdb = imdb.map(preprocess_function, batched=True)
-```
-
-ìŽì [`DataCollatorWithPadding`]넌 ìŹì©íìŹ ìì ë°°ìč넌 ë§ë€ìŽëŽ
ìë€. ë°ìŽí°ì
ì ìČŽë„Œ ì”ë êžžìŽëĄ íšë©íë ëì , *ëì íšë©*ì ìŹì©íìŹ ë°°ìčìì ê°ì„ ꞎ êžžìŽì ë§êČ ëŹžì„ì íšë©íë êČìŽ íšìšì ì
ëë€.
-
-
-
-```py
->>> from transformers import DataCollatorWithPadding
-
->>> data_collator = DataCollatorWithPadding(tokenizer=tokenizer)
-```
-
-
-```py
->>> from transformers import DataCollatorWithPadding
-
->>> data_collator = DataCollatorWithPadding(tokenizer=tokenizer, return_tensors="tf")
-```
-
-
-
-## íê°íêž°[[evaluate]]
-
-íë š ì€ ëȘšëžì ì±ë„ì íê°íêž° ìíŽ ë©ížëŠì íŹíšíë êČìŽ ì ì©í©ëë€. đ€ [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)넌 ì°žìĄ°íìžì):
-
-```py
->>> import evaluate
-
->>> accuracy = evaluate.load("accuracy")
-```
-
-ê·žë° ë€ì `compute_metrics` íšì넌 ë§ë€ìŽì ììžĄêłŒ ë ìŽëžì êłì°íìŹ ì íë넌 êłì°íëëĄ [`~evaluate.EvaluationModule.compute`]넌 ížì¶í©ëë€:
-
-```py
->>> import numpy as np
-
-
->>> def compute_metrics(eval_pred):
-... predictions, labels = eval_pred
-... predictions = np.argmax(predictions, axis=1)
-... return accuracy.compute(predictions=predictions, references=labels)
-```
-
-ìŽì `compute_metrics` íšìë ì€ëčëìêł , íë š êłŒì ì ì€ì í ë ë€ì ìŽíŽëłŒ ìì ì
ëë€.
-
-## íë š[[train]]
-
-ëȘšëžì íë šíêž° ì ì, `id2label`ì `label2id`넌 ìŹì©íìŹ ììëë idì ë ìŽëžì ë§”ì ìì±íìžì:
-
-```py
->>> id2label = {0: "NEGATIVE", 1: "POSITIVE"}
->>> label2id = {"NEGATIVE": 0, "POSITIVE": 1}
-```
-
-
-
-
-
-[`Trainer`]넌 ìŹì©íìŹ ëȘšëžì íìž íëíë ë°©ëČì ì”ìíì§ ìì êČœì°, [ìŹêž°](../training#train-with-pytorch-trainer)ì êž°ëłž íí 늏ìŒì íìžíìžì!
-
-
-
-ìŽì ëȘšëžì íë šìíŹ ì€ëčê° ëìì”ëë€! [`AutoModelForSequenceClassification`]ëĄ DistilBERT넌 ê°ìłì€êł ììëë ë ìŽëž ìì ë ìŽëž ë§€íì ì§ì íìžì:
-
-```py
->>> from transformers import AutoModelForSequenceClassification, TrainingArguments, Trainer
-
->>> model = AutoModelForSequenceClassification.from_pretrained(
-... "distilbert-base-uncased", num_labels=2, id2label=id2label, label2id=label2id
-... )
-```
-
-ìŽì ìž ëšêłë§ ê±°ìč멎 ëì
ëë€:
-
-1. [`TrainingArguments`]ìì íìŽíŒíëŒëŻží°ë„Œ ì ìíìžì. `output_dir`ë ëȘšëžì ì ì„í ììč넌 ì§ì íë ì ìŒí íëŒëŻží°ì
ëë€. ìŽ ëȘšëžì Hubì ì
ëĄëíêž° ìíŽ `push_to_hub=True`넌 ì€ì í©ëë€. (ëȘšëžì ì
ëĄëíêž° ìíŽ Hugging Faceì ëĄê·žìžíŽìŒí©ëë€.) ê° ìíìŽ ëë ëë§ë€, [`Trainer`]ë ì íë넌 íê°íêł íë š ìČŽíŹíŹìžížë„Œ ì ì„í©ëë€.
-2. [`Trainer`]ì íë š ìžìì ëȘšëž, ë°ìŽí°ì
, í íŹëìŽì , ë°ìŽí° ìì§êž° ë° `compute_metrics` íšì넌 ì ëŹíìžì.
-3. [`~Trainer.train`]넌 ížì¶íìŹ ëȘšëžì íìž íëíìžì.
-
-```py
->>> training_args = TrainingArguments(
-... output_dir="my_awesome_model",
-... learning_rate=2e-5,
-... per_device_train_batch_size=16,
-... per_device_eval_batch_size=16,
-... num_train_epochs=2,
-... weight_decay=0.01,
-... evaluation_strategy="epoch",
-... save_strategy="epoch",
-... load_best_model_at_end=True,
-... push_to_hub=True,
-... )
-
->>> trainer = Trainer(
-... model=model,
-... args=training_args,
-... train_dataset=tokenized_imdb["train"],
-... eval_dataset=tokenized_imdb["test"],
-... tokenizer=tokenizer,
-... data_collator=data_collator,
-... compute_metrics=compute_metrics,
-... )
-
->>> trainer.train()
-```
-
-
-
-[`Trainer`]ë `tokenizer`넌 ì ëŹí멎 êž°ëłžì ìŒëĄ ëì ë§€íì ì ì©í©ëë€. ìŽ êČœì°, ëȘ
ìì ìŒëĄ ë°ìŽí° ìì§êž°ë„Œ ì§ì í íìê° ìì”ëë€.
-
-
-
-íë šìŽ ìëŁë멎, [`~transformers.Trainer.push_to_hub`] ë©ìë넌 ìŹì©íìŹ ëȘšëžì Hubì êł”ì í ì ìì”ëë€.
-
-```py
->>> trainer.push_to_hub()
-```
-
-
-
-
-Keras넌 ìŹì©íìŹ ëȘšëžì íìž íëíë ë°©ëČì ì”ìíì§ ìì êČœì°, [ìŹêž°](../training#train-a-tensorflow-model-with-keras)ì êž°ëłž íí 늏ìŒì íìžíìžì!
-
-
-TensorFlowìì ëȘšëžì íìž íëíë €ë©Ž, 뚌ì ì”í°ë§ìŽì íšìì íì”ë„ ì€ìŒì„Ž, ê·žëŠŹêł ìŒë¶ íë š íìŽíŒíëŒëŻží°ë„Œ ì€ì íŽìŒ í©ëë€:
-
-```py
->>> from transformers import create_optimizer
->>> import tensorflow as tf
-
->>> batch_size = 16
->>> num_epochs = 5
->>> batches_per_epoch = len(tokenized_imdb["train"]) // batch_size
->>> total_train_steps = int(batches_per_epoch * num_epochs)
->>> optimizer, schedule = create_optimizer(init_lr=2e-5, num_warmup_steps=0, num_train_steps=total_train_steps)
-```
-
-ê·žë° ë€ì [`TFAutoModelForSequenceClassification`]ì ìŹì©íìŹ DistilBERT넌 ëĄëíêł , ììëë ë ìŽëž ìì ë ìŽëž ë§€íì ëĄëí ì ìì”ëë€:
-
-```py
->>> from transformers import TFAutoModelForSequenceClassification
-
->>> model = TFAutoModelForSequenceClassification.from_pretrained(
-... "distilbert-base-uncased", num_labels=2, id2label=id2label, label2id=label2id
-... )
-```
-
-[`~transformers.TFPreTrainedModel.prepare_tf_dataset`]ì ìŹì©íìŹ ë°ìŽí°ì
ì `tf.data.Dataset` íììŒëĄ ëłíí©ëë€:
-
-```py
->>> tf_train_set = model.prepare_tf_dataset(
-... tokenized_imdb["train"],
-... shuffle=True,
-... batch_size=16,
-... collate_fn=data_collator,
-... )
-
->>> tf_validation_set = model.prepare_tf_dataset(
-... tokenized_imdb["test"],
-... shuffle=False,
-... batch_size=16,
-... collate_fn=data_collator,
-... )
-```
-
-[`compile`](https://keras.io/api/models/model_training_apis/#compile-method)넌 ìŹì©íìŹ íë ší ëȘšëžì ê”Źì±í©ëë€:
-
-```py
->>> import tensorflow as tf
-
->>> model.compile(optimizer=optimizer)
-```
-
-íë šì ììíêž° ì ì ì€ì íŽìŒí ë§ì§ë§ ë ê°ì§ë ììžĄìì ì íë넌 êłì°íêł , ëȘšëžì Hubì ì
ëĄëí ë°©ëČì ì êł”íë êČì
ëë€. ëȘšë [Keras callbacks](../main_classes/keras_callbacks)넌 ìŹì©íìŹ ìíë©ëë€.
-
-[`~transformers.KerasMetricCallback`]ì `compute_metrics`넌 ì ëŹíìŹ ì íë넌 ëì
ëë€.
-
-```py
->>> from transformers.keras_callbacks import KerasMetricCallback
-
->>> metric_callback = KerasMetricCallback(metric_fn=compute_metrics, eval_dataset=tf_validation_set)
-```
-
-[`~transformers.PushToHubCallback`]ìì ëȘšëžêłŒ í íŹëìŽì 넌 ì
ëĄëí ììč넌 ì§ì í©ëë€:
-
-```py
->>> from transformers.keras_callbacks import PushToHubCallback
-
->>> push_to_hub_callback = PushToHubCallback(
-... output_dir="my_awesome_model",
-... tokenizer=tokenizer,
-... )
-```
-
-ê·žë° ë€ì ìœë°±ì íšê» 돶ì”ëë€:
-
-```py
->>> callbacks = [metric_callback, push_to_hub_callback]
-```
-
-ëëìŽ, ëȘšëž íë šì ììí ì€ëčê° ëìì”ëë€! [`fit`](https://keras.io/api/models/model_training_apis/#fit-method)ì íë š ë°ìŽí°ì
, êČìŠ ë°ìŽí°ì
, ìíì ì ë° ìœë°±ì ì ëŹíìŹ íìž íëí©ëë€:
-
-```py
->>> model.fit(x=tf_train_set, validation_data=tf_validation_set, epochs=3, callbacks=callbacks)
-```
-
-íë šìŽ ìëŁë멎, ëȘšëžìŽ ìëìŒëĄ Hubì ì
ëĄëëìŽ ëȘšë ìŹëìŽ ìŹì©í ì ìì”ëë€!
-
-
-
-
-
-í
ì€íž ë¶ë„넌 ìí ëȘšëžì íìž íëíë ììží ìì ë ë€ì [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)넌 ì°žìĄ°íìžì.
-
-
-
-## ì¶ëĄ [[inference]]
-
-ìąìì, ìŽì ëȘšëžì íìž íëíìŒë ì¶ëĄ ì ìŹì©í ì ìì”ëë€!
-
-ì¶ëĄ ì ìííêł ì íë í
ì€ížë„Œ ê°ì žìëŽ
ìë€:
-
-```py
->>> text = "This was a masterpiece. Not completely faithful to the books, but enthralling from beginning to end. Might be my favorite of the three."
-```
-
-íìž íëë ëȘšëžëĄ ì¶ëĄ ì ìëíë ê°ì„ ê°ëší ë°©ëČì [`pipeline`]넌 ìŹì©íë êČì
ëë€. ëȘšëžëĄ ê°ì ë¶ìì ìí `pipeline`ì ìžì€íŽì€ííêł , í
ì€ížë„Œ ì ëŹíŽëłŽìžì:
-
-```py
->>> from transformers import pipeline
-
->>> classifier = pipeline("sentiment-analysis", model="stevhliu/my_awesome_model")
->>> classifier(text)
-[{'label': 'POSITIVE', 'score': 0.9994940757751465}]
-```
-
-ìíë€ë©Ž, `pipeline`ì êČ°êłŒë„Œ ìëìŒëĄ ëł”ì í ìë ìì”ëë€.
-
-
-
-í
ì€ížë„Œ í í°ííêł PyTorch í
ì넌 ë°íí©ëë€.
-
-```py
->>> from transformers import AutoTokenizer
-
->>> tokenizer = AutoTokenizer.from_pretrained("stevhliu/my_awesome_model")
->>> inputs = tokenizer(text, return_tensors="pt")
-```
-
-ì
ë „ì ëȘšëžì ì ëŹíêł `logits`ì ë°íí©ëë€:
-
-```py
->>> from transformers import AutoModelForSequenceClassification
-
->>> model = AutoModelForSequenceClassification.from_pretrained("stevhliu/my_awesome_model")
->>> with torch.no_grad():
-... logits = model(**inputs).logits
-```
-
-ê°ì„ ëì íë„ ì ê°ì§ íŽëì€ë„Œ ëȘšëžì `id2label` ë§€íì ìŹì©íìŹ í
ì€íž ë ìŽëžëĄ ëłíí©ëë€:
-
-```py
->>> predicted_class_id = logits.argmax().item()
->>> model.config.id2label[predicted_class_id]
-'POSITIVE'
-```
-
-
-í
ì€ížë„Œ í í°ííêł TensorFlow í
ì넌 ë°íí©ëë€:
-
-```py
->>> from transformers import AutoTokenizer
-
->>> tokenizer = AutoTokenizer.from_pretrained("stevhliu/my_awesome_model")
->>> inputs = tokenizer(text, return_tensors="tf")
-```
-
-ì
ë „ê°ì ëȘšëžì ì ëŹíêł `logits`ì ë°íí©ëë€:
-
-```py
->>> from transformers import TFAutoModelForSequenceClassification
-
->>> model = TFAutoModelForSequenceClassification.from_pretrained("stevhliu/my_awesome_model")
->>> logits = model(**inputs).logits
-```
-
-ê°ì„ ëì íë„ ì ê°ì§ íŽëì€ë„Œ ëȘšëžì `id2label` ë§€íì ìŹì©íìŹ í
ì€íž ë ìŽëžëĄ ëłíí©ëë€:
-
-```py
->>> predicted_class_id = int(tf.math.argmax(logits, axis=-1)[0])
->>> model.config.id2label[predicted_class_id]
-'POSITIVE'
-```
-
-
diff --git a/docs/source/ko/tasks/summarization.md b/docs/source/ko/tasks/summarization.md
new file mode 100644
index 000000000000..5ca5f63a27c9
--- /dev/null
+++ b/docs/source/ko/tasks/summarization.md
@@ -0,0 +1,418 @@
+
+
+# ììœ[[summarization]]
+
+[[open-in-colab]]
+
+
+
+ììœì 돞ìë êž°ìŹìì ì€ìí ì ëłŽë„Œ ëȘšë íŹíšíë ì§§êČ ë§ëë ìŒì
ëë€.
+ëČìêłŒ ë§ì°Źê°ì§ëĄ, ìíì€-íŹ-ìíì€ ëŹžì ëĄ ê”Źì±í ì ìë ëíì ìž ìì
ì€ íëì
ëë€.
+ììœìë ìëì ê°ìŽ ì íìŽ ìì”ëë€:
+
+- ì¶ì¶(Extractive) ììœ: 돞ììì ê°ì„ êŽë šì± ëì ì ëłŽë„Œ ì¶ì¶í©ëë€.
+- ìì±(Abstractive) ììœ: ê°ì„ êŽë šì± ëì ì ëłŽë„Œ íŹì°©íŽëŽë ìëĄìŽ í
ì€ížë„Œ ìì±í©ëë€.
+
+ìŽ ê°ìŽëìì ìê°í ëŽì©ì ìëì ê°ì”ëë€:
+
+1. ìì± ììœì ìí [BillSum](https://huggingface.co/datasets/billsum) ë°ìŽí°ì
ì€ ìș늏íŹëì ìŁŒ ëČì íì ì§í©ìŒëĄ [T5](https://huggingface.co/t5-small)넌 íìžíëí©ëë€.
+2. íìžíëë ëȘšëžì ìŹì©íìŹ ì¶ëĄ í©ëë€.
+
+
+ìŽ íí 늏ìŒìì ì€ëȘ
íë ìì
ì ë€ì ëȘšëž ìí€í
ìČìì ì§ìë©ëë€:
+
+
+
+[BART](../model_doc/bart), [BigBird-Pegasus](../model_doc/bigbird_pegasus), [Blenderbot](../model_doc/blenderbot), [BlenderbotSmall](../model_doc/blenderbot-small), [Encoder decoder](../model_doc/encoder-decoder), [FairSeq Machine-Translation](../model_doc/fsmt), [GPTSAN-japanese](../model_doc/gptsan-japanese), [LED](../model_doc/led), [LongT5](../model_doc/longt5), [M2M100](../model_doc/m2m_100), [Marian](../model_doc/marian), [mBART](../model_doc/mbart), [MT5](../model_doc/mt5), [MVP](../model_doc/mvp), [NLLB](../model_doc/nllb), [NLLB-MOE](../model_doc/nllb-moe), [Pegasus](../model_doc/pegasus), [PEGASUS-X](../model_doc/pegasus_x), [PLBart](../model_doc/plbart), [ProphetNet](../model_doc/prophetnet), [SwitchTransformers](../model_doc/switch_transformers), [T5](../model_doc/t5), [XLM-ProphetNet](../model_doc/xlm-prophetnet)
+
+
+
+
+
+ììíêž° ì ì íìí ëŒìŽëžëŹëŠŹê° ëȘšë ì€ìčëìŽ ìëì§ íìžíìžì:
+
+```bash
+pip install transformers datasets evaluate rouge_score
+```
+
+Hugging Face êłì ì ëĄê·žìží멎 ëȘšëžì ì
ëĄëíêł ì»€ëź€ëí°ì êł”ì í ì ìì”ëë€.
+í í°ì ì
ë „íìŹ ëĄê·žìžíìžì.
+
+```py
+>>> from huggingface_hub import notebook_login
+
+>>> notebook_login()
+```
+
+## BillSum ë°ìŽí°ì
ê°ì žì€êž°[[load-billsum-dataset]]
+
+đ€ Datasets ëŒìŽëžëŹëŠŹìì BillSum ë°ìŽí°ì
ì ìì ëČì ìž ìș늏íŹëì ìŁŒ ëČì íì ì§í©ì ê°ì žì€ìžì:
+
+```py
+>>> from datasets import load_dataset
+
+>>> billsum = load_dataset("billsum", split="ca_test")
+```
+
+[`~datasets.Dataset.train_test_split`] ë©ìëëĄ ë°ìŽí°ì
ì íì”ì©ì í
ì€ížì©ìŒëĄ ëëìžì:
+
+```py
+>>> billsum = billsum.train_test_split(test_size=0.2)
+```
+
+ê·žë° ë€ì ìì넌 íë ìŽíŽëłŽìžì:
+
+```py
+>>> billsum["train"][0]
+{'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.',
+ '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.',
+ 'title': 'An act to add Section 10295.35 to the Public Contract Code, relating to public contracts.'}
+```
+
+ìŹêž°ì ë€ì ë ê°ì íë넌 ìŹì©íêČ ë©ëë€:
+
+- `text`: ëȘšëžì ì
ë „ìŽ ë ëČì í
ì€ížì
ëë€.
+- `summary`: `text`ì ê°ë”í ëČì ìŒëĄ ëȘšëžì íêČìŽ ë©ëë€.
+
+## ì ìČ늏[[preprocess]]
+
+ë€ììŒëĄ `text`ì `summary`넌 ìČ늏íêž° ìí T5 í íŹëìŽì 넌 ê°ì žì”ëë€:
+
+```py
+>>> from transformers import AutoTokenizer
+
+>>> checkpoint = "t5-small"
+>>> tokenizer = AutoTokenizer.from_pretrained(checkpoint)
+```
+
+ìì±íë €ë ì ìČ늏 íšìë ìë ìĄ°ê±Žì ë§ìĄ±íŽìŒ í©ëë€:
+
+1. ì
ë „ ìì í륏íížë„Œ ë¶ìŹ T5ê° ììœ ìì
ìì ìžìí ì ìëëĄ í©ëë€. ìŹëŹ NLP ìì
ì ìíí ì ìë ìŒë¶ ëȘšëžì íčì ìì
ì ëí í륏íížê° íìí©ëë€.
+2. ë ìŽëžì í í°íí ë `text_target` ìžì넌 ìŹì©í©ëë€.
+3. `max_length` ë§€ê°ëłìëĄ ì€ì ë ì”ë êžžìŽë„Œ ëì§ ìëëĄ êžŽ ìíì€ë„Œ ìëŒë
ëë€.
+
+```py
+>>> prefix = "summarize: "
+
+
+>>> def preprocess_function(examples):
+... inputs = [prefix + doc for doc in examples["text"]]
+... model_inputs = tokenizer(inputs, max_length=1024, truncation=True)
+
+... labels = tokenizer(text_target=examples["summary"], max_length=128, truncation=True)
+
+... model_inputs["labels"] = labels["input_ids"]
+... return model_inputs
+```
+
+ì ìČŽ ë°ìŽí°ì
ì ì ìČ늏 íšì넌 ì ì©íë €ë©Ž đ€ Datasetsì [`~datasets.Dataset.map`] ë©ìë넌 ìŹì©íìžì.
+`batched=True`ëĄ ì€ì íìŹ ë°ìŽí°ì
ì ìŹëŹ ìì넌 í ëČì ìČ늏í멎 `map` íšìì ìë넌 ëìŒ ì ìì”ëë€.
+
+```py
+>>> tokenized_billsum = billsum.map(preprocess_function, batched=True)
+```
+
+ìŽì [`DataCollatorForSeq2Seq`]넌 ìŹì©íìŹ ìì ë°°ìč넌 ë§ëìžì.
+ì ìČŽ ë°ìŽí°ì
ì ì”ë êžžìŽëĄ íšë©íë êČëłŽë€ ë°°ìčë§ë€ ê°ì„ ꞎ ëŹžì„ êžžìŽì ë§ì¶° *ëì íšë©*íë êČìŽ ë íšìšì ì
ëë€.
+
+
+
+```py
+>>> from transformers import DataCollatorForSeq2Seq
+
+>>> data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer, model=checkpoint)
+```
+
+
+```py
+>>> from transformers import DataCollatorForSeq2Seq
+
+>>> data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer, model=checkpoint, return_tensors="tf")
+```
+
+
+
+## íê°[[evaluate]]
+
+íì” ì€ì íê° ì§í넌 íŹíší멎 ëȘšëžì ì±ë„ì íê°íë ë° ëììŽ ëë êČœì°ê° ë§ì”ëë€.
+đ€ [Evaluate](https://huggingface.co/docs/evaluate/index) ëŒìŽëžëŹëŠŹë„Œ ìŹì©í멎 íê° ë°©ëČì ëč 넎êČ ë¶ëŹìŹ ì ìì”ëë€.
+ìŽ ìì
ììë [ROUGE](https://huggingface.co/spaces/evaluate-metric/rouge) íê° ì§í넌 ê°ì žì”ëë€.
+(íê° ì§í넌 ë¶ëŹì€êł êłì°íë ë°©ëČì đ€ Evaluate [ëëŹëłŽêž°](https://huggingface.co/docs/evaluate/a_quick_tour)넌 ì°žìĄ°íìžì.)
+
+```py
+>>> import evaluate
+
+>>> rouge = evaluate.load("rouge")
+```
+
+ê·žë° ë€ì ììžĄê°êłŒ ë ìŽëžì [`~evaluate.EvaluationModule.compute`]ì ì ëŹíìŹ ROUGE ì§í넌 êłì°íë íšì넌 ë§ëëë€:
+
+```py
+>>> import numpy as np
+
+
+>>> def compute_metrics(eval_pred):
+... predictions, labels = eval_pred
+... decoded_preds = tokenizer.batch_decode(predictions, skip_special_tokens=True)
+... labels = np.where(labels != -100, labels, tokenizer.pad_token_id)
+... decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)
+
+... result = rouge.compute(predictions=decoded_preds, references=decoded_labels, use_stemmer=True)
+
+... prediction_lens = [np.count_nonzero(pred != tokenizer.pad_token_id) for pred in predictions]
+... result["gen_len"] = np.mean(prediction_lens)
+
+... return {k: round(v, 4) for k, v in result.items()}
+```
+
+ìŽì `compute_metrics` íšì넌 ìŹì©í ì€ëčê° ëììŒë©°, íì”ì ì€ì í ë ìŽ íšìëĄ ëëììŹ êČì
ëë€.
+
+## íì”[[train]]
+
+
+
+
+
+ëȘšëžì [`Trainer`]ëĄ íìžíë íë êČìŽ ì”ìíì§ ìë€ë©Ž, [ìŹêž°](../training#train-with-pytorch-trainer)ìì êž°ëłž íí 늏ìŒì íìžíŽëłŽìžì!
+
+
+
+ìŽì ëȘšëž íì”ì ììí ì€ëčê° ëìì”ëë€! [`AutoModelForSeq2SeqLM`]ëĄ T5넌 ê°ì žì€ìžì:
+
+```py
+>>> from transformers import AutoModelForSeq2SeqLM, Seq2SeqTrainingArguments, Seq2SeqTrainer
+
+>>> model = AutoModelForSeq2SeqLM.from_pretrained(checkpoint)
+```
+
+ìŽì ìž ëšêłë§ ëšìì”ëë€:
+
+1. [`Seq2SeqTrainingArguments`]ìì íì” íìŽíŒíëŒëŻží°ë„Œ ì ìíìžì.
+ì ìŒí íì ë§€ê°ëłìë ëȘšëžì ì ì„í ììč넌 ì§ì íë `output_dir`ì
ëë€.
+`push_to_hub=True`넌 ì€ì íìŹ ìŽ ëȘšëžì Hubì ížìí ì ìì”ëë€(ëȘšëžì ì
ëĄëíë €ë©Ž Hugging Faceì ëĄê·žìžíŽìŒ í©ëë€.)
+[`Trainer`]ë ê° ìíìŽ ëë ëë§ë€ ROUGE ì§í넌 íê°íêł íì” ìČŽíŹíŹìžížë„Œ ì ì„í©ëë€.
+2. ëȘšëž, ë°ìŽí°ì
, í íŹëìŽì , ë°ìŽí° ìœë ìŽí° ë° `compute_metrics` íšìì íšê» íì” ìžì넌 [`Seq2SeqTrainer`]ì ì ëŹíìžì.
+3. [`~Trainer.train`]ì ížì¶íìŹ ëȘšëžì íìžíëíìžì.
+
+```py
+>>> training_args = Seq2SeqTrainingArguments(
+... output_dir="my_awesome_billsum_model",
+... evaluation_strategy="epoch",
+... learning_rate=2e-5,
+... per_device_train_batch_size=16,
+... per_device_eval_batch_size=16,
+... weight_decay=0.01,
+... save_total_limit=3,
+... num_train_epochs=4,
+... predict_with_generate=True,
+... fp16=True,
+... push_to_hub=True,
+... )
+
+>>> trainer = Seq2SeqTrainer(
+... model=model,
+... args=training_args,
+... train_dataset=tokenized_billsum["train"],
+... eval_dataset=tokenized_billsum["test"],
+... tokenizer=tokenizer,
+... data_collator=data_collator,
+... compute_metrics=compute_metrics,
+... )
+
+>>> trainer.train()
+```
+
+íì”ìŽ ìëŁë멎, ëê”Źë ëȘšëžì ìŹì©í ì ìëëĄ [`~transformers.Trainer.push_to_hub`] ë©ìëëĄ Hubì êł”ì í©ëë€:
+
+```py
+>>> trainer.push_to_hub()
+```
+
+
+
+
+KerasëĄ ëȘšëž íìžíëì íë êČìŽ ì”ìíì§ ìë€ë©Ž, [ìŹêž°](../training#train-a-tensorflow-model-with-keras)ìì êž°ëłžì ìž íí 늏ìŒì íìžíìžì!
+
+
+TensorFlowìì ëȘšëžì íìžíëíë €ë©Ž, 뚌ì ì”í°ë§ìŽì , íì”ë„ ì€ìŒì€ ê·žëŠŹêł ëȘ ê°ì§ íì” íìŽíŒíëŒëŻží°ë„Œ ì€ì íìžì:
+
+```py
+>>> from transformers import create_optimizer, AdamWeightDecay
+
+>>> optimizer = AdamWeightDecay(learning_rate=2e-5, weight_decay_rate=0.01)
+```
+
+ê·žë° ë€ì [`TFAutoModelForSeq2SeqLM`]ì ìŹì©íìŹ T5넌 ê°ì žì€ìžì:
+
+```py
+>>> from transformers import TFAutoModelForSeq2SeqLM
+
+>>> model = TFAutoModelForSeq2SeqLM.from_pretrained(checkpoint)
+```
+
+[`~transformers.TFPreTrainedModel.prepare_tf_dataset`]ì ìŹì©íìŹ ë°ìŽí°ì
ì `tf.data.Dataset` íììŒëĄ ëłííìžì:
+
+```py
+>>> tf_train_set = model.prepare_tf_dataset(
+... tokenized_billsum["train"],
+... shuffle=True,
+... batch_size=16,
+... collate_fn=data_collator,
+... )
+
+>>> tf_test_set = model.prepare_tf_dataset(
+... tokenized_billsum["test"],
+... shuffle=False,
+... batch_size=16,
+... collate_fn=data_collator,
+... )
+```
+
+[`compile`](https://keras.io/api/models/model_training_apis/#compile-method)ì ìŹì©íìŹ ëȘšëžì íì”í ì ìëëĄ ê”Źì±íìžì:
+
+```py
+>>> import tensorflow as tf
+
+>>> model.compile(optimizer=optimizer)
+```
+
+íì”ì ììíêž° ì ì ì€ì íŽìŒ í ë§ì§ë§ ë ê°ì§ë ììžĄìì ROUGE ì ì넌 êłì°íêł ëȘšëžì Hubì ížìíë ë°©ëČì ì êł”íë êČì
ëë€.
+ë ìì
ëȘšë [Keras callbacks](../main_classes/keras_callbacks)ìŒëĄ ìíí ì ìì”ëë€.
+
+[`~transformers.KerasMetricCallback`]ì `compute_metrics` íšì넌 ì ëŹíìžì:
+
+```py
+>>> from transformers.keras_callbacks import KerasMetricCallback
+
+>>> metric_callback = KerasMetricCallback(metric_fn=compute_metrics, eval_dataset=tf_validation_set)
+```
+
+[`~transformers.PushToHubCallback`]ìì ëȘšëžêłŒ í íŹëìŽì 넌 ížìí ììč넌 ì§ì íìžì:
+
+```py
+>>> from transformers.keras_callbacks import PushToHubCallback
+
+>>> push_to_hub_callback = PushToHubCallback(
+... output_dir="my_awesome_billsum_model",
+... tokenizer=tokenizer,
+... )
+```
+
+ê·žë° ë€ì ìœë°±ì ëČë€ëĄ 돶ìŽì€ëë€:
+
+```py
+>>> callbacks = [metric_callback, push_to_hub_callback]
+```
+
+ëëìŽ ëȘšëž íì”ì ììí ì€ëčê° ëìì”ëë€!
+íì” ë° êČìŠ ë°ìŽí°ì
, ìí ì ë° ìœë°±êłŒ íšê» [`fit`](https://keras.io/api/models/model_training_apis/#fit-method)ì ížì¶íìŹ ëȘšëžì íìžíëíìžì.
+
+```py
+>>> model.fit(x=tf_train_set, validation_data=tf_test_set, epochs=3, callbacks=callbacks)
+```
+
+íì”ìŽ ìëŁë멎 ëȘšëžìŽ ìëìŒëĄ Hubì ì
ëĄëëìŽ ëê”Źë ìŹì©í ì ìêČ ë©ëë€!
+
+
+
+
+
+ììœì ìíŽ ëȘšëžì íìžíëíë ë°©ëČì ëí ë ììží ìì 넌 ëłŽë €ë©Ž [PyTorch notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/summarization.ipynb)
+ëë [TensorFlow notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/summarization-tf.ipynb)ì ì°žêł íìžì.
+
+
+
+## ì¶ëĄ [[inference]]
+
+ìąìì, ìŽì ëȘšëžì íìžíëíìŒë ì¶ëĄ ì ìŹì©í ì ìì”ëë€!
+
+ììœí í
ì€ížë„Œ ìì±íŽëłŽìžì. T5ì êČœì° ìì
ì ë°ëŒ ì
ë „ ìì ì ëìŹë„Œ ë¶ìŹìŒ í©ëë€. ììœì êČœì°, ìëì ê°ì ì ëìŹë„Œ ì
ë „ ìì ë¶ìŹìŒ í©ëë€:
+
+```py
+>>> 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."
+```
+
+ì¶ëĄ ì ìíŽ íìžíëí ëȘšëžì ìííŽ ëłŽë ê°ì„ ê°ëší ë°©ëČì [`pipeline`]ìì ìŹì©íë êČì
ëë€.
+ëȘšëžì ìŹì©íìŹ ììœì ìíí [`pipeline`]ì ìžì€íŽì€ííêł í
ì€ížë„Œ ì ëŹíìžì:
+
+```py
+>>> from transformers import pipeline
+
+>>> summarizer = pipeline("summarization", model="stevhliu/my_awesome_billsum_model")
+>>> summarizer(text)
+[{"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."}]
+```
+
+ìíë€ë©Ž ìëìŒëĄ ë€ìêłŒ ê°ì ìì
ì ìííìŹ [`pipeline`]ì êČ°êłŒì ëìŒí êČ°êłŒë„Œ ì»ì ì ìì”ëë€:
+
+
+
+
+í
ì€ížë„Œ í íŹëìŽìŠíêł `input_ids`넌 PyTorch í
ìëĄ ë°íí©ëë€:
+
+```py
+>>> from transformers import AutoTokenizer
+
+>>> tokenizer = AutoTokenizer.from_pretrained("stevhliu/my_awesome_billsum_model")
+>>> inputs = tokenizer(text, return_tensors="pt").input_ids
+```
+
+ììœëŹžì ìì±íë €ë©Ž [`~transformers.generation_utils.GenerationMixin.generate`] ë©ìë넌 ìŹì©íìžì.
+í
ì€íž ìì±ì ëí ë€ìí ì ë”êłŒ ìì±ì ì ìŽíêž° ìí ë§€ê°ëłìì ëí ììží ëŽì©ì [í
ì€íž ìì±](../main_classes/text_generation) API넌 ì°žìĄ°íìžì.
+
+```py
+>>> from transformers import AutoModelForSeq2SeqLM
+
+>>> model = AutoModelForSeq2SeqLM.from_pretrained("stevhliu/my_awesome_billsum_model")
+>>> outputs = model.generate(inputs, max_new_tokens=100, do_sample=False)
+```
+
+ìì±ë í í° ID넌 í
ì€ížëĄ ëìœë©í©ëë€:
+
+```py
+>>> tokenizer.decode(outputs[0], skip_special_tokens=True)
+'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.'
+```
+
+
+í
ì€ížë„Œ í íŹëìŽìŠíêł `input_ids`넌 TensorFlow í
ìëĄ ë°íí©ëë€:
+
+```py
+>>> from transformers import AutoTokenizer
+
+>>> tokenizer = AutoTokenizer.from_pretrained("stevhliu/my_awesome_billsum_model")
+>>> inputs = tokenizer(text, return_tensors="tf").input_ids
+```
+
+ììœëŹžì ìì±íë €ë©Ž [`~transformers.generation_tf_utils.TFGenerationMixin.generate`] ë©ìë넌 ìŹì©íìžì.
+í
ì€íž ìì±ì ëí ë€ìí ì ë”êłŒ ìì±ì ì ìŽíêž° ìí ë§€ê°ëłìì ëí ììží ëŽì©ì [í
ì€íž ìì±](../main_classes/text_generation) API넌 ì°žìĄ°íìžì.
+
+```py
+>>> from transformers import TFAutoModelForSeq2SeqLM
+
+>>> model = TFAutoModelForSeq2SeqLM.from_pretrained("stevhliu/my_awesome_billsum_model")
+>>> outputs = model.generate(inputs, max_new_tokens=100, do_sample=False)
+```
+
+ìì±ë í í° ID넌 í
ì€ížëĄ ëìœë©í©ëë€:
+
+```py
+>>> tokenizer.decode(outputs[0], skip_special_tokens=True)
+'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.'
+```
+
+
diff --git a/docs/source/ko/tasks/summarization.mdx b/docs/source/ko/tasks/summarization.mdx
deleted file mode 100644
index 19c6c7073218..000000000000
--- a/docs/source/ko/tasks/summarization.mdx
+++ /dev/null
@@ -1,414 +0,0 @@
-
-
-# ììœ[[summarization]]
-
-[[open-in-colab]]
-
-
-
-ììœì 돞ìë êž°ìŹìì ì€ìí ì ëłŽë„Œ ëȘšë íŹíšíë ì§§êČ ë§ëë ìŒì
ëë€.
-ëČìêłŒ ë§ì°Źê°ì§ëĄ, ìíì€-íŹ-ìíì€ ëŹžì ëĄ ê”Źì±í ì ìë ëíì ìž ìì
ì€ íëì
ëë€.
-ììœìë ìëì ê°ìŽ ì íìŽ ìì”ëë€:
-
-- ì¶ì¶(Extractive) ììœ: 돞ììì ê°ì„ êŽë šì± ëì ì ëłŽë„Œ ì¶ì¶í©ëë€.
-- ìì±(Abstractive) ììœ: ê°ì„ êŽë šì± ëì ì ëłŽë„Œ íŹì°©íŽëŽë ìëĄìŽ í
ì€ížë„Œ ìì±í©ëë€.
-
-ìŽ ê°ìŽëìì ìê°í ëŽì©ì ìëì ê°ì”ëë€:
-
-1. ìì± ììœì ìí [BillSum](https://huggingface.co/datasets/billsum) ë°ìŽí°ì
ì€ ìș늏íŹëì ìŁŒ ëČì íì ì§í©ìŒëĄ [T5](https://huggingface.co/t5-small)넌 íìžíëí©ëë€.
-2. íìžíëë ëȘšëžì ìŹì©íìŹ ì¶ëĄ í©ëë€.
-
-
-ìŽ íí 늏ìŒìì ì€ëȘ
íë ìì
ì ë€ì ëȘšëž ìí€í
ìČìì ì§ìë©ëë€:
-
-
-
-[BART](../model_doc/bart), [BigBird-Pegasus](../model_doc/bigbird_pegasus), [Blenderbot](../model_doc/blenderbot), [BlenderbotSmall](../model_doc/blenderbot-small), [Encoder decoder](../model_doc/encoder-decoder), [FairSeq Machine-Translation](../model_doc/fsmt), [GPTSAN-japanese](../model_doc/gptsan-japanese), [LED](../model_doc/led), [LongT5](../model_doc/longt5), [M2M100](../model_doc/m2m_100), [Marian](../model_doc/marian), [mBART](../model_doc/mbart), [MT5](../model_doc/mt5), [MVP](../model_doc/mvp), [NLLB](../model_doc/nllb), [NLLB-MOE](../model_doc/nllb-moe), [Pegasus](../model_doc/pegasus), [PEGASUS-X](../model_doc/pegasus_x), [PLBart](../model_doc/plbart), [ProphetNet](../model_doc/prophetnet), [SwitchTransformers](../model_doc/switch_transformers), [T5](../model_doc/t5), [XLM-ProphetNet](../model_doc/xlm-prophetnet)
-
-
-
-
-
-ììíêž° ì ì íìí ëŒìŽëžëŹëŠŹê° ëȘšë ì€ìčëìŽ ìëì§ íìžíìžì:
-
-```bash
-pip install transformers datasets evaluate rouge_score
-```
-
-Hugging Face êłì ì ëĄê·žìží멎 ëȘšëžì ì
ëĄëíêł ì»€ëź€ëí°ì êł”ì í ì ìì”ëë€.
-í í°ì ì
ë „íìŹ ëĄê·žìžíìžì.
-
-```py
->>> from huggingface_hub import notebook_login
-
->>> notebook_login()
-```
-
-## BillSum ë°ìŽí°ì
ê°ì žì€êž°[[load-billsum-dataset]]
-
-đ€ Datasets ëŒìŽëžëŹëŠŹìì BillSum ë°ìŽí°ì
ì ìì ëČì ìž ìș늏íŹëì ìŁŒ ëČì íì ì§í©ì ê°ì žì€ìžì:
-
-```py
->>> from datasets import load_dataset
-
->>> billsum = load_dataset("billsum", split="ca_test")
-```
-
-[`~datasets.Dataset.train_test_split`] ë©ìëëĄ ë°ìŽí°ì
ì íì”ì©ì í
ì€ížì©ìŒëĄ ëëìžì:
-
-```py
->>> billsum = billsum.train_test_split(test_size=0.2)
-```
-
-ê·žë° ë€ì ìì넌 íë ìŽíŽëłŽìžì:
-
-```py
->>> billsum["train"][0]
-{'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.',
- '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.',
- 'title': 'An act to add Section 10295.35 to the Public Contract Code, relating to public contracts.'}
-```
-
-ìŹêž°ì ë€ì ë ê°ì íë넌 ìŹì©íêČ ë©ëë€:
-
-- `text`: ëȘšëžì ì
ë „ìŽ ë ëČì í
ì€ížì
ëë€.
-- `summary`: `text`ì ê°ë”í ëČì ìŒëĄ ëȘšëžì íêČìŽ ë©ëë€.
-
-## ì ìČ늏[[preprocess]]
-
-ë€ììŒëĄ `text`ì `summary`넌 ìČ늏íêž° ìí T5 í íŹëìŽì 넌 ê°ì žì”ëë€:
-
-```py
->>> from transformers import AutoTokenizer
-
->>> checkpoint = "t5-small"
->>> tokenizer = AutoTokenizer.from_pretrained(checkpoint)
-```
-
-ìì±íë €ë ì ìČ늏 íšìë ìë ìĄ°ê±Žì ë§ìĄ±íŽìŒ í©ëë€:
-
-1. ì
ë „ ìì í륏íížë„Œ ë¶ìŹ T5ê° ììœ ìì
ìì ìžìí ì ìëëĄ í©ëë€. ìŹëŹ NLP ìì
ì ìíí ì ìë ìŒë¶ ëȘšëžì íčì ìì
ì ëí í륏íížê° íìí©ëë€.
-2. ë ìŽëžì í í°íí ë `text_target` ìžì넌 ìŹì©í©ëë€.
-3. `max_length` ë§€ê°ëłìëĄ ì€ì ë ì”ë êžžìŽë„Œ ëì§ ìëëĄ êžŽ ìíì€ë„Œ ìëŒë
ëë€.
-
-```py
->>> prefix = "summarize: "
-
-
->>> def preprocess_function(examples):
-... inputs = [prefix + doc for doc in examples["text"]]
-... model_inputs = tokenizer(inputs, max_length=1024, truncation=True)
-
-... labels = tokenizer(text_target=examples["summary"], max_length=128, truncation=True)
-
-... model_inputs["labels"] = labels["input_ids"]
-... return model_inputs
-```
-
-ì ìČŽ ë°ìŽí°ì
ì ì ìČ늏 íšì넌 ì ì©íë €ë©Ž đ€ Datasetsì [`~datasets.Dataset.map`] ë©ìë넌 ìŹì©íìžì.
-`batched=True`ëĄ ì€ì íìŹ ë°ìŽí°ì
ì ìŹëŹ ìì넌 í ëČì ìČ늏í멎 `map` íšìì ìë넌 ëìŒ ì ìì”ëë€.
-
-```py
->>> tokenized_billsum = billsum.map(preprocess_function, batched=True)
-```
-
-ìŽì [`DataCollatorForSeq2Seq`]넌 ìŹì©íìŹ ìì ë°°ìč넌 ë§ëìžì.
-ì ìČŽ ë°ìŽí°ì
ì ì”ë êžžìŽëĄ íšë©íë êČëłŽë€ ë°°ìčë§ë€ ê°ì„ ꞎ ëŹžì„ êžžìŽì ë§ì¶° *ëì íšë©*íë êČìŽ ë íšìšì ì
ëë€.
-
-
-
-```py
->>> from transformers import DataCollatorForSeq2Seq
-
->>> data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer, model=checkpoint)
-```
-
-
-```py
->>> from transformers import DataCollatorForSeq2Seq
-
->>> data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer, model=checkpoint, return_tensors="tf")
-```
-
-
-
-## íê°[[evaluate]]
-
-íì” ì€ì íê° ì§í넌 íŹíší멎 ëȘšëžì ì±ë„ì íê°íë ë° ëììŽ ëë êČœì°ê° ë§ì”ëë€.
-đ€ [Evaluate](https://huggingface.co/docs/evaluate/index) ëŒìŽëžëŹëŠŹë„Œ ìŹì©í멎 íê° ë°©ëČì ëč 넎êČ ë¶ëŹìŹ ì ìì”ëë€.
-ìŽ ìì
ììë [ROUGE](https://huggingface.co/spaces/evaluate-metric/rouge) íê° ì§í넌 ê°ì žì”ëë€.
-(íê° ì§í넌 ë¶ëŹì€êł êłì°íë ë°©ëČì đ€ Evaluate [ëëŹëłŽêž°](https://huggingface.co/docs/evaluate/a_quick_tour)넌 ì°žìĄ°íìžì.)
-
-```py
->>> import evaluate
-
->>> rouge = evaluate.load("rouge")
-```
-
-ê·žë° ë€ì ììžĄê°êłŒ ë ìŽëžì [`~evaluate.EvaluationModule.compute`]ì ì ëŹíìŹ ROUGE ì§í넌 êłì°íë íšì넌 ë§ëëë€:
-
-```py
->>> import numpy as np
-
-
->>> def compute_metrics(eval_pred):
-... predictions, labels = eval_pred
-... decoded_preds = tokenizer.batch_decode(predictions, skip_special_tokens=True)
-... labels = np.where(labels != -100, labels, tokenizer.pad_token_id)
-... decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)
-
-... result = rouge.compute(predictions=decoded_preds, references=decoded_labels, use_stemmer=True)
-
-... prediction_lens = [np.count_nonzero(pred != tokenizer.pad_token_id) for pred in predictions]
-... result["gen_len"] = np.mean(prediction_lens)
-
-... return {k: round(v, 4) for k, v in result.items()}
-```
-
-ìŽì `compute_metrics` íšì넌 ìŹì©í ì€ëčê° ëììŒë©°, íì”ì ì€ì í ë ìŽ íšìëĄ ëëììŹ êČì
ëë€.
-
-## íì”[[train]]
-
-
-
-
-
-ëȘšëžì [`Trainer`]ëĄ íìžíë íë êČìŽ ì”ìíì§ ìë€ë©Ž, [ìŹêž°](../training#train-with-pytorch-trainer)ìì êž°ëłž íí 늏ìŒì íìžíŽëłŽìžì!
-
-
-
-ìŽì ëȘšëž íì”ì ììí ì€ëčê° ëìì”ëë€! [`AutoModelForSeq2SeqLM`]ëĄ T5넌 ê°ì žì€ìžì:
-
-```py
->>> from transformers import AutoModelForSeq2SeqLM, Seq2SeqTrainingArguments, Seq2SeqTrainer
-
->>> model = AutoModelForSeq2SeqLM.from_pretrained(checkpoint)
-```
-
-ìŽì ìž ëšêłë§ ëšìì”ëë€:
-
-1. [`Seq2SeqTrainingArguments`]ìì íì” íìŽíŒíëŒëŻží°ë„Œ ì ìíìžì.
-ì ìŒí íì ë§€ê°ëłìë ëȘšëžì ì ì„í ììč넌 ì§ì íë `output_dir`ì
ëë€.
-`push_to_hub=True`넌 ì€ì íìŹ ìŽ ëȘšëžì Hubì ížìí ì ìì”ëë€(ëȘšëžì ì
ëĄëíë €ë©Ž Hugging Faceì ëĄê·žìžíŽìŒ í©ëë€.)
-[`Trainer`]ë ê° ìíìŽ ëë ëë§ë€ ROUGE ì§í넌 íê°íêł íì” ìČŽíŹíŹìžížë„Œ ì ì„í©ëë€.
-2. ëȘšëž, ë°ìŽí°ì
, í íŹëìŽì , ë°ìŽí° ìœë ìŽí° ë° `compute_metrics` íšìì íšê» íì” ìžì넌 [`Seq2SeqTrainer`]ì ì ëŹíìžì.
-3. [`~Trainer.train`]ì ížì¶íìŹ ëȘšëžì íìžíëíìžì.
-
-```py
->>> training_args = Seq2SeqTrainingArguments(
-... output_dir="my_awesome_billsum_model",
-... evaluation_strategy="epoch",
-... learning_rate=2e-5,
-... per_device_train_batch_size=16,
-... per_device_eval_batch_size=16,
-... weight_decay=0.01,
-... save_total_limit=3,
-... num_train_epochs=4,
-... predict_with_generate=True,
-... fp16=True,
-... push_to_hub=True,
-... )
-
->>> trainer = Seq2SeqTrainer(
-... model=model,
-... args=training_args,
-... train_dataset=tokenized_billsum["train"],
-... eval_dataset=tokenized_billsum["test"],
-... tokenizer=tokenizer,
-... data_collator=data_collator,
-... compute_metrics=compute_metrics,
-... )
-
->>> trainer.train()
-```
-
-íì”ìŽ ìëŁë멎, ëê”Źë ëȘšëžì ìŹì©í ì ìëëĄ [`~transformers.Trainer.push_to_hub`] ë©ìëëĄ Hubì êł”ì í©ëë€:
-
-```py
->>> trainer.push_to_hub()
-```
-
-
-
-
-KerasëĄ ëȘšëž íìžíëì íë êČìŽ ì”ìíì§ ìë€ë©Ž, [ìŹêž°](../training#train-a-tensorflow-model-with-keras)ìì êž°ëłžì ìž íí 늏ìŒì íìžíìžì!
-
-
-TensorFlowìì ëȘšëžì íìžíëíë €ë©Ž, 뚌ì ì”í°ë§ìŽì , íì”ë„ ì€ìŒì€ ê·žëŠŹêł ëȘ ê°ì§ íì” íìŽíŒíëŒëŻží°ë„Œ ì€ì íìžì:
-
-```py
->>> from transformers import create_optimizer, AdamWeightDecay
-
->>> optimizer = AdamWeightDecay(learning_rate=2e-5, weight_decay_rate=0.01)
-```
-
-ê·žë° ë€ì [`TFAutoModelForSeq2SeqLM`]ì ìŹì©íìŹ T5넌 ê°ì žì€ìžì:
-
-```py
->>> from transformers import TFAutoModelForSeq2SeqLM
-
->>> model = TFAutoModelForSeq2SeqLM.from_pretrained(checkpoint)
-```
-
-[`~transformers.TFPreTrainedModel.prepare_tf_dataset`]ì ìŹì©íìŹ ë°ìŽí°ì
ì `tf.data.Dataset` íììŒëĄ ëłííìžì:
-
-```py
->>> tf_train_set = model.prepare_tf_dataset(
-... tokenized_billsum["train"],
-... shuffle=True,
-... batch_size=16,
-... collate_fn=data_collator,
-... )
-
->>> tf_test_set = model.prepare_tf_dataset(
-... tokenized_billsum["test"],
-... shuffle=False,
-... batch_size=16,
-... collate_fn=data_collator,
-... )
-```
-
-[`compile`](https://keras.io/api/models/model_training_apis/#compile-method)ì ìŹì©íìŹ ëȘšëžì íì”í ì ìëëĄ ê”Źì±íìžì:
-
-```py
->>> import tensorflow as tf
-
->>> model.compile(optimizer=optimizer)
-```
-
-íì”ì ììíêž° ì ì ì€ì íŽìŒ í ë§ì§ë§ ë ê°ì§ë ììžĄìì ROUGE ì ì넌 êłì°íêł ëȘšëžì Hubì ížìíë ë°©ëČì ì êł”íë êČì
ëë€.
-ë ìì
ëȘšë [Keras callbacks](../main_classes/keras_callbacks)ìŒëĄ ìíí ì ìì”ëë€.
-
-[`~transformers.KerasMetricCallback`]ì `compute_metrics` íšì넌 ì ëŹíìžì:
-
-```py
->>> from transformers.keras_callbacks import KerasMetricCallback
-
->>> metric_callback = KerasMetricCallback(metric_fn=compute_metrics, eval_dataset=tf_validation_set)
-```
-
-[`~transformers.PushToHubCallback`]ìì ëȘšëžêłŒ í íŹëìŽì 넌 ížìí ììč넌 ì§ì íìžì:
-
-```py
->>> from transformers.keras_callbacks import PushToHubCallback
-
->>> push_to_hub_callback = PushToHubCallback(
-... output_dir="my_awesome_billsum_model",
-... tokenizer=tokenizer,
-... )
-```
-
-ê·žë° ë€ì ìœë°±ì ëČë€ëĄ 돶ìŽì€ëë€:
-
-```py
->>> callbacks = [metric_callback, push_to_hub_callback]
-```
-
-ëëìŽ ëȘšëž íì”ì ììí ì€ëčê° ëìì”ëë€!
-íì” ë° êČìŠ ë°ìŽí°ì
, ìí ì ë° ìœë°±êłŒ íšê» [`fit`](https://keras.io/api/models/model_training_apis/#fit-method)ì ížì¶íìŹ ëȘšëžì íìžíëíìžì.
-
-```py
->>> model.fit(x=tf_train_set, validation_data=tf_test_set, epochs=3, callbacks=callbacks)
-```
-
-íì”ìŽ ìëŁë멎 ëȘšëžìŽ ìëìŒëĄ Hubì ì
ëĄëëìŽ ëê”Źë ìŹì©í ì ìêČ ë©ëë€!
-
-
-
-
-
-ììœì ìíŽ ëȘšëžì íìžíëíë ë°©ëČì ëí ë ììží ìì 넌 ëłŽë €ë©Ž [PyTorch notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/summarization.ipynb)
-ëë [TensorFlow notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/summarization-tf.ipynb)ì ì°žêł íìžì.
-
-
-
-## ì¶ëĄ [[inference]]
-
-ìąìì, ìŽì ëȘšëžì íìžíëíìŒë ì¶ëĄ ì ìŹì©í ì ìì”ëë€!
-
-ììœí í
ì€ížë„Œ ìì±íŽëłŽìžì. T5ì êČœì° ìì
ì ë°ëŒ ì
ë „ ìì ì ëìŹë„Œ ë¶ìŹìŒ í©ëë€. ììœì êČœì°, ìëì ê°ì ì ëìŹë„Œ ì
ë „ ìì ë¶ìŹìŒ í©ëë€:
-
-```py
->>> 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."
-```
-
-ì¶ëĄ ì ìíŽ íìžíëí ëȘšëžì ìííŽ ëłŽë ê°ì„ ê°ëší ë°©ëČì [`pipeline`]ìì ìŹì©íë êČì
ëë€.
-ëȘšëžì ìŹì©íìŹ ììœì ìíí [`pipeline`]ì ìžì€íŽì€ííêł í
ì€ížë„Œ ì ëŹíìžì:
-
-```py
->>> from transformers import pipeline
-
->>> summarizer = pipeline("summarization", model="stevhliu/my_awesome_billsum_model")
->>> summarizer(text)
-[{"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."}]
-```
-
-ìíë€ë©Ž ìëìŒëĄ ë€ìêłŒ ê°ì ìì
ì ìííìŹ [`pipeline`]ì êČ°êłŒì ëìŒí êČ°êłŒë„Œ ì»ì ì ìì”ëë€:
-
-
-
-
-í
ì€ížë„Œ í íŹëìŽìŠíêł `input_ids`넌 PyTorch í
ìëĄ ë°íí©ëë€:
-
-```py
->>> from transformers import AutoTokenizer
-
->>> tokenizer = AutoTokenizer.from_pretrained("stevhliu/my_awesome_billsum_model")
->>> inputs = tokenizer(text, return_tensors="pt").input_ids
-```
-
-ììœëŹžì ìì±íë €ë©Ž [`~transformers.generation_utils.GenerationMixin.generate`] ë©ìë넌 ìŹì©íìžì.
-í
ì€íž ìì±ì ëí ë€ìí ì ë”êłŒ ìì±ì ì ìŽíêž° ìí ë§€ê°ëłìì ëí ììží ëŽì©ì [í
ì€íž ìì±](../main_classes/text_generation) API넌 ì°žìĄ°íìžì.
-
-```py
->>> from transformers import AutoModelForSeq2SeqLM
-
->>> model = AutoModelForSeq2SeqLM.from_pretrained("stevhliu/my_awesome_billsum_model")
->>> outputs = model.generate(inputs, max_new_tokens=100, do_sample=False)
-```
-
-ìì±ë í í° ID넌 í
ì€ížëĄ ëìœë©í©ëë€:
-
-```py
->>> tokenizer.decode(outputs[0], skip_special_tokens=True)
-'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.'
-```
-
-
-í
ì€ížë„Œ í íŹëìŽìŠíêł `input_ids`넌 TensorFlow í
ìëĄ ë°íí©ëë€:
-
-```py
->>> from transformers import AutoTokenizer
-
->>> tokenizer = AutoTokenizer.from_pretrained("stevhliu/my_awesome_billsum_model")
->>> inputs = tokenizer(text, return_tensors="tf").input_ids
-```
-
-ììœëŹžì ìì±íë €ë©Ž [`~transformers.generation_tf_utils.TFGenerationMixin.generate`] ë©ìë넌 ìŹì©íìžì.
-í
ì€íž ìì±ì ëí ë€ìí ì ë”êłŒ ìì±ì ì ìŽíêž° ìí ë§€ê°ëłìì ëí ììží ëŽì©ì [í
ì€íž ìì±](../main_classes/text_generation) API넌 ì°žìĄ°íìžì.
-
-```py
->>> from transformers import TFAutoModelForSeq2SeqLM
-
->>> model = TFAutoModelForSeq2SeqLM.from_pretrained("stevhliu/my_awesome_billsum_model")
->>> outputs = model.generate(inputs, max_new_tokens=100, do_sample=False)
-```
-
-ìì±ë í í° ID넌 í
ì€ížëĄ ëìœë©í©ëë€:
-
-```py
->>> tokenizer.decode(outputs[0], skip_special_tokens=True)
-'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.'
-```
-
-
diff --git a/docs/source/ko/tasks/token_classification.md b/docs/source/ko/tasks/token_classification.md
new file mode 100644
index 000000000000..b09c2c8078aa
--- /dev/null
+++ b/docs/source/ko/tasks/token_classification.md
@@ -0,0 +1,560 @@
+
+
+# í í° ë¶ë„[[token-classification]]
+
+[[open-in-colab]]
+
+
+
+í í° ë¶ë„ë 돞ì„ì ê°ëł í í°ì ë ìŽëžì í ëčí©ëë€. ê°ì„ ìŒë°ì ìž í í° ë¶ë„ ìì
ì€ íëë ê°ìČŽëȘ
ìžì(Named Entity Recognition, NER)ì
ëë€. ê°ìČŽëȘ
ìžìì 돞ì„ìì ìŹë, ììč ëë ìĄ°ì§êłŒ ê°ì ê° ê°ìČŽì ë ìŽëžì ì°ŸìŒë €êł ìëí©ëë€.
+
+ìŽ ê°ìŽëìì íì”í ëŽì©ì:
+
+1. [WNUT 17](https://huggingface.co/datasets/wnut_17) ë°ìŽí° ìžížìì [DistilBERT](https://huggingface.co/distilbert-base-uncased)넌 íìž íëíìŹ ìëĄìŽ ê°ìČŽë„Œ íì§í©ëë€.
+2. ì¶ëĄ ì ìíŽ íìž íë ëȘšëžì ìŹì©í©ëë€.
+
+
+ìŽ íí 늏ìŒìì ì€ëȘ
íë ìì
ì ë€ì ëȘšëž ìí€í
ìČì ìíŽ ì§ìë©ëë€:
+
+
+
+[ALBERT](../model_doc/albert), [BERT](../model_doc/bert), [BigBird](../model_doc/big_bird), [BioGpt](../model_doc/biogpt), [BLOOM](../model_doc/bloom), [CamemBERT](../model_doc/camembert), [CANINE](../model_doc/canine), [ConvBERT](../model_doc/convbert), [Data2VecText](../model_doc/data2vec-text), [DeBERTa](../model_doc/deberta), [DeBERTa-v2](../model_doc/deberta-v2), [DistilBERT](../model_doc/distilbert), [ELECTRA](../model_doc/electra), [ERNIE](../model_doc/ernie), [ErnieM](../model_doc/ernie_m), [ESM](../model_doc/esm), [FlauBERT](../model_doc/flaubert), [FNet](../model_doc/fnet), [Funnel Transformer](../model_doc/funnel), [GPT-Sw3](../model_doc/gpt-sw3), [OpenAI GPT-2](../model_doc/gpt2), [GPTBigCode](../model_doc/gpt_bigcode), [I-BERT](../model_doc/ibert), [LayoutLM](../model_doc/layoutlm), [LayoutLMv2](../model_doc/layoutlmv2), [LayoutLMv3](../model_doc/layoutlmv3), [LiLT](../model_doc/lilt), [Longformer](../model_doc/longformer), [LUKE](../model_doc/luke), [MarkupLM](../model_doc/markuplm), [MEGA](../model_doc/mega), [Megatron-BERT](../model_doc/megatron-bert), [MobileBERT](../model_doc/mobilebert), [MPNet](../model_doc/mpnet), [Nezha](../model_doc/nezha), [Nyströmformer](../model_doc/nystromformer), [QDQBert](../model_doc/qdqbert), [RemBERT](../model_doc/rembert), [RoBERTa](../model_doc/roberta), [RoBERTa-PreLayerNorm](../model_doc/roberta-prelayernorm), [RoCBert](../model_doc/roc_bert), [RoFormer](../model_doc/roformer), [SqueezeBERT](../model_doc/squeezebert), [XLM](../model_doc/xlm), [XLM-RoBERTa](../model_doc/xlm-roberta), [XLM-RoBERTa-XL](../model_doc/xlm-roberta-xl), [XLNet](../model_doc/xlnet), [X-MOD](../model_doc/xmod), [YOSO](../model_doc/yoso)
+
+
+
+
+
+ììíêž° ì ì, íìí ëȘšë ëŒìŽëžëŹëŠŹê° ì€ìčëìŽ ìëì§ íìžíìžì:
+
+```bash
+pip install transformers datasets evaluate seqeval
+```
+
+Hugging Face êłì ì ëĄê·žìžíìŹ ëȘšëžì ì
ëĄëíêł ì»€ëź€ëí°ì êł”ì íë êČì ê¶ì„í©ëë€. ë©ìì§ê° íìë멎, í í°ì ì
ë „íìŹ ëĄê·žìžíìžì:
+
+```py
+>>> from huggingface_hub import notebook_login
+
+>>> notebook_login()
+```
+
+## WNUT 17 ë°ìŽí° ìžíž ê°ì žì€êž°[[load-wnut-17-dataset]]
+
+뚌ì đ€ Datasets ëŒìŽëžëŹëŠŹìì WNUT 17 ë°ìŽí° ìžížë„Œ ê°ì žì”ëë€:
+
+```py
+>>> from datasets import load_dataset
+
+>>> wnut = load_dataset("wnut_17")
+```
+
+ë€ì ìì 넌 ìŽíŽëłŽìžì:
+
+```py
+>>> wnut["train"][0]
+{'id': '0',
+ '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],
+ 'tokens': ['@paulwalk', 'It', "'s", 'the', 'view', 'from', 'where', 'I', "'m", 'living', 'for', 'two', 'weeks', '.', 'Empire', 'State', 'Building', '=', 'ESB', '.', 'Pretty', 'bad', 'storm', 'here', 'last', 'evening', '.']
+}
+```
+
+`ner_tags`ì ê° ì«ìë ê°ìČŽë„Œ ëíë
ëë€. ì«ì넌 ë ìŽëž ìŽëŠìŒëĄ ëłííìŹ ê°ìČŽê° ëŹŽììžì§ íìží©ëë€:
+
+```py
+>>> label_list = wnut["train"].features[f"ner_tags"].feature.names
+>>> label_list
+[
+ "O",
+ "B-corporation",
+ "I-corporation",
+ "B-creative-work",
+ "I-creative-work",
+ "B-group",
+ "I-group",
+ "B-location",
+ "I-location",
+ "B-person",
+ "I-person",
+ "B-product",
+ "I-product",
+]
+```
+
+ê° `ner_tag`ì ìì ë¶ì 돞ìë ê°ìČŽì í í° ììč넌 ëíë
ëë€:
+
+- `B-`ë ê°ìČŽì ììì ëíë
ëë€.
+- `I-`ë í í°ìŽ ëìŒí ê°ìČŽ ëŽë¶ì íŹíšëìŽ ììì ëíë
ëë€(ì넌 ë€ìŽ `State` í í°ì `Empire State Building`ì ê°ì ê°ìČŽì ìŒë¶ì
ëë€).
+- `0`ë í í°ìŽ ìŽë€ ê°ìČŽìë íŽëčíì§ ììì ëíë
ëë€.
+
+## ì ìČ늏[[preprocess]]
+
+
+
+ë€ììŒëĄ `tokens` íë넌 ì ìČ늏íêž° ìíŽ DistilBERT í íŹëìŽì 넌 ê°ì žì”ëë€:
+
+```py
+>>> from transformers import AutoTokenizer
+
+>>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
+```
+
+ìì ìì `tokens` íë넌 볎멎 ì
ë „ìŽ ìŽëŻž í í°íë êČìČëŒ ëłŽì
ëë€. ê·žëŹë ì€ì ëĄ ì
ë „ì ìì§ í í°íëì§ ìììŒëŻëĄ ëšìŽë„Œ íì ëšìŽëĄ í í°ííêž° ìíŽ `is_split_into_words=True`넌 ì€ì íŽìŒ í©ëë€. ìì ëĄ íìží©ëë€:
+
+```py
+>>> example = wnut["train"][0]
+>>> tokenized_input = tokenizer(example["tokens"], is_split_into_words=True)
+>>> tokens = tokenizer.convert_ids_to_tokens(tokenized_input["input_ids"])
+>>> tokens
+['[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]']
+```
+
+ê·žëŹë ìŽëĄ ìžíŽ `[CLS]`êłŒ `[SEP]`ëŒë íčì í í°ìŽ ì¶ê°ëêł , íì ëšìŽ í í°íëĄ ìžíŽ ì
ë „êłŒ ë ìŽëž ê°ì ë¶ìŒìčê° ë°ìí©ëë€. íëì ë ìŽëžì íŽëčíë ëšìŒ ëšìŽë ìŽì ë ê°ì íì ëšìŽëĄ ë¶í ë ì ìì”ëë€. í í°êłŒ ë ìŽëžì ë€ìêłŒ ê°ìŽ ìŹì ë ŹíŽìŒ í©ëë€:
+
+1. [`word_ids`](https://huggingface.co/docs/transformers/main_classes/tokenizer#transformers.BatchEncoding.word_ids) ë©ìëëĄ ëȘšë í í°ì íŽëč ëšìŽì ë§€íí©ëë€.
+2. íčì í í° `[CLS]`ì `[SEP]`ì `-100` ë ìŽëžì í ëčíìŹ, PyTorch ìì€ íšìê° íŽëč í í°ì 돎ìíëëĄ í©ëë€.
+3. ìŁŒìŽì§ ëšìŽì ìČ« ëČì§ž í í°ìë§ ë ìŽëžì ì§ì í©ëë€. ê°ì ëšìŽì ë€ë„ž íì í í°ì `-100`ì í ëčí©ëë€.
+
+ë€ìì í í°êłŒ ë ìŽëžì ìŹì ë Źíêł DistilBERTì ì”ë ì
ë „ êžžìŽëłŽë€ êžžì§ ìëëĄ ìíì€ë„Œ ìëŒëŽë íšì넌 ë§ëë ë°©ëČì
ëë€:
+
+```py
+>>> def tokenize_and_align_labels(examples):
+... tokenized_inputs = tokenizer(examples["tokens"], truncation=True, is_split_into_words=True)
+
+... labels = []
+... for i, label in enumerate(examples[f"ner_tags"]):
+... word_ids = tokenized_inputs.word_ids(batch_index=i) # Map tokens to their respective word.
+... previous_word_idx = None
+... label_ids = []
+... for word_idx in word_ids: # Set the special tokens to -100.
+... if word_idx is None:
+... label_ids.append(-100)
+... elif word_idx != previous_word_idx: # Only label the first token of a given word.
+... label_ids.append(label[word_idx])
+... else:
+... label_ids.append(-100)
+... previous_word_idx = word_idx
+... labels.append(label_ids)
+
+... tokenized_inputs["labels"] = labels
+... return tokenized_inputs
+```
+
+ì ìČŽ ë°ìŽí° ìžížì ì ìČ늏 íšì넌 ì ì©íë €ë©Ž, đ€ Datasets [`~datasets.Dataset.map`] íšì넌 ìŹì©íìžì. `batched=True`ëĄ ì€ì íìŹ ë°ìŽí° ìžížì ìŹëŹ ìì넌 í ëČì ìČ늏í멎 `map` íšìì ìë넌 ëìŒ ì ìì”ëë€:
+```py
+>>> tokenized_wnut = wnut.map(tokenize_and_align_labels, batched=True)
+```
+
+ìŽì [`DataCollatorWithPadding`]넌 ìŹì©íìŹ ìì ë°°ìč넌 ë§ë€ìŽëŽ
ìë€. ë°ìŽí° ìžíž ì ìČŽë„Œ ì”ë êžžìŽëĄ íšë©íë ëì , *ëì íšë©*ì ìŹì©íìŹ ë°°ìčìì ê°ì„ ꞎ êžžìŽì ë§êČ ëŹžì„ì íšë©íë êČìŽ íšìšì ì
ëë€.
+
+
+
+```py
+>>> from transformers import DataCollatorForTokenClassification
+
+>>> data_collator = DataCollatorForTokenClassification(tokenizer=tokenizer)
+```
+
+
+```py
+>>> from transformers import DataCollatorForTokenClassification
+
+>>> data_collator = DataCollatorForTokenClassification(tokenizer=tokenizer, return_tensors="tf")
+```
+
+
+
+## íê°[[evaluation]]
+
+íë š ì€ ëȘšëžì ì±ë„ì íê°íêž° ìíŽ íê° ì§í넌 íŹíšíë êČìŽ ì ì©í©ëë€. đ€ [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 ë° ì íëì ê°ì ìŹëŹ ì ì넌 ì°ì¶í©ëë€.
+
+```py
+>>> import evaluate
+
+>>> seqeval = evaluate.load("seqeval")
+```
+
+뚌ì NER ë ìŽëžì ê°ì žìš ë€ì, [`~evaluate.EvaluationModule.compute`]ì ì€ì ììžĄêłŒ ì€ì ë ìŽëžì ì ëŹíìŹ ì ì넌 êłì°íë íšì넌 ë§ëëë€:
+
+```py
+>>> import numpy as np
+
+>>> labels = [label_list[i] for i in example[f"ner_tags"]]
+
+
+>>> def compute_metrics(p):
+... predictions, labels = p
+... predictions = np.argmax(predictions, axis=2)
+
+... true_predictions = [
+... [label_list[p] for (p, l) in zip(prediction, label) if l != -100]
+... for prediction, label in zip(predictions, labels)
+... ]
+... true_labels = [
+... [label_list[l] for (p, l) in zip(prediction, label) if l != -100]
+... for prediction, label in zip(predictions, labels)
+... ]
+
+... results = seqeval.compute(predictions=true_predictions, references=true_labels)
+... return {
+... "precision": results["overall_precision"],
+... "recall": results["overall_recall"],
+... "f1": results["overall_f1"],
+... "accuracy": results["overall_accuracy"],
+... }
+```
+
+ìŽì `compute_metrics` íšì넌 ìŹì©í ì€ëčê° ëììŒë©°, íë šì ì€ì í멎 ìŽ íšìëĄ ëëììŹ êČì
ëë€.
+
+## íë š[[train]]
+
+ëȘšëžì íë šíêž° ì ì, `id2label`ì `label2id`넌 ìŹì©íìŹ ììëë idì ë ìŽëžì ë§”ì ìì±íìžì:
+
+```py
+>>> id2label = {
+... 0: "O",
+... 1: "B-corporation",
+... 2: "I-corporation",
+... 3: "B-creative-work",
+... 4: "I-creative-work",
+... 5: "B-group",
+... 6: "I-group",
+... 7: "B-location",
+... 8: "I-location",
+... 9: "B-person",
+... 10: "I-person",
+... 11: "B-product",
+... 12: "I-product",
+... }
+>>> label2id = {
+... "O": 0,
+... "B-corporation": 1,
+... "I-corporation": 2,
+... "B-creative-work": 3,
+... "I-creative-work": 4,
+... "B-group": 5,
+... "I-group": 6,
+... "B-location": 7,
+... "I-location": 8,
+... "B-person": 9,
+... "I-person": 10,
+... "B-product": 11,
+... "I-product": 12,
+... }
+```
+
+
+
+
+
+[`Trainer`]넌 ìŹì©íìŹ ëȘšëžì íìž íëíë ë°©ëČì ì”ìíì§ ìì êČœì°, [ìŹêž°](../training#train-with-pytorch-trainer)ìì êž°ëłž íí 늏ìŒì íìžíìžì!
+
+
+
+ìŽì ëȘšëžì íë šìíŹ ì€ëčê° ëìì”ëë€! [`AutoModelForSequenceClassification`]ëĄ DistilBERT넌 ê°ì žì€êł ììëë ë ìŽëž ìì ë ìŽëž ë§€íì ì§ì íìžì:
+
+```py
+>>> from transformers import AutoModelForTokenClassification, TrainingArguments, Trainer
+
+>>> model = AutoModelForTokenClassification.from_pretrained(
+... "distilbert-base-uncased", num_labels=13, id2label=id2label, label2id=label2id
+... )
+```
+
+ìŽì ìž ëšêłë§ ê±°ìč멎 ëì
ëë€:
+
+1. [`TrainingArguments`]ìì íìŽíŒíëŒëŻží°ë„Œ ì ìíìžì. `output_dir`ë ëȘšëžì ì ì„í ììč넌 ì§ì íë ì ìŒí ë§€ê°ëłìì
ëë€. ìŽ ëȘšëžì íëžì ì
ëĄëíêž° ìíŽ `push_to_hub=True`넌 ì€ì í©ëë€(ëȘšëžì ì
ëĄëíêž° ìíŽ Hugging Faceì ëĄê·žìžíŽìŒí©ëë€.) ê° ìíìŽ ëë ëë§ë€, [`Trainer`]ë seqeval ì ì넌 íê°íêł íë š ìČŽíŹíŹìžížë„Œ ì ì„í©ëë€.
+2. [`Trainer`]ì íë š ìžìì ëȘšëž, ë°ìŽí° ìžíž, í íŹëìŽì , ë°ìŽí° ìœë ìŽí° ë° `compute_metrics` íšì넌 ì ëŹíìžì.
+3. [`~Trainer.train`]넌 ížì¶íìŹ ëȘšëžì íìž íëíìžì.
+
+```py
+>>> training_args = TrainingArguments(
+... output_dir="my_awesome_wnut_model",
+... learning_rate=2e-5,
+... per_device_train_batch_size=16,
+... per_device_eval_batch_size=16,
+... num_train_epochs=2,
+... weight_decay=0.01,
+... evaluation_strategy="epoch",
+... save_strategy="epoch",
+... load_best_model_at_end=True,
+... push_to_hub=True,
+... )
+
+>>> trainer = Trainer(
+... model=model,
+... args=training_args,
+... train_dataset=tokenized_wnut["train"],
+... eval_dataset=tokenized_wnut["test"],
+... tokenizer=tokenizer,
+... data_collator=data_collator,
+... compute_metrics=compute_metrics,
+... )
+
+>>> trainer.train()
+```
+
+íë šìŽ ìëŁë멎, [`~transformers.Trainer.push_to_hub`] ë©ìë넌 ìŹì©íìŹ ëȘšëžì íëžì êł”ì í ì ìì”ëë€.
+
+```py
+>>> trainer.push_to_hub()
+```
+
+
+
+
+Keras넌 ìŹì©íìŹ ëȘšëžì íìž íëíë ë°©ëČì ì”ìíì§ ìì êČœì°, [ìŹêž°](../training#train-a-tensorflow-model-with-keras)ì êž°ëłž íí 늏ìŒì íìžíìžì!
+
+
+TensorFlowìì ëȘšëžì íìž íëíë €ë©Ž, 뚌ì ì”í°ë§ìŽì íšìì íì”ë„ ì€ìŒì„Ž, ê·žëŠŹêł ìŒë¶ íë š íìŽíŒíëŒëŻží°ë„Œ ì€ì íŽìŒ í©ëë€:
+
+```py
+>>> from transformers import create_optimizer
+
+>>> batch_size = 16
+>>> num_train_epochs = 3
+>>> num_train_steps = (len(tokenized_wnut["train"]) // batch_size) * num_train_epochs
+>>> optimizer, lr_schedule = create_optimizer(
+... init_lr=2e-5,
+... num_train_steps=num_train_steps,
+... weight_decay_rate=0.01,
+... num_warmup_steps=0,
+... )
+```
+
+ê·žë° ë€ì [`TFAutoModelForSequenceClassification`]ì ìŹì©íìŹ DistilBERT넌 ê°ì žì€êł , ììëë ë ìŽëž ìì ë ìŽëž ë§€íì ì§ì í©ëë€:
+
+```py
+>>> from transformers import TFAutoModelForTokenClassification
+
+>>> model = TFAutoModelForTokenClassification.from_pretrained(
+... "distilbert-base-uncased", num_labels=13, id2label=id2label, label2id=label2id
+... )
+```
+
+[`~transformers.TFPreTrainedModel.prepare_tf_dataset`]ì ìŹì©íìŹ ë°ìŽí° ìžížë„Œ `tf.data.Dataset` íììŒëĄ ëłíí©ëë€:
+
+```py
+>>> tf_train_set = model.prepare_tf_dataset(
+... tokenized_wnut["train"],
+... shuffle=True,
+... batch_size=16,
+... collate_fn=data_collator,
+... )
+
+>>> tf_validation_set = model.prepare_tf_dataset(
+... tokenized_wnut["validation"],
+... shuffle=False,
+... batch_size=16,
+... collate_fn=data_collator,
+... )
+```
+
+[`compile`](https://keras.io/api/models/model_training_apis/#compile-method)넌 ìŹì©íìŹ íë ší ëȘšëžì ê”Źì±í©ëë€:
+
+```py
+>>> import tensorflow as tf
+
+>>> model.compile(optimizer=optimizer)
+```
+
+íë šì ììíêž° ì ì ì€ì íŽìŒí ë§ì§ë§ ë ê°ì§ë ììžĄìì seqeval ì ì넌 êłì°íêł , ëȘšëžì íëžì ì
ëĄëí ë°©ëČì ì êł”íë êČì
ëë€. ëȘšë [Keras callbacks](../main_classes/keras_callbacks)넌 ìŹì©íìŹ ìíë©ëë€.
+
+[`~transformers.KerasMetricCallback`]ì `compute_metrics` íšì넌 ì ëŹíìžì:
+
+```py
+>>> from transformers.keras_callbacks import KerasMetricCallback
+
+>>> metric_callback = KerasMetricCallback(metric_fn=compute_metrics, eval_dataset=tf_validation_set)
+```
+
+[`~transformers.PushToHubCallback`]ìì ëȘšëžêłŒ í íŹëìŽì 넌 ì
ëĄëí ììč넌 ì§ì í©ëë€:
+
+```py
+>>> from transformers.keras_callbacks import PushToHubCallback
+
+>>> push_to_hub_callback = PushToHubCallback(
+... output_dir="my_awesome_wnut_model",
+... tokenizer=tokenizer,
+... )
+```
+
+ê·žë° ë€ì ìœë°±ì íšê» 돶ì”ëë€:
+
+```py
+>>> callbacks = [metric_callback, push_to_hub_callback]
+```
+
+ëëìŽ, ëȘšëž íë šì ììí ì€ëčê° ëìì”ëë€! [`fit`](https://keras.io/api/models/model_training_apis/#fit-method)ì íë š ë°ìŽí° ìžíž, êČìŠ ë°ìŽí° ìžíž, ìíì ì ë° ìœë°±ì ì ëŹíìŹ íìž íëí©ëë€:
+
+```py
+>>> model.fit(x=tf_train_set, validation_data=tf_validation_set, epochs=3, callbacks=callbacks)
+```
+
+íë šìŽ ìëŁë멎, ëȘšëžìŽ ìëìŒëĄ íëžì ì
ëĄëëìŽ ëê”Źë ìŹì©í ì ìì”ëë€!
+
+
+
+
+
+í í° ë¶ë„넌 ìí ëȘšëžì íìž íëíë ììží ìì ë ë€ì
+[PyTorch notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/token_classification.ipynb)
+ëë [TensorFlow notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/token_classification-tf.ipynb)넌 ì°žìĄ°íìžì.
+
+
+
+## ì¶ëĄ [[inference]]
+
+ìąìì, ìŽì ëȘšëžì íìž íëíìŒë ì¶ëĄ ì ìŹì©í ì ìì”ëë€!
+
+ì¶ëĄ ì ìííêł ì íë í
ì€ížë„Œ ê°ì žìëŽ
ìë€:
+
+```py
+>>> text = "The Golden State Warriors are an American professional basketball team based in San Francisco."
+```
+
+íìž íëë ëȘšëžëĄ ì¶ëĄ ì ìëíë ê°ì„ ê°ëší ë°©ëČì [`pipeline`]넌 ìŹì©íë êČì
ëë€. ëȘšëžëĄ NERì `pipeline`ì ìžì€íŽì€ííêł , í
ì€ížë„Œ ì ëŹíŽëłŽìžì:
+
+```py
+>>> from transformers import pipeline
+
+>>> classifier = pipeline("ner", model="stevhliu/my_awesome_wnut_model")
+>>> classifier(text)
+[{'entity': 'B-location',
+ 'score': 0.42658573,
+ 'index': 2,
+ 'word': 'golden',
+ 'start': 4,
+ 'end': 10},
+ {'entity': 'I-location',
+ 'score': 0.35856336,
+ 'index': 3,
+ 'word': 'state',
+ 'start': 11,
+ 'end': 16},
+ {'entity': 'B-group',
+ 'score': 0.3064001,
+ 'index': 4,
+ 'word': 'warriors',
+ 'start': 17,
+ 'end': 25},
+ {'entity': 'B-location',
+ 'score': 0.65523505,
+ 'index': 13,
+ 'word': 'san',
+ 'start': 80,
+ 'end': 83},
+ {'entity': 'B-location',
+ 'score': 0.4668663,
+ 'index': 14,
+ 'word': 'francisco',
+ 'start': 84,
+ 'end': 93}]
+```
+
+ìíë€ë©Ž, `pipeline`ì êČ°êłŒë„Œ ìëìŒëĄ ëł”ì í ìë ìì”ëë€:
+
+
+
+í
ì€ížë„Œ í í°ííêł PyTorch í
ì넌 ë°íí©ëë€:
+
+```py
+>>> from transformers import AutoTokenizer
+
+>>> tokenizer = AutoTokenizer.from_pretrained("stevhliu/my_awesome_wnut_model")
+>>> inputs = tokenizer(text, return_tensors="pt")
+```
+
+ì
ë „ì ëȘšëžì ì ëŹíêł `logits`ì ë°íí©ëë€:
+
+```py
+>>> from transformers import AutoModelForTokenClassification
+
+>>> model = AutoModelForTokenClassification.from_pretrained("stevhliu/my_awesome_wnut_model")
+>>> with torch.no_grad():
+... logits = model(**inputs).logits
+```
+
+ê°ì„ ëì íë„ ì ê°ì§ íŽëì€ë„Œ ëȘšëžì `id2label` ë§€íì ìŹì©íìŹ í
ì€íž ë ìŽëžëĄ ëłíí©ëë€:
+
+```py
+>>> predictions = torch.argmax(logits, dim=2)
+>>> predicted_token_class = [model.config.id2label[t.item()] for t in predictions[0]]
+>>> predicted_token_class
+['O',
+ 'O',
+ 'B-location',
+ 'I-location',
+ 'B-group',
+ 'O',
+ 'O',
+ 'O',
+ 'O',
+ 'O',
+ 'O',
+ 'O',
+ 'O',
+ 'B-location',
+ 'B-location',
+ 'O',
+ 'O']
+```
+
+
+í
ì€ížë„Œ í í°ííêł TensorFlow í
ì넌 ë°íí©ëë€:
+
+```py
+>>> from transformers import AutoTokenizer
+
+>>> tokenizer = AutoTokenizer.from_pretrained("stevhliu/my_awesome_wnut_model")
+>>> inputs = tokenizer(text, return_tensors="tf")
+```
+
+ì
ë „ê°ì ëȘšëžì ì ëŹíêł `logits`ì ë°íí©ëë€:
+
+```py
+>>> from transformers import TFAutoModelForTokenClassification
+
+>>> model = TFAutoModelForTokenClassification.from_pretrained("stevhliu/my_awesome_wnut_model")
+>>> logits = model(**inputs).logits
+```
+
+ê°ì„ ëì íë„ ì ê°ì§ íŽëì€ë„Œ ëȘšëžì `id2label` ë§€íì ìŹì©íìŹ í
ì€íž ë ìŽëžëĄ ëłíí©ëë€:
+
+```py
+>>> predicted_token_class_ids = tf.math.argmax(logits, axis=-1)
+>>> predicted_token_class = [model.config.id2label[t] for t in predicted_token_class_ids[0].numpy().tolist()]
+>>> predicted_token_class
+['O',
+ 'O',
+ 'B-location',
+ 'I-location',
+ 'B-group',
+ 'O',
+ 'O',
+ 'O',
+ 'O',
+ 'O',
+ 'O',
+ 'O',
+ 'O',
+ 'B-location',
+ 'B-location',
+ 'O',
+ 'O']
+```
+
+
diff --git a/docs/source/ko/tasks/token_classification.mdx b/docs/source/ko/tasks/token_classification.mdx
deleted file mode 100644
index c0c0271828ee..000000000000
--- a/docs/source/ko/tasks/token_classification.mdx
+++ /dev/null
@@ -1,556 +0,0 @@
-
-
-# í í° ë¶ë„[[token-classification]]
-
-[[open-in-colab]]
-
-
-
-í í° ë¶ë„ë 돞ì„ì ê°ëł í í°ì ë ìŽëžì í ëčí©ëë€. ê°ì„ ìŒë°ì ìž í í° ë¶ë„ ìì
ì€ íëë ê°ìČŽëȘ
ìžì(Named Entity Recognition, NER)ì
ëë€. ê°ìČŽëȘ
ìžìì 돞ì„ìì ìŹë, ììč ëë ìĄ°ì§êłŒ ê°ì ê° ê°ìČŽì ë ìŽëžì ì°ŸìŒë €êł ìëí©ëë€.
-
-ìŽ ê°ìŽëìì íì”í ëŽì©ì:
-
-1. [WNUT 17](https://huggingface.co/datasets/wnut_17) ë°ìŽí° ìžížìì [DistilBERT](https://huggingface.co/distilbert-base-uncased)넌 íìž íëíìŹ ìëĄìŽ ê°ìČŽë„Œ íì§í©ëë€.
-2. ì¶ëĄ ì ìíŽ íìž íë ëȘšëžì ìŹì©í©ëë€.
-
-
-ìŽ íí 늏ìŒìì ì€ëȘ
íë ìì
ì ë€ì ëȘšëž ìí€í
ìČì ìíŽ ì§ìë©ëë€:
-
-
-
-[ALBERT](../model_doc/albert), [BERT](../model_doc/bert), [BigBird](../model_doc/big_bird), [BioGpt](../model_doc/biogpt), [BLOOM](../model_doc/bloom), [CamemBERT](../model_doc/camembert), [CANINE](../model_doc/canine), [ConvBERT](../model_doc/convbert), [Data2VecText](../model_doc/data2vec-text), [DeBERTa](../model_doc/deberta), [DeBERTa-v2](../model_doc/deberta-v2), [DistilBERT](../model_doc/distilbert), [ELECTRA](../model_doc/electra), [ERNIE](../model_doc/ernie), [ErnieM](../model_doc/ernie_m), [ESM](../model_doc/esm), [FlauBERT](../model_doc/flaubert), [FNet](../model_doc/fnet), [Funnel Transformer](../model_doc/funnel), [GPT-Sw3](../model_doc/gpt-sw3), [OpenAI GPT-2](../model_doc/gpt2), [GPTBigCode](../model_doc/gpt_bigcode), [I-BERT](../model_doc/ibert), [LayoutLM](../model_doc/layoutlm), [LayoutLMv2](../model_doc/layoutlmv2), [LayoutLMv3](../model_doc/layoutlmv3), [LiLT](../model_doc/lilt), [Longformer](../model_doc/longformer), [LUKE](../model_doc/luke), [MarkupLM](../model_doc/markuplm), [MEGA](../model_doc/mega), [Megatron-BERT](../model_doc/megatron-bert), [MobileBERT](../model_doc/mobilebert), [MPNet](../model_doc/mpnet), [Nezha](../model_doc/nezha), [Nyströmformer](../model_doc/nystromformer), [QDQBert](../model_doc/qdqbert), [RemBERT](../model_doc/rembert), [RoBERTa](../model_doc/roberta), [RoBERTa-PreLayerNorm](../model_doc/roberta-prelayernorm), [RoCBert](../model_doc/roc_bert), [RoFormer](../model_doc/roformer), [SqueezeBERT](../model_doc/squeezebert), [XLM](../model_doc/xlm), [XLM-RoBERTa](../model_doc/xlm-roberta), [XLM-RoBERTa-XL](../model_doc/xlm-roberta-xl), [XLNet](../model_doc/xlnet), [X-MOD](../model_doc/xmod), [YOSO](../model_doc/yoso)
-
-
-
-
-
-ììíêž° ì ì, íìí ëȘšë ëŒìŽëžëŹëŠŹê° ì€ìčëìŽ ìëì§ íìžíìžì:
-
-```bash
-pip install transformers datasets evaluate seqeval
-```
-
-Hugging Face êłì ì ëĄê·žìžíìŹ ëȘšëžì ì
ëĄëíêł ì»€ëź€ëí°ì êł”ì íë êČì ê¶ì„í©ëë€. ë©ìì§ê° íìë멎, í í°ì ì
ë „íìŹ ëĄê·žìžíìžì:
-
-```py
->>> from huggingface_hub import notebook_login
-
->>> notebook_login()
-```
-
-## WNUT 17 ë°ìŽí° ìžíž ê°ì žì€êž°[[load-wnut-17-dataset]]
-
-뚌ì đ€ Datasets ëŒìŽëžëŹëŠŹìì WNUT 17 ë°ìŽí° ìžížë„Œ ê°ì žì”ëë€:
-
-```py
->>> from datasets import load_dataset
-
->>> wnut = load_dataset("wnut_17")
-```
-
-ë€ì ìì 넌 ìŽíŽëłŽìžì:
-
-```py
->>> wnut["train"][0]
-{'id': '0',
- '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],
- 'tokens': ['@paulwalk', 'It', "'s", 'the', 'view', 'from', 'where', 'I', "'m", 'living', 'for', 'two', 'weeks', '.', 'Empire', 'State', 'Building', '=', 'ESB', '.', 'Pretty', 'bad', 'storm', 'here', 'last', 'evening', '.']
-}
-```
-
-`ner_tags`ì ê° ì«ìë ê°ìČŽë„Œ ëíë
ëë€. ì«ì넌 ë ìŽëž ìŽëŠìŒëĄ ëłííìŹ ê°ìČŽê° ëŹŽììžì§ íìží©ëë€:
-
-```py
->>> label_list = wnut["train"].features[f"ner_tags"].feature.names
->>> label_list
-[
- "O",
- "B-corporation",
- "I-corporation",
- "B-creative-work",
- "I-creative-work",
- "B-group",
- "I-group",
- "B-location",
- "I-location",
- "B-person",
- "I-person",
- "B-product",
- "I-product",
-]
-```
-
-ê° `ner_tag`ì ìì ë¶ì 돞ìë ê°ìČŽì í í° ììč넌 ëíë
ëë€:
-
-- `B-`ë ê°ìČŽì ììì ëíë
ëë€.
-- `I-`ë í í°ìŽ ëìŒí ê°ìČŽ ëŽë¶ì íŹíšëìŽ ììì ëíë
ëë€(ì넌 ë€ìŽ `State` í í°ì `Empire State Building`ì ê°ì ê°ìČŽì ìŒë¶ì
ëë€).
-- `0`ë í í°ìŽ ìŽë€ ê°ìČŽìë íŽëčíì§ ììì ëíë
ëë€.
-
-## ì ìČ늏[[preprocess]]
-
-
-
-ë€ììŒëĄ `tokens` íë넌 ì ìČ늏íêž° ìíŽ DistilBERT í íŹëìŽì 넌 ê°ì žì”ëë€:
-
-```py
->>> from transformers import AutoTokenizer
-
->>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
-```
-
-ìì ìì `tokens` íë넌 볎멎 ì
ë „ìŽ ìŽëŻž í í°íë êČìČëŒ ëłŽì
ëë€. ê·žëŹë ì€ì ëĄ ì
ë „ì ìì§ í í°íëì§ ìììŒëŻëĄ ëšìŽë„Œ íì ëšìŽëĄ í í°ííêž° ìíŽ `is_split_into_words=True`넌 ì€ì íŽìŒ í©ëë€. ìì ëĄ íìží©ëë€:
-
-```py
->>> example = wnut["train"][0]
->>> tokenized_input = tokenizer(example["tokens"], is_split_into_words=True)
->>> tokens = tokenizer.convert_ids_to_tokens(tokenized_input["input_ids"])
->>> tokens
-['[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]']
-```
-
-ê·žëŹë ìŽëĄ ìžíŽ `[CLS]`êłŒ `[SEP]`ëŒë íčì í í°ìŽ ì¶ê°ëêł , íì ëšìŽ í í°íëĄ ìžíŽ ì
ë „êłŒ ë ìŽëž ê°ì ë¶ìŒìčê° ë°ìí©ëë€. íëì ë ìŽëžì íŽëčíë ëšìŒ ëšìŽë ìŽì ë ê°ì íì ëšìŽëĄ ë¶í ë ì ìì”ëë€. í í°êłŒ ë ìŽëžì ë€ìêłŒ ê°ìŽ ìŹì ë ŹíŽìŒ í©ëë€:
-
-1. [`word_ids`](https://huggingface.co/docs/transformers/main_classes/tokenizer#transformers.BatchEncoding.word_ids) ë©ìëëĄ ëȘšë í í°ì íŽëč ëšìŽì ë§€íí©ëë€.
-2. íčì í í° `[CLS]`ì `[SEP]`ì `-100` ë ìŽëžì í ëčíìŹ, PyTorch ìì€ íšìê° íŽëč í í°ì 돎ìíëëĄ í©ëë€.
-3. ìŁŒìŽì§ ëšìŽì ìČ« ëČì§ž í í°ìë§ ë ìŽëžì ì§ì í©ëë€. ê°ì ëšìŽì ë€ë„ž íì í í°ì `-100`ì í ëčí©ëë€.
-
-ë€ìì í í°êłŒ ë ìŽëžì ìŹì ë Źíêł DistilBERTì ì”ë ì
ë „ êžžìŽëłŽë€ êžžì§ ìëëĄ ìíì€ë„Œ ìëŒëŽë íšì넌 ë§ëë ë°©ëČì
ëë€:
-
-```py
->>> def tokenize_and_align_labels(examples):
-... tokenized_inputs = tokenizer(examples["tokens"], truncation=True, is_split_into_words=True)
-
-... labels = []
-... for i, label in enumerate(examples[f"ner_tags"]):
-... word_ids = tokenized_inputs.word_ids(batch_index=i) # Map tokens to their respective word.
-... previous_word_idx = None
-... label_ids = []
-... for word_idx in word_ids: # Set the special tokens to -100.
-... if word_idx is None:
-... label_ids.append(-100)
-... elif word_idx != previous_word_idx: # Only label the first token of a given word.
-... label_ids.append(label[word_idx])
-... else:
-... label_ids.append(-100)
-... previous_word_idx = word_idx
-... labels.append(label_ids)
-
-... tokenized_inputs["labels"] = labels
-... return tokenized_inputs
-```
-
-ì ìČŽ ë°ìŽí° ìžížì ì ìČ늏 íšì넌 ì ì©íë €ë©Ž, đ€ Datasets [`~datasets.Dataset.map`] íšì넌 ìŹì©íìžì. `batched=True`ëĄ ì€ì íìŹ ë°ìŽí° ìžížì ìŹëŹ ìì넌 í ëČì ìČ늏í멎 `map` íšìì ìë넌 ëìŒ ì ìì”ëë€:
-```py
->>> tokenized_wnut = wnut.map(tokenize_and_align_labels, batched=True)
-```
-
-ìŽì [`DataCollatorWithPadding`]넌 ìŹì©íìŹ ìì ë°°ìč넌 ë§ë€ìŽëŽ
ìë€. ë°ìŽí° ìžíž ì ìČŽë„Œ ì”ë êžžìŽëĄ íšë©íë ëì , *ëì íšë©*ì ìŹì©íìŹ ë°°ìčìì ê°ì„ ꞎ êžžìŽì ë§êČ ëŹžì„ì íšë©íë êČìŽ íšìšì ì
ëë€.
-
-
-
-```py
->>> from transformers import DataCollatorForTokenClassification
-
->>> data_collator = DataCollatorForTokenClassification(tokenizer=tokenizer)
-```
-
-
-```py
->>> from transformers import DataCollatorForTokenClassification
-
->>> data_collator = DataCollatorForTokenClassification(tokenizer=tokenizer, return_tensors="tf")
-```
-
-
-
-## íê°[[evaluation]]
-
-íë š ì€ ëȘšëžì ì±ë„ì íê°íêž° ìíŽ íê° ì§í넌 íŹíšíë êČìŽ ì ì©í©ëë€. đ€ [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 ë° ì íëì ê°ì ìŹëŹ ì ì넌 ì°ì¶í©ëë€.
-
-```py
->>> import evaluate
-
->>> seqeval = evaluate.load("seqeval")
-```
-
-뚌ì NER ë ìŽëžì ê°ì žìš ë€ì, [`~evaluate.EvaluationModule.compute`]ì ì€ì ììžĄêłŒ ì€ì ë ìŽëžì ì ëŹíìŹ ì ì넌 êłì°íë íšì넌 ë§ëëë€:
-
-```py
->>> import numpy as np
-
->>> labels = [label_list[i] for i in example[f"ner_tags"]]
-
-
->>> def compute_metrics(p):
-... predictions, labels = p
-... predictions = np.argmax(predictions, axis=2)
-
-... true_predictions = [
-... [label_list[p] for (p, l) in zip(prediction, label) if l != -100]
-... for prediction, label in zip(predictions, labels)
-... ]
-... true_labels = [
-... [label_list[l] for (p, l) in zip(prediction, label) if l != -100]
-... for prediction, label in zip(predictions, labels)
-... ]
-
-... results = seqeval.compute(predictions=true_predictions, references=true_labels)
-... return {
-... "precision": results["overall_precision"],
-... "recall": results["overall_recall"],
-... "f1": results["overall_f1"],
-... "accuracy": results["overall_accuracy"],
-... }
-```
-
-ìŽì `compute_metrics` íšì넌 ìŹì©í ì€ëčê° ëììŒë©°, íë šì ì€ì í멎 ìŽ íšìëĄ ëëììŹ êČì
ëë€.
-
-## íë š[[train]]
-
-ëȘšëžì íë šíêž° ì ì, `id2label`ì `label2id`넌 ìŹì©íìŹ ììëë idì ë ìŽëžì ë§”ì ìì±íìžì:
-
-```py
->>> id2label = {
-... 0: "O",
-... 1: "B-corporation",
-... 2: "I-corporation",
-... 3: "B-creative-work",
-... 4: "I-creative-work",
-... 5: "B-group",
-... 6: "I-group",
-... 7: "B-location",
-... 8: "I-location",
-... 9: "B-person",
-... 10: "I-person",
-... 11: "B-product",
-... 12: "I-product",
-... }
->>> label2id = {
-... "O": 0,
-... "B-corporation": 1,
-... "I-corporation": 2,
-... "B-creative-work": 3,
-... "I-creative-work": 4,
-... "B-group": 5,
-... "I-group": 6,
-... "B-location": 7,
-... "I-location": 8,
-... "B-person": 9,
-... "I-person": 10,
-... "B-product": 11,
-... "I-product": 12,
-... }
-```
-
-
-
-
-
-[`Trainer`]넌 ìŹì©íìŹ ëȘšëžì íìž íëíë ë°©ëČì ì”ìíì§ ìì êČœì°, [ìŹêž°](../training#train-with-pytorch-trainer)ìì êž°ëłž íí 늏ìŒì íìžíìžì!
-
-
-
-ìŽì ëȘšëžì íë šìíŹ ì€ëčê° ëìì”ëë€! [`AutoModelForSequenceClassification`]ëĄ DistilBERT넌 ê°ì žì€êł ììëë ë ìŽëž ìì ë ìŽëž ë§€íì ì§ì íìžì:
-
-```py
->>> from transformers import AutoModelForTokenClassification, TrainingArguments, Trainer
-
->>> model = AutoModelForTokenClassification.from_pretrained(
-... "distilbert-base-uncased", num_labels=13, id2label=id2label, label2id=label2id
-... )
-```
-
-ìŽì ìž ëšêłë§ ê±°ìč멎 ëì
ëë€:
-
-1. [`TrainingArguments`]ìì íìŽíŒíëŒëŻží°ë„Œ ì ìíìžì. `output_dir`ë ëȘšëžì ì ì„í ììč넌 ì§ì íë ì ìŒí ë§€ê°ëłìì
ëë€. ìŽ ëȘšëžì íëžì ì
ëĄëíêž° ìíŽ `push_to_hub=True`넌 ì€ì í©ëë€(ëȘšëžì ì
ëĄëíêž° ìíŽ Hugging Faceì ëĄê·žìžíŽìŒí©ëë€.) ê° ìíìŽ ëë ëë§ë€, [`Trainer`]ë seqeval ì ì넌 íê°íêł íë š ìČŽíŹíŹìžížë„Œ ì ì„í©ëë€.
-2. [`Trainer`]ì íë š ìžìì ëȘšëž, ë°ìŽí° ìžíž, í íŹëìŽì , ë°ìŽí° ìœë ìŽí° ë° `compute_metrics` íšì넌 ì ëŹíìžì.
-3. [`~Trainer.train`]넌 ížì¶íìŹ ëȘšëžì íìž íëíìžì.
-
-```py
->>> training_args = TrainingArguments(
-... output_dir="my_awesome_wnut_model",
-... learning_rate=2e-5,
-... per_device_train_batch_size=16,
-... per_device_eval_batch_size=16,
-... num_train_epochs=2,
-... weight_decay=0.01,
-... evaluation_strategy="epoch",
-... save_strategy="epoch",
-... load_best_model_at_end=True,
-... push_to_hub=True,
-... )
-
->>> trainer = Trainer(
-... model=model,
-... args=training_args,
-... train_dataset=tokenized_wnut["train"],
-... eval_dataset=tokenized_wnut["test"],
-... tokenizer=tokenizer,
-... data_collator=data_collator,
-... compute_metrics=compute_metrics,
-... )
-
->>> trainer.train()
-```
-
-íë šìŽ ìëŁë멎, [`~transformers.Trainer.push_to_hub`] ë©ìë넌 ìŹì©íìŹ ëȘšëžì íëžì êł”ì í ì ìì”ëë€.
-
-```py
->>> trainer.push_to_hub()
-```
-
-
-
-
-Keras넌 ìŹì©íìŹ ëȘšëžì íìž íëíë ë°©ëČì ì”ìíì§ ìì êČœì°, [ìŹêž°](../training#train-a-tensorflow-model-with-keras)ì êž°ëłž íí 늏ìŒì íìžíìžì!
-
-
-TensorFlowìì ëȘšëžì íìž íëíë €ë©Ž, 뚌ì ì”í°ë§ìŽì íšìì íì”ë„ ì€ìŒì„Ž, ê·žëŠŹêł ìŒë¶ íë š íìŽíŒíëŒëŻží°ë„Œ ì€ì íŽìŒ í©ëë€:
-
-```py
->>> from transformers import create_optimizer
-
->>> batch_size = 16
->>> num_train_epochs = 3
->>> num_train_steps = (len(tokenized_wnut["train"]) // batch_size) * num_train_epochs
->>> optimizer, lr_schedule = create_optimizer(
-... init_lr=2e-5,
-... num_train_steps=num_train_steps,
-... weight_decay_rate=0.01,
-... num_warmup_steps=0,
-... )
-```
-
-ê·žë° ë€ì [`TFAutoModelForSequenceClassification`]ì ìŹì©íìŹ DistilBERT넌 ê°ì žì€êł , ììëë ë ìŽëž ìì ë ìŽëž ë§€íì ì§ì í©ëë€:
-
-```py
->>> from transformers import TFAutoModelForTokenClassification
-
->>> model = TFAutoModelForTokenClassification.from_pretrained(
-... "distilbert-base-uncased", num_labels=13, id2label=id2label, label2id=label2id
-... )
-```
-
-[`~transformers.TFPreTrainedModel.prepare_tf_dataset`]ì ìŹì©íìŹ ë°ìŽí° ìžížë„Œ `tf.data.Dataset` íììŒëĄ ëłíí©ëë€:
-
-```py
->>> tf_train_set = model.prepare_tf_dataset(
-... tokenized_wnut["train"],
-... shuffle=True,
-... batch_size=16,
-... collate_fn=data_collator,
-... )
-
->>> tf_validation_set = model.prepare_tf_dataset(
-... tokenized_wnut["validation"],
-... shuffle=False,
-... batch_size=16,
-... collate_fn=data_collator,
-... )
-```
-
-[`compile`](https://keras.io/api/models/model_training_apis/#compile-method)넌 ìŹì©íìŹ íë ší ëȘšëžì ê”Źì±í©ëë€:
-
-```py
->>> import tensorflow as tf
-
->>> model.compile(optimizer=optimizer)
-```
-
-íë šì ììíêž° ì ì ì€ì íŽìŒí ë§ì§ë§ ë ê°ì§ë ììžĄìì seqeval ì ì넌 êłì°íêł , ëȘšëžì íëžì ì
ëĄëí ë°©ëČì ì êł”íë êČì
ëë€. ëȘšë [Keras callbacks](../main_classes/keras_callbacks)넌 ìŹì©íìŹ ìíë©ëë€.
-
-[`~transformers.KerasMetricCallback`]ì `compute_metrics` íšì넌 ì ëŹíìžì:
-
-```py
->>> from transformers.keras_callbacks import KerasMetricCallback
-
->>> metric_callback = KerasMetricCallback(metric_fn=compute_metrics, eval_dataset=tf_validation_set)
-```
-
-[`~transformers.PushToHubCallback`]ìì ëȘšëžêłŒ í íŹëìŽì 넌 ì
ëĄëí ììč넌 ì§ì í©ëë€:
-
-```py
->>> from transformers.keras_callbacks import PushToHubCallback
-
->>> push_to_hub_callback = PushToHubCallback(
-... output_dir="my_awesome_wnut_model",
-... tokenizer=tokenizer,
-... )
-```
-
-ê·žë° ë€ì ìœë°±ì íšê» 돶ì”ëë€:
-
-```py
->>> callbacks = [metric_callback, push_to_hub_callback]
-```
-
-ëëìŽ, ëȘšëž íë šì ììí ì€ëčê° ëìì”ëë€! [`fit`](https://keras.io/api/models/model_training_apis/#fit-method)ì íë š ë°ìŽí° ìžíž, êČìŠ ë°ìŽí° ìžíž, ìíì ì ë° ìœë°±ì ì ëŹíìŹ íìž íëí©ëë€:
-
-```py
->>> model.fit(x=tf_train_set, validation_data=tf_validation_set, epochs=3, callbacks=callbacks)
-```
-
-íë šìŽ ìëŁë멎, ëȘšëžìŽ ìëìŒëĄ íëžì ì
ëĄëëìŽ ëê”Źë ìŹì©í ì ìì”ëë€!
-
-
-
-
-
-í í° ë¶ë„넌 ìí ëȘšëžì íìž íëíë ììží ìì ë ë€ì
-[PyTorch notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/token_classification.ipynb)
-ëë [TensorFlow notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/token_classification-tf.ipynb)넌 ì°žìĄ°íìžì.
-
-
-
-## ì¶ëĄ [[inference]]
-
-ìąìì, ìŽì ëȘšëžì íìž íëíìŒë ì¶ëĄ ì ìŹì©í ì ìì”ëë€!
-
-ì¶ëĄ ì ìííêł ì íë í
ì€ížë„Œ ê°ì žìëŽ
ìë€:
-
-```py
->>> text = "The Golden State Warriors are an American professional basketball team based in San Francisco."
-```
-
-íìž íëë ëȘšëžëĄ ì¶ëĄ ì ìëíë ê°ì„ ê°ëší ë°©ëČì [`pipeline`]넌 ìŹì©íë êČì
ëë€. ëȘšëžëĄ NERì `pipeline`ì ìžì€íŽì€ííêł , í
ì€ížë„Œ ì ëŹíŽëłŽìžì:
-
-```py
->>> from transformers import pipeline
-
->>> classifier = pipeline("ner", model="stevhliu/my_awesome_wnut_model")
->>> classifier(text)
-[{'entity': 'B-location',
- 'score': 0.42658573,
- 'index': 2,
- 'word': 'golden',
- 'start': 4,
- 'end': 10},
- {'entity': 'I-location',
- 'score': 0.35856336,
- 'index': 3,
- 'word': 'state',
- 'start': 11,
- 'end': 16},
- {'entity': 'B-group',
- 'score': 0.3064001,
- 'index': 4,
- 'word': 'warriors',
- 'start': 17,
- 'end': 25},
- {'entity': 'B-location',
- 'score': 0.65523505,
- 'index': 13,
- 'word': 'san',
- 'start': 80,
- 'end': 83},
- {'entity': 'B-location',
- 'score': 0.4668663,
- 'index': 14,
- 'word': 'francisco',
- 'start': 84,
- 'end': 93}]
-```
-
-ìíë€ë©Ž, `pipeline`ì êČ°êłŒë„Œ ìëìŒëĄ ëł”ì í ìë ìì”ëë€:
-
-
-
-í
ì€ížë„Œ í í°ííêł PyTorch í
ì넌 ë°íí©ëë€:
-
-```py
->>> from transformers import AutoTokenizer
-
->>> tokenizer = AutoTokenizer.from_pretrained("stevhliu/my_awesome_wnut_model")
->>> inputs = tokenizer(text, return_tensors="pt")
-```
-
-ì
ë „ì ëȘšëžì ì ëŹíêł `logits`ì ë°íí©ëë€:
-
-```py
->>> from transformers import AutoModelForTokenClassification
-
->>> model = AutoModelForTokenClassification.from_pretrained("stevhliu/my_awesome_wnut_model")
->>> with torch.no_grad():
-... logits = model(**inputs).logits
-```
-
-ê°ì„ ëì íë„ ì ê°ì§ íŽëì€ë„Œ ëȘšëžì `id2label` ë§€íì ìŹì©íìŹ í
ì€íž ë ìŽëžëĄ ëłíí©ëë€:
-
-```py
->>> predictions = torch.argmax(logits, dim=2)
->>> predicted_token_class = [model.config.id2label[t.item()] for t in predictions[0]]
->>> predicted_token_class
-['O',
- 'O',
- 'B-location',
- 'I-location',
- 'B-group',
- 'O',
- 'O',
- 'O',
- 'O',
- 'O',
- 'O',
- 'O',
- 'O',
- 'B-location',
- 'B-location',
- 'O',
- 'O']
-```
-
-
-í
ì€ížë„Œ í í°ííêł TensorFlow í
ì넌 ë°íí©ëë€:
-
-```py
->>> from transformers import AutoTokenizer
-
->>> tokenizer = AutoTokenizer.from_pretrained("stevhliu/my_awesome_wnut_model")
->>> inputs = tokenizer(text, return_tensors="tf")
-```
-
-ì
ë „ê°ì ëȘšëžì ì ëŹíêł `logits`ì ë°íí©ëë€:
-
-```py
->>> from transformers import TFAutoModelForTokenClassification
-
->>> model = TFAutoModelForTokenClassification.from_pretrained("stevhliu/my_awesome_wnut_model")
->>> logits = model(**inputs).logits
-```
-
-ê°ì„ ëì íë„ ì ê°ì§ íŽëì€ë„Œ ëȘšëžì `id2label` ë§€íì ìŹì©íìŹ í
ì€íž ë ìŽëžëĄ ëłíí©ëë€:
-
-```py
->>> predicted_token_class_ids = tf.math.argmax(logits, axis=-1)
->>> predicted_token_class = [model.config.id2label[t] for t in predicted_token_class_ids[0].numpy().tolist()]
->>> predicted_token_class
-['O',
- 'O',
- 'B-location',
- 'I-location',
- 'B-group',
- 'O',
- 'O',
- 'O',
- 'O',
- 'O',
- 'O',
- 'O',
- 'O',
- 'B-location',
- 'B-location',
- 'O',
- 'O']
-```
-
-
diff --git a/docs/source/ko/tasks/translation.md b/docs/source/ko/tasks/translation.md
new file mode 100644
index 000000000000..b18f56d13b9d
--- /dev/null
+++ b/docs/source/ko/tasks/translation.md
@@ -0,0 +1,409 @@
+
+
+# ëČì[[translation]]
+
+[[open-in-colab]]
+
+
+
+ëČìì í ìžìŽëĄ ë ìíì€ë„Œ ë€ë„ž ìžìŽëĄ ëłíí©ëë€. ëČììŽë ììœì ì
ë „ì ë°ì ìŒë šì ì¶ë „ì ë°ííë ê°ë „í íë ììíŹìž ìíì€-íŹ-ìíì€ ëŹžì ëĄ ê”Źì±í ì ìë ëíì ìž íì€íŹì
ëë€. ëČì ìì€í
ì ìŒë°ì ìŒëĄ ë€ë„ž ìžìŽëĄ ë í
ì€íž ê°ì ëČìì ìŹì©ëì§ë§, ìì± ê°ì í”ììŽë í
ì€íž-ìì± ëë ìì±-í
ì€ížì ê°ì ìĄ°í©ìë ìŹì©ë ì ìì”ëë€.
+
+ìŽ ê°ìŽëìì íì”í ëŽì©ì:
+
+1. ììŽ í
ì€ížë„Œ íëì€ìŽëĄ ëČìíêž° ìíŽ [T5](https://huggingface.co/t5-small) ëȘšëžì OPUS Books ë°ìŽí°ìžížì ììŽ-íëì€ìŽ íì ì§í©ìŒëĄ íìžíëíë ë°©ëČêłŒ
+2. íìžíëë ëȘšëžì ì¶ëĄ ì ìŹì©íë ë°©ëČì
ëë€.
+
+
+ìŽ íì€íŹ ê°ìŽëë ìë ëȘšëž ìí€í
ìČìë ìì©í ì ìì”ëë€.
+
+
+
+[BART](../model_doc/bart), [BigBird-Pegasus](../model_doc/bigbird_pegasus), [Blenderbot](../model_doc/blenderbot), [BlenderbotSmall](../model_doc/blenderbot-small), [Encoder decoder](../model_doc/encoder-decoder), [FairSeq Machine-Translation](../model_doc/fsmt), [GPTSAN-japanese](../model_doc/gptsan-japanese), [LED](../model_doc/led), [LongT5](../model_doc/longt5), [M2M100](../model_doc/m2m_100), [Marian](../model_doc/marian), [mBART](../model_doc/mbart), [MT5](../model_doc/mt5), [MVP](../model_doc/mvp), [NLLB](../model_doc/nllb), [NLLB-MOE](../model_doc/nllb-moe), [Pegasus](../model_doc/pegasus), [PEGASUS-X](../model_doc/pegasus_x), [PLBart](../model_doc/plbart), [ProphetNet](../model_doc/prophetnet), [SwitchTransformers](../model_doc/switch_transformers), [T5](../model_doc/t5), [XLM-ProphetNet](../model_doc/xlm-prophetnet)
+
+
+
+
+
+ììíêž° ì ì íìí ëŒìŽëžëŹëŠŹê° ëȘšë ì€ìčëìŽ ìëì§ íìžíìžì:
+
+```bash
+pip install transformers datasets evaluate sacrebleu
+```
+
+ëȘšëžì ì
ëĄëíêł ì»€ëź€ëí°ì êł”ì í ì ìëëĄ Hugging Face êłì ì ëĄê·žìžíë êČìŽ ìąì”ëë€. ìëĄìŽ ì°œìŽ íìë멎 í í°ì ì
ë „íìŹ ëĄê·žìžíìžì.
+
+```py
+>>> from huggingface_hub import notebook_login
+
+>>> notebook_login()
+```
+
+## OPUS Books ë°ìŽí°ìžíž ê°ì žì€êž°[[load-opus-books-dataset]]
+
+뚌ì đ€ Datasets ëŒìŽëžëŹëŠŹìì [OPUS Books](https://huggingface.co/datasets/opus_books) ë°ìŽí°ìžížì ììŽ-íëì€ìŽ íì ì§í©ì ê°ì žì€ìžì.
+
+```py
+>>> from datasets import load_dataset
+
+>>> books = load_dataset("opus_books", "en-fr")
+```
+
+ë°ìŽí°ìžížë„Œ [`~datasets.Dataset.train_test_split`] ë©ìë넌 ìŹì©íìŹ íë š ë° í
ì€íž ë°ìŽí°ëĄ ë¶í íìžì.
+
+```py
+>>> books = books["train"].train_test_split(test_size=0.2)
+```
+
+íë š ë°ìŽí°ìì ìì넌 ìŽíŽëłŒêčì?
+
+```py
+>>> books["train"][0]
+{'id': '90560',
+ 'translation': {'en': 'But this lofty plateau measured only a few fathoms, and soon we reentered Our Element.',
+ 'fr': 'Mais ce plateau élevé ne mesurait que quelques toises, et bientÎt nous fûmes rentrés dans notre élément.'}}
+```
+
+ë°íë ëì
ë늏ì `translation` í€ê° í
ì€ížì ììŽ, íëì€ìŽ ëČì ì íŹíšíêł ìë êČì ëłŒ ì ìì”ëë€.
+
+## ì ìČ늏[[preprocess]]
+
+
+
+ë€ì ëšêłëĄ ììŽ-íëì€ìŽ ìì ìČ늏íêž° ìíŽ T5 í íŹëìŽì 넌 ê°ì žì€ìžì.
+
+```py
+>>> from transformers import AutoTokenizer
+
+>>> checkpoint = "t5-small"
+>>> tokenizer = AutoTokenizer.from_pretrained(checkpoint)
+```
+
+ë§ë€ ì ìČ늏 íšìë ìë ìê”ŹìŹíì ì¶©ìĄ±íŽìŒ í©ëë€:
+
+1. T5ê° ëČì íì€íŹìì ìžì§í ì ìëëĄ ì
ë „ ìì í륏íížë„Œ ì¶ê°íìžì. ìŹëŹ NLP íì€íŹë„Œ í ì ìë ëȘšëž ì€ ìŒë¶ë ìŽë êČ íì€íŹ í륏íížë„Œ 믞늏 ì€ìŒí©ëë€.
+2. ììŽ(ììŽ)êłŒ ëČììŽ(íëì€ìŽ)넌 ëłëëĄ í í°ííìžì. ììŽ ìŽíëĄ ìŹì íì”ë í íŹëìŽì ëĄ íëì€ìŽ í
ì€ížë„Œ í í°íí ìë ìêž° ë돞ì
ëë€.
+3. `max_length` ë§€ê°ëłìëĄ ì€ì í ì”ë êžžìŽëłŽë€ êžžì§ ìëëĄ ìíì€ë„Œ truncateíìžì.
+
+```py
+>>> source_lang = "en"
+>>> target_lang = "fr"
+>>> prefix = "translate English to French: "
+
+
+>>> def preprocess_function(examples):
+... inputs = [prefix + example[source_lang] for example in examples["translation"]]
+... targets = [example[target_lang] for example in examples["translation"]]
+... model_inputs = tokenizer(inputs, text_target=targets, max_length=128, truncation=True)
+... return model_inputs
+```
+
+ì ìČŽ ë°ìŽí°ìžížì ì ìČ늏 íšì넌 ì ì©íë €ë©Ž đ€ Datasetsì [`~datasets.Dataset.map`] ë©ìë넌 ìŹì©íìžì. `map` íšìì ìë넌 ëìŽë €ë©Ž `batched=True`넌 ì€ì íìŹ ë°ìŽí°ìžížì ìŹëŹ ìì넌 í ëČì ìČ늏íë ë°©ëČìŽ ìì”ëë€.
+
+```py
+>>> tokenized_books = books.map(preprocess_function, batched=True)
+```
+
+ìŽì [`DataCollatorForSeq2Seq`]넌 ìŹì©íìŹ ìì ë°°ìč넌 ìì±í©ëë€. ë°ìŽí°ìžížì ì”ë êžžìŽëĄ ì ë¶ë„Œ paddingíë ëì , ë°ìŽí° ì ë Ź ì€ ê° ë°°ìčì ì”ë êžžìŽëĄ 돞ì„ì *ëì ìŒëĄ padding*íë êČìŽ ë íšìšì ì
ëë€.
+
+
+
+```py
+>>> from transformers import DataCollatorForSeq2Seq
+
+>>> data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer, model=checkpoint)
+```
+
+
+
+```py
+>>> from transformers import DataCollatorForSeq2Seq
+
+>>> data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer, model=checkpoint, return_tensors="tf")
+```
+
+
+
+## íê°[[evalulate]]
+
+íë š ì€ì ë©ížëŠì íŹíší멎 ëȘšëžì ì±ë„ì íê°íë ë° ëììŽ ë©ëë€. đ€ [Evaluate](https://huggingface.co/docs/evaluate/index) ëŒìŽëžëŹëŠŹëĄ íê° ë°©ëČ(evaluation method)ì ëč 넎êČ ê°ì žìŹ ì ìì”ëë€. íìŹ íì€íŹì ì í©í SacreBLEU ë©ížëŠì ê°ì žì€ìžì. (ë©ížëŠì ê°ì žì€êł êłì°íë ë°©ëČì ëíŽ ììží ììëłŽë €ë©Ž đ€ Evaluate [ëëŹëłŽêž°](https://huggingface.co/docs/evaluate/a_quick_tour)넌 ì°žìĄ°íìžì):
+
+```py
+>>> import evaluate
+
+>>> metric = evaluate.load("sacrebleu")
+```
+
+ê·žë° ë€ì [`~evaluate.EvaluationModule.compute`]ì ììžĄê°êłŒ ë ìŽëžì ì ëŹíìŹ SacreBLEU ì ì넌 êłì°íë íšì넌 ìì±íìžì:
+
+```py
+>>> import numpy as np
+
+
+>>> def postprocess_text(preds, labels):
+... preds = [pred.strip() for pred in preds]
+... labels = [[label.strip()] for label in labels]
+
+... return preds, labels
+
+
+>>> def compute_metrics(eval_preds):
+... preds, labels = eval_preds
+... if isinstance(preds, tuple):
+... preds = preds[0]
+... decoded_preds = tokenizer.batch_decode(preds, skip_special_tokens=True)
+
+... labels = np.where(labels != -100, labels, tokenizer.pad_token_id)
+... decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)
+
+... decoded_preds, decoded_labels = postprocess_text(decoded_preds, decoded_labels)
+
+... result = metric.compute(predictions=decoded_preds, references=decoded_labels)
+... result = {"bleu": result["score"]}
+
+... prediction_lens = [np.count_nonzero(pred != tokenizer.pad_token_id) for pred in preds]
+... result["gen_len"] = np.mean(prediction_lens)
+... result = {k: round(v, 4) for k, v in result.items()}
+... return result
+```
+
+ìŽì `compute_metrics` íšìë ì€ëčëìêł , íë š êłŒì ì ì€ì í ë ë€ì ìŽíŽëłŒ ìì ì
ëë€.
+
+## íë š[[train]]
+
+
+
+
+
+[`Trainer`]ëĄ ëȘšëžì íìžíëíë ë°©ëČì ì”ìíì§ ìë€ë©Ž [ìŹêž°](../training#train-with-pytorch-trainer)ìì êž°ëłž íí 늏ìŒì ìŽíŽëłŽìêž° ë°ëëë€!
+
+
+
+ëȘšëžì íë šìíŹ ì€ëčê° ëìê”°ì! [`AutoModelForSeq2SeqLM`]ìŒëĄ T5넌 ëĄëíìžì:
+
+```py
+>>> from transformers import AutoModelForSeq2SeqLM, Seq2SeqTrainingArguments, Seq2SeqTrainer
+
+>>> model = AutoModelForSeq2SeqLM.from_pretrained(checkpoint)
+```
+
+ìŽì ìž ëšêłë§ ê±°ìč멎 ëì
ëë€:
+
+1. [`Seq2SeqTrainingArguments`]ìì íë š íìŽíŒíëŒëŻží°ë„Œ ì ìíìžì. ì ìŒí íì ë§€ê°ëłìë ëȘšëžì ì ì„í ììčìž `output_dir`ì
ëë€. ëȘšëžì Hubì ížìíêž° ìíŽ `push_to_hub=True`ëĄ ì€ì íìžì. (ëȘšëžì ì
ëĄëíë €ë©Ž Hugging Faceì ëĄê·žìžíŽìŒ í©ëë€.) [`Trainer`]ë ìíìŽ ëë ëë§ë€ SacreBLEU ë©ížëŠì íê°íêł íë š ìČŽíŹíŹìžížë„Œ ì ì„í©ëë€.
+2. [`Seq2SeqTrainer`]ì íë š ìžì넌 ì ëŹíìžì. ëȘšëž, ë°ìŽí° ìžíž, í íŹëìŽì , data collator ë° `compute_metrics` íšìë ë©ëŹì ì ëŹíŽìŒ í©ëë€.
+3. [`~Trainer.train`]ì ížì¶íìŹ ëȘšëžì íìžíëíìžì.
+
+```py
+>>> training_args = Seq2SeqTrainingArguments(
+... output_dir="my_awesome_opus_books_model",
+... evaluation_strategy="epoch",
+... learning_rate=2e-5,
+... per_device_train_batch_size=16,
+... per_device_eval_batch_size=16,
+... weight_decay=0.01,
+... save_total_limit=3,
+... num_train_epochs=2,
+... predict_with_generate=True,
+... fp16=True,
+... push_to_hub=True,
+... )
+
+>>> trainer = Seq2SeqTrainer(
+... model=model,
+... args=training_args,
+... train_dataset=tokenized_books["train"],
+... eval_dataset=tokenized_books["test"],
+... tokenizer=tokenizer,
+... data_collator=data_collator,
+... compute_metrics=compute_metrics,
+... )
+
+>>> trainer.train()
+````
+
+íì”ìŽ ìëŁë멎 [`~transformers.Trainer.push_to_hub`] ë©ìëëĄ ëȘšëžì Hubì êł”ì íìžì. ìŽëŹë©Ž ëê”Źë ëȘšëžì ìŹì©í ì ìêČ ë©ëë€:
+
+```py
+>>> trainer.push_to_hub()
+```
+
+
+
+
+KerasëĄ ëȘšëžì íìžíëíë ë°©ëČìŽ ì”ìíì§ ìë€ë©Ž, [ìŹêž°](../training#train-a-tensorflow-model-with-keras)ìì êž°ëłž íí 늏ìŒì ìŽíŽëłŽìêž° ë°ëëë€!
+
+
+TensorFlowìì ëȘšëžì íìžíëíë €ë©Ž ì°ì optimizer íšì, íì”ë„ ì€ìŒì€ ë±ì íë š íìŽíŒíëŒëŻží°ë„Œ ì€ì íìžì:
+
+```py
+>>> from transformers import AdamWeightDecay
+
+>>> optimizer = AdamWeightDecay(learning_rate=2e-5, weight_decay_rate=0.01)
+```
+
+ìŽì [`TFAutoModelForSeq2SeqLM`]ëĄ T5넌 ê°ì žì€ìžì:
+
+```py
+>>> from transformers import TFAutoModelForSeq2SeqLM
+
+>>> model = TFAutoModelForSeq2SeqLM.from_pretrained(checkpoint)
+```
+
+[`~transformers.TFPreTrainedModel.prepare_tf_dataset`]ëĄ ë°ìŽí° ìžížë„Œ `tf.data.Dataset` íììŒëĄ ëłííìžì:
+
+```py
+>>> tf_train_set = model.prepare_tf_dataset(
+... tokenized_books["train"],
+... shuffle=True,
+... batch_size=16,
+... collate_fn=data_collator,
+... )
+
+>>> tf_test_set = model.prepare_tf_dataset(
+... tokenized_books["test"],
+... shuffle=False,
+... batch_size=16,
+... collate_fn=data_collator,
+... )
+```
+
+íë šíêž° ìíŽ [`compile`](https://keras.io/api/models/model_training_apis/#compile-method) ë©ìëëĄ ëȘšëžì ê”Źì±íìžì:
+
+```py
+>>> import tensorflow as tf
+
+>>> model.compile(optimizer=optimizer)
+```
+
+íë šì ììíêž° ì ì ììžĄê°ìŒëĄë¶í° SacreBLEU ë©ížëŠì êłì°íë ë°©ëČêłŒ ëȘšëžì Hubì ì
ëĄëíë ë°©ëČ ë ê°ì§ë„Œ 믞늏 ì€ì íŽëŹìŒ í©ëë€. ë ë€ [Keras callbacks](../main_classes/keras_callbacks)ëĄ ê”Źííìžì.
+
+[`~transformers.KerasMetricCallback`]ì `compute_metrics` íšì넌 ì ëŹíìžì.
+
+```py
+>>> from transformers.keras_callbacks import KerasMetricCallback
+
+>>> metric_callback = KerasMetricCallback(metric_fn=compute_metrics, eval_dataset=tf_validation_set)
+```
+
+ëȘšëžêłŒ í íŹëìŽì 넌 ì
ëĄëí ììč넌 [`~transformers.PushToHubCallback`]ìì ì§ì íìžì:
+
+```py
+>>> from transformers.keras_callbacks import PushToHubCallback
+
+>>> push_to_hub_callback = PushToHubCallback(
+... output_dir="my_awesome_opus_books_model",
+... tokenizer=tokenizer,
+... )
+```
+
+ìŽì ìœë°±ë€ì íë°ëĄ 돶ìŽìŁŒìžì:
+
+```py
+>>> callbacks = [metric_callback, push_to_hub_callback]
+```
+
+ëëìŽ ëȘšëžì íë šìíŹ ëȘšë ì€ëč넌 ë§ìł€ê”°ì! ìŽì íë š ë° êČìŠ ë°ìŽí° ìžížì [`fit`](https://keras.io/api/models/model_training_apis/#fit-method) ë©ìë넌 ìí ìì ë§ë€ìŽë ìœë°±êłŒ íšê» ížì¶íìŹ ëȘšëžì íìžíëíìžì:
+
+```py
+>>> model.fit(x=tf_train_set, validation_data=tf_test_set, epochs=3, callbacks=callbacks)
+```
+
+íì”ìŽ ìëŁë멎 ëȘšëžìŽ ìëìŒëĄ Hubì ì
ëĄëëêł , ëê”Źë ìŹì©í ì ìêČ ë©ëë€!
+
+
+
+
+
+ëČìì ìíŽ ëȘšëžì íìžíëíë ë°©ëČì ëí ëłŽë€ ììží ìì ë íŽëč [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)ì ì°žìĄ°íìžì.
+
+
+
+## ì¶ëĄ [[inference]]
+
+ìąìì, ìŽì ëȘšëžì íìžíëíìŒë ì¶ëĄ ì ìŹì©í ì ìì”ëë€!
+
+ë€ë„ž ìžìŽëĄ ëČìíêł ì¶ì í
ì€ížë„Œ ìšëłŽìžì. T5ì êČœì° ìíë íì€íŹë„Œ ì
ë „ì ì ëìŹëĄ ì¶ê°íŽìŒ í©ëë€. ì넌 ë€ìŽ ììŽìì íëì€ìŽëĄ ëČìíë êČœì°, ìëì ê°ì ì ëìŹê° ì¶ê°ë©ëë€:
+
+```py
+>>> text = "translate English to French: Legumes share resources with nitrogen-fixing bacteria."
+```
+
+íìžíëë ëȘšëžëĄ ì¶ëĄ íêž°ì ì ìŒ ê°ëší ë°©ëČì [`pipeline`]ì ìŹì©íë êČì
ëë€. íŽëč ëȘšëžëĄ ëČì `pipeline`ì ë§ë ë€, í
ì€ížë„Œ ì ëŹíìžì:
+
+```py
+>>> from transformers import pipeline
+
+>>> translator = pipeline("translation", model="my_awesome_opus_books_model")
+>>> translator(text)
+[{'translation_text': 'Legumes partagent des ressources avec des bactéries azotantes.'}]
+```
+
+ìíë€ë©Ž `pipeline`ì êČ°êłŒë„Œ ì§ì ëł”ì í ìë ìì”ëë€:
+
+
+
+í
ì€ížë„Œ í í°ííêł `input_ids`넌 PyTorch í
ìëĄ ë°ííìžì:
+
+```py
+>>> from transformers import AutoTokenizer
+
+>>> tokenizer = AutoTokenizer.from_pretrained("my_awesome_opus_books_model")
+>>> inputs = tokenizer(text, return_tensors="pt").input_ids
+```
+
+[`~transformers.generation_utils.GenerationMixin.generate`] ë©ìëëĄ ëČìì ìì±íìžì. ë€ìí í
ì€íž ìì± ì ë” ë° ìì±ì ì ìŽíêž° ìí ë§€ê°ëłìì ëí ììží ëŽì©ì [Text Generation](../main_classes/text_generation) API넌 ìŽíŽëłŽìêž° ë°ëëë€.
+
+```py
+>>> from transformers import AutoModelForSeq2SeqLM
+
+>>> model = AutoModelForSeq2SeqLM.from_pretrained("my_awesome_opus_books_model")
+>>> outputs = model.generate(inputs, max_new_tokens=40, do_sample=True, top_k=30, top_p=0.95)
+```
+
+ìì±ë í í° IDë€ì ë€ì í
ì€ížëĄ ëìœë©íìžì:
+
+```py
+>>> tokenizer.decode(outputs[0], skip_special_tokens=True)
+'Les lignées partagent des ressources avec des bactéries enfixant l'azote.'
+```
+
+
+í
ì€ížë„Œ í í°ííêł `input_ids`넌 TensorFlow í
ìëĄ ë°ííìžì:
+
+```py
+>>> from transformers import AutoTokenizer
+
+>>> tokenizer = AutoTokenizer.from_pretrained("my_awesome_opus_books_model")
+>>> inputs = tokenizer(text, return_tensors="tf").input_ids
+```
+
+[`~transformers.generation_tf_utils.TFGenerationMixin.generate`] ë©ìëëĄ ëČìì ìì±íìžì. ë€ìí í
ì€íž ìì± ì ë” ë° ìì±ì ì ìŽíêž° ìí ë§€ê°ëłìì ëí ììží ëŽì©ì [Text Generation](../main_classes/text_generation) API넌 ìŽíŽëłŽìêž° ë°ëëë€.
+
+```py
+>>> from transformers import TFAutoModelForSeq2SeqLM
+
+>>> model = TFAutoModelForSeq2SeqLM.from_pretrained("my_awesome_opus_books_model")
+>>> outputs = model.generate(inputs, max_new_tokens=40, do_sample=True, top_k=30, top_p=0.95)
+```
+
+ìì±ë í í° IDë€ì ë€ì í
ì€ížëĄ ëìœë©íìžì:
+
+```py
+>>> tokenizer.decode(outputs[0], skip_special_tokens=True)
+'Les lugumes partagent les ressources avec des bactéries fixatrices d'azote.'
+```
+
+
diff --git a/docs/source/ko/tasks/translation.mdx b/docs/source/ko/tasks/translation.mdx
deleted file mode 100644
index f0256052af70..000000000000
--- a/docs/source/ko/tasks/translation.mdx
+++ /dev/null
@@ -1,405 +0,0 @@
-
-
-# ëČì[[translation]]
-
-[[open-in-colab]]
-
-
-
-ëČìì í ìžìŽëĄ ë ìíì€ë„Œ ë€ë„ž ìžìŽëĄ ëłíí©ëë€. ëČììŽë ììœì ì
ë „ì ë°ì ìŒë šì ì¶ë „ì ë°ííë ê°ë „í íë ììíŹìž ìíì€-íŹ-ìíì€ ëŹžì ëĄ ê”Źì±í ì ìë ëíì ìž íì€íŹì
ëë€. ëČì ìì€í
ì ìŒë°ì ìŒëĄ ë€ë„ž ìžìŽëĄ ë í
ì€íž ê°ì ëČìì ìŹì©ëì§ë§, ìì± ê°ì í”ììŽë í
ì€íž-ìì± ëë ìì±-í
ì€ížì ê°ì ìĄ°í©ìë ìŹì©ë ì ìì”ëë€.
-
-ìŽ ê°ìŽëìì íì”í ëŽì©ì:
-
-1. ììŽ í
ì€ížë„Œ íëì€ìŽëĄ ëČìíêž° ìíŽ [T5](https://huggingface.co/t5-small) ëȘšëžì OPUS Books ë°ìŽí°ìžížì ììŽ-íëì€ìŽ íì ì§í©ìŒëĄ íìžíëíë ë°©ëČêłŒ
-2. íìžíëë ëȘšëžì ì¶ëĄ ì ìŹì©íë ë°©ëČì
ëë€.
-
-
-ìŽ íì€íŹ ê°ìŽëë ìë ëȘšëž ìí€í
ìČìë ìì©í ì ìì”ëë€.
-
-
-
-[BART](../model_doc/bart), [BigBird-Pegasus](../model_doc/bigbird_pegasus), [Blenderbot](../model_doc/blenderbot), [BlenderbotSmall](../model_doc/blenderbot-small), [Encoder decoder](../model_doc/encoder-decoder), [FairSeq Machine-Translation](../model_doc/fsmt), [GPTSAN-japanese](../model_doc/gptsan-japanese), [LED](../model_doc/led), [LongT5](../model_doc/longt5), [M2M100](../model_doc/m2m_100), [Marian](../model_doc/marian), [mBART](../model_doc/mbart), [MT5](../model_doc/mt5), [MVP](../model_doc/mvp), [NLLB](../model_doc/nllb), [NLLB-MOE](../model_doc/nllb-moe), [Pegasus](../model_doc/pegasus), [PEGASUS-X](../model_doc/pegasus_x), [PLBart](../model_doc/plbart), [ProphetNet](../model_doc/prophetnet), [SwitchTransformers](../model_doc/switch_transformers), [T5](../model_doc/t5), [XLM-ProphetNet](../model_doc/xlm-prophetnet)
-
-
-
-
-
-ììíêž° ì ì íìí ëŒìŽëžëŹëŠŹê° ëȘšë ì€ìčëìŽ ìëì§ íìžíìžì:
-
-```bash
-pip install transformers datasets evaluate sacrebleu
-```
-
-ëȘšëžì ì
ëĄëíêł ì»€ëź€ëí°ì êł”ì í ì ìëëĄ Hugging Face êłì ì ëĄê·žìžíë êČìŽ ìąì”ëë€. ìëĄìŽ ì°œìŽ íìë멎 í í°ì ì
ë „íìŹ ëĄê·žìžíìžì.
-
-```py
->>> from huggingface_hub import notebook_login
-
->>> notebook_login()
-```
-
-## OPUS Books ë°ìŽí°ìžíž ê°ì žì€êž°[[load-opus-books-dataset]]
-
-뚌ì đ€ Datasets ëŒìŽëžëŹëŠŹìì [OPUS Books](https://huggingface.co/datasets/opus_books) ë°ìŽí°ìžížì ììŽ-íëì€ìŽ íì ì§í©ì ê°ì žì€ìžì.
-
-```py
->>> from datasets import load_dataset
-
->>> books = load_dataset("opus_books", "en-fr")
-```
-
-ë°ìŽí°ìžížë„Œ [`~datasets.Dataset.train_test_split`] ë©ìë넌 ìŹì©íìŹ íë š ë° í
ì€íž ë°ìŽí°ëĄ ë¶í íìžì.
-
-```py
->>> books = books["train"].train_test_split(test_size=0.2)
-```
-
-íë š ë°ìŽí°ìì ìì넌 ìŽíŽëłŒêčì?
-
-```py
->>> books["train"][0]
-{'id': '90560',
- 'translation': {'en': 'But this lofty plateau measured only a few fathoms, and soon we reentered Our Element.',
- 'fr': 'Mais ce plateau élevé ne mesurait que quelques toises, et bientÎt nous fûmes rentrés dans notre élément.'}}
-```
-
-ë°íë ëì
ë늏ì `translation` í€ê° í
ì€ížì ììŽ, íëì€ìŽ ëČì ì íŹíšíêł ìë êČì ëłŒ ì ìì”ëë€.
-
-## ì ìČ늏[[preprocess]]
-
-
-
-ë€ì ëšêłëĄ ììŽ-íëì€ìŽ ìì ìČ늏íêž° ìíŽ T5 í íŹëìŽì 넌 ê°ì žì€ìžì.
-
-```py
->>> from transformers import AutoTokenizer
-
->>> checkpoint = "t5-small"
->>> tokenizer = AutoTokenizer.from_pretrained(checkpoint)
-```
-
-ë§ë€ ì ìČ늏 íšìë ìë ìê”ŹìŹíì ì¶©ìĄ±íŽìŒ í©ëë€:
-
-1. T5ê° ëČì íì€íŹìì ìžì§í ì ìëëĄ ì
ë „ ìì í륏íížë„Œ ì¶ê°íìžì. ìŹëŹ NLP íì€íŹë„Œ í ì ìë ëȘšëž ì€ ìŒë¶ë ìŽë êČ íì€íŹ í륏íížë„Œ 믞늏 ì€ìŒí©ëë€.
-2. ììŽ(ììŽ)êłŒ ëČììŽ(íëì€ìŽ)넌 ëłëëĄ í í°ííìžì. ììŽ ìŽíëĄ ìŹì íì”ë í íŹëìŽì ëĄ íëì€ìŽ í
ì€ížë„Œ í í°íí ìë ìêž° ë돞ì
ëë€.
-3. `max_length` ë§€ê°ëłìëĄ ì€ì í ì”ë êžžìŽëłŽë€ êžžì§ ìëëĄ ìíì€ë„Œ truncateíìžì.
-
-```py
->>> source_lang = "en"
->>> target_lang = "fr"
->>> prefix = "translate English to French: "
-
-
->>> def preprocess_function(examples):
-... inputs = [prefix + example[source_lang] for example in examples["translation"]]
-... targets = [example[target_lang] for example in examples["translation"]]
-... model_inputs = tokenizer(inputs, text_target=targets, max_length=128, truncation=True)
-... return model_inputs
-```
-
-ì ìČŽ ë°ìŽí°ìžížì ì ìČ늏 íšì넌 ì ì©íë €ë©Ž đ€ Datasetsì [`~datasets.Dataset.map`] ë©ìë넌 ìŹì©íìžì. `map` íšìì ìë넌 ëìŽë €ë©Ž `batched=True`넌 ì€ì íìŹ ë°ìŽí°ìžížì ìŹëŹ ìì넌 í ëČì ìČ늏íë ë°©ëČìŽ ìì”ëë€.
-
-```py
->>> tokenized_books = books.map(preprocess_function, batched=True)
-```
-
-ìŽì [`DataCollatorForSeq2Seq`]넌 ìŹì©íìŹ ìì ë°°ìč넌 ìì±í©ëë€. ë°ìŽí°ìžížì ì”ë êžžìŽëĄ ì ë¶ë„Œ paddingíë ëì , ë°ìŽí° ì ë Ź ì€ ê° ë°°ìčì ì”ë êžžìŽëĄ 돞ì„ì *ëì ìŒëĄ padding*íë êČìŽ ë íšìšì ì
ëë€.
-
-
-
-```py
->>> from transformers import DataCollatorForSeq2Seq
-
->>> data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer, model=checkpoint)
-```
-
-
-
-```py
->>> from transformers import DataCollatorForSeq2Seq
-
->>> data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer, model=checkpoint, return_tensors="tf")
-```
-
-
-
-## íê°[[evalulate]]
-
-íë š ì€ì ë©ížëŠì íŹíší멎 ëȘšëžì ì±ë„ì íê°íë ë° ëììŽ ë©ëë€. đ€ [Evaluate](https://huggingface.co/docs/evaluate/index) ëŒìŽëžëŹëŠŹëĄ íê° ë°©ëČ(evaluation method)ì ëč 넎êČ ê°ì žìŹ ì ìì”ëë€. íìŹ íì€íŹì ì í©í SacreBLEU ë©ížëŠì ê°ì žì€ìžì. (ë©ížëŠì ê°ì žì€êł êłì°íë ë°©ëČì ëíŽ ììží ììëłŽë €ë©Ž đ€ Evaluate [ëëŹëłŽêž°](https://huggingface.co/docs/evaluate/a_quick_tour)넌 ì°žìĄ°íìžì):
-
-```py
->>> import evaluate
-
->>> metric = evaluate.load("sacrebleu")
-```
-
-ê·žë° ë€ì [`~evaluate.EvaluationModule.compute`]ì ììžĄê°êłŒ ë ìŽëžì ì ëŹíìŹ SacreBLEU ì ì넌 êłì°íë íšì넌 ìì±íìžì:
-
-```py
->>> import numpy as np
-
-
->>> def postprocess_text(preds, labels):
-... preds = [pred.strip() for pred in preds]
-... labels = [[label.strip()] for label in labels]
-
-... return preds, labels
-
-
->>> def compute_metrics(eval_preds):
-... preds, labels = eval_preds
-... if isinstance(preds, tuple):
-... preds = preds[0]
-... decoded_preds = tokenizer.batch_decode(preds, skip_special_tokens=True)
-
-... labels = np.where(labels != -100, labels, tokenizer.pad_token_id)
-... decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)
-
-... decoded_preds, decoded_labels = postprocess_text(decoded_preds, decoded_labels)
-
-... result = metric.compute(predictions=decoded_preds, references=decoded_labels)
-... result = {"bleu": result["score"]}
-
-... prediction_lens = [np.count_nonzero(pred != tokenizer.pad_token_id) for pred in preds]
-... result["gen_len"] = np.mean(prediction_lens)
-... result = {k: round(v, 4) for k, v in result.items()}
-... return result
-```
-
-ìŽì `compute_metrics` íšìë ì€ëčëìêł , íë š êłŒì ì ì€ì í ë ë€ì ìŽíŽëłŒ ìì ì
ëë€.
-
-## íë š[[train]]
-
-
-
-
-
-[`Trainer`]ëĄ ëȘšëžì íìžíëíë ë°©ëČì ì”ìíì§ ìë€ë©Ž [ìŹêž°](../training#train-with-pytorch-trainer)ìì êž°ëłž íí 늏ìŒì ìŽíŽëłŽìêž° ë°ëëë€!
-
-
-
-ëȘšëžì íë šìíŹ ì€ëčê° ëìê”°ì! [`AutoModelForSeq2SeqLM`]ìŒëĄ T5넌 ëĄëíìžì:
-
-```py
->>> from transformers import AutoModelForSeq2SeqLM, Seq2SeqTrainingArguments, Seq2SeqTrainer
-
->>> model = AutoModelForSeq2SeqLM.from_pretrained(checkpoint)
-```
-
-ìŽì ìž ëšêłë§ ê±°ìč멎 ëì
ëë€:
-
-1. [`Seq2SeqTrainingArguments`]ìì íë š íìŽíŒíëŒëŻží°ë„Œ ì ìíìžì. ì ìŒí íì ë§€ê°ëłìë ëȘšëžì ì ì„í ììčìž `output_dir`ì
ëë€. ëȘšëžì Hubì ížìíêž° ìíŽ `push_to_hub=True`ëĄ ì€ì íìžì. (ëȘšëžì ì
ëĄëíë €ë©Ž Hugging Faceì ëĄê·žìžíŽìŒ í©ëë€.) [`Trainer`]ë ìíìŽ ëë ëë§ë€ SacreBLEU ë©ížëŠì íê°íêł íë š ìČŽíŹíŹìžížë„Œ ì ì„í©ëë€.
-2. [`Seq2SeqTrainer`]ì íë š ìžì넌 ì ëŹíìžì. ëȘšëž, ë°ìŽí° ìžíž, í íŹëìŽì , data collator ë° `compute_metrics` íšìë ë©ëŹì ì ëŹíŽìŒ í©ëë€.
-3. [`~Trainer.train`]ì ížì¶íìŹ ëȘšëžì íìžíëíìžì.
-
-```py
->>> training_args = Seq2SeqTrainingArguments(
-... output_dir="my_awesome_opus_books_model",
-... evaluation_strategy="epoch",
-... learning_rate=2e-5,
-... per_device_train_batch_size=16,
-... per_device_eval_batch_size=16,
-... weight_decay=0.01,
-... save_total_limit=3,
-... num_train_epochs=2,
-... predict_with_generate=True,
-... fp16=True,
-... push_to_hub=True,
-... )
-
->>> trainer = Seq2SeqTrainer(
-... model=model,
-... args=training_args,
-... train_dataset=tokenized_books["train"],
-... eval_dataset=tokenized_books["test"],
-... tokenizer=tokenizer,
-... data_collator=data_collator,
-... compute_metrics=compute_metrics,
-... )
-
->>> trainer.train()
-````
-
-íì”ìŽ ìëŁë멎 [`~transformers.Trainer.push_to_hub`] ë©ìëëĄ ëȘšëžì Hubì êł”ì íìžì. ìŽëŹë©Ž ëê”Źë ëȘšëžì ìŹì©í ì ìêČ ë©ëë€:
-
-```py
->>> trainer.push_to_hub()
-```
-
-
-
-
-KerasëĄ ëȘšëžì íìžíëíë ë°©ëČìŽ ì”ìíì§ ìë€ë©Ž, [ìŹêž°](../training#train-a-tensorflow-model-with-keras)ìì êž°ëłž íí 늏ìŒì ìŽíŽëłŽìêž° ë°ëëë€!
-
-
-TensorFlowìì ëȘšëžì íìžíëíë €ë©Ž ì°ì optimizer íšì, íì”ë„ ì€ìŒì€ ë±ì íë š íìŽíŒíëŒëŻží°ë„Œ ì€ì íìžì:
-
-```py
->>> from transformers import AdamWeightDecay
-
->>> optimizer = AdamWeightDecay(learning_rate=2e-5, weight_decay_rate=0.01)
-```
-
-ìŽì [`TFAutoModelForSeq2SeqLM`]ëĄ T5넌 ê°ì žì€ìžì:
-
-```py
->>> from transformers import TFAutoModelForSeq2SeqLM
-
->>> model = TFAutoModelForSeq2SeqLM.from_pretrained(checkpoint)
-```
-
-[`~transformers.TFPreTrainedModel.prepare_tf_dataset`]ëĄ ë°ìŽí° ìžížë„Œ `tf.data.Dataset` íììŒëĄ ëłííìžì:
-
-```py
->>> tf_train_set = model.prepare_tf_dataset(
-... tokenized_books["train"],
-... shuffle=True,
-... batch_size=16,
-... collate_fn=data_collator,
-... )
-
->>> tf_test_set = model.prepare_tf_dataset(
-... tokenized_books["test"],
-... shuffle=False,
-... batch_size=16,
-... collate_fn=data_collator,
-... )
-```
-
-íë šíêž° ìíŽ [`compile`](https://keras.io/api/models/model_training_apis/#compile-method) ë©ìëëĄ ëȘšëžì ê”Źì±íìžì:
-
-```py
->>> import tensorflow as tf
-
->>> model.compile(optimizer=optimizer)
-```
-
-íë šì ììíêž° ì ì ììžĄê°ìŒëĄë¶í° SacreBLEU ë©ížëŠì êłì°íë ë°©ëČêłŒ ëȘšëžì Hubì ì
ëĄëíë ë°©ëČ ë ê°ì§ë„Œ 믞늏 ì€ì íŽëŹìŒ í©ëë€. ë ë€ [Keras callbacks](../main_classes/keras_callbacks)ëĄ ê”Źííìžì.
-
-[`~transformers.KerasMetricCallback`]ì `compute_metrics` íšì넌 ì ëŹíìžì.
-
-```py
->>> from transformers.keras_callbacks import KerasMetricCallback
-
->>> metric_callback = KerasMetricCallback(metric_fn=compute_metrics, eval_dataset=tf_validation_set)
-```
-
-ëȘšëžêłŒ í íŹëìŽì 넌 ì
ëĄëí ììč넌 [`~transformers.PushToHubCallback`]ìì ì§ì íìžì:
-
-```py
->>> from transformers.keras_callbacks import PushToHubCallback
-
->>> push_to_hub_callback = PushToHubCallback(
-... output_dir="my_awesome_opus_books_model",
-... tokenizer=tokenizer,
-... )
-```
-
-ìŽì ìœë°±ë€ì íë°ëĄ 돶ìŽìŁŒìžì:
-
-```py
->>> callbacks = [metric_callback, push_to_hub_callback]
-```
-
-ëëìŽ ëȘšëžì íë šìíŹ ëȘšë ì€ëč넌 ë§ìł€ê”°ì! ìŽì íë š ë° êČìŠ ë°ìŽí° ìžížì [`fit`](https://keras.io/api/models/model_training_apis/#fit-method) ë©ìë넌 ìí ìì ë§ë€ìŽë ìœë°±êłŒ íšê» ížì¶íìŹ ëȘšëžì íìžíëíìžì:
-
-```py
->>> model.fit(x=tf_train_set, validation_data=tf_test_set, epochs=3, callbacks=callbacks)
-```
-
-íì”ìŽ ìëŁë멎 ëȘšëžìŽ ìëìŒëĄ Hubì ì
ëĄëëêł , ëê”Źë ìŹì©í ì ìêČ ë©ëë€!
-
-
-
-
-
-ëČìì ìíŽ ëȘšëžì íìžíëíë ë°©ëČì ëí ëłŽë€ ììží ìì ë íŽëč [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)ì ì°žìĄ°íìžì.
-
-
-
-## ì¶ëĄ [[inference]]
-
-ìąìì, ìŽì ëȘšëžì íìžíëíìŒë ì¶ëĄ ì ìŹì©í ì ìì”ëë€!
-
-ë€ë„ž ìžìŽëĄ ëČìíêł ì¶ì í
ì€ížë„Œ ìšëłŽìžì. T5ì êČœì° ìíë íì€íŹë„Œ ì
ë „ì ì ëìŹëĄ ì¶ê°íŽìŒ í©ëë€. ì넌 ë€ìŽ ììŽìì íëì€ìŽëĄ ëČìíë êČœì°, ìëì ê°ì ì ëìŹê° ì¶ê°ë©ëë€:
-
-```py
->>> text = "translate English to French: Legumes share resources with nitrogen-fixing bacteria."
-```
-
-íìžíëë ëȘšëžëĄ ì¶ëĄ íêž°ì ì ìŒ ê°ëší ë°©ëČì [`pipeline`]ì ìŹì©íë êČì
ëë€. íŽëč ëȘšëžëĄ ëČì `pipeline`ì ë§ë ë€, í
ì€ížë„Œ ì ëŹíìžì:
-
-```py
->>> from transformers import pipeline
-
->>> translator = pipeline("translation", model="my_awesome_opus_books_model")
->>> translator(text)
-[{'translation_text': 'Legumes partagent des ressources avec des bactéries azotantes.'}]
-```
-
-ìíë€ë©Ž `pipeline`ì êČ°êłŒë„Œ ì§ì ëł”ì í ìë ìì”ëë€:
-
-
-
-í
ì€ížë„Œ í í°ííêł `input_ids`넌 PyTorch í
ìëĄ ë°ííìžì:
-
-```py
->>> from transformers import AutoTokenizer
-
->>> tokenizer = AutoTokenizer.from_pretrained("my_awesome_opus_books_model")
->>> inputs = tokenizer(text, return_tensors="pt").input_ids
-```
-
-[`~transformers.generation_utils.GenerationMixin.generate`] ë©ìëëĄ ëČìì ìì±íìžì. ë€ìí í
ì€íž ìì± ì ë” ë° ìì±ì ì ìŽíêž° ìí ë§€ê°ëłìì ëí ììží ëŽì©ì [Text Generation](../main_classes/text_generation) API넌 ìŽíŽëłŽìêž° ë°ëëë€.
-
-```py
->>> from transformers import AutoModelForSeq2SeqLM
-
->>> model = AutoModelForSeq2SeqLM.from_pretrained("my_awesome_opus_books_model")
->>> outputs = model.generate(inputs, max_new_tokens=40, do_sample=True, top_k=30, top_p=0.95)
-```
-
-ìì±ë í í° IDë€ì ë€ì í
ì€ížëĄ ëìœë©íìžì:
-
-```py
->>> tokenizer.decode(outputs[0], skip_special_tokens=True)
-'Les lignées partagent des ressources avec des bactéries enfixant l'azote.'
-```
-
-
-í
ì€ížë„Œ í í°ííêł `input_ids`넌 TensorFlow í
ìëĄ ë°ííìžì:
-
-```py
->>> from transformers import AutoTokenizer
-
->>> tokenizer = AutoTokenizer.from_pretrained("my_awesome_opus_books_model")
->>> inputs = tokenizer(text, return_tensors="tf").input_ids
-```
-
-[`~transformers.generation_tf_utils.TFGenerationMixin.generate`] ë©ìëëĄ ëČìì ìì±íìžì. ë€ìí í
ì€íž ìì± ì ë” ë° ìì±ì ì ìŽíêž° ìí ë§€ê°ëłìì ëí ììží ëŽì©ì [Text Generation](../main_classes/text_generation) API넌 ìŽíŽëłŽìêž° ë°ëëë€.
-
-```py
->>> from transformers import TFAutoModelForSeq2SeqLM
-
->>> model = TFAutoModelForSeq2SeqLM.from_pretrained("my_awesome_opus_books_model")
->>> outputs = model.generate(inputs, max_new_tokens=40, do_sample=True, top_k=30, top_p=0.95)
-```
-
-ìì±ë í í° IDë€ì ë€ì í
ì€ížëĄ ëìœë©íìžì:
-
-```py
->>> tokenizer.decode(outputs[0], skip_special_tokens=True)
-'Les lugumes partagent les ressources avec des bactéries fixatrices d'azote.'
-```
-
-
diff --git a/docs/source/ko/tasks/video_classification.md b/docs/source/ko/tasks/video_classification.md
new file mode 100644
index 000000000000..eb04352d84a0
--- /dev/null
+++ b/docs/source/ko/tasks/video_classification.md
@@ -0,0 +1,498 @@
+
+
+# ìì ë¶ë„ [[video-classification]]
+
+[[open-in-colab]]
+
+
+ìì ë¶ë„ë ìì ì ìČŽì ë ìŽëž ëë íŽëì€ë„Œ ì§ì íë ìì
ì
ëë€. ê° ìììë íëì íŽëì€ê° ìì êČìŒëĄ ììë©ëë€. ìì ë¶ë„ ëȘšëžì ììì ì
ë „ìŒëĄ ë°ì ìŽë íŽëì€ì ìíëì§ì ëí ììžĄì ë°íí©ëë€. ìŽëŹí ëȘšëžì ìììŽ ìŽë€ ëŽì©ìžì§ ë¶ë„íë ë° ìŹì©ë ì ìì”ëë€. ìì ë¶ë„ì ì€ì ìì© ìë íŒížëì€ ì±ìì ì ì©í ëì / ìŽë ìžì ìëčì€ê° ìì”ëë€. ìŽë ëí ìê° ì„ì ìžìŽ ìŽëí ë ëłŽìĄ°íëë° ìŹì©ë ì ìì”ëë€
+
+ìŽ ê°ìŽëììë ë€ìì ìííë ë°©ëČì 볎ìŹì€ëë€:
+
+1. [UCF101](https://www.crcv.ucf.edu/data/UCF101.php) ë°ìŽí° ìžížì íì ì§í©ì í”íŽ [VideoMAE](https://huggingface.co/docs/transformers/main/en/model_doc/videomae) ëȘšëžì ëŻžìž ìĄ°ì íêž°.
+2. ëŻžìž ìĄ°ì í ëȘšëžì ì¶ëĄ ì ìŹì©íêž°.
+
+
+
+ìŽ íí 늏ìŒìì ì€ëȘ
íë ìì
ì ë€ì ëȘšëž ìí€í
ìČìì ì§ìë©ëë€:
+
+
+
+[TimeSformer](../model_doc/timesformer), [VideoMAE](../model_doc/videomae)
+
+
+
+
+
+
+ììíêž° ì ì íìí ëȘšë ëŒìŽëžëŹëŠŹê° ì€ìčëìëì§ íìžíìžì:
+```bash
+pip install -q pytorchvideo transformers evaluate
+```
+
+ììì ìČ늏íêł ì€ëčíêž° ìíŽ [PyTorchVideo](https://pytorchvideo.org/)(ìŽí `pytorchvideo`)넌 ìŹì©í©ëë€.
+
+ì»€ëź€ëí°ì ëȘšëžì ì
ëĄëíêł êł”ì í ì ìëëĄ Hugging Face êłì ì ëĄê·žìžíë êČì ê¶ì„í©ëë€. í륏íížê° ëíë멎 í í°ì ì
ë „íìŹ ëĄê·žìžíìžì:
+
+```py
+>>> from huggingface_hub import notebook_login
+
+>>> notebook_login()
+```
+
+## UCF101 ë°ìŽí°ì
ë¶ëŹì€êž° [[load-ufc101-dataset]]
+
+[UCF-101](https://www.crcv.ucf.edu/data/UCF101.php) ë°ìŽí° ìžížì íì ì§í©(subset)ì ë¶ëŹì€ë êČìŒëĄ ììí ì ìì”ëë€. ì ìČŽ ë°ìŽí° ìžížë„Œ íì”íëë° ë ë§ì ìê°ì í ì íêž° ì ì ë°ìŽí°ì íì ì§í©ì ë¶ëŹì ëȘšë êČìŽ ì ìëíëì§ ì€ííêł íìží ì ìì”ëë€.
+
+```py
+>>> from huggingface_hub import hf_hub_download
+
+>>> hf_dataset_identifier = "sayakpaul/ucf101-subset"
+>>> filename = "UCF101_subset.tar.gz"
+>>> file_path = hf_hub_download(repo_id=hf_dataset_identifier, filename=filename, repo_type="dataset")
+```
+
+ë°ìŽí° ìžížì íì ì§í©ìŽ ë€ìŽëĄë ë멎, ìì¶ë íìŒì ìì¶ì íŽì íŽìŒ í©ëë€:
+```py
+>>> import tarfile
+
+>>> with tarfile.open(file_path) as t:
+... t.extractall(".")
+```
+
+ì ìČŽ ë°ìŽí° ìžížë ë€ìêłŒ ê°ìŽ ê”Źì±ëìŽ ìì”ëë€.
+
+```bash
+UCF101_subset/
+ train/
+ BandMarching/
+ video_1.mp4
+ video_2.mp4
+ ...
+ Archery
+ video_1.mp4
+ video_2.mp4
+ ...
+ ...
+ val/
+ BandMarching/
+ video_1.mp4
+ video_2.mp4
+ ...
+ Archery
+ video_1.mp4
+ video_2.mp4
+ ...
+ ...
+ test/
+ BandMarching/
+ video_1.mp4
+ video_2.mp4
+ ...
+ Archery
+ video_1.mp4
+ video_2.mp4
+ ...
+ ...
+```
+
+
+ì ë Źë ììì êČœëĄë ë€ìêłŒ ê°ì”ëë€:
+
+```bash
+...
+'UCF101_subset/train/ApplyEyeMakeup/v_ApplyEyeMakeup_g07_c04.avi',
+'UCF101_subset/train/ApplyEyeMakeup/v_ApplyEyeMakeup_g07_c06.avi',
+'UCF101_subset/train/ApplyEyeMakeup/v_ApplyEyeMakeup_g08_c01.avi',
+'UCF101_subset/train/ApplyEyeMakeup/v_ApplyEyeMakeup_g09_c02.avi',
+'UCF101_subset/train/ApplyEyeMakeup/v_ApplyEyeMakeup_g09_c06.avi'
+...
+```
+
+ëìŒí ê·žëŁč/ì„멎ì ìíë ìì íŽëŠœì íìŒ êČœëĄìì `g`ëĄ íìëìŽ ìì”ëë€. ì넌 ë€ë©Ž, `v_ApplyEyeMakeup_g07_c04.avi`ì `v_ApplyEyeMakeup_g07_c06.avi` ìŽ ìì”ëë€. ìŽ ëì ê°ì ê·žëŁčì
ëë€.
+
+êČìŠ ë° íê° ë°ìŽí° ë¶í ì í ë, [ë°ìŽí° ëì¶(data leakage)](https://www.kaggle.com/code/alexisbcook/data-leakage)ì ë°©ì§íêž° ìíŽ ëìŒí ê·žëŁč / ì„멎ì ìì íŽëŠœì ìŹì©íì§ ìììŒ í©ëë€. ìŽ íí 늏ìŒìì ìŹì©íë íì ì§í©ì ìŽëŹí ì ëłŽë„Œ êł ë €íêł ìì”ëë€.
+
+ê·ž ë€ììŒëĄ, ë°ìŽí° ìžížì ìĄŽìŹíë ëŒëČšì ì¶ì¶í©ëë€. ëí, ëȘšëžì ìŽêž°íí ë ëììŽ ë ëì
ë늏(dictionary data type)넌 ìì±í©ëë€.
+
+* `label2id`: íŽëì€ ìŽëŠì ì ìì ë§€íí©ëë€.
+* `id2label`: ì ì넌 íŽëì€ ìŽëŠì ë§€íí©ëë€.
+
+```py
+>>> class_labels = sorted({str(path).split("/")[2] for path in all_video_file_paths})
+>>> label2id = {label: i for i, label in enumerate(class_labels)}
+>>> id2label = {i: label for label, i in label2id.items()}
+
+>>> print(f"Unique classes: {list(label2id.keys())}.")
+
+# Unique classes: ['ApplyEyeMakeup', 'ApplyLipstick', 'Archery', 'BabyCrawling', 'BalanceBeam', 'BandMarching', 'BaseballPitch', 'Basketball', 'BasketballDunk', 'BenchPress'].
+```
+
+ìŽ ë°ìŽí° ìžížìë ìŽ 10ê°ì êł ì í íŽëì€ê° ìì”ëë€. ê° íŽëì€ë§ë€ 30ê°ì ìììŽ íë š ìžížì ìì”ëë€
+
+## ëŻžìž ìĄ°ì íêž° ìíŽ ëȘšëž ê°ì žì€êž° [[load-a-model-to-fine-tune]]
+
+ìŹì íë šë ìČŽíŹíŹìžížì ìČŽíŹíŹìžížì ì°êŽë ìŽëŻžì§ íëĄìžì넌 ìŹì©íìŹ ìì ë¶ë„ ëȘšëžì ìžì€íŽì€íí©ëë€. ëȘšëžì ìžìœëìë 믞늏 íì”ë ë§€ê°ëłìê° ì êł”ëë©°, ë¶ë„ í€ë(ë°ìŽí°ë„Œ ë¶ë„íë ë§ì§ë§ ë ìŽìŽ)ë 돎ììëĄ ìŽêž°íë©ëë€. ë°ìŽí° ìžížì ì ìČ늏 íìŽíëŒìžì ìì±í ëë ìŽëŻžì§ íëĄìžìê° ì ì©í©ëë€.
+
+```py
+>>> from transformers import VideoMAEImageProcessor, VideoMAEForVideoClassification
+
+>>> model_ckpt = "MCG-NJU/videomae-base"
+>>> image_processor = VideoMAEImageProcessor.from_pretrained(model_ckpt)
+>>> model = VideoMAEForVideoClassification.from_pretrained(
+... model_ckpt,
+... label2id=label2id,
+... id2label=id2label,
+... ignore_mismatched_sizes=True, # provide this in case you're planning to fine-tune an already fine-tuned checkpoint
+... )
+```
+
+ëȘšëžì ê°ì žì€ë ëì, ë€ìêłŒ ê°ì êČœêł ë„Œ ë§ìŁŒìč ì ìì”ëë€:
+
+```bash
+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']
+- 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).
+- 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).
+Some weights of VideoMAEForVideoClassification were not initialized from the model checkpoint at MCG-NJU/videomae-base and are newly initialized: ['classifier.bias', 'classifier.weight']
+You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.
+```
+
+
+ì êČœêł ë ì°ëŠŹê° ìŒë¶ ê°ì€ìč(ì: `classifier` ìž”ì ê°ì€ìčì íží„)넌 ëČëŠŹêł ìëĄìŽ `classifier` ìž”ì ê°ì€ìčì íží„ì 돎ììëĄ ìŽêž°ííêł ìë€ë êČì ìë €ì€ëë€. ìŽ êČœì°ìë 믞늏 íì”ë ê°ì€ìčê° ìë ìëĄìŽ í€ë넌 ì¶ê°íêł ììŒëŻëĄ, ëŒìŽëžëŹëŠŹê° ëȘšëžì ì¶ëĄ ì ìŹì©íêž° ì ì ëŻžìž ìĄ°ì íëŒêł êČœêł ë„Œ 볎ëŽë êČì ëčì°í©ëë€. ê·žëŠŹêł ìŽì ì°ëŠŹë ìŽ ëȘšëžì ëŻžìž ìĄ°ì í ìì ì
ëë€.
+
+**ì°žêł ** ìŽ [ìČŽíŹíŹìžíž](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)ë ìì”ëë€.
+
+## íë šì ìí ë°ìŽí° ìžíž ì€ëčíêž°[[prepare-the-datasets-for-training]]
+
+ìì ì ìČëŠŹë„Œ ìíŽ [PyTorchVideo ëŒìŽëžëŹëŠŹ](https://pytorchvideo.org/)넌 íì©í êČì
ëë€. íìí ìą
ìì±ì ê°ì žì€ë êČìŒëĄ ììíìžì.
+
+```py
+>>> import pytorchvideo.data
+
+>>> from pytorchvideo.transforms import (
+... ApplyTransformToKey,
+... Normalize,
+... RandomShortSideScale,
+... RemoveKey,
+... ShortSideScale,
+... UniformTemporalSubsample,
+... )
+
+>>> from torchvision.transforms import (
+... Compose,
+... Lambda,
+... RandomCrop,
+... RandomHorizontalFlip,
+... Resize,
+... )
+```
+
+íì” ë°ìŽí° ìžíž ëłíìë 'ê· ìŒí ìê° ìíë§(uniform temporal subsampling)', 'íœì
ì ê·í(pixel normalization)', 'ëë€ ìëŒëŽêž°(random cropping)' ë° 'ëë€ ìí ë€ì§êž°(random horizontal flipping)'ì ìĄ°í©ì ìŹì©í©ëë€. êČìŠ ë° íê° ë°ìŽí° ìžíž ëłíìë 'ëë€ ìëŒëŽêž°'ì 'ëë€ ë€ì§êž°'넌 ì ìží ëìŒí ëłí ìČŽìžì ì ì§í©ëë€. ìŽëŹí ëłíì ëíŽ ììží ììëłŽë €ë©Ž [PyTorchVideo êł”ì 돞ì](https://pytorchvideo.org)넌 íìžíìžì.
+
+ìŹì íë šë ëȘšëžêłŒ êŽë šë ìŽëŻžì§ íëĄìžì넌 ìŹì©íìŹ ë€ì ì ëłŽë„Œ ì»ì ì ìì”ëë€:
+
+* ìì íë ì íœì
ì ì ê·ííë ë° ìŹì©ëë ìŽëŻžì§ íê· êłŒ íì€ ížì°š
+* ìì íë ììŽ ìĄ°ì ë êł”ê° íŽìë
+
+
+뚌ì , ëȘ ê°ì§ ìì넌 ì ìí©ëë€.
+
+```py
+>>> mean = image_processor.image_mean
+>>> std = image_processor.image_std
+>>> if "shortest_edge" in image_processor.size:
+... height = width = image_processor.size["shortest_edge"]
+>>> else:
+... height = image_processor.size["height"]
+... width = image_processor.size["width"]
+>>> resize_to = (height, width)
+
+>>> num_frames_to_sample = model.config.num_frames
+>>> sample_rate = 4
+>>> fps = 30
+>>> clip_duration = num_frames_to_sample * sample_rate / fps
+```
+
+ìŽì ë°ìŽí° ìžížì íčíë ì ìČ늏(transform)êłŒ ë°ìŽí° ìžíž ììČŽë„Œ ì ìí©ëë€. 뚌ì íë š ë°ìŽí° ìžížëĄ ììí©ëë€:
+
+```py
+>>> train_transform = Compose(
+... [
+... ApplyTransformToKey(
+... key="video",
+... transform=Compose(
+... [
+... UniformTemporalSubsample(num_frames_to_sample),
+... Lambda(lambda x: x / 255.0),
+... Normalize(mean, std),
+... RandomShortSideScale(min_size=256, max_size=320),
+... RandomCrop(resize_to),
+... RandomHorizontalFlip(p=0.5),
+... ]
+... ),
+... ),
+... ]
+... )
+
+>>> train_dataset = pytorchvideo.data.Ucf101(
+... data_path=os.path.join(dataset_root_path, "train"),
+... clip_sampler=pytorchvideo.data.make_clip_sampler("random", clip_duration),
+... decode_audio=False,
+... transform=train_transform,
+... )
+```
+
+ê°ì ë°©ìì ìì
íëŠì êČìŠêłŒ íê° ìžížìë ì ì©í ì ìì”ëë€.
+
+```py
+>>> val_transform = Compose(
+... [
+... ApplyTransformToKey(
+... key="video",
+... transform=Compose(
+... [
+... UniformTemporalSubsample(num_frames_to_sample),
+... Lambda(lambda x: x / 255.0),
+... Normalize(mean, std),
+... Resize(resize_to),
+... ]
+... ),
+... ),
+... ]
+... )
+
+>>> val_dataset = pytorchvideo.data.Ucf101(
+... data_path=os.path.join(dataset_root_path, "val"),
+... clip_sampler=pytorchvideo.data.make_clip_sampler("uniform", clip_duration),
+... decode_audio=False,
+... transform=val_transform,
+... )
+
+>>> test_dataset = pytorchvideo.data.Ucf101(
+... data_path=os.path.join(dataset_root_path, "test"),
+... clip_sampler=pytorchvideo.data.make_clip_sampler("uniform", clip_duration),
+... decode_audio=False,
+... transform=val_transform,
+... )
+```
+
+
+**ì°žêł **: ìì ë°ìŽí° ìžížì íìŽíëŒìžì [êł”ì íìŽí ìč ìì ](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()` íšì넌 ìŹì©íë ë° ëŹžì ê° ìì êČì
ëë€.
+
+ë°ìŽí° ìžížì ììì ê°ì넌 ìêž° ìíŽ `num_videos` ìžìì ì ê·Œí ì ìì”ëë€.
+
+```py
+>>> print(train_dataset.num_videos, val_dataset.num_videos, test_dataset.num_videos)
+# (300, 30, 75)
+```
+
+## ë ëì ëëČêč
ì ìíŽ ì ìČ늏 ìì ìê°ííêž°[[visualize-the-preprocessed-video-for-better-debugging]]
+
+```py
+>>> import imageio
+>>> import numpy as np
+>>> from IPython.display import Image
+
+>>> def unnormalize_img(img):
+... """Un-normalizes the image pixels."""
+... img = (img * std) + mean
+... img = (img * 255).astype("uint8")
+... return img.clip(0, 255)
+
+>>> def create_gif(video_tensor, filename="sample.gif"):
+... """Prepares a GIF from a video tensor.
+...
+... The video tensor is expected to have the following shape:
+... (num_frames, num_channels, height, width).
+... """
+... frames = []
+... for video_frame in video_tensor:
+... frame_unnormalized = unnormalize_img(video_frame.permute(1, 2, 0).numpy())
+... frames.append(frame_unnormalized)
+... kargs = {"duration": 0.25}
+... imageio.mimsave(filename, frames, "GIF", **kargs)
+... return filename
+
+>>> def display_gif(video_tensor, gif_name="sample.gif"):
+... """Prepares and displays a GIF from a video tensor."""
+... video_tensor = video_tensor.permute(1, 0, 2, 3)
+... gif_filename = create_gif(video_tensor, gif_name)
+... return Image(filename=gif_filename)
+
+>>> sample_video = next(iter(train_dataset))
+>>> video_tensor = sample_video["video"]
+>>> display_gif(video_tensor)
+```
+
+
+
+
+
+## ëȘšëž íë šíêž°[[train-the-model]]
+
+đ€ Transformersì [`Trainer`](https://huggingface.co/docs/transformers/main_classes/trainer)넌 ìŹì©íìŹ ëȘšëžì íë šììŒëłŽìžì. `Trainer`넌 ìžì€íŽì€ííë €ë©Ž íë š ì€ì êłŒ íê° ì§í넌 ì ìíŽìŒ í©ëë€. ê°ì„ ì€ìí êČì [`TrainingArguments`](https://huggingface.co/transformers/main_classes/trainer.html#transformers.TrainingArguments)ì
ëë€. ìŽ íŽëì€ë íë šì ê”Źì±íë ëȘšë ìì±ì íŹíšíë©°, íë š ì€ ìČŽíŹíŹìžížë„Œ ì ì„í ì¶ë „ íŽë ìŽëŠì íìëĄ í©ëë€. ëí đ€ Hubì ëȘšëž ì ì„ìì ëȘšë ì ëłŽë„Œ ëêž°ííë ë° ëììŽ ë©ëë€.
+
+ëë¶ë¶ì íë š ìžìë ë°ëĄ ì€ëȘ
í íìë ìì”ëë€. íì§ë§ ìŹêž°ìì ì€ìí ìžìë `remove_unused_columns=False` ì
ëë€. ìŽ ìžìë ëȘšëžì ížì¶ íšììì ìŹì©ëì§ ìë ëȘšë ìì± ìŽ(columns)ì ìì í©ëë€. êž°ëłžê°ì ìŒë°ì ìŒëĄ Trueì
ëë€. ìŽë ìŹì©ëì§ ìë êž°ë„ ìŽì ìì íë êČìŽ ìŽìì ìŽë©°, ì
ë „ì ëȘšëžì ížì¶ íšìëĄ íêž°(unpack)ê° ìŹìì§êž° ë돞ì
ëë€. íì§ë§ ìŽ êČœì°ìë `pixel_values`(ëȘšëžì ì
ë „ìŒëĄ íìì ìž í€)넌 ìì±íêž° ìíŽ ìŹì©ëì§ ìë êž°ë„('video'ê° íčí ê·žë ì”ëë€)ìŽ íìí©ëë€. ë°ëŒì remove_unused_columnsì FalseëĄ ì€ì íŽìŒ í©ëë€.
+
+```py
+>>> from transformers import TrainingArguments, Trainer
+
+>>> model_name = model_ckpt.split("/")[-1]
+>>> new_model_name = f"{model_name}-finetuned-ucf101-subset"
+>>> num_epochs = 4
+
+>>> args = TrainingArguments(
+... new_model_name,
+... remove_unused_columns=False,
+... evaluation_strategy="epoch",
+... save_strategy="epoch",
+... learning_rate=5e-5,
+... per_device_train_batch_size=batch_size,
+... per_device_eval_batch_size=batch_size,
+... warmup_ratio=0.1,
+... logging_steps=10,
+... load_best_model_at_end=True,
+... metric_for_best_model="accuracy",
+... push_to_hub=True,
+... max_steps=(train_dataset.num_videos // batch_size) * num_epochs,
+... )
+```
+
+`pytorchvideo.data.Ucf101()` íšìëĄ ë°íëë ë°ìŽí° ìžížë `__len__` ë©ìëê° ìŽìëìŽ ìì§ ìì”ëë€. ë°ëŒì, `TrainingArguments`넌 ìžì€íŽì€íí ë `max_steps`넌 ì ìíŽìŒ í©ëë€.
+
+ë€ììŒëĄ, íê°ì§í넌 ë¶ëŹì€êł , ììžĄê°ìì íê°ì§í넌 êłì°í íšì넌 ì ìí©ëë€. íìí ì ìČ늏 ìì
ì ììžĄë ëĄì§(logits)ì argmax ê°ì ì·šíë êČëżì
ëë€:
+
+```py
+import evaluate
+
+metric = evaluate.load("accuracy")
+
+
+def compute_metrics(eval_pred):
+ predictions = np.argmax(eval_pred.predictions, axis=1)
+ return metric.compute(predictions=predictions, references=eval_pred.label_ids)
+```
+
+**íê°ì ëí ì°žêł ìŹí**:
+
+[VideoMAE ë
ŒëŹž](https://arxiv.org/abs/2203.12602)ìì ì ìë ë€ìêłŒ ê°ì íê° ì ë”ì ìŹì©í©ëë€. í
ì€íž ìììì ìŹëŹ íŽëŠœì ì ííêł ê·ž íŽëŠœì ë€ìí íŹëĄì ì ì©íìŹ ì§êł ì ì넌 ëłŽêł í©ëë€. ê·žëŹë ìŽëČ íí 늏ìŒììë ê°ëšíšêłŒ ê°êȰíšì ìíŽ íŽëč ì ë”ì êł ë €íì§ ìì”ëë€.
+
+ëí, ìì 넌 돶ìŽì ë°°ìč넌 íì±íë `collate_fn`ì ì ìíŽìŒí©ëë€. ê° ë°°ìčë `pixel_values`ì `labels`ëŒë 2ê°ì í€ëĄ ê”Źì±ë©ëë€.
+
+```py
+>>> def collate_fn(examples):
+... # permute to (num_frames, num_channels, height, width)
+... pixel_values = torch.stack(
+... [example["video"].permute(1, 0, 2, 3) for example in examples]
+... )
+... labels = torch.tensor([example["label"] for example in examples])
+... return {"pixel_values": pixel_values, "labels": labels}
+```
+
+ê·žë° ë€ì ìŽ ëȘšë êČì ë°ìŽí° ìžížì íšê» `Trainer`ì ì ëŹíêž°ë§ í멎 ë©ëë€:
+
+```py
+>>> trainer = Trainer(
+... model,
+... args,
+... train_dataset=train_dataset,
+... eval_dataset=val_dataset,
+... tokenizer=image_processor,
+... compute_metrics=compute_metrics,
+... data_collator=collate_fn,
+... )
+```
+
+ë°ìŽí°ë„Œ ìŽëŻž ìČ늏íëë°ë ë¶ê”Źíêł `image_processor`넌 í íŹëìŽì ìžìëĄ ëŁì ìŽì ë JSONìŒëĄ ì ì„ëë ìŽëŻžì§ íëĄìžì ê”Źì± íìŒìŽ Hubì ì ì„ìì ì
ëĄëëëëĄ íêž° ìíšì
ëë€.
+
+`train` ë©ìë넌 ížì¶íìŹ ëȘšëžì ëŻžìž ìĄ°ì íìžì:
+
+```py
+>>> train_results = trainer.train()
+```
+
+íì”ìŽ ìëŁë멎, ëȘšëžì [`~transformers.Trainer.push_to_hub`] ë©ìë넌 ìŹì©íìŹ íëžì êł”ì íìŹ ëê”Źë ëȘšëžì ìŹì©í ì ìëëĄ í©ëë€:
+```py
+>>> trainer.push_to_hub()
+```
+
+## ì¶ëĄ íêž°[[inference]]
+
+ìąì”ëë€. ìŽì ëŻžìž ìĄ°ì ë ëȘšëžì ì¶ëĄ íë ë° ìŹì©í ì ìì”ëë€.
+
+ì¶ëĄ ì ìŹì©í ììì ë¶ëŹì€ìžì:
+```py
+>>> sample_test_video = next(iter(test_dataset))
+```
+
+
+
+
+
+ëŻžìž ìĄ°ì ë ëȘšëžì ì¶ëĄ ì ìŹì©íë ê°ì„ ê°ëší ë°©ëČì [`pipeline`](https://huggingface.co/docs/transformers/main/en/main_classes/pipelines#transformers.VideoClassificationPipeline)ìì ëȘšëžì ìŹì©íë êČì
ëë€. ëȘšëžëĄ ìì ë¶ë„넌 íêž° ìíŽ `pipeline`ì ìžì€íŽì€ííêł ììì ì ëŹíìžì:
+
+```py
+>>> from transformers import pipeline
+
+>>> video_cls = pipeline(model="my_awesome_video_cls_model")
+>>> video_cls("https://huggingface.co/datasets/sayakpaul/ucf101-subset/resolve/main/v_BasketballDunk_g14_c06.avi")
+[{'score': 0.9272987842559814, 'label': 'BasketballDunk'},
+ {'score': 0.017777055501937866, 'label': 'BabyCrawling'},
+ {'score': 0.01663011871278286, 'label': 'BalanceBeam'},
+ {'score': 0.009560945443809032, 'label': 'BandMarching'},
+ {'score': 0.0068979403004050255, 'label': 'BaseballPitch'}]
+```
+
+ë§ìœ ìíë€ë©Ž ìëìŒëĄ `pipeline`ì êČ°êłŒë„Œ ìŹíí ì ìì”ëë€:
+
+
+```py
+>>> def run_inference(model, video):
+... # (num_frames, num_channels, height, width)
+... perumuted_sample_test_video = video.permute(1, 0, 2, 3)
+... inputs = {
+... "pixel_values": perumuted_sample_test_video.unsqueeze(0),
+... "labels": torch.tensor(
+... [sample_test_video["label"]]
+... ), # this can be skipped if you don't have labels available.
+... }
+
+... device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
+... inputs = {k: v.to(device) for k, v in inputs.items()}
+... model = model.to(device)
+
+... # forward pass
+... with torch.no_grad():
+... outputs = model(**inputs)
+... logits = outputs.logits
+
+... return logits
+```
+
+ëȘšëžì ì
ë „ê°ì ëŁêł `logits`ì ë°íë°ìŒìžì:
+
+```
+>>> logits = run_inference(trained_model, sample_test_video["video"])
+```
+
+`logits`ì ëìœë©í멎, ì°ëŠŹë ë€ì êČ°êłŒë„Œ ì»ì ì ìì”ëë€:
+
+```py
+>>> predicted_class_idx = logits.argmax(-1).item()
+>>> print("Predicted class:", model.config.id2label[predicted_class_idx])
+# Predicted class: BasketballDunk
+```
diff --git a/docs/source/ko/tasks/zero_shot_image_classification.md b/docs/source/ko/tasks/zero_shot_image_classification.md
new file mode 100644
index 000000000000..f824de93b865
--- /dev/null
+++ b/docs/source/ko/tasks/zero_shot_image_classification.md
@@ -0,0 +1,144 @@
+
+
+# ì ëĄì·(zero-shot) ìŽëŻžì§ ë¶ë„[[zeroshot-image-classification]]
+
+[[open-in-colab]]
+
+ì ëĄì·(zero-shot) ìŽëŻžì§ ë¶ë„ë íčì ìčŽí
êł ëŠŹì ììê° íŹíšë ë°ìŽí°ë„Œ íì”ëì§ ìì ëȘšëžì ìŹì©íŽ ìŽëŻžì§ ë¶ë„넌 ìííë ìì
ì
ëë€.
+
+ìŒë°ì ìŒëĄ ìŽëŻžì§ ë¶ë„넌 ìíŽìë ë ìŽëžìŽ ëŹëа íčì ìŽëŻžì§ ë°ìŽí°ëĄ ëȘšëž íì”ìŽ íìíë©°, ìŽ ëȘšëžì íčì ìŽëŻžì§ì íčì§ì ë ìŽëžì "ë§€í"íë ë°©ëČì íì”í©ëë€.
+ìëĄìŽ ë ìŽëžìŽ ìë ë¶ë„ ìì
ì ìŽëŹí ëȘšëžì ìŹì©íŽìŒ íë êČœì°ìë, ëȘšëžì "ìŹëłŽì "íêž° ìíŽ ëŻžìž ìĄ°ì ìŽ íìí©ëë€.
+
+ìŽì ëìĄ°ì ìŒëĄ, ì ëĄì· ëë ê°ë°©í ìŽí(open vocabulary) ìŽëŻžì§ ë¶ë„ ëȘšëžì ìŒë°ì ìŒëĄ ëê·ëȘš ìŽëŻžì§ ë°ìŽí°ì íŽëč ì€ëȘ
ì ëíŽ íì”ë ë©í°ëȘšëŹ(multimodal) ëȘšëžì
ëë€.
+ìŽëŹí ëȘšëžì ì ëĄì· ìŽëŻžì§ ë¶ë„넌 íŹíší ë§ì ë€ìŽì€ížëŠŒ ìì
ì ìŹì©í ì ìë ì ë Źë(aligned) ëčì ìžìŽ ííì íì”í©ëë€.
+
+ìŽë ìŽëŻžì§ ë¶ë„ì ëí ëłŽë€ ì ì°í ì ê·Œ ë°©ììŒëĄ, ì¶ê° íì” ë°ìŽí° ììŽ ìëĄìŽ ë ìŽëžìŽë íì”íì§ ëȘ»í ìčŽí
êł ëŠŹì ëíŽ ëȘšëžì ìŒë°íí ì ìì”ëë€.
+ëí, ìŹì©ìê° ëì ê°ìČŽì ëí ìì íìì í
ì€íž ì€ëȘ
ìŒëĄ ìŽëŻžì§ë„Œ êČìí ì ìì”ëë€.
+
+ìŽëČ ê°ìŽëìì ë°°ìž ëŽì©ì ë€ìêłŒ ê°ì”ëë€:
+
+* ì ëĄì· ìŽëŻžì§ ë¶ë„ íìŽíëŒìž ë§ë€êž°
+* ì§ì ì ëĄì· ìŽëŻžì§ ë¶ë„ ëȘšëž ì¶ëĄ ì€ííêž°
+
+ììíêž° ì ì íìí ëŒìŽëžëŹëŠŹê° ëȘšë ì€ìčëìŽ ìëì§ íìžíìžì:
+
+```bash
+pip install -q transformers
+```
+
+## ì ëĄì·(zero-shot) ìŽëŻžì§ ë¶ë„ íìŽíëŒìž[[zeroshot-image-classification-pipeline]]
+
+[`pipeline`]ì íì©í멎 ê°ì„ ê°ëšíêČ ì ëĄì· ìŽëŻžì§ ë¶ë„넌 ì§ìíë ëȘšëžëĄ ì¶ëĄ íŽëłŒ ì ìì”ëë€.
+[Hugging Face Hubì ì
ëĄëë ìČŽíŹíŹìžíž](https://huggingface.co/models?pipeline_tag=zero-shot-image-classification&sort=downloads)ìì íìŽíëŒìžì ìžì€íŽì€íí©ëë€.
+
+```python
+>>> from transformers import pipeline
+
+>>> checkpoint = "openai/clip-vit-large-patch14"
+>>> detector = pipeline(model=checkpoint, task="zero-shot-image-classification")
+```
+
+ë€ììŒëĄ, ë¶ë„íêł ì¶ì ìŽëŻžì§ë„Œ ì ííìžì.
+
+```py
+>>> from PIL import Image
+>>> import requests
+
+>>> url = "https://unsplash.com/photos/g8oS8-82DxI/download?ixid=MnwxMjA3fDB8MXx0b3BpY3x8SnBnNktpZGwtSGt8fHx8fDJ8fDE2NzgxMDYwODc&force=true&w=640"
+>>> image = Image.open(requests.get(url, stream=True).raw)
+
+>>> image
+```
+
+
+
+
+
+ìŽëŻžì§ì íŽëč ìŽëŻžì§ì í볎 ë ìŽëžìž `candidate_labels`넌 íìŽíëŒìžìŒëĄ ì ëŹí©ëë€.
+ìŹêž°ìë ìŽëŻžì§ë„Œ ì§ì ì ëŹíì§ë§, 컎íší°ì ì ì„ë ìŽëŻžì§ì êČœëĄë urlëĄ ì ëŹí ìë ìì”ëë€.
+`candidate_labels`ë ìŽ ìììČëŒ ê°ëší ëšìŽìŒ ìë ìêł ìą ë ì€ëȘ
ì ìž ëšìŽìŒ ìë ìì”ëë€.
+
+```py
+>>> predictions = classifier(image, candidate_labels=["fox", "bear", "seagull", "owl"])
+>>> predictions
+[{'score': 0.9996670484542847, 'label': 'owl'},
+ {'score': 0.000199399160919711, 'label': 'seagull'},
+ {'score': 7.392891711788252e-05, 'label': 'fox'},
+ {'score': 5.96074532950297e-05, 'label': 'bear'}]
+```
+
+## ì§ì ì ëĄì·(zero-shot) ìŽëŻžì§ ë¶ë„íêž°[[zeroshot-image-classification-by-hand]]
+
+ìŽì ì ëĄì· ìŽëŻžì§ ë¶ë„ íìŽíëŒìž ìŹì© ë°©ëČì ìŽíŽëłŽììŒë, ì€ííë ë°©ëČì ìŽíŽëłŽêČ ì”ëë€.
+
+[Hugging Face Hubì ì
ëĄëë ìČŽíŹíŹìžíž](https://huggingface.co/models?pipeline_tag=zero-shot-image-classification&sort=downloads)ìì ëȘšëžêłŒ íëĄìžì넌 ê°ì žì€ë êČìŒëĄ ììí©ëë€.
+ìŹêž°ìë ìŽì êłŒ ëìŒí ìČŽíŹíŹìžížë„Œ ìŹì©íêČ ì”ëë€:
+
+```py
+>>> from transformers import AutoProcessor, AutoModelForZeroShotImageClassification
+
+>>> model = AutoModelForZeroShotImageClassification.from_pretrained(checkpoint)
+>>> processor = AutoProcessor.from_pretrained(checkpoint)
+```
+
+ë€ë„ž ìŽëŻžì§ë„Œ ìŹì©íŽ ëłŽêČ ì”ëë€.
+
+```py
+>>> from PIL import Image
+>>> import requests
+
+>>> url = "https://unsplash.com/photos/xBRQfR2bqNI/download?ixid=MnwxMjA3fDB8MXxhbGx8fHx8fHx8fHwxNjc4Mzg4ODEx&force=true&w=640"
+>>> image = Image.open(requests.get(url, stream=True).raw)
+
+>>> image
+```
+
+
+
+
+
+íëĄìžì넌 ìŹì©íŽ ëȘšëžì ì
ë „ì ì€ëčí©ëë€.
+íëĄìžìë ëȘšëžì ì
ë „ìŒëĄ ìŹì©íêž° ìíŽ ìŽëŻžì§ íŹêž°ë„Œ ëłííêł ì ê·ííë ìŽëŻžì§ íëĄìžìì í
ì€íž ì
ë „ì ìČ늏íë í íŹëìŽì ëĄ ê”Źì±ë©ëë€.
+
+```py
+>>> candidate_labels = ["tree", "car", "bike", "cat"]
+>>> inputs = processor(images=image, text=candidate_labels, return_tensors="pt", padding=True)
+```
+
+ëȘšëžì ì
ë „ì ì ëŹíêł , êČ°êłŒë„Œ íìČ늏í©ëë€:
+
+```py
+>>> import torch
+
+>>> with torch.no_grad():
+... outputs = model(**inputs)
+
+>>> logits = outputs.logits_per_image[0]
+>>> probs = logits.softmax(dim=-1).numpy()
+>>> scores = probs.tolist()
+
+>>> result = [
+... {"score": score, "label": candidate_label}
+... for score, candidate_label in sorted(zip(probs, candidate_labels), key=lambda x: -x[0])
+... ]
+
+>>> result
+[{'score': 0.998572, 'label': 'car'},
+ {'score': 0.0010570387, 'label': 'bike'},
+ {'score': 0.0003393686, 'label': 'tree'},
+ {'score': 3.1572064e-05, 'label': 'cat'}]
+```
\ No newline at end of file
diff --git a/docs/source/ko/tasks/zero_shot_image_classification.mdx b/docs/source/ko/tasks/zero_shot_image_classification.mdx
deleted file mode 100644
index 199c089007b2..000000000000
--- a/docs/source/ko/tasks/zero_shot_image_classification.mdx
+++ /dev/null
@@ -1,140 +0,0 @@
-
-
-# ì ëĄì·(zero-shot) ìŽëŻžì§ ë¶ë„[[zeroshot-image-classification]]
-
-[[open-in-colab]]
-
-ì ëĄì·(zero-shot) ìŽëŻžì§ ë¶ë„ë íčì ìčŽí
êł ëŠŹì ììê° íŹíšë ë°ìŽí°ë„Œ íì”ëì§ ìì ëȘšëžì ìŹì©íŽ ìŽëŻžì§ ë¶ë„넌 ìííë ìì
ì
ëë€.
-
-ìŒë°ì ìŒëĄ ìŽëŻžì§ ë¶ë„넌 ìíŽìë ë ìŽëžìŽ ëŹëа íčì ìŽëŻžì§ ë°ìŽí°ëĄ ëȘšëž íì”ìŽ íìíë©°, ìŽ ëȘšëžì íčì ìŽëŻžì§ì íčì§ì ë ìŽëžì "ë§€í"íë ë°©ëČì íì”í©ëë€.
-ìëĄìŽ ë ìŽëžìŽ ìë ë¶ë„ ìì
ì ìŽëŹí ëȘšëžì ìŹì©íŽìŒ íë êČœì°ìë, ëȘšëžì "ìŹëłŽì "íêž° ìíŽ ëŻžìž ìĄ°ì ìŽ íìí©ëë€.
-
-ìŽì ëìĄ°ì ìŒëĄ, ì ëĄì· ëë ê°ë°©í ìŽí(open vocabulary) ìŽëŻžì§ ë¶ë„ ëȘšëžì ìŒë°ì ìŒëĄ ëê·ëȘš ìŽëŻžì§ ë°ìŽí°ì íŽëč ì€ëȘ
ì ëíŽ íì”ë ë©í°ëȘšëŹ(multimodal) ëȘšëžì
ëë€.
-ìŽëŹí ëȘšëžì ì ëĄì· ìŽëŻžì§ ë¶ë„넌 íŹíší ë§ì ë€ìŽì€ížëŠŒ ìì
ì ìŹì©í ì ìë ì ë Źë(aligned) ëčì ìžìŽ ííì íì”í©ëë€.
-
-ìŽë ìŽëŻžì§ ë¶ë„ì ëí ëłŽë€ ì ì°í ì ê·Œ ë°©ììŒëĄ, ì¶ê° íì” ë°ìŽí° ììŽ ìëĄìŽ ë ìŽëžìŽë íì”íì§ ëȘ»í ìčŽí
êł ëŠŹì ëíŽ ëȘšëžì ìŒë°íí ì ìì”ëë€.
-ëí, ìŹì©ìê° ëì ê°ìČŽì ëí ìì íìì í
ì€íž ì€ëȘ
ìŒëĄ ìŽëŻžì§ë„Œ êČìí ì ìì”ëë€.
-
-ìŽëČ ê°ìŽëìì ë°°ìž ëŽì©ì ë€ìêłŒ ê°ì”ëë€:
-
-* ì ëĄì· ìŽëŻžì§ ë¶ë„ íìŽíëŒìž ë§ë€êž°
-* ì§ì ì ëĄì· ìŽëŻžì§ ë¶ë„ ëȘšëž ì¶ëĄ ì€ííêž°
-
-ììíêž° ì ì íìí ëŒìŽëžëŹëŠŹê° ëȘšë ì€ìčëìŽ ìëì§ íìžíìžì:
-
-```bash
-pip install -q transformers
-```
-
-## ì ëĄì·(zero-shot) ìŽëŻžì§ ë¶ë„ íìŽíëŒìž[[zeroshot-image-classification-pipeline]]
-
-[`pipeline`]ì íì©í멎 ê°ì„ ê°ëšíêČ ì ëĄì· ìŽëŻžì§ ë¶ë„넌 ì§ìíë ëȘšëžëĄ ì¶ëĄ íŽëłŒ ì ìì”ëë€.
-[Hugging Face Hubì ì
ëĄëë ìČŽíŹíŹìžíž](https://huggingface.co/models?pipeline_tag=zero-shot-image-classification&sort=downloads)ìì íìŽíëŒìžì ìžì€íŽì€íí©ëë€.
-
-```python
->>> from transformers import pipeline
-
->>> checkpoint = "openai/clip-vit-large-patch14"
->>> detector = pipeline(model=checkpoint, task="zero-shot-image-classification")
-```
-
-ë€ììŒëĄ, ë¶ë„íêł ì¶ì ìŽëŻžì§ë„Œ ì ííìžì.
-
-```py
->>> from PIL import Image
->>> import requests
-
->>> url = "https://unsplash.com/photos/g8oS8-82DxI/download?ixid=MnwxMjA3fDB8MXx0b3BpY3x8SnBnNktpZGwtSGt8fHx8fDJ8fDE2NzgxMDYwODc&force=true&w=640"
->>> image = Image.open(requests.get(url, stream=True).raw)
-
->>> image
-```
-
-
-
-
-
-ìŽëŻžì§ì íŽëč ìŽëŻžì§ì í볎 ë ìŽëžìž `candidate_labels`넌 íìŽíëŒìžìŒëĄ ì ëŹí©ëë€.
-ìŹêž°ìë ìŽëŻžì§ë„Œ ì§ì ì ëŹíì§ë§, 컎íší°ì ì ì„ë ìŽëŻžì§ì êČœëĄë urlëĄ ì ëŹí ìë ìì”ëë€.
-`candidate_labels`ë ìŽ ìììČëŒ ê°ëší ëšìŽìŒ ìë ìêł ìą ë ì€ëȘ
ì ìž ëšìŽìŒ ìë ìì”ëë€.
-
-```py
->>> predictions = classifier(image, candidate_labels=["fox", "bear", "seagull", "owl"])
->>> predictions
-[{'score': 0.9996670484542847, 'label': 'owl'},
- {'score': 0.000199399160919711, 'label': 'seagull'},
- {'score': 7.392891711788252e-05, 'label': 'fox'},
- {'score': 5.96074532950297e-05, 'label': 'bear'}]
-```
-
-## ì§ì ì ëĄì·(zero-shot) ìŽëŻžì§ ë¶ë„íêž°[[zeroshot-image-classification-by-hand]]
-
-ìŽì ì ëĄì· ìŽëŻžì§ ë¶ë„ íìŽíëŒìž ìŹì© ë°©ëČì ìŽíŽëłŽììŒë, ì€ííë ë°©ëČì ìŽíŽëłŽêČ ì”ëë€.
-
-[Hugging Face Hubì ì
ëĄëë ìČŽíŹíŹìžíž](https://huggingface.co/models?pipeline_tag=zero-shot-image-classification&sort=downloads)ìì ëȘšëžêłŒ íëĄìžì넌 ê°ì žì€ë êČìŒëĄ ììí©ëë€.
-ìŹêž°ìë ìŽì êłŒ ëìŒí ìČŽíŹíŹìžížë„Œ ìŹì©íêČ ì”ëë€:
-
-```py
->>> from transformers import AutoProcessor, AutoModelForZeroShotImageClassification
-
->>> model = AutoModelForZeroShotImageClassification.from_pretrained(checkpoint)
->>> processor = AutoProcessor.from_pretrained(checkpoint)
-```
-
-ë€ë„ž ìŽëŻžì§ë„Œ ìŹì©íŽ ëłŽêČ ì”ëë€.
-
-```py
->>> from PIL import Image
->>> import requests
-
->>> url = "https://unsplash.com/photos/xBRQfR2bqNI/download?ixid=MnwxMjA3fDB8MXxhbGx8fHx8fHx8fHwxNjc4Mzg4ODEx&force=true&w=640"
->>> image = Image.open(requests.get(url, stream=True).raw)
-
->>> image
-```
-
-
-
-
-
-íëĄìžì넌 ìŹì©íŽ ëȘšëžì ì
ë „ì ì€ëčí©ëë€.
-íëĄìžìë ëȘšëžì ì
ë „ìŒëĄ ìŹì©íêž° ìíŽ ìŽëŻžì§ íŹêž°ë„Œ ëłííêł ì ê·ííë ìŽëŻžì§ íëĄìžìì í
ì€íž ì
ë „ì ìČ늏íë í íŹëìŽì ëĄ ê”Źì±ë©ëë€.
-
-```py
->>> candidate_labels = ["tree", "car", "bike", "cat"]
->>> inputs = processor(images=image, text=candidate_labels, return_tensors="pt", padding=True)
-```
-
-ëȘšëžì ì
ë „ì ì ëŹíêł , êČ°êłŒë„Œ íìČ늏í©ëë€:
-
-```py
->>> import torch
-
->>> with torch.no_grad():
-... outputs = model(**inputs)
-
->>> logits = outputs.logits_per_image[0]
->>> probs = logits.softmax(dim=-1).numpy()
->>> scores = probs.tolist()
-
->>> result = [
-... {"score": score, "label": candidate_label}
-... for score, candidate_label in sorted(zip(probs, candidate_labels), key=lambda x: -x[0])
-... ]
-
->>> result
-[{'score': 0.998572, 'label': 'car'},
- {'score': 0.0010570387, 'label': 'bike'},
- {'score': 0.0003393686, 'label': 'tree'},
- {'score': 3.1572064e-05, 'label': 'cat'}]
-```
\ No newline at end of file
diff --git a/docs/source/ko/tasks/zero_shot_object_detection.md b/docs/source/ko/tasks/zero_shot_object_detection.md
new file mode 100644
index 000000000000..8e9b52e8c7a2
--- /dev/null
+++ b/docs/source/ko/tasks/zero_shot_object_detection.md
@@ -0,0 +1,307 @@
+
+
+# ì ëĄì·(zero-shot) ê°ìČŽ íì§[[zeroshot-object-detection]]
+
+[[open-in-colab]]
+
+ìŒë°ì ìŒëĄ [ê°ìČŽ íì§](object_detection)ì ìŹì©ëë ëȘšëžì íì”íêž° ìíŽìë ë ìŽëžìŽ ì§ì ë ìŽëŻžì§ ë°ìŽí° ìžížê° íìí©ëë€.
+ê·žëŠŹêł íì” ë°ìŽí°ì ìĄŽìŹíë íŽëì€(ë ìŽëž)ë§ íì§í ì ìë€ë íêłì ìŽ ìì”ëë€.
+
+ë€ë„ž ë°©ìì ìŹì©íë [OWL-ViT](../model_doc/owlvit) ëȘšëžëĄ ì ëĄì· ê°ìČŽ íì§ê° ê°ë„í©ëë€.
+OWL-ViTë ê°ë°©í ìŽí(open-vocabulary) ê°ìČŽ íì§êž°ì
ëë€.
+ìŠ, ë ìŽëžìŽ ì§ì ë ë°ìŽí° ìžížì ëŻžìž ìĄ°ì íì§ ìêł ìì í
ì€íž ìżŒëŠŹë„Œ êž°ë°ìŒëĄ ìŽëŻžì§ìì ê°ìČŽë„Œ íì§í ì ìì”ëë€.
+
+OWL-ViT ëȘšëžì ë©í° ëȘšëŹ ííì íì©íŽ ê°ë°©í ìŽí íì§(open-vocabulary detection)넌 ìíí©ëë€.
+[CLIP](../model_doc/clip) ëȘšëžì êČœëí(lightweight)ë ê°ìČŽ ë¶ë„ì ì§ìí(localization) í€ë넌 êȰí©í©ëë€.
+ê°ë°©í ìŽí íì§ë CLIPì í
ì€íž ìžìœëëĄ free-text ìżŒëŠŹë„Œ ìëČ ë©íêł , ê°ìČŽ ë¶ë„ì ì§ìí í€ëì ì
ë „ìŒëĄ ìŹì©í©ëë€.
+ìŽëŻžì§ì íŽëč í
ì€íž ì€ëȘ
ì ì°êȰí멎 ViTê° ìŽëŻžì§ íšìč(image patches)넌 ì
ë „ìŒëĄ ìČ늏í©ëë€.
+OWL-ViT ëȘšëžì ì ìë€ì CLIP ëȘšëžì ìČìë¶í° íì”(scratch learning)í íì, bipartite matching loss넌 ìŹì©íìŹ íì€ ê°ìČŽ ìžì ë°ìŽí°ì
ìŒëĄ OWL-ViT ëȘšëžì ëŻžìž ìĄ°ì íì”ëë€.
+
+ìŽ ì ê·Œ ë°©ìì ìŹì©í멎 ëȘšëžì ë ìŽëžìŽ ì§ì ë ë°ìŽí° ìžížì ëí ìŹì íì” ììŽë í
ì€íž ì€ëȘ
ì êž°ë°ìŒëĄ ê°ìČŽë„Œ íì§í ì ìì”ëë€.
+
+ìŽëČ ê°ìŽëììë OWL-ViT ëȘšëžì ìŹì©ëČì ë€ëٰ êČì
ëë€:
+- í
ì€íž í륏ííž êž°ë° ê°ìČŽ íì§
+- ìŒêŽ ê°ìČŽ íì§
+- ìŽëŻžì§ ê°ìŽë ê°ìČŽ íì§
+
+ììíêž° ì ì íìí ëŒìŽëžëŹëŠŹê° ëȘšë ì€ìčëìŽ ìëì§ íìžíìžì:
+```bash
+pip install -q transformers
+```
+
+## ì ëĄì·(zero-shot) ê°ìČŽ íì§ íìŽíëŒìž[[zeroshot-object-detection-pipeline]]
+
+[`pipeline`]ì íì©í멎 ê°ì„ ê°ëšíêČ OWL-ViT ëȘšëžì ì¶ëĄ íŽëłŒ ì ìì”ëë€.
+[Hugging Face Hubì ì
ëĄëë ìČŽíŹíŹìžíž](https://huggingface.co/models?pipeline_tag=zero-shot-image-classification&sort=downloads)ìì ì ëĄì·(zero-shot) ê°ìČŽ íì§ì© íìŽíëŒìžì ìžì€íŽì€íí©ëë€:
+
+```python
+>>> from transformers import pipeline
+
+>>> checkpoint = "google/owlvit-base-patch32"
+>>> detector = pipeline(model=checkpoint, task="zero-shot-object-detection")
+```
+
+ë€ììŒëĄ, ê°ìČŽë„Œ íì§íêł ì¶ì ìŽëŻžì§ë„Œ ì ííìžì.
+ìŹêž°ìë [NASA](https://www.nasa.gov/multimedia/imagegallery/index.html) Great Images ë°ìŽí° ìžížì ìŒë¶ìž ì°ìŁŒëčíìŹ ììŒëа ìœëаì€(Eileen Collins) ìŹì§ì ìŹì©íêČ ì”ëë€.
+
+```py
+>>> import skimage
+>>> import numpy as np
+>>> from PIL import Image
+
+>>> image = skimage.data.astronaut()
+>>> image = Image.fromarray(np.uint8(image)).convert("RGB")
+
+>>> image
+```
+
+
+
+
+
+ìŽëŻžì§ì íŽëč ìŽëŻžì§ì í볎 ë ìŽëžì íìŽíëŒìžìŒëĄ ì ëŹí©ëë€.
+ìŹêž°ìë ìŽëŻžì§ë„Œ ì§ì ì ëŹíì§ë§, 컎íší°ì ì ì„ë ìŽëŻžì§ì êČœëĄë urlëĄ ì ëŹí ìë ìì”ëë€.
+candidate_labelsë ìŽ ìììČëŒ ê°ëší ëšìŽìŒ ìë ìêł ìą ë ì€ëȘ
ì ìž ëšìŽìŒ ìë ìì”ëë€.
+ëí, ìŽëŻžì§ë„Œ êČì(query)íë €ë ëȘšë íëȘ©ì ëí í
ì€íž ì€ëȘ
ë ì ëŹí©ëë€.
+
+```py
+>>> predictions = detector(
+... image,
+... candidate_labels=["human face", "rocket", "nasa badge", "star-spangled banner"],
+... )
+>>> predictions
+[{'score': 0.3571370542049408,
+ 'label': 'human face',
+ 'box': {'xmin': 180, 'ymin': 71, 'xmax': 271, 'ymax': 178}},
+ {'score': 0.28099656105041504,
+ 'label': 'nasa badge',
+ 'box': {'xmin': 129, 'ymin': 348, 'xmax': 206, 'ymax': 427}},
+ {'score': 0.2110239565372467,
+ 'label': 'rocket',
+ 'box': {'xmin': 350, 'ymin': -1, 'xmax': 468, 'ymax': 288}},
+ {'score': 0.13790413737297058,
+ 'label': 'star-spangled banner',
+ 'box': {'xmin': 1, 'ymin': 1, 'xmax': 105, 'ymax': 509}},
+ {'score': 0.11950037628412247,
+ 'label': 'nasa badge',
+ 'box': {'xmin': 277, 'ymin': 338, 'xmax': 327, 'ymax': 380}},
+ {'score': 0.10649408400058746,
+ 'label': 'rocket',
+ 'box': {'xmin': 358, 'ymin': 64, 'xmax': 424, 'ymax': 280}}]
+```
+
+ìŽì ììžĄê°ì ìê°ííŽëŽ
ìë€:
+
+```py
+>>> from PIL import ImageDraw
+
+>>> draw = ImageDraw.Draw(image)
+
+>>> for prediction in predictions:
+... box = prediction["box"]
+... label = prediction["label"]
+... score = prediction["score"]
+
+... xmin, ymin, xmax, ymax = box.values()
+... draw.rectangle((xmin, ymin, xmax, ymax), outline="red", width=1)
+... draw.text((xmin, ymin), f"{label}: {round(score,2)}", fill="white")
+
+>>> image
+```
+
+
+
+
+
+## í
ì€íž í륏ííž êž°ë° ê°ìČŽ íì§[[textprompted-zeroshot-object-detection-by-hand]]
+
+ì ëĄì· ê°ìČŽ íì§ íìŽíëŒìž ìŹì©ëČì ëíŽ ìŽíŽëłŽììŒë, ìŽì ëìŒí êČ°êłŒë„Œ ëł”ì íŽëłŽêČ ì”ëë€.
+
+[Hugging Face Hubì ì
ëĄëë ìČŽíŹíŹìžíž](https://huggingface.co/models?other=owlvit)ìì êŽë š ëȘšëžêłŒ íëĄìžì넌 ê°ì žì€ë êČìŒëĄ ììí©ëë€.
+ìŹêž°ìë ìŽì êłŒ ëìŒí ìČŽíŹíŹìžížë„Œ ìŹì©íêČ ì”ëë€:
+
+```py
+>>> from transformers import AutoProcessor, AutoModelForZeroShotObjectDetection
+
+>>> model = AutoModelForZeroShotObjectDetection.from_pretrained(checkpoint)
+>>> processor = AutoProcessor.from_pretrained(checkpoint)
+```
+
+ë€ë„ž ìŽëŻžì§ë„Œ ìŹì©íŽ ëłŽêČ ì”ëë€:
+
+```py
+>>> import requests
+
+>>> url = "https://unsplash.com/photos/oj0zeY2Ltk4/download?ixid=MnwxMjA3fDB8MXxzZWFyY2h8MTR8fHBpY25pY3xlbnwwfHx8fDE2Nzc0OTE1NDk&force=true&w=640"
+>>> im = Image.open(requests.get(url, stream=True).raw)
+>>> im
+```
+
+
+
+
+
+íëĄìžì넌 ìŹì©íŽ ëȘšëžì ì
ë „ì ì€ëčí©ëë€.
+íëĄìžìë ëȘšëžì ì
ë „ìŒëĄ ìŹì©íêž° ìíŽ ìŽëŻžì§ íŹêž°ë„Œ ëłííêł ì ê·ííë ìŽëŻžì§ íëĄìžìì í
ì€íž ì
ë „ì ìČ늏íë [`CLIPTokenizer`]ëĄ ê”Źì±ë©ëë€.
+
+```py
+>>> text_queries = ["hat", "book", "sunglasses", "camera"]
+>>> inputs = processor(text=text_queries, images=im, return_tensors="pt")
+```
+
+ëȘšëžì ì
ë „ì ì ëŹíêł êČ°êłŒë„Œ íìČ늏 ë° ìê°íí©ëë€.
+ìŽëŻžì§ íëĄìžìê° ëȘšëžì ìŽëŻžì§ë„Œ ì
ë „íêž° ì ì ìŽëŻžì§ íŹêž°ë„Œ ìĄ°ì íêž° ë돞ì, [`~OwlViTImageProcessor.post_process_object_detection`] ë©ìë넌 ìŹì©íŽ
+ììžĄê°ì ë°ìŽë© ë°ì€(bounding box)ê° ìëłž ìŽëŻžì§ì ìąíì ìëì ìŒëĄ ëìŒíì§ íìžíŽìŒ í©ëë€.
+
+```py
+>>> import torch
+
+>>> with torch.no_grad():
+... outputs = model(**inputs)
+... target_sizes = torch.tensor([im.size[::-1]])
+... results = processor.post_process_object_detection(outputs, threshold=0.1, target_sizes=target_sizes)[0]
+
+>>> draw = ImageDraw.Draw(im)
+
+>>> scores = results["scores"].tolist()
+>>> labels = results["labels"].tolist()
+>>> boxes = results["boxes"].tolist()
+
+>>> for box, score, label in zip(boxes, scores, labels):
+... xmin, ymin, xmax, ymax = box
+... draw.rectangle((xmin, ymin, xmax, ymax), outline="red", width=1)
+... draw.text((xmin, ymin), f"{text_queries[label]}: {round(score,2)}", fill="white")
+
+>>> im
+```
+
+
+
+
+
+## ìŒêŽ ìČ늏[[batch-processing]]
+
+ìŹëŹ ìŽëŻžì§ì í
ì€íž ìżŒëŠŹë„Œ ì ëŹíìŹ ìŹëŹ ìŽëŻžì§ìì ìëĄ ë€ë„ž(ëë ëìŒí) ê°ìČŽë„Œ êČìí ì ìì”ëë€.
+ìŒêŽ ìČëŠŹë„Œ ìíŽì í
ì€íž ìżŒëŠŹë ìŽì€ 늏ì€ížëĄ, ìŽëŻžì§ë PIL ìŽëŻžì§, PyTorch í
ì, ëë NumPy ë°°ìŽëĄ ìŽëŁšìŽì§ 늏ì€ížëĄ íëĄìžìì ì ëŹíŽìŒ í©ëë€.
+
+```py
+>>> images = [image, im]
+>>> text_queries = [
+... ["human face", "rocket", "nasa badge", "star-spangled banner"],
+... ["hat", "book", "sunglasses", "camera"],
+... ]
+>>> inputs = processor(text=text_queries, images=images, return_tensors="pt")
+```
+
+ìŽì ìë íìČëŠŹë„Œ ìíŽ ëšìŒ ìŽëŻžì§ì íŹêž°ë„Œ í
ìëĄ ì ëŹíì§ë§, ííì ì ëŹí ì ìêł , ìŹëŹ ìŽëŻžì§ë„Œ ìČ늏íë êČœì°ìë ííëĄ ìŽëŁšìŽì§ 늏ì€ížë„Œ ì ëŹí ìë ìì”ëë€.
+ìë ë ìì ì ëí ììžĄì ìì±íêł , ë ëČì§ž ìŽëŻžì§(`image_idx = 1`)넌 ìê°ííŽ ëłŽêČ ì”ëë€.
+
+```py
+>>> with torch.no_grad():
+... outputs = model(**inputs)
+... target_sizes = [x.size[::-1] for x in images]
+... results = processor.post_process_object_detection(outputs, threshold=0.1, target_sizes=target_sizes)
+
+>>> image_idx = 1
+>>> draw = ImageDraw.Draw(images[image_idx])
+
+>>> scores = results[image_idx]["scores"].tolist()
+>>> labels = results[image_idx]["labels"].tolist()
+>>> boxes = results[image_idx]["boxes"].tolist()
+
+>>> for box, score, label in zip(boxes, scores, labels):
+... xmin, ymin, xmax, ymax = box
+... draw.rectangle((xmin, ymin, xmax, ymax), outline="red", width=1)
+... draw.text((xmin, ymin), f"{text_queries[image_idx][label]}: {round(score,2)}", fill="white")
+
+>>> images[image_idx]
+```
+
+
+
+
+
+## ìŽëŻžì§ ê°ìŽë ê°ìČŽ íì§[[imageguided-object-detection]]
+
+í
ì€íž ìżŒëŠŹë„Œ ìŽì©í ì ëĄì· ê°ìČŽ íì§ ìžìë OWL-ViT ëȘšëžì ìŽëŻžì§ ê°ìŽë ê°ìČŽ íì§ êž°ë„ì ì êł”í©ëë€.
+ìŽëŻžì§ë„Œ ìżŒëŠŹëĄ ìŹì©íŽ ëì ìŽëŻžì§ìì ì ìŹí ê°ìČŽë„Œ ì°Ÿì ì ìë€ë ì믞ì
ëë€.
+í
ì€íž ìżŒëŠŹì ëŹëŠŹ íëì ìì ìŽëŻžì§ììë§ ê°ë„í©ëë€.
+
+ìíì êł ììŽ ë ë§ëŠŹê° ìë ìŽëŻžì§ë„Œ ëì ìŽëŻžì§(target image)ëĄ, êł ììŽ í ë§ëŠŹê° ìë ìŽëŻžì§ë„Œ ìżŒëŠŹëĄ ìŹì©íŽëłŽêČ ì”ëë€:
+
+```py
+>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+>>> image_target = Image.open(requests.get(url, stream=True).raw)
+
+>>> query_url = "http://images.cocodataset.org/val2017/000000524280.jpg"
+>>> query_image = Image.open(requests.get(query_url, stream=True).raw)
+```
+
+ë€ì ìŽëŻžì§ë„Œ ìŽíŽëłŽêČ ì”ëë€:
+
+```py
+>>> import matplotlib.pyplot as plt
+
+>>> fig, ax = plt.subplots(1, 2)
+>>> ax[0].imshow(image_target)
+>>> ax[1].imshow(query_image)
+```
+
+
+
+
+
+ì ìČ늏 ëšêłìì í
ì€íž ìżŒëŠŹ ëì ì `query_images`넌 ìŹì©í©ëë€:
+
+```py
+>>> inputs = processor(images=image_target, query_images=query_image, return_tensors="pt")
+```
+
+ììžĄì êČœì°, ëȘšëžì ì
ë „ì ì ëŹíë ëì [`~OwlViTForObjectDetection.image_guided_detection`]ì ì ëŹí©ëë€.
+ë ìŽëžìŽ ìë€ë ì ì ì ìží멎 ìŽì êłŒ ëìŒí©ëë€.
+ìŽì êłŒ ëìŒíêČ ìŽëŻžì§ë„Œ ìê°íí©ëë€.
+
+```py
+>>> with torch.no_grad():
+... outputs = model.image_guided_detection(**inputs)
+... target_sizes = torch.tensor([image_target.size[::-1]])
+... results = processor.post_process_image_guided_detection(outputs=outputs, target_sizes=target_sizes)[0]
+
+>>> draw = ImageDraw.Draw(image_target)
+
+>>> scores = results["scores"].tolist()
+>>> boxes = results["boxes"].tolist()
+
+>>> for box, score, label in zip(boxes, scores, labels):
+... xmin, ymin, xmax, ymax = box
+... draw.rectangle((xmin, ymin, xmax, ymax), outline="white", width=4)
+
+>>> image_target
+```
+
+
+
+
+
+OWL-ViT ëȘšëžì ì¶ëĄ íêł ì¶ë€ë©Ž ìë ë°ëȘšë„Œ íìžíìžì:
+
+
diff --git a/docs/source/ko/tasks_explained.md b/docs/source/ko/tasks_explained.md
new file mode 100644
index 000000000000..78c90849bb89
--- /dev/null
+++ b/docs/source/ko/tasks_explained.md
@@ -0,0 +1,295 @@
+
+
+# đ€ TransformersëĄ ìì
ì íŽêȰíë ë°©ëČ[[how-transformers-solve-tasks]]
+
+[đ€ TransformersëĄ í ì ìë ìì
](task_summary)ìì ìì°ìŽ ìČ늏(NLP), ìì± ë° ì€ëì€, 컎íší° ëčì ìì
ë±ì ì€ìí ìì©ì ë°°ì ì”ëë€. ìŽ íìŽì§ììë ëȘšëžìŽ ìŽëŹí ìì
ì ìŽë»êČ íŽêȰíëì§ ììží ìŽíŽëłŽêł ëŽë¶ìì ìŽë€ ìŒìŽ ìŒìŽëëì§ ì€ëȘ
í©ëë€. ìŁŒìŽì§ ìì
ì íŽêȰíë ë§ì ë°©ëČìŽ ììŒë©°, ìŒë¶ ëȘšëžì íčì êž°ì ì ê”Źííê±°ë ìŹì§ìŽ ìëĄìŽ ë°©ììŒëĄ ìì
ì ì ê·Œí ìë ìì§ë§, Transformer ëȘšëžì êČœì° ìŒë°ì ìž ììŽëìŽë ëìŒí©ëë€. ì ì°í ìí€í
ìČ ëë¶ì ëë¶ë¶ì ëȘšëžì ìžìœë, ëìœë ëë ìžìœë-ëìœë ê”ŹìĄ°ì ëłíì
ëë€. Transformer ëȘšëžëżë§ ìëëŒ ì°ëŠŹì ëŒìŽëžëŹëŠŹìë ì€ëë 컎íší° ëčì ìì
ì ìŹì©ëë ëȘ ê°ì§ í©ì±êł± ì êČœë§(CNNs)ë ìì”ëë€. ëí, ì°ëŠŹë íë CNNì ìë ë°©ìì ëíŽ ì€ëȘ
í êČì
ëë€.
+
+ìì
ìŽ ìŽë»êČ íŽêȰëëì§ ì€ëȘ
íêž° ìíŽ, ì ì©í ììžĄì ì¶ë „íêł ì ëȘšëž ëŽë¶ìì ìŽë€ ìŒìŽ ìŒìŽëëì§ ìŽíŽëŽ
ëë€.
+
+- ì€ëì€ ë¶ë„ ë° ìë ìì± ìžì(ASR)ì ìí [Wav2Vec2](model_doc/wav2vec2)
+- ìŽëŻžì§ ë¶ë„넌 ìí [Vision Transformer (ViT)](model_doc/vit) ë° [ConvNeXT](model_doc/convnext)
+- ê°ìČŽ íì§ë„Œ ìí [DETR](model_doc/detr)
+- ìŽëŻžì§ ë¶í ì ìí [Mask2Former](model_doc/mask2former)
+- êčìŽ ì¶ì ì ìí [GLPN](model_doc/glpn)
+- ìžìœë넌 ìŹì©íë í
ì€íž ë¶ë„, í í° ë¶ë„ ë° ì§ììë”êłŒ ê°ì NLP ìì
ì ìí [BERT](model_doc/bert)
+- ëìœë넌 ìŹì©íë í
ì€íž ìì±êłŒ ê°ì NLP ìì
ì ìí [GPT2](model_doc/gpt2)
+- ìžìœë-ëìœë넌 ìŹì©íë ììœ ë° ëČìêłŒ ê°ì NLP ìì
ì ìí [BART](model_doc/bart)
+
+
+
+ë ëìê°êž° ì ì, êž°ìĄŽ Transformer ìí€í
ìČì ëí êž°ëłžì ìž ì§ìì ìì§íë êČìŽ ìąì”ëë€. ìžìœë, ëìœë ë° ìŽí
ì
ì ìë ë°©ìì ì멎 ë€ìí Transformer ëȘšëžìŽ ìŽë»êČ ìëíëì§ ìŽíŽíë ë° ëììŽ ë©ëë€. ìì ëšêłê±°ë ëł”ì”ìŽ íìí êČœì°, ë ë§ì ì ëłŽë„Œ ìíŽ [ìœì€](https://huggingface.co/course/chapter1/4?fw=pt)넌 íìžíìžì!
+
+
+
+## ìì± ë° ì€ëì€[[speech-and-audio]]
+
+[Wav2Vec2](model_doc/wav2vec2)ë ë ìŽëžìŽ ì§ì ëì§ ìì ìì± ë°ìŽí°ì ëíŽ ìŹì íë šë ëȘšëžëĄ, ì€ëì€ ë¶ë„ ë° ìë ìì± ìžìì ìíŽ ë ìŽëžìŽ ì§ì ë ë°ìŽí°ëĄ ëŻžìž ìĄ°ì í©ëë€.
+
+
+
+
+
+ìŽ ëȘšëžìë 4ê°ì§ ìŁŒì ê”Źì± ììê° ìì”ëë€:
+
+1. *íčì§ ìžìœë(feature encoder)*ë ìì ì€ëì€ íí(raw audio waveform)ì ê°ì žìì ì ëĄ íê· ë° ëšì ë¶ì°ìŒëĄ íì€ííêł , ê°ê° 20ms êžžìŽì íčì§ ëČĄí°ì ìíì€ëĄ ëłíí©ëë€.
+
+2. ì€ëì€ ííì ëłžì§ì ìŒëĄ ì°ìì ìŽêž° ë돞ì, í
ì€íž ìíì€ë„Œ ëšìŽëĄ ëëë êČêłŒ ê°ìŽ ë¶í í ì ìì”ëë€. ê·žëì *ììí ëȘšë(quantization module)*ëĄ ì ëŹëë íčì§ ëČĄí°ë ìŽì°í ìì± ëšì넌 íì”íêž° ìí êČì
ëë€. ìì± ëšìë *ìœëë¶(codebook)*(ìŽíì§ìŽëŒêł ìê°í ì ìì”ëë€)ìŽëŒë ìœëëšìŽ(codewords) ìœë ì
ìì ì íë©ëë€. ìœëë¶ìì ì°ìì ìž ì€ëì€ ì
ë „ì ê°ì„ ì ëíëŽë ëČĄí° ëë ìì± ëšìê° ì íëìŽ ëȘšëžì í”êłŒí©ëë€.
+
+3. íčì§ ëČĄí°ì ì ë°ì 돎ììëĄ ë§ì€íŹê° ì ì©ëë©°, ë§ì€íŹë íčì§ ëČĄí°ë *ìëì ììč ìëČ ë©*ì ì¶ê°íë Transformer ìžìœëìž *돞맄 ë€ížìíŹ(context network)*ëĄ ì ëŹë©ëë€.
+
+4. 돞맄 ë€ížìíŹì ìŹì íë š ëȘ©íë *ëìĄ°ì ìì
(contrastive task)*ì
ëë€. ëȘšëžì ìëȘ»ë ììžĄ ìíì€ìì ë§ì€íŹë ììžĄì ì€ì ììíë ìì± ííì ììžĄíë©°, ëȘšëžìŽ ê°ì„ ì ìŹí 컚í
ì€íž ëČĄí°ì ììíë ìì± ëšì(íêČ ë ìŽëž)넌 ì°ŸëëĄ ê¶ì„í©ëë€.
+
+ìŽì wav2vec2ê° ìŹì íë šëììŒëŻëĄ, ì€ëì€ ë¶ë„ ëë ìë ìì± ìžìì ìíŽ ë°ìŽí°ì ë§ì¶° ëŻžìž ìĄ°ì í ì ìì”ëë€!
+
+### ì€ëì€ ë¶ë„[[audio-classification]]
+
+ìŹì íë šë ëȘšëžì ì€ëì€ ë¶ë„ì ìŹì©íë €ë©Ž, êž°ëłž Wav2Vec2 ëȘšëž ìëšì ìíì€ ë¶ë„ í€ë넌 ì¶ê°í멎 ë©ëë€. ë¶ë„ í€ëë ìžìœëì ìë ìí(hidden states)넌 ë°ë ì í ë ìŽìŽì
ëë€. ìë ìíë ê°ê° êžžìŽê° ë€ë„ž ì€ëì€ íë ììì íì”ë íčì§ì ëíë
ëë€. êł ì êžžìŽì ëČĄí° íë넌 ë§ë€êž° ìíŽ, ìë ìíë 뚌ì íë§ëêł , íŽëì€ ë ìŽëžì ëí ëĄì§ìŒëĄ ëłíë©ëë€. ê°ì„ ê°ë„ì±ìŽ ëì íŽëì€ë„Œ ì°Ÿêž° ìíŽ ëĄì§êłŒ íêČ ìŹìŽì ê”ì°š ìížëĄíŒ ìì€ìŽ êłì°ë©ëë€.
+
+ì€ëì€ ë¶ë„ì ì§ì ëì í ì€ëčê° ëì
šëì? ìì í [ì€ëì€ ë¶ë„ ê°ìŽë](tasks/audio_classification)넌 íìžíìŹ Wav2Vec2넌 ëŻžìž ìĄ°ì íêł ì¶ëĄ ì ìŹì©íë ë°©ëČì íì”íìžì!
+
+### ìë ìì± ìžì[[automatic-speech-recognition]]
+
+ìŹì íë šë ëȘšëžì ìë ìì± ìžìì ìŹì©íë €ë©Ž, [ì°êČ°ìŁŒìì ìê° ë¶ë„(CTC, Connectionist Temporal Classification)](glossary#connectionist-temporal-classification-ctc)넌 ìíŽ êž°ëłž Wav2Vec2 ëȘšëž ìëšì ìžìŽ ëȘšëžë§ í€ë넌 ì¶ê°í©ëë€. ìžìŽ ëȘšëžë§ í€ëë ìžìœëì ìë ìí넌 ë°ìì ëĄì§ìŒëĄ ëłíí©ëë€. ê° ëĄì§ì í í° íŽëì€(í í° ìë ìì
ì ìŽíìì ëíë©ëë€)넌 ëíë
ëë€. CTC ìì€ì í
ì€ížëĄ ëìœë©ë í í°ìì ê°ì„ ê°ë„ì±ìŽ ëì í í° ìíì€ë„Œ ì°Ÿêž° ìíŽ ëĄì§êłŒ íêČ ìŹìŽìì êłì°ë©ëë€.
+
+ìë ìì± ìžìì ì§ì ëì í ì€ëčê° ëì
šëì? ìì í [ìë ìì± ìžì ê°ìŽë](tasks/asr)넌 íìžíìŹ Wav2Vec2넌 ëŻžìž ìĄ°ì íêł ì¶ëĄ ì ìŹì©íë ë°©ëČì íì”íìžì!
+
+## 컎íší° ëčì [[computer-vision]]
+
+컎íší° ëčì ìì
ì ì ê·Œíë 2ê°ì§ ë°©ëČìŽ ìì”ëë€:
+
+1. ìŽëŻžì§ë„Œ íšìč ìíì€ëĄ ë¶ëŠŹíêł TransformerëĄ ëłë Ź ìČ늏í©ëë€.
+2. [ConvNeXT](model_doc/convnext)ì ê°ì íë CNNì ìŹì©í©ëë€. ìŽë í©ì±êł± ë ìŽìŽë„Œ êž°ë°ìŒëĄ íì§ë§ íë ë€ížìíŹ ì€êłë„Œ ì ì©í©ëë€.
+
+
+
+ìž ëČì§ž ë°©ëČì Transformerì í©ì±êł±(ì넌 ë€ìŽ, [Convolutional Vision Transformer](model_doc/cvt) ëë [LeViT](model_doc/levit))ì êȰí©íë êČì
ëë€. ì°ëŠŹë ìŽíŽëłŒ ë ê°ì§ ë°©ëČë§ êȰí©íêž° ë돞ì ìŹêž°ì ìŽ ë°©ëČì ë€ëŁšì§ ìì”ëë€.
+
+
+
+ViTì ConvNeXTë ìŒë°ì ìŒëĄ ìŽëŻžì§ ë¶ë„ìì ìŹì©ëì§ë§, ëŹŒìČŽ ê°ì§, ë¶í , êčìŽ ì¶ì êłŒ ê°ì ë€ë„ž ëčì ìì
ìë ê°ê° DETR, Mask2Former, GLPNìŽ ë ì í©íëŻëĄ ìŽëŹí ëȘšëžì ìŽíŽëłŽêČ ì”ëë€.
+
+### ìŽëŻžì§ ë¶ë„[[image-classification]]
+
+ViTì ConvNeXT ëȘšë ìŽëŻžì§ ë¶ë„ì ìŹì©ë ì ìì§ë§, ViTë ìŽí
ì
ë©ì»€ëìŠì, ConvNeXTë í©ì±êł±ì ìŹì©íë êČìŽ ìŁŒë ì°šìŽì
ëë€.
+
+#### Transformer[[transformer]]
+
+[ViT](model_doc/vit)ì í©ì±êł±ì ì ì ìŒëĄ ìì Transformer ìí€í
ìČëĄ ëìČŽí©ëë€. êž°ìĄŽ Transformerì ì”ìíë€ë©Ž, ViT넌 ìŽíŽíë ë°©ëČì ëë¶ë¶ì ìŽëŻž íì
íë€êł ëłŒ ì ìì”ëë€.
+
+
+
+
+
+ViTê° ëì
í ìŁŒì ëłêČœ ìŹíì ìŽëŻžì§ê° TransformerëĄ ìŽë»êČ ì ëŹëëì§ì ìì”ëë€:
+
+1. ìŽëŻžì§ë ìëĄ ì€ìČ©ëì§ ìë ì ìŹê°í íšìčëĄ ë¶í ëêł , ê° íšìčë ëČĄí° ëë *íšìč ìëČ ë©(patch embedding)*ìŒëĄ ëłíë©ëë€. íšìč ìëČ ë©ì ì ì í ì
ë „ ì°šìì ë§ëë 2D í©ì±êł± êłìž”ìì ìì±ë©ëë€(êž°ëłž Transformerì êČœì° ê° íšìčì ìëČ ë©ë§ë€ 768ê°ì ê°ìŽ íìí©ëë€). 224x224 íœì
ìŽëŻžì§ê° ìë€ë©Ž, 16x16 ìŽëŻžì§ íšìč 196ê°ëĄ ë¶í í ì ìì”ëë€. í
ì€ížê° ëšìŽëĄ í í°íëë êČìČëŒ, ìŽëŻžì§ë íšìč ìíì€ëĄ "í í°í"ë©ëë€.
+
+2. *íì” ê°ë„í ìëČ ë©(learnable embedding)*(íčìí `[CLS]` í í°)ìŽ BERTì ê°ìŽ íšìč ìëČ ë©ì ìì ë¶ë¶ì ì¶ê°ë©ëë€. `[CLS]` í í°ì ë§ì§ë§ ìë ìíë ë¶ì°©ë ë¶ë„ í€ëì ì
ë „ìŒëĄ ìŹì©ëêł , ë€ë„ž ì¶ë „ì 돎ìë©ëë€. ìŽ í í°ì ëȘšëžìŽ ìŽëŻžì§ì ííì ìžìœë©íë ë°©ëČì íì”íë ë° ëììŽ ë©ëë€.
+
+3. íšìčì íì” ê°ë„í ìëČ ë©ì ë§ì§ë§ìŒëĄ ì¶ê°í êČì *ììč ìëČ ë©*ì
ëë€. ìëí멎 ëȘšëžì ìŽëŻžì§ íšìčì ìì넌 ëȘšë„Žêž° ë돞ì
ëë€. ììč ìëČ ë©ë íì” ê°ë„íë©°, íšìč ìëČ ë©êłŒ ëìŒí íŹêž°ë„Œ ê°ì§ëë€. ì”ìą
ì ìŒëĄ, ëȘšë ìëČ ë©ìŽ Transformer ìžìœëì ì ëŹë©ëë€.
+
+4. `[CLS]` í í°ì íŹíší ì¶ë „ì ë€ìž” íŒì
ížëĄ í€ë(MLP)ì ì ëŹë©ëë€. ViTì ìŹì íë š ëȘ©íë ëšìí ë¶ë„ì
ëë€. ë€ë„ž ë¶ë„ í€ëì ê°ìŽ, MLP í€ëë ì¶ë „ì íŽëì€ ë ìŽëžì ëíŽ ëĄì§ìŒëĄ ëłííêł ê”ì°š ìížëĄíŒ ìì€ì êłì°íìŹ ê°ì„ ê°ë„ì±ìŽ ëì íŽëì€ë„Œ ì°Ÿì”ëë€.
+
+ìŽëŻžì§ ë¶ë„ì ì§ì ëì í ì€ëčê° ëì
šëì? ìì í [ìŽëŻžì§ ë¶ë„ ê°ìŽë](tasks/image_classification)넌 íìžíìŹ ViT넌 ëŻžìž ìĄ°ì íêł ì¶ëĄ ì ìŹì©íë ë°©ëČì íì”íìžì!
+
+#### CNN[[cnn]]
+
+
+
+ìŽ ìčì
ììë í©ì±êł±ì ëíŽ ê°ë”íêČ ì€ëȘ
í©ëë€. ê·žëŹë ìŽëŻžì§ì ëȘšìêłŒ íŹêž°ê° ìŽë»êČ ëłííëì§ì ëí ìŹì ìŽíŽê° ìë€ë©Ž ëììŽ ë êČì
ëë€. í©ì±êł±ì ì”ìíì§ ìì êČœì°, fastai bookì [í©ì±êł± ì êČœë§ ì±í°](https://github.com/fastai/fastbook/blob/master/13_convolutions.ipynb)넌 íìžíìžì!
+
+
+
+[ConvNeXT](model_doc/convnext)ë ì±ë„ì ëìŽêž° ìíŽ ìëĄìŽ íë ë€ížìíŹ ì€êłë„Œ ì ì©í CNN ê”ŹìĄ°ì
ëë€. ê·žëŹë í©ì±êł±ì ìŹì í ëȘšëžì í”ìŹì
ëë€. ëì ìì€ì êŽì ìì ëłŒ ë, [í©ì±êł±](glossary#convolution)ì ìì íë Ź(*컀ë*)ì ìŽëŻžì§ íœì
ì ìì ìëì°ë„Œ êł±íë ì°ì°ì
ëë€. ìŽë íčì í
ì€ìł(texture)ìŽë ì ì êłĄë„ êłŒ ê°ì ìŒë¶ íčì§ì êłì°í©ëë€. ê·žëŹêł ë€ì íœì
ìëì°ëĄ ëìŽê°ëë°, ìŹêž°ì í©ì±êł±ìŽ ìŽëíë ê±°ëŠŹë„Œ *볎í(stride)*ìŽëŒêł í©ëë€.
+
+
+
+
+
+íšë©ìŽë 볎íìŽ ìë êž°ëłž í©ì±êł±, ë„ëŹëì ìí í©ì±êł± ì°ì° ê°ìŽë
+
+ìŽ ì¶ë „ì ë€ë„ž í©ì±êł± ë ìŽìŽì ì ëŹí ì ììŒë©°, ê° ì°ìì ìž ë ìŽìŽë„Œ í”íŽ ë€ížìíŹë í«ëê·žë ëĄìŒêłŒ ê°ìŽ ë ëł”ìĄíêł ì¶ìì ìž êČì íì”í©ëë€. í©ì±êł± ë ìŽìŽ ìŹìŽì íë§ ë ìŽìŽë„Œ ì¶ê°íìŹ ì°šìì ì€ìŽêł íčì§ì ììč ëłíì ëíŽ ëȘšëžì ë êČŹêł íêČ ë§ëë êČìŽ ìŒë°ì ì
ëë€.
+
+
+
+
+
+ConvNeXTë CNNì 5ê°ì§ ë°©ììŒëĄ íëíí©ëë€:
+
+1. ê° ëšêłì ëžëĄ ì넌 ëłêČœíêł ë í° ëłŽíêłŒ ê·žì ëìíë 컀ë íŹêž°ëĄ ìŽëŻžì§ë„Œ "íšìčí(patchify)"í©ëë€. êČčìčì§ ìë ìŹëŒìŽë© ìëì°ë ViTê° ìŽëŻžì§ë„Œ íšìčëĄ ë¶í íë ë°©ëČêłŒ ì ìŹíêČ ìŽ íšìčí ì ë”ì ë§ëëë€.
+
+2. *ëłëȘ©(bottleneck)* ë ìŽìŽë ì±ë ì넌 ì€ìë€ê° ë€ì ëł”ìí©ëë€. ìëí멎 1x1 í©ì±êł±ì ìííë êČìŽ ë ëč ë„Žêł , êčìŽë„Œ ë늎 ì ìêž° ë돞ì
ëë€. ì ëłëȘ©(inverted bottlenect)ì ì±ë ì넌 íì„íêł ì¶ìíšìŒëĄìš ê·ž ë°ëëĄ ìííëŻëĄ, ë©ëȘšëŠŹ íšìšìŽ ë ëì”ëë€.
+
+3. ëłëȘ© ë ìŽìŽì ìŒë°ì ìž 3x3 í©ì±êł± ë ìŽìŽë„Œ ê° ì
ë „ ì±ëì ê°ëłì ìŒëĄ í©ì±êł±ì ì ì©í ë€ì ë§ì§ë§ì ìë *êčìŽëł í©ì±êł±(depthwise convolution)*ìŒëĄ ëìČŽí©ëë€. ìŽë ë€ížìíŹ íìŽ ëí ì±ë„ìŽ í„ìë©ëë€.
+
+4. ViTë ìŽí
ì
ë©ì»€ëìŠ ëë¶ì í ëČì ë ë§ì ìŽëŻžì§ë„Œ ëłŒ ì ìë ì ì ìì íë넌 ê°ì§êł ìì”ëë€. ConvNeXTë 컀ë íŹêž°ë„Œ 7x7ëĄ ëë € ìŽ íšêłŒë„Œ ìŹííë €êł ìëí©ëë€.
+
+5. ëí ConvNeXTë Transformer ëȘšëžì ëȘšë°©íë ëȘ ê°ì§ ë ìŽìŽ ì€êłë„Œ ëłêČœí©ëë€. íì±í ë° ì ê·í ë ìŽìŽê° ë ì êł , íì±í íšìê° ReLU ëì GELUëĄ ì íëêł , BatchNorm ëì LayerNormì ìŹì©í©ëë€.
+
+í©ì±êł± ëžëĄì ì¶ë „ì ë¶ë„ í€ëëĄ ì ëŹëë©°, ë¶ë„ í€ëë ì¶ë „ì ëĄì§ìŒëĄ ëłííêł ê”ì°š ìížëĄíŒ ìì€ì êłì°íìŹ ê°ì„ ê°ë„ì±ìŽ ëì ë ìŽëžì ì°Ÿì”ëë€.
+
+### ê°ìČŽ íì§[[object-detection]]
+
+[DETR](model_doc/detr), *DEtection TRansformer*ë CNNêłŒ Transformer ìžìœë-ëìœë넌 êȰí©í ìą
ëšê°(end-to-end) ê°ìČŽ íì§ ëȘšëžì
ëë€.
+
+
+
+
+
+1. ìŹì íë šë CNN *백볞(backbone)*ì íœì
ê°ìŒëĄ ëíëž ìŽëŻžì§ë„Œ ê°ì žì ì íŽìë íčì§ ë§”ì ë§ëëë€. íčì§ ë§”ì ëíŽ 1x1 í©ì±êł±ì ì ì©íìŹ ì°šìì ì€ìŽêł , êł ìì€ ìŽëŻžì§ ííì ê°ì§ ìëĄìŽ íčì§ ë§”ì ìì±í©ëë€. Transformerë ìíì€ ëȘšëžìŽêž° ë돞ì íčì§ ë§”ì ììč ìëČ ë©êłŒ êȰí©ë íčì§ ëČĄí°ì ìíì€ëĄ íííí©ëë€.
+
+2. íčì§ ëČĄí°ë ìŽí
ì
ë ìŽìŽë„Œ ìŹì©íìŹ ìŽëŻžì§ ííì íì”íë ìžìœëì ì ëŹë©ëë€. ë€ììŒëĄ, ìžìœëì ìë ìíë ëìœëìì *ê°ìČŽ ìżŒëŠŹ*ì êȰí©ë©ëë€. ê°ìČŽ ìżŒëŠŹë ìŽëŻžì§ì ë€ë„ž ììì ìŽì ì ë§ì¶ íì”ë ìëČ ë©ìŒëĄ íì”ëêł , ê° ìŽí
ì
ë ìŽìŽë„Œ ì§íí멎ì ê°±ì ë©ëë€. ëìœëì ìë ìíë ê° ê°ìČŽ ìżŒëŠŹì ëí ë°ìŽë© ë°ì€ ìąíì íŽëì€ ë ìŽëžì ììžĄíë ìë°©í„ ë€ížìíŹì ì ëŹëë©°, ê°ìČŽê° ìë êČœì° `no object`ê° ì¶ë „ë©ëë€.
+
+ DETRì ê° ê°ìČŽ ìżŒëŠŹë„Œ ëłë ŹëĄ ëìœë©íìŹ *N* ê°ì ì”ìą
ììžĄì ì¶ë „í©ëë€. ìŹêž°ì *N*ì ìżŒëŠŹ ìì
ëë€. í ëČì íëì ìì넌 ììžĄíë ìŒë°ì ìž ìêž°íê· ëȘšëžêłŒ ëŹëŠŹ, ê°ìČŽ íì§ë í ëČì *N* ê°ì ììžĄì ìííë ì§í© ììžĄ ìì
(`ë°ìŽë© ë°ì€`, `íŽëì€ ë ìŽëž`)ì
ëë€.
+
+3. DETRì íë š ì€ *ìŽë¶ ë§€ìč ìì€(bipartite matching loss)*ì ìŹì©íìŹ êł ì ë ìì ììžĄêłŒ êł ì ë ì€ì ì ë” ë ìŽëž(ground truth labels) ìžížë„Œ ëčê”í©ëë€. *N*ê°ì ë ìŽëž ìžížì ì€ì ì ë” ë ìŽëžëłŽë€ ì ì êČœì°, `no object` íŽëì€ëĄ íšë©ë©ëë€. ìŽ ìì€ íšìë DETRìŽ ììžĄêłŒ ì€ì ì ë” ë ìŽëž ê° 1:1 ëìì ì°ŸëëĄ ê¶ì„í©ëë€. ë°ìŽë© ë°ì€ ëë íŽëì€ ë ìŽëž ì€ íëëŒë ìëȘ»ë êČœì°, ìì€ìŽ ë°ìí©ëë€. ë§ì°Źê°ì§ëĄ, ìĄŽìŹíì§ ìë ê°ìČŽë„Œ ììžĄíë êČœì°, íšëí°ë„Œ ë°ì”ëë€. ìŽëĄ ìžíŽ DETRì ìŽëŻžì§ìì ëì ì ëë ëŹŒìČŽ íëì ì§ì€íë ëì , ë€ë„ž ê°ìČŽë„Œ ì°ŸëëĄ ê¶ì„ë©ëë€.
+
+ê°ìČŽ íì§ í€ëê° DETR ìëšì ì¶ê°ëìŽ íŽëì€ ë ìŽëžêłŒ ë°ìŽë© ë°ì€ì ìąí넌 ì°Ÿì”ëë€. ê°ìČŽ íì§ í€ëìë ë ê°ì§ ê”Źì± ììê° ìì”ëë€: ëìœë ìë ìí넌 íŽëì€ ë ìŽëžì ëĄì§ìŒëĄ ëłííë ì í ë ìŽìŽ ë° ë°ìŽë© ë°ì€ë„Œ ììžĄíë MLP
+
+ê°ìČŽ íì§ì ì§ì ëì í ì€ëčê° ëì
šëì? ìì í [ê°ìČŽ íì§ ê°ìŽë](tasks/object_detection)넌 íìžíìŹ DETRì ëŻžìž ìĄ°ì íêł ì¶ëĄ ì ìŹì©íë ë°©ëČì íì”íìžì!
+
+### ìŽëŻžì§ ë¶í [[image-segmentation]]
+
+[Mask2Former](model_doc/mask2former)ë ëȘšë ì íì ìŽëŻžì§ ë¶í ìì
ì íŽêȰíë ëČì© ìí€í
ìČì
ëë€. ì í”ì ìž ë¶í ëȘšëžì ìŒë°ì ìŒëĄ ìë©í±(semantic) ëë íëí±(panoptic) ë¶í êłŒ ê°ì ìŽëŻžì§ ë¶í ì íčì íì ìì
ì ë§ì¶° ìĄ°ì ë©ëë€. Mask2Formerë ëȘšë ìì
ì *ë§ì€íŹ ë¶ë„* 돞ì ëĄ ê”Źì±í©ëë€. ë§ì€íŹ ë¶ë„ë íœì
ì *N*ê° ìžê·žëšŒížëĄ ê·žëŁčííêł , ìŁŒìŽì§ ìŽëŻžì§ì ëíŽ *N*ê°ì ë§ì€íŹì ê·žì ëìíë íŽëì€ ë ìŽëžì ììžĄí©ëë€. ìŽ ìčì
ìì Mask2Formerì ìë ë°©ëČì ì€ëȘ
í ë€ì, ë§ì§ë§ì SegFormer넌 ëŻžìž ìĄ°ì íŽëłŒ ì ìì”ëë€.
+
+
+
+
+
+Mask2Formerìë 3ê°ì§ ìŁŒì ê”Źì± ììê° ìì”ëë€:
+
+1. [Swin](model_doc/swin) ë°±ëłžìŽ ìŽëŻžì§ë„Œ ë°ì 3ê°ì ì°ìë 3x3 í©ì±êł±ìì ì íŽìë ìŽëŻžì§ íčì§ ë§”ì ìì±í©ëë€.
+
+2. íčì§ ë§”ì *íœì
ëìœë*ì ì ëŹë©ëë€. ìŽ ëìœëë ì íŽìë íčì§ì êł íŽìë íœì
ìëČ ë©ìŒëĄ ì ì§ì ìŒëĄ ì
ìíë§í©ëë€. íœì
ëìœëë ì€ì ëĄ ìëłž ìŽëŻžì§ì 1/32, 1/16, 1/8 íŽìëì ë€ì€ ì€ìŒìŒ íčì§(ì íŽìë ë° êł íŽìë íčì§ ëȘšë íŹíš)ì ìì±í©ëë€.
+
+3. ìŽëŹí ìëĄ ë€ë„ž íŹêž°ì íčì§ ë§”ì êł íŽìë íčì§ìì ìì ê°ìČŽë„Œ íŹì°©íêž° ìíŽ í ëČì íëì Transformer ëìœë ë ìŽìŽì ì°ìì ìŒëĄ êł”êžë©ëë€. Mask2Formerì í”ìŹì ëìœëì *ë§ì€íŹ ìŽí
ì
* ë©ì»€ëìŠì
ëë€. ì ìČŽ ìŽëŻžì§ë„Œ ì°žìĄ°í ì ìë íŹëĄì€ ìŽí
ì
(cross-attention)êłŒ ëŹëŠŹ, ë§ì€íŹ ìŽí
ì
ì ìŽëŻžì§ì íčì ìììë§ ì§ì€í©ëë€. ìŽë ìŽëŻžì§ì ì§ìì íčì§ë§ìŒëĄ ëȘšëžìŽ ì¶©ë¶í íì”í ì ìêž° ë돞ì ë ëč ë„Žêł ì±ë„ìŽ ì°ìí©ëë€.
+
+4. [DETR](tasks_explained#object-detection)êłŒ ê°ìŽ, Mask2Formerë íì”ë ê°ìČŽ ìżŒëŠŹë„Œ ìŹì©íêł ìŽë„Œ íœì
ëìœëììì ìŽëŻžì§ íčì§êłŒ êȰí©íìŹ ììžĄ ì§í©(`íŽëì€ ë ìŽëž`, `ë§ì€íŹ ììžĄ`)ì ìì±í©ëë€. ëìœëì ìë ìíë ì í ë ìŽìŽëĄ ì ëŹëìŽ íŽëì€ ë ìŽëžì ëí ëĄì§ìŒëĄ ëłíë©ëë€. ëĄì§êłŒ íŽëì€ ë ìŽëž ìŹìŽì ê”ì°š ìížëĄíŒ ìì€ì êłì°íìŹ ê°ì„ ê°ë„ì±ìŽ ëì êČì ì°Ÿì”ëë€.
+
+ ë§ì€íŹ ììžĄì íœì
ìëČ ë©êłŒ ì”ìą
ëìœë ìë ìí넌 êȰí©íìŹ ìì±ë©ëë€. ìê·žëȘšìŽë ê”ì°š ìížëĄíŒ ë° Dice ìì€ì ëĄì§êłŒ ì€ì ì ë” ë§ì€íŹ(ground truth mask) ìŹìŽìì êłì°ëìŽ ê°ì„ ê°ë„ì±ìŽ ëì ë§ì€íŹë„Œ ì°Ÿì”ëë€.
+
+ìŽëŻžì§ ë¶í ì ì§ì ëì í ì€ëčê° ëì
šëì? ìì í [ìŽëŻžì§ ë¶í ê°ìŽë](tasks/semantic_segmentation)넌 íìžíìŹ SegFormer넌 ëŻžìž ìĄ°ì íêł ì¶ëĄ ì ìŹì©íë ë°©ëČì íì”íìžì!
+
+### êčìŽ ì¶ì [[depth-estimation]]
+
+[GLPN](model_doc/glpn), *Global-Local Path Network*ë [SegFormer](model_doc/segformer) ìžìœëì êČœë ëìœë넌 êȰí©í êčìŽ ì¶ì ì ìí Transformerì
ëë€.
+
+
+
+
+
+1. ViTì ê°ìŽ, ìŽëŻžì§ë íšìč ìíì€ëĄ ë¶í ëì§ë§, ìŽëŻžì§ íšìčê° ë ìë€ë ì ìŽ ë€ëŠ
ëë€. ìŽë ìžê·žë©í
ìŽì
ìŽë êčìŽ ì¶ì êłŒ ê°ì ë°ë ììžĄ ìì
ì ë ì í©í©ëë€. ìŽëŻžì§ íšìčë íšìč ìëČ ë©ìŒëĄ ëłíëìŽ(íšìč ìëČ ë©ìŽ ìì±ëë ë°©ëČì [ìŽëŻžì§ ë¶ë„](#image-classification) ìčì
ì ì°žìĄ°íìžì), ìžìœëëĄ ì ëŹë©ëë€.
+
+2. ìžìœëë íšìč ìëČ ë©ì ë°ì, ìŹëŹ ìžìœë ëžëĄì ì ëŹí©ëë€. ê° ëžëĄì ìŽí
ì
ë° Mix-FFN ë ìŽìŽëĄ ê”Źì±ë©ëë€. íìì ëȘ©ì ì ììč ì ëłŽë„Œ ì êł”íë êČì
ëë€. ê° ìžìœë ëžëĄì ëìë êłìž”ì ííì ìì±íêž° ìí *íšìč ëłí©(patch merging)* ë ìŽìŽê° ìì”ëë€. ê° ìžì í íšìč ê·žëŁčì íčì§ì ì°êȰëêł , ì°êȰë íčì§ì ì í ë ìŽìŽê° ì ì©ëìŽ íšìč ì넌 1/4ì íŽìëëĄ ì€ì
ëë€. ìŽë ë€ì ìžìœë ëžëĄì ì
ë „ìŽ ëë©°, ìŽëŹí ì ìČŽ íëĄìžì€ë 1/8, 1/16, 1/32 íŽìëì ìŽëŻžì§ íčì§ì ê°ì§ ëêčì§ ë°ëł”ë©ëë€.
+
+3. êČœë ëìœëë ìžìœëìì ë§ì§ë§ íčì§ ë§”(1/32 íŹêž°)ì ê°ì žì 1/16 íŹêž°ëĄ ì
ìíë§í©ëë€. ìŹêž°ì, íčì§ì *ì íì íčì§ ì”í©(SFF, Selective Feature Fusion)* ëȘšëëĄ ì ëŹë©ëë€. ìŽ ëȘšëì ê° íčì§ì ëíŽ ìŽí
ì
ë§”ìì ëĄì»Ź ë° ì ì íčì§ì ì ííêł êȰí©í ë€ì, 1/8ëĄ ì
ìíë§í©ëë€. ìŽ íëĄìžì€ë ëìœë©ë íčì±ìŽ ìëłž ìŽëŻžì§ì ëìŒí íŹêž°ê° ë ëêčì§ ë°ëł”ë©ëë€. ì¶ë „ì ë ê°ì í©ì±êł± ë ìŽìŽë„Œ ê±°ìč ë€ì, ìê·žëȘšìŽë íì±íê° ì ì©ëìŽ ê° íœì
ì êčìŽë„Œ ììžĄí©ëë€.
+
+## ìì°ìŽìČ늏[[natural-language-processing]]
+
+Transformerë ìŽêž°ì êž°êł ëČìì ìíŽ ì€êłëìêł , ê·ž ìŽíëĄë ìŹì€ì ëȘšë NLP ìì
ì íŽêȰíêž° ìí êž°ëłž ìí€í
ìČê° ëìì”ëë€. ìŽë€ ìì
ì Transformerì ìžìœë ê”ŹìĄ°ì ì í©íë©°, ë€ë„ž ìì
ì ëìœëì ë ì í©í©ëë€. ë ë€ë„ž ìì
ì Transformerì ìžìœë-ëìœë ê”ŹìĄ°ë„Œ ëȘšë íì©í©ëë€.
+
+### í
ì€íž ë¶ë„[[text-classification]]
+
+[BERT](model_doc/bert)ë ìžìœë ì ì© ëȘšëžìŽë©°, í
ì€ížì íë¶í ííì íì”íêž° ìíŽ ìë°©í„ì ëšìŽì ìŁŒëȘ©íšìŒëĄìš ìŹìž” ìë°©í„ì±(deep bidirectionality)ì íšêłŒì ìŒëĄ ê”Źíí ì”ìŽì ëȘšëžì
ëë€.
+
+1. BERTë [WordPiece](tokenizer_summary#wordpiece) í í°í넌 ìŹì©íìŹ ëŹžì„ì í í° ìëČ ë©ì ìì±í©ëë€. ëšìŒ 돞ì„êłŒ í ìì 돞ì„ì ê”Źë¶íêž° ìíŽ íčìí `[SEP]` í í°ìŽ ì¶ê°ë©ëë€. ëȘšë í
ì€íž ìíì€ì ìì ë¶ë¶ìë íčìí `[CLS]` í í°ìŽ ì¶ê°ë©ëë€. `[CLS]` í í°ìŽ ìë ì”ìą
ì¶ë „ì ë¶ë„ ìì
ì ìí ë¶ë„ í€ëëĄ ì
ë „ì ìŹì©ë©ëë€. BERTë ëí í ìì 돞ì„ìì ê° í í°ìŽ ìČ« ëČì§ž 돞ì„ìžì§ ë ëČì§ž 돞ì„ì ìíëì§ ëíëŽë ìžê·žëšŒíž ìëČ ë©(segment embedding)ì ì¶ê°í©ëë€.
+
+2. BERTë ë§ì€íŹë ìžìŽ ëȘšëžë§êłŒ ë€ì ëŹžì„ ììžĄ, ë ê°ì§ ëȘ©ì ìŒëĄ ìŹì íë šë©ëë€. ë§ì€íŹë ìžìŽ ëȘšëžë§ììë ì
ë „ í í°ì ìŒë¶ê° 돎ììëĄ ë§ì€íčëêł , ëȘšëžì ìŽë„Œ ììžĄíŽìŒ í©ëë€. ìŽë ëȘšëžìŽ ëȘšë ëšìŽë„Œ ëłŽêł ë€ì ëšìŽë„Œ "ììžĄ"í ì ìë ìë°©í„ì± ëŹžì 넌 íŽêȰí©ëë€. ììžĄë ë§ì€íŹ í í°ì ì”ìą
ìë ìíë ìŽíì ëí ìíížë§„ì€ê° ìë ìë°©í„ ë€ížìíŹëĄ ì ëŹëìŽ ë§ì€íŹë ëšìŽë„Œ ììžĄí©ëë€.
+
+ ë ëČì§ž ìŹì íë š ëìì ë€ì ëŹžì„ ììžĄì
ëë€. ëȘšëžì ëŹžì„ Bê° ëŹžì„ A ë€ìì ì€ëì§ ììžĄíŽìŒ í©ëë€. ëŹžì„ Bê° ë€ì 돞ì„ìž êČœì°ì 돎ìì 돞ì„ìž êČœì° ê°ê° 50%ì íë„ ëĄ ë°ìí©ëë€. ë€ì 돞ì„ìžì§ ìëì§ì ëí ììžĄì ë ê°ì íŽëì€(`IsNext` ë° `NotNext`)ì ëí ìíížë§„ì€ê° ìë ìë°©í„ ë€ížìíŹëĄ ì ëŹë©ëë€.
+
+3. ì
ë „ ìëČ ë©ì ìŹëŹ ìžìœë ë ìŽìŽë„Œ ê±°ìłì ì”ìą
ìë ìí넌 ì¶ë „í©ëë€.
+
+ìŹì íë šë ëȘšëžì í
ì€íž ë¶ë„ì ìŹì©íë €ë©Ž, êž°ëłž BERT ëȘšëž ìëšì ìíì€ ë¶ë„ í€ë넌 ì¶ê°í©ëë€. ìíì€ ë¶ë„ í€ëë ì”ìą
ìë ìí넌 ë°ë ì í ë ìŽìŽìŽë©°, ëĄì§ìŒëĄ ëłííêž° ìíŽ ì í ëłíì ìíí©ëë€. ê”ì°š ìížëĄíŒ ìì€ì ëĄì§êłŒ íêČ ê°ì êłì°ëìŽ ê°ì„ ê°ë„ì±ìŽ ëì ë ìŽëžì ì°Ÿì”ëë€.
+
+í
ì€íž ë¶ë„ì ì§ì ëì í ì€ëčê° ëì
šëì? ìì í [í
ì€íž ë¶ë„ ê°ìŽë](tasks/sequence_classification)넌 íìžíìŹ DistilBERT넌 ëŻžìž ìĄ°ì íêł ì¶ëĄ ì ìŹì©íë ë°©ëČì íì”íìžì!
+
+### í í° ë¶ë„[[token-classification]]
+
+ê°ìČŽëȘ
ìžì(Named Entity Recognition, NER)êłŒ ê°ì í í° ë¶ë„ ìì
ì BERT넌 ìŹì©íë €ë©Ž, êž°ëłž BERT ëȘšëž ìëšì í í° ë¶ë„ í€ë넌 ì¶ê°í©ëë€. í í° ë¶ë„ í€ëë ì”ìą
ìë ìí넌 ë°ë ì í ë ìŽìŽìŽë©°, ëĄì§ìŒëĄ ëłííêž° ìíŽ ì í ëłíì ìíí©ëë€. ê”ì°š ìížëĄíŒ ìì€ì ëĄì§êłŒ ê° í í° ê°ì êłì°ëìŽ ê°ì„ ê°ë„ì±ìŽ ëì ë ìŽëžì ì°Ÿì”ëë€.
+
+í í° ë¶ë„ì ì§ì ëì í ì€ëčê° ëì
šëì? ìì í [í í° ë¶ë„ ê°ìŽë](tasks/token_classification)넌 íìžíìŹ DistilBERT넌 ëŻžìž ìĄ°ì íêł ì¶ëĄ ì ìŹì©íë ë°©ëČì íì”íìžì!
+
+### ì§ììë”[[question-answering]]
+
+ì§ììë”ì BERT넌 ìŹì©íë €ë©Ž, êž°ëłž BERT ëȘšëž ìì ì€íŹ(span) ë¶ë„ í€ë넌 ì¶ê°í©ëë€. ìŽ ì í ë ìŽìŽë ì”ìą
ìë ìí넌 ë°êł , ë”ëłì ëìíë `ì€íŹ`ì ììêłŒ ë ëĄê·žë„Œ êłì°íêž° ìíŽ ì í ëłíì ìíí©ëë€. ê”ì°š ìížëĄíŒ ìì€ì ëĄì§êłŒ ê° ë ìŽëž ììč ê°ì êłì°ëìŽ ë”ëłì ëìíë ê°ì„ ê°ë„ì±ìŽ ëì í
ì€ížì ì€íŹì ì°Ÿì”ëë€.
+
+ì§ììë”ì ì§ì ëì í ì€ëčê° ëì
šëì? ìì í [ì§ììë” ê°ìŽë](tasks/question_answering)넌 íìžíìŹ DistilBERT넌 ëŻžìž ìĄ°ì íêł ì¶ëĄ ì ìŹì©íë ë°©ëČì íì”íìžì!
+
+
+
+đĄ ìŹì íë šë BERT넌 ë€ìí ìì
ì ìŹì©íë êČìŽ ìŒë§ë ìŹìŽì§ ìŁŒëȘ©íìžì. ìŹì íë šë ëȘšëžì íčì í€ë넌 ì¶ê°íêž°ë§ í멎 ìë ìí넌 ìíë ì¶ë „ìŒëĄ ìĄ°ìí ì ìì”ëë€!
+
+
+
+### í
ì€íž ìì±[[text-generation]]
+
+[GPT-2](model_doc/gpt2)ë ëëì í
ì€ížì ëíŽ ìŹì íë šë ëìœë© ì ì© ëȘšëžì
ëë€. í륏íížë„Œ ìŁŒìŽì§ë©Ž ì€ëë „ ìë (íì ìŹì€ì ìëì§ë§!) í
ì€ížë„Œ ìì±íêł ëȘ
ìì ìŒëĄ íë šëì§ ììììë ë¶ê”Źíêł ì§ììë”êłŒ ê°ì ë€ë„ž NLP ìì
ì ììí ì ìì”ëë€.
+
+
+
+
+
+1. GPT-2ë ëšìŽë„Œ í í°ííêł í í° ìëČ ë©ì ìì±íêž° ìíŽ [ë°ìŽíž íìŽ ìžìœë©(BPE, byte pair encoding)](tokenizer_summary#bytepair-encoding-bpe)ì ìŹì©í©ëë€. ììč ìžìœë©ì ìíì€ìì ê° í í°ì ììč넌 ëíëŽêž° ìíŽ í í° ìëČ ë©ì ì¶ê°ë©ëë€. ì
ë „ ìëČ ë©ì ìŹëŹ ëìœë ëžëĄì ê±°ìł ìŒë¶ ì”ìą
ìë ìí넌 ì¶ë „í©ëë€. ê° ëìœë ëžëĄ ëŽìì GPT-2ë *ë§ì€íŹë ì
í ìŽí
ì
(masked self-attention)* ë ìŽìŽë„Œ ìŹì©í©ëë€. ìŽë GPT-2ê° ìŽí í í°(future tokens)ì ìŁŒì넌 êž°ìžìŒ ì ìëëĄ í©ëë€. ìŒìȘœì ìë í í°ìë§ ìŁŒì넌 êž°ìžìŒ ì ìì”ëë€. ë§ì€íŹë ì
í ìŽí
ì
ììë ìŽí
ì
ë§ì€íŹë„Œ ìŹì©íìŹ ìŽí í í°ì ëí ì ì(score)넌 `0`ìŒëĄ ì€ì íêž° ë돞ì BERTì [`mask`] í í°êłŒ ë€ëŠ
ëë€.
+
+2. ëìœëì ì¶ë „ì ìžìŽ ëȘšëžë§ í€ëì ì ëŹëë©°, ìžìŽ ëȘšëžë§ í€ëë ìë ìí넌 ëĄì§ìŒëĄ ì í ëłíì ìíí©ëë€. ë ìŽëžì ìíì€ì ë€ì í í°ìŒëĄ, ëĄì§ì ì€ë„žìȘœìŒëĄ íëì© ìŽëíìŹ ìì±ë©ëë€. ê”ì°š ìížëĄíŒ ìì€ì ìŽëë ëĄì§êłŒ ë ìŽëž ê°ì êłì°ëìŽ ê°ì„ ê°ë„ì±ìŽ ëì ë€ì í í°ì ì¶ë „í©ëë€.
+
+GPT-2ì ìŹì íë š ëȘ©ì ì ì ì ìŒëĄ [ìžêłŒì ìžìŽ ëȘšëžë§](glossary#causal-language-modeling)ì êž°ë°íìŹ, ìíì€ìì ë€ì ëšìŽë„Œ ììžĄíë êČì
ëë€. ìŽë GPT-2ê° í
ì€íž ìì±ì êŽë šë ìì
ì íčí ì°ìíëëĄ í©ëë€.
+
+í
ì€íž ìì±ì ì§ì ëì í ì€ëčê° ëì
šëì? ìì í [ìžêłŒì ìžìŽ ëȘšëžë§ ê°ìŽë](tasks/language_modeling#causal-language-modeling)넌 íìžíìŹ DistilGPT-2넌 ëŻžìž ìĄ°ì íêł ì¶ëĄ ì ìŹì©íë ë°©ëČì íì”íìžì!
+
+
+
+í
ì€íž ìì±ì ëí ììží ëŽì©ì [í
ì€íž ìì± ì ë”](generation_strategies) ê°ìŽë넌 íìžíìžì!
+
+
+
+### ììœ[[summarization]]
+
+[BART](model_doc/bart) ë° [T5](model_doc/t5)ì ê°ì ìžìœë-ëìœë ëȘšëžì ììœ ìì
ì ìíì€-íŹ-ìíì€ íšíŽì ìíŽ ì€êłëìì”ëë€. ìŽ ìčì
ìì BARTì ìë ë°©ëČì ì€ëȘ
í ë€ì, ë§ì§ë§ì T5넌 ëŻžìž ìĄ°ì íŽëłŒ ì ìì”ëë€.
+
+
+
+
+
+1. BARTì ìžìœë ìí€í
ìČë BERTì ë§€ì° ì ìŹíë©° í
ì€ížì í í° ë° ììč ìëČ ë©ì ë°ì”ëë€. BARTë ì
ë „ì ëłíìí€êł ëìœëëĄ ìŹê”Źì±íìŹ ìŹì íë šë©ëë€. íčì ëłí êž°ëČìŽ ìë ë€ë„ž ìžìœëìë ëŹëŠŹ, BARTë ëȘšë ì íì ëłíì ì ì©í ì ìì”ëë€. ê·žëŹë *text infilling* ëłí êž°ëČìŽ ê°ì„ ì ìëí©ëë€. Text Infilingììë ìŹëŹ í
ì€íž ì€íŹì **ëšìŒ** [`mask`] í í°ìŒëĄ ëìČŽí©ëë€. ìŽë ëȘšëžìŽ ë§ì€íŹë í í°ì ììžĄíŽìŒ íêł , ëȘšëžì ëëœë í í°ì ì넌 ììžĄíëëĄ ê°ë„Žìčêž° ë돞ì ì€ìí©ëë€. ì
ë „ ìëČ ë©êłŒ ë§ì€íŹë ì€íŹìŽ ìžìœë넌 ê±°ìł ì”ìą
ìë ìí넌 ì¶ë „íì§ë§, BERTì ëŹëŠŹ BARTë ë§ì§ë§ì ëšìŽë„Œ ììžĄíë ìë°©í„ ë€ížìíŹë„Œ ì¶ê°íì§ ìì”ëë€.
+
+2. ìžìœëì ì¶ë „ì ëìœëëĄ ì ëŹëë©°, ëìœëë ìžìœëì ì¶ë „ìì ë§ì€íŹ í í°êłŒ ëłíëì§ ìì í í°ì ììžĄíŽìŒ í©ëë€. ìŽë ëìœëê° ìëłž í
ì€ížë„Œ ëł”ìíë ë° ëììŽ ëë ì¶ê°ì ìž ëŹžë§„ì ì»ëëĄ í©ëë€. ëìœëì ì¶ë „ì ìžìŽ ëȘšëžë§ í€ëì ì ëŹëë©°, ìžìŽ ëȘšëžë§ í€ëë ìë ìí넌 ëĄì§ìŒëĄ ì í ëłíì ìíí©ëë€. ê”ì°š ìížëĄíŒ ìì€ì ëĄì§êłŒ í í°ìŽ ì€ë„žìȘœìŒëĄ ìŽëë ë ìŽëž ê°ì êłì°ë©ëë€.
+
+ììœì ì§ì ëì í ì€ëčê° ëì
šëì? ìì í [ììœ ê°ìŽë](tasks/summarization)넌 íìžíìŹ T5넌 ëŻžìž ìĄ°ì íêł ì¶ëĄ ì ìŹì©íë ë°©ëČì íì”íìžì!
+
+
+
+í
ì€íž ìì±ì ëí ììží ëŽì©ì [í
ì€íž ìì± ì ë”](generation_strategies) ê°ìŽë넌 íìžíìžì!
+
+
+
+### ëČì[[translation]]
+
+ëČìì ìíì€-íŹ-ìíì€ ìì
ì ë ë€ë„ž ìëĄ, [BART](model_doc/bart) ëë [T5](model_doc/t5)ì ê°ì ìžìœë-ëìœë ëȘšëžì ìŹì©í ì ìì”ëë€. ìŽ ìčì
ìì BARTì ìë ë°©ëČì ì€ëȘ
í ë€ì, ë§ì§ë§ì T5넌 ëŻžìž ìĄ°ì íŽëłŒ ì ìì”ëë€.
+
+BARTë ììČ ìžìŽë„Œ íêČ ìžìŽëĄ ëìœë©í ì ìë ì
ë „ì ë§€ííêž° ìíŽ ëŹŽììëĄ ìŽêž°íë ëłëì ìžìœë넌 ì¶ê°íìŹ ëČìì ì ì©í©ëë€. ìŽ ìëĄìŽ ìžìœëì ìëČ ë©ì ìëłž ëšìŽ ìëČ ë© ëì ìŹì íë šë ìžìœëëĄ ì ëŹë©ëë€. ììČ ìžìœëë ëȘšëž ì¶ë „ì ê”ì°š ìížëĄíŒ ìì€ëĄë¶í° ììČ ìžìœë, ììč ìëČ ë©, ì
ë „ ìëČ ë©ì ê°±ì íìŹ íë šë©ëë€. ìČ« ëČì§ž ëšêłììë ëȘšëž íëŒëŻží°ê° êł ì ëêł , ë ëČì§ž ëšêłììë ëȘšë ëȘšëž íëŒëŻží°ê° íšê» íë šë©ëë€.
+
+BARTë ìŽí ëČìì ìíŽ ë€ìí ìžìŽëĄ ìŹì íë šë ë€ê”ìŽ ëČì ì mBARTëĄ íì„ëìì”ëë€.
+
+ëČìì ì§ì ëì í ì€ëčê° ëì
šëì? ìì í [ëČì ê°ìŽë](tasks/summarization)넌 íìžíìŹ T5넌 ëŻžìž ìĄ°ì íêł ì¶ëĄ ì ìŹì©íë ë°©ëČì íì”íìžì!
+
+
+
+í
ì€íž ìì±ì ëí ììží ëŽì©ì [í
ì€íž ìì± ì ë”](generation_strategies) ê°ìŽë넌 íìžíìžì!
+
+
\ No newline at end of file
diff --git a/docs/source/ko/testing.md b/docs/source/ko/testing.md
new file mode 100644
index 000000000000..0e40ff9f07c6
--- /dev/null
+++ b/docs/source/ko/testing.md
@@ -0,0 +1,1278 @@
+
+
+# í
ì€íž[[testing]]
+
+
+뚌ì đ€ Transformers ëȘšëžìŽ ìŽë»êČ í
ì€ížëëì§ ìŽíŽëłŽêł , ìëĄìŽ í
ì€ížë„Œ ìì± ë° êž°ìĄŽ í
ì€ížë„Œ ê°ì íë ë°©ëČì ììëŽ
ìë€.
+
+ìŽ ì ì„ììë 2ê°ì í
ì€íž ì€ìížê° ìì”ëë€:
+
+1. `tests` - ìŒë° APIì ëí í
ì€íž
+2. `examples` - APIì ìŒë¶ê° ìë ë€ìí ìì© íëĄê·žëšì ëí í
ì€íž
+
+## Transformers í
ì€íž ë°©ëČ[[how-transformers-are-tested]]
+
+1. PRìŽ ì ì¶ë멎 9ê°ì CircleCi ìì
ìŒëĄ í
ì€ížê° ì§íë©ëë€. íŽëč PRì ëíŽ ìëĄìŽ ì»€ë°ìŽ ìì±ë ëë§ë€ í
ì€ížë ë€ì ì§íë©ëë€. ìŽ ìì
ë€ì
+ ìŽ [config íìŒ](https://github.com/huggingface/transformers/tree/main/.circleci/config.yml)ì ì ìëìŽ ììŒëŻëĄ íìíë€ë©Ž
+ ìŹì©ìì ëĄì»Ź íêČœìì ëìŒíêČ ìŹííŽ ëłŒ ì ìì”ëë€.
+
+ ìŽ CI ìì
ì `@slow` í
ì€ížë„Œ ì€ííì§ ìì”ëë€.
+
+2. [github actions](https://github.com/huggingface/transformers/actions)ì ìíŽ ì€íëë ìì
ì 3ê°ì
ëë€:
+
+ - [torch hub integration](https://github.com/huggingface/transformers/tree/main/.github/workflows/github-torch-hub.yml):
+ torch hub integrationìŽ ìëíëì§ íìží©ëë€.
+
+ - [self-hosted (push)](https://github.com/huggingface/transformers/tree/main/.github/workflows/self-push.yml): `main` ëžëìčìì 컀ë°ìŽ ì
ë°ìŽížë êČœì°ìë§ GPU넌 ìŽì©í ëč 넞 í
ì€ížë„Œ ì€íí©ëë€.
+ ìŽë `src`, `tests`, `.github` íŽë ì€ íëì ìœëê° ì
ë°ìŽížë êČœì°ìë§ ì€íë©ëë€.
+ (model card, notebook, êž°í ë±ë±ì ì¶ê°í êČœì° ì€íëì§ ìëëĄ íêž° ìíŽìì
ëë€)
+
+ - [self-hosted runner](https://github.com/huggingface/transformers/tree/main/.github/workflows/self-scheduled.yml): `tests` ë° `examples`ìì
+ GPU넌 ìŽì©í ìŒë° í
ì€íž, ë늰 í
ì€ížë„Œ ì€íí©ëë€.
+
+
+```bash
+RUN_SLOW=1 pytest tests/
+RUN_SLOW=1 pytest examples/
+```
+
+ êČ°êłŒë [ìŹêž°](https://github.com/huggingface/transformers/actions)ìì íìží ì ìì”ëë€.
+
+
+## í
ì€íž ì€í[[running-tests]]
+
+
+
+
+
+### ì€íí í
ì€íž ì í[[choosing-which-tests-to-run]]
+
+ìŽ ëŹžìë í
ì€ížë„Œ ì€ííë ë€ìí ë°©ëČì ëíŽ ììží ì€ëȘ
í©ëë€.
+ëȘšë ëŽì©ì ìœì íìë, ë ììží ëŽì©ìŽ íìíë€ë©Ž [ìŹêž°](https://docs.pytest.org/en/latest/usage.html)ìì íìží ì ìì”ëë€.
+
+ë€ìì ê°ì„ ì ì©í í
ì€íž ì€í ë°©ëČ ëȘ ê°ì§ì
ëë€.
+
+ëȘšë ì€í:
+
+```console
+pytest
+```
+
+ëë:
+
+```bash
+make test
+```
+
+íìë ë€ìêłŒ ê°ìŽ ì ìë©ëë€:
+
+```bash
+python -m pytest -n auto --dist=loadfile -s -v ./tests/
+```
+
+ìì ëȘ
ë čìŽë pytestìêČ ìëì ëŽì©ì ì ëŹí©ëë€:
+
+- ìŹì© ê°ë„í CPU ìœìŽ ìë§íŒ í
ì€íž íëĄìžì€ë„Œ ì€íí©ëë€. (RAMìŽ ì¶©ë¶íì§ ìë€ë©Ž, í
ì€íž íëĄìžì€ ìê° ë돎 ë§ì ì ìì”ëë€!)
+- ëìŒí íìŒì ëȘšë í
ì€ížë ëìŒí í
ì€íž íëĄìžì€ìì ì€íëìŽìŒ í©ëë€.
+- ì¶ë „ì ìșĄìČíì§ ìì”ëë€.
+- ììží ëȘšëëĄ ì€íí©ëë€.
+
+
+
+### ëȘšë í
ì€íž ëȘ©ëĄ ê°ì žì€êž°[[getting-the-list-of-all-tests]]
+
+í
ì€íž ì€ìížì ëȘšë í
ì€íž:
+
+```bash
+pytest --collect-only -q
+```
+
+ì§ì ë í
ì€íž íìŒì ëȘšë í
ì€íž:
+
+```bash
+pytest tests/test_optimization.py --collect-only -q
+```
+
+### íčì í
ì€íž ëȘšë ì€í[[run-a-specific-test-module]]
+
+ê°ëł í
ì€íž ëȘšë ì€ííêž°:
+
+```bash
+pytest tests/test_logging.py
+```
+
+### íčì í
ì€íž ì€í[[run-specific-tests]]
+
+ëë¶ë¶ì í
ì€íž ëŽë¶ììë unittestê° ìŹì©ë©ëë€. ë°ëŒì íčì íì í
ì€ížë„Œ ì€ííë €ë©Ž íŽëč í
ì€ížë„Œ íŹíšíë unittest íŽëì€ì ìŽëŠì ìììŒ í©ëë€.
+ì넌 ë€ìŽ ë€ìêłŒ ê°ì ì ìì”ëë€:
+
+```bash
+pytest tests/test_optimization.py::OptimizationTest::test_adam_w
+```
+
+ìì ëȘ
ë čìŽì ì믞ë ë€ìêłŒ ê°ì”ëë€:
+
+- `tests/test_optimization.py` - í
ì€ížê° ìë íìŒ
+- `OptimizationTest` - íŽëì€ì ìŽëŠ
+- `test_adam_w` - íčì í
ì€íž íšìì ìŽëŠ
+
+íìŒì ìŹëŹ íŽëì€ê° íŹíšë êČœì°, íčì íŽëì€ì í
ì€ížë§ ì€íí ìë ìì”ëë€. ì넌 ë€ìŽ ë€ìêłŒ ê°ì”ëë€:
+
+```bash
+pytest tests/test_optimization.py::OptimizationTest
+```
+
+ìŽ ëȘ
ë čìŽë íŽëč íŽëì€ ëŽë¶ì ëȘšë í
ì€ížë„Œ ì€íí©ëë€.
+
+ììì ìžêží êČìČëŒ `OptimizationTest` íŽëì€ì íŹíšë í
ì€ížë„Œ íìží ì ìì”ëë€.
+
+```bash
+pytest tests/test_optimization.py::OptimizationTest --collect-only -q
+```
+
+í€ìë ííìì ìŹì©íìŹ í
ì€ížë„Œ ì€íí ìë ìì”ëë€.
+
+`adam`ìŽëŒë ìŽëŠì íŹíšíë í
ì€ížë§ ì€ííë €ë©Ž ë€ìêłŒ ê°ì”ëë€:
+
+```bash
+pytest -k adam tests/test_optimization.py
+```
+
+ë
ŒëŠŹ ì°ì°ì `and`ì `or`넌 ìŹì©íìŹ ëȘšë í€ìëê° ìŒìčíŽìŒ íëì§ ëë ìŽë íëê° ìŒìčíŽìŒ íëì§ë„Œ ëíëŒ ì ìì”ëë€.
+`not`ì ë¶ì í ë ìŹì©í ì ìì”ëë€.
+
+`adam`ìŽëŒë ìŽëŠì íŹíšíì§ ìë ëȘšë í
ì€ížë„Œ ì€ííë €ë©Ž ë€ìêłŒ ê°ì”ëë€:
+
+```bash
+pytest -k "not adam" tests/test_optimization.py
+```
+
+ë ê°ì§ íšíŽì íëëĄ êȰí©í ìë ìì”ëë€:
+
+```bash
+pytest -k "ada and not adam" tests/test_optimization.py
+```
+
+ì넌 ë€ìŽ `test_adafactor`ì `test_adam_w`넌 ëȘšë ì€ííë €ë©Ž ë€ìì ìŹì©í ì ìì”ëë€:
+
+```bash
+pytest -k "test_adam_w or test_adam_w" tests/test_optimization.py
+```
+
+ìŹêž°ì `or`넌 ìŹì©íë êČì ì ìíìžì. ë í€ìë ì€ íëê° ìŒìčíëëĄ íêž° ìí ëȘ©ì ìŒëĄ ìŹì©íêž° ë돞ì
ëë€.
+
+ë íšíŽìŽ ëȘšë íŹíšëìŽìŒ íë í
ì€ížë§ ì€ííë €ë©Ž, `and`넌 ìŹì©íŽìŒ í©ëë€:
+
+```bash
+pytest -k "test and ada" tests/test_optimization.py
+```
+
+### `accelerate` í
ì€íž ì€í[[run-`accelerate`-tests]]
+
+ëȘšëžìì `accelerate` í
ì€ížë„Œ ì€ííŽìŒ í ëê° ìì”ëë€. ìŽë„Œ ìíŽìë ëȘ
ë čìŽì `-m accelerate_tests`넌 ì¶ê°í멎 ë©ëë€.
+ì넌 ë€ìŽ, `OPT`ìì ìŽëŹí í
ì€ížë„Œ ì€ííë €ë©Ž ë€ìêłŒ ê°ì”ëë€:
+```bash
+RUN_SLOW=1 pytest -m accelerate_tests tests/models/opt/test_modeling_opt.py
+```
+
+### 돞ì í
ì€íž ì€í[[run-documentation-tests]]
+
+ìì 돞ìê° ìŹë°ë„žì§ í
ì€ížíë €ë©Ž `doctests`ê° í”êłŒíëì§ íìžíŽìŒ í©ëë€.
+ì넌 ë€ìŽ, [`WhisperModel.forward`'s docstring](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/modeling_whisper.py#L1017-L1035)넌 ìŹì©íŽ ëŽ
ìë€:
+
+```python
+r"""
+Returns:
+
+Example:
+ ```python
+ >>> import torch
+ >>> from transformers import WhisperModel, WhisperFeatureExtractor
+ >>> from datasets import load_dataset
+
+ >>> model = WhisperModel.from_pretrained("openai/whisper-base")
+ >>> feature_extractor = WhisperFeatureExtractor.from_pretrained("openai/whisper-base")
+ >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
+ >>> inputs = feature_extractor(ds[0]["audio"]["array"], return_tensors="pt")
+ >>> input_features = inputs.input_features
+ >>> decoder_input_ids = torch.tensor([[1, 1]]) * model.config.decoder_start_token_id
+ >>> last_hidden_state = model(input_features, decoder_input_ids=decoder_input_ids).last_hidden_state
+ >>> list(last_hidden_state.shape)
+ [1, 2, 512]
+ ```"""
+
+```
+
+ìíë íìŒì ëȘšë docstring ìì 넌 ìëìŒëĄ í
ì€ížíë €ë©Ž ë€ì ëȘ
ë čì ì€íí멎 ë©ëë€:
+```bash
+pytest --doctest-modules
+```
+íìŒì íì„ìê° markdownìž êČœì° `--doctest-glob="*.md"` ìžì넌 ì¶ê°íŽìŒ í©ëë€.
+
+### ìì ë í
ì€ížë§ ì€í[[run-only-modified-tests]]
+
+ìì ë íìŒ ëë íìŹ ëžëìč (Git êž°ì€)ì êŽë šë í
ì€ížë„Œ ì€ííë €ë©Ž [pytest-picked](https://github.com/anapaulagomes/pytest-picked)ì ìŹì©í ì ìì”ëë€.
+ìŽë ëłêČœí ëŽì©ìŽ í
ì€ížì ìí„ì ìŁŒì§ ììëì§ ëč 넎êČ íìží ì ìë ìąì ë°©ëČì
ëë€.
+
+```bash
+pip install pytest-picked
+```
+
+```bash
+pytest --picked
+```
+
+ìì ëìì§ë§, ìì§ ì»€ë°ëì§ ìì ëȘšë íìŒ ë° íŽëìì í
ì€ížê° ì€íë©ëë€.
+
+### ìì€ ìì ì ì€íší í
ì€íž ìë ìŹì€í[[automatically-rerun-failed-tests-on-source-modification]]
+
+[pytest-xdist](https://github.com/pytest-dev/pytest-xdist)ë ëȘšë ì€íší í
ì€ížë„Œ ê°ì§íêł ,
+íìŒì ìì í íì íìŒì êłì ìŹì€ííìŹ í
ì€ížê° ì±êł”í ëêčì§ êž°ë€ëŠŹë ë§€ì° ì ì©í êž°ë„ì ì êł”í©ëë€.
+ë°ëŒì ìì í ëŽì©ì íìží í pytest넌 ë€ì ììí íìê° ìì”ëë€.
+ëȘšë í
ì€ížê° í”êłŒë ëêčì§ ìŽ êłŒì ì ë°ëł”í í ë€ì ì ìČŽ ì€íìŽ ìŽëŁšìŽì§ëë€.
+
+```bash
+pip install pytest-xdist
+```
+
+ìŹê·ì ëȘšëì ìŹì©: `pytest -f` ëë `pytest --looponfail`
+
+íìŒì ëłêČœ ìŹíì `looponfailroots` ëŁšíž ëë í°ëŠŹì íŽëč ëŽì©ì (ìŹê·ì ìŒëĄ) íìžíìŹ ê°ì§ë©ëë€.
+ìŽ ê°ì êž°ëłžê°ìŽ ìëíì§ ìë êČœì°,
+`setup.cfg`ì ì€ì ì”ì
ì ëłêČœíìŹ íëĄì ížìì ëłêČœí ì ìì”ëë€:
+
+```ini
+[tool:pytest]
+looponfailroots = transformers tests
+```
+
+ëë `pytest.ini`/``tox.ini`` íìŒ:
+
+```ini
+[pytest]
+looponfailroots = transformers tests
+```
+
+ìŽë êČ í멎 ini-fileì ëë í°ëŠŹë„Œ êž°ì€ìŒëĄ ìëì ìŒëĄ ì§ì ë ê° ëë í°ëŠŹìì íìŒ ëłêČœ ìŹíë§ ì°ŸêČ ë©ëë€.
+
+
+ìŽ êž°ë„ì ëìČŽí ì ìë ê”Źí ë°©ëČìž [pytest-watch](https://github.com/joeyespo/pytest-watch)ë ìì”ëë€.
+
+
+### íčì í
ì€íž ëȘšë 걎ëë°êž°[[skip-a-test-module]]
+
+ëȘšë í
ì€íž ëȘšëì ì€ííë íčì ëȘšëì ì ìžíë €ë©Ž, ì€íí í
ì€íž ëȘ©ëĄì ëȘ
ìì ìŒëĄ ì§ì í ì ìì”ëë€.
+ì넌 ë€ìŽ, `test_modeling_*.py` í
ì€ížë„Œ ì ìží ëȘšë í
ì€ížë„Œ ì€ííë €ë©Ž ë€ìì ìŹì©í ì ìì”ëë€:
+
+```bash
+pytest *ls -1 tests/*py | grep -v test_modeling*
+```
+
+### ìí ìŽêž°í[[clearing state]]
+
+CI ëčë ë° (ìëì ëí) êČ©ëŠŹê° ì€ìí êČœì°, ìșì넌 ì§ììŒ í©ëë€:
+
+```bash
+pytest --cache-clear tests
+```
+
+### í
ì€ížë„Œ ëłë ŹëĄ ì€í[[running-tests-in-parallel]]
+
+ìŽì ì ìžêží êČìČëŒ `make test`ë í
ì€ížë„Œ ëłë ŹëĄ ì€ííêž° ìíŽ
+`pytest-xdist` íëŹê·žìž(`-n X` ìžì, ì넌 ë€ìŽ `-n 2`넌 ìŹì©íìŹ 2ê°ì ëłë Ź ìì
ì€í)ì í”íŽ ì€íë©ëë€.
+
+`pytest-xdist`ì `--dist=` ì”ì
ì ìŹì©íìŹ í
ì€ížë„Œ ìŽë»êČ ê·žëŁčíí ì§ ì ìŽí ì ìì”ëë€.
+`--dist=loadfile`ì íëì íìŒì ìë í
ì€ížë„Œ ëìŒí íëĄìžì€ëĄ ê·žëŁčíí©ëë€.
+
+ì€íë í
ì€ížì ììê° ë€ë„Žêł ììžĄí ì ìêž° ë돞ì, `pytest-xdist`ëĄ í
ì€íž ì€ìížë„Œ ì€íí멎 ì€íšê° ë°ìí ì ìì”ëë€ (êČì¶ëì§ ìì êȰí©ë í
ì€ížê° ìë êČœì°).
+ìŽ êČœì° [pytest-replay](https://github.com/ESSS/pytest-replay)넌 ìŹì©í멎 ëìŒí ììëĄ í
ì€ížë„Œ ë€ì ì€ííŽì
+ì€íšíë ìíì€ë„Œ ì”ìííë ë°ì ëììŽ ë©ëë€.
+
+### í
ì€íž ììì ë°ëł”[[test-order-and-repetition]]
+
+ì ìŹì ìž ìą
ìì± ë° ìí êŽë š ëČê·ž(tear down)넌 ê°ì§íêž° ìíŽ
+í
ì€ížë„Œ ìŹëŹ ëČ, ì°ììŒëĄ, 돎ììëĄ ëë ìžížëĄ ë°ëł”íë êČìŽ ìąì”ëë€.
+ê·žëŠŹêł ì§ì ì ìž ìŹëŹ ëČì ë°ëł”ì DLì 돎ììì±ì ìíŽ ë°êČŹëë ìŒë¶ 돞ì 넌 ê°ì§íë ë°ìë ì ì©í©ëë€.
+
+
+#### í
ì€ížë„Œ ë°ëł”[[repeat-tests]]
+
+- [pytest-flakefinder](https://github.com/dropbox/pytest-flakefinder):
+
+```bash
+pip install pytest-flakefinder
+```
+
+ëȘšë í
ì€ížë„Œ ìŹëŹ ëČ ì€íí©ëë€(êž°ëłžê°ì 50ëČ):
+
+```bash
+pytest --flake-finder --flake-runs=5 tests/test_failing_test.py
+```
+
+
+
+ìŽ íëŹê·žìžì `pytest-xdist`ì `-n` íëê·žì íšê» ìëíì§ ìì”ëë€.
+
+
+
+
+
+`pytest-repeat`ëŒë ë ë€ë„ž íëŹê·žìžë ìì§ë§ `unittest`ì íšê» ìëíì§ ìì”ëë€.
+
+
+
+#### í
ì€ížë„Œ ììì ììëĄ ì€í[[run-tests-in-a-random-order]]
+
+```bash
+pip install pytest-random-order
+```
+
+ì€ì: `pytest-random-order`ê° ì€ìčë멎 í
ì€ížê° ìëìŒëĄ ììì ììëĄ ìì
ëë€.
+ê”Źì± ëłêČœìŽë 컀맚ë ëŒìž ì”ì
ìŽ íìíì§ ìì”ëë€.
+
+ìì ì€ëȘ
í êČìČëŒ ìŽë„Œ í”íŽ í í
ì€ížì ìíê° ë€ë„ž í
ì€ížì ìíì ìí„ì 믞ìčë êȰí©ë í
ì€ížë„Œ ê°ì§í ì ìì”ëë€.
+`pytest-random-order`ê° ì€ìčë멎 íŽëč ìžì
ìì ìŹì©ë ëë€ ìëê° ì¶ë „ëë©° ì넌 ë€ìŽ ë€ìêłŒ ê°ì”ëë€:
+
+```bash
+pytest tests
+[...]
+Using --random-order-bucket=module
+Using --random-order-seed=573663
+```
+
+ë°ëŒì íčì ìíì€ê° ì€íšíë êČœì°ìë ì íí ìë넌 ì¶ê°íìŹ ìŹíí ì ìì”ëë€. ì넌 ë€ìŽ ë€ìêłŒ ê°ì”ëë€:
+
+```bash
+pytest --random-order-seed=573663
+[...]
+Using --random-order-bucket=module
+Using --random-order-seed=573663
+```
+
+ì íí ëìŒí í
ì€íž ëȘ©ëĄ(ëë ëȘ©ëĄìŽ ìì)ì ìŹì©íë êČœì°ìë§ ì íí ìì넌 ìŹíí©ëë€.
+ëȘ©ëĄì ìëìŒëĄ ìąíêž° ììí멎 ë ìŽì ìëì ììĄŽí ì ìêł ì€íšíë ì íí ììëĄ ìëìŒëĄ ëȘ©ëĄì ëìŽíŽìŒí©ëë€. ê·žëŠŹêł `--random-order-bucket=none`ì ìŹì©íìŹ pytestìêČ ìì넌 ììëĄ ì€ì íì§ ìëëĄ ìë €ìŒ í©ëë€.
+ì넌 ë€ìŽ ë€ìêłŒ ê°ì”ëë€:
+
+```bash
+pytest --random-order-bucket=none tests/test_a.py tests/test_c.py tests/test_b.py
+```
+
+ëȘšë í
ì€ížì ëíŽ ìꞰ넌 ëčíì±ííë €ë©Ž ë€ìêłŒ ê°ì”ëë€:
+
+```bash
+pytest --random-order-bucket=none
+```
+
+êž°ëłžì ìŒëĄ `--random-order-bucket=module`ìŽ ëŽìŹëìŽ ììŒëŻëĄ, ëȘšë ìì€ìì íìŒì ìì”ëë€.
+ëí `class`, `package`, `global` ë° `none` ìì€ììë ìì ì ìì”ëë€.
+ììží ëŽì©ì íŽëč [돞ì](https://github.com/jbasko/pytest-random-order)넌 ì°žìĄ°íìžì.
+
+ë ë€ë„ž 돎ììíì ëìì [`pytest-randomly`](https://github.com/pytest-dev/pytest-randomly)ì
ëë€.
+ìŽ ëȘšëì ë§€ì° ì ìŹí êž°ë„/ìží°íìŽì€ë„Œ ê°ì§êł ìì§ë§, `pytest-random-order`ì ìë ëČí· ëȘšë넌 ìŹì©í ìë ìì”ëë€.
+ì€ìč íìë ìëìŒëĄ ì ì©ëë 돞ì ë ëìŒíêČ ê°ì§ëë€.
+
+### ìžêŽêłŒ ëëì ëłêČœ[[look-and-feel-variations]
+
+#### pytest-sugar ìŹì©[[pytest-sugar]]
+
+[pytest-sugar](https://github.com/Frozenball/pytest-sugar)ë í
ì€ížê° 볎ìŹì§ë íí넌 ê°ì íêł ,
+ì§í ìí© ë°ë„Œ ì¶ê°íë©°, ì€íší í
ì€ížì êČìŠì ìŠì íìíë íëŹê·žìžì
ëë€. ì€ìčí멎 ìëìŒëĄ íì±íë©ëë€.
+
+```bash
+pip install pytest-sugar
+```
+
+pytest-sugar ììŽ í
ì€ížë„Œ ì€ííë €ë©Ž ë€ìêłŒ ê°ì”ëë€:
+
+```bash
+pytest -p no:sugar
+```
+
+ëë ì ê±°íìžì.
+
+
+
+#### ê° íì í
ì€íž ìŽëŠêłŒ ì§í ìí© ëłŽêł [[report-each-sub-test-name-and-its-progress]]
+
+`pytest`넌 í”íŽ ëšìŒ ëë ê·žëŁčì í
ì€ížë„Œ ì€ííë êČœì°(`pip install pytest-pspec` ìŽí):
+
+```bash
+pytest --pspec tests/test_optimization.py
+```
+
+#### ì€íší í
ì€íž ìŠì íì[[instantly-shows-failed-tests]]
+
+[pytest-instafail](https://github.com/pytest-dev/pytest-instafail)ì í
ì€íž ìžì
ì ëêčì§ êž°ë€ëŠŹì§ ìêł
+ì€íš ë° ì€ë„넌 ìŠì íìí©ëë€.
+
+```bash
+pip install pytest-instafail
+```
+
+```bash
+pytest --instafail
+```
+
+### GPU ìŹì© ìŹë¶[[to-GPU-or-not-to-GPU]]
+
+GPUê° íì±íë íêČœìì, CPU ì ì© ëȘšëëĄ í
ì€ížíë €ë©Ž `CUDA_VISIBLE_DEVICES=""`넌 ì¶ê°í©ëë€:
+
+```bash
+CUDA_VISIBLE_DEVICES="" pytest tests/test_logging.py
+```
+
+ëë ë€ì€ GPUê° ìë êČœì° `pytest`ìì ìŹì©í GPU넌 ì§ì í ìë ìì”ëë€.
+ì넌 ë€ìŽ, GPU `0` ë° `1`ìŽ ìë êČœì° ë€ìì ì€íí ì ìì”ëë€:
+
+```bash
+CUDA_VISIBLE_DEVICES="1" pytest tests/test_logging.py
+```
+
+ìŽë êČ í멎 ë€ë„ž GPUìì ë€ë„ž ìì
ì ì€ííë €ë êČœì° ì ì©í©ëë€.
+
+ìŒë¶ í
ì€ížë ë°ëì CPU ì ì©ìŒëĄ ì€ííŽìŒ íë©°, ìŒë¶ë CPU ëë GPU ëë TPUìì ì€ííŽìŒ íêł , ìŒë¶ë ìŹëŹ GPUìì ì€ííŽìŒ í©ëë€.
+ë€ì ì€í” ë°ìœë ìŽí°ë í
ì€ížì ìê”Ź ìŹíì CPU/GPU/TPUëłëĄ ì€ì íë ë° ìŹì©ë©ëë€:
+
+- `require_torch` - ìŽ í
ì€ížë torchììë§ ì€íë©ëë€.
+- `require_torch_gpu` - `require_torch`ì ì¶ê°ëĄ ì ìŽë 1ê°ì GPUê° íìí©ëë€.
+- `require_torch_multi_gpu` - `require_torch`ì ì¶ê°ëĄ ì ìŽë 2ê°ì GPUê° íìí©ëë€.
+- `require_torch_non_multi_gpu` - `require_torch`ì ì¶ê°ëĄ 0ê° ëë 1ê°ì GPUê° íìí©ëë€.
+- `require_torch_up_to_2_gpus` - `require_torch`ì ì¶ê°ëĄ 0ê°, 1ê° ëë 2ê°ì GPUê° íìí©ëë€.
+- `require_torch_tpu` - `require_torch`ì ì¶ê°ëĄ ì ìŽë 1ê°ì TPUê° íìí©ëë€.
+
+GPU ìê”Ź ìŹíì íëĄ ì 늏í멎 ìëì ê°ì”ëëă
:
+
+
+| n gpus | decorator |
+|--------+--------------------------------|
+| `>= 0` | `@require_torch` |
+| `>= 1` | `@require_torch_gpu` |
+| `>= 2` | `@require_torch_multi_gpu` |
+| `< 2` | `@require_torch_non_multi_gpu` |
+| `< 3` | `@require_torch_up_to_2_gpus` |
+
+
+ì넌 ë€ìŽ, 2ê° ìŽìì GPUê° ìêł pytorchê° ì€ìčëìŽ ìì ëìë§ ì€íëìŽìŒ íë í
ì€ížë ë€ìêłŒ ê°ì”ëë€:
+
+```python no-style
+@require_torch_multi_gpu
+def test_example_with_multi_gpu():
+```
+
+`tensorflow`ê° íìí êČœì° `require_tf` ë°ìœë ìŽí°ë„Œ ìŹì©í©ëë€. ì넌 ë€ìŽ ë€ìêłŒ ê°ì”ëë€:
+
+```python no-style
+@require_tf
+def test_tf_thing_with_tensorflow():
+```
+
+ìŽëŹí ë°ìœë ìŽí°ë ì€ìČ©ë ì ìì”ëë€.
+ì넌 ë€ìŽ, ë늰 í
ì€ížëĄ ì§íëêł pytorchìì ì ìŽë íëì GPUê° íìí êČœì° ë€ìêłŒ ê°ìŽ ì€ì í ì ìì”ëë€:
+
+```python no-style
+@require_torch_gpu
+@slow
+def test_example_slow_on_gpu():
+```
+
+`@parametrized`ì ê°ì ìŒë¶ ë°ìœë ìŽí°ë í
ì€íž ìŽëŠì ë€ì ìì±íêž° ë돞ì `@require_*` ì€í” ë°ìœë ìŽí°ë ìŹë°ë„ŽêČ ìëíë €ë©Ž íì ë§š ë§ì§ë§ì ëìŽëìŽìŒ í©ëë€.
+ë€ìì ìŹë°ë„ž ìŹì© ìì
ëë€:
+
+```python no-style
+@parameterized.expand(...)
+@require_torch_multi_gpu
+def test_integration_foo():
+```
+
+`@pytest.mark.parametrize`ìë ìŽëŹí ìì 돞ì ë ììŒëŻëĄ ìČì íčì ë§ì§ë§ì ììčìíŹ ì ìêł ìŽëŹí êČœì°ìë ì ìëí êČì
ëë€.
+íì§ë§ unittestê° ìë êČœì°ìë§ ìëí©ëë€.
+
+í
ì€íž ëŽë¶ìì ë€ìì ìŹì©í ì ìì”ëë€:
+
+- ìŹì© ê°ë„í GPU ì:
+
+```python
+from transformers.testing_utils import get_gpu_count
+
+n_gpu = get_gpu_count() #torchì tfì íšê» ìë
+```
+
+### ë¶ì° íë š[[distributed-training]]
+
+`pytest`ë ë¶ì° íë šì ì§ì ì ìŒëĄ ë€ëŁšì§ ëȘ»í©ëë€.
+ìŽë„Œ ìëí멎 íì íëĄìžì€ê° ìŹë°ë„ž ìì
ì ìííì§ ìêł `pytest`ëŒêł ìê°íêž°ì í
ì€íž ì€ìížë„Œ ë°ëł”íŽì ì€ííêČ ë©ëë€.
+ê·žëŹë ìŒë° íëĄìžì€ë„Œ ìì±í ë€ì ìŹëŹ ì컀넌 ìì±íêł IO íìŽí넌 êŽëŠŹíëëĄ í멎 ëìí©ëë€.
+
+ë€ìì ìŹì© ê°ë„í í
ì€ížì
ëë€:
+
+- [test_trainer_distributed.py](https://github.com/huggingface/transformers/tree/main/tests/trainer/test_trainer_distributed.py)
+- [test_deepspeed.py](https://github.com/huggingface/transformers/tree/main/tests/deepspeed/test_deepspeed.py)
+
+ì€í ì§ì ìŒëĄ ë°ëĄ ìŽëíë €ë©Ž, íŽëč í
ì€ížìì `execute_subprocess_async` ížì¶ì êČìíìžì.
+
+ìŽëŹí í
ì€ížë„Œ ì€ííë €ë©Ž ì ìŽë 2ê°ì GPUê° íìí©ëë€.
+
+```bash
+CUDA_VISIBLE_DEVICES=0,1 RUN_SLOW=1 pytest -sv tests/test_trainer_distributed.py
+```
+
+### ì¶ë „ ìșĄìČ[[output-capture]]
+
+í
ì€íž ì€í ì€ `stdout` ë° `stderr`ëĄ ì ìĄë ëȘšë ì¶ë „ìŽ ìșĄìČë©ëë€.
+í
ì€ížë ì€ì ë©ìëê° ì€íší멎 ìșĄìČë ì¶ë „ì ìŒë°ì ìŒëĄ ì€íš ì¶ì ì 볎ì íšê» íìë©ëë€.
+
+ì¶ë „ ìșĄìČ넌 ëčíì±ííêł `stdout` ë° `stderr`넌 ì ìì ìŒëĄ ë°ìŒë €ë©Ž `-s` ëë `--capture=no`넌 ìŹì©íìžì:
+
+```bash
+pytest -s tests/test_logging.py
+```
+
+í
ì€íž êČ°êłŒë„Œ JUnit íìì ì¶ë „ìŒëĄ 볎ëŽë €ë©Ž ë€ìì ìŹì©íìžì:
+
+```bash
+py.test tests --junitxml=result.xml
+```
+
+### ìì ìĄ°ì [[color-control]]
+
+ìììŽ ìêČ íë €ë©Ž ë€ìêłŒ ê°ìŽ ì€ì íìžì(ì넌 ë€ìŽ í°ì ë°°êČœì ë
žëì êžìšë ê°ë
ì±ìŽ ìąì§ ìì”ëë€):
+
+```bash
+pytest --color=no tests/test_logging.py
+```
+
+### online pastebin serviceì í
ì€íž ëłŽêł ì ì ìĄ[[sending test report to online pastebin service]]
+
+ê° í
ì€íž ì€íšì ëí URLì ë§ëëë€:
+
+```bash
+pytest --pastebin=failed tests/test_logging.py
+```
+
+ìŽë êČ í멎 ê° ì€íšì ëí URLì ì êł”íë remote Paste serviceì í
ì€íž ì€í ì ëłŽë„Œ ì ì¶í©ëë€.
+ìŒë°ì ìž í
ì€ížë„Œ ì íí ìë ìêł íčì íčì ì€íšë§ 볎ëŽë €ë©Ž `-x`ì ê°ìŽ ì¶ê°í ìë ìì”ëë€.
+
+ì ìČŽ í
ì€íž ìžì
ëĄê·žì ëí URLì ìì±í©ëë€:
+
+```bash
+pytest --pastebin=all tests/test_logging.py
+```
+
+## í
ì€íž ìì±[[writing-tests]]
+
+đ€ transformers í
ì€ížë ëë¶ë¶ `unittest`넌 êž°ë°ìŒëĄ íì§ë§,
+`pytest`ìì ì€íëëŻëĄ ëë¶ë¶ì êČœì° ë ìì€í
ì êž°ë„ì ìŹì©í ì ìì”ëë€.
+
+ì§ìëë êž°ë„ì ëíŽ [ìŹêž°](https://docs.pytest.org/en/stable/unittest.html)ìì íìží ì ìì§ë§,
+êž°ì”íŽìŒ í ì€ìí ì ì ëë¶ë¶ì `pytest` fixtureê° ìëíì§ ìëë€ë êČì
ëë€.
+íëŒëŻží°íë ìëíì§ ìì§ë§, ì°ëŠŹë ëčì·í ë°©ììŒëĄ ìëíë `parameterized` ëȘšëì ìŹì©í©ëë€.
+
+
+### ë§€ê°ëłìí[[parametrization]]
+
+ëìŒí í
ì€ížë„Œ ë€ë„ž ìžìëĄ ìŹëŹ ëČ ì€ííŽìŒ íë êČœì°ê° ìą
ìą
ìì”ëë€.
+í
ì€íž ëŽìì ìŽ ìì
ì ìíí ì ìì§ë§, ê·žë êČ í멎 íëì ìžì ìžížì ëíŽ í
ì€ížë„Œ ì€íí ì ìì”ëë€.
+
+```python
+# test_this1.py
+import unittest
+from parameterized import parameterized
+
+
+class TestMathUnitTest(unittest.TestCase):
+ @parameterized.expand(
+ [
+ ("negative", -1.5, -2.0),
+ ("integer", 1, 1.0),
+ ("large fraction", 1.6, 1),
+ ]
+ )
+ def test_floor(self, name, input, expected):
+ assert_equal(math.floor(input), expected)
+```
+
+ìŽì êž°ëłžì ìŒëĄ ìŽ í
ì€ížë `test_floor`ì ë§ì§ë§ 3ê° ìžìê°
+ë§€ê°ëłì ëȘ©ëĄì íŽëč ìžìì í ëčëë êČìŒëĄ 3ëČ ì€íë êČì
ëë€.
+
+ê·žëŠŹêł `negative` ë° `integer` ë§€ê°ëłì ì§í©ë§ ì€ííë €ë©Ž ë€ìêłŒ ê°ìŽ ì€íí ì ìì”ëë€:
+
+```bash
+pytest -k "negative and integer" tests/test_mytest.py
+```
+
+ëë `negative` íì í
ì€ížë„Œ ì ìží ëȘšë ìëž í
ì€ížë„Œ ë€ìêłŒ ê°ìŽ ì€íí ì ìì”ëë€:
+
+```bash
+pytest -k "not negative" tests/test_mytest.py
+```
+
+ììì ìžêží `-k` íí°ë„Œ ìŹì©íë êČ ìžìë,
+ê° ìëž í
ì€ížì ì íí ìŽëŠì íìží íì ìŒë¶ íčì ì ìČŽ ìëž í
ì€ížë„Œ ì€íí ì ìì”ëë€.
+
+```bash
+pytest test_this1.py --collect-only -q
+```
+
+ê·žëŠŹêł ë€ìì ëŽì©ì íìží ì ìì êČì
ëë€:
+
+```bash
+test_this1.py::TestMathUnitTest::test_floor_0_negative
+test_this1.py::TestMathUnitTest::test_floor_1_integer
+test_this1.py::TestMathUnitTest::test_floor_2_large_fraction
+```
+
+2ê°ì íčì í ìëž í
ì€ížë§ ì€íí ìë ìì”ëë€:
+
+```bash
+pytest test_this1.py::TestMathUnitTest::test_floor_0_negative test_this1.py::TestMathUnitTest::test_floor_1_integer
+```
+
+`transformers`ì ê°ë°ì ìą
ìì±ì ìŽëŻž ìë [parameterized](https://pypi.org/project/parameterized/) ëȘšëì
+`unittests`ì `pytest` í
ì€íž ëȘšëìì ìëí©ëë€.
+
+ê·žëŹë í
ì€ížê° `unittest`ê° ìë êČœì° `pytest.mark.parametrize`넌 ìŹì©í ì ìì”ëë€(ìŽëŻž ìë ìŒë¶ í
ì€ížìì ìŹì©ëë êČœì°ë ìì”ëë€.
+ìŁŒëĄ `examples` íìì ìì”ëë€).
+
+ë€ìì `pytest`ì `parametrize` ë§ì»€ë„Œ ìŹì©í ëìŒí ìì
ëë€:
+
+```python
+# test_this2.py
+import pytest
+
+
+@pytest.mark.parametrize(
+ "name, input, expected",
+ [
+ ("negative", -1.5, -2.0),
+ ("integer", 1, 1.0),
+ ("large fraction", 1.6, 1),
+ ],
+)
+def test_floor(name, input, expected):
+ assert_equal(math.floor(input), expected)
+```
+
+`parameterized`ì ë§ì°Źê°ì§ëĄ `pytest.mark.parametrize`넌 ìŹì©í멎
+`-k` íí°ê° ìëíì§ ìë êČœì°ìë ì€íí ìëž í
ì€ížë„Œ ì ííêČ ì§ì í ì ìì”ëë€.
+ëš, ìŽ ë§€ê°ëłìí íšìë ìëž í
ì€ížì ìŽëŠ ì§í©ì ìœê° ë€ë„ŽêČ ìì±í©ëë€. ë€ìêłŒ ê°ì ëȘšì”ì
ëë€:
+
+```bash
+pytest test_this2.py --collect-only -q
+```
+
+ê·žëŠŹêł ë€ìì ëŽì©ì íìží ì ìì êČì
ëë€:
+
+```bash
+test_this2.py::test_floor[integer-1-1.0]
+test_this2.py::test_floor[negative--1.5--2.0]
+test_this2.py::test_floor[large fraction-1.6-1]
+```
+
+íčì í í
ì€ížì ëíŽìë§ ì€íí ìë ìì”ëë€:
+
+```bash
+pytest test_this2.py::test_floor[negative--1.5--2.0] test_this2.py::test_floor[integer-1-1.0]
+```
+
+ìŽì ì ììì ê°ìŽ ì€íí ì ìì”ëë€.
+
+
+
+### íìŒ ë° ëë í°ëŠŹ[[files-and-directories]]
+
+í
ì€ížìì ìą
ìą
íìŹ í
ì€íž íìŒêłŒ êŽë šë ìëì ìž ììč넌 ìììŒ íë êČœì°ê° ìì”ëë€.
+í
ì€ížê° ìŹëŹ ëë í°ëŠŹìì ížì¶ëê±°ë êčìŽê° ë€ë„ž íì ëë í°ëŠŹì ìì ì ìêž° ë돞ì ê·ž ììč넌 ìë êČì ê°ëšíì§ ìì”ëë€.
+`transformers.test_utils.TestCasePlus`ëŒë íŹíŒ íŽëì€ë ëȘšë êž°ëłž êČœëĄë„Œ ìČ늏íêł ê°ëší ìĄìžì넌 ì êł”íìŹ ìŽ ëŹžì 넌 íŽêȰí©ëë€:
+
+
+- `pathlib` ê°ìČŽ(ìì í ì íŽì§ êČœëĄ)
+
+ - `test_file_path` - íìŹ í
ì€íž íìŒ êČœëĄ (ì: `__file__`)
+ - test_file_dir` - íìŹ í
ì€íž íìŒìŽ íŹíšë ëë í°ëŠŹ
+ - tests_dir` - `tests` í
ì€íž ì€ìížì ëë í°ëŠŹ
+ - examples_dir` - `examples` í
ì€íž ì€ìížì ëë í°ëŠŹ
+ - repo_root_dir` - ì ì„ì ëë í°ëŠŹ
+ - src_dir` - `src`ì ëë í°ëŠŹ(ì: `transformers` íì ëë í°ëŠŹê° ìë êłł)
+
+- 돞ììŽëĄ ëłíë êČœëĄ---ìì ëìŒíì§ë§, `pathlib` ê°ìČŽê° ìë 돞ììŽëĄ êČœëĄë„Œ ë°íí©ëë€:
+
+ - `test_file_path_str`
+ - `test_file_dir_str`
+ - `tests_dir_str`
+ - `examples_dir_str`
+ - `repo_root_dir_str`
+ - `src_dir_str`
+
+ìì ëŽì©ì ìŹì©íë €ë©Ž í
ì€ížê° 'transformers.test_utils.TestCasePlus'ì ìëžíŽëì€ì ìëì§ íìžíŽìŒ í©ëë€.
+ì넌 ë€ìŽ ë€ìêłŒ ê°ì”ëë€:
+
+```python
+from transformers.testing_utils import TestCasePlus
+
+
+class PathExampleTest(TestCasePlus):
+ def test_something_involving_local_locations(self):
+ data_dir = self.tests_dir / "fixtures/tests_samples/wmt_en_ro"
+```
+
+ë§ìœ `pathlib`넌 í”íŽ êČœëĄë„Œ ìĄ°ìí íìê° ìê±°ë êČœëĄë„Œ 돞ììŽëĄë§ íìëĄ íë êČœì°ìë `pathlib` ê°ìČŽì `str()`ì ížì¶íê±°ë `_str`ëĄ ëëë ì ê·Œì넌 ìŹì©í ì ìì”ëë€.
+ì넌 ë€ìŽ ë€ìêłŒ ê°ì”ëë€:
+
+```python
+from transformers.testing_utils import TestCasePlus
+
+
+class PathExampleTest(TestCasePlus):
+ def test_something_involving_stringified_locations(self):
+ examples_dir = self.examples_dir_str
+```
+
+### ìì íìŒ ë° ëë í°ëŠŹ[[temporary-files-and-directories]]
+
+êł ì í ìì íìŒ ë° ëë í°ëŠŹë„Œ ìŹì©íë êČì ëłë Ź í
ì€íž ì€íì ììŽ íìì ì
ëë€.
+ìŽë êČ íšìŒëĄìš í
ì€ížë€ìŽ ìëĄì ë°ìŽí°ë„Œ ëźìŽì°ì§ ìêČ í ì ìì”ëë€. ëí ì°ëŠŹë ìì±ë í
ì€ížì ìą
ëŁ ëšêłìì ìŽëŹí ìì íìŒ ë° ëë í°ëŠŹë„Œ ì ê±°íêł ì¶ì”ëë€.
+ë°ëŒì ìŽëŹí ìê”Ź ìŹíì ì¶©ìĄ±ììŒìŁŒë `tempfile`êłŒ ê°ì íší€ì§ë„Œ ìŹì©íë êČìŽ ì€ìí©ëë€.
+
+ê·žëŹë í
ì€ížë„Œ ëëČêč
í ëë ìì íìŒìŽë ëë í°ëŠŹì ë€ìŽê°ë ëŽì©ì íìží ì ììŽìŒ íë©°,
+ìŹì€íëë ê° í
ì€ížë§ë€ ìì íìŒìŽë ëë í°ëŠŹì êČœëĄì ëíŽ ëŹŽìì ê°ìŽ ìë ì íí ê°ì ìêł ì¶ì êČì
ëë€.
+
+`transformers.test_utils.TestCasePlus`ëŒë ëì°ëŻž íŽëì€ë ìŽëŹí ëȘ©ì ì ê°ì„ ì í©í©ëë€.
+ìŽ íŽëì€ë `unittest.TestCase`ì íì íŽëì€ìŽëŻëĄ, ì°ëŠŹë ìŽêČì í
ì€íž ëȘšëìì ìœêČ ììí ì ìì”ëë€.
+
+ë€ìì íŽëč íŽëì€ë„Œ ìŹì©íë ììì
ëë€:
+
+```python
+from transformers.testing_utils import TestCasePlus
+
+
+class ExamplesTests(TestCasePlus):
+ def test_whatever(self):
+ tmp_dir = self.get_auto_remove_tmp_dir()
+```
+
+ìŽ ìœëë êł ì í ìì ëë í°ëŠŹë„Œ ìì±íêł `tmp_dir`ì íŽëč ììčëĄ ì€ì í©ëë€.
+
+- êł ì í ìì ëë í°ëŠŹë„Œ ìì±í©ëë€:
+
+```python
+def test_whatever(self):
+ tmp_dir = self.get_auto_remove_tmp_dir()
+```
+
+`tmp_dir`ìë ìì±ë ìì ëë í°ëŠŹì êČœëĄê° íŹíšë©ëë€.
+ìŽë í
ì€ížì ìą
ëŁ ëšêłìì ìëìŒëĄ ì ê±°ë©ëë€.
+
+- ì íí êČœëĄëĄ ìì ëë í°ëŠŹ ìì± íì í
ì€íž ìì ì ì ëčìŽ ìë ìíìžì§ íìžíêł , í
ì€íž íìë ëčì°ì§ ë§ìžì.
+
+```python
+def test_whatever(self):
+ tmp_dir = self.get_auto_remove_tmp_dir("./xxx")
+```
+
+ìŽêČì ëëČêč
í ë íčì ëë í°ëŠŹë„Œ ëȘšëí°ë§íêł ,
+ê·ž ëë í°ëŠŹì ìŽì ì ì€íë í
ì€ížê° ë°ìŽí°ë„Œ ëšêž°ì§ ìëëĄ íë ë°ì ì ì©í©ëë€.
+
+- `before` ë° `after` ìžì넌 ì§ì ì€ëČëŒìŽë©íìŹ êž°ëłž ëìì ëłêČœí ì ììŒë©°
+ë€ì ì€ íëì ëììŒëĄ ìŽìŽì§ëë€:
+
+ - `before=True`: í
ì€íž ìì ì ìì ëë í°ëŠŹê° íì ì§ìì§ëë€.
+ - `before=False`: ìì ëë í°ëŠŹê° ìŽëŻž ìĄŽìŹíë êČœì° êž°ìĄŽ íìŒì ê·žëëĄ ëšì”ëë€.
+ - `after=True`: í
ì€íž ìą
ëŁ ì ìì ëë í°ëŠŹê° íì ìì ë©ëë€.
+ - `after=False`: í
ì€íž ìą
ëŁ ì ìì ëë í°ëŠŹê° íì ê·žëëĄ ì ì§ë©ëë€.
+
+
+
+`rm -r`ì íŽëčíë ëȘ
ë čì ìì íêČ ì€ííêž° ìíŽ,
+ëȘ
ìì ìž `tmp_dir`ì ìŹì©íë êČœì° íëĄì íž ì ì„ì ìČŽíŹ ììì íì ëë í°ëŠŹë§ íì©ë©ëë€.
+ë°ëŒì ì€ìëĄ `/tmp`ê° ìë ì€ìí íìŒ ìì€í
ì ìŒë¶ê° ìì ëì§ ìëëĄ íì `./`ëĄ ììíë êČœëĄë„Œ ì ëŹíŽìŒ í©ëë€.
+
+
+
+
+
+ê° í
ì€ížë ìŹëŹ ê°ì ìì ëë í°ëŠŹë„Œ ë±ëĄí ì ììŒë©°,
+ëłëëĄ ììČíì§ ìë í ëȘšë ìëìŒëĄ ì ê±°ë©ëë€.
+
+
+
+### ìì sys.path ì€ëČëŒìŽë[[temporary-sys.path-override]]
+
+`sys.path`넌 ë€ë„ž í
ì€ížëĄ ììëĄ ì€ëČëŒìŽëíêž° ìíŽ ì넌 ë€ìŽ `ExtendSysPath` 컚í
ì€íž êŽëŠŹì넌 ìŹì©í ì ìì”ëë€.
+ì넌 ë€ìŽ ë€ìêłŒ ê°ì”ëë€:
+
+
+```python
+import os
+from transformers.testing_utils import ExtendSysPath
+
+bindir = os.path.abspath(os.path.dirname(__file__))
+with ExtendSysPath(f"{bindir}/.."):
+ from test_trainer import TrainerIntegrationCommon # noqa
+```
+
+### í
ì€íž 걎ëë°êž°[[skipping-tests]]
+
+ìŽêČì ëČê·žê° ë°êČŹëìŽ ìëĄìŽ í
ì€ížê° ìì±ëìì§ë§ ìì§ ê·ž ëČê·žê° ìì ëì§ ìì êČœì°ì ì ì©í©ëë€.
+ìŽ í
ì€ížë„Œ ìŁŒ ì ì„ìì 컀ë°íë €ë©Ž `make test` ì€ì 걎ëë°ëëĄ íŽìŒ í©ëë€.
+
+ë°©ëČ:
+
+- **skip**ì í
ì€ížê° ìŒë¶ ìĄ°ê±ŽìŽ ì¶©ìĄ±ë êČœì°ìë§ í”êłŒë êČìŒëĄ ììëêł , ê·žë ì§ ììŒë©Ž pytestê° ì ìČŽ í
ì€ížë„Œ 걎ëë°ìŽìŒ íšì ì믞í©ëë€.
+ìŒë°ì ìž ìëĄë Windowsê° ìë íë«íŒìì Windows ì ì© í
ì€ížë„Œ 걎ëë°ê±°ë
+ìžë¶ 늏ìì€(ì넌 ë€ìŽ ë°ìŽí°ëČ ìŽì€)ì ììĄŽíë í
ì€ížë„Œ 걎ëë°ë êČìŽ ìì”ëë€.
+
+- **xfail**ì í
ì€ížê° íčì í ìŽì ëĄ ìžíŽ ì€íší êČìŒëĄ ììíë êČì ì믞í©ëë€.
+ìŒë°ì ìž ìëĄë ìì§ ê”Źíëì§ ìì êž°ë„ìŽë ìì§ ìì ëì§ ìì ëČê·žì í
ì€ížê° ìì”ëë€.
+`xfail`ëĄ íìë í
ì€ížê° ììëëĄ ì€íšíì§ ìêł í”êłŒë êČœì°, ìŽêČì xpassìŽë©° í
ì€íž êČ°êłŒ ììœì êž°ëĄë©ëë€.
+
+ë ê°ì§ ì€ìí ì°šìŽì ì€ íëë `skip`ì í
ì€ížë„Œ ì€ííì§ ìì§ë§ `xfail`ì ì€ííë€ë êČì
ëë€.
+ë°ëŒì ì€ë„ê° ìë ìœëê° ìŒë¶ í
ì€ížì ìí„ì 믞ìč ì ìë êČœì° `xfail`ì ìŹì©íì§ ë§ìžì.
+
+#### ê”Źí[[implementation]]
+
+- ì ìČŽ í
ì€ížë„Œ ëŹŽìĄ°ê±Ž 걎ëë°ë €ë©Ž ë€ìêłŒ ê°ìŽ í ì ìì”ëë€:
+
+```python no-style
+@unittest.skip("this bug needs to be fixed")
+def test_feature_x():
+```
+
+ëë pytest넌 í”íŽ:
+
+```python no-style
+@pytest.mark.skip(reason="this bug needs to be fixed")
+```
+
+ëë `xfail` ë°©ììŒëĄ:
+
+```python no-style
+@pytest.mark.xfail
+def test_feature_x():
+```
+
+- í
ì€íž ëŽë¶ìì ëŽë¶ íìžì ë°ëŒ í
ì€ížë„Œ 걎ëë°ë ë°©ëČì ë€ìêłŒ ê°ì”ëë€:
+
+```python
+def test_feature_x():
+ if not has_something():
+ pytest.skip("unsupported configuration")
+```
+
+ëë ëȘšë ì ìČŽ:
+
+```python
+import pytest
+
+if not pytest.config.getoption("--custom-flag"):
+ pytest.skip("--custom-flag is missing, skipping tests", allow_module_level=True)
+```
+
+ëë `xfail` ë°©ììŒëĄ:
+
+```python
+def test_feature_x():
+ pytest.xfail("expected to fail until bug XYZ is fixed")
+```
+
+- importê° missingë ëȘšëìŽ ìì ë ê·ž ëȘšëì ëȘšë í
ì€ížë„Œ 걎ëë°ë ë°©ëČ:
+
+```python
+docutils = pytest.importorskip("docutils", minversion="0.3")
+```
+
+- ìĄ°ê±Žì ë°ëŒ í
ì€ížë„Œ 걎ëë°ë ë°©ëČ:
+
+```python no-style
+@pytest.mark.skipif(sys.version_info < (3,6), reason="requires python3.6 or higher")
+def test_feature_x():
+```
+
+ëë:
+
+```python no-style
+@unittest.skipIf(torch_device == "cpu", "Can't do half precision")
+def test_feature_x():
+```
+
+ëë ëȘšë ì ìČŽë„Œ 걎ëë°ë ë°©ëČ:
+
+```python no-style
+@pytest.mark.skipif(sys.platform == 'win32', reason="does not run on windows")
+class TestClass():
+ def test_feature_x(self):
+```
+
+ëłŽë€ ììží ìì ë° ë°©ëČì [ìŹêž°](https://docs.pytest.org/en/latest/skipping.html)ìì íìží ì ìì”ëë€.
+
+### ë늰 í
ì€íž[[slow-tests]]
+
+í
ì€íž ëŒìŽëžëŹëŠŹë ì§ìì ìŒëĄ íì„ëêł ììŒë©°, ìŒë¶ í
ì€ížë ì€ííë ë° ëȘ ë¶ìŽ ê±žëŠœëë€.
+ê·žëŠŹêł ì°ëŠŹìêČë í
ì€íž ì€ìížê° CI넌 í”íŽ ìëŁëêž°êčì§ í ìê°ì êž°ë€ëŠŽ ìŹì ê° ìì”ëë€.
+ë°ëŒì íì í
ì€ížë„Œ ìí ìŒë¶ ììžë„Œ ì ìžíêł ë늰 í
ì€ížë ë€ìêłŒ ê°ìŽ íìíŽìŒ í©ëë€.
+
+```python no-style
+from transformers.testing_utils import slow
+@slow
+def test_integration_foo():
+```
+
+`@slow`ëĄ íìë í
ì€ížë„Œ ì€ííë €ë©Ž `RUN_SLOW=1` íêČœ ëłì넌 ì€ì íìžì. ì넌 ë€ìŽ ë€ìêłŒ ê°ì”ëë€:
+
+```bash
+RUN_SLOW=1 pytest tests
+```
+
+`@parameterized`ì ê°ì ëȘ ê°ì§ ë°ìœë ìŽí°ë í
ì€íž ìŽëŠì ë€ì ìì±í©ëë€.
+ê·žëŹëŻëĄ `@slow`ì ëëšžì§ ê±Žëë°êž° ë°ìœë ìŽí° `@require_*`ê° ìŹë°ë„ŽêČ ìëëë €ë©Ž ë§ì§ë§ì ëìŽëìŽìŒ í©ëë€. ë€ìì ìŹë°ë„ž ìŹì© ìì
ëë€.
+
+```python no-style
+@parameterized.expand(...)
+@slow
+def test_integration_foo():
+```
+
+ìŽ ëŹžìì ìŽë°ë¶ì ì€ëȘ
ë êČìČëŒ ë늰 í
ì€ížë PRì CI íìžìŽ ìë ììœë ìŒì êž°ë°ìŒëĄ ì€íë©ëë€.
+ë°ëŒì PR ì ì¶ ì€ì ìŒë¶ 돞ì 넌 ëìč ì±ëĄ ëłí©ë ì ìì”ëë€.
+ìŽëŹí 돞ì ë€ì ë€ìëČì ìì ë CI ìì
ì€ì ê°ì§ë©ëë€.
+íì§ë§ PRì ì ì¶íêž° ì ì ìì ì 컎íší°ìì ë늰 í
ì€ížë„Œ ì€ííë êČ ëí ì€ìí©ëë€.
+
+ë늰 í
ì€ížëĄ íìíŽìŒ íëì§ ìŹë¶ë„Œ êȰì íë ëë”ì ìž êȰì êž°ì€ì ë€ìêłŒ ê°ì”ëë€.
+
+ë§ìœ í
ì€ížê° ëŒìŽëžëŹëŠŹì ëŽë¶ ê”Źì± ìì ì€ íëì ì§ì€ëìŽ ìë€ë©Ž(ì: ëȘšëžë§ íìŒ, í í°í íìŒ, íìŽíëŒìž),
+íŽëč í
ì€ížë„Œ ë늰 í
ì€íž ì€ìížìì ì€ííŽìŒ í©ëë€.
+ë§ìœ ëŒìŽëžëŹëŠŹì ë€ë„ž ìžĄë©Ž(ì: 돞ì ëë ìì )ì ì§ì€ëìŽ ìë€ë©Ž,
+íŽëč í
ì€ížë„Œ ë늰 í
ì€íž ì€ìížìì ì€ííŽìŒ í©ëë€. ê·žëŠŹêł ìŽ ì ê·Œ ë°©ìì 볎ìíêž° ìíŽ ììžë„Œ ë§ë€ìŽìŒ í©ëë€.
+
+- ëŹŽê±°ìŽ ê°ì€ìč ìžížë 50MBëłŽë€ í° ë°ìŽí°ì
ì ë€ìŽëĄëíŽìŒ íë ëȘšë í
ì€íž(ì: ëȘšëž í”í© í
ì€íž, í íŹëìŽì í”í© í
ì€íž, íìŽíëŒìž í”í© í
ì€íž)넌
+ ë늰 í
ì€ížëĄ ì€ì íŽìŒ í©ëë€.
+ ìëĄìŽ ëȘšëžì ì¶ê°íë êČœì° í”í© í
ì€ížì©ìŒëĄ 돎ìì ê°ì€ìčëĄ ìì ëČì ì ë§ë€ìŽ íëžì ì
ëĄëíŽìŒ í©ëë€.
+ ìŽ ëŽì©ì ìë ëšëœìì ì€ëȘ
ë©ëë€.
+- íčëłí ëč 넎êČ ì€íëëëĄ ì”ì íëì§ ìì íì”ì ìííŽìŒ íë í
ì€ížë ë늰 í
ì€ížëĄ ì€ì íŽìŒ í©ëë€.
+- ëëŠŹì§ ìììŒ í í
ì€íž ì€ ìŒë¶ê° ê·čëëĄ ë늰 êČœì°
+ ììžë„Œ ëì
íêł ìŽë„Œ `@slow`ëĄ ì€ì í ì ìì”ëë€.
+ ëì©ë íìŒì ëì€íŹì ì ì„íêł ë¶ëŹì€ë ìë ëȘšëžë§ í
ì€ížë `@slow`ìŒëĄ íìë í
ì€ížì ìąì ìì
ëë€.
+- CIìì 1ìŽ ìŽëŽì í
ì€ížê° ìëŁëë êČœì°(ë€ìŽëĄë íŹíš)ìë ë늰 í
ì€ížê° ìëìŽìŒ í©ëë€.
+
+ë늰 í
ì€ížê° ìë êČœì°ìë ë€ìí ëŽë¶ë„Œ ìì í 컀ëČí멎ì ëč 넎êČ ì ì§ëìŽìŒ í©ëë€.
+ì넌 ë€ìŽ, 돎ìì ê°ì€ìč넌 ìŹì©íìŹ íčëłí ìì±ë ìì ëȘšëžëĄ í
ì€íží멎 ìëčí 컀ëČ늏ì§ë„Œ ì»ì ì ìì”ëë€.
+ìŽëŹí ëȘšëžì ì”ìíì ë ìŽìŽ ì(ì: 2), ìŽí íŹêž°(ì: 1000) ë±ì ììë§ ê°ì§ëë€. ê·žë° ë€ì `@slow` í
ì€ížë ëí ë늰 ëȘšëžì ìŹì©íìŹ ì ì±ì ìž í
ì€ížë„Œ ìíí ì ìì”ëë€.
+ìŽëŹí ìì ëȘšëžì ìŹì©íë ë°©ëČì íìžíë €ë©Ž ë€ìêłŒ ê°ìŽ *tiny* ëȘšëžì ì°Ÿì볎ìžì.
+
+```bash
+grep tiny tests examples
+```
+
+ë€ìì ìì ëȘšëž[stas/tiny-wmt19-en-de](https://huggingface.co/stas/tiny-wmt19-en-de)ì ë§ë
+[script](https://github.com/huggingface/transformers/tree/main/scripts/fsmt/fsmt-make-tiny-model.py) ììì
ëë€.
+íčì ëȘšëžì ìí€í
ìČì ë§êČ ìœêČ ìĄ°ì í ì ìì”ëë€.
+
+ì넌 ë€ìŽ ëì©ë ëȘšëžì ë€ìŽëĄëíë êČœì° ë°íìì ìëȘ» ìžĄì íêž° ìœì§ë§,
+ëĄì»Źìì í
ì€íží멎 ë€ìŽëĄëí íìŒìŽ ìșìëìŽ ë€ìŽëĄë ìê°ìŽ ìžĄì ëì§ ìì”ëë€.
+ëì CI ëĄê·žì ì€í ìë ëłŽêł ì넌 íìžíìžì(`pytest --durations=0 tests`ì ì¶ë „).
+
+ìŽ ëłŽêł ìë ë늰 ìŽìê°ìŒëĄ íìëì§ ìê±°ë ëč 넎êČ ë€ì ìì±íŽìŒ íë ë늰 ìŽìê°ì ì°Ÿë ë°ë ì ì©í©ëë€.
+CIìì í
ì€íž ì€ìížê° ëë €ì§êž° ììí멎 ìŽ ëłŽêł ìì ë§š ì ëȘ©ëĄì ê°ì„ ë늰 í
ì€ížê° íìë©ëë€.
+
+
+
+### stdout/stderr ì¶ë „ í
ì€íž[[testing-the-stdout/stderr-output]]
+
+`stdout` ë°/ëë `stderr`ëĄ ì°ë íšì넌 í
ì€ížíë €ë©Ž `pytest`ì [capsys ìì€í
](https://docs.pytest.org/en/latest/capture.html)ì ìŹì©íìŹ íŽëč ì€ížëŠŒì ìĄìžì€í ì ìì”ëë€.
+ë€ìêłŒ ê°ìŽ ìíí ì ìì”ëë€.
+
+```python
+import sys
+
+
+def print_to_stdout(s):
+ print(s)
+
+
+def print_to_stderr(s):
+ sys.stderr.write(s)
+
+
+def test_result_and_stdout(capsys):
+ msg = "Hello"
+ print_to_stdout(msg)
+ print_to_stderr(msg)
+ out, err = capsys.readouterr() # ìșĄìČë ì¶ë „ ì€ížëŠŒ ìŹì©
+ # ì í ìŹí: ìșĄìČë ì€ížëŠŒ ìŹìì±
+ sys.stdout.write(out)
+ sys.stderr.write(err)
+ # í
ì€íž:
+ assert msg in out
+ assert msg in err
+```
+
+ê·žëŠŹêł , ëŹŒëĄ ëë¶ë¶ì êČœì°ìë `stderr`ë ììžì ìŒë¶ëĄ ì êł”ë©ëë€.
+ê·žëŹëŻëĄ íŽëč êČœì°ìë try/except넌 ìŹì©íŽìŒ í©ëë€.
+
+```python
+def raise_exception(msg):
+ raise ValueError(msg)
+
+
+def test_something_exception():
+ msg = "Not a good value"
+ error = ""
+ try:
+ raise_exception(msg)
+ except Exception as e:
+ error = str(e)
+ assert msg in error, f"{msg} is in the exception:\n{error}"
+```
+
+`stdout`넌 ìșĄìČíë ë ë€ë„ž ë°©ëČì `contextlib.redirect_stdout`넌 ìŹì©íë êČì
ëë€.
+
+```python
+from io import StringIO
+from contextlib import redirect_stdout
+
+
+def print_to_stdout(s):
+ print(s)
+
+
+def test_result_and_stdout():
+ msg = "Hello"
+ buffer = StringIO()
+ with redirect_stdout(buffer):
+ print_to_stdout(msg)
+ out = buffer.getvalue()
+ # ì í ìŹí: ìșĄìČë ì€ížëŠŒ ìŹìì±
+ sys.stdout.write(out)
+ # í
ì€íž:
+ assert msg in out
+```
+
+`stdout` ìșĄìČì êŽë šë ì€ìí 돞ì ì€ íëë ëłŽí” `print`ìì ìŽì ì ìžìë ëŽì©ì ìŹì€ì íë `\r` 돞ìê° íŹíšë ì ìë€ë êČì
ëë€.
+`pytest`ììë 돞ì ê° ìì§ë§ `pytest -s`ììë ìŽëŹí 돞ìê° ëČíŒì íŹíšëëŻëĄ
+`-s`ê° ìê±°ë ìë ìíìì íì€ížë„Œ ìíí ì ììŒë €ë©Ž ìșĄìČë ì¶ë „ì ëíŽ ì¶ê°ì ìž ì ëŠŹê° íìí©ëë€.
+ìŽ êČœì°ìë `re.sub(r'~.*\r', '', buf, 0, re.M)`ì ìŹì©í ì ìì”ëë€.
+
+íì§ë§ ëì°ëŻž 컚í
ì€íž êŽëŠŹì ëíŒë„Œ ìŹì©í멎
+ì¶ë „ì `\r`ìŽ íŹíšëìŽ ìëì§ì ìŹë¶ì êŽêłììŽ ëȘšë êČì ìëìŒëĄ ìČ늏íëŻëĄ ížëŠŹí©ëë€.
+
+```python
+from transformers.testing_utils import CaptureStdout
+
+with CaptureStdout() as cs:
+ function_that_writes_to_stdout()
+print(cs.out)
+```
+
+ë€ìì ì ìČŽ í
ì€íž ìì ì
ëë€.
+
+```python
+from transformers.testing_utils import CaptureStdout
+
+msg = "Secret message\r"
+final = "Hello World"
+with CaptureStdout() as cs:
+ print(msg + final)
+assert cs.out == final + "\n", f"captured: {cs.out}, expecting {final}"
+```
+
+`stderr`넌 ìșĄìČíêł ì¶ë€ë©Ž, ëì `CaptureStderr` íŽëì€ë„Œ ìŹì©íìžì.
+
+```python
+from transformers.testing_utils import CaptureStderr
+
+with CaptureStderr() as cs:
+ function_that_writes_to_stderr()
+print(cs.err)
+```
+
+ë ì€ížëŠŒì ëìì ìșĄìČíŽìŒ íë€ë©Ž, ë¶ëȘš `CaptureStd` íŽëì€ë„Œ ìŹì©íìžì.
+
+```python
+from transformers.testing_utils import CaptureStd
+
+with CaptureStd() as cs:
+ function_that_writes_to_stdout_and_stderr()
+print(cs.err, cs.out)
+```
+
+ëí, í
ì€ížì ëëČêč
ì ì§ìíêž° ìíŽ
+ìŽëŹí 컚í
ì€íž êŽëŠŹìë êž°ëłžì ìŒëĄ 컚í
ì€ížìì ìą
ëŁí ë ìșĄìČë ì€ížëŠŒì ìëìŒëĄ ë€ì ì€íí©ëë€.
+
+
+### ëĄê±° ì€ížëŠŒ ìșĄìČ[[capturing-logger-stream]]
+
+ëĄê±° ì¶ë „ì êČìŠíŽìŒ íë êČœì° `CaptureLogger`넌 ìŹì©í ì ìì”ëë€.
+
+```python
+from transformers import logging
+from transformers.testing_utils import CaptureLogger
+
+msg = "Testing 1, 2, 3"
+logging.set_verbosity_info()
+logger = logging.get_logger("transformers.models.bart.tokenization_bart")
+with CaptureLogger(logger) as cl:
+ logger.info(msg)
+assert cl.out, msg + "\n"
+```
+
+### íêČœ ëłì넌 ìŽì©íìŹ í
ì€íž[[testing-with-environment-variables]]
+
+íčì í
ì€ížì íêČœ ëłì ìí„ì êČìŠíë €ë©Ž
+`transformers.testing_utils.mockenv`ëŒë ëì°ëŻž ë°ìœë ìŽí°ë„Œ ìŹì©í ì ìì”ëë€.
+
+```python
+from transformers.testing_utils import mockenv
+
+
+class HfArgumentParserTest(unittest.TestCase):
+ @mockenv(TRANSFORMERS_VERBOSITY="error")
+ def test_env_override(self):
+ env_level_str = os.getenv("TRANSFORMERS_VERBOSITY", None)
+```
+
+ìŒë¶ êČœì°ìë ìžë¶ íëĄê·žëšì ížì¶íŽìŒí ìë ìëë°, ìŽ ëìë ìŹëŹ ê°ì ëĄì»Ź êČœëĄë„Œ íŹíšíë `os.environ`ìì `PYTHONPATH`ì ì€ì ìŽ íìí©ëë€.
+íŹíŒ íŽëì€ `transformers.test_utils.TestCasePlus`ê° ëììŽ ë©ëë€:
+
+```python
+from transformers.testing_utils import TestCasePlus
+
+
+class EnvExampleTest(TestCasePlus):
+ def test_external_prog(self):
+ env = self.get_env()
+ # ìŽì `env`넌 ìŹì©íìŹ ìžë¶ íëĄê·žëš ížì¶
+```
+
+í
ì€íž íìŒìŽ `tests` í
ì€íž ì€ìíž ëë `examples`ì ìëì§ì ë°ëŒ
+`env[PYTHONPATH]`ê° ë ëë í°ëŠŹ ì€ íë넌 íŹíšíëëĄ ì€ì ëë©°,
+íìŹ ì ì„ìì ëíŽ í
ì€ížê° ìíëëëĄ `src` ëë í°ëŠŹë íŹíšë©ëë€.
+í
ì€íž ížì¶ ìŽì ì ì€ì ë êČœì°ìë `env[PYTHONPATH]`넌 ê·žëëĄ ìŹì©í©ëë€.
+
+ìŽ íŹíŒ ë©ìëë `os.environ` ê°ìČŽì ìŹëłžì ìì±íëŻëĄ ìëłžì ê·žëëĄ ì ì§ë©ëë€.
+
+
+### ìŹí ê°ë„í êČ°êłŒ ì»êž°[[getting-reproducible-results]]
+
+ìŒë¶ ìí©ìì í
ì€ížìì ììì±ì ì ê±°íìŹ ëìŒíêČ ìŹí ê°ë„í êČ°êłŒë„Œ ì»êł ì¶ì ì ìì”ëë€.
+ìŽë„Œ ìíŽìë ë€ìêłŒ ê°ìŽ ìë넌 êł ì íŽìŒ í©ëë€.
+
+```python
+seed = 42
+
+# íìŽìŹ RNG
+import random
+
+random.seed(seed)
+
+# íìŽí ìč RNG
+import torch
+
+torch.manual_seed(seed)
+torch.backends.cudnn.deterministic = True
+if torch.cuda.is_available():
+ torch.cuda.manual_seed_all(seed)
+
+# ëíìŽ RNG
+import numpy as np
+
+np.random.seed(seed)
+
+# í
ìíëĄ RNG
+tf.random.set_seed(seed)
+```
+
+### í
ì€íž ëëČêč
[[debugging tests]]
+
+êČœêł ê° ìë êłłìì ëëČ거넌 ììíë €ë©Ž ë€ìì ìííìžì.
+
+```bash
+pytest tests/test_logging.py -W error::UserWarning --pdb
+```
+
+## Github Actions ìíŹíëĄì° ìì
ìČ늏[[working-with-github-actions-workflows]]
+
+ì
í ížì ìíŹíëĄì° CI ìì
ì ížëŠŹê±°íë €ë©Ž, ë€ìì ìííŽìŒ í©ëë€.
+
+1. `transformers` ìëłžìì ì ëžëìč넌 ë§ëëë€(íŹíŹê° ìëëë€!).
+2. ëžëìč ìŽëŠì `ci_` ëë `ci-`ëĄ ììíŽìŒ í©ëë€(`main`ë ížëŠŹê±°íì§ë§ `main`ììë PRì í ì ìì”ëë€).
+ ëí íčì êČœëĄì ëíŽìë§ ížëŠŹê±°ëëŻëĄ ìŽ ëŹžìê° ìì±ë íì ëłêČœë ëŽì©ì
+ [ìŹêž°](https://github.com/huggingface/transformers/blob/main/.github/workflows/self-push.yml)ì *push:*ìì íìží ì ìì”ëë€.
+3. ìŽ ëžëìčìì PRì ìì±í©ëë€
+4. ê·žë° ë€ì [ìŹêž°](https://github.com/huggingface/transformers/actions/workflows/self-push.yml)ìì ìì
ìŽ ëíëëì§ íìží ì ìì”ëë€.
+ ë°±ëĄê·žê° ìë êČœì°, ë°ëĄ ì€íëì§ ìì ìë ìì”ëë€.
+
+
+
+
+## ì€íì ìž CI êž°ë„ í
ì€íž[[testing-Experimental-CI-Features]]
+
+CI êž°ë„ì í
ì€ížíë êČì ìŒë° CI ìëì ë°©íŽê° ë ì ìêž° ë돞ì ì ìŹì ìŒëĄ 돞ì ê° ë°ìí ì ìì”ëë€.
+ë°ëŒì ìëĄìŽ CI êž°ë„ì ì¶ê°íë êČœì° ë€ìêłŒ ê°ìŽ ìííŽìŒ í©ëë€.
+
+1. í
ì€ížíŽìŒ í ëŽì©ì í
ì€ížíë ìëĄìŽ ì ì© ìì
ì ìì±í©ëë€.
+2. ìëĄìŽ ìì
ì íì ì±êł”íŽìŒë§ ë
čì â넌 ë°ì ì ìì”ëë€(ìëì ììží ëŽì©ìŽ ìì”ëë€).
+3. ë€ìí PR ì íì ëí íìžì ìíŽ
+ (ìŹì©ì íŹíŹ ëžëìč, íŹíŹëì§ ìì ëžëìč, github.com UI ì§ì íìŒ ížì§ìì ìì±ë ëžëìč, ê°ì ížì ë± PRì ì íì ììŁŒ ë€ìí©ëë€.)
+ ë©°ìč ëì ì€í ìì
ì ëĄê·žë„Œ ëȘšëí°ë§í멎ì ì€ííŽëŽ
ëë€.
+ (ìëì ìŒëĄ íì ë
čìì íìíëŻëĄ ìì
ì ìČŽê° ë
čìì ìëëŒë ì ì ì ìí©ëë€.)
+4. ëȘšë êČìŽ ìì ì ìžì§ íìží í, ìëĄìŽ ëłêČœ ìŹíì êž°ìĄŽ ìì
ì ëłí©í©ëë€.
+
+ìŽë êČ í멎 CI êž°ë„ ììČŽì ëí ì€íìŽ ìŒë° ìì
íëŠì ë°©íŽê° ëì§ ìì”ëë€.
+
+ê·žëŹë ìëĄìŽ CI êž°ë„ìŽ ê°ë° ì€ìž ëì, íì ì±êł”íëëĄ í ì ìë ë°©ëČì 돎ììŒêčì?
+
+TravisCIì ê°ì ìŒë¶ CIë `ignore-step-failure`넌 ì§ìíë©° ì ìČŽ ìì
ì ì±êł”í êČìŒëĄ ëłŽêł íì§ë§,
+íìŹ ì°ëŠŹê° ìŹì©íë CircleCIì Github Actionsë ìŽë„Œ ì§ìíì§ ìì”ëë€.
+
+ë°ëŒì ë€ìêłŒ ê°ì íŽêȰì±
ì ìŹì©í ì ìì”ëë€.
+
+1. bash ì€íŹëŠœížìì ê°ë„í ë§ì ì€ë„넌 ì”ì íêž° ìíŽ ì€í ëȘ
ë čì ìì ë¶ë¶ì `set +euo pipefail`ì ì¶ê°í©ëë€.
+2. ë§ì§ë§ ëȘ
ë čì ë°ëì ì±êł”íŽìŒ í©ëë€. `echo "done"` ëë `true`넌 ìŹì©í멎 ë©ëë€.
+
+ììë ë€ìêłŒ ê°ì”ëë€.
+
+```yaml
+- run:
+ name: run CI experiment
+ command: |
+ set +euo pipefail
+ echo "setting run-all-despite-any-errors-mode"
+ this_command_will_fail
+ echo "but bash continues to run"
+ # emulate another failure
+ false
+ # but the last command must be a success
+ echo "during experiment do not remove: reporting success to CI, even if there were failures"
+```
+
+ê°ëší ëȘ
ë čì êČœì° ë€ìêłŒ ê°ìŽ ìíí ìë ìì”ëë€.
+
+```bash
+cmd_that_may_fail || true
+```
+
+êČ°êłŒì ë§ìĄ±í íìë ëŹŒëĄ , ì€íì ìž ëšêł ëë ìì
ì ìŒë° ìì
ì ëëšžì§ ë¶ë¶êłŒ í”í©í멎ì
+`set +euo pipefail` ëë êž°í ì¶ê°í ìì넌 ì ê±°íìŹ
+ì€í ìì
ìŽ ìŒë° CI ìëì ë°©íŽëì§ ìëëĄ íŽìŒ í©ëë€.
+
+ìŽ ì ë°ì ìž êłŒì ì ì€í ëšêłê° PRì ì ë°ì ìž ìíì ìí„ì ìŁŒì§ ìêł ì€íšíëëĄ
+`allow-failure`ì ê°ì êž°ë„ì ì€ì í ì ìë€ë©Ž íšìŹ ë ìŹì ì êČì
ëë€.
+ê·žëŹë ììì ìžêží ë°ì ê°ìŽ CircleCIì Github Actionsë íìŹ ìŽëŹí êž°ë„ë€ ì§ìíì§ ìì”ëë€.
+
+ìŽ êž°ë„ì ì§ìì ìí íŹíì ì°žìŹíêł CI êŽë š ì€ë ëë€ìì ìŽëŹí ìí©ì íìží ìë ìì”ëë€.
+
+- [Github Actions:](https://github.com/actions/toolkit/issues/399)
+- [CircleCI:](https://ideas.circleci.com/ideas/CCI-I-344)
diff --git a/docs/source/ko/tf_xla.md b/docs/source/ko/tf_xla.md
new file mode 100644
index 000000000000..66d30abb2e98
--- /dev/null
+++ b/docs/source/ko/tf_xla.md
@@ -0,0 +1,174 @@
+
+
+# TensorFlow ëȘšëžì ìí XLA í”í© [[xla-integration-for-tensorflow-models]]
+
+[[open-in-colab]]
+
+XLA(Accelerated Linear Algebra)ë TensorFlow ëȘšëžì ì€í ìê°ì ê°ìííêž° ìí 컎íìŒëŹì
ëë€. [êł”ì 돞ì](https://www.tensorflow.org/xla)ì ë°ë„Žë©Ž ë€ìêłŒ ê°ì”ëë€:
+
+XLA(Accelerated Linear Algebra)ë ì í ëì넌 ìí ëë©ìž íčí 컎íìŒëŹëĄ, TensorFlow ëȘšëžì ìì€ ìœë ëłêČœ ììŽ ê°ìíí ì ìì”ëë€.
+
+TensorFlowìì XLA넌 ìŹì©íë êČì ê°ëší©ëë€. XLAë `tensorflow` ëŒìŽëžëŹëŠŹ ëŽì íší€ì§ëĄ ì êł”ëë©°, [`tf.function`](https://www.tensorflow.org/guide/intro_to_graphs)êłŒ ê°ì ê·žëí ìì± íšììì `jit_compile` ìžì넌 ìŹì©íìŹ íì±íí ì ìì”ëë€. `fit()` ë° `predict()`ì ê°ì Keras ë©ìë넌 ìŹì©íë êČœì°, `jit_compile` ìžì넌 `model.compile()`ì ì ëŹíìŹ XLA넌 ê°ëšíêČ íì±íí ì ìì”ëë€. ê·žëŹë XLAë ìŽëŹí ë©ìëì ê”íëì§ ìêł ììì `tf.function`ì ê°ìííë ë°ìë ìŹì©í ì ìì”ëë€.
+
+đ€ Transformersììë [GPT2](https://huggingface.co/docs/transformers/model_doc/gpt2), [T5](https://huggingface.co/docs/transformers/model_doc/t5), [OPT](https://huggingface.co/docs/transformers/model_doc/opt)ì ê°ì ëȘšëžì í
ì€íž ìì±, ê·žëŠŹêł [Whisper](https://huggingface.co/docs/transformers/model_doc/whisper)ì ê°ì ëȘšëžì ìì± ìČëŠŹë„Œ íŹíšíìŹ ìŹëŹ TensorFlow ë©ìëê° XLAì ížíëëëĄ ë€ì ìì±ëìì”ëë€.
+
+ì íí ìë í„ìì ëȘšëžì ë°ëŒ ë€ë„Žì§ë§, đ€ Transformers ëŽì TensorFlow í
ì€íž ìì± ëȘšëžì êČœì° ì”ë 100ë°°ì ìë í„ìì íìžíì”ëë€. ìŽ ëŹžìììë ìŽëŹí ëȘšëžì ëíŽ XLA넌 ìŹì©íìŹ ì”ë ì±ë„ì ì»ë ë°©ëČì ì€ëȘ
í©ëë€. ëí XLA í”í©ì ëČ€ìčë§íŹ ë° ëììž ìČ íì ëí ì¶ê° ìëŁ ë§íŹë ì êł”í êČì
ëë€.
+
+## XLA넌 ìŹì©íìŹ TF íšì ì€ííêž° [[running-tf-functions-with-xla]]
+
+TensorFlowìì ë€ìêłŒ ê°ì ëȘšëžì êł ë €íŽ ëŽ
ìë€:
+
+```py
+import tensorflow as tf
+
+model = tf.keras.Sequential(
+ [tf.keras.layers.Dense(10, input_shape=(10,), activation="relu"), tf.keras.layers.Dense(5, activation="softmax")]
+)
+```
+
+ì ëȘšëžì ì°šììŽ `(10, )`ìž ì
ë „ì ë°ì”ëë€. ë€ìêłŒ ê°ìŽ ëȘšëžì ìŹì©íìŹ ìì í넌 ì€íí ì ìì”ëë€:
+
+```py
+# ëȘšëžì ëí ììì ì
ë „ì ìì±í©ëë€.
+batch_size = 16
+input_vector_dim = 10
+random_inputs = tf.random.normal((batch_size, input_vector_dim))
+
+# ìì í넌 ì€íí©ëë€.
+_ = model(random_inputs)
+```
+
+XLAëĄ ì»ŽíìŒë íšìëĄ ìì í넌 ì€ííë €ë©Ž ë€ìêłŒ ê°ìŽ íŽìŒ í©ëë€:
+
+```py
+xla_fn = tf.function(model, jit_compile=True)
+_ = xla_fn(random_inputs)
+```
+
+`model`ì êž°ëłž `call()` íšìë XLA ê·žëí넌 컎íìŒíë ë° ìŹì©ë©ëë€. ê·žëŹë ë€ë„ž ëȘšëž íšì넌 XLAëĄ ì»ŽíìŒíë €ë©Ž ë€ìêłŒ ê°ìŽ í ìë ìì”ëë€:
+
+```py
+my_xla_fn = tf.function(model.my_xla_fn, jit_compile=True)
+```
+
+## đ€ Transformersìì XLA넌 ìŹì©íìŹ TF í
ì€íž ìì± ëȘšëž ì€ííêž° [[running-a-tf-text-generation-model-with-xla-from-transformers]]
+
+đ€ Transformersìì XLAëĄ ê°ìíë ìì±ì íì±ííë €ë©Ž ì”ì ëČì ì `transformers`ê° ì€ìčëìŽ ììŽìŒ í©ëë€. ë€ìêłŒ ê°ìŽ ì€ìčí ì ìì”ëë€:
+
+```bash
+pip install transformers --upgrade
+```
+
+ê·žëŠŹêł ë€ì ìœë넌 ì€íí ì ìì”ëë€:
+
+```py
+import tensorflow as tf
+from transformers import AutoTokenizer, TFAutoModelForCausalLM
+
+# ì”ì ëČì ì Transformersê° ì€ìčëìŽ ìì§ ìë€ë©Ž ì€ë„ê° ë°ìí©ëë€.
+from transformers.utils import check_min_version
+
+check_min_version("4.21.0")
+
+
+tokenizer = AutoTokenizer.from_pretrained("gpt2", padding_side="left", pad_token="")
+model = TFAutoModelForCausalLM.from_pretrained("gpt2")
+input_string = ["TensorFlow is"]
+
+# XLA ìì± íšì넌 ë§ë€êž° ìí í ì€
+xla_generate = tf.function(model.generate, jit_compile=True)
+
+tokenized_input = tokenizer(input_string, return_tensors="tf")
+generated_tokens = xla_generate(**tokenized_input, num_beams=2)
+
+decoded_text = tokenizer.decode(generated_tokens[0], skip_special_tokens=True)
+print(f"Generated -- {decoded_text}")
+# Generated -- TensorFlow is an open-source, open-source, distributed-source application # framework for the
+```
+
+ì ì ìëŻìŽ, `generate()`ìì XLA넌 íì±ííë êČì ëš í ì€ì ìœëì
ëë€. ìœëì ëëšžì§ ë¶ë¶ì ëłêČœëì§ ìì”ëë€. ê·žëŹë ì ìœë ì€ëí«ììë XLAì íčì í ëȘ ê°ì§ ìŁŒìí ì ìŽ ìì”ëë€. XLAê° ê°ì žë€ì€ ìë í„ìì ì€ííêž° ìíŽìë ìŽë„Œ ìêł ììŽìŒ í©ëë€. ë€ì ìčì
ìì ìŽì ëíŽ ë
Œìí©ëë€.
+
+## ìŁŒìí ì [[gotchas-to-be-aware-of]]
+
+XLA íì±í íšì(`xla_generate()`ì ê°ì)넌 ìČì ì€íí ë ëŽë¶ì ìŒëĄ êłì° ê·žëí넌 ì¶ëĄ íë €êł íë©°, ìŽë ìê°ìŽ ììë©ëë€. ìŽ êłŒì ì [âì¶ì (tracing)â](https://www.tensorflow.org/guide/intro_to_graphs#when_is_a_function_tracing)ìŽëŒêł ìë €ì ž ìì”ëë€.
+
+ìì± ìê°ìŽ ëč ë„Žì§ ìë€ë êČì ì ì ìì êČì
ëë€. `xla_generate()`(ëë ë€ë„ž XLA íì±í íšì)ì ì°ì ížì¶ì íšìì ì ëŹë ì
ë „ìŽ ìŽêž°ì ê”Źì¶ë êłì° ê·žëíì ëìŒí íí넌 ë°ë„žë€ë©Ž, êłì° ê·žëí넌 ì¶ëĄ í íìê° ìì”ëë€. ìŽë ì
ë „ ííê° êł ì ë ëȘšëŹëŠŹí°(ì: ìŽëŻžì§)ìë 돞ì ê° ëì§ ìì§ë§, ê°ëł ì
ë „ íí ëȘšëŹëŠŹí°(ì: í
ì€íž)넌 ìŹì©í ë ìŁŒìíŽìŒ í©ëë€.
+
+`xla_generate()`ê° íì ëìŒí ì
ë „ ííëĄ ëìíëëĄ íë €ë©Ž, í íŹëìŽì 넌 ížì¶í ë `padding` ìžì넌 ì§ì í ì ìì”ëë€.
+
+```py
+import tensorflow as tf
+from transformers import AutoTokenizer, TFAutoModelForCausalLM
+
+tokenizer = AutoTokenizer.from_pretrained("gpt2", padding_side="left", pad_token="")
+model = TFAutoModelForCausalLM.from_pretrained("gpt2")
+input_string = ["TensorFlow is"]
+
+xla_generate = tf.function(model.generate, jit_compile=True)
+
+# ìŹêž°ì, padding ì”ì
ìŽ ìë í íŹëìŽì 넌 ížì¶í©ëë€.
+tokenized_input = tokenizer(input_string, pad_to_multiple_of=8, padding=True, return_tensors="tf")
+
+generated_tokens = xla_generate(**tokenized_input, num_beams=2)
+decoded_text = tokenizer.decode(generated_tokens[0], skip_special_tokens=True)
+print(f"Generated -- {decoded_text}")
+```
+
+ìŽë êČ í멎 `xla_generate()`ì ëí ì
ë „ìŽ íì ì¶ì ë ííëĄ ì ëŹëìŽ ìì± ìê°ìŽ ê°ìíë©ëë€. ë€ì ìœëëĄ ìŽë„Œ íìží ì ìì”ëë€:
+
+```py
+import time
+import tensorflow as tf
+from transformers import AutoTokenizer, TFAutoModelForCausalLM
+
+tokenizer = AutoTokenizer.from_pretrained("gpt2", padding_side="left", pad_token="")
+model = TFAutoModelForCausalLM.from_pretrained("gpt2")
+
+xla_generate = tf.function(model.generate, jit_compile=True)
+
+for input_string in ["TensorFlow is", "TensorFlow is a", "TFLite is a"]:
+ tokenized_input = tokenizer(input_string, pad_to_multiple_of=8, padding=True, return_tensors="tf")
+ start = time.time_ns()
+ generated_tokens = xla_generate(**tokenized_input, num_beams=2)
+ end = time.time_ns()
+ print(f"Execution time -- {(end - start) / 1e6:.1f} ms\n")
+```
+
+Tesla T4 GPUììë ë€ìêłŒ ê°ì ì¶ë „ì ììí ì ìì”ëë€:
+
+```bash
+Execution time -- 30819.6 ms
+
+Execution time -- 79.0 ms
+
+Execution time -- 78.9 ms
+```
+`xla_generate()`ì ìČ« ëČì§ž ížì¶ì ì¶ì ë돞ì ìê°ìŽ ì€ë ê±žëŠŹì§ë§, ì°ì ížì¶ì ëȘ ë°°ë ëč ëŠ
ëë€. ìì± ì”ì
ì ëí ìŽë€ ëłêČœìŽë ë€ì ì¶ì ì ì ë°íëŻëĄ ìì± ìê°ìŽ ëë €ì§ ì ììì ëȘ
ìŹíìžì.
+
+ìŽ ëŹžìììë đ€ Transformersìì ì êł”íë ëȘšë í
ì€íž ìì± ì”ì
ì ë€ëŁšì§ ììì”ëë€. êł êž ìŹì© ìŹëĄì ëíŽ ëŹžì넌 ì°žìĄ°íìêž° ë°ëëë€.
+
+## ì¶ê° ìëŁ [[additional-resources]]
+
+ìŹêž°ì đ€ Transformersì XLAì ëíŽ ë ììží ìêł ì¶ì êČœì° ëììŽ ë ì ìë ëȘ ê°ì§ ì¶ê° ìëŁë„Œ ì êł”í©ëë€.
+
+* [ìŽ Colab ë
žížë¶](https://colab.research.google.com/github/huggingface/blog/blob/main/notebooks/91_tf_xla_generate.ipynb)ì XLAì ížíëë ìžìœë-ëìœë([T5](https://huggingface.co/docs/transformers/model_doc/t5)ì ê°ì) ë° ëìœë ì ì©([GPT2](https://huggingface.co/docs/transformers/model_doc/gpt2)ì ê°ì) í
ì€íž ìì± ëȘšëžì ì€ííŽ ëłŒ ì ìë ëíí ë°ëȘšë„Œ ì êł”í©ëë€.
+* [ìŽ ëžëĄê·ž êž](https://huggingface.co/blog/tf-xla-generate)ì TensorFlowìì XLAì ëí ìčì í ìê°ì íšê» XLAì ížíëë ëȘšëžì ëčê” ëČ€ìčë§íŹì ëí ê°ì넌 ì êł”í©ëë€.
+* [ìŽ ëžëĄê·ž êž](https://blog.tensorflow.org/2022/11/how-hugging-face-improved-text-generation-performance-with-xla.html)ì đ€ Transformersì TensorFlow ëȘšëžì XLA ì§ìì ì¶ê°íë êČì ëí ëììž ìČ íì ë
Œìí©ëë€.
+* XLAì TensorFlow ê·žëíì ëíŽ ë ììží ìêł ì¶ì êČœì° ì¶ìČíë êž:
+ * [XLA: êž°êł íì”ì ìí ì”ì í 컎íìŒëŹ](https://www.tensorflow.org/xla)
+ * [ê·žëí ë° tf.function ìê°](https://www.tensorflow.org/guide/intro_to_graphs)
+ * [tf.functionìŒëĄ ì±ë„ í„ìíêž°](https://www.tensorflow.org/guide/function)
\ No newline at end of file
diff --git a/docs/source/ko/tflite.md b/docs/source/ko/tflite.md
new file mode 100644
index 000000000000..5d08ea407854
--- /dev/null
+++ b/docs/source/ko/tflite.md
@@ -0,0 +1,62 @@
+
+
+# TFLiteëĄ ëŽëłŽëŽêž°[[export-to-tflite]]
+
+[TensorFlow Lite](https://www.tensorflow.org/lite/guide)ë ìììŽ ì íë íŽëí°, ìëČ ëë ìì€í
, ìŹëŹŒìží°ë·(IoT) êž°êž°ìì
+êž°êłíì” ëȘšëžì ë°°íŹíêž° ìí êČœë íë ììíŹì
ëë€.
+TFLiteë ì°ì° ë„ë „, ë©ëȘšëŠŹ, ì ë „ ìëčê° ì íë êž°êž°ìì ëȘšëžì íšìšì ìŒëĄ ì”ì ííêł ì€ííêž° ìíŽ
+ì€êłëìì”ëë€.
+TensorFlow Lite ëȘšëžì `.tflite` íìŒ íì„ìëĄ ìëłëë íčìíêł íšìšì ìž íŽëì© íŹë§·ìŒëĄ ííë©ëë€.
+
+đ€ Optimumì `exporters.tflite` ëȘšëëĄ đ€ Transformers ëȘšëžì TFLiteëĄ ëŽëłŽëŽë êž°ë„ì ì êł”í©ëë€.
+ì§ìëë ëȘšëž ìí€í
ìČ ëȘ©ëĄì [đ€ Optimum 돞ì](https://huggingface.co/docs/optimum/exporters/tflite/overview)넌 ì°žêł íìžì.
+
+ëȘšëžì TFLiteëĄ ëŽëłŽëŽë €ë©Ž, íìí ìą
ìì±ì ì€ìčíìžì:
+
+```bash
+pip install optimum[exporters-tf]
+```
+
+ëȘšë ìŹì© ê°ë„í ìžì넌 íìžíë €ë©Ž, [đ€ Optimum 돞ì](https://huggingface.co/docs/optimum/main/en/exporters/tflite/usage_guides/export_a_model)넌 ì°žêł íê±°ë
+í°ëŻžëìì ëìë§ì ìŽíŽëłŽìžì:
+
+```bash
+optimum-cli export tflite --help
+```
+
+ì넌 ë€ìŽ đ€ Hubììì `bert-base-uncased` ëȘšëž ìČŽíŹíŹìžížë„Œ ëŽëłŽëŽë €ë©Ž, ë€ì ëȘ
ë čì ì€ííìžì:
+
+```bash
+optimum-cli export tflite --model bert-base-uncased --sequence_length 128 bert_tflite/
+```
+
+ë€ìêłŒ ê°ìŽ ì§í ìí©ì ëíëŽë ëĄê·žì êČ°êłŒëŹŒìž `model.tflite`ê° ì ì„ë ììč넌 볎ìŹìŁŒë ëĄê·žê° íìë©ëë€:
+
+```bash
+Validating TFLite model...
+ -[â] TFLite model output names match reference model (logits)
+ - Validating TFLite Model output "logits":
+ -[â] (1, 128, 30522) matches (1, 128, 30522)
+ -[x] values not close enough, max diff: 5.817413330078125e-05 (atol: 1e-05)
+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:
+- logits: max diff = 5.817413330078125e-05.
+ The exported model was saved at: bert_tflite
+ ```
+
+ì ìì ë đ€ Hubììì ìČŽíŹíŹìžížë„Œ ëŽëłŽëŽë ë°©ëČì 볎ìŹì€ëë€.
+ëĄì»Ź ëȘšëžì ëŽëłŽëžë€ë©Ž, 뚌ì ëȘšëž ê°ì€ìčì í íŹëìŽì íìŒìŽ ëȘšë ê°ì ëë í°ëŠŹ( `local_path` )ì ì ì„ëëì§ íìžíìžì.
+CLI넌 ìŹì©í ë, đ€ Hubììì ìČŽíŹíŹìžíž ìŽëŠ ëì `model` ìžìì `local_path`넌 ì ëŹí멎 ë©ëë€.
\ No newline at end of file
diff --git a/docs/source/ko/torchscript.md b/docs/source/ko/torchscript.md
new file mode 100644
index 000000000000..297479caf2c0
--- /dev/null
+++ b/docs/source/ko/torchscript.md
@@ -0,0 +1,189 @@
+
+
+# TorchScriptëĄ ëŽëłŽëŽêž°[[export-to-torchscript]]
+
+
+
+TorchScript넌 íì©í ì€íì ìì§ ìŽêž° ëšêłëĄ, ê°ëłì ìž ì
ë „ íŹêž° ëȘšëžë€ì í”íŽ ê·ž êž°ë„ì±ì êłì íê”Źíêł ìì”ëë€.
+ìŽ êž°ë„ì ì íŹê° êŽìŹì ëêł ìë ë¶ìŒ ì€ íëìŽë©°,
+ììŒëĄ ì¶ìë ëČì ìì ë ë§ì ìœë ìì , ë ì ì°í ê”Źí, ê·žëŠŹêł Python êž°ë° ìœëì 컎íìŒë TorchScript넌 ëčê”íë ëČ€ìčë§íŹë„Œ ë±ì í”íŽ ë¶ìì ìŹíí ìì ì
ëë€.
+
+
+
+[TorchScript 돞ì](https://pytorch.org/docs/stable/jit.html)ììë ìŽë êČ ë§í©ëë€.
+
+> TorchScriptë PyTorch ìœëìì ì§ë Źí ë° ì”ì í ê°ë„í ëȘšëžì ìì±íë ë°©ëČì
ëë€.
+
+[JITêłŒ TRACE](https://pytorch.org/docs/stable/jit.html)ë ê°ë°ìê° ëȘšëžì ëŽëłŽëŽì íšìš ì§í„ì ìž C++ íëĄê·žëšêłŒ ê°ì ë€ë„ž íëĄê·žëšìì ìŹìŹì©í ì ìëëĄ íë PyTorch ëȘšëì
ëë€.
+
+PyTorch êž°ë° Python íëĄê·žëšêłŒ ë€ë„ž íêČœìì ëȘšëžì ìŹìŹì©í ì ìëëĄ, đ€ Transformers ëȘšëžì TorchScriptëĄ ëŽëłŽëŒ ì ìë ìží°íìŽì€ë„Œ ì êł”í©ëë€.
+ìŽ ëŹžìììë TorchScript넌 ìŹì©íìŹ ëȘšëžì ëŽëłŽëŽêł ìŹì©íë ë°©ëČì ì€ëȘ
í©ëë€.
+
+ëȘšëžì ëŽëłŽëŽë €ë©Ž ë ê°ì§ê° íìí©ëë€:
+
+- `torchscript` íëê·žëĄ ëȘšëž ìžì€íŽì€í
+- ë믞 ì
ë „ì ìŹì©í ìì í(forward pass)
+
+ìŽ íì ìĄ°ê±Žë€ì ìëì ììží ì€ëȘ
ë êČìČëŒ ê°ë°ìë€ìŽ ìŁŒìíŽìŒ í ìŹëŹ ìŹíë€ì ì믞í©ëë€.
+
+## TorchScript íëê·žì ëŹ¶ìž ê°ì€ìč(tied weights)[[torchscript-flag-and-tied-weights]]
+
+`torchscript` íëê·žê° íìí ìŽì ë ëë¶ë¶ì đ€ Transformers ìžìŽ ëȘšëžìì `Embedding` ë ìŽìŽì `Decoding` ë ìŽìŽ ê°ì ëŹ¶ìž ê°ì€ìč(tied weights)ê° ìĄŽìŹíêž° ë돞ì
ëë€.
+TorchScriptë ëŹ¶ìž ê°ì€ìč넌 ê°ì§ ëȘšëžì ëŽëłŽëŒ ì ììŒëŻëĄ, 믞늏 ê°ì€ìč넌 íêł ëł”ì íŽìŒ í©ëë€.
+
+`torchscript` íëê·žëĄ ìžì€íŽì€íë ëȘšëžì `Embedding` ë ìŽìŽì `Decoding` ë ìŽìŽê° ë¶ëŠŹëìŽ ììŒëŻëĄ ìŽíì íë šíŽìë ì ë©ëë€.
+íë šì íêČ ë멎 ë ë ìŽìŽ ê° ëêž°íê° íŽì ëìŽ ìììč ëȘ»í êČ°êłŒê° ë°ìí ì ìì”ëë€.
+
+ìžìŽ ëȘšëž í€ë넌 ê°ì§ ìì ëȘšëžì ê°ì€ìčê° ëŹ¶ìŹ ìì§ ììì ìŽ ëŹžì ê° ë°ìíì§ ìì”ëë€.
+ìŽëŹí ëȘšëžë€ì `torchscript` íëê·ž ììŽ ìì íêČ ëŽëłŽëŒ ì ìì”ëë€.
+
+## ë믞 ì
ë „êłŒ íì€ êžžìŽ[[dummy-inputs-and-standard-lengths]]
+
+ë믞 ì
ë „(dummy inputs)ì ëȘšëžì ìì í(forward pass)ì ìŹì©ë©ëë€.
+ì
ë „ ê°ìŽ ë ìŽìŽë„Œ í”íŽ ì íëë ëì, PyTorchë ê° í
ììì ì€íë ë€ë„ž ì°ì°ì ì¶ì í©ëë€.
+ìŽëŹí êž°ëĄë ì°ì°ì ëȘšëžì *ì¶ì (trace)*ì ìì±íë ë° ìŹì©ë©ëë€.
+
+ì¶ì ì ì
ë „ì ì°šìì êž°ì€ìŒëĄ ìì±ë©ëë€.
+ë°ëŒì ë믞 ì
ë „ì ì°šìì ì íëìŽ, ë€ë„ž ìíì€ êžžìŽë ë°°ìč íŹêž°ììë ìëíì§ ìì”ëë€.
+ë€ë„ž íŹêž°ëĄ ìëí êČœì° ë€ìêłŒ ê°ì ì€ë„ê° ë°ìí©ëë€:
+
+```
+`The expanded size of the tensor (3) must match the existing size (7) at non-singleton dimension 2`
+```
+ì¶ëĄ ì€ ëȘšëžì êł”êžë ê°ì„ í° ì
ë „ë§íŒ í° ë믞 ì
ë „ íŹêž°ëĄ ëȘšëžì ì¶ì íë êČìŽ ìąì”ëë€.
+íšë©ì ëëœë ê°ì ì±ì°ë ë° ëììŽ ë ì ìì”ëë€.
+ê·žëŹë ëȘšëžìŽ ë í° ì
ë „ íŹêž°ëĄ ì¶ì ëêž° ë돞ì, íë Źì ì°šììŽ ì»€ì§êł êłì°ëìŽ ë§ìì§ëë€.
+
+ë€ìí ìíì€ êžžìŽ ëȘšëžì ëŽëłŽëŒ ëë ê° ì
ë „ì ëíŽ ìíëë ìŽ ì°ì° íìì ìŁŒìíêł ì±ë„ì ìŁŒì êčêČ íìžíìžì.
+
+## Pythonìì TorchScript ìŹì©íêž°[[using-torchscript-in-python]]
+
+ìŽ ìčì
ììë ëȘšëžì ì ì„íêł ê°ì žì€ë ë°©ëČ, ì¶ì ì ìŹì©íìŹ ì¶ëĄ íë ë°©ëČì 볎ìŹì€ëë€.
+
+### ëȘšëž ì ì„íêž°[[saving-a-model]]
+
+`BertModel`ì TorchScriptëĄ ëŽëłŽëŽë €ë©Ž `BertConfig` íŽëì€ìì `BertModel`ì ìžì€íŽì€íí ë€ì, `traced_bert.pt`ëŒë íìŒëȘ
ìŒëĄ ëì€íŹì ì ì„í멎 ë©ëë€.
+
+```python
+from transformers import BertModel, BertTokenizer, BertConfig
+import torch
+
+enc = BertTokenizer.from_pretrained("bert-base-uncased")
+
+# ì
ë „ í
ì€íž í í°ííêž°
+text = "[CLS] Who was Jim Henson ? [SEP] Jim Henson was a puppeteer [SEP]"
+tokenized_text = enc.tokenize(text)
+
+# ì
ë „ í í° ì€ íë넌 ë§ì€íčíêž°
+masked_index = 8
+tokenized_text[masked_index] = "[MASK]"
+indexed_tokens = enc.convert_tokens_to_ids(tokenized_text)
+segments_ids = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1]
+
+# ë믞 ì
ë „ ë§ë€êž°
+tokens_tensor = torch.tensor([indexed_tokens])
+segments_tensors = torch.tensor([segments_ids])
+dummy_input = [tokens_tensor, segments_tensors]
+
+# torchscript íëê·žëĄ ëȘšëž ìŽêž°ííêž°
+# ìŽ ëȘšëžì LM í€ëê° ììŒëŻëĄ íìíì§ ìì§ë§, íë귞넌 TrueëĄ ì€ì í©ëë€.
+config = BertConfig(
+ vocab_size_or_config_json_file=32000,
+ hidden_size=768,
+ num_hidden_layers=12,
+ num_attention_heads=12,
+ intermediate_size=3072,
+ torchscript=True,
+)
+
+# ëȘšëžì ìžì€íŽížííêž°
+model = BertModel(config)
+
+# ëȘšëžì íê° ëȘšëëĄ ëìŽìŒ í©ëë€.
+model.eval()
+
+# ë§ìœ *from_pretrained*넌 ìŹì©íìŹ ëȘšëžì ìžì€íŽì€ííë êČœì°, TorchScript íë귞넌 ìœêČ ì€ì í ì ìì”ëë€
+model = BertModel.from_pretrained("bert-base-uncased", torchscript=True)
+
+# ì¶ì ìì±íêž°
+traced_model = torch.jit.trace(model, [tokens_tensor, segments_tensors])
+torch.jit.save(traced_model, "traced_bert.pt")
+```
+
+### ëȘšëž ê°ì žì€êž°[[loading-a-model]]
+
+ìŽì ìŽì ì ì ì„í `BertModel`, ìŠ `traced_bert.pt`넌 ëì€íŹìì ê°ì žì€êł , ìŽì ì ìŽêž°íí `dummy_input`ìì ìŹì©í ì ìì”ëë€.
+
+```python
+loaded_model = torch.jit.load("traced_bert.pt")
+loaded_model.eval()
+
+all_encoder_layers, pooled_output = loaded_model(*dummy_input)
+```
+
+### ì¶ì ë ëȘšëžì ìŹì©íìŹ ì¶ëĄ íêž°[[using-a-traced-model-for-inference]]
+
+`__call__` ìŽì€ ìžëì€ìœìŽ(dunder) ë©ìë넌 ìŹì©íìŹ ì¶ëĄ ì ì¶ì ë ëȘšëžì ìŹì©íìžì:
+
+```python
+traced_model(tokens_tensor, segments_tensors)
+```
+
+## Neuron SDKëĄ Hugging Face TorchScript ëȘšëžì AWSì ë°°íŹíêž°[[deploy-hugging-face-torchscript-models-to-aws-with-the-neuron-sdk]]
+
+AWSê° íŽëŒì°ëìì ì ëčì©, êł ì±ë„ ëšžì ëŹë ì¶ëĄ ì ìí [Amazon EC2 Inf1](https://aws.amazon.com/ec2/instance-types/inf1/) ìžì€íŽì€ ì íê”°ì ì¶ìíì”ëë€.
+Inf1 ìžì€íŽì€ë ë„ëŹë ì¶ëĄ ìíŹëĄëì íčíë ë§ì¶€ íëìšìŽ ê°ìêž°ìž AWS Inferentia ìč©ìŒëĄ ê”Źëë©ëë€.
+[AWS Neuron](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/#)ì Inferentia넌 ìí SDKëĄ, Inf1ì ë°°íŹíêž° ìí transformers ëȘšëž ì¶ì ë° ì”ì í넌 ì§ìí©ëë€.
+Neuron SDKë ë€ìêłŒ ê°ì êž°ë„ì ì êł”í©ëë€:
+
+1. ìœë í ì€ë§ ëłêČœí멎 íŽëŒì°ë ì¶ëĄ 넌 ìíŽ TorchScript ëȘšëžì ì¶ì íêł ì”ì íí ì ìë ìŹìŽ API
+2. ìŠì ìŹì© ê°ë„í ì±ë„ ì”ì íëĄ [ëčì© íšìš í„ì](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/neuron-guide/benchmark/>)
+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 ëȘšëž ì§ì
+
+### ììŹì [[implications]]
+
+[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ìì ì”ìì ì±ë„ì 볎ì
ëë€.
+ê·žëŹë í
ì€íž ìì± ìì
ë [AWS Neuron MarianMT íí 늏ìŒ](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/src/examples/pytorch/transformers-marianmt.html)ì ë°ëŒ Inf1ìì ì€íëëëĄ ìĄ°ì í ì ìì”ëë€.
+
+Inferentiaìì ë°ëĄ ëłíí ì ìë ëȘšëžì ëí ììží ì 볎ë Neuron 돞ìì [Model Architecture Fit](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/neuron-guide/models/models-inferentia.html#models-inferentia) ìčì
ìì íìží ì ìì”ëë€.
+
+### ìą
ìì±[[dependencies]]
+
+AWS Neuronì ìŹì©íìŹ ëȘšëžì ëłííë €ë©Ž [Neuron SDK íêČœ](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/neuron-guide/neuron-frameworks/pytorch-neuron/index.html#installation-guide)ìŽ íìí©ëë€.
+ ìŽë [AWS Deep Learning AMI](https://docs.aws.amazon.com/dlami/latest/devguide/tutorial-inferentia-launching.html)ì 믞늏 ê”Źì±ëìŽ ìì”ëë€.
+
+### AWS NeuronìŒëĄ ëȘšëž ëłííêž°[[converting-a-model-for-aws-neuron]]
+
+`BertModel`ì ì¶ì íë €ë©Ž, [Pythonìì TorchScript ìŹì©íêž°](torchscript#using-torchscript-in-python)ììì ëìŒí ìœë넌 ìŹì©íŽì AWS NEURONì© ëȘšëžì ëłíí©ëë€.
+`torch.neuron` íë ììíŹ ì”ì€í
ì
ì ê°ì žì Python API넌 í”íŽ Neuron SDKì ê”Źì± ììì ì ê·Œí©ëë€:
+
+```python
+from transformers import BertModel, BertTokenizer, BertConfig
+import torch
+import torch.neuron
+```
+
+ë€ì ì€ë§ ìì í멎 ë©ëë€:
+
+```diff
+- torch.jit.trace(model, [tokens_tensor, segments_tensors])
++ torch.neuron.trace(model, [token_tensor, segments_tensors])
+```
+
+ìŽëĄìš Neuron SDKê° ëȘšëžì ì¶ì íêł Inf1 ìžì€íŽì€ì ì”ì íí ì ìêČ ë©ëë€.
+
+AWS Neuron SDKì êž°ë„, ëê”Ź, ìì íí ëŠŹìŒ ë° ì”ì ì
ë°ìŽížì ëíŽ ììží ììëłŽë €ë©Ž [AWS NeuronSDK 돞ì](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/index.html)넌 ì°žìĄ°íìžì.
diff --git a/docs/source/ko/torchscript.mdx b/docs/source/ko/torchscript.mdx
deleted file mode 100644
index 1a22baf92bec..000000000000
--- a/docs/source/ko/torchscript.mdx
+++ /dev/null
@@ -1,185 +0,0 @@
-
-
-# TorchScriptëĄ ëŽëłŽëŽêž°[[export-to-torchscript]]
-
-
-
-TorchScript넌 íì©í ì€íì ìì§ ìŽêž° ëšêłëĄ, ê°ëłì ìž ì
ë „ íŹêž° ëȘšëžë€ì í”íŽ ê·ž êž°ë„ì±ì êłì íê”Źíêł ìì”ëë€.
-ìŽ êž°ë„ì ì íŹê° êŽìŹì ëêł ìë ë¶ìŒ ì€ íëìŽë©°,
-ììŒëĄ ì¶ìë ëČì ìì ë ë§ì ìœë ìì , ë ì ì°í ê”Źí, ê·žëŠŹêł Python êž°ë° ìœëì 컎íìŒë TorchScript넌 ëčê”íë ëČ€ìčë§íŹë„Œ ë±ì í”íŽ ë¶ìì ìŹíí ìì ì
ëë€.
-
-
-
-[TorchScript 돞ì](https://pytorch.org/docs/stable/jit.html)ììë ìŽë êČ ë§í©ëë€.
-
-> TorchScriptë PyTorch ìœëìì ì§ë Źí ë° ì”ì í ê°ë„í ëȘšëžì ìì±íë ë°©ëČì
ëë€.
-
-[JITêłŒ TRACE](https://pytorch.org/docs/stable/jit.html)ë ê°ë°ìê° ëȘšëžì ëŽëłŽëŽì íšìš ì§í„ì ìž C++ íëĄê·žëšêłŒ ê°ì ë€ë„ž íëĄê·žëšìì ìŹìŹì©í ì ìëëĄ íë PyTorch ëȘšëì
ëë€.
-
-PyTorch êž°ë° Python íëĄê·žëšêłŒ ë€ë„ž íêČœìì ëȘšëžì ìŹìŹì©í ì ìëëĄ, đ€ Transformers ëȘšëžì TorchScriptëĄ ëŽëłŽëŒ ì ìë ìží°íìŽì€ë„Œ ì êł”í©ëë€.
-ìŽ ëŹžìììë TorchScript넌 ìŹì©íìŹ ëȘšëžì ëŽëłŽëŽêł ìŹì©íë ë°©ëČì ì€ëȘ
í©ëë€.
-
-ëȘšëžì ëŽëłŽëŽë €ë©Ž ë ê°ì§ê° íìí©ëë€:
-
-- `torchscript` íëê·žëĄ ëȘšëž ìžì€íŽì€í
-- ë믞 ì
ë „ì ìŹì©í ìì í(forward pass)
-
-ìŽ íì ìĄ°ê±Žë€ì ìëì ììží ì€ëȘ
ë êČìČëŒ ê°ë°ìë€ìŽ ìŁŒìíŽìŒ í ìŹëŹ ìŹíë€ì ì믞í©ëë€.
-
-## TorchScript íëê·žì ëŹ¶ìž ê°ì€ìč(tied weights)[[torchscript-flag-and-tied-weights]]
-
-`torchscript` íëê·žê° íìí ìŽì ë ëë¶ë¶ì đ€ Transformers ìžìŽ ëȘšëžìì `Embedding` ë ìŽìŽì `Decoding` ë ìŽìŽ ê°ì ëŹ¶ìž ê°ì€ìč(tied weights)ê° ìĄŽìŹíêž° ë돞ì
ëë€.
-TorchScriptë ëŹ¶ìž ê°ì€ìč넌 ê°ì§ ëȘšëžì ëŽëłŽëŒ ì ììŒëŻëĄ, 믞늏 ê°ì€ìč넌 íêł ëł”ì íŽìŒ í©ëë€.
-
-`torchscript` íëê·žëĄ ìžì€íŽì€íë ëȘšëžì `Embedding` ë ìŽìŽì `Decoding` ë ìŽìŽê° ë¶ëŠŹëìŽ ììŒëŻëĄ ìŽíì íë šíŽìë ì ë©ëë€.
-íë šì íêČ ë멎 ë ë ìŽìŽ ê° ëêž°íê° íŽì ëìŽ ìììč ëȘ»í êČ°êłŒê° ë°ìí ì ìì”ëë€.
-
-ìžìŽ ëȘšëž í€ë넌 ê°ì§ ìì ëȘšëžì ê°ì€ìčê° ëŹ¶ìŹ ìì§ ììì ìŽ ëŹžì ê° ë°ìíì§ ìì”ëë€.
-ìŽëŹí ëȘšëžë€ì `torchscript` íëê·ž ììŽ ìì íêČ ëŽëłŽëŒ ì ìì”ëë€.
-
-## ë믞 ì
ë „êłŒ íì€ êžžìŽ[[dummy-inputs-and-standard-lengths]]
-
-ë믞 ì
ë „(dummy inputs)ì ëȘšëžì ìì í(forward pass)ì ìŹì©ë©ëë€.
-ì
ë „ ê°ìŽ ë ìŽìŽë„Œ í”íŽ ì íëë ëì, PyTorchë ê° í
ììì ì€íë ë€ë„ž ì°ì°ì ì¶ì í©ëë€.
-ìŽëŹí êž°ëĄë ì°ì°ì ëȘšëžì *ì¶ì (trace)*ì ìì±íë ë° ìŹì©ë©ëë€.
-
-ì¶ì ì ì
ë „ì ì°šìì êž°ì€ìŒëĄ ìì±ë©ëë€.
-ë°ëŒì ë믞 ì
ë „ì ì°šìì ì íëìŽ, ë€ë„ž ìíì€ êžžìŽë ë°°ìč íŹêž°ììë ìëíì§ ìì”ëë€.
-ë€ë„ž íŹêž°ëĄ ìëí êČœì° ë€ìêłŒ ê°ì ì€ë„ê° ë°ìí©ëë€:
-
-```
-`The expanded size of the tensor (3) must match the existing size (7) at non-singleton dimension 2`
-```
-ì¶ëĄ ì€ ëȘšëžì êł”êžë ê°ì„ í° ì
ë „ë§íŒ í° ë믞 ì
ë „ íŹêž°ëĄ ëȘšëžì ì¶ì íë êČìŽ ìąì”ëë€.
-íšë©ì ëëœë ê°ì ì±ì°ë ë° ëììŽ ë ì ìì”ëë€.
-ê·žëŹë ëȘšëžìŽ ë í° ì
ë „ íŹêž°ëĄ ì¶ì ëêž° ë돞ì, íë Źì ì°šììŽ ì»€ì§êł êłì°ëìŽ ë§ìì§ëë€.
-
-ë€ìí ìíì€ êžžìŽ ëȘšëžì ëŽëłŽëŒ ëë ê° ì
ë „ì ëíŽ ìíëë ìŽ ì°ì° íìì ìŁŒìíêł ì±ë„ì ìŁŒì êčêČ íìžíìžì.
-
-## Pythonìì TorchScript ìŹì©íêž°[[using-torchscript-in-python]]
-
-ìŽ ìčì
ììë ëȘšëžì ì ì„íêł ê°ì žì€ë ë°©ëČ, ì¶ì ì ìŹì©íìŹ ì¶ëĄ íë ë°©ëČì 볎ìŹì€ëë€.
-
-### ëȘšëž ì ì„íêž°[[saving-a-model]]
-
-`BertModel`ì TorchScriptëĄ ëŽëłŽëŽë €ë©Ž `BertConfig` íŽëì€ìì `BertModel`ì ìžì€íŽì€íí ë€ì, `traced_bert.pt`ëŒë íìŒëȘ
ìŒëĄ ëì€íŹì ì ì„í멎 ë©ëë€.
-
-```python
-from transformers import BertModel, BertTokenizer, BertConfig
-import torch
-
-enc = BertTokenizer.from_pretrained("bert-base-uncased")
-
-# ì
ë „ í
ì€íž í í°ííêž°
-text = "[CLS] Who was Jim Henson ? [SEP] Jim Henson was a puppeteer [SEP]"
-tokenized_text = enc.tokenize(text)
-
-# ì
ë „ í í° ì€ íë넌 ë§ì€íčíêž°
-masked_index = 8
-tokenized_text[masked_index] = "[MASK]"
-indexed_tokens = enc.convert_tokens_to_ids(tokenized_text)
-segments_ids = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1]
-
-# ë믞 ì
ë „ ë§ë€êž°
-tokens_tensor = torch.tensor([indexed_tokens])
-segments_tensors = torch.tensor([segments_ids])
-dummy_input = [tokens_tensor, segments_tensors]
-
-# torchscript íëê·žëĄ ëȘšëž ìŽêž°ííêž°
-# ìŽ ëȘšëžì LM í€ëê° ììŒëŻëĄ íìíì§ ìì§ë§, íë귞넌 TrueëĄ ì€ì í©ëë€.
-config = BertConfig(
- vocab_size_or_config_json_file=32000,
- hidden_size=768,
- num_hidden_layers=12,
- num_attention_heads=12,
- intermediate_size=3072,
- torchscript=True,
-)
-
-# ëȘšëžì ìžì€íŽížííêž°
-model = BertModel(config)
-
-# ëȘšëžì íê° ëȘšëëĄ ëìŽìŒ í©ëë€.
-model.eval()
-
-# ë§ìœ *from_pretrained*넌 ìŹì©íìŹ ëȘšëžì ìžì€íŽì€ííë êČœì°, TorchScript íë귞넌 ìœêČ ì€ì í ì ìì”ëë€
-model = BertModel.from_pretrained("bert-base-uncased", torchscript=True)
-
-# ì¶ì ìì±íêž°
-traced_model = torch.jit.trace(model, [tokens_tensor, segments_tensors])
-torch.jit.save(traced_model, "traced_bert.pt")
-```
-
-### ëȘšëž ê°ì žì€êž°[[loading-a-model]]
-
-ìŽì ìŽì ì ì ì„í `BertModel`, ìŠ `traced_bert.pt`넌 ëì€íŹìì ê°ì žì€êł , ìŽì ì ìŽêž°íí `dummy_input`ìì ìŹì©í ì ìì”ëë€.
-
-```python
-loaded_model = torch.jit.load("traced_bert.pt")
-loaded_model.eval()
-
-all_encoder_layers, pooled_output = loaded_model(*dummy_input)
-```
-
-### ì¶ì ë ëȘšëžì ìŹì©íìŹ ì¶ëĄ íêž°[[using-a-traced-model-for-inference]]
-
-`__call__` ìŽì€ ìžëì€ìœìŽ(dunder) ë©ìë넌 ìŹì©íìŹ ì¶ëĄ ì ì¶ì ë ëȘšëžì ìŹì©íìžì:
-
-```python
-traced_model(tokens_tensor, segments_tensors)
-```
-
-## Neuron SDKëĄ Hugging Face TorchScript ëȘšëžì AWSì ë°°íŹíêž°[[deploy-hugging-face-torchscript-models-to-aws-with-the-neuron-sdk]]
-
-AWSê° íŽëŒì°ëìì ì ëčì©, êł ì±ë„ ëšžì ëŹë ì¶ëĄ ì ìí [Amazon EC2 Inf1](https://aws.amazon.com/ec2/instance-types/inf1/) ìžì€íŽì€ ì íê”°ì ì¶ìíì”ëë€.
-Inf1 ìžì€íŽì€ë ë„ëŹë ì¶ëĄ ìíŹëĄëì íčíë ë§ì¶€ íëìšìŽ ê°ìêž°ìž AWS Inferentia ìč©ìŒëĄ ê”Źëë©ëë€.
-[AWS Neuron](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/#)ì Inferentia넌 ìí SDKëĄ, Inf1ì ë°°íŹíêž° ìí transformers ëȘšëž ì¶ì ë° ì”ì í넌 ì§ìí©ëë€.
-Neuron SDKë ë€ìêłŒ ê°ì êž°ë„ì ì êł”í©ëë€:
-
-1. ìœë í ì€ë§ ëłêČœí멎 íŽëŒì°ë ì¶ëĄ 넌 ìíŽ TorchScript ëȘšëžì ì¶ì íêł ì”ì íí ì ìë ìŹìŽ API
-2. ìŠì ìŹì© ê°ë„í ì±ë„ ì”ì íëĄ [ëčì© íšìš í„ì](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/neuron-guide/benchmark/>)
-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 ëȘšëž ì§ì
-
-### ììŹì [[implications]]
-
-[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ìì ì”ìì ì±ë„ì 볎ì
ëë€.
-ê·žëŹë í
ì€íž ìì± ìì
ë [AWS Neuron MarianMT íí 늏ìŒ](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/src/examples/pytorch/transformers-marianmt.html)ì ë°ëŒ Inf1ìì ì€íëëëĄ ìĄ°ì í ì ìì”ëë€.
-
-Inferentiaìì ë°ëĄ ëłíí ì ìë ëȘšëžì ëí ììží ì 볎ë Neuron 돞ìì [Model Architecture Fit](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/neuron-guide/models/models-inferentia.html#models-inferentia) ìčì
ìì íìží ì ìì”ëë€.
-
-### ìą
ìì±[[dependencies]]
-
-AWS Neuronì ìŹì©íìŹ ëȘšëžì ëłííë €ë©Ž [Neuron SDK íêČœ](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/neuron-guide/neuron-frameworks/pytorch-neuron/index.html#installation-guide)ìŽ íìí©ëë€.
- ìŽë [AWS Deep Learning AMI](https://docs.aws.amazon.com/dlami/latest/devguide/tutorial-inferentia-launching.html)ì 믞늏 ê”Źì±ëìŽ ìì”ëë€.
-
-### AWS NeuronìŒëĄ ëȘšëž ëłííêž°[[converting-a-model-for-aws-neuron]]
-
-`BertModel`ì ì¶ì íë €ë©Ž, [Pythonìì TorchScript ìŹì©íêž°](torchscript#using-torchscript-in-python)ììì ëìŒí ìœë넌 ìŹì©íŽì AWS NEURONì© ëȘšëžì ëłíí©ëë€.
-`torch.neuron` íë ììíŹ ì”ì€í
ì
ì ê°ì žì Python API넌 í”íŽ Neuron SDKì ê”Źì± ììì ì ê·Œí©ëë€:
-
-```python
-from transformers import BertModel, BertTokenizer, BertConfig
-import torch
-import torch.neuron
-```
-
-ë€ì ì€ë§ ìì í멎 ë©ëë€:
-
-```diff
-- torch.jit.trace(model, [tokens_tensor, segments_tensors])
-+ torch.neuron.trace(model, [token_tensor, segments_tensors])
-```
-
-ìŽëĄìš Neuron SDKê° ëȘšëžì ì¶ì íêł Inf1 ìžì€íŽì€ì ì”ì íí ì ìêČ ë©ëë€.
-
-AWS Neuron SDKì êž°ë„, ëê”Ź, ìì íí ëŠŹìŒ ë° ì”ì ì
ë°ìŽížì ëíŽ ììží ììëłŽë €ë©Ž [AWS NeuronSDK 돞ì](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/index.html)넌 ì°žìĄ°íìžì.
diff --git a/docs/source/ko/training.md b/docs/source/ko/training.md
new file mode 100644
index 000000000000..4e375f0f7215
--- /dev/null
+++ b/docs/source/ko/training.md
@@ -0,0 +1,428 @@
+
+
+# ìŹì íì”ë ëȘšëž ëŻžìž íëíêž°[[finetune-a-pretrained-model]]
+
+[[open-in-colab]]
+
+ìŹì íì”ë ëȘšëžì ìŹì©í멎 ìëčí ìŽì ìŽ ìì”ëë€. êłì° ëčì©êłŒ íìë°ìê”ì ì€ìŽêł , ìČìë¶í° ëȘšëžì íì”ìíŹ íì ììŽ ì”ì ëȘšëžì ìŹì©í ì ìì”ëë€. đ€ Transformersë ë€ìí ìì
ì ìíŽ ìŹì íì”ë ììČ ê°ì ëȘšëžì ìĄìžì€í ì ìì”ëë€. ìŹì íì”ë ëȘšëžì ìŹì©íë êČœì°, ìì ì ìì
êłŒ êŽë šë ë°ìŽí°ì
ì ìŹì©íŽ íì”í©ëë€. ìŽêČì ëŻžìž íëìŽëŒêł íë ë§€ì° ê°ë „í íë š êž°ëČì
ëë€. ìŽ íí 늏ìŒììë ëčì ìŽ ì íí ë„ëŹë íë ììíŹëĄ ìŹì íì”ë ëȘšëžì ëŻžìž íëí©ëë€:
+
+* đ€ TransformersëĄ ìŹì íì”ë ëȘšëž ëŻžìž íëíêž° [`Trainer`].
+* Keras넌 ìŹì©íìŹ TensorFlowìì ìŹì íì”ë ëȘšëžì ëŻžìž íëíêž°.
+* êž°ëłž PyTorchìì ìŹì íì”ë ëȘšëžì ëŻžìž íëíêž°.
+
+
+
+## ë°ìŽí°ì
ì€ëč[[prepare-a-dataset]]
+
+
+
+ìŹì íì”ë ëȘšëžì ëŻžìž íëíêž° ìíŽì ë°ìŽí°ì
ì ë€ìŽëĄëíêł íë ší ì ìëëĄ ì€ëčíìžì. ìŽì íí 늏ìŒìì íë šì ìíŽ ë°ìŽí°ë„Œ ìČ늏íë ë°©ëČì 볎ìŹëë žëë°, ì§êžìŽ ë°°ìž ê±ž ëì§ì êž°íì
ëë€!
+
+뚌ì [Yelp 늏뷰](https://huggingface.co/datasets/yelp_review_full) ë°ìŽí° ìžížë„Œ ëĄëí©ëë€:
+
+```py
+>>> from datasets import load_dataset
+
+>>> dataset = load_dataset("yelp_review_full")
+>>> dataset["train"][100]
+{'label': 0,
+ '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!'}
+```
+
+í
ì€ížë„Œ ìČ늏íêł ìëĄ ë€ë„ž êžžìŽì ìíì€ íšë© ë° ìëŒëŽêž° ì ë”ì íŹíšíë €ë©Ž í íŹëìŽì ê° íìí©ëë€. ë°ìŽí°ì
ì í ëČì ìČ늏íë €ë©Ž đ€ Dataset [`map`](https://huggingface.co/docs/datasets/process.html#map) ë©ìë넌 ìŹì©íìŹ ì ìČŽ ë°ìŽí°ì
ì ì ìČ늏 íšì넌 ì ì©íìžì:
+
+```py
+>>> from transformers import AutoTokenizer
+
+>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
+
+
+>>> def tokenize_function(examples):
+... return tokenizer(examples["text"], padding="max_length", truncation=True)
+
+
+>>> tokenized_datasets = dataset.map(tokenize_function, batched=True)
+```
+
+íìí êČœì° ëŻžìž íëì ìíŽ ë°ìŽí°ì
ì ìì ë¶ë¶ ì§í©ì ë§ë€ìŽ ëŻžìž íë ìì
ìê°ì ì€ìŒ ì ìì”ëë€:
+
+```py
+>>> small_train_dataset = tokenized_datasets["train"].shuffle(seed=42).select(range(1000))
+>>> small_eval_dataset = tokenized_datasets["test"].shuffle(seed=42).select(range(1000))
+```
+
+
+
+## Train
+
+ìŹêž°ìë¶í°ë ìŹì©íë €ë íë ììíŹì íŽëčíë ìčì
ì ë°ëŒìŒ í©ëë€. ì€ë„žìȘœ ìŹìŽëë°ì ë§íŹë„Œ ìŹì©íìŹ ìíë íë ììíŹëĄ ìŽëí ì ììŒë©°, íčì íë ììíŹì ëȘšë ìœí
ìž ë„Œ ìšêž°ë €ë©Ž íŽëč íë ììíŹ ëžëĄì ì€ë„žìȘœ ìëšì ìë ëČíŒì ìŹì©í멎 ë©ëë€!
+
+
+
+
+
+## íìŽí ìč TrainerëĄ íë šíêž°[[train-with-pytorch-trainer]]
+
+đ€ Transformersë đ€ Transformers ëȘšëž íë šì ì”ì íë [`Trainer`] íŽëì€ë„Œ ì êł”íìŹ íë š 룚í넌 ì§ì ìì±íì§ ìêł ë ìœêČ íë šì ììí ì ìì”ëë€. [`Trainer`] APIë ëĄêč
(logging), êČœìŹ ëì (gradient accumulation), íŒí© ì ë°ë(mixed precision) ë± ë€ìí íë š ì”ì
êłŒ êž°ë„ì ì§ìí©ëë€.
+
+뚌ì ëȘšëžì ê°ì žì€êł ììëë ë ìŽëž ì넌 ì§ì í©ëë€. Yelp 늏뷰 [ë°ìŽí°ì
ìčŽë](https://huggingface.co/datasets/yelp_review_full#data-fields)ìì 5ê°ì ë ìŽëžìŽ ììì ì ì ìì”ëë€:
+
+```py
+>>> from transformers import AutoModelForSequenceClassification
+
+>>> model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=5)
+```
+
+
+
+ìŹì íë šë ê°ì€ìč ì€ ìŒë¶ê° ìŹì©ëì§ ìêł ìŒë¶ ê°ì€ìčê° ëŹŽììëĄ íìëë€ë êČœêł ê° íìë©ëë€.
+ê±±ì ë§ìžì. ìŽêČì ìŹë°ë„ž ëìì
ëë€! ìŹì íì”ë BERT ëȘšëžì í€ëë íêž°ëêł ëŹŽììëĄ ìŽêž°íë ë¶ë„ í€ëëĄ ëìČŽë©ëë€. ìŽì ìŹì íì”ë ëȘšëžì ì§ììŒëĄ ìíì€ ë¶ë„ ìì
ì ìí ìëĄìŽ ëȘšëž í€ë넌 ëŻžìž íë í©ëë€.
+
+
+
+### íìŽíŒíëŒëŻží° íë š[[training-hyperparameters]]
+
+ë€ììŒëĄ ì í ì ìë ëȘšë íìŽíŒíëŒëŻží°ì ë€ìí íë š ì”ì
ì íì±ííêž° ìí íë귞넌 íŹíšíë [`TrainingArguments`] íŽëì€ë„Œ ìì±í©ëë€.
+
+ìŽ íí 늏ìŒììë êž°ëłž íë š [íìŽíŒíëŒëŻží°](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments)ëĄ ììíì§ë§, ìì ëĄêČ ì€ííìŹ ìŹëŹë¶ë€ìêČ ë§ë ì”ì ì ì€ì ì ì°Ÿì ì ìì”ëë€.
+
+íë šìì ìČŽíŹíŹìžíž(checkpoints)넌 ì ì„í ììč넌 ì§ì í©ëë€:
+
+```py
+>>> from transformers import TrainingArguments
+
+>>> training_args = TrainingArguments(output_dir="test_trainer")
+```
+
+### íê° íêž°[[evaluate]]
+
+[`Trainer`]ë íë š ì€ì ëȘšëž ì±ë„ì ìëìŒëĄ íê°íì§ ìì”ëë€. íê° ì§í넌 êłì°íêł ëłŽêł í íšì넌 [`Trainer`]ì ì ëŹíŽìŒ í©ëë€.
+[đ€ 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)넌 ì°žìĄ°íìžì):
+
+```py
+>>> import numpy as np
+>>> import evaluate
+
+>>> metric = evaluate.load("accuracy")
+```
+
+`metric`ìì [`~evaluate.compute`]넌 ížì¶íìŹ ììžĄì ì íë넌 êłì°í©ëë€. ììžĄì `compute`ì ì ëŹíêž° ì ì ììžĄì ëĄì§ìŒëĄ ëłííŽìŒ í©ëë€(ëȘšë đ€ Transformers ëȘšëžì ëĄì§ìŒëĄ ë°ííë€ë ì ì êž°ì”íìžì):
+
+```py
+>>> def compute_metrics(eval_pred):
+... logits, labels = eval_pred
+... predictions = np.argmax(logits, axis=-1)
+... return metric.compute(predictions=predictions, references=labels)
+```
+
+ëŻžìž íë ì€ì íê° ì§í넌 ëȘšëí°ë§íë €ë©Ž íë š ìžìì `evaluation_strategy` íëŒëŻží°ë„Œ ì§ì íìŹ ê° ìíìŽ ëë ë íê° ì§í넌 íìží ì ìì”ëë€:
+
+```py
+>>> from transformers import TrainingArguments, Trainer
+
+>>> training_args = TrainingArguments(output_dir="test_trainer", evaluation_strategy="epoch")
+```
+
+### íë š íêž°[[trainer]]
+
+ëȘšëž, íë š ìžì, íë š ë° í
ì€íž ë°ìŽí°ì
, íê° íšìê° íŹíšë [`Trainer`] ê°ìČŽë„Œ ë§ëëë€:
+
+```py
+>>> trainer = Trainer(
+... model=model,
+... args=training_args,
+... train_dataset=small_train_dataset,
+... eval_dataset=small_eval_dataset,
+... compute_metrics=compute_metrics,
+... )
+```
+
+ê·žëŠŹêł [`~transformers.Trainer.train`]ì ížì¶íìŹ ëȘšëžì ëŻžìž íëí©ëë€:
+
+```py
+>>> trainer.train()
+```
+
+
+
+
+
+
+## KerasëĄ í
ìíëĄì° ëȘšëž íë šíêž°[[train-a-tensorflow-model-with-keras]]
+
+Keras API넌 ìŹì©íìŹ í
ìíëĄì°ìì đ€ Transformers ëȘšëžì íë ší ìë ìì”ëë€!
+
+### Kerasì© ë°ìŽí° ëĄë[[loading-data-for-keras]]
+
+Keras APIëĄ đ€ Transformers ëȘšëžì íì”ìí€ë €ë©Ž ë°ìŽí°ì
ì Kerasê° ìŽíŽí ì ìë íììŒëĄ ëłííŽìŒ í©ëë€.
+ë°ìŽí° ìžížê° ìì êČœì°, ì ìČŽë„Œ NumPy ë°°ìŽëĄ ëłííìŹ KerasëĄ ì ëŹí멎 ë©ëë€.
+ë ëł”ìĄí ìì
ì ìííêž° ì ì 뚌ì ìŽ ìì
ì ìëíŽ ëłŽêČ ì”ëë€.
+
+뚌ì ë°ìŽí° ìžížë„Œ ëĄëí©ëë€. [GLUE ëČ€ìčë§íŹ](https://huggingface.co/datasets/glue)ì CoLA ë°ìŽí° ìžížë„Œ ìŹì©íêČ ì”ëë€.
+ê°ëší ë°ìŽë늏 í
ì€íž ë¶ë„ ìì
ìŽëŻëĄ ì§êžì íë š ë°ìŽí° ë¶í ë§ ìŹì©í©ëë€.
+
+```py
+from datasets import load_dataset
+
+dataset = load_dataset("glue", "cola")
+dataset = dataset["train"] # Just take the training split for now
+```
+
+ë€ììŒëĄ í íŹëìŽì 넌 ëĄëíêł ë°ìŽí°ë„Œ NumPy ë°°ìŽëĄ í í°íí©ëë€. ë ìŽëžì ìŽëŻž 0êłŒ 1ëĄ ë 늏ì€ížìŽêž° ë돞ì í í°ííì§ ìêł ë°ëĄ NumPy ë°°ìŽëĄ ëłíí ì ìì”ëë€!
+
+```py
+from transformers import AutoTokenizer
+
+tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
+tokenized_data = tokenizer(dataset["sentence"], return_tensors="np", padding=True)
+# Tokenizer returns a BatchEncoding, but we convert that to a dict for Keras
+tokenized_data = dict(tokenized_data)
+
+labels = np.array(dataset["label"]) # Label is already an array of 0 and 1
+```
+
+ë§ì§ë§ìŒëĄ ëȘšëžì ëĄë, [`compile`](https://keras.io/api/models/model_training_apis/#compile-method), [`fit`](https://keras.io/api/models/model_training_apis/#fit-method)í©ëë€:
+
+```py
+from transformers import TFAutoModelForSequenceClassification
+from tensorflow.keras.optimizers import Adam
+
+# Load and compile our model
+model = TFAutoModelForSequenceClassification.from_pretrained("bert-base-cased")
+# Lower learning rates are often better for fine-tuning transformers
+model.compile(optimizer=Adam(3e-5))
+
+model.fit(tokenized_data, labels)
+```
+
+
+
+ëȘšëžì `compile()`í ë ìì€ ìžì넌 ëȘšëžì ì ëŹí íìê° ìì”ëë€!
+ìŽ ìžì넌 ëčìë멎 íêč
íìŽì€ ëȘšëžì ìì
êłŒ ëȘšëž ìí€í
ìČì ì í©í ìì€ì ìëìŒëĄ ì íí©ëë€.
+ìíë€ë©Ž ìžì ë ì§ ì§ì ìì€ì ì§ì íìŹ ìŽë„Œ ìŹì ìí ì ìì”ëë€!
+
+
+
+ìŽ ì ê·Œ ë°©ìì ìê·ëȘš ë°ìŽí° ì§í©ììë ì ìëíì§ë§, ëê·ëȘš ë°ìŽí° ì§í©ììë 돞ì ê° ë ì ìì”ëë€. ì ê·žëŽêčì?
+í í°íë ë°°ìŽêłŒ ë ìŽëžì ë©ëȘšëŠŹì ìì í ëĄëíêł NumPyë "ë€ìë ìí" ë°°ìŽì ìČ늏íì§ ìêž° ë돞ì,
+ëȘšë í í°íë ìíì ì ìČŽ ë°ìŽí°ì
ìì ê°ì„ ꞎ ìíì êžžìŽë§íŒ íšë©íŽìŒ í©ëë€. ìŽë êČ í멎 ë°°ìŽìŽ íšìŹ ë 컀ì§êł ìŽ íšë© í í°ìŒëĄ ìžíŽ íì” ìëë ëë €ì§ëë€!
+
+### ë°ìŽí°ë„Œ tf.data.DatasetìŒëĄ ëĄëíêž°[[loading-data-as-a-tfdatadataset]]
+
+íì” ìëê° ëë €ì§ë êČì íŒíë €ë©Ž ë°ìŽí°ë„Œ `tf.data.Dataset`ìŒëĄ ëĄëí ì ìì”ëë€. ìíë€ë©Ž ì§ì
+`tf.data` íìŽíëŒìžì ì§ì ìì±í ìë ìì§ë§, ìŽ ìì
ì ê°ížíêČ ìííë ì ìë ë ê°ì§ ë°©ëČìŽ ìì”ëë€:
+
+- [`~TFPreTrainedModel.prepare_tf_dataset`]: ëë¶ë¶ì êČœì° ìŽ ë°©ëČì ê¶ì„í©ëë€. ëȘšëžì ë©ìëìŽêž° ë돞ì ëȘšëžì êČìŹíìŹ ëȘšëž ì
ë „ìŒëĄ ìŹì©í ì ìë ìŽì ìëìŒëĄ íì
íêł
+ëëšžì§ë ëČë €ì ë ëšìíêł ì±ë„ìŽ ìąì ë°ìŽí° ì§í©ì ë§ë€ ì ìì”ëë€.
+- [`~datasets.Dataset.to_tf_dataset`]: ìŽ ë°©ëČì ìą ë ëźì ìì€ìŽë©°, íŹíší 'ìŽ'êłŒ 'ë ìŽëž'ì ì íí ì§ì íìŹ
+ë°ìŽí°ì
ì ìì±íë ë°©ëČì ì íí ì ìŽíêł ì¶ì ë ì ì©íë©°, íŹíší 'columns'êłŒ 'label_cols'ì ì íí ì§ì í ì ìì”ëë€.
+
+[`~TFPreTrainedModel.prepare_tf_dataset`]ì ìŹì©íë €ë©Ž 뚌ì ë€ì ìœë ìíêłŒ ê°ìŽ í íŹëìŽì ì¶ë „ì ë°ìŽí° ìžížì ìŽëĄ ì¶ê°íŽìŒ í©ëë€:
+
+```py
+def tokenize_dataset(data):
+ # Keys of the returned dictionary will be added to the dataset as columns
+ return tokenizer(data["text"])
+
+
+dataset = dataset.map(tokenize_dataset)
+```
+
+íêč
íìŽì€ ë°ìŽí°ì
ì êž°ëłžì ìŒëĄ ëì€íŹì ì ì„ëëŻëĄ ë©ëȘšëŠŹ ìŹì©ëì ëëŠŹì§ ìëë€ë ì ì êž°ì”íìžì!
+ìŽìŽ ì¶ê°ë멎 ë°ìŽí°ì
ìì ë°°ìč넌 ì€ížëŠŹë°íêł ê° ë°°ìčì íšë©ì ì¶ê°í ì ììŒëŻëĄ ì ìČŽ ë°ìŽí°ì
ì íšë©ì ì¶ê°íë êČëłŽë€ íšë© í í°ì ì넌 íŹêČ ì€ìŒ ì ìì”ëë€.
+
+
+```py
+>>> tf_dataset = model.prepare_tf_dataset(dataset, batch_size=16, shuffle=True, tokenizer=tokenizer)
+```
+
+ìì ìœë ìíììë ë°°ìčê° ëĄëë ë ìŹë°ë„ŽêČ íšë©í ì ìëëĄ `prepare_tf_dataset`ì í íŹëìŽì 넌 ì ëŹíŽìŒ í©ëë€.
+ë°ìŽí°ì
ì ëȘšë ìí êžžìŽê° ê°êł íšë©ìŽ íìíì§ ìì êČœì° ìŽ ìžì넌 걎ëëž ì ìì”ëë€.
+ìíì ì±ì°ë êČëłŽë€ ë ëł”ìĄí ìì
(ì: ë§ì€íčë ìžìŽì í í° ìì ëȘšëžë§)ì ìííêž° ìíŽ í í°ì ììììŒìŒ íë êČœì°,
+`collate_fn` ìžì넌 ìŹì©íìŹ ìí ëȘ©ëĄì ë°°ìčëĄ ëłííêł ìíë ì ìČëŠŹë„Œ ì ì©í íšì넌 ì ëŹí ì ìì”ëë€.
+[ìì](https://github.com/huggingface/transformers/tree/main/examples) ëë
+[ë
žížë¶](https://huggingface.co/docs/transformers/notebooks)ì ì°žìĄ°íìŹ ìŽ ì ê·Œ ë°©ììŽ ì€ì ëĄ ìëíë ëȘšì”ì íìžíìžì.
+
+`tf.data.Dataset`ì ìì±í íìë ìŽì êłŒ ë§ì°Źê°ì§ëĄ ëȘšëžì 컎íìŒíêł íë š(fit)í ì ìì”ëë€:
+
+```py
+model.compile(optimizer=Adam(3e-5))
+
+model.fit(tf_dataset)
+```
+
+
+
+
+
+
+## êž°ëłž íìŽí ìčëĄ íë šíêž°[[train-in-native-pytorch]]
+
+
+
+
+
+[`Trainer`]ë íë š 룚í넌 ìČ늏íë©° í ì€ì ìœëëĄ ëȘšëžì ëŻžìž ìĄ°ì í ì ìì”ëë€. ì§ì íë š 룚í넌 ìì±íë êČì ì ížíë ìŹì©ìì êČœì°, êž°ëłž PyTorchìì đ€ Transformers ëȘšëžì ëŻžìž ìĄ°ì í ìë ìì”ëë€.
+
+ìŽ ìì ìì ë
žížë¶ì ë€ì ììíê±°ë ë€ì ìœë넌 ì€ííŽ ë©ëȘšëŠŹë„Œ í볎íŽìŒ í ì ìì”ëë€:
+
+```py
+del model
+del trainer
+torch.cuda.empty_cache()
+```
+
+ë€ììŒëĄ, 'í í°íë ë°ìŽí°ì
'ì ìëìŒëĄ íìČ늏íìŹ íë šë šì ìŹì©í ì ìëëĄ ì€ëčí©ëë€.
+
+1. ëȘšëžìŽ ìì í
ì€ížë„Œ ì
ë „ìŒëĄ íì©íì§ ììŒëŻëĄ `text` ìŽì ì ê±°í©ëë€:
+
+ ```py
+ >>> tokenized_datasets = tokenized_datasets.remove_columns(["text"])
+ ```
+
+2. ëȘšëžìì ìžìì ìŽëŠìŽ `labels`ëĄ ì§ì ë êČìŒëĄ ììíëŻëĄ `label` ìŽì ìŽëŠì `labels`ëĄ ëłêČœí©ëë€:
+
+ ```py
+ >>> tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
+ ```
+
+3. ë°ìŽí°ì
ì íìì List ëì PyTorch í
ì넌 ë°ííëëĄ ì€ì í©ëë€:
+
+ ```py
+ >>> tokenized_datasets.set_format("torch")
+ ```
+
+ê·žëŠŹêł ìì íìë ëëĄ ë°ìŽí°ì
ì ë ìì íì ì§í©ì ìì±íìŹ ëŻžìž ìĄ°ì ìë넌 ëì
ëë€:
+
+```py
+>>> small_train_dataset = tokenized_datasets["train"].shuffle(seed=42).select(range(1000))
+>>> small_eval_dataset = tokenized_datasets["test"].shuffle(seed=42).select(range(1000))
+```
+
+### DataLoader[[dataloader]]
+
+íë š ë° í
ì€íž ë°ìŽí°ì
ì ëí 'DataLoader'넌 ìì±íìŹ ë°ìŽí° ë°°ìč넌 ë°ëł”í ì ìì”ëë€:
+
+```py
+>>> from torch.utils.data import DataLoader
+
+>>> train_dataloader = DataLoader(small_train_dataset, shuffle=True, batch_size=8)
+>>> eval_dataloader = DataLoader(small_eval_dataset, batch_size=8)
+```
+
+ììžĄì ìí ë ìŽëž ê°ì넌 ìŹì©íìŹ ëȘšëžì ëĄëí©ëë€:
+
+```py
+>>> from transformers import AutoModelForSequenceClassification
+
+>>> model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=5)
+```
+
+### ì”í°ë§ìŽì ë° íì” ìë ì€ìŒì€ëŹ[[optimizer-and-learning-rate-scheduler]]
+
+ì”í°ë§ìŽì ì íì” ìë ì€ìŒì€ëŹë„Œ ìì±íìŹ ëȘšëžì ëŻžìž ìĄ°ì í©ëë€. íìŽí ìčìì ì êł”íë [`AdamW`](https://pytorch.org/docs/stable/generated/torch.optim.AdamW.html) ì”í°ë§ìŽì 넌 ìŹì©íŽ ëłŽêČ ì”ëë€:
+
+```py
+>>> from torch.optim import AdamW
+
+>>> optimizer = AdamW(model.parameters(), lr=5e-5)
+```
+
+[`Trainer`]ìì êž°ëłž íì” ìë ì€ìŒì€ëŹë„Œ ìì±í©ëë€:
+
+```py
+>>> from transformers import get_scheduler
+
+>>> num_epochs = 3
+>>> num_training_steps = num_epochs * len(train_dataloader)
+>>> lr_scheduler = get_scheduler(
+... name="linear", optimizer=optimizer, num_warmup_steps=0, num_training_steps=num_training_steps
+... )
+```
+
+ë§ì§ë§ìŒëĄ, GPUì ìĄìžì€í ì ìë êČœì° 'device'넌 ì§ì íìŹ GPU넌 ìŹì©íëëĄ í©ëë€. ê·žë ì§ ììŒë©Ž CPUìì íë šíë©° ëȘ ë¶ìŽ ìë ëȘ ìê°ìŽ ê±žëŠŽ ì ìì”ëë€.
+
+```py
+>>> import torch
+
+>>> device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
+>>> model.to(device)
+```
+
+
+
+[Colaboratory](https://colab.research.google.com/) ëë [SageMaker StudioLab](https://studiolab.sagemaker.aws/)êłŒ ê°ì ížì€í
ë
žížë¶ìŽ ìë êČœì° íŽëŒì°ë GPUì 돎ëŁëĄ ìĄìžì€í ì ìì”ëë€.
+
+
+
+ìŽì íë ší ì€ëčê° ëìì”ëë€! đ„ł
+
+### íë š 룚í[[training-loop]]
+
+íë š ì§í ìí©ì ì¶ì íë €ë©Ž [tqdm](https://tqdm.github.io/) ëŒìŽëžëŹëŠŹë„Œ ìŹì©íìŹ ížë ìŽë ëšêł ìì ì§íë„ íìì€ì ì¶ê°íìžì:
+
+```py
+>>> from tqdm.auto import tqdm
+
+>>> progress_bar = tqdm(range(num_training_steps))
+
+>>> model.train()
+>>> for epoch in range(num_epochs):
+... for batch in train_dataloader:
+... batch = {k: v.to(device) for k, v in batch.items()}
+... outputs = model(**batch)
+... loss = outputs.loss
+... loss.backward()
+
+... optimizer.step()
+... lr_scheduler.step()
+... optimizer.zero_grad()
+... progress_bar.update(1)
+```
+
+### íê° íêž°[[evaluate]]
+
+[`Trainer`]ì íê° íšì넌 ì¶ê°í ë°©ëČêłŒ ë§ì°Źê°ì§ëĄ, íë š 룚í넌 ì§ì ìì±í ëë ëìŒí ìì
ì ìííŽìŒ í©ëë€. íì§ë§ ìŽëČìë ê° ìíŹíŹê° ëë ëë§ë€ íê°ì§í넌 êłì°íìŹ ëłŽêł íë ëì , [`~evaluate.add_batch`]넌 ìŹì©íìŹ ëȘšë ë°°ìč넌 ëì íêł ë§š ë§ì§ë§ì íê°ì§í넌 êłì°í©ëë€.
+
+```py
+>>> import evaluate
+
+>>> metric = evaluate.load("accuracy")
+>>> model.eval()
+>>> for batch in eval_dataloader:
+... batch = {k: v.to(device) for k, v in batch.items()}
+... with torch.no_grad():
+... outputs = model(**batch)
+
+... logits = outputs.logits
+... predictions = torch.argmax(logits, dim=-1)
+... metric.add_batch(predictions=predictions, references=batch["labels"])
+
+>>> metric.compute()
+```
+
+
+
+
+
+## ì¶ê° ìëŁ[[additional-resources]]
+
+ë ë§ì ëŻžìž íë ìì ë ë€ìì ì°žìĄ°íìžì:
+
+- [đ€ Trnasformers ìì ](https://github.com/huggingface/transformers/tree/main/examples)ìë PyTorch ë° í
ìíëĄì°ìì ìŒë°ì ìž NLP ìì
ì íë ší ì ìë ì€íŹëŠœížê° íŹíšëìŽ ìì”ëë€.
+
+- [đ€ Transformers ë
žížë¶](notebooks)ìë PyTorch ë° í
ìíëĄì°ìì íčì ìì
ì ìíŽ ëȘšëžì ëŻžìž íëíë ë°©ëČì ëí ë€ìí ë
žížë¶ìŽ íŹíšëìŽ ìì”ëë€.
diff --git a/docs/source/ko/training.mdx b/docs/source/ko/training.mdx
deleted file mode 100644
index 0366c656f0a0..000000000000
--- a/docs/source/ko/training.mdx
+++ /dev/null
@@ -1,424 +0,0 @@
-
-
-# ìŹì íì”ë ëȘšëž ëŻžìž íëíêž°[[finetune-a-pretrained-model]]
-
-[[open-in-colab]]
-
-ìŹì íì”ë ëȘšëžì ìŹì©í멎 ìëčí ìŽì ìŽ ìì”ëë€. êłì° ëčì©êłŒ íìë°ìê”ì ì€ìŽêł , ìČìë¶í° ëȘšëžì íì”ìíŹ íì ììŽ ì”ì ëȘšëžì ìŹì©í ì ìì”ëë€. đ€ Transformersë ë€ìí ìì
ì ìíŽ ìŹì íì”ë ììČ ê°ì ëȘšëžì ìĄìžì€í ì ìì”ëë€. ìŹì íì”ë ëȘšëžì ìŹì©íë êČœì°, ìì ì ìì
êłŒ êŽë šë ë°ìŽí°ì
ì ìŹì©íŽ íì”í©ëë€. ìŽêČì ëŻžìž íëìŽëŒêł íë ë§€ì° ê°ë „í íë š êž°ëČì
ëë€. ìŽ íí 늏ìŒììë ëčì ìŽ ì íí ë„ëŹë íë ììíŹëĄ ìŹì íì”ë ëȘšëžì ëŻžìž íëí©ëë€:
-
-* đ€ TransformersëĄ ìŹì íì”ë ëȘšëž ëŻžìž íëíêž° [`Trainer`].
-* Keras넌 ìŹì©íìŹ TensorFlowìì ìŹì íì”ë ëȘšëžì ëŻžìž íëíêž°.
-* êž°ëłž PyTorchìì ìŹì íì”ë ëȘšëžì ëŻžìž íëíêž°.
-
-
-
-## ë°ìŽí°ì
ì€ëč[[prepare-a-dataset]]
-
-
-
-ìŹì íì”ë ëȘšëžì ëŻžìž íëíêž° ìíŽì ë°ìŽí°ì
ì ë€ìŽëĄëíêł íë ší ì ìëëĄ ì€ëčíìžì. ìŽì íí 늏ìŒìì íë šì ìíŽ ë°ìŽí°ë„Œ ìČ늏íë ë°©ëČì 볎ìŹëë žëë°, ì§êžìŽ ë°°ìž ê±ž ëì§ì êž°íì
ëë€!
-
-뚌ì [Yelp 늏뷰](https://huggingface.co/datasets/yelp_review_full) ë°ìŽí° ìžížë„Œ ëĄëí©ëë€:
-
-```py
->>> from datasets import load_dataset
-
->>> dataset = load_dataset("yelp_review_full")
->>> dataset["train"][100]
-{'label': 0,
- '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!'}
-```
-
-í
ì€ížë„Œ ìČ늏íêł ìëĄ ë€ë„ž êžžìŽì ìíì€ íšë© ë° ìëŒëŽêž° ì ë”ì íŹíšíë €ë©Ž í íŹëìŽì ê° íìí©ëë€. ë°ìŽí°ì
ì í ëČì ìČ늏íë €ë©Ž đ€ Dataset [`map`](https://huggingface.co/docs/datasets/process.html#map) ë©ìë넌 ìŹì©íìŹ ì ìČŽ ë°ìŽí°ì
ì ì ìČ늏 íšì넌 ì ì©íìžì:
-
-```py
->>> from transformers import AutoTokenizer
-
->>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
-
-
->>> def tokenize_function(examples):
-... return tokenizer(examples["text"], padding="max_length", truncation=True)
-
-
->>> tokenized_datasets = dataset.map(tokenize_function, batched=True)
-```
-
-íìí êČœì° ëŻžìž íëì ìíŽ ë°ìŽí°ì
ì ìì ë¶ë¶ ì§í©ì ë§ë€ìŽ ëŻžìž íë ìì
ìê°ì ì€ìŒ ì ìì”ëë€:
-
-```py
->>> small_train_dataset = tokenized_datasets["train"].shuffle(seed=42).select(range(1000))
->>> small_eval_dataset = tokenized_datasets["test"].shuffle(seed=42).select(range(1000))
-```
-
-
-
-## Train
-
-ìŹêž°ìë¶í°ë ìŹì©íë €ë íë ììíŹì íŽëčíë ìčì
ì ë°ëŒìŒ í©ëë€. ì€ë„žìȘœ ìŹìŽëë°ì ë§íŹë„Œ ìŹì©íìŹ ìíë íë ììíŹëĄ ìŽëí ì ììŒë©°, íčì íë ììíŹì ëȘšë ìœí
ìž ë„Œ ìšêž°ë €ë©Ž íŽëč íë ììíŹ ëžëĄì ì€ë„žìȘœ ìëšì ìë ëČíŒì ìŹì©í멎 ë©ëë€!
-
-
-
-
-
-## íìŽí ìč TrainerëĄ íë šíêž°[[train-with-pytorch-trainer]]
-
-đ€ Transformersë đ€ Transformers ëȘšëž íë šì ì”ì íë [`Trainer`] íŽëì€ë„Œ ì êł”íìŹ íë š 룚í넌 ì§ì ìì±íì§ ìêł ë ìœêČ íë šì ììí ì ìì”ëë€. [`Trainer`] APIë ëĄêč
(logging), êČœìŹ ëì (gradient accumulation), íŒí© ì ë°ë(mixed precision) ë± ë€ìí íë š ì”ì
êłŒ êž°ë„ì ì§ìí©ëë€.
-
-뚌ì ëȘšëžì ê°ì žì€êł ììëë ë ìŽëž ì넌 ì§ì í©ëë€. Yelp 늏뷰 [ë°ìŽí°ì
ìčŽë](https://huggingface.co/datasets/yelp_review_full#data-fields)ìì 5ê°ì ë ìŽëžìŽ ììì ì ì ìì”ëë€:
-
-```py
->>> from transformers import AutoModelForSequenceClassification
-
->>> model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=5)
-```
-
-
-
-ìŹì íë šë ê°ì€ìč ì€ ìŒë¶ê° ìŹì©ëì§ ìêł ìŒë¶ ê°ì€ìčê° ëŹŽììëĄ íìëë€ë êČœêł ê° íìë©ëë€.
-ê±±ì ë§ìžì. ìŽêČì ìŹë°ë„ž ëìì
ëë€! ìŹì íì”ë BERT ëȘšëžì í€ëë íêž°ëêł ëŹŽììëĄ ìŽêž°íë ë¶ë„ í€ëëĄ ëìČŽë©ëë€. ìŽì ìŹì íì”ë ëȘšëžì ì§ììŒëĄ ìíì€ ë¶ë„ ìì
ì ìí ìëĄìŽ ëȘšëž í€ë넌 ëŻžìž íë í©ëë€.
-
-
-
-### íìŽíŒíëŒëŻží° íë š[[training-hyperparameters]]
-
-ë€ììŒëĄ ì í ì ìë ëȘšë íìŽíŒíëŒëŻží°ì ë€ìí íë š ì”ì
ì íì±ííêž° ìí íë귞넌 íŹíšíë [`TrainingArguments`] íŽëì€ë„Œ ìì±í©ëë€.
-
-ìŽ íí 늏ìŒììë êž°ëłž íë š [íìŽíŒíëŒëŻží°](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments)ëĄ ììíì§ë§, ìì ëĄêČ ì€ííìŹ ìŹëŹë¶ë€ìêČ ë§ë ì”ì ì ì€ì ì ì°Ÿì ì ìì”ëë€.
-
-íë šìì ìČŽíŹíŹìžíž(checkpoints)넌 ì ì„í ììč넌 ì§ì í©ëë€:
-
-```py
->>> from transformers import TrainingArguments
-
->>> training_args = TrainingArguments(output_dir="test_trainer")
-```
-
-### íê° íêž°[[evaluate]]
-
-[`Trainer`]ë íë š ì€ì ëȘšëž ì±ë„ì ìëìŒëĄ íê°íì§ ìì”ëë€. íê° ì§í넌 êłì°íêł ëłŽêł í íšì넌 [`Trainer`]ì ì ëŹíŽìŒ í©ëë€.
-[đ€ 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)넌 ì°žìĄ°íìžì):
-
-```py
->>> import numpy as np
->>> import evaluate
-
->>> metric = evaluate.load("accuracy")
-```
-
-`metric`ìì [`~evaluate.compute`]넌 ížì¶íìŹ ììžĄì ì íë넌 êłì°í©ëë€. ììžĄì `compute`ì ì ëŹíêž° ì ì ììžĄì ëĄì§ìŒëĄ ëłííŽìŒ í©ëë€(ëȘšë đ€ Transformers ëȘšëžì ëĄì§ìŒëĄ ë°ííë€ë ì ì êž°ì”íìžì):
-
-```py
->>> def compute_metrics(eval_pred):
-... logits, labels = eval_pred
-... predictions = np.argmax(logits, axis=-1)
-... return metric.compute(predictions=predictions, references=labels)
-```
-
-ëŻžìž íë ì€ì íê° ì§í넌 ëȘšëí°ë§íë €ë©Ž íë š ìžìì `evaluation_strategy` íëŒëŻží°ë„Œ ì§ì íìŹ ê° ìíìŽ ëë ë íê° ì§í넌 íìží ì ìì”ëë€:
-
-```py
->>> from transformers import TrainingArguments, Trainer
-
->>> training_args = TrainingArguments(output_dir="test_trainer", evaluation_strategy="epoch")
-```
-
-### íë š íêž°[[trainer]]
-
-ëȘšëž, íë š ìžì, íë š ë° í
ì€íž ë°ìŽí°ì
, íê° íšìê° íŹíšë [`Trainer`] ê°ìČŽë„Œ ë§ëëë€:
-
-```py
->>> trainer = Trainer(
-... model=model,
-... args=training_args,
-... train_dataset=small_train_dataset,
-... eval_dataset=small_eval_dataset,
-... compute_metrics=compute_metrics,
-... )
-```
-
-ê·žëŠŹêł [`~transformers.Trainer.train`]ì ížì¶íìŹ ëȘšëžì ëŻžìž íëí©ëë€:
-
-```py
->>> trainer.train()
-```
-
-
-
-
-
-
-## KerasëĄ í
ìíëĄì° ëȘšëž íë šíêž°[[train-a-tensorflow-model-with-keras]]
-
-Keras API넌 ìŹì©íìŹ í
ìíëĄì°ìì đ€ Transformers ëȘšëžì íë ší ìë ìì”ëë€!
-
-### Kerasì© ë°ìŽí° ëĄë[[loading-data-for-keras]]
-
-Keras APIëĄ đ€ Transformers ëȘšëžì íì”ìí€ë €ë©Ž ë°ìŽí°ì
ì Kerasê° ìŽíŽí ì ìë íììŒëĄ ëłííŽìŒ í©ëë€.
-ë°ìŽí° ìžížê° ìì êČœì°, ì ìČŽë„Œ NumPy ë°°ìŽëĄ ëłííìŹ KerasëĄ ì ëŹí멎 ë©ëë€.
-ë ëł”ìĄí ìì
ì ìííêž° ì ì 뚌ì ìŽ ìì
ì ìëíŽ ëłŽêČ ì”ëë€.
-
-뚌ì ë°ìŽí° ìžížë„Œ ëĄëí©ëë€. [GLUE ëČ€ìčë§íŹ](https://huggingface.co/datasets/glue)ì CoLA ë°ìŽí° ìžížë„Œ ìŹì©íêČ ì”ëë€.
-ê°ëší ë°ìŽë늏 í
ì€íž ë¶ë„ ìì
ìŽëŻëĄ ì§êžì íë š ë°ìŽí° ë¶í ë§ ìŹì©í©ëë€.
-
-```py
-from datasets import load_dataset
-
-dataset = load_dataset("glue", "cola")
-dataset = dataset["train"] # Just take the training split for now
-```
-
-ë€ììŒëĄ í íŹëìŽì 넌 ëĄëíêł ë°ìŽí°ë„Œ NumPy ë°°ìŽëĄ í í°íí©ëë€. ë ìŽëžì ìŽëŻž 0êłŒ 1ëĄ ë 늏ì€ížìŽêž° ë돞ì í í°ííì§ ìêł ë°ëĄ NumPy ë°°ìŽëĄ ëłíí ì ìì”ëë€!
-
-```py
-from transformers import AutoTokenizer
-
-tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
-tokenized_data = tokenizer(dataset["sentence"], return_tensors="np", padding=True)
-# Tokenizer returns a BatchEncoding, but we convert that to a dict for Keras
-tokenized_data = dict(tokenized_data)
-
-labels = np.array(dataset["label"]) # Label is already an array of 0 and 1
-```
-
-ë§ì§ë§ìŒëĄ ëȘšëžì ëĄë, [`compile`](https://keras.io/api/models/model_training_apis/#compile-method), [`fit`](https://keras.io/api/models/model_training_apis/#fit-method)í©ëë€:
-
-```py
-from transformers import TFAutoModelForSequenceClassification
-from tensorflow.keras.optimizers import Adam
-
-# Load and compile our model
-model = TFAutoModelForSequenceClassification.from_pretrained("bert-base-cased")
-# Lower learning rates are often better for fine-tuning transformers
-model.compile(optimizer=Adam(3e-5))
-
-model.fit(tokenized_data, labels)
-```
-
-
-
-ëȘšëžì `compile()`í ë ìì€ ìžì넌 ëȘšëžì ì ëŹí íìê° ìì”ëë€!
-ìŽ ìžì넌 ëčìë멎 íêč
íìŽì€ ëȘšëžì ìì
êłŒ ëȘšëž ìí€í
ìČì ì í©í ìì€ì ìëìŒëĄ ì íí©ëë€.
-ìíë€ë©Ž ìžì ë ì§ ì§ì ìì€ì ì§ì íìŹ ìŽë„Œ ìŹì ìí ì ìì”ëë€!
-
-
-
-ìŽ ì ê·Œ ë°©ìì ìê·ëȘš ë°ìŽí° ì§í©ììë ì ìëíì§ë§, ëê·ëȘš ë°ìŽí° ì§í©ììë 돞ì ê° ë ì ìì”ëë€. ì ê·žëŽêčì?
-í í°íë ë°°ìŽêłŒ ë ìŽëžì ë©ëȘšëŠŹì ìì í ëĄëíêł NumPyë "ë€ìë ìí" ë°°ìŽì ìČ늏íì§ ìêž° ë돞ì,
-ëȘšë í í°íë ìíì ì ìČŽ ë°ìŽí°ì
ìì ê°ì„ ꞎ ìíì êžžìŽë§íŒ íšë©íŽìŒ í©ëë€. ìŽë êČ í멎 ë°°ìŽìŽ íšìŹ ë 컀ì§êł ìŽ íšë© í í°ìŒëĄ ìžíŽ íì” ìëë ëë €ì§ëë€!
-
-### ë°ìŽí°ë„Œ tf.data.DatasetìŒëĄ ëĄëíêž°[[loading-data-as-a-tfdatadataset]]
-
-íì” ìëê° ëë €ì§ë êČì íŒíë €ë©Ž ë°ìŽí°ë„Œ `tf.data.Dataset`ìŒëĄ ëĄëí ì ìì”ëë€. ìíë€ë©Ž ì§ì
-`tf.data` íìŽíëŒìžì ì§ì ìì±í ìë ìì§ë§, ìŽ ìì
ì ê°ížíêČ ìííë ì ìë ë ê°ì§ ë°©ëČìŽ ìì”ëë€:
-
-- [`~TFPreTrainedModel.prepare_tf_dataset`]: ëë¶ë¶ì êČœì° ìŽ ë°©ëČì ê¶ì„í©ëë€. ëȘšëžì ë©ìëìŽêž° ë돞ì ëȘšëžì êČìŹíìŹ ëȘšëž ì
ë „ìŒëĄ ìŹì©í ì ìë ìŽì ìëìŒëĄ íì
íêł
-ëëšžì§ë ëČë €ì ë ëšìíêł ì±ë„ìŽ ìąì ë°ìŽí° ì§í©ì ë§ë€ ì ìì”ëë€.
-- [`~datasets.Dataset.to_tf_dataset`]: ìŽ ë°©ëČì ìą ë ëźì ìì€ìŽë©°, íŹíší 'ìŽ'êłŒ 'ë ìŽëž'ì ì íí ì§ì íìŹ
-ë°ìŽí°ì
ì ìì±íë ë°©ëČì ì íí ì ìŽíêł ì¶ì ë ì ì©íë©°, íŹíší 'columns'êłŒ 'label_cols'ì ì íí ì§ì í ì ìì”ëë€.
-
-[`~TFPreTrainedModel.prepare_tf_dataset`]ì ìŹì©íë €ë©Ž 뚌ì ë€ì ìœë ìíêłŒ ê°ìŽ í íŹëìŽì ì¶ë „ì ë°ìŽí° ìžížì ìŽëĄ ì¶ê°íŽìŒ í©ëë€:
-
-```py
-def tokenize_dataset(data):
- # Keys of the returned dictionary will be added to the dataset as columns
- return tokenizer(data["text"])
-
-
-dataset = dataset.map(tokenize_dataset)
-```
-
-íêč
íìŽì€ ë°ìŽí°ì
ì êž°ëłžì ìŒëĄ ëì€íŹì ì ì„ëëŻëĄ ë©ëȘšëŠŹ ìŹì©ëì ëëŠŹì§ ìëë€ë ì ì êž°ì”íìžì!
-ìŽìŽ ì¶ê°ë멎 ë°ìŽí°ì
ìì ë°°ìč넌 ì€ížëŠŹë°íêł ê° ë°°ìčì íšë©ì ì¶ê°í ì ììŒëŻëĄ ì ìČŽ ë°ìŽí°ì
ì íšë©ì ì¶ê°íë êČëłŽë€ íšë© í í°ì ì넌 íŹêČ ì€ìŒ ì ìì”ëë€.
-
-
-```py
->>> tf_dataset = model.prepare_tf_dataset(dataset, batch_size=16, shuffle=True, tokenizer=tokenizer)
-```
-
-ìì ìœë ìíììë ë°°ìčê° ëĄëë ë ìŹë°ë„ŽêČ íšë©í ì ìëëĄ `prepare_tf_dataset`ì í íŹëìŽì 넌 ì ëŹíŽìŒ í©ëë€.
-ë°ìŽí°ì
ì ëȘšë ìí êžžìŽê° ê°êł íšë©ìŽ íìíì§ ìì êČœì° ìŽ ìžì넌 걎ëëž ì ìì”ëë€.
-ìíì ì±ì°ë êČëłŽë€ ë ëł”ìĄí ìì
(ì: ë§ì€íčë ìžìŽì í í° ìì ëȘšëžë§)ì ìííêž° ìíŽ í í°ì ììììŒìŒ íë êČœì°,
-`collate_fn` ìžì넌 ìŹì©íìŹ ìí ëȘ©ëĄì ë°°ìčëĄ ëłííêł ìíë ì ìČëŠŹë„Œ ì ì©í íšì넌 ì ëŹí ì ìì”ëë€.
-[ìì](https://github.com/huggingface/transformers/tree/main/examples) ëë
-[ë
žížë¶](https://huggingface.co/docs/transformers/notebooks)ì ì°žìĄ°íìŹ ìŽ ì ê·Œ ë°©ììŽ ì€ì ëĄ ìëíë ëȘšì”ì íìžíìžì.
-
-`tf.data.Dataset`ì ìì±í íìë ìŽì êłŒ ë§ì°Źê°ì§ëĄ ëȘšëžì 컎íìŒíêł íë š(fit)í ì ìì”ëë€:
-
-```py
-model.compile(optimizer=Adam(3e-5))
-
-model.fit(tf_dataset)
-```
-
-
-
-
-
-
-## êž°ëłž íìŽí ìčëĄ íë šíêž°[[train-in-native-pytorch]]
-
-
-
-
-
-[`Trainer`]ë íë š 룚í넌 ìČ늏íë©° í ì€ì ìœëëĄ ëȘšëžì ëŻžìž ìĄ°ì í ì ìì”ëë€. ì§ì íë š 룚í넌 ìì±íë êČì ì ížíë ìŹì©ìì êČœì°, êž°ëłž PyTorchìì đ€ Transformers ëȘšëžì ëŻžìž ìĄ°ì í ìë ìì”ëë€.
-
-ìŽ ìì ìì ë
žížë¶ì ë€ì ììíê±°ë ë€ì ìœë넌 ì€ííŽ ë©ëȘšëŠŹë„Œ í볎íŽìŒ í ì ìì”ëë€:
-
-```py
-del model
-del trainer
-torch.cuda.empty_cache()
-```
-
-ë€ììŒëĄ, 'í í°íë ë°ìŽí°ì
'ì ìëìŒëĄ íìČ늏íìŹ íë šë šì ìŹì©í ì ìëëĄ ì€ëčí©ëë€.
-
-1. ëȘšëžìŽ ìì í
ì€ížë„Œ ì
ë „ìŒëĄ íì©íì§ ììŒëŻëĄ `text` ìŽì ì ê±°í©ëë€:
-
- ```py
- >>> tokenized_datasets = tokenized_datasets.remove_columns(["text"])
- ```
-
-2. ëȘšëžìì ìžìì ìŽëŠìŽ `labels`ëĄ ì§ì ë êČìŒëĄ ììíëŻëĄ `label` ìŽì ìŽëŠì `labels`ëĄ ëłêČœí©ëë€:
-
- ```py
- >>> tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
- ```
-
-3. ë°ìŽí°ì
ì íìì List ëì PyTorch í
ì넌 ë°ííëëĄ ì€ì í©ëë€:
-
- ```py
- >>> tokenized_datasets.set_format("torch")
- ```
-
-ê·žëŠŹêł ìì íìë ëëĄ ë°ìŽí°ì
ì ë ìì íì ì§í©ì ìì±íìŹ ëŻžìž ìĄ°ì ìë넌 ëì
ëë€:
-
-```py
->>> small_train_dataset = tokenized_datasets["train"].shuffle(seed=42).select(range(1000))
->>> small_eval_dataset = tokenized_datasets["test"].shuffle(seed=42).select(range(1000))
-```
-
-### DataLoader[[dataloader]]
-
-íë š ë° í
ì€íž ë°ìŽí°ì
ì ëí 'DataLoader'넌 ìì±íìŹ ë°ìŽí° ë°°ìč넌 ë°ëł”í ì ìì”ëë€:
-
-```py
->>> from torch.utils.data import DataLoader
-
->>> train_dataloader = DataLoader(small_train_dataset, shuffle=True, batch_size=8)
->>> eval_dataloader = DataLoader(small_eval_dataset, batch_size=8)
-```
-
-ììžĄì ìí ë ìŽëž ê°ì넌 ìŹì©íìŹ ëȘšëžì ëĄëí©ëë€:
-
-```py
->>> from transformers import AutoModelForSequenceClassification
-
->>> model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=5)
-```
-
-### ì”í°ë§ìŽì ë° íì” ìë ì€ìŒì€ëŹ[[optimizer-and-learning-rate-scheduler]]
-
-ì”í°ë§ìŽì ì íì” ìë ì€ìŒì€ëŹë„Œ ìì±íìŹ ëȘšëžì ëŻžìž ìĄ°ì í©ëë€. íìŽí ìčìì ì êł”íë [`AdamW`](https://pytorch.org/docs/stable/generated/torch.optim.AdamW.html) ì”í°ë§ìŽì 넌 ìŹì©íŽ ëłŽêČ ì”ëë€:
-
-```py
->>> from torch.optim import AdamW
-
->>> optimizer = AdamW(model.parameters(), lr=5e-5)
-```
-
-[`Trainer`]ìì êž°ëłž íì” ìë ì€ìŒì€ëŹë„Œ ìì±í©ëë€:
-
-```py
->>> from transformers import get_scheduler
-
->>> num_epochs = 3
->>> num_training_steps = num_epochs * len(train_dataloader)
->>> lr_scheduler = get_scheduler(
-... name="linear", optimizer=optimizer, num_warmup_steps=0, num_training_steps=num_training_steps
-... )
-```
-
-ë§ì§ë§ìŒëĄ, GPUì ìĄìžì€í ì ìë êČœì° 'device'넌 ì§ì íìŹ GPU넌 ìŹì©íëëĄ í©ëë€. ê·žë ì§ ììŒë©Ž CPUìì íë šíë©° ëȘ ë¶ìŽ ìë ëȘ ìê°ìŽ ê±žëŠŽ ì ìì”ëë€.
-
-```py
->>> import torch
-
->>> device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
->>> model.to(device)
-```
-
-
-
-[Colaboratory](https://colab.research.google.com/) ëë [SageMaker StudioLab](https://studiolab.sagemaker.aws/)êłŒ ê°ì ížì€í
ë
žížë¶ìŽ ìë êČœì° íŽëŒì°ë GPUì 돎ëŁëĄ ìĄìžì€í ì ìì”ëë€.
-
-
-
-ìŽì íë ší ì€ëčê° ëìì”ëë€! đ„ł
-
-### íë š 룚í[[training-loop]]
-
-íë š ì§í ìí©ì ì¶ì íë €ë©Ž [tqdm](https://tqdm.github.io/) ëŒìŽëžëŹëŠŹë„Œ ìŹì©íìŹ ížë ìŽë ëšêł ìì ì§íë„ íìì€ì ì¶ê°íìžì:
-
-```py
->>> from tqdm.auto import tqdm
-
->>> progress_bar = tqdm(range(num_training_steps))
-
->>> model.train()
->>> for epoch in range(num_epochs):
-... for batch in train_dataloader:
-... batch = {k: v.to(device) for k, v in batch.items()}
-... outputs = model(**batch)
-... loss = outputs.loss
-... loss.backward()
-
-... optimizer.step()
-... lr_scheduler.step()
-... optimizer.zero_grad()
-... progress_bar.update(1)
-```
-
-### íê° íêž°[[evaluate]]
-
-[`Trainer`]ì íê° íšì넌 ì¶ê°í ë°©ëČêłŒ ë§ì°Źê°ì§ëĄ, íë š 룚í넌 ì§ì ìì±í ëë ëìŒí ìì
ì ìííŽìŒ í©ëë€. íì§ë§ ìŽëČìë ê° ìíŹíŹê° ëë ëë§ë€ íê°ì§í넌 êłì°íìŹ ëłŽêł íë ëì , [`~evaluate.add_batch`]넌 ìŹì©íìŹ ëȘšë ë°°ìč넌 ëì íêł ë§š ë§ì§ë§ì íê°ì§í넌 êłì°í©ëë€.
-
-```py
->>> import evaluate
-
->>> metric = evaluate.load("accuracy")
->>> model.eval()
->>> for batch in eval_dataloader:
-... batch = {k: v.to(device) for k, v in batch.items()}
-... with torch.no_grad():
-... outputs = model(**batch)
-
-... logits = outputs.logits
-... predictions = torch.argmax(logits, dim=-1)
-... metric.add_batch(predictions=predictions, references=batch["labels"])
-
->>> metric.compute()
-```
-
-
-
-
-
-## ì¶ê° ìëŁ[[additional-resources]]
-
-ë ë§ì ëŻžìž íë ìì ë ë€ìì ì°žìĄ°íìžì:
-
-- [đ€ Trnasformers ìì ](https://github.com/huggingface/transformers/tree/main/examples)ìë PyTorch ë° í
ìíëĄì°ìì ìŒë°ì ìž NLP ìì
ì íë ší ì ìë ì€íŹëŠœížê° íŹíšëìŽ ìì”ëë€.
-
-- [đ€ Transformers ë
žížë¶](notebooks)ìë PyTorch ë° í
ìíëĄì°ìì íčì ìì
ì ìíŽ ëȘšëžì ëŻžìž íëíë ë°©ëČì ëí ë€ìí ë
žížë¶ìŽ íŹíšëìŽ ìì”ëë€.
diff --git a/docs/source/ko/transformers_agents.md b/docs/source/ko/transformers_agents.md
new file mode 100644
index 000000000000..eeb00761e9a7
--- /dev/null
+++ b/docs/source/ko/transformers_agents.md
@@ -0,0 +1,328 @@
+
+
+# Transformers Agent [[transformers-agent]]
+
+
+
+Transformers Agentë ì€í ì€ìž APIëĄ ìžì ë ì§ ëłêČœë ì ìì”ëë€.
+API ëë êž°ë° ëȘšëžìŽ ëłêČœëêž° ìœêž° ë돞ì ììŽì ížê° ë°ííë êČ°êłŒë ëŹëŒì§ ì ìì”ëë€.
+
+
+
+Transformers ëČì 4.29.0.ìì *ëê”Ź*ì *ììŽì íž*ëŒë 컚ì
ì ëì
íì”ëë€. [ìŽ colab](https://colab.research.google.com/drive/1c7MHD-T1forUPGcC_jlwsIptOzpG3hSj)ìì ìŹì©íŽëłŒ ì ìì”ëë€.
+
+ê°ëší ë§í멎, Agentë ížëì€íŹëšž ìì ìì°ìŽ API넌 ì êł”í©ëë€.
+ìì ë ëê”Ź ìžížë„Œ ì ìíêł , ìì°ìŽë„Œ íŽìíìŹ ìŽëŹí ëê”Źë„Œ ìŹì©í ì ìë ììŽì ížë„Œ ì€êłíì”ëë€.
+ìŽ APIë íì„ìŽ ê°ë„íëëĄ ì€êł ëìì”ëë€.
+ìŁŒì ëê”Źë„Œ ì ëłíŽëìì§ë§, ì»€ëź€ëí°ìì ê°ë°í ëȘšë ëê”Źë„Œ ìŹì©í ì ìëëĄ ìì€í
ì ìœêČ íì„í ì ìë ë°©ëČë 볎ìŹë늏êČ ì”ëë€.
+
+ëȘ ê°ì§ ì넌 í”íŽ ìëĄìŽ APIëĄ ëŹŽìì í ì ìëì§ ìŽíŽëłŽêČ ì”ëë€.
+ìŽ APIë íčí ë©í°ëȘšëŹ ìì
ìì ê°ë „íëŻëĄ ìŽëŻžì§ë„Œ ìì±íêł í
ì€ížë„Œ ì늏ëŽìŽ ìœìŽëłŽêČ ì”ëë€.
+
+```py
+agent.run("Caption the following image", image=image)
+```
+
+| **Input** | **Output** |
+|-----------------------------------------------------------------------------------------------------------------------------|-----------------------------------|
+| | A beaver is swimming in the water |
+
+---
+
+```py
+agent.run("Read the following text out loud", text=text)
+```
+| **Input** | **Output** |
+|-------------------------------------------------------------------------------------------------------------------------|----------------------------------------------|
+| A beaver is swimming in the water | your browser does not support the audio element.
+
+---
+
+```py
+agent.run(
+ "In the following `document`, where will the TRRF Scientific Advisory Council Meeting take place?",
+ document=document,
+)
+```
+| **Input** | **Output** |
+|-----------------------------------------------------------------------------------------------------------------------------|----------------|
+| | ballroom foyer |
+
+## ë°ëĄ ììíêž° [[quickstart]]
+
+`agent.run`ì ìŹì©íë €ë©Ž 뚌ì ëê·ëȘš ìžìŽ ëȘšëž(LLM)ìž ììŽì ížë„Œ ìžì€íŽì€ííŽìŒ í©ëë€.
+ì íŹë openAI ëȘšëžëżë§ ìëëŒ BigCode ë° OpenAssistantì ì€íìì€ ëìČŽ ëȘšëžë ì§ìí©ëë€.
+openAI ëȘšëžì ì±ë„ìŽ ë ì°ìíì§ë§(ëš, openAI API í€ê° íìíëŻëĄ 돎ëŁëĄ ìŹì©í ì ìì),
+Hugging Faceë BigCodeì OpenAssistant ëȘšëžì ìëíŹìžížì ëí ëŹŽëŁ ìĄìžì€ë„Œ ì êł”íêł ìì”ëë€.
+
+ì°ì ëȘšë êž°ëłž ìą
ìì±ì ì€ìčíë €ë©Ž `agents`넌 ì¶ê°ëĄ ì€ìčíìžì.
+```bash
+pip install transformers[agents]
+```
+
+openAI ëȘšëžì ìŹì©íë €ë©Ž `openai` ìą
ìì±ì ì€ìčí í [`OpenAiAgent`]넌 ìžì€íŽì€íí©ëë€:
+
+```bash
+pip install openai
+```
+
+
+```py
+from transformers import OpenAiAgent
+
+agent = OpenAiAgent(model="text-davinci-003", api_key="")
+```
+
+BigCode ëë OpenAssistant넌 ìŹì©íë €ë©Ž 뚌ì ëĄê·žìžíìŹ Inference APIì ìĄìžì€íìžì:
+
+```py
+from huggingface_hub import login
+
+login("")
+```
+
+ê·žë° ë€ì ììŽì ížë„Œ ìžì€íŽì€íí©ëë€.
+
+```py
+from transformers import HfAgent
+
+# Starcoder
+agent = HfAgent("https://api-inference.huggingface.co/models/bigcode/starcoder")
+# StarcoderBase
+# agent = HfAgent("https://api-inference.huggingface.co/models/bigcode/starcoderbase")
+# OpenAssistant
+# agent = HfAgent(url_endpoint="https://api-inference.huggingface.co/models/OpenAssistant/oasst-sft-4-pythia-12b-epoch-3.5")
+```
+
+íìŹ Hugging Faceìì 돎ëŁëĄ ì êł”íë ì¶ëĄ API넌 ìŹì©íêł ìì”ëë€.
+ìŽ ëȘšëžì ëí ììČŽ ì¶ëĄ ìëíŹìžížê° ìë êČœì°(ëë ë€ë„ž ìëíŹìžížê° ìë êČœì°) ìì URLì íŽëč URL ìëíŹìžížëĄ ë°êż ì ìì”ëë€.
+
+
+
+StarCoderì OpenAssistantë 돎ëŁëĄ ìŹì©í ì ììŒë©° ê°ëší ìì
ìì ëëŒìž ì ëëĄ ì ìëí©ëë€.
+ê·žëŹë ë ëł”ìĄí í륏íížë„Œ ìČ늏í ëë ìČŽíŹíŹìžížê° ì ìëíì§ ìì”ëë€.
+ìŽëŹí 돞ì ê° ë°ìí멎 OpenAI ëȘšëžì ìŹì©íŽ ëłŽìêž° ë°ëëë€. ììœêČë ì€íìì€ë ìëì§ë§ íìŹëĄìë ë ëì ì±ë„ì ì êł”í©ëë€.
+
+
+
+ìŽì ì€ëčê° ìëŁëìì”ëë€! ìŽì ìì ëĄêČ ìŹì©í ì ìë ë ê°ì§ APIì ëíŽ ììží ìì볎êČ ì”ëë€.
+
+### ëšìŒ ì€í (run) [[single-execution-(run)]]
+
+ëšìŒ ì€í ë°©ëČì ììŽì ížì [`~Agent.run`] ë©ìë넌 ìŹì©íë êČœì°ì
ëë€:
+
+```py
+agent.run("Draw me a picture of rivers and lakes.")
+```
+
+
+
+ìííë €ë ìì
ì ì í©í ëê”Źë„Œ ìëìŒëĄ ì ííìŹ ì ì íêČ ì€íí©ëë€.
+ëìŒí ëȘ
ë čìŽìì íë ëë ìŹëŹ ê°ì ìì
ì ìíí ì ìì”ëë€
+(ë€ë§, ëȘ
ë čìŽê° ëł”ìĄí ìëĄ ììŽì ížê° ì€íší ê°ë„ì±ìŽ ëìì§ëë€).
+
+```py
+agent.run("Draw me a picture of the sea then transform the picture to add an island")
+```
+
+
+
+
+
+
+ëȘšë [`~Agent.run`] ìì
ì ë
늜ì ìŽëŻëĄ ë€ë„ž ìì
ìŒëĄ ìŹëŹ ëČ ì°ìíŽì ì€íí ì ìì”ëë€.
+
+`agent`ë í° ìžìŽ ëȘšëžìŒ ëżìŽëŻëĄ í륏íížì ìœê°ì ëłí넌 ìŁŒë©Ž ìì í ë€ë„ž êČ°êłŒê° ëìŹ ì ìë€ë ì ì ì ìíìžì.
+ìííë €ë ìì
ì ì”ëí ëȘ
ííêČ ì€ëȘ
íë êČìŽ ì€ìí©ëë€.
+ìąì í륏íížë„Œ ìì±íë ë°©ëČì [ìŹêž°](custom_tools#writing-good-user-inputs)ìì ììží íìží ì ìì”ëë€.
+
+ìŹëŹ ì€íì ê±žìł ìí넌 ì ì§íê±°ë í
ì€ížê° ìë ê°ìČŽë„Œ ììŽì ížìêČ ì ëŹíë €ë êČœì°ìë ììŽì ížê° ìŹì©í ëłì넌 ì§ì í ì ìì”ëë€.
+ì넌 ë€ìŽ ê°êłŒ ížìì ìČ« ëČì§ž ìŽëŻžì§ë„Œ ìì±í ë€,
+ëȘšëžìŽ íŽëč 귞늌ì ìŹì ì¶ê°íëëĄ ë€ìêłŒ ê°ìŽ ììČí ì ìì”ëë€:
+
+```python
+picture = agent.run("Generate a picture of rivers and lakes.")
+updated_picture = agent.run("Transform the image in `picture` to add an island to it.", picture=picture)
+```
+
+
+
+ìŽ ë°©ëČì ëȘšëžìŽ ììČì ìŽíŽíì§ ëȘ»íêł ëê”Źë„Œ íŒí©í ë ì ì©í ì ìì”ëë€. ì넌 ë€ë©Ž ë€ìêłŒ ê°ì”ëë€:
+
+```py
+agent.run("Draw me the picture of a capybara swimming in the sea")
+```
+
+ìŹêž°ì ëȘšëžì ë ê°ì§ ë°©ììŒëĄ íŽìí ì ìì”ëë€:
+- `text-to-image`ìŽ ë°ë€ìì í€ììčë ìčŽíŒë°ëŒë„Œ ìì±íëëĄ í©ëë€.
+- ëë `text-to-image`ìŽ ìčŽíŒë°ëŒë„Œ ìì±í ë€ì `image-transformation` ëê”Źë„Œ ìŹì©íìŹ ë°ë€ìì í€ììčëëĄ í©ëë€.
+
+ìČ« ëČì§ž ìë늏ì€ë„Œ ê°ì ëĄ ì€ííë €ë©Ž í륏íížë„Œ ìžìëĄ ì ëŹíìŹ ì€íí ì ìì”ëë€:
+
+```py
+agent.run("Draw me a picture of the `prompt`", prompt="a capybara swimming in the sea")
+```
+
+
+
+
+### ëí êž°ë° ì€í (chat) [[chat-based-execution-(chat)]]
+
+ììŽì ížë [`~Agent.chat`] ë©ìë넌 ìŹì©íë ëí êž°ë° ì ê·Œ ë°©ìë ìì”ëë€:
+
+```py
+agent.chat("Generate a picture of rivers and lakes")
+```
+
+
+
+```py
+agent.chat("Transform the picture so that there is a rock in there")
+```
+
+
+
+
+
+ìŽ ë°©ìì ìŹëŹ ëȘ
ë čìŽì ê±žìł ìí넌 ì ì§íêł ì í ë í„믞ëĄìŽ ì ê·Œ ë°©ìì
ëë€.
+ì€íì©ìŒëĄ ë ìąì§ë§ ëł”ìĄí ëȘ
ë čìŽëłŽë€ë
+ëšìŒ ëȘ
ë čìŽ([`~Agent.run`] ë©ìëê° ë ì ìČ늏íë ëȘ
ë čìŽ)ì íšìŹ ë ì ìëíë êČœí„ìŽ ìì”ëë€.
+
+ìŽ ë©ìëë í
ì€ížê° ìë ì íìŽë íčì í륏íížë„Œ ì ëŹíë €ë êČœì° ìžì넌 ë°ì ìë ìì”ëë€.
+
+### â ïž ìêČ© ì€í [[remote-execution]]
+
+ë°ëȘš ëȘ©ì êłŒ ëȘšë ì€ì ìì ìŹì©í ì ìëëĄ
+ììŽì ížê° ì ê·Œí ì ìë ëȘ ê°ì§ êž°ëłž ëê”Źì ëí ìêČ© ì€íꞰ넌 ë§ë€ìì”ëë€.
+ìŽëŹí ëê”Źë [inference endpoints](https://huggingface.co/inference-endpoints)넌 ìŹì©íìŹ ë§ë€ìŽìĄì”ëë€.
+ìêČ© ì€íêž° ëê”Źë„Œ ì§ì ì€ì íë ë°©ëČì ëłŽë €ë©Ž [ìŹì©ì ì ì ëê”Ź ê°ìŽë](./custom_tools)넌 ìœìŽëłŽìêž° ë°ëëë€.
+
+ìêČ© ëê”ŹëĄ ì€ííë €ë©Ž [`~Agent.run`] ëë [`~Agent.chat`] ì€ íëì `remote=True`넌 ì§ì íêž°ë§ í멎 ë©ëë€.
+
+ì넌 ë€ìŽ ë€ì ëȘ
ë čì ë§ì RAMìŽë GPU ììŽë ëȘšë ì„ìčìì íšìšì ìŒëĄ ì€íí ì ìì”ëë€:
+
+```py
+agent.run("Draw me a picture of rivers and lakes", remote=True)
+```
+
+[`~Agent.chat`]ë ë§ì°Źê°ì§ì
ëë€:
+
+```py
+agent.chat("Draw me a picture of rivers and lakes", remote=True)
+```
+
+### ìŹêž°ì ëŹŽìš ìŒìŽ ìŒìŽëë ê±°ìŁ ? ëê”Źë 돎ììŽêł , ììŽì ížë 돎ììžê°ì? [[whats-happening-here-what-are-tools-and-what-are-agents]]
+
+
+
+#### ììŽì íž [[agents]]
+
+ìŹêž°ì "ììŽì íž"ë ëê·ëȘš ìžìŽ ëȘšëžìŽë©°, íčì ëê”Ź ëȘšìì ì ê·Œí ì ìëëĄ í륏íížíêł ìì”ëë€.
+
+LLMì ìì ìœë ìíì ìì±íë ë° ìëčí ë„ìíëŻëĄ,
+ìŽ ì„ì ì íì©íŽ ëê”Ź ëȘšìì ìŹì©íìŹ ìì
ì ìííë ìì ìœë ìíì ì êł”íëŒë ë©ìì§ë„Œ íìí©ëë€.
+ê·žë° ë€ì ììŽì ížìêČ ì êł”íë ìì
êłŒ ì êł”íë ëê”Źì ëí ì€ëȘ
ìŒëĄ ìŽ í륏íížê° ìëŁë©ëë€.
+ìŽë êČ í멎 ìŹì© ì€ìž ëê”Źë€ì 돞ìì ì ê·Œí ì ììŒë©°, íŽëč ëê”Źë€ì ì
ë „êłŒ ì¶ë „ì ììíêł , êŽë šë ìœë넌 ìì±í ì ìì”ëë€.
+
+#### ëê”Ź [[tools]]
+
+ëê”Źë ë§€ì° ê°ëší©ëë€. ìŽëŠêłŒ ì€ëȘ
ìŽ ìë ëšìŒ êž°ë„ìŒëĄ ê”Źì±ëìŽ ìì”ëë€.
+ê·žë° ë€ì ìŽëŹí ëê”Źì ì€ëȘ
ì ìŹì©íìŹ ìëŽììêČ í륏íížë„Œ íìí©ëë€.
+ìŽ í륏íížë„Œ í”íŽ ìëŽììêČ ìżŒëŠŹìì ììČë ìì
ì ìííêž° ìíŽ ëê”Źë„Œ íì©íë ë°©ëČì 볎ìŹì€ëë€.
+
+ììŽì ížê° ë§€ì° ììì ìž ëê”Źë„Œ ìŹì©íìŹ ë ëì ìœë넌 ìì±íêž° ë돞ì íìŽíëŒìžìŽ ìë ìì í ìëĄìŽ ëê”Źë„Œ ìŹì©í©ëë€.
+íìŽíëŒìžì ë ë§ìŽ ëŠŹí©í°ë§ëë©° ìą
ìą
ìŹëŹ ìì
ì íëëĄ êȰí©í©ëë€.
+ëê”Źë íëì ë§€ì° ê°ëší ìì
ìë§ ì§ì€íëëĄ ëìŽ ìì”ëë€.
+
+#### ìœë ì€í?! [[code-execution]]
+
+ê·žë° ë€ì ìŽ ìœëë ëê”Źì íšê» ì ëŹë ì
ë „ ìžížì ëíŽ ìì Python ìží°í늏í°ë„Œ ìŹì©íìŹ ì€íë©ëë€.
+"ìì ìœë ì€íìŽëŒë!"ìŽëŒêł ëčëȘ
ì ì§ë„Žë ìëŠŹê° ë€ëŠŹêČ ì§ë§, ê·žë ì§ ìì ìŽì 넌 ì€ëȘ
íêČ ì”ëë€.
+
+ížì¶í ì ìë íšìë ì êł”í ëê”Źì ìžì êž°ë„ëżìŽëŻëĄ ìŽëŻž ì€íí ì ìë êž°ë„ìŽ ì íëìŽ ìì”ëë€.
+Hugging Face ëê”ŹëĄ ì íëìŽ ìë€ë©Ž ìì í êČì
ëë€.
+
+ê·žëŠŹêł ìŽížëŠŹë·°íž ìĄ°íë ê°ì žì€êž°ë„Œ íì©íì§ ììŒëŻëĄ
+(ìŽì°šíŒ ìì íšì ì§í©ì ì
/ì¶ë „ì ì ëŹí ëë íìíì§ ìììŒ í©ëë€)
+ê°ì„ ëȘ
ë°±í êł”êČ©(ìŽì°šíŒ LLMì ì¶ë „íëŒë ë©ìì§ë„Œ íìíŽìŒ í©ëë€)ì 돞ì ê° ëì§ ìì”ëë€.
+ë§€ì° ìì íêČ íêł ì¶ë€ë©Ž ì¶ê° ìžì return_code=True넌 ìŹì©íìŹ run() ë©ìë넌 ì€íí멎 ë©ëë€.
+ìŽ êČœì° ììŽì ížê° ì€íí ìœë넌 ë°ííêł ì€íí ì§ ìŹë¶ë„Œ êȰì í ì ìì”ëë€.
+
+ë¶ëČì ìž ì°ì°ì ìííë €êł íê±°ë ììŽì ížê° ìì±í ìœëì ìŒë°ì ìž íìŽìŹ ì€ë„ê° ìë êČœì°
+ì€íìŽ ì€ì§ë©ëë€.
+
+### ìì ë ëê”Ź ëȘšì [[a-curated-set-of-tools]]
+
+ì íŹë ìŽëŹí ììŽì ížë€ì ìëì ê°íí ì ìë ìŒë šì ëê”Źë„Œ íìžíêł ìì”ëë€.
+ë€ìì ì°ëë ëê”Źì ì”ì ëȘ©ëĄì
ëë€:
+
+- **돞ì ì§ëŹž ë”ëł**: ìŽëŻžì§ íìì 돞ì(ì: PDF)ê° ìŁŒìŽì§ë©Ž ìŽ ëŹžìì ëí ì§ëŹžì ë”ëłí©ëë€. ([Donut](./model_doc/donut))
+- **í
ì€íž ì§ëŹž ë”ëł**: ꞎ í
ì€ížì ì§ëŹžìŽ ìŁŒìŽì§ë©Ž í
ì€ížìì ì§ëŹžì ë”ëłí©ëë€. ([Flan-T5](./model_doc/flan-t5))
+- **ëŹŽìĄ°ê±Ž ìŽëŻžì§ ìșĄì
ë**: ìŽëŻžì§ì ìșĄì
ì ë”ëë€! ([BLIP](./model_doc/blip))
+- **ìŽëŻžì§ ì§ëŹž ë”ëł**: ìŽëŻžì§ê° ìŁŒìŽì§ë©Ž ìŽ ìŽëŻžì§ì ëí ì§ëŹžì ë”ëłíêž°. ([VILT](./model_doc/vilt))
+- **ìŽëŻžì§ ë¶í **: ìŽëŻžì§ì í륏íížê° ìŁŒìŽì§ë©Ž íŽëč í륏íížì ë¶í ë§ì€íŹë„Œ ì¶ë „í©ëë€. ([CLIPSeg](./model_doc/clipseg))
+- **ìì±ì í
ì€ížëĄ ëłí**: ìŹëìŽ ë§íë ì€ëì€ ë
čììŽ ìŁŒìŽì§ë©Ž ìì±ì í
ì€ížëĄ ëłíí©ëë€. ([Whisper](./model_doc/whisper))
+- **í
ì€íž ìì± ëłí**: í
ì€ížë„Œ ìì±ìŒëĄ ëłíí©ëë€. ([SpeechT5](./model_doc/speecht5))
+- **ì ëĄ ì·(zero-shot) í
ì€íž ë¶ë„**: í
ì€ížì ë ìŽëž ëȘ©ëĄìŽ ìŁŒìŽì§ë©Ž í
ì€ížì ê°ì„ êŽë š ìë ë ìŽëžì ìëłí©ëë€. ([BART](./model_doc/bart))
+- **í
ì€íž ììœ**: ꞎ í
ì€ížë„Œ í ëŹžì„ ëë ëȘ 돞ì„ìŒëĄ ììœí©ëë€. ([BART](./model_doc/bart))
+- **ëČì**: í
ì€ížë„Œ ì§ì ë ìžìŽëĄ ëČìí©ëë€. ([NLLB](./model_doc/nllb))
+
+ìŽëŹí ëê”Źë ížëì€íŹëšžì í”í©ëìŽ ììŒë©°, ì넌 ë€ìŽ ìëìŒëĄë ìŹì©í ì ìì”ëë€:
+
+```py
+from transformers import load_tool
+
+tool = load_tool("text-to-speech")
+audio = tool("This is a text to speech tool")
+```
+
+### ìŹì©ì ì ì ëê”Ź [[custom-tools]]
+
+ìì ë ëê”Ź ìžížë ìì§ë§, ìŽ ê”ŹíìŽ ì êł”íë ê°ì„ í° ê°ìčë ìŹì©ì ì§ì ëê”Źë„Œ ëč 넎êČ ë§ë€êł êł”ì í ì ìë€ë ì ì
ëë€.
+
+ëê”Źì ìœë넌 Hugging Face Spaceë ëȘšëž ì ì„ìì ížìí멎 ììŽì ížìêČ ì§ì ëê”Źë„Œ íì©í ì ìì”ëë€. [`huggingface-tools` organization](https://huggingface.co/huggingface-tools)ì ëȘ ê°ì§ **ížëì€íŹëšžì ê”Źì ë°ì§ ìë** íŽì ì¶ê°íì”ëë€:
+
+- **í
ì€íž ë€ìŽëĄë**: ìč URLìì í
ì€ížë„Œ ë€ìŽëĄëí©ëë€.
+- **í
ì€íž ìŽëŻžì§ ëłí**: í륏íížì ë°ëŒ ìŽëŻžì§ë„Œ ìì±íìŹ ìì ì ìž íì°ì íì©í©ëë€.
+- **ìŽëŻžì§ ëłí**: ìŽêž° ìŽëŻžì§ì í륏íížê° ìŁŒìŽì§ ìŽëŻžì§ë„Œ ìì íêł , ìì ì ìž íì°ì íì©íë ì§ì íœì
2 íœì
ì íì©í©ëë€.
+- **í
ì€íž ëčëì€ ëłí**: í륏íížì ë°ëŒ ìì ëčëì€ë„Œ ìì±íë©°, damo-vilabì íì©í©ëë€.
+
+ì íŹê° ìČìë¶í° ìŹì©íêł ìë í
ì€íž-ìŽëŻžì§ ëłí ëê”Źë [*huggingface-tools/text-to-image*](https://huggingface.co/spaces/huggingface-tools/text-to-image)ì ìë ìêČ© ëê”Źì
ëë€! ì íŹë ìŽ ëê”Źì ë€ë„ž ìĄ°ì§ì ìŽëŹí ëê”Źë„Œ êłì ì¶ìíìŹ ìŽ ê”Źíì ëì± ê°íí êČì
ëë€.
+
+ììŽì ížë êž°ëłžì ìŒëĄ [`huggingface-tools`](https://huggingface.co/huggingface-tools)ì ìë ëê”Źì ì ê·Œí ì ìì”ëë€.
+[ë€ì ê°ìŽë](custom_tools)ìì ëê”Źë„Œ ìì±íêł êł”ì íë ë°©ëČêłŒ Hubì ìë ìŹì©ì ì§ì ëê”Źë„Œ íì©íë ë°©ëČì ëíŽ ì€ëȘ
í©ëë€.
+
+### ìœë ìì±[[code-generation]]
+
+ì§êžêčì§ ììŽì ížë„Œ ìŹì©íìŹ ìì
ì ìííë ë°©ëČì 볎ìŹëë žì”ëë€. íì§ë§ ììŽì ížë ë§€ì° ì íë Python ìží°í늏í°ë„Œ ìŹì©íìŹ ì€íí ìœëë§ ìì±íêł ìì”ëë€. ë€ë„ž ì€ì ìì ìì±ë ìœë넌 ìŹì©íë €ë êČœì° ììŽì ížìêČ ëê”Ź ì ì ë° ì íí ê°ì žì€êž°ì íšê» ìœë넌 ë°ííëŒë ë©ìì§ë„Œ íìí ì ìì”ëë€.
+
+ì넌 ë€ìŽ ë€ì ëȘ
ë čìŽë
+```python
+agent.run("Draw me a picture of rivers and lakes", return_code=True)
+```
+
+ë€ì ìœë넌 ë°íí©ëë€.
+
+```python
+from transformers import load_tool
+
+image_generator = load_tool("huggingface-tools/text-to-image")
+
+image = image_generator(prompt="rivers and lakes")
+```
+
+ìŽ ìœëë ì§ì ìì íêł ì€íí ì ìì”ëë€.
\ No newline at end of file
diff --git a/docs/source/ko/troubleshooting.md b/docs/source/ko/troubleshooting.md
new file mode 100644
index 000000000000..5eef788e0993
--- /dev/null
+++ b/docs/source/ko/troubleshooting.md
@@ -0,0 +1,198 @@
+
+
+# 돞ì íŽêȰ[[troubleshoot]]
+
+ëëëĄ ì€ë„ê° ë°ìí ì ìì§ë§, ì íŹê° ëìë늏êČ ì”ëë€! ìŽ ê°ìŽëë íìŹêčì§ íìžë ê°ì„ ìŒë°ì ìž ëŹžì ëȘ ê°ì§ì ê·žêČë€ì íŽêȰíë ë°©ëČì ëíŽ ë€ëŁčëë€. ê·žëŹë ìŽ ê°ìŽëë ëȘšë đ€ Transformers 돞ì 넌 íŹêŽì ìŒëĄ ë€ëŁšêł ìì§ ìì”ëë€. 돞ì íŽêȰì ë ë§ì ëìì ë°ìŒë €ë©Ž ë€ìì ìëíŽëłŽìžì:
+
+
+
+1. [íŹëŒ](https://discuss.huggingface.co/)ìì ëìì ììČíìžì. [Beginners](https://discuss.huggingface.co/c/beginners/5) ëë [đ€ Transformers](https://discuss.huggingface.co/c/transformers/9)ì ê°ì íčì ìčŽí
êł ëŠŹì ì§ëŹžì êČìí ì ìì”ëë€. ìŹí ê°ë„í ìœëì íšê» ì ìì ë íŹëŒ êČìëŹŒì ìì±íìŹ ìŹëŹë¶ì 돞ì ê° íŽêȰë ê°ë„ì±ì ê·čëííìžì!
+
+
+
+2. ëŒìŽëžëŹëŠŹì êŽë šë ëČê·žìŽë©Ž đ€ Transformers ì ì„ììì [ìŽì](https://github.com/huggingface/transformers/issues/new/choose)넌 ìì±íìžì. ëČê·žì ëíŽ ì€ëȘ
íë ì ëłŽë„Œ ê°ë„í ë§ìŽ íŹíšíë €êł ë
žë „íìŹ, 돎ììŽ ìëȘ» ëìëì§ì ìŽë»êČ ìì í ì ìëì§ ë ì íì
í ì ìëëĄ ëììŁŒìžì.
+
+3. ìŽì ëČì ì đ€ Transformersì ìŹì©íë êČœì° ì€ìí ëłêČœ ìŹíìŽ ëČì ìŹìŽì ëì
ëìêž° ë돞ì [ë§ìŽê·žë ìŽì
](migration) ê°ìŽë넌 íìžíìžì.
+
+돞ì íŽêȰ ë° ëì ë§€ëŽìŒì ëí ììží ëŽì©ì Hugging Face ê°ìąì [8ì„](https://huggingface.co/course/chapter8/1?fw=pt)ì ì°žìĄ°íìžì.
+
+
+## ë°©íëČœ íêČœ[[firewalled-environments]]
+
+íŽëŒì°ë ë° ëŽë¶ë§(intranet) ì€ì ì ìŒë¶ GPU ìžì€íŽì€ë ìžë¶ ì°êȰì ëí ë°©íëČœìŒëĄ ì°šëšëìŽ ì°êȰ ì€ë„ê° ë°ìí ì ìì”ëë€. ì€íŹëŠœížê° ëȘšëž ê°ì€ìčë ë°ìŽí°ë„Œ ë€ìŽëĄëíë €êł í ë, ë€ìŽëĄëê° ì€ëšëêł ë€ì ë©ìì§ì íšê» ìê° ìŽêłŒë©ëë€:
+
+```
+ValueError: Connection error, and we cannot find the requested files in the cached path.
+Please try again or make sure your Internet connection is on.
+```
+
+ìŽ êČœì°ìë ì°êȰ ì€ë„넌 íŒíêž° ìíŽ đ€ Transformers넌 [ì€íëŒìž ëȘšë](installation#offline-mode)ëĄ ì€ííŽìŒ í©ëë€.
+
+## CUDA ë©ëȘšëŠŹ ë¶ìĄ±(CUDA out of memory)[[cuda-out-of-memory]]
+
+ìë°±ë§ ê°ì ë§€ê°ëłìëĄ ëê·ëȘš ëȘšëžì íë šíë êČì ì ì í íëìšìŽ ììŽ ìŽë €ìž ì ìì”ëë€. GPU ë©ëȘšëŠŹê° ë¶ìĄ±í êČœì° ë°ìí ì ìë ìŒë°ì ìž ì€ë„ë ë€ìêłŒ ê°ì”ëë€:
+
+```
+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)
+```
+
+ë€ìì ë©ëȘšëŠŹ ìŹì©ì ì€ìŽêž° ìíŽ ìëíŽ ëłŒ ì ìë ëȘ ê°ì§ ì ìŹì ìž íŽêȰì±
ì
ëë€:
+
+- [`TrainingArguments`]ì [`per_device_train_batch_size`](main_classes/trainer#transformers.TrainingArguments.per_device_train_batch_size) ê°ì ì€ìŽìžì.
+- [`TrainingArguments`]ì [`gradient_accumulation_steps`](main_classes/trainer#transformers.TrainingArguments.gradient_accumulation_steps)ì ì ìČŽ ë°°ìč íŹêž°ë„Œ íšêłŒì ìŒëĄ ë늏ìžì.
+
+
+
+ë©ëȘšëŠŹ ì ìœ êž°ì ì ëí ììží ëŽì©ì ì±ë„ [ê°ìŽë](performance)넌 ì°žìĄ°íìžì.
+
+
+
+## ì ì„ë TensorFlow ëȘšëžì ê°ì žìŹ ì ìì”ëë€(Unable to load a saved TensorFlow model)[[unable-to-load-a-saved-uensorFlow-model]]
+
+TensorFlowì [model.save](https://www.tensorflow.org/tutorials/keras/save_and_load#save_the_entire_model) ë©ìëë ìí€í
ìČ, ê°ì€ìč, íë š ê”Źì± ë± ì ìČŽ ëȘšëžì ëšìŒ íìŒì ì ì„í©ëë€. ê·žëŹë ëȘšëž íìŒì ë€ì ê°ì žìŹ ë đ€ Transformersë ëȘšëž íìŒì ìë ëȘšë TensorFlow êŽë š ê°ìČŽë„Œ ê°ì žì€ì§ ìì ì ìêž° ë돞ì ì€ë„ê° ë°ìí ì ìì”ëë€. TensorFlow ëȘšëž ì ì„ ë° ê°ì žì€êž° 돞ì 넌 íŒíë €ë©Ž ë€ìì ê¶ì„í©ëë€:
+
+- ëȘšëž ê°ì€ìč넌 `h5` íìŒ íì„ìëĄ [`model.save_weights`](https://www.tensorflow.org/tutorials/keras/save_and_load#save_the_entire_model)ëĄ ì ì„í ë€ì [`~TFPreTrainedModel.from_pretrained`]ëĄ ëȘšëžì ë€ì ê°ì žì”ëë€:
+
+```py
+>>> from transformers import TFPreTrainedModel
+>>> from tensorflow import keras
+
+>>> model.save_weights("some_folder/tf_model.h5")
+>>> model = TFPreTrainedModel.from_pretrained("some_folder")
+```
+
+- ëȘšëžì [`~TFPretrainedModel.save_pretrained`]ëĄ ì ì„íêł [`~TFPreTrainedModel.from_pretrained`]ëĄ ë€ì ê°ì žì”ëë€:
+
+```py
+>>> from transformers import TFPreTrainedModel
+
+>>> model.save_pretrained("path_to/model")
+>>> model = TFPreTrainedModel.from_pretrained("path_to/model")
+```
+
+## ImportError[[importerror]]
+
+íčí ì”ì ëȘšëžìž êČœì° ë§ë ì ìë ë€ë„ž ìŒë°ì ìž ì€ë„ë `ImportError`ì
ëë€:
+
+```
+ImportError: cannot import name 'ImageGPTImageProcessor' from 'transformers' (unknown location)
+```
+
+ìŽëŹí ì€ë„ ì íì êČœì° ì”ì ëȘšëžì ìĄìžì€í ì ìëëĄ ì”ì ëČì ì đ€ Transformersê° ì€ìčëìŽ ìëì§ íìžíìžì:
+
+```bash
+pip install transformers --upgrade
+```
+
+## CUDA error: device-side assert triggered[[cuda-error-deviceside-assert-triggered]]
+
+ëëëĄ ì„ìč ìœë ì€ë„ì ëí ìŒë°ì ìž CUDA ì€ë„ê° ë°ìí ì ìì”ëë€.
+
+```
+RuntimeError: CUDA error: device-side assert triggered
+```
+
+ë ììží ì€ë„ ë©ìì§ë„Œ ì»ìŒë €ë©Ž ì°ì ìœë넌 CPUìì ì€íí©ëë€. ë€ì íêČœ ëłì넌 ìœëì ìì ë¶ë¶ì ì¶ê°íìŹ CPUëĄ ì ííìžì:
+
+```py
+>>> import os
+
+>>> os.environ["CUDA_VISIBLE_DEVICES"] = ""
+```
+
+ë ë€ë„ž ì”ì
ì GPUìì ë ëì ìì¶ì (traceback)ì ì»ë êČì
ëë€. ë€ì íêČœ ëłì넌 ìœëì ìì ë¶ë¶ì ì¶ê°íìŹ ìì¶ì ìŽ ì€ë„ê° ë°ìí ìì€ë„Œ ê°ëŠŹí€ëëĄ íìžì:
+
+```py
+>>> import os
+
+>>> os.environ["CUDA_LAUNCH_BLOCKING"] = "1"
+```
+
+## íšë© í í°ìŽ ë§ì€íčëì§ ìì êČœì° ìëȘ»ë ì¶ë „(Incorrect output when padding tokens aren't masked)[[incorrect-output-when-padding-tokens-arent-masked]]
+
+êČœì°ì ë°ëŒ `input_ids`ì íšë© í í°ìŽ íŹíšë êČœì° `hidden_state` ì¶ë „ìŽ ìŹë°ë„Žì§ ìì ì ìì”ëë€. ë°ëȘšë„Œ ìíŽ ëȘšëžêłŒ í íŹëìŽì 넌 ê°ì žì€ìžì. ëȘšëžì `pad_token_id`ì ìĄìžì€íìŹ íŽëč ê°ì íìží ì ìì”ëë€. ìŒë¶ ëȘšëžì êČœì° `pad_token_id`ê° `None`ìŒ ì ìì§ë§ ìžì ë ì§ ìëìŒëĄ ì€ì í ì ìì”ëë€.
+
+```py
+>>> from transformers import AutoModelForSequenceClassification
+>>> import torch
+
+>>> model = AutoModelForSequenceClassification.from_pretrained("bert-base-uncased")
+>>> model.config.pad_token_id
+0
+```
+
+ë€ì ìì ë íšë© í í°ì ë§ì€íčíì§ ìì ì¶ë „ì 볎ìŹì€ëë€:
+
+```py
+>>> input_ids = torch.tensor([[7592, 2057, 2097, 2393, 9611, 2115], [7592, 0, 0, 0, 0, 0]])
+>>> output = model(input_ids)
+>>> print(output.logits)
+tensor([[ 0.0082, -0.2307],
+ [ 0.1317, -0.1683]], grad_fn=)
+```
+
+ë€ìì ë ëČì§ž ìíì€ì ì€ì ì¶ë „ì
ëë€:
+
+```py
+>>> input_ids = torch.tensor([[7592]])
+>>> output = model(input_ids)
+>>> print(output.logits)
+tensor([[-0.1008, -0.4061]], grad_fn=)
+```
+
+ëë¶ë¶ì êČœì° ëȘšëžì `attention_mask`넌 ì êł”íìŹ íšë© í í°ì 돎ìíŽìŒ ìŽëŹí ìĄ°ì©í ì€ë„넌 ë°©ì§í ì ìì”ëë€. ìŽì ë ëČì§ž ìíì€ì ì¶ë „ìŽ ì€ì ì¶ë „êłŒ ìŒìčí©ëë€:
+
+
+
+ìŒë°ì ìŒëĄ í íŹëìŽì ë íčì í íŹëìŽì ì êž°ëłž ê°ì êž°ì€ìŒëĄ ìŹì©ìì ëí 'attention_mask'넌 ë§ëëë€.
+
+
+
+```py
+>>> attention_mask = torch.tensor([[1, 1, 1, 1, 1, 1], [1, 0, 0, 0, 0, 0]])
+>>> output = model(input_ids, attention_mask=attention_mask)
+>>> print(output.logits)
+tensor([[ 0.0082, -0.2307],
+ [-0.1008, -0.4061]], grad_fn=)
+```
+
+đ€ Transformersë íšë© í í°ìŽ ì êł”ë êČœì° íšë© í í°ì ë§ì€íčíêž° ìí `attention_mask`넌 ìëìŒëĄ ìì±íì§ ìì”ëë€. ê·ž ìŽì ë ë€ìêłŒ ê°ì”ëë€:
+
+- ìŒë¶ ëȘšëžìë íšë© í í°ìŽ ìì”ëë€.
+- ìŒë¶ ìŹì© ìŹëĄì êČœì° ìŹì©ìê° ëȘšëžìŽ íšë© í í°ì êŽëŠŹíꞰ넌 ìí©ëë€.
+
+## ValueError: ìŽ ì íì AutoModelì ëíŽ ìžìí ì ìë XYZ ê”Źì± íŽëì€(ValueError: Unrecognized configuration class XYZ for this kind of AutoModel)[[valueerror-unrecognized-configuration-class-xyz-for-this-kind-of-automodel]]
+
+ìŒë°ì ìŒëĄ, ìŹì íì”ë ëȘšëžì ìžì€íŽì€ë„Œ ê°ì žì€êž° ìíŽ [`AutoModel`] íŽëì€ë„Œ ìŹì©íë êČìŽ ìąì”ëë€.
+ìŽ íŽëì€ë ê”Źì±ì ë°ëŒ ìŁŒìŽì§ ìČŽíŹíŹìžížìì ìŹë°ë„ž ìí€í
ìČ넌 ìëìŒëĄ ì¶ëĄ íêł ê°ì žìŹ ì ìì”ëë€.
+ëȘšëžì ìČŽíŹíŹìžížìì ê°ì žìŹ ë ìŽ `ValueError`ê° ë°ìí멎, ìŽë Auto íŽëì€ê° ìŁŒìŽì§ ìČŽíŹíŹìžížì ê”Źì±ìì
+ê°ì žì€ë €ë ëȘšëž ì íêłŒ ë§€íì ì°Ÿì ì ìë€ë êČì ì믞í©ëë€. ê°ì„ ííêČ ë°ìíë êČœì°ë
+ìČŽíŹíŹìžížê° ìŁŒìŽì§ íì€íŹë„Œ ì§ìíì§ ìì ëì
ëë€.
+ì넌 ë€ìŽ, ë€ì ìì ìì ì§ììë”ì ëí GPT2ê° ìêž° ë돞ì ì€ë„ê° ë°ìí©ëë€:
+
+```py
+>>> from transformers import AutoProcessor, AutoModelForQuestionAnswering
+
+>>> processor = AutoProcessor.from_pretrained("gpt2-medium")
+>>> model = AutoModelForQuestionAnswering.from_pretrained("gpt2-medium")
+ValueError: Unrecognized configuration class for this kind of AutoModel: AutoModelForQuestionAnswering.
+Model type should be one of AlbertConfig, BartConfig, BertConfig, BigBirdConfig, BigBirdPegasusConfig, BloomConfig, ...
+```
diff --git a/docs/source/ms/_toctree.yml b/docs/source/ms/_toctree.yml
new file mode 100644
index 000000000000..0ec1ee59ad89
--- /dev/null
+++ b/docs/source/ms/_toctree.yml
@@ -0,0 +1,688 @@
+- sections:
+ - local: index
+ title: đ€ Transformers
+ - local: quicktour
+ title: Lawatan cepat
+ - local: installation
+ title: Pemasangan
+ title: Mulakan
+- sections:
+ - local: pipeline_tutorial
+ title: Jalankan inferens dengan saluran paip
+ - local: autoclass_tutorial
+ title: Tulis kod mudah alih dengan AutoClass
+ - local: preprocessing
+ title: Praproses data
+ - local: training
+ title: Perhalusi model yang telah dilatih
+ - local: run_scripts
+ title: Latih dengan skrip
+ - local: accelerate
+ title: Sediakan latihan yang diedarkan dengan đ€ Accelerate
+ - local: model_sharing
+ title: Kongsi model anda
+ - local: transformers_agents
+ title: Ejen
+ title: Tutorials
+- sections:
+ - sections:
+ - local: tasks/sequence_classification
+ title: Klasifikasi teks
+ - local: tasks/token_classification
+ title: Klasifikasi token
+ - local: tasks/question_answering
+ title: Soalan menjawab
+ - local: tasks/language_modeling
+ title: Pemodelan bahasa sebab-akibat
+ - local: tasks/masked_language_modeling
+ title: Pemodelan bahasa Masked
+ - local: tasks/translation
+ title: Terjemahan
+ - local: tasks/summarization
+ title: Rumusan
+ - local: tasks/multiple_choice
+ title: Pilihan
+ title: Natural Language Processing
+ isExpanded: false
+ - sections:
+ - local: tasks/audio_classification
+ title: Klasifikasi audio
+ - local: tasks/asr
+ title: Pengecaman pertuturan automatik
+ title: Audio
+ isExpanded: false
+ - sections:
+ - local: tasks/image_classification
+ title: Klasifikasi imej
+ - local: tasks/semantic_segmentation
+ title: Segmentasi semantik
+ - local: tasks/video_classification
+ title: Klasifikasi video
+ - local: tasks/object_detection
+ title: Pengesanan objek
+ - local: tasks/zero_shot_object_detection
+ title: Pengesanan objek Zero-Shot
+ - local: tasks/zero_shot_image_classification
+ title: Klasifikasi imej tangkapan Zero-Shot
+ - local: tasks/monocular_depth_estimation
+ title: Anggaran kedalaman
+ title: Visi komputer
+ isExpanded: false
+ - sections:
+ - local: tasks/image_captioning
+ title: Kapsyen imej
+ - local: tasks/document_question_answering
+ title: Menjawab Soalan Dokumen
+ - local: tasks/text-to-speech
+ title: Teks kepada ucapan
+ title: Multimodal
+ isExpanded: false
+ title: Panduan Tugasan
+- sections:
+ - local: fast_tokenizers
+ title: Gunakan tokenizer cepat dari đ€ Tokenizers
+ - local: multilingual
+ title: Jalankan inferens dengan model berbilang bahasa
+ - local: generation_strategies
+ title: Sesuaikan strategi penjanaan teks
+ - local: create_a_model
+ title: Gunakan API khusus model
+ - local: custom_models
+ title: Kongsi model tersuai
+ - local: sagemaker
+ title: Jalankan latihan di Amazon SageMaker
+ - local: serialization
+ title: Eksport ke ONNX
+ - local: torchscript
+ title: Eksport ke TorchScript
+ - local: benchmarks
+ title: Penanda aras
+ - local: Buku nota dengan contoh
+ title: Notebooks with examples
+ - local: Sumber komuniti
+ title: Community resources
+ - local: Sumber komuniti
+ title: Custom Tools and Prompts
+ - local: Alat dan Gesaan Tersuai
+ title: Selesaikan masalah
+ title: Panduan Developer
+- sections:
+ - local: performance
+ title: Gambaran keseluruhan
+ - local: perf_train_gpu_one
+ title: Latihan pada satu GPU
+ - local: perf_train_gpu_many
+ title: Latihan pada banyak GPU
+ - local: perf_train_cpu
+ title: Latihan mengenai CPU
+ - local: perf_train_cpu_many
+ title: Latihan pada banyak CPU
+ - local: perf_train_tpu
+ title: Latihan mengenai TPU
+ - local: perf_train_tpu_tf
+ title: Latihan tentang TPU dengan TensorFlow
+ - local: perf_train_special
+ title: Latihan mengenai Perkakasan Khusus
+ - local: perf_infer_cpu
+ title: Inferens pada CPU
+ - local: perf_infer_gpu_one
+ title: Inferens pada satu GPU
+ - local: perf_infer_gpu_many
+ title: Inferens pada banyak GPUs
+ - local: perf_infer_special
+ title: Inferens pada Perkakasan Khusus
+ - local: perf_hardware
+ title: Perkakasan tersuai untuk latihan
+ - local: big_models
+ title: Menghidupkan model besar
+ - local: debugging
+ title: Penyahpepijatan
+ - local: hpo_train
+ title: Carian Hiperparameter menggunakan API Pelatih
+ - local: tf_xla
+ title: Penyepaduan XLA untuk Model TensorFlow
+ title: Prestasi dan kebolehskalaan
+- sections:
+ - local: contributing
+ title: Bagaimana untuk menyumbang kepada transformer?
+ - local: add_new_model
+ title: Bagaimana untuk menambah model pada đ€ Transformers?
+ - local: add_tensorflow_model
+ title: Bagaimana untuk menukar model Transformers kepada TensorFlow?
+ - local: add_new_pipeline
+ title: Bagaimana untuk menambah saluran paip ke đ€ Transformers?
+ - local: testing
+ title: Ujian
+ - local: pr_checks
+ title: Menyemak Permintaan Tarik
+ title: Sumbangkan
+
+- sections:
+ - local: philosophy
+ title: Falsafah
+ - local: glossary
+ title: Glosari
+ - local: task_summary
+ title: Apa đ€ Transformers boleh buat
+ - local: tasks_explained
+ title: Bagaimana đ€ Transformers menyelesaikan tugasan
+ - local: model_summary
+ title: Keluarga model Transformer
+ - local: tokenizer_summary
+ title: Ringkasan tokenizer
+ - local: attention
+ title: Mekanisme perhatian
+ - local: pad_truncation
+ title: Padding dan pemotongan
+ - local: bertology
+ title: BERTology
+ - local: perplexity
+ title: Kekeliruan model panjang tetap
+ - local: pipeline_webserver
+ title: Saluran paip untuk inferens pelayan web
+ title: Panduan konsep
+- sections:
+ - sections:
+ - local: main_classes/agent
+ title: Ejen dan Alat
+ - local: model_doc/auto
+ title: Kelas Auto
+ - local: main_classes/callback
+ title: Panggilan balik
+ - local: main_classes/configuration
+ title: Configuration
+ - local: main_classes/data_collator
+ title: Data Collator
+ - local: main_classes/keras_callbacks
+ title: Keras callbacks
+ - local: main_classes/logging
+ title: Logging
+ - local: main_classes/model
+ title: Models
+ - local: main_classes/text_generation
+ title: Text Generation
+ - local: main_classes/onnx
+ title: ONNX
+ - local: main_classes/optimizer_schedules
+ title: Optimization
+ - local: main_classes/output
+ title: Model outputs
+ - local: main_classes/pipelines
+ title: Pipelines
+ - local: main_classes/processors
+ title: Processors
+ - local: main_classes/quantization
+ title: Quantization
+ - local: main_classes/tokenizer
+ title: Tokenizer
+ - local: main_classes/trainer
+ title: Trainer
+ - local: main_classes/deepspeed
+ title: DeepSpeed Integration
+ - local: main_classes/feature_extractor
+ title: Feature Extractor
+ - local: main_classes/image_processor
+ title: Image Processor
+ title: Main Classes
+ - sections:
+ - isExpanded: false
+ sections:
+ - local: model_doc/albert
+ title: ALBERT
+ - local: model_doc/bart
+ title: BART
+ - local: model_doc/barthez
+ title: BARThez
+ - local: model_doc/bartpho
+ title: BARTpho
+ - local: model_doc/bert
+ title: BERT
+ - local: model_doc/bert-generation
+ title: BertGeneration
+ - local: model_doc/bert-japanese
+ title: BertJapanese
+ - local: model_doc/bertweet
+ title: Bertweet
+ - local: model_doc/big_bird
+ title: BigBird
+ - local: model_doc/bigbird_pegasus
+ title: BigBirdPegasus
+ - local: model_doc/biogpt
+ title: BioGpt
+ - local: model_doc/blenderbot
+ title: Blenderbot
+ - local: model_doc/blenderbot-small
+ title: Blenderbot Small
+ - local: model_doc/bloom
+ title: BLOOM
+ - local: model_doc/bort
+ title: BORT
+ - local: model_doc/byt5
+ title: ByT5
+ - local: model_doc/camembert
+ title: CamemBERT
+ - local: model_doc/canine
+ title: CANINE
+ - local: model_doc/codegen
+ title: CodeGen
+ - local: model_doc/convbert
+ title: ConvBERT
+ - local: model_doc/cpm
+ title: CPM
+ - local: model_doc/cpmant
+ title: CPMANT
+ - local: model_doc/ctrl
+ title: CTRL
+ - local: model_doc/deberta
+ title: DeBERTa
+ - local: model_doc/deberta-v2
+ title: DeBERTa-v2
+ - local: model_doc/dialogpt
+ title: DialoGPT
+ - local: model_doc/distilbert
+ title: DistilBERT
+ - local: model_doc/dpr
+ title: DPR
+ - local: model_doc/electra
+ title: ELECTRA
+ - local: model_doc/encoder-decoder
+ title: Encoder Decoder Models
+ - local: model_doc/ernie
+ title: ERNIE
+ - local: model_doc/ernie_m
+ title: ErnieM
+ - local: model_doc/esm
+ title: ESM
+ - local: model_doc/flan-t5
+ title: FLAN-T5
+ - local: model_doc/flan-ul2
+ title: FLAN-UL2
+ - local: model_doc/flaubert
+ title: FlauBERT
+ - local: model_doc/fnet
+ title: FNet
+ - local: model_doc/fsmt
+ title: FSMT
+ - local: model_doc/funnel
+ title: Funnel Transformer
+ - local: model_doc/openai-gpt
+ title: GPT
+ - local: model_doc/gpt_neo
+ title: GPT Neo
+ - local: model_doc/gpt_neox
+ title: GPT NeoX
+ - local: model_doc/gpt_neox_japanese
+ title: GPT NeoX Japanese
+ - local: model_doc/gptj
+ title: GPT-J
+ - local: model_doc/gpt2
+ title: GPT2
+ - local: model_doc/gpt_bigcode
+ title: GPTBigCode
+ - local: model_doc/gptsan-japanese
+ title: GPTSAN Japanese
+ - local: model_doc/gpt-sw3
+ title: GPTSw3
+ - local: model_doc/herbert
+ title: HerBERT
+ - local: model_doc/ibert
+ title: I-BERT
+ - local: model_doc/jukebox
+ title: Jukebox
+ - local: model_doc/led
+ title: LED
+ - local: model_doc/llama
+ title: LLaMA
+ - local: model_doc/longformer
+ title: Longformer
+ - local: model_doc/longt5
+ title: LongT5
+ - local: model_doc/luke
+ title: LUKE
+ - local: model_doc/m2m_100
+ title: M2M100
+ - local: model_doc/marian
+ title: MarianMT
+ - local: model_doc/markuplm
+ title: MarkupLM
+ - local: model_doc/mbart
+ title: MBart and MBart-50
+ - local: model_doc/mega
+ title: MEGA
+ - local: model_doc/megatron-bert
+ title: MegatronBERT
+ - local: model_doc/megatron_gpt2
+ title: MegatronGPT2
+ - local: model_doc/mluke
+ title: mLUKE
+ - local: model_doc/mobilebert
+ title: MobileBERT
+ - local: model_doc/mpnet
+ title: MPNet
+ - local: model_doc/mt5
+ title: MT5
+ - local: model_doc/mvp
+ title: MVP
+ - local: model_doc/nezha
+ title: NEZHA
+ - local: model_doc/nllb
+ title: NLLB
+ - local: model_doc/nllb-moe
+ title: NLLB-MoE
+ - local: model_doc/nystromformer
+ title: Nyströmformer
+ - local: model_doc/open-llama
+ title: Open-Llama
+ - local: model_doc/opt
+ title: OPT
+ - local: model_doc/pegasus
+ title: Pegasus
+ - local: model_doc/pegasus_x
+ title: PEGASUS-X
+ - local: model_doc/phobert
+ title: PhoBERT
+ - local: model_doc/plbart
+ title: PLBart
+ - local: model_doc/prophetnet
+ title: ProphetNet
+ - local: model_doc/qdqbert
+ title: QDQBert
+ - local: model_doc/rag
+ title: RAG
+ - local: model_doc/realm
+ title: REALM
+ - local: model_doc/reformer
+ title: Reformer
+ - local: model_doc/rembert
+ title: RemBERT
+ - local: model_doc/retribert
+ title: RetriBERT
+ - local: model_doc/roberta
+ title: RoBERTa
+ - local: model_doc/roberta-prelayernorm
+ title: RoBERTa-PreLayerNorm
+ - local: model_doc/roc_bert
+ title: RoCBert
+ - local: model_doc/roformer
+ title: RoFormer
+ - local: model_doc/rwkv
+ title: RWKV
+ - local: model_doc/splinter
+ title: Splinter
+ - local: model_doc/squeezebert
+ title: SqueezeBERT
+ - local: model_doc/switch_transformers
+ title: SwitchTransformers
+ - local: model_doc/t5
+ title: T5
+ - local: model_doc/t5v1.1
+ title: T5v1.1
+ - local: model_doc/tapex
+ title: TAPEX
+ - local: model_doc/transfo-xl
+ title: Transformer XL
+ - local: model_doc/ul2
+ title: UL2
+ - local: model_doc/xmod
+ title: X-MOD
+ - local: model_doc/xglm
+ title: XGLM
+ - local: model_doc/xlm
+ title: XLM
+ - local: model_doc/xlm-prophetnet
+ title: XLM-ProphetNet
+ - local: model_doc/xlm-roberta
+ title: XLM-RoBERTa
+ - local: model_doc/xlm-roberta-xl
+ title: XLM-RoBERTa-XL
+ - local: model_doc/xlm-v
+ title: XLM-V
+ - local: model_doc/xlnet
+ title: XLNet
+ - local: model_doc/yoso
+ title: YOSO
+ title: Text models
+ - isExpanded: false
+ sections:
+ - local: model_doc/beit
+ title: BEiT
+ - local: model_doc/bit
+ title: BiT
+ - local: model_doc/conditional_detr
+ title: Conditional DETR
+ - local: model_doc/convnext
+ title: ConvNeXT
+ - local: model_doc/convnextv2
+ title: ConvNeXTV2
+ - local: model_doc/cvt
+ title: CvT
+ - local: model_doc/deformable_detr
+ title: Deformable DETR
+ - local: model_doc/deit
+ title: DeiT
+ - local: model_doc/deta
+ title: DETA
+ - local: model_doc/detr
+ title: DETR
+ - local: model_doc/dinat
+ title: DiNAT
+ - local: model_doc/dit
+ title: DiT
+ - local: model_doc/dpt
+ title: DPT
+ - local: model_doc/efficientformer
+ title: EfficientFormer
+ - local: model_doc/efficientnet
+ title: EfficientNet
+ - local: model_doc/focalnet
+ title: FocalNet
+ - local: model_doc/glpn
+ title: GLPN
+ - local: model_doc/imagegpt
+ title: ImageGPT
+ - local: model_doc/levit
+ title: LeViT
+ - local: model_doc/mask2former
+ title: Mask2Former
+ - local: model_doc/maskformer
+ title: MaskFormer
+ - local: model_doc/mobilenet_v1
+ title: MobileNetV1
+ - local: model_doc/mobilenet_v2
+ title: MobileNetV2
+ - local: model_doc/mobilevit
+ title: MobileViT
+ - local: model_doc/nat
+ title: NAT
+ - local: model_doc/poolformer
+ title: PoolFormer
+ - local: model_doc/regnet
+ title: RegNet
+ - local: model_doc/resnet
+ title: ResNet
+ - local: model_doc/segformer
+ title: SegFormer
+ - local: model_doc/swiftformer
+ title: SwiftFormer
+ - local: model_doc/swin
+ title: Swin Transformer
+ - local: model_doc/swinv2
+ title: Swin Transformer V2
+ - local: model_doc/swin2sr
+ title: Swin2SR
+ - local: model_doc/table-transformer
+ title: Table Transformer
+ - local: model_doc/timesformer
+ title: TimeSformer
+ - local: model_doc/upernet
+ title: UperNet
+ - local: model_doc/van
+ title: VAN
+ - local: model_doc/videomae
+ title: VideoMAE
+ - local: model_doc/vit
+ title: Vision Transformer (ViT)
+ - local: model_doc/vit_hybrid
+ title: ViT Hybrid
+ - local: model_doc/vit_mae
+ title: ViTMAE
+ - local: model_doc/vit_msn
+ title: ViTMSN
+ - local: model_doc/yolos
+ title: YOLOS
+ title: Vision models
+ - isExpanded: false
+ sections:
+ - local: model_doc/audio-spectrogram-transformer
+ title: Audio Spectrogram Transformer
+ - local: model_doc/clap
+ title: CLAP
+ - local: model_doc/hubert
+ title: Hubert
+ - local: model_doc/mctct
+ title: MCTCT
+ - local: model_doc/sew
+ title: SEW
+ - local: model_doc/sew-d
+ title: SEW-D
+ - local: model_doc/speech_to_text
+ title: Speech2Text
+ - local: model_doc/speech_to_text_2
+ title: Speech2Text2
+ - local: model_doc/speecht5
+ title: SpeechT5
+ - local: model_doc/unispeech
+ title: UniSpeech
+ - local: model_doc/unispeech-sat
+ title: UniSpeech-SAT
+ - local: model_doc/wav2vec2
+ title: Wav2Vec2
+ - local: model_doc/wav2vec2-conformer
+ title: Wav2Vec2-Conformer
+ - local: model_doc/wav2vec2_phoneme
+ title: Wav2Vec2Phoneme
+ - local: model_doc/wavlm
+ title: WavLM
+ - local: model_doc/whisper
+ title: Whisper
+ - local: model_doc/xls_r
+ title: XLS-R
+ - local: model_doc/xlsr_wav2vec2
+ title: XLSR-Wav2Vec2
+ title: Audio models
+ - isExpanded: false
+ sections:
+ - local: model_doc/align
+ title: ALIGN
+ - local: model_doc/altclip
+ title: AltCLIP
+ - local: model_doc/blip
+ title: BLIP
+ - local: model_doc/blip-2
+ title: BLIP-2
+ - local: model_doc/bridgetower
+ title: BridgeTower
+ - local: model_doc/chinese_clip
+ title: Chinese-CLIP
+ - local: model_doc/clip
+ title: CLIP
+ - local: model_doc/clipseg
+ title: CLIPSeg
+ - local: model_doc/data2vec
+ title: Data2Vec
+ - local: model_doc/deplot
+ title: DePlot
+ - local: model_doc/donut
+ title: Donut
+ - local: model_doc/flava
+ title: FLAVA
+ - local: model_doc/git
+ title: GIT
+ - local: model_doc/groupvit
+ title: GroupViT
+ - local: model_doc/layoutlm
+ title: LayoutLM
+ - local: model_doc/layoutlmv2
+ title: LayoutLMV2
+ - local: model_doc/layoutlmv3
+ title: LayoutLMV3
+ - local: model_doc/layoutxlm
+ title: LayoutXLM
+ - local: model_doc/lilt
+ title: LiLT
+ - local: model_doc/lxmert
+ title: LXMERT
+ - local: model_doc/matcha
+ title: MatCha
+ - local: model_doc/mgp-str
+ title: MGP-STR
+ - local: model_doc/oneformer
+ title: OneFormer
+ - local: model_doc/owlvit
+ title: OWL-ViT
+ - local: model_doc/perceiver
+ title: Perceiver
+ - local: model_doc/pix2struct
+ title: Pix2Struct
+ - local: model_doc/sam
+ title: Segment Anything
+ - local: model_doc/speech-encoder-decoder
+ title: Speech Encoder Decoder Models
+ - local: model_doc/tapas
+ title: TAPAS
+ - local: model_doc/trocr
+ title: TrOCR
+ - local: model_doc/tvlt
+ title: TVLT
+ - local: model_doc/vilt
+ title: ViLT
+ - local: model_doc/vision-encoder-decoder
+ title: Vision Encoder Decoder Models
+ - local: model_doc/vision-text-dual-encoder
+ title: Vision Text Dual Encoder
+ - local: model_doc/visual_bert
+ title: VisualBERT
+ - local: model_doc/xclip
+ title: X-CLIP
+ title: Multimodal models
+ - isExpanded: false
+ sections:
+ - local: model_doc/decision_transformer
+ title: Decision Transformer
+ - local: model_doc/trajectory_transformer
+ title: Trajectory Transformer
+ title: Reinforcement learning models
+ - isExpanded: false
+ sections:
+ - local: model_doc/informer
+ title: Informer
+ - local: model_doc/time_series_transformer
+ title: Time Series Transformer
+ title: Time series models
+ - isExpanded: false
+ sections:
+ - local: model_doc/graphormer
+ title: Graphormer
+ title: Graph models
+ title: Models
+ - sections:
+ - local: internal/modeling_utils
+ title: Custom Layers and Utilities
+ - local: internal/pipelines_utils
+ title: Utilities for pipelines
+ - local: internal/tokenization_utils
+ title: Utilities for Tokenizers
+ - local: internal/trainer_utils
+ title: Utilities for Trainer
+ - local: internal/generation_utils
+ title: Utilities for Generation
+ - local: internal/image_processing_utils
+ title: Utilities for Image Processors
+ - local: internal/audio_utils
+ title: Utilities for Audio processing
+ - local: internal/file_utils
+ title: General Utilities
+ - local: internal/time_series_utils
+ title: Utilities for Time Series
+ title: Internal Helpers
+ title: API
diff --git a/docs/source/ms/index.md b/docs/source/ms/index.md
new file mode 100644
index 000000000000..8ae0b484aa61
--- /dev/null
+++ b/docs/source/ms/index.md
@@ -0,0 +1,460 @@
+
+
+# đ€ Transformers
+
+Pembelajaran Mesin terkini untuk [PyTorch](https://pytorch.org/), [TensorFlow](https://www.tensorflow.org/), dan [JAX](https://jax.readthedocs.io/en/latest/).
+
+đ€ 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:
+
+đ **Natural Language Processing**: klasifikasi teks, pengecaman entiti bernama, menjawab soalan, pemodelan bahasa, ringkasan, terjemahan, pilihan berganda dan penjanaan teks.
+đŒïž **Computer Vision**: pengelasan imej, pengesanan objek dan pembahagian.
+đŁïž **Audio**: pengecaman pertuturan automatik dan klasifikasi audio.
+đ **Multimodal**: jawapan soalan jadual, pengecaman aksara optik, pengekstrakan maklumat daripada dokumen yang diimbas, klasifikasi video dan jawapan soalan visual.
+
+đ€ 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.
+
+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!
+
+## Jika anda sedang mencari sokongan tersuai daripada pasukan Hugging Face
+
+
+
+
+
+## Kandungan
+
+Dokumentasi disusun kepada lima bahagian:
+
+- **MULAKAN** menyediakan lawatan pantas ke perpustakaan dan arahan pemasangan untuk bangun dan berjalan.
+- **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.
+- **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.
+- **PANDUAN KONSEP** menawarkan lebih banyak perbincangan dan penjelasan tentang konsep dan idea asas di sebalik model, tugasan dan falsafah reka bentuk đ€ Transformers.
+- **API** menerangkan semua kelas dan fungsi:
+
+ - **KELAS UTAMA** memperincikan kelas yang paling penting seperti konfigurasi, model, tokenizer dan saluran paip.
+ - **MODEL** memperincikan kelas dan fungsi yang berkaitan dengan setiap model yang dilaksanakan dalam perpustakaan.
+ - **PEMBANTU DALAMAN** memperincikan kelas utiliti dan fungsi yang digunakan secara dalaman.
+
+### Model yang disokong
+
+
+
+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://arxiv.org/abs/1909.11942), by Zhenzhong Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.
+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://arxiv.org/abs/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.
+1. **[AltCLIP](model_doc/altclip)** (from BAAI) released with the paper [AltCLIP: Altering the Language Encoder in CLIP for Extended Language Capabilities](https://arxiv.org/abs/2211.06679) by Chen, Zhongzhi and Liu, Guang and Zhang, Bo-Wen and Ye, Fulong and Yang, Qinghong and Wu, Ledell.
+1. **[Audio Spectrogram Transformer](model_doc/audio-spectrogram-transformer)** (from MIT) released with the paper [AST: Audio Spectrogram Transformer](https://arxiv.org/abs/2104.01778) by Yuan Gong, Yu-An Chung, James Glass.
+1. **[Autoformer](model_doc/autoformer)** (from Tsinghua University) released with the paper [Autoformer: Decomposition Transformers with Auto-Correlation for Long-Term Series Forecasting](https://arxiv.org/abs/2106.13008) by Haixu Wu, Jiehui Xu, Jianmin Wang, Mingsheng Long.
+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://arxiv.org/abs/1910.13461) by Mike Lewis, Yinhan Liu, Naman Goyal, Marjan Ghazvininejad, Abdelrahman Mohamed, Omer Levy, Ves Stoyanov and Luke Zettlemoyer.
+1. **[BARThez](model_doc/barthez)** (from Ăcole polytechnique) released with the paper [BARThez: a Skilled Pretrained French Sequence-to-Sequence Model](https://arxiv.org/abs/2010.12321) by Moussa Kamal Eddine, Antoine J.-P. Tixier, Michalis Vazirgiannis.
+1. **[BARTpho](model_doc/bartpho)** (from VinAI Research) released with the paper [BARTpho: Pre-trained Sequence-to-Sequence Models for Vietnamese](https://arxiv.org/abs/2109.09701) by Nguyen Luong Tran, Duong Minh Le and Dat Quoc Nguyen.
+1. **[BEiT](model_doc/beit)** (from Microsoft) released with the paper [BEiT: BERT Pre-Training of Image Transformers](https://arxiv.org/abs/2106.08254) by Hangbo Bao, Li Dong, Furu Wei.
+1. **[BERT](model_doc/bert)** (from Google) released with the paper [BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding](https://arxiv.org/abs/1810.04805) by Jacob Devlin, Ming-Wei Chang, Kenton Lee and Kristina Toutanova.
+1. **[BERT For Sequence Generation](model_doc/bert-generation)** (from Google) released with the paper [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://arxiv.org/abs/1907.12461) by Sascha Rothe, Shashi Narayan, Aliaksei Severyn.
+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.
+1. **[BigBird-Pegasus](model_doc/bigbird_pegasus)** (from Google Research) released with the paper [Big Bird: Transformers for Longer Sequences](https://arxiv.org/abs/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.
+1. **[BigBird-RoBERTa](model_doc/big_bird)** (from Google Research) released with the paper [Big Bird: Transformers for Longer Sequences](https://arxiv.org/abs/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.
+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.
+1. **[BiT](model_doc/bit)** (from Google AI) released with the paper [Big Transfer (BiT): General Visual Representation Learning](https://arxiv.org/abs/1912.11370) by Alexander Kolesnikov, Lucas Beyer, Xiaohua Zhai, Joan Puigcerver, Jessica Yung, Sylvain Gelly, Neil Houlsby.
+1. **[Blenderbot](model_doc/blenderbot)** (from Facebook) released with the paper [Recipes for building an open-domain chatbot](https://arxiv.org/abs/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.
+1. **[BlenderbotSmall](model_doc/blenderbot-small)** (from Facebook) released with the paper [Recipes for building an open-domain chatbot](https://arxiv.org/abs/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.
+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://arxiv.org/abs/2201.12086) by Junnan Li, Dongxu Li, Caiming Xiong, Steven Hoi.
+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://arxiv.org/abs/2301.12597) by Junnan Li, Dongxu Li, Silvio Savarese, Steven Hoi.
+1. **[BLOOM](model_doc/bloom)** (from BigScience workshop) released by the [BigScience Workshop](https://bigscience.huggingface.co/).
+1. **[BORT](model_doc/bort)** (from Alexa) released with the paper [Optimal Subarchitecture Extraction For BERT](https://arxiv.org/abs/2010.10499) by Adrian de Wynter and Daniel J. Perry.
+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://arxiv.org/abs/2206.08657) by Xiao Xu, Chenfei Wu, Shachar Rosenman, Vasudev Lal, Wanxiang Che, Nan Duan.
+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://arxiv.org/abs/2105.13626) by Linting Xue, Aditya Barua, Noah Constant, Rami Al-Rfou, Sharan Narang, Mihir Kale, Adam Roberts, Colin Raffel.
+1. **[CamemBERT](model_doc/camembert)** (from Inria/Facebook/Sorbonne) released with the paper [CamemBERT: a Tasty French Language Model](https://arxiv.org/abs/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.
+1. **[CANINE](model_doc/canine)** (from Google Research) released with the paper [CANINE: Pre-training an Efficient Tokenization-Free Encoder for Language Representation](https://arxiv.org/abs/2103.06874) by Jonathan H. Clark, Dan Garrette, Iulia Turc, John Wieting.
+1. **[Chinese-CLIP](model_doc/chinese_clip)** (from OFA-Sys) released with the paper [Chinese CLIP: Contrastive Vision-Language Pretraining in Chinese](https://arxiv.org/abs/2211.01335) by An Yang, Junshu Pan, Junyang Lin, Rui Men, Yichang Zhang, Jingren Zhou, Chang Zhou.
+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://arxiv.org/abs/2211.06687) by Yusong Wu, Ke Chen, Tianyu Zhang, Yuchen Hui, Taylor Berg-Kirkpatrick, Shlomo Dubnov.
+1. **[CLIP](model_doc/clip)** (from OpenAI) released with the paper [Learning Transferable Visual Models From Natural Language Supervision](https://arxiv.org/abs/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.
+1. **[CLIPSeg](model_doc/clipseg)** (from University of Göttingen) released with the paper [Image Segmentation Using Text and Image Prompts](https://arxiv.org/abs/2112.10003) by Timo LĂŒddecke and Alexander Ecker.
+1. **[CodeGen](model_doc/codegen)** (from Salesforce) released with the paper [A Conversational Paradigm for Program Synthesis](https://arxiv.org/abs/2203.13474) by Erik Nijkamp, Bo Pang, Hiroaki Hayashi, Lifu Tu, Huan Wang, Yingbo Zhou, Silvio Savarese, Caiming Xiong.
+1. **[Conditional DETR](model_doc/conditional_detr)** (from Microsoft Research Asia) released with the paper [Conditional DETR for Fast Training Convergence](https://arxiv.org/abs/2108.06152) by Depu Meng, Xiaokang Chen, Zejia Fan, Gang Zeng, Houqiang Li, Yuhui Yuan, Lei Sun, Jingdong Wang.
+1. **[ConvBERT](model_doc/convbert)** (from YituTech) released with the paper [ConvBERT: Improving BERT with Span-based Dynamic Convolution](https://arxiv.org/abs/2008.02496) by Zihang Jiang, Weihao Yu, Daquan Zhou, Yunpeng Chen, Jiashi Feng, Shuicheng Yan.
+1. **[ConvNeXT](model_doc/convnext)** (from Facebook AI) released with the paper [A ConvNet for the 2020s](https://arxiv.org/abs/2201.03545) by Zhuang Liu, Hanzi Mao, Chao-Yuan Wu, Christoph Feichtenhofer, Trevor Darrell, Saining Xie.
+1. **[ConvNeXTV2](model_doc/convnextv2)** (from Facebook AI) released with the paper [ConvNeXt V2: Co-designing and Scaling ConvNets with Masked Autoencoders](https://arxiv.org/abs/2301.00808) by Sanghyun Woo, Shoubhik Debnath, Ronghang Hu, Xinlei Chen, Zhuang Liu, In So Kweon, Saining Xie.
+1. **[CPM](model_doc/cpm)** (from Tsinghua University) released with the paper [CPM: A Large-scale Generative Chinese Pre-trained Language Model](https://arxiv.org/abs/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.
+1. **[CPM-Ant](model_doc/cpmant)** (from OpenBMB) released by the [OpenBMB](https://www.openbmb.org/).
+1. **[CTRL](model_doc/ctrl)** (from Salesforce) released with the paper [CTRL: A Conditional Transformer Language Model for Controllable Generation](https://arxiv.org/abs/1909.05858) by Nitish Shirish Keskar*, Bryan McCann*, Lav R. Varshney, Caiming Xiong and Richard Socher.
+1. **[CvT](model_doc/cvt)** (from Microsoft) released with the paper [CvT: Introducing Convolutions to Vision Transformers](https://arxiv.org/abs/2103.15808) by Haiping Wu, Bin Xiao, Noel Codella, Mengchen Liu, Xiyang Dai, Lu Yuan, Lei Zhang.
+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://arxiv.org/abs/2202.03555) by Alexei Baevski, Wei-Ning Hsu, Qiantong Xu, Arun Babu, Jiatao Gu, Michael Auli.
+1. **[DeBERTa](model_doc/deberta)** (from Microsoft) released with the paper [DeBERTa: Decoding-enhanced BERT with Disentangled Attention](https://arxiv.org/abs/2006.03654) by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen.
+1. **[DeBERTa-v2](model_doc/deberta-v2)** (from Microsoft) released with the paper [DeBERTa: Decoding-enhanced BERT with Disentangled Attention](https://arxiv.org/abs/2006.03654) by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen.
+1. **[Decision Transformer](model_doc/decision_transformer)** (from Berkeley/Facebook/Google) released with the paper [Decision Transformer: Reinforcement Learning via Sequence Modeling](https://arxiv.org/abs/2106.01345) by Lili Chen, Kevin Lu, Aravind Rajeswaran, Kimin Lee, Aditya Grover, Michael Laskin, Pieter Abbeel, Aravind Srinivas, Igor Mordatch.
+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://arxiv.org/abs/2010.04159) by Xizhou Zhu, Weijie Su, Lewei Lu, Bin Li, Xiaogang Wang, Jifeng Dai.
+1. **[DeiT](model_doc/deit)** (from Facebook) released with the paper [Training data-efficient image transformers & distillation through attention](https://arxiv.org/abs/2012.12877) by Hugo Touvron, Matthieu Cord, Matthijs Douze, Francisco Massa, Alexandre Sablayrolles, Hervé Jégou.
+1. **[DePlot](model_doc/deplot)** (from Google AI) released with the paper [DePlot: One-shot visual language reasoning by plot-to-table translation](https://arxiv.org/abs/2212.10505) by Fangyu Liu, Julian Martin Eisenschlos, Francesco Piccinno, Syrine Krichene, Chenxi Pang, Kenton Lee, Mandar Joshi, Wenhu Chen, Nigel Collier, Yasemin Altun.
+1. **[DETA](model_doc/deta)** (from The University of Texas at Austin) released with the paper [NMS Strikes Back](https://arxiv.org/abs/2212.06137) by Jeffrey Ouyang-Zhang, Jang Hyun Cho, Xingyi Zhou, Philipp KrĂ€henbĂŒhl.
+1. **[DETR](model_doc/detr)** (from Facebook) released with the paper [End-to-End Object Detection with Transformers](https://arxiv.org/abs/2005.12872) by Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov, Sergey Zagoruyko.
+1. **[DialoGPT](model_doc/dialogpt)** (from Microsoft Research) released with the paper [DialoGPT: Large-Scale Generative Pre-training for Conversational Response Generation](https://arxiv.org/abs/1911.00536) by Yizhe Zhang, Siqi Sun, Michel Galley, Yen-Chun Chen, Chris Brockett, Xiang Gao, Jianfeng Gao, Jingjing Liu, Bill Dolan.
+1. **[DiNAT](model_doc/dinat)** (from SHI Labs) released with the paper [Dilated Neighborhood Attention Transformer](https://arxiv.org/abs/2209.15001) by Ali Hassani and Humphrey Shi.
+1. **[DistilBERT](model_doc/distilbert)** (from HuggingFace), released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter](https://arxiv.org/abs/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/tree/main/examples/research_projects/distillation), RoBERTa into [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/research_projects/distillation), Multilingual BERT into [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/research_projects/distillation) and a German version of DistilBERT.
+1. **[DiT](model_doc/dit)** (from Microsoft Research) released with the paper [DiT: Self-supervised Pre-training for Document Image Transformer](https://arxiv.org/abs/2203.02378) by Junlong Li, Yiheng Xu, Tengchao Lv, Lei Cui, Cha Zhang, Furu Wei.
+1. **[Donut](model_doc/donut)** (from NAVER), released together with the paper [OCR-free Document Understanding Transformer](https://arxiv.org/abs/2111.15664) by Geewook Kim, Teakgyu Hong, Moonbin Yim, Jeongyeon Nam, Jinyoung Park, Jinyeong Yim, Wonseok Hwang, Sangdoo Yun, Dongyoon Han, Seunghyun Park.
+1. **[DPR](model_doc/dpr)** (from Facebook) released with the paper [Dense Passage Retrieval for Open-Domain Question Answering](https://arxiv.org/abs/2004.04906) by Vladimir Karpukhin, Barlas OÄuz, Sewon Min, Patrick Lewis, Ledell Wu, Sergey Edunov, Danqi Chen, and Wen-tau Yih.
+1. **[DPT](master/model_doc/dpt)** (from Intel Labs) released with the paper [Vision Transformers for Dense Prediction](https://arxiv.org/abs/2103.13413) by René Ranftl, Alexey Bochkovskiy, Vladlen Koltun.
+1. **[EfficientFormer](model_doc/efficientformer)** (from Snap Research) released with the paper [EfficientFormer: Vision Transformers at MobileNetSpeed](https://arxiv.org/abs/2206.01191) by Yanyu Li, Geng Yuan, Yang Wen, Ju Hu, Georgios Evangelidis, Sergey Tulyakov, Yanzhi Wang, Jian Ren.
+1. **[EfficientNet](model_doc/efficientnet)** (from Google Brain) released with the paper [EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks](https://arxiv.org/abs/1905.11946) by Mingxing Tan, Quoc V. Le.
+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://arxiv.org/abs/2003.10555) by Kevin Clark, Minh-Thang Luong, Quoc V. Le, Christopher D. Manning.
+1. **[EncoderDecoder](model_doc/encoder-decoder)** (from Google Research) released with the paper [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://arxiv.org/abs/1907.12461) by Sascha Rothe, Shashi Narayan, Aliaksei Severyn.
+1. **[ERNIE](model_doc/ernie)** (from Baidu) released with the paper [ERNIE: Enhanced Representation through Knowledge Integration](https://arxiv.org/abs/1904.09223) by Yu Sun, Shuohuan Wang, Yukun Li, Shikun Feng, Xuyi Chen, Han Zhang, Xin Tian, Danxiang Zhu, Hao Tian, Hua Wu.
+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://arxiv.org/abs/2012.15674) by Xuan Ouyang, Shuohuan Wang, Chao Pang, Yu Sun, Hao Tian, Hua Wu, Haifeng Wang.
+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.
+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
+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
+1. **[FlauBERT](model_doc/flaubert)** (from CNRS) released with the paper [FlauBERT: Unsupervised Language Model Pre-training for French](https://arxiv.org/abs/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.
+1. **[FLAVA](model_doc/flava)** (from Facebook AI) released with the paper [FLAVA: A Foundational Language And Vision Alignment Model](https://arxiv.org/abs/2112.04482) by Amanpreet Singh, Ronghang Hu, Vedanuj Goswami, Guillaume Couairon, Wojciech Galuba, Marcus Rohrbach, and Douwe Kiela.
+1. **[FNet](model_doc/fnet)** (from Google Research) released with the paper [FNet: Mixing Tokens with Fourier Transforms](https://arxiv.org/abs/2105.03824) by James Lee-Thorp, Joshua Ainslie, Ilya Eckstein, Santiago Ontanon.
+1. **[FocalNet](model_doc/focalnet)** (from Microsoft Research) released with the paper [Focal Modulation Networks](https://arxiv.org/abs/2203.11926) by Jianwei Yang, Chunyuan Li, Xiyang Dai, Lu Yuan, Jianfeng Gao.
+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://arxiv.org/abs/2006.03236) by Zihang Dai, Guokun Lai, Yiming Yang, Quoc V. Le.
+1. **[GIT](model_doc/git)** (from Microsoft Research) released with the paper [GIT: A Generative Image-to-text Transformer for Vision and Language](https://arxiv.org/abs/2205.14100) by Jianfeng Wang, Zhengyuan Yang, Xiaowei Hu, Linjie Li, Kevin Lin, Zhe Gan, Zicheng Liu, Ce Liu, Lijuan Wang.
+1. **[GLPN](model_doc/glpn)** (from KAIST) released with the paper [Global-Local Path Networks for Monocular Depth Estimation with Vertical CutDepth](https://arxiv.org/abs/2201.07436) by Doyeon Kim, Woonghyun Ga, Pyungwhan Ahn, Donggyu Joo, Sehwan Chun, Junmo Kim.
+1. **[GPT](model_doc/openai-gpt)** (from OpenAI) released with the paper [Improving Language Understanding by Generative Pre-Training](https://blog.openai.com/language-unsupervised/) by Alec Radford, Karthik Narasimhan, Tim Salimans and Ilya Sutskever.
+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.
+1. **[GPT NeoX](model_doc/gpt_neox)** (from EleutherAI) released with the paper [GPT-NeoX-20B: An Open-Source Autoregressive Language Model](https://arxiv.org/abs/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
+1. **[GPT NeoX Japanese](model_doc/gpt_neox_japanese)** (from ABEJA) released by Shinya Otani, Takayoshi Makabe, Anuj Arora, and Kyo Hattori.
+1. **[GPT-2](model_doc/gpt2)** (from OpenAI) released with the paper [Language Models are Unsupervised Multitask Learners](https://blog.openai.com/better-language-models/) by Alec Radford*, Jeffrey Wu*, Rewon Child, David Luan, Dario Amodei** and Ilya Sutskever**.
+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.
+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.
+1. **[GPTBigCode](model_doc/gpt_bigcode)** (from BigCode) released with the paper [SantaCoder: don't reach for the stars!](https://arxiv.org/abs/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.
+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).
+1. **[Graphormer](model_doc/graphormer)** (from Microsoft) released with the paper [Do Transformers Really Perform Bad for Graph Representation?](https://arxiv.org/abs/2106.05234) by Chengxuan Ying, Tianle Cai, Shengjie Luo, Shuxin Zheng, Guolin Ke, Di He, Yanming Shen, Tie-Yan Liu.
+1. **[GroupViT](model_doc/groupvit)** (from UCSD, NVIDIA) released with the paper [GroupViT: Semantic Segmentation Emerges from Text Supervision](https://arxiv.org/abs/2202.11094) by Jiarui Xu, Shalini De Mello, Sifei Liu, Wonmin Byeon, Thomas Breuel, Jan Kautz, Xiaolong Wang.
+1. **[Hubert](model_doc/hubert)** (from Facebook) released with the paper [HuBERT: Self-Supervised Speech Representation Learning by Masked Prediction of Hidden Units](https://arxiv.org/abs/2106.07447) by Wei-Ning Hsu, Benjamin Bolte, Yao-Hung Hubert Tsai, Kushal Lakhotia, Ruslan Salakhutdinov, Abdelrahman Mohamed.
+1. **[I-BERT](model_doc/ibert)** (from Berkeley) released with the paper [I-BERT: Integer-only BERT Quantization](https://arxiv.org/abs/2101.01321) by Sehoon Kim, Amir Gholami, Zhewei Yao, Michael W. Mahoney, Kurt Keutzer.
+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.
+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://arxiv.org/abs/2012.07436) by Haoyi Zhou, Shanghang Zhang, Jieqi Peng, Shuai Zhang, Jianxin Li, Hui Xiong, and Wancai Zhang.
+1. **[Jukebox](model_doc/jukebox)** (from OpenAI) released with the paper [Jukebox: A Generative Model for Music](https://arxiv.org/pdf/2005.00341.pdf) by Prafulla Dhariwal, Heewoo Jun, Christine Payne, Jong Wook Kim, Alec Radford, Ilya Sutskever.
+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://arxiv.org/abs/1912.13318) by Yiheng Xu, Minghao Li, Lei Cui, Shaohan Huang, Furu Wei, Ming Zhou.
+1. **[LayoutLMv2](model_doc/layoutlmv2)** (from Microsoft Research Asia) released with the paper [LayoutLMv2: Multi-modal Pre-training for Visually-Rich Document Understanding](https://arxiv.org/abs/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.
+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://arxiv.org/abs/2204.08387) by Yupan Huang, Tengchao Lv, Lei Cui, Yutong Lu, Furu Wei.
+1. **[LayoutXLM](model_doc/layoutxlm)** (from Microsoft Research Asia) released with the paper [LayoutXLM: Multimodal Pre-training for Multilingual Visually-rich Document Understanding](https://arxiv.org/abs/2104.08836) by Yiheng Xu, Tengchao Lv, Lei Cui, Guoxin Wang, Yijuan Lu, Dinei Florencio, Cha Zhang, Furu Wei.
+1. **[LED](model_doc/led)** (from AllenAI) released with the paper [Longformer: The Long-Document Transformer](https://arxiv.org/abs/2004.05150) by Iz Beltagy, Matthew E. Peters, Arman Cohan.
+1. **[LeViT](model_doc/levit)** (from Meta AI) released with the paper [LeViT: A Vision Transformer in ConvNet's Clothing for Faster Inference](https://arxiv.org/abs/2104.01136) by Ben Graham, Alaaeldin El-Nouby, Hugo Touvron, Pierre Stock, Armand Joulin, Hervé Jégou, Matthijs Douze.
+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://arxiv.org/abs/2202.13669) by Jiapeng Wang, Lianwen Jin, Kai Ding.
+1. **[LLaMA](model_doc/llama)** (from The FAIR team of Meta AI) released with the paper [LLaMA: Open and Efficient Foundation Language Models](https://arxiv.org/abs/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.
+1. **[Longformer](model_doc/longformer)** (from AllenAI) released with the paper [Longformer: The Long-Document Transformer](https://arxiv.org/abs/2004.05150) by Iz Beltagy, Matthew E. Peters, Arman Cohan.
+1. **[LongT5](model_doc/longt5)** (from Google AI) released with the paper [LongT5: Efficient Text-To-Text Transformer for Long Sequences](https://arxiv.org/abs/2112.07916) by Mandy Guo, Joshua Ainslie, David Uthus, Santiago Ontanon, Jianmo Ni, Yun-Hsuan Sung, Yinfei Yang.
+1. **[LUKE](model_doc/luke)** (from Studio Ousia) released with the paper [LUKE: Deep Contextualized Entity Representations with Entity-aware Self-attention](https://arxiv.org/abs/2010.01057) by Ikuya Yamada, Akari Asai, Hiroyuki Shindo, Hideaki Takeda, Yuji Matsumoto.
+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://arxiv.org/abs/1908.07490) by Hao Tan and Mohit Bansal.
+1. **[M-CTC-T](model_doc/mctct)** (from Facebook) released with the paper [Pseudo-Labeling For Massively Multilingual Speech Recognition](https://arxiv.org/abs/2111.00161) by Loren Lugosch, Tatiana Likhomanenko, Gabriel Synnaeve, and Ronan Collobert.
+1. **[M2M100](model_doc/m2m_100)** (from Facebook) released with the paper [Beyond English-Centric Multilingual Machine Translation](https://arxiv.org/abs/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.
+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.
+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://arxiv.org/abs/2110.08518) by Junlong Li, Yiheng Xu, Lei Cui, Furu Wei.
+1. **[Mask2Former](model_doc/mask2former)** (from FAIR and UIUC) released with the paper [Masked-attention Mask Transformer for Universal Image Segmentation](https://arxiv.org/abs/2112.01527) by Bowen Cheng, Ishan Misra, Alexander G. Schwing, Alexander Kirillov, Rohit Girdhar.
+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://arxiv.org/abs/2107.06278) by Bowen Cheng, Alexander G. Schwing, Alexander Kirillov.
+1. **[MatCha](model_doc/matcha)** (from Google AI) released with the paper [MatCha: Enhancing Visual Language Pretraining with Math Reasoning and Chart Derendering](https://arxiv.org/abs/2212.09662) by Fangyu Liu, Francesco Piccinno, Syrine Krichene, Chenxi Pang, Kenton Lee, Mandar Joshi, Yasemin Altun, Nigel Collier, Julian Martin Eisenschlos.
+1. **[mBART](model_doc/mbart)** (from Facebook) released with the paper [Multilingual Denoising Pre-training for Neural Machine Translation](https://arxiv.org/abs/2001.08210) by Yinhan Liu, Jiatao Gu, Naman Goyal, Xian Li, Sergey Edunov, Marjan Ghazvininejad, Mike Lewis, Luke Zettlemoyer.
+1. **[mBART-50](model_doc/mbart)** (from Facebook) released with the paper [Multilingual Translation with Extensible Multilingual Pretraining and Finetuning](https://arxiv.org/abs/2008.00401) by Yuqing Tang, Chau Tran, Xian Li, Peng-Jen Chen, Naman Goyal, Vishrav Chaudhary, Jiatao Gu, Angela Fan.
+1. **[MEGA](model_doc/mega)** (from Meta/USC/CMU/SJTU) released with the paper [Mega: Moving Average Equipped Gated Attention](https://arxiv.org/abs/2209.10655) by Xuezhe Ma, Chunting Zhou, Xiang Kong, Junxian He, Liangke Gui, Graham Neubig, Jonathan May, and Luke Zettlemoyer.
+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://arxiv.org/abs/1909.08053) by Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper and Bryan Catanzaro.
+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://arxiv.org/abs/1909.08053) by Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper and Bryan Catanzaro.
+1. **[MGP-STR](model_doc/mgp-str)** (from Alibaba Research) released with the paper [Multi-Granularity Prediction for Scene Text Recognition](https://arxiv.org/abs/2209.03592) by Peng Wang, Cheng Da, and Cong Yao.
+1. **[mLUKE](model_doc/mluke)** (from Studio Ousia) released with the paper [mLUKE: The Power of Entity Representations in Multilingual Pretrained Language Models](https://arxiv.org/abs/2110.08151) by Ryokan Ri, Ikuya Yamada, and Yoshimasa Tsuruoka.
+1. **[MobileBERT](model_doc/mobilebert)** (from CMU/Google Brain) released with the paper [MobileBERT: a Compact Task-Agnostic BERT for Resource-Limited Devices](https://arxiv.org/abs/2004.02984) by Zhiqing Sun, Hongkun Yu, Xiaodan Song, Renjie Liu, Yiming Yang, and Denny Zhou.
+1. **[MobileNetV1](model_doc/mobilenet_v1)** (from Google Inc.) released with the paper [MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications](https://arxiv.org/abs/1704.04861) by Andrew G. Howard, Menglong Zhu, Bo Chen, Dmitry Kalenichenko, Weijun Wang, Tobias Weyand, Marco Andreetto, Hartwig Adam.
+1. **[MobileNetV2](model_doc/mobilenet_v2)** (from Google Inc.) released with the paper [MobileNetV2: Inverted Residuals and Linear Bottlenecks](https://arxiv.org/abs/1801.04381) by Mark Sandler, Andrew Howard, Menglong Zhu, Andrey Zhmoginov, Liang-Chieh Chen.
+1. **[MobileViT](model_doc/mobilevit)** (from Apple) released with the paper [MobileViT: Light-weight, General-purpose, and Mobile-friendly Vision Transformer](https://arxiv.org/abs/2110.02178) by Sachin Mehta and Mohammad Rastegari.
+1. **[MPNet](model_doc/mpnet)** (from Microsoft Research) released with the paper [MPNet: Masked and Permuted Pre-training for Language Understanding](https://arxiv.org/abs/2004.09297) by Kaitao Song, Xu Tan, Tao Qin, Jianfeng Lu, Tie-Yan Liu.
+1. **[MT5](model_doc/mt5)** (from Google AI) released with the paper [mT5: A massively multilingual pre-trained text-to-text transformer](https://arxiv.org/abs/2010.11934) by Linting Xue, Noah Constant, Adam Roberts, Mihir Kale, Rami Al-Rfou, Aditya Siddhant, Aditya Barua, Colin Raffel.
+1. **[MVP](model_doc/mvp)** (from RUC AI Box) released with the paper [MVP: Multi-task Supervised Pre-training for Natural Language Generation](https://arxiv.org/abs/2206.12131) by Tianyi Tang, Junyi Li, Wayne Xin Zhao and Ji-Rong Wen.
+1. **[NAT](model_doc/nat)** (from SHI Labs) released with the paper [Neighborhood Attention Transformer](https://arxiv.org/abs/2204.07143) by Ali Hassani, Steven Walton, Jiachen Li, Shen Li, and Humphrey Shi.
+1. **[Nezha](model_doc/nezha)** (from Huawei Noahâs Ark Lab) released with the paper [NEZHA: Neural Contextualized Representation for Chinese Language Understanding](https://arxiv.org/abs/1909.00204) by Junqiu Wei, Xiaozhe Ren, Xiaoguang Li, Wenyong Huang, Yi Liao, Yasheng Wang, Jiashu Lin, Xin Jiang, Xiao Chen and Qun Liu.
+1. **[NLLB](model_doc/nllb)** (from Meta) released with the paper [No Language Left Behind: Scaling Human-Centered Machine Translation](https://arxiv.org/abs/2207.04672) by the NLLB team.
+1. **[NLLB-MOE](model_doc/nllb-moe)** (from Meta) released with the paper [No Language Left Behind: Scaling Human-Centered Machine Translation](https://arxiv.org/abs/2207.04672) by the NLLB team.
+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://arxiv.org/abs/2102.03902) by Yunyang Xiong, Zhanpeng Zeng, Rudrasis Chakraborty, Mingxing Tan, Glenn Fung, Yin Li, Vikas Singh.
+1. **[OneFormer](model_doc/oneformer)** (from SHI Labs) released with the paper [OneFormer: One Transformer to Rule Universal Image Segmentation](https://arxiv.org/abs/2211.06220) by Jitesh Jain, Jiachen Li, MangTik Chiu, Ali Hassani, Nikita Orlov, Humphrey Shi.
+1. **[OpenLlama](model_doc/open-llama)** (from [s-JoL](https://huggingface.co/s-JoL)) released in [Open-Llama](https://github.com/s-JoL/Open-Llama).
+1. **[OPT](master/model_doc/opt)** (from Meta AI) released with the paper [OPT: Open Pre-trained Transformer Language Models](https://arxiv.org/abs/2205.01068) by Susan Zhang, Stephen Roller, Naman Goyal, Mikel Artetxe, Moya Chen, Shuohui Chen et al.
+1. **[OWL-ViT](model_doc/owlvit)** (from Google AI) released with the paper [Simple Open-Vocabulary Object Detection with Vision Transformers](https://arxiv.org/abs/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.
+1. **[Pegasus](model_doc/pegasus)** (from Google) released with the paper [PEGASUS: Pre-training with Extracted Gap-sentences for Abstractive Summarization](https://arxiv.org/abs/1912.08777) by Jingqing Zhang, Yao Zhao, Mohammad Saleh and Peter J. Liu.
+1. **[PEGASUS-X](model_doc/pegasus_x)** (from Google) released with the paper [Investigating Efficiently Extending Transformers for Long Input Summarization](https://arxiv.org/abs/2208.04347) by Jason Phang, Yao Zhao, and Peter J. Liu.
+1. **[Perceiver IO](model_doc/perceiver)** (from Deepmind) released with the paper [Perceiver IO: A General Architecture for Structured Inputs & Outputs](https://arxiv.org/abs/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.
+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.
+1. **[Pix2Struct](model_doc/pix2struct)** (from Google) released with the paper [Pix2Struct: Screenshot Parsing as Pretraining for Visual Language Understanding](https://arxiv.org/abs/2210.03347) by Kenton Lee, Mandar Joshi, Iulia Turc, Hexiang Hu, Fangyu Liu, Julian Eisenschlos, Urvashi Khandelwal, Peter Shaw, Ming-Wei Chang, Kristina Toutanova.
+1. **[PLBart](model_doc/plbart)** (from UCLA NLP) released with the paper [Unified Pre-training for Program Understanding and Generation](https://arxiv.org/abs/2103.06333) by Wasi Uddin Ahmad, Saikat Chakraborty, Baishakhi Ray, Kai-Wei Chang.
+1. **[PoolFormer](model_doc/poolformer)** (from Sea AI Labs) released with the paper [MetaFormer is Actually What You Need for Vision](https://arxiv.org/abs/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.
+1. **[ProphetNet](model_doc/prophetnet)** (from Microsoft Research) released with the paper [ProphetNet: Predicting Future N-gram for Sequence-to-Sequence Pre-training](https://arxiv.org/abs/2001.04063) by Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang and Ming Zhou.
+1. **[QDQBert](model_doc/qdqbert)** (from NVIDIA) released with the paper [Integer Quantization for Deep Learning Inference: Principles and Empirical Evaluation](https://arxiv.org/abs/2004.09602) by Hao Wu, Patrick Judd, Xiaojie Zhang, Mikhail Isaev and Paulius Micikevicius.
+1. **[RAG](model_doc/rag)** (from Facebook) released with the paper [Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks](https://arxiv.org/abs/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.
+1. **[REALM](model_doc/realm.html)** (from Google Research) released with the paper [REALM: Retrieval-Augmented Language Model Pre-Training](https://arxiv.org/abs/2002.08909) by Kelvin Guu, Kenton Lee, Zora Tung, Panupong Pasupat and Ming-Wei Chang.
+1. **[Reformer](model_doc/reformer)** (from Google Research) released with the paper [Reformer: The Efficient Transformer](https://arxiv.org/abs/2001.04451) by Nikita Kitaev, Ćukasz Kaiser, Anselm Levskaya.
+1. **[RegNet](model_doc/regnet)** (from META Platforms) released with the paper [Designing Network Design Space](https://arxiv.org/abs/2003.13678) by Ilija Radosavovic, Raj Prateek Kosaraju, Ross Girshick, Kaiming He, Piotr DollĂĄr.
+1. **[RemBERT](model_doc/rembert)** (from Google Research) released with the paper [Rethinking embedding coupling in pre-trained language models](https://arxiv.org/abs/2010.12821) by Hyung Won Chung, Thibault Févry, Henry Tsai, M. Johnson, Sebastian Ruder.
+1. **[ResNet](model_doc/resnet)** (from Microsoft Research) released with the paper [Deep Residual Learning for Image Recognition](https://arxiv.org/abs/1512.03385) by Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun.
+1. **[RoBERTa](model_doc/roberta)** (from Facebook), released together with the paper [RoBERTa: A Robustly Optimized BERT Pretraining Approach](https://arxiv.org/abs/1907.11692) by Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Mandar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, Veselin Stoyanov.
+1. **[RoBERTa-PreLayerNorm](model_doc/roberta-prelayernorm)** (from Facebook) released with the paper [fairseq: A Fast, Extensible Toolkit for Sequence Modeling](https://arxiv.org/abs/1904.01038) by Myle Ott, Sergey Edunov, Alexei Baevski, Angela Fan, Sam Gross, Nathan Ng, David Grangier, Michael Auli.
+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.
+1. **[RoFormer](model_doc/roformer)** (from ZhuiyiTechnology), released together with the paper [RoFormer: Enhanced Transformer with Rotary Position Embedding](https://arxiv.org/abs/2104.09864) by Jianlin Su and Yu Lu and Shengfeng Pan and Bo Wen and Yunfeng Liu.
+1. **[RWKV](model_doc/rwkv)** (from Bo Peng), released on [this repo](https://github.com/BlinkDL/RWKV-LM) by Bo Peng.
+1. **[SegFormer](model_doc/segformer)** (from NVIDIA) released with the paper [SegFormer: Simple and Efficient Design for Semantic Segmentation with Transformers](https://arxiv.org/abs/2105.15203) by Enze Xie, Wenhai Wang, Zhiding Yu, Anima Anandkumar, Jose M. Alvarez, Ping Luo.
+1. **[Segment Anything](model_doc/sam)** (from Meta AI) released with the paper [Segment Anything](https://arxiv.org/pdf/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.
+1. **[SEW](model_doc/sew)** (from ASAPP) released with the paper [Performance-Efficiency Trade-offs in Unsupervised Pre-training for Speech Recognition](https://arxiv.org/abs/2109.06870) by Felix Wu, Kwangyoun Kim, Jing Pan, Kyu Han, Kilian Q. Weinberger, Yoav Artzi.
+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://arxiv.org/abs/2109.06870) by Felix Wu, Kwangyoun Kim, Jing Pan, Kyu Han, Kilian Q. Weinberger, Yoav Artzi.
+1. **[SpeechT5](model_doc/speecht5)** (from Microsoft Research) released with the paper [SpeechT5: Unified-Modal Encoder-Decoder Pre-Training for Spoken Language Processing](https://arxiv.org/abs/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.
+1. **[SpeechToTextTransformer](model_doc/speech_to_text)** (from Facebook), released together with the paper [fairseq S2T: Fast Speech-to-Text Modeling with fairseq](https://arxiv.org/abs/2010.05171) by Changhan Wang, Yun Tang, Xutai Ma, Anne Wu, Dmytro Okhonko, Juan Pino.
+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://arxiv.org/abs/2104.06678) by Changhan Wang, Anne Wu, Juan Pino, Alexei Baevski, Michael Auli, Alexis Conneau.
+1. **[Splinter](model_doc/splinter)** (from Tel Aviv University), released together with the paper [Few-Shot Question Answering by Pretraining Span Selection](https://arxiv.org/abs/2101.00438) by Ori Ram, Yuval Kirstain, Jonathan Berant, Amir Globerson, Omer Levy.
+1. **[SqueezeBERT](model_doc/squeezebert)** (from Berkeley) released with the paper [SqueezeBERT: What can computer vision teach NLP about efficient neural networks?](https://arxiv.org/abs/2006.11316) by Forrest N. Iandola, Albert E. Shaw, Ravi Krishna, and Kurt W. Keutzer.
+1. **[SwiftFormer](model_doc/swiftformer)** (from MBZUAI) released with the paper [SwiftFormer: Efficient Additive Attention for Transformer-based Real-time Mobile Vision Applications](https://arxiv.org/abs/2303.15446) by Abdelrahman Shaker, Muhammad Maaz, Hanoona Rasheed, Salman Khan, Ming-Hsuan Yang, Fahad Shahbaz Khan.
+1. **[Swin Transformer](model_doc/swin)** (from Microsoft) released with the paper [Swin Transformer: Hierarchical Vision Transformer using Shifted Windows](https://arxiv.org/abs/2103.14030) by Ze Liu, Yutong Lin, Yue Cao, Han Hu, Yixuan Wei, Zheng Zhang, Stephen Lin, Baining Guo.
+1. **[Swin Transformer V2](model_doc/swinv2)** (from Microsoft) released with the paper [Swin Transformer V2: Scaling Up Capacity and Resolution](https://arxiv.org/abs/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.
+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://arxiv.org/abs/2209.11345) by Marcos V. Conde, Ui-Jin Choi, Maxime Burchi, Radu Timofte.
+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://arxiv.org/abs/2101.03961) by William Fedus, Barret Zoph, Noam Shazeer.
+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://arxiv.org/abs/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.
+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.
+1. **[Table Transformer](model_doc/table-transformer)** (from Microsoft Research) released with the paper [PubTables-1M: Towards Comprehensive Table Extraction From Unstructured Documents](https://arxiv.org/abs/2110.00061) by Brandon Smock, Rohith Pesala, Robin Abraham.
+1. **[TAPAS](model_doc/tapas)** (from Google AI) released with the paper [TAPAS: Weakly Supervised Table Parsing via Pre-training](https://arxiv.org/abs/2004.02349) by Jonathan Herzig, PaweĆ Krzysztof Nowak, Thomas MĂŒller, Francesco Piccinno and Julian Martin Eisenschlos.
+1. **[TAPEX](model_doc/tapex)** (from Microsoft Research) released with the paper [TAPEX: Table Pre-training via Learning a Neural SQL Executor](https://arxiv.org/abs/2107.07653) by Qian Liu, Bei Chen, Jiaqi Guo, Morteza Ziyadi, Zeqi Lin, Weizhu Chen, Jian-Guang Lou.
+1. **[Time Series Transformer](model_doc/time_series_transformer)** (from HuggingFace).
+1. **[TimeSformer](model_doc/timesformer)** (from Facebook) released with the paper [Is Space-Time Attention All You Need for Video Understanding?](https://arxiv.org/abs/2102.05095) by Gedas Bertasius, Heng Wang, Lorenzo Torresani.
+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://arxiv.org/abs/2106.02039) by Michael Janner, Qiyang Li, Sergey Levine
+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://arxiv.org/abs/1901.02860) by Zihang Dai*, Zhilin Yang*, Yiming Yang, Jaime Carbonell, Quoc V. Le, Ruslan Salakhutdinov.
+1. **[TrOCR](model_doc/trocr)** (from Microsoft), released together with the paper [TrOCR: Transformer-based Optical Character Recognition with Pre-trained Models](https://arxiv.org/abs/2109.10282) by Minghao Li, Tengchao Lv, Lei Cui, Yijuan Lu, Dinei Florencio, Cha Zhang, Zhoujun Li, Furu Wei.
+1. **[TVLT](model_doc/tvlt)** (from UNC Chapel Hill) released with the paper [TVLT: Textless Vision-Language Transformer](https://arxiv.org/abs/2209.14156) by Zineng Tang, Jaemin Cho, Yixin Nie, Mohit Bansal.
+1. **[UL2](model_doc/ul2)** (from Google Research) released with the paper [Unifying Language Learning Paradigms](https://arxiv.org/abs/2205.05131v1) by Yi Tay, Mostafa Dehghani, Vinh Q. Tran, Xavier Garcia, Dara Bahri, Tal Schuster, Huaixiu Steven Zheng, Neil Houlsby, Donald Metzler
+1. **[UniSpeech](model_doc/unispeech)** (from Microsoft Research) released with the paper [UniSpeech: Unified Speech Representation Learning with Labeled and Unlabeled Data](https://arxiv.org/abs/2101.07597) by Chengyi Wang, Yu Wu, Yao Qian, Kenichi Kumatani, Shujie Liu, Furu Wei, Michael Zeng, Xuedong Huang.
+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://arxiv.org/abs/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.
+1. **[UPerNet](model_doc/upernet)** (from Peking University) released with the paper [Unified Perceptual Parsing for Scene Understanding](https://arxiv.org/abs/1807.10221) by Tete Xiao, Yingcheng Liu, Bolei Zhou, Yuning Jiang, Jian Sun.
+1. **[VAN](model_doc/van)** (from Tsinghua University and Nankai University) released with the paper [Visual Attention Network](https://arxiv.org/abs/2202.09741) by Meng-Hao Guo, Cheng-Ze Lu, Zheng-Ning Liu, Ming-Ming Cheng, Shi-Min Hu.
+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://arxiv.org/abs/2203.12602) by Zhan Tong, Yibing Song, Jue Wang, Limin Wang.
+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://arxiv.org/abs/2102.03334) by Wonjae Kim, Bokyung Son, Ildoo Kim.
+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://arxiv.org/abs/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.
+1. **[VisualBERT](model_doc/visual_bert)** (from UCLA NLP) released with the paper [VisualBERT: A Simple and Performant Baseline for Vision and Language](https://arxiv.org/pdf/1908.03557) by Liunian Harold Li, Mark Yatskar, Da Yin, Cho-Jui Hsieh, Kai-Wei Chang.
+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://arxiv.org/abs/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.
+1. **[ViTMAE](model_doc/vit_mae)** (from Meta AI) released with the paper [Masked Autoencoders Are Scalable Vision Learners](https://arxiv.org/abs/2111.06377) by Kaiming He, Xinlei Chen, Saining Xie, Yanghao Li, Piotr DollĂĄr, Ross Girshick.
+1. **[ViTMSN](model_doc/vit_msn)** (from Meta AI) released with the paper [Masked Siamese Networks for Label-Efficient Learning](https://arxiv.org/abs/2204.07141) by Mahmoud Assran, Mathilde Caron, Ishan Misra, Piotr Bojanowski, Florian Bordes, Pascal Vincent, Armand Joulin, Michael Rabbat, Nicolas Ballas.
+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://arxiv.org/abs/2006.11477) by Alexei Baevski, Henry Zhou, Abdelrahman Mohamed, Michael Auli.
+1. **[Wav2Vec2-Conformer](model_doc/wav2vec2-conformer)** (from Facebook AI) released with the paper [FAIRSEQ S2T: Fast Speech-to-Text Modeling with FAIRSEQ](https://arxiv.org/abs/2010.05171) by Changhan Wang, Yun Tang, Xutai Ma, Anne Wu, Sravya Popuri, Dmytro Okhonko, Juan Pino.
+1. **[Wav2Vec2Phoneme](model_doc/wav2vec2_phoneme)** (from Facebook AI) released with the paper [Simple and Effective Zero-shot Cross-lingual Phoneme Recognition](https://arxiv.org/abs/2109.11680) by Qiantong Xu, Alexei Baevski, Michael Auli.
+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://arxiv.org/abs/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.
+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.
+1. **[X-CLIP](model_doc/xclip)** (from Microsoft Research) released with the paper [Expanding Language-Image Pretrained Models for General Video Recognition](https://arxiv.org/abs/2208.02816) by Bolin Ni, Houwen Peng, Minghao Chen, Songyang Zhang, Gaofeng Meng, Jianlong Fu, Shiming Xiang, Haibin Ling.
+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.
+1. **[XGLM](model_doc/xglm)** (From Facebook AI) released with the paper [Few-shot Learning with Multilingual Language Models](https://arxiv.org/abs/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.
+1. **[XLM](model_doc/xlm)** (from Facebook) released together with the paper [Cross-lingual Language Model Pretraining](https://arxiv.org/abs/1901.07291) by Guillaume Lample and Alexis Conneau.
+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://arxiv.org/abs/2001.04063) by Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang and Ming Zhou.
+1. **[XLM-RoBERTa](model_doc/xlm-roberta)** (from Facebook AI), released together with the paper [Unsupervised Cross-lingual Representation Learning at Scale](https://arxiv.org/abs/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.
+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://arxiv.org/abs/2105.00572) by Naman Goyal, Jingfei Du, Myle Ott, Giri Anantharaman, Alexis Conneau.
+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://arxiv.org/abs/2301.10472) by Davis Liang, Hila Gonen, Yuning Mao, Rui Hou, Naman Goyal, Marjan Ghazvininejad, Luke Zettlemoyer, Madian Khabsa.
+1. **[XLNet](model_doc/xlnet)** (from Google/CMU) released with the paper [âXLNet: Generalized Autoregressive Pretraining for Language Understanding](https://arxiv.org/abs/1906.08237) by Zhilin Yang*, Zihang Dai*, Yiming Yang, Jaime Carbonell, Ruslan Salakhutdinov, Quoc V. Le.
+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://arxiv.org/abs/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.
+1. **[XLSR-Wav2Vec2](model_doc/xlsr_wav2vec2)** (from Facebook AI) released with the paper [Unsupervised Cross-Lingual Representation Learning For Speech Recognition](https://arxiv.org/abs/2006.13979) by Alexis Conneau, Alexei Baevski, Ronan Collobert, Abdelrahman Mohamed, Michael Auli.
+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://arxiv.org/abs/2106.00666) by Yuxin Fang, Bencheng Liao, Xinggang Wang, Jiemin Fang, Jiyang Qi, Rui Wu, Jianwei Niu, Wenyu Liu.
+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://arxiv.org/abs/2111.09714) by Zhanpeng Zeng, Yunyang Xiong, Sathya N. Ravi, Shailesh Acharya, Glenn Fung, Vikas Singh.
+
+
+### Rangka kerja yang disokong
+
+Jadual di bawah mewakili sokongan semasa dalam perpustakaan untuk setiap model tersebut, sama ada model tersebut mempunyai Python
+tokenizer (dipanggil ""lambat""). Tokenizer ""pantas"" yang disokong oleh perpustakaan Tokenizers đ€, sama ada mereka mempunyai sokongan dalam Jax (melalui
+Flax), PyTorch, dan/atau TensorFlow.
+
+
+
+| Model | Tokenizer slow | Tokenizer fast | PyTorch support | TensorFlow support | Flax Support |
+|:-----------------------------:|:--------------:|:--------------:|:---------------:|:------------------:|:------------:|
+| ALBERT | â
| â
| â
| â
| â
|
+| ALIGN | â | â | â
| â | â |
+| AltCLIP | â | â | â
| â | â |
+| Audio Spectrogram Transformer | â | â | â
| â | â |
+| Autoformer | â | â | â
| â | â |
+| BART | â
| â
| â
| â
| â
|
+| BEiT | â | â | â
| â | â
|
+| BERT | â
| â
| â
| â
| â
|
+| Bert Generation | â
| â | â
| â | â |
+| BigBird | â
| â
| â
| â | â
|
+| BigBird-Pegasus | â | â | â
| â | â |
+| BioGpt | â
| â | â
| â | â |
+| BiT | â | â | â
| â | â |
+| Blenderbot | â
| â
| â
| â
| â
|
+| BlenderbotSmall | â
| â
| â
| â
| â
|
+| BLIP | â | â | â
| â
| â |
+| BLIP-2 | â | â | â
| â | â |
+| BLOOM | â | â
| â
| â | â |
+| BridgeTower | â | â | â
| â | â |
+| CamemBERT | â
| â
| â
| â
| â |
+| CANINE | â
| â | â
| â | â |
+| Chinese-CLIP | â | â | â
| â | â |
+| CLAP | â | â | â
| â | â |
+| CLIP | â
| â
| â
| â
| â
|
+| CLIPSeg | â | â | â
| â | â |
+| CodeGen | â
| â
| â
| â | â |
+| Conditional DETR | â | â | â
| â | â |
+| ConvBERT | â
| â
| â
| â
| â |
+| ConvNeXT | â | â | â
| â
| â |
+| ConvNeXTV2 | â | â | â
| â | â |
+| CPM-Ant | â
| â | â
| â | â |
+| CTRL | â
| â | â
| â
| â |
+| CvT | â | â | â
| â
| â |
+| Data2VecAudio | â | â | â
| â | â |
+| Data2VecText | â | â | â
| â | â |
+| Data2VecVision | â | â | â
| â
| â |
+| DeBERTa | â
| â
| â
| â
| â |
+| DeBERTa-v2 | â
| â
| â
| â
| â |
+| Decision Transformer | â | â | â
| â | â |
+| Deformable DETR | â | â | â
| â | â |
+| DeiT | â | â | â
| â
| â |
+| DETA | â | â | â
| â | â |
+| DETR | â | â | â
| â | â |
+| DiNAT | â | â | â
| â | â |
+| DistilBERT | â
| â
| â
| â
| â
|
+| DonutSwin | â | â | â
| â | â |
+| DPR | â
| â
| â
| â
| â |
+| DPT | â | â | â
| â | â |
+| EfficientFormer | â | â | â
| â
| â |
+| EfficientNet | â | â | â
| â | â |
+| ELECTRA | â
| â
| â
| â
| â
|
+| Encoder decoder | â | â | â
| â
| â
|
+| ERNIE | â | â | â
| â | â |
+| ErnieM | â
| â | â
| â | â |
+| ESM | â
| â | â
| â
| â |
+| FairSeq Machine-Translation | â
| â | â
| â | â |
+| FlauBERT | â
| â | â
| â
| â |
+| FLAVA | â | â | â
| â | â |
+| FNet | â
| â
| â
| â | â |
+| FocalNet | â | â | â
| â | â |
+| Funnel Transformer | â
| â
| â
| â
| â |
+| GIT | â | â | â
| â | â |
+| GLPN | â | â | â
| â | â |
+| GPT Neo | â | â | â
| â | â
|
+| GPT NeoX | â | â
| â
| â | â |
+| GPT NeoX Japanese | â
| â | â
| â | â |
+| GPT-J | â | â | â
| â
| â
|
+| GPT-Sw3 | â
| â
| â
| â
| â
|
+| GPTBigCode | â | â | â
| â | â |
+| GPTSAN-japanese | â
| â | â
| â | â |
+| Graphormer | â | â | â
| â | â |
+| GroupViT | â | â | â
| â
| â |
+| Hubert | â | â | â
| â
| â |
+| I-BERT | â | â | â
| â | â |
+| ImageGPT | â | â | â
| â | â |
+| Informer | â | â | â
| â | â |
+| Jukebox | â
| â | â
| â | â |
+| LayoutLM | â
| â
| â
| â
| â |
+| LayoutLMv2 | â
| â
| â
| â | â |
+| LayoutLMv3 | â
| â
| â
| â
| â |
+| LED | â
| â
| â
| â
| â |
+| LeViT | â | â | â
| â | â |
+| LiLT | â | â | â
| â | â |
+| LLaMA | â
| â
| â
| â | â |
+| Longformer | â
| â
| â
| â
| â |
+| LongT5 | â | â | â
| â | â
|
+| LUKE | â
| â | â
| â | â |
+| LXMERT | â
| â
| â
| â
| â |
+| M-CTC-T | â | â | â
| â | â |
+| M2M100 | â
| â | â
| â | â |
+| Marian | â
| â | â
| â
| â
|
+| MarkupLM | â
| â
| â
| â | â |
+| Mask2Former | â | â | â
| â | â |
+| MaskFormer | â | â | â
| â | â |
+| MaskFormerSwin | â | â | â | â | â |
+| mBART | â
| â
| â
| â
| â
|
+| MEGA | â | â | â
| â | â |
+| Megatron-BERT | â | â | â
| â | â |
+| MGP-STR | â
| â | â
| â | â |
+| MobileBERT | â
| â
| â
| â
| â |
+| MobileNetV1 | â | â | â
| â | â |
+| MobileNetV2 | â | â | â
| â | â |
+| MobileViT | â | â | â
| â
| â |
+| MPNet | â
| â
| â
| â
| â |
+| MT5 | â
| â
| â
| â
| â
|
+| MVP | â
| â
| â
| â | â |
+| NAT | â | â | â
| â | â |
+| Nezha | â | â | â
| â | â |
+| NLLB-MOE | â | â | â
| â | â |
+| Nyströmformer | â | â | â
| â | â |
+| OneFormer | â | â | â
| â | â |
+| OpenAI GPT | â
| â
| â
| â
| â |
+| OpenAI GPT-2 | â
| â
| â
| â
| â
|
+| OpenLlama | â | â | â
| â | â |
+| OPT | â | â | â
| â
| â
|
+| OWL-ViT | â | â | â
| â | â |
+| Pegasus | â
| â
| â
| â
| â
|
+| PEGASUS-X | â | â | â
| â | â |
+| Perceiver | â
| â | â
| â | â |
+| Pix2Struct | â | â | â
| â | â |
+| PLBart | â
| â | â
| â | â |
+| PoolFormer | â | â | â
| â | â |
+| ProphetNet | â
| â | â
| â | â |
+| QDQBert | â | â | â
| â | â |
+| RAG | â
| â | â
| â
| â |
+| REALM | â
| â
| â
| â | â |
+| Reformer | â
| â
| â
| â | â |
+| RegNet | â | â | â
| â
| â
|
+| RemBERT | â
| â
| â
| â
| â |
+| ResNet | â | â | â
| â
| â
|
+| RetriBERT | â
| â
| â
| â | â |
+| RoBERTa | â
| â
| â
| â
| â
|
+| RoBERTa-PreLayerNorm | â | â | â
| â
| â
|
+| RoCBert | â
| â | â
| â | â |
+| RoFormer | â
| â
| â
| â
| â
|
+| RWKV | â | â | â
| â | â |
+| SAM | â | â | â
| â
| â |
+| SegFormer | â | â | â
| â
| â |
+| SEW | â | â | â
| â | â |
+| SEW-D | â | â | â
| â | â |
+| Speech Encoder decoder | â | â | â
| â | â
|
+| Speech2Text | â
| â | â
| â
| â |
+| Speech2Text2 | â
| â | â | â | â |
+| SpeechT5 | â
| â | â
| â | â |
+| Splinter | â
| â
| â
| â | â |
+| SqueezeBERT | â
| â
| â
| â | â |
+| SwiftFormer | â | â | â
| â | â |
+| Swin Transformer | â | â | â
| â
| â |
+| Swin Transformer V2 | â | â | â
| â | â |
+| Swin2SR | â | â | â
| â | â |
+| SwitchTransformers | â | â | â
| â | â |
+| T5 | â
| â
| â
| â
| â
|
+| Table Transformer | â | â | â
| â | â |
+| TAPAS | â
| â | â
| â
| â |
+| Time Series Transformer | â | â | â
| â | â |
+| TimeSformer | â | â | â
| â | â |
+| Trajectory Transformer | â | â | â
| â | â |
+| Transformer-XL | â
| â | â
| â
| â |
+| TrOCR | â | â | â
| â | â |
+| TVLT | â | â | â
| â | â |
+| UniSpeech | â | â | â
| â | â |
+| UniSpeechSat | â | â | â
| â | â |
+| UPerNet | â | â | â
| â | â |
+| VAN | â | â | â
| â | â |
+| VideoMAE | â | â | â
| â | â |
+| ViLT | â | â | â
| â | â |
+| Vision Encoder decoder | â | â | â
| â
| â
|
+| VisionTextDualEncoder | â | â | â
| â
| â
|
+| VisualBERT | â | â | â
| â | â |
+| ViT | â | â | â
| â
| â
|
+| ViT Hybrid | â | â | â
| â | â |
+| ViTMAE | â | â | â
| â
| â |
+| ViTMSN | â | â | â
| â | â |
+| Wav2Vec2 | â
| â | â
| â
| â
|
+| Wav2Vec2-Conformer | â | â | â
| â | â |
+| WavLM | â | â | â
| â | â |
+| Whisper | â
| â
| â
| â
| â
|
+| X-CLIP | â | â | â
| â | â |
+| X-MOD | â | â | â
| â | â |
+| XGLM | â
| â
| â
| â
| â
|
+| XLM | â
| â | â
| â
| â |
+| XLM-ProphetNet | â
| â | â
| â | â |
+| XLM-RoBERTa | â
| â
| â
| â
| â
|
+| XLM-RoBERTa-XL | â | â | â
| â | â |
+| XLNet | â
| â
| â
| â
| â |
+| YOLOS | â | â | â
| â | â |
+| YOSO | â | â | â
| â | â |
+
+
diff --git a/docs/source/pt/accelerate.md b/docs/source/pt/accelerate.md
new file mode 100644
index 000000000000..a4e346a2b487
--- /dev/null
+++ b/docs/source/pt/accelerate.md
@@ -0,0 +1,145 @@
+
+
+# Treinamento distribuĂdo com o đ€ Accelerate
+
+O paralelismo surgiu como uma estratégia para treinar modelos grandes em hardware limitado e aumentar a velocidade
+de treinamento em vĂĄrias Ăłrdens de magnitude. Na Hugging Face criamos a biblioteca [đ€ Accelerate](https://huggingface.co/docs/accelerate)
+para ajudar os usuĂĄrios a treinar modelos đ€ Transformers com qualquer configuração distribuĂda, seja em uma mĂĄquina
+com mĂșltiplos GPUs ou em mĂșltiplos GPUs distribuidos entre muitas mĂĄquinas. Neste tutorial, vocĂȘ irĂĄ aprender como
+personalizar seu laço de treinamento de PyTorch para poder treinar em ambientes distribuĂdos.
+
+## Configuração
+
+De inĂcio, instale o đ€ Accelerate:
+
+```bash
+pip install accelerate
+```
+
+Logo, devemos importar e criar um objeto [`Accelerator`](https://huggingface.co/docs/accelerate/package_reference/accelerator#accelerate.Accelerator).
+O `Accelerator` detectarĂĄ automĂĄticamente a configuração distribuĂda disponĂvel e inicializarĂĄ todos os
+componentes necessĂĄrios para o treinamento. NĂŁo hĂĄ necessidade portanto de especificar o dispositivo onde deve colocar seu modelo.
+
+```py
+>>> from accelerate import Accelerator
+
+>>> accelerator = Accelerator()
+```
+
+## Preparando a aceleração
+
+Passe todos os objetos relevantes ao treinamento para o método [`prepare`](https://huggingface.co/docs/accelerate/package_reference/accelerator#accelerate.Accelerator.prepare).
+Isto inclui os DataLoaders de treino e evaluação, um modelo e um otimizador:
+
+```py
+>>> train_dataloader, eval_dataloader, model, optimizer = accelerator.prepare(
+... train_dataloader, eval_dataloader, model, optimizer
+... )
+```
+
+## Backward
+
+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:
+
+```py
+>>> for epoch in range(num_epochs):
+... for batch in train_dataloader:
+... outputs = model(**batch)
+... loss = outputs.loss
+... accelerator.backward(loss)
+
+... optimizer.step()
+... lr_scheduler.step()
+... optimizer.zero_grad()
+... progress_bar.update(1)
+```
+
+Como se poder ver no seguinte código, só precisarå adicionar quatro linhas de código ao seu laço de treinamento
+para habilitar o treinamento distribuĂdo!
+
+```diff
++ from accelerate import Accelerator
+ from transformers import AdamW, AutoModelForSequenceClassification, get_scheduler
+
++ accelerator = Accelerator()
+
+ model = AutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=2)
+ optimizer = AdamW(model.parameters(), lr=3e-5)
+
+- device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
+- model.to(device)
+
++ train_dataloader, eval_dataloader, model, optimizer = accelerator.prepare(
++ train_dataloader, eval_dataloader, model, optimizer
++ )
+
+ num_epochs = 3
+ num_training_steps = num_epochs * len(train_dataloader)
+ lr_scheduler = get_scheduler(
+ "linear",
+ optimizer=optimizer,
+ num_warmup_steps=0,
+ num_training_steps=num_training_steps
+ )
+
+ progress_bar = tqdm(range(num_training_steps))
+
+ model.train()
+ for epoch in range(num_epochs):
+ for batch in train_dataloader:
+- batch = {k: v.to(device) for k, v in batch.items()}
+ outputs = model(**batch)
+ loss = outputs.loss
+- loss.backward()
++ accelerator.backward(loss)
+
+ optimizer.step()
+ lr_scheduler.step()
+ optimizer.zero_grad()
+ progress_bar.update(1)
+```
+
+## Treinamento
+
+Quando tiver adicionado as linhas de cĂłdigo relevantes, inicie o treinamento por um script ou notebook como o Colab.
+
+### Treinamento em um Script
+
+Se estiver rodando seu treinamento em um Script, execute o seguinte comando para criar e guardar um arquivo de configuração:
+
+```bash
+accelerate config
+```
+
+Comece o treinamento com:
+
+```bash
+accelerate launch train.py
+```
+
+### Treinamento em um Notebook
+
+O đ€ Accelerate pode rodar em um notebook, por exemplo, se estiver planejando usar as TPUs do Google Colab.
+Encapsule o código responsåvel pelo treinamento de uma função e passe-o ao `notebook_launcher`:
+
+```py
+>>> from accelerate import notebook_launcher
+
+>>> notebook_launcher(training_function)
+```
+
+Para obter mais informaçÔes sobre o đ€ Accelerate e suas numerosas funçÔes, consulte a [documentaciĂłn](https://huggingface.co/docs/accelerate/index).
diff --git a/docs/source/pt/accelerate.mdx b/docs/source/pt/accelerate.mdx
deleted file mode 100644
index 59dbd96a83b2..000000000000
--- a/docs/source/pt/accelerate.mdx
+++ /dev/null
@@ -1,141 +0,0 @@
-
-
-# Treinamento distribuĂdo com o đ€ Accelerate
-
-O paralelismo surgiu como uma estratégia para treinar modelos grandes em hardware limitado e aumentar a velocidade
-de treinamento em vĂĄrias Ăłrdens de magnitude. Na Hugging Face criamos a biblioteca [đ€ Accelerate](https://huggingface.co/docs/accelerate)
-para ajudar os usuĂĄrios a treinar modelos đ€ Transformers com qualquer configuração distribuĂda, seja em uma mĂĄquina
-com mĂșltiplos GPUs ou em mĂșltiplos GPUs distribuidos entre muitas mĂĄquinas. Neste tutorial, vocĂȘ irĂĄ aprender como
-personalizar seu laço de treinamento de PyTorch para poder treinar em ambientes distribuĂdos.
-
-## Configuração
-
-De inĂcio, instale o đ€ Accelerate:
-
-```bash
-pip install accelerate
-```
-
-Logo, devemos importar e criar um objeto [`Accelerator`](https://huggingface.co/docs/accelerate/package_reference/accelerator#accelerate.Accelerator).
-O `Accelerator` detectarĂĄ automĂĄticamente a configuração distribuĂda disponĂvel e inicializarĂĄ todos os
-componentes necessĂĄrios para o treinamento. NĂŁo hĂĄ necessidade portanto de especificar o dispositivo onde deve colocar seu modelo.
-
-```py
->>> from accelerate import Accelerator
-
->>> accelerator = Accelerator()
-```
-
-## Preparando a aceleração
-
-Passe todos os objetos relevantes ao treinamento para o método [`prepare`](https://huggingface.co/docs/accelerate/package_reference/accelerator#accelerate.Accelerator.prepare).
-Isto inclui os DataLoaders de treino e evaluação, um modelo e um otimizador:
-
-```py
->>> train_dataloader, eval_dataloader, model, optimizer = accelerator.prepare(
-... train_dataloader, eval_dataloader, model, optimizer
-... )
-```
-
-## Backward
-
-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:
-
-```py
->>> for epoch in range(num_epochs):
-... for batch in train_dataloader:
-... outputs = model(**batch)
-... loss = outputs.loss
-... accelerator.backward(loss)
-
-... optimizer.step()
-... lr_scheduler.step()
-... optimizer.zero_grad()
-... progress_bar.update(1)
-```
-
-Como se poder ver no seguinte código, só precisarå adicionar quatro linhas de código ao seu laço de treinamento
-para habilitar o treinamento distribuĂdo!
-
-```diff
-+ from accelerate import Accelerator
- from transformers import AdamW, AutoModelForSequenceClassification, get_scheduler
-
-+ accelerator = Accelerator()
-
- model = AutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=2)
- optimizer = AdamW(model.parameters(), lr=3e-5)
-
-- device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
-- model.to(device)
-
-+ train_dataloader, eval_dataloader, model, optimizer = accelerator.prepare(
-+ train_dataloader, eval_dataloader, model, optimizer
-+ )
-
- num_epochs = 3
- num_training_steps = num_epochs * len(train_dataloader)
- lr_scheduler = get_scheduler(
- "linear",
- optimizer=optimizer,
- num_warmup_steps=0,
- num_training_steps=num_training_steps
- )
-
- progress_bar = tqdm(range(num_training_steps))
-
- model.train()
- for epoch in range(num_epochs):
- for batch in train_dataloader:
-- batch = {k: v.to(device) for k, v in batch.items()}
- outputs = model(**batch)
- loss = outputs.loss
-- loss.backward()
-+ accelerator.backward(loss)
-
- optimizer.step()
- lr_scheduler.step()
- optimizer.zero_grad()
- progress_bar.update(1)
-```
-
-## Treinamento
-
-Quando tiver adicionado as linhas de cĂłdigo relevantes, inicie o treinamento por um script ou notebook como o Colab.
-
-### Treinamento em um Script
-
-Se estiver rodando seu treinamento em um Script, execute o seguinte comando para criar e guardar um arquivo de configuração:
-
-```bash
-accelerate config
-```
-
-Comece o treinamento com:
-
-```bash
-accelerate launch train.py
-```
-
-### Treinamento em um Notebook
-
-O đ€ Accelerate pode rodar em um notebook, por exemplo, se estiver planejando usar as TPUs do Google Colab.
-Encapsule o código responsåvel pelo treinamento de uma função e passe-o ao `notebook_launcher`:
-
-```py
->>> from accelerate import notebook_launcher
-
->>> notebook_launcher(training_function)
-```
-
-Para obter mais informaçÔes sobre o đ€ Accelerate e suas numerosas funçÔes, consulte a [documentaciĂłn](https://huggingface.co/docs/accelerate/index).
diff --git a/docs/source/pt/converting_tensorflow_models.md b/docs/source/pt/converting_tensorflow_models.md
new file mode 100644
index 000000000000..ac1271d2764b
--- /dev/null
+++ b/docs/source/pt/converting_tensorflow_models.md
@@ -0,0 +1,166 @@
+
+
+# Convertendo checkpoints do TensorFlow para Pytorch
+
+Uma interface de linha de comando Ă© fornecida para converter os checkpoints originais Bert/GPT/GPT-2/Transformer-XL/XLNet/XLM em modelos
+que podem ser carregados usando os métodos `from_pretrained` da biblioteca.
+
+
+
+A partir da versĂŁo 2.3.0 o script de conversĂŁo agora faz parte do transformers CLI (**transformers-cli**) disponĂvel em qualquer instalação
+transformers >= 2.3.0.
+
+A documentação abaixo reflete o formato do comando **transformers-cli convert**.
+
+
+
+## BERT
+
+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
+[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.
+
+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
+arquivo de configuração (`bert_config.json`), e então cria um modelo PyTorch para esta configuração, carrega os pesos
+do checkpoint do TensorFlow no modelo PyTorch e salva o modelo resultante em um arquivo PyTorch que pode
+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) ).
+
+VocĂȘ sĂł precisa executar este script de conversĂŁo **uma vez** para obter um modelo PyTorch. VocĂȘ pode entĂŁo desconsiderar o checkpoint em
+ TensorFlow (os trĂȘs arquivos começando com `bert_model.ckpt`), mas certifique-se de manter o arquivo de configuração (\
+`bert_config.json`) e o arquivo de vocabulårio (`vocab.txt`), pois eles também são necessårios para o modelo PyTorch.
+
+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.
+
+Aqui estå um exemplo do processo de conversão para um modelo `BERT-Base Uncased` pré-treinado:
+
+```bash
+export BERT_BASE_DIR=/path/to/bert/uncased_L-12_H-768_A-12
+
+transformers-cli convert --model_type bert \
+ --tf_checkpoint $BERT_BASE_DIR/bert_model.ckpt \
+ --config $BERT_BASE_DIR/bert_config.json \
+ --pytorch_dump_output $BERT_BASE_DIR/pytorch_model.bin
+```
+
+VocĂȘ pode baixar os modelos prĂ©-treinados do Google para a conversĂŁo [aqui](https://github.com/google-research/bert#pre-trained-models).
+
+## ALBERT
+
+Converta os checkpoints do modelo ALBERT em TensorFlow para PyTorch usando o
+[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.
+
+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
+arquivo de configuração (`albert_config.json`), entĂŁo cria e salva um modelo PyTorch. Para executar esta conversĂŁo, vocĂȘ
+precisa ter o TensorFlow e o PyTorch instalados.
+
+Aqui estå um exemplo do processo de conversão para o modelo `ALBERT Base` pré-treinado:
+
+```bash
+export ALBERT_BASE_DIR=/path/to/albert/albert_base
+
+transformers-cli convert --model_type albert \
+ --tf_checkpoint $ALBERT_BASE_DIR/model.ckpt-best \
+ --config $ALBERT_BASE_DIR/albert_config.json \
+ --pytorch_dump_output $ALBERT_BASE_DIR/pytorch_model.bin
+```
+
+VocĂȘ pode baixar os modelos prĂ©-treinados do Google para a conversĂŁo [aqui](https://github.com/google-research/albert#pre-trained-models).
+
+## OpenAI GPT
+
+Aqui estå um exemplo do processo de conversão para um modelo OpenAI GPT pré-treinado, supondo que seu checkpoint NumPy
+foi salvo com o mesmo formato do modelo pré-treinado OpenAI (veja [aqui](https://github.com/openai/finetune-transformer-lm)\
+)
+
+```bash
+export OPENAI_GPT_CHECKPOINT_FOLDER_PATH=/path/to/openai/pretrained/numpy/weights
+
+transformers-cli convert --model_type gpt \
+ --tf_checkpoint $OPENAI_GPT_CHECKPOINT_FOLDER_PATH \
+ --pytorch_dump_output $PYTORCH_DUMP_OUTPUT \
+ [--config OPENAI_GPT_CONFIG] \
+ [--finetuning_task_name OPENAI_GPT_FINETUNED_TASK] \
+```
+
+## OpenAI GPT-2
+
+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))
+
+```bash
+export OPENAI_GPT2_CHECKPOINT_PATH=/path/to/gpt2/pretrained/weights
+
+transformers-cli convert --model_type gpt2 \
+ --tf_checkpoint $OPENAI_GPT2_CHECKPOINT_PATH \
+ --pytorch_dump_output $PYTORCH_DUMP_OUTPUT \
+ [--config OPENAI_GPT2_CONFIG] \
+ [--finetuning_task_name OPENAI_GPT2_FINETUNED_TASK]
+```
+
+## Transformer-XL
+
+Aqui estå um exemplo do processo de conversão para um modelo Transformer-XL pré-treinado (consulte [aqui](https://github.com/kimiyoung/transformer-xl/tree/master/tf#obtain-and-evaluate-pretrained-modelos-sota))
+
+```bash
+export TRANSFO_XL_CHECKPOINT_FOLDER_PATH=/path/to/transfo/xl/checkpoint
+
+transformers-cli convert --model_type transfo_xl \
+ --tf_checkpoint $TRANSFO_XL_CHECKPOINT_FOLDER_PATH \
+ --pytorch_dump_output $PYTORCH_DUMP_OUTPUT \
+ [--config TRANSFO_XL_CONFIG] \
+ [--finetuning_task_name TRANSFO_XL_FINETUNED_TASK]
+```
+
+## XLNet
+
+Aqui estå um exemplo do processo de conversão para um modelo XLNet pré-treinado:
+
+```bash
+export TRANSFO_XL_CHECKPOINT_PATH=/path/to/xlnet/checkpoint
+export TRANSFO_XL_CONFIG_PATH=/path/to/xlnet/config
+
+transformers-cli convert --model_type xlnet \
+ --tf_checkpoint $TRANSFO_XL_CHECKPOINT_PATH \
+ --config $TRANSFO_XL_CONFIG_PATH \
+ --pytorch_dump_output $PYTORCH_DUMP_OUTPUT \
+ [--finetuning_task_name XLNET_FINETUNED_TASK] \
+```
+
+## XLM
+
+Aqui estå um exemplo do processo de conversão para um modelo XLM pré-treinado:
+
+```bash
+export XLM_CHECKPOINT_PATH=/path/to/xlm/checkpoint
+
+transformers-cli convert --model_type xlm \
+ --tf_checkpoint $XLM_CHECKPOINT_PATH \
+ --pytorch_dump_output $PYTORCH_DUMP_OUTPUT
+ [--config XML_CONFIG] \
+ [--finetuning_task_name XML_FINETUNED_TASK]
+```
+
+## T5
+
+Aqui estå um exemplo do processo de conversão para um modelo T5 pré-treinado:
+
+```bash
+export T5=/path/to/t5/uncased_L-12_H-768_A-12
+
+transformers-cli convert --model_type t5 \
+ --tf_checkpoint $T5/t5_model.ckpt \
+ --config $T5/t5_config.json \
+ --pytorch_dump_output $T5/pytorch_model.bin
+```
diff --git a/docs/source/pt/converting_tensorflow_models.mdx b/docs/source/pt/converting_tensorflow_models.mdx
deleted file mode 100644
index db7be687c385..000000000000
--- a/docs/source/pt/converting_tensorflow_models.mdx
+++ /dev/null
@@ -1,162 +0,0 @@
-
-
-# Convertendo checkpoints do TensorFlow para Pytorch
-
-Uma interface de linha de comando Ă© fornecida para converter os checkpoints originais Bert/GPT/GPT-2/Transformer-XL/XLNet/XLM em modelos
-que podem ser carregados usando os métodos `from_pretrained` da biblioteca.
-
-
-
-A partir da versĂŁo 2.3.0 o script de conversĂŁo agora faz parte do transformers CLI (**transformers-cli**) disponĂvel em qualquer instalação
-transformers >= 2.3.0.
-
-A documentação abaixo reflete o formato do comando **transformers-cli convert**.
-
-
-
-## BERT
-
-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
-[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.
-
-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
-arquivo de configuração (`bert_config.json`), e então cria um modelo PyTorch para esta configuração, carrega os pesos
-do checkpoint do TensorFlow no modelo PyTorch e salva o modelo resultante em um arquivo PyTorch que pode
-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) ).
-
-VocĂȘ sĂł precisa executar este script de conversĂŁo **uma vez** para obter um modelo PyTorch. VocĂȘ pode entĂŁo desconsiderar o checkpoint em
- TensorFlow (os trĂȘs arquivos começando com `bert_model.ckpt`), mas certifique-se de manter o arquivo de configuração (\
-`bert_config.json`) e o arquivo de vocabulårio (`vocab.txt`), pois eles também são necessårios para o modelo PyTorch.
-
-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.
-
-Aqui estå um exemplo do processo de conversão para um modelo `BERT-Base Uncased` pré-treinado:
-
-```bash
-export BERT_BASE_DIR=/path/to/bert/uncased_L-12_H-768_A-12
-
-transformers-cli convert --model_type bert \
- --tf_checkpoint $BERT_BASE_DIR/bert_model.ckpt \
- --config $BERT_BASE_DIR/bert_config.json \
- --pytorch_dump_output $BERT_BASE_DIR/pytorch_model.bin
-```
-
-VocĂȘ pode baixar os modelos prĂ©-treinados do Google para a conversĂŁo [aqui](https://github.com/google-research/bert#pre-trained-models).
-
-## ALBERT
-
-Converta os checkpoints do modelo ALBERT em TensorFlow para PyTorch usando o
-[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.
-
-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
-arquivo de configuração (`albert_config.json`), entĂŁo cria e salva um modelo PyTorch. Para executar esta conversĂŁo, vocĂȘ
-precisa ter o TensorFlow e o PyTorch instalados.
-
-Aqui estå um exemplo do processo de conversão para o modelo `ALBERT Base` pré-treinado:
-
-```bash
-export ALBERT_BASE_DIR=/path/to/albert/albert_base
-
-transformers-cli convert --model_type albert \
- --tf_checkpoint $ALBERT_BASE_DIR/model.ckpt-best \
- --config $ALBERT_BASE_DIR/albert_config.json \
- --pytorch_dump_output $ALBERT_BASE_DIR/pytorch_model.bin
-```
-
-VocĂȘ pode baixar os modelos prĂ©-treinados do Google para a conversĂŁo [aqui](https://github.com/google-research/albert#pre-trained-models).
-
-## OpenAI GPT
-
-Aqui estå um exemplo do processo de conversão para um modelo OpenAI GPT pré-treinado, supondo que seu checkpoint NumPy
-foi salvo com o mesmo formato do modelo pré-treinado OpenAI (veja [aqui](https://github.com/openai/finetune-transformer-lm)\
-)
-
-```bash
-export OPENAI_GPT_CHECKPOINT_FOLDER_PATH=/path/to/openai/pretrained/numpy/weights
-
-transformers-cli convert --model_type gpt \
- --tf_checkpoint $OPENAI_GPT_CHECKPOINT_FOLDER_PATH \
- --pytorch_dump_output $PYTORCH_DUMP_OUTPUT \
- [--config OPENAI_GPT_CONFIG] \
- [--finetuning_task_name OPENAI_GPT_FINETUNED_TASK] \
-```
-
-## OpenAI GPT-2
-
-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))
-
-```bash
-export OPENAI_GPT2_CHECKPOINT_PATH=/path/to/gpt2/pretrained/weights
-
-transformers-cli convert --model_type gpt2 \
- --tf_checkpoint $OPENAI_GPT2_CHECKPOINT_PATH \
- --pytorch_dump_output $PYTORCH_DUMP_OUTPUT \
- [--config OPENAI_GPT2_CONFIG] \
- [--finetuning_task_name OPENAI_GPT2_FINETUNED_TASK]
-```
-
-## Transformer-XL
-
-Aqui estå um exemplo do processo de conversão para um modelo Transformer-XL pré-treinado (consulte [aqui](https://github.com/kimiyoung/transformer-xl/tree/master/tf#obtain-and-evaluate-pretrained-modelos-sota))
-
-```bash
-export TRANSFO_XL_CHECKPOINT_FOLDER_PATH=/path/to/transfo/xl/checkpoint
-
-transformers-cli convert --model_type transfo_xl \
- --tf_checkpoint $TRANSFO_XL_CHECKPOINT_FOLDER_PATH \
- --pytorch_dump_output $PYTORCH_DUMP_OUTPUT \
- [--config TRANSFO_XL_CONFIG] \
- [--finetuning_task_name TRANSFO_XL_FINETUNED_TASK]
-```
-
-## XLNet
-
-Aqui estå um exemplo do processo de conversão para um modelo XLNet pré-treinado:
-
-```bash
-export TRANSFO_XL_CHECKPOINT_PATH=/path/to/xlnet/checkpoint
-export TRANSFO_XL_CONFIG_PATH=/path/to/xlnet/config
-
-transformers-cli convert --model_type xlnet \
- --tf_checkpoint $TRANSFO_XL_CHECKPOINT_PATH \
- --config $TRANSFO_XL_CONFIG_PATH \
- --pytorch_dump_output $PYTORCH_DUMP_OUTPUT \
- [--finetuning_task_name XLNET_FINETUNED_TASK] \
-```
-
-## XLM
-
-Aqui estå um exemplo do processo de conversão para um modelo XLM pré-treinado:
-
-```bash
-export XLM_CHECKPOINT_PATH=/path/to/xlm/checkpoint
-
-transformers-cli convert --model_type xlm \
- --tf_checkpoint $XLM_CHECKPOINT_PATH \
- --pytorch_dump_output $PYTORCH_DUMP_OUTPUT
- [--config XML_CONFIG] \
- [--finetuning_task_name XML_FINETUNED_TASK]
-```
-
-## T5
-
-Aqui estå um exemplo do processo de conversão para um modelo T5 pré-treinado:
-
-```bash
-export T5=/path/to/t5/uncased_L-12_H-768_A-12
-
-transformers-cli convert --model_type t5 \
- --tf_checkpoint $T5/t5_model.ckpt \
- --config $T5/t5_config.json \
- --pytorch_dump_output $T5/pytorch_model.bin
-```
diff --git a/docs/source/pt/create_a_model.md b/docs/source/pt/create_a_model.md
new file mode 100644
index 000000000000..8c53752d6cf8
--- /dev/null
+++ b/docs/source/pt/create_a_model.md
@@ -0,0 +1,359 @@
+
+
+# Criar uma arquitetura customizada
+
+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:
+
+- Carregar e customizar a configuração de um modelo.
+- Criar a arquitetura de um modelo.
+- Criar um tokenizer rĂĄpido e devagar para textos.
+- Criar extrator de features para tarefas envolvendo audio e imagem.
+- Criar um processador para tarefas multimodais.
+
+## configuration
+
+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.
+
+DĂȘ uma olhada a mais em [DistilBERT](model_doc/distilbert) acessando [`DistilBertConfig`] para observar esses atributos:
+
+```py
+>>> from transformers import DistilBertConfig
+
+>>> config = DistilBertConfig()
+>>> print(config)
+DistilBertConfig {
+ "activation": "gelu",
+ "attention_dropout": 0.1,
+ "dim": 768,
+ "dropout": 0.1,
+ "hidden_dim": 3072,
+ "initializer_range": 0.02,
+ "max_position_embeddings": 512,
+ "model_type": "distilbert",
+ "n_heads": 12,
+ "n_layers": 6,
+ "pad_token_id": 0,
+ "qa_dropout": 0.1,
+ "seq_classif_dropout": 0.2,
+ "sinusoidal_pos_embds": false,
+ "transformers_version": "4.16.2",
+ "vocab_size": 30522
+}
+```
+
+[`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:
+
+- Tentar uma função de ativação diferente com o parùmetro `activation`.
+- Usar uma taxa de desistĂȘncia maior para as probabilidades de 'attention' com o parĂąmetro `attention_dropout`.
+
+```py
+>>> my_config = DistilBertConfig(activation="relu", attention_dropout=0.4)
+>>> print(my_config)
+DistilBertConfig {
+ "activation": "relu",
+ "attention_dropout": 0.4,
+ "dim": 768,
+ "dropout": 0.1,
+ "hidden_dim": 3072,
+ "initializer_range": 0.02,
+ "max_position_embeddings": 512,
+ "model_type": "distilbert",
+ "n_heads": 12,
+ "n_layers": 6,
+ "pad_token_id": 0,
+ "qa_dropout": 0.1,
+ "seq_classif_dropout": 0.2,
+ "sinusoidal_pos_embds": false,
+ "transformers_version": "4.16.2",
+ "vocab_size": 30522
+}
+```
+
+Atributos de um modelo pré-treinado podem ser modificados na função [`~PretrainedConfig.from_pretrained`]:
+
+```py
+>>> my_config = DistilBertConfig.from_pretrained("distilbert-base-uncased", activation="relu", attention_dropout=0.4)
+```
+
+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:
+
+```py
+>>> my_config.save_pretrained(save_directory="./your_model_save_path")
+```
+
+Para reusar o arquivo de configuraçÔes, carregue com [`~PretrainedConfig.from_pretrained`]:
+
+```py
+>>> my_config = DistilBertConfig.from_pretrained("./your_model_save_path/my_config.json")
+```
+
+
+
+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.
+
+
+
+## Modelo
+
+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/flax.linen.html#module). Isso significa que os modelos sĂŁo compatĂveis com cada respectivo uso de framework.
+
+
+
+Carregar seus atributos de configuração customizados em um modelo:
+
+```py
+>>> from transformers import DistilBertModel
+
+>>> my_config = DistilBertConfig.from_pretrained("./your_model_save_path/my_config.json")
+>>> model = DistilBertModel(my_config)
+```
+
+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.
+
+Criar um modelo pré-treinado com [`~PreTrainedModel.from_pretrained`]:
+
+```py
+>>> model = DistilBertModel.from_pretrained("distilbert-base-uncased")
+```
+
+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:
+
+```py
+>>> model = DistilBertModel.from_pretrained("distilbert-base-uncased", config=my_config)
+```
+
+
+Carregar os seus próprios atributos padrÔes de contiguração no modelo:
+
+```py
+>>> from transformers import TFDistilBertModel
+
+>>> my_config = DistilBertConfig.from_pretrained("./your_model_save_path/my_config.json")
+>>> tf_model = TFDistilBertModel(my_config)
+```
+
+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.
+
+Criar um modelo pré-treinado com [`~TFPreTrainedModel.from_pretrained`]:
+
+```py
+>>> tf_model = TFDistilBertModel.from_pretrained("distilbert-base-uncased")
+```
+
+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:
+
+```py
+>>> tf_model = TFDistilBertModel.from_pretrained("distilbert-base-uncased", config=my_config)
+```
+
+
+
+### Heads do modelo
+
+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).
+
+
+
+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.
+
+```py
+>>> from transformers import DistilBertForSequenceClassification
+
+>>> model = DistilBertForSequenceClassification.from_pretrained("distilbert-base-uncased")
+```
+
+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.
+
+```py
+>>> from transformers import DistilBertForQuestionAnswering
+
+>>> model = DistilBertForQuestionAnswering.from_pretrained("distilbert-base-uncased")
+```
+
+
+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.
+
+```py
+>>> from transformers import TFDistilBertForSequenceClassification
+
+>>> tf_model = TFDistilBertForSequenceClassification.from_pretrained("distilbert-base-uncased")
+```
+
+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.
+
+```py
+>>> from transformers import TFDistilBertForQuestionAnswering
+
+>>> tf_model = TFDistilBertForQuestionAnswering.from_pretrained("distilbert-base-uncased")
+```
+
+
+
+## Tokenizer
+
+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:
+
+- [`PreTrainedTokenizer`]: uma implementação em Python de um tokenizer.
+- [`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.
+
+Os dois tokenizers suporta métodos comuns como os de codificar e decodificar, adicionar novos tokens, e gerenciar tokens especiais.
+
+
+
+Nem todo modelo suporta um 'fast tokenizer'. De uma olhada aqui [table](index#supported-frameworks) pra checar se um modelo suporta 'fast tokenizer'.
+
+
+
+Se vocĂȘ treinou seu prĂłrpio tokenizer, vocĂȘ pode criar um a partir do seu arquivo *vocabulary*:
+
+```py
+>>> from transformers import DistilBertTokenizer
+
+>>> my_tokenizer = DistilBertTokenizer(vocab_file="my_vocab_file.txt", do_lower_case=False, padding_side="left")
+```
+
+Ă 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`]:
+
+```py
+>>> from transformers import DistilBertTokenizer
+
+>>> slow_tokenizer = DistilBertTokenizer.from_pretrained("distilbert-base-uncased")
+```
+
+Criando um 'fast tokenizer' com a classe [`DistilBertTokenizerFast`]:
+
+```py
+>>> from transformers import DistilBertTokenizerFast
+
+>>> fast_tokenizer = DistilBertTokenizerFast.from_pretrained("distilbert-base-uncased")
+```
+
+
+
+Pos padrĂŁo, [`AutoTokenizer`] tentarĂĄ carregar um 'fast tokenizer'. VocĂȘ pode disabilitar esse comportamento colocando `use_fast=False` no `from_pretrained`.
+
+
+
+## Extrator de features
+
+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.
+
+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:
+
+```py
+>>> from transformers import ViTFeatureExtractor
+
+>>> vit_extractor = ViTFeatureExtractor()
+>>> print(vit_extractor)
+ViTFeatureExtractor {
+ "do_normalize": true,
+ "do_resize": true,
+ "feature_extractor_type": "ViTFeatureExtractor",
+ "image_mean": [
+ 0.5,
+ 0.5,
+ 0.5
+ ],
+ "image_std": [
+ 0.5,
+ 0.5,
+ 0.5
+ ],
+ "resample": 2,
+ "size": 224
+}
+```
+
+
+
+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.
+
+
+
+Modifique qualquer parĂąmetro dentre os [`ViTFeatureExtractor`] para criar seu extrator de features customizado.
+
+```py
+>>> from transformers import ViTFeatureExtractor
+
+>>> my_vit_extractor = ViTFeatureExtractor(resample="PIL.Image.BOX", do_normalize=False, image_mean=[0.3, 0.3, 0.3])
+>>> print(my_vit_extractor)
+ViTFeatureExtractor {
+ "do_normalize": false,
+ "do_resize": true,
+ "feature_extractor_type": "ViTFeatureExtractor",
+ "image_mean": [
+ 0.3,
+ 0.3,
+ 0.3
+ ],
+ "image_std": [
+ 0.5,
+ 0.5,
+ 0.5
+ ],
+ "resample": "PIL.Image.BOX",
+ "size": 224
+}
+```
+
+Para entradas de ĂĄutio, vocĂȘ pode criar um [`Wav2Vec2FeatureExtractor`] e customizar os parĂąmetros de uma forma similar:
+
+```py
+>>> from transformers import Wav2Vec2FeatureExtractor
+
+>>> w2v2_extractor = Wav2Vec2FeatureExtractor()
+>>> print(w2v2_extractor)
+Wav2Vec2FeatureExtractor {
+ "do_normalize": true,
+ "feature_extractor_type": "Wav2Vec2FeatureExtractor",
+ "feature_size": 1,
+ "padding_side": "right",
+ "padding_value": 0.0,
+ "return_attention_mask": false,
+ "sampling_rate": 16000
+}
+```
+
+## Processor
+
+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.
+
+Crie um extrator de features para lidar com as entradas de ĂĄudio.
+
+```py
+>>> from transformers import Wav2Vec2FeatureExtractor
+
+>>> feature_extractor = Wav2Vec2FeatureExtractor(padding_value=1.0, do_normalize=True)
+```
+
+Crie um tokenizer para lidar com a entrada de textos:
+
+```py
+>>> from transformers import Wav2Vec2CTCTokenizer
+
+>>> tokenizer = Wav2Vec2CTCTokenizer(vocab_file="my_vocab_file.txt")
+```
+
+Combine o extrator de features e o tokenizer no [`Wav2Vec2Processor`]:
+
+```py
+>>> from transformers import Wav2Vec2Processor
+
+>>> processor = Wav2Vec2Processor(feature_extractor=feature_extractor, tokenizer=tokenizer)
+```
+
+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.
\ No newline at end of file
diff --git a/docs/source/pt/create_a_model.mdx b/docs/source/pt/create_a_model.mdx
deleted file mode 100644
index bde2b1b18770..000000000000
--- a/docs/source/pt/create_a_model.mdx
+++ /dev/null
@@ -1,355 +0,0 @@
-
-
-# Criar uma arquitetura customizada
-
-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:
-
-- Carregar e customizar a configuração de um modelo.
-- Criar a arquitetura de um modelo.
-- Criar um tokenizer rĂĄpido e devagar para textos.
-- Criar extrator de features para tarefas envolvendo audio e imagem.
-- Criar um processador para tarefas multimodais.
-
-## configuration
-
-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.
-
-DĂȘ uma olhada a mais em [DistilBERT](model_doc/distilbert) acessando [`DistilBertConfig`] para observar esses atributos:
-
-```py
->>> from transformers import DistilBertConfig
-
->>> config = DistilBertConfig()
->>> print(config)
-DistilBertConfig {
- "activation": "gelu",
- "attention_dropout": 0.1,
- "dim": 768,
- "dropout": 0.1,
- "hidden_dim": 3072,
- "initializer_range": 0.02,
- "max_position_embeddings": 512,
- "model_type": "distilbert",
- "n_heads": 12,
- "n_layers": 6,
- "pad_token_id": 0,
- "qa_dropout": 0.1,
- "seq_classif_dropout": 0.2,
- "sinusoidal_pos_embds": false,
- "transformers_version": "4.16.2",
- "vocab_size": 30522
-}
-```
-
-[`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:
-
-- Tentar uma função de ativação diferente com o parùmetro `activation`.
-- Usar uma taxa de desistĂȘncia maior para as probabilidades de 'attention' com o parĂąmetro `attention_dropout`.
-
-```py
->>> my_config = DistilBertConfig(activation="relu", attention_dropout=0.4)
->>> print(my_config)
-DistilBertConfig {
- "activation": "relu",
- "attention_dropout": 0.4,
- "dim": 768,
- "dropout": 0.1,
- "hidden_dim": 3072,
- "initializer_range": 0.02,
- "max_position_embeddings": 512,
- "model_type": "distilbert",
- "n_heads": 12,
- "n_layers": 6,
- "pad_token_id": 0,
- "qa_dropout": 0.1,
- "seq_classif_dropout": 0.2,
- "sinusoidal_pos_embds": false,
- "transformers_version": "4.16.2",
- "vocab_size": 30522
-}
-```
-
-Atributos de um modelo pré-treinado podem ser modificados na função [`~PretrainedConfig.from_pretrained`]:
-
-```py
->>> my_config = DistilBertConfig.from_pretrained("distilbert-base-uncased", activation="relu", attention_dropout=0.4)
-```
-
-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:
-
-```py
->>> my_config.save_pretrained(save_directory="./your_model_save_path")
-```
-
-Para reusar o arquivo de configuraçÔes, carregue com [`~PretrainedConfig.from_pretrained`]:
-
-```py
->>> my_config = DistilBertConfig.from_pretrained("./your_model_save_path/my_config.json")
-```
-
-
-
-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.
-
-
-
-## Modelo
-
-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/flax.linen.html#module). Isso significa que os modelos sĂŁo compatĂveis com cada respectivo uso de framework.
-
-
-
-Carregar seus atributos de configuração customizados em um modelo:
-
-```py
->>> from transformers import DistilBertModel
-
->>> my_config = DistilBertConfig.from_pretrained("./your_model_save_path/my_config.json")
->>> model = DistilBertModel(my_config)
-```
-
-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.
-
-Criar um modelo pré-treinado com [`~PreTrainedModel.from_pretrained`]:
-
-```py
->>> model = DistilBertModel.from_pretrained("distilbert-base-uncased")
-```
-
-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:
-
-```py
->>> model = DistilBertModel.from_pretrained("distilbert-base-uncased", config=my_config)
-```
-
-
-Carregar os seus próprios atributos padrÔes de contiguração no modelo:
-
-```py
->>> from transformers import TFDistilBertModel
-
->>> my_config = DistilBertConfig.from_pretrained("./your_model_save_path/my_config.json")
->>> tf_model = TFDistilBertModel(my_config)
-```
-
-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.
-
-Criar um modelo pré-treinado com [`~TFPreTrainedModel.from_pretrained`]:
-
-```py
->>> tf_model = TFDistilBertModel.from_pretrained("distilbert-base-uncased")
-```
-
-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:
-
-```py
->>> tf_model = TFDistilBertModel.from_pretrained("distilbert-base-uncased", config=my_config)
-```
-
-
-
-### Heads do modelo
-
-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).
-
-
-
-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.
-
-```py
->>> from transformers import DistilBertForSequenceClassification
-
->>> model = DistilBertForSequenceClassification.from_pretrained("distilbert-base-uncased")
-```
-
-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.
-
-```py
->>> from transformers import DistilBertForQuestionAnswering
-
->>> model = DistilBertForQuestionAnswering.from_pretrained("distilbert-base-uncased")
-```
-
-
-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.
-
-```py
->>> from transformers import TFDistilBertForSequenceClassification
-
->>> tf_model = TFDistilBertForSequenceClassification.from_pretrained("distilbert-base-uncased")
-```
-
-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.
-
-```py
->>> from transformers import TFDistilBertForQuestionAnswering
-
->>> tf_model = TFDistilBertForQuestionAnswering.from_pretrained("distilbert-base-uncased")
-```
-
-
-
-## Tokenizer
-
-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:
-
-- [`PreTrainedTokenizer`]: uma implementação em Python de um tokenizer.
-- [`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.
-
-Os dois tokenizers suporta métodos comuns como os de codificar e decodificar, adicionar novos tokens, e gerenciar tokens especiais.
-
-
-
-Nem todo modelo suporta um 'fast tokenizer'. De uma olhada aqui [table](index#supported-frameworks) pra checar se um modelo suporta 'fast tokenizer'.
-
-
-
-Se vocĂȘ treinou seu prĂłrpio tokenizer, vocĂȘ pode criar um a partir do seu arquivo *vocabulary*:
-
-```py
->>> from transformers import DistilBertTokenizer
-
->>> my_tokenizer = DistilBertTokenizer(vocab_file="my_vocab_file.txt", do_lower_case=False, padding_side="left")
-```
-
-Ă 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`]:
-
-```py
->>> from transformers import DistilBertTokenizer
-
->>> slow_tokenizer = DistilBertTokenizer.from_pretrained("distilbert-base-uncased")
-```
-
-Criando um 'fast tokenizer' com a classe [`DistilBertTokenizerFast`]:
-
-```py
->>> from transformers import DistilBertTokenizerFast
-
->>> fast_tokenizer = DistilBertTokenizerFast.from_pretrained("distilbert-base-uncased")
-```
-
-
-
-Pos padrĂŁo, [`AutoTokenizer`] tentarĂĄ carregar um 'fast tokenizer'. VocĂȘ pode disabilitar esse comportamento colocando `use_fast=False` no `from_pretrained`.
-
-
-
-## Extrator de features
-
-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.
-
-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:
-
-```py
->>> from transformers import ViTFeatureExtractor
-
->>> vit_extractor = ViTFeatureExtractor()
->>> print(vit_extractor)
-ViTFeatureExtractor {
- "do_normalize": true,
- "do_resize": true,
- "feature_extractor_type": "ViTFeatureExtractor",
- "image_mean": [
- 0.5,
- 0.5,
- 0.5
- ],
- "image_std": [
- 0.5,
- 0.5,
- 0.5
- ],
- "resample": 2,
- "size": 224
-}
-```
-
-
-
-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.
-
-
-
-Modifique qualquer parĂąmetro dentre os [`ViTFeatureExtractor`] para criar seu extrator de features customizado.
-
-```py
->>> from transformers import ViTFeatureExtractor
-
->>> my_vit_extractor = ViTFeatureExtractor(resample="PIL.Image.BOX", do_normalize=False, image_mean=[0.3, 0.3, 0.3])
->>> print(my_vit_extractor)
-ViTFeatureExtractor {
- "do_normalize": false,
- "do_resize": true,
- "feature_extractor_type": "ViTFeatureExtractor",
- "image_mean": [
- 0.3,
- 0.3,
- 0.3
- ],
- "image_std": [
- 0.5,
- 0.5,
- 0.5
- ],
- "resample": "PIL.Image.BOX",
- "size": 224
-}
-```
-
-Para entradas de ĂĄutio, vocĂȘ pode criar um [`Wav2Vec2FeatureExtractor`] e customizar os parĂąmetros de uma forma similar:
-
-```py
->>> from transformers import Wav2Vec2FeatureExtractor
-
->>> w2v2_extractor = Wav2Vec2FeatureExtractor()
->>> print(w2v2_extractor)
-Wav2Vec2FeatureExtractor {
- "do_normalize": true,
- "feature_extractor_type": "Wav2Vec2FeatureExtractor",
- "feature_size": 1,
- "padding_side": "right",
- "padding_value": 0.0,
- "return_attention_mask": false,
- "sampling_rate": 16000
-}
-```
-
-## Processor
-
-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.
-
-Crie um extrator de features para lidar com as entradas de ĂĄudio.
-
-```py
->>> from transformers import Wav2Vec2FeatureExtractor
-
->>> feature_extractor = Wav2Vec2FeatureExtractor(padding_value=1.0, do_normalize=True)
-```
-
-Crie um tokenizer para lidar com a entrada de textos:
-
-```py
->>> from transformers import Wav2Vec2CTCTokenizer
-
->>> tokenizer = Wav2Vec2CTCTokenizer(vocab_file="my_vocab_file.txt")
-```
-
-Combine o extrator de features e o tokenizer no [`Wav2Vec2Processor`]:
-
-```py
->>> from transformers import Wav2Vec2Processor
-
->>> processor = Wav2Vec2Processor(feature_extractor=feature_extractor, tokenizer=tokenizer)
-```
-
-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.
\ No newline at end of file
diff --git a/docs/source/pt/custom_models.md b/docs/source/pt/custom_models.md
new file mode 100644
index 000000000000..70c56913a383
--- /dev/null
+++ b/docs/source/pt/custom_models.md
@@ -0,0 +1,358 @@
+
+
+# Compartilhando modelos customizados
+
+A biblioteca đ€ Transformers foi projetada para ser facilmente extensĂvel. Cada modelo Ă© totalmente codificado em uma determinada subpasta
+do repositĂłrio sem abstração, para que vocĂȘ possa copiar facilmente um arquivo de modelagem e ajustĂĄ-lo Ă s suas necessidades.
+
+Se vocĂȘ estiver escrevendo um modelo totalmente novo, pode ser mais fĂĄcil começar do zero. Neste tutorial, mostraremos
+como escrever um modelo customizado e sua configuração para que possa ser usado com Transformers, e como vocĂȘ pode compartilhĂĄ-lo
+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.
+
+Ilustraremos tudo isso em um modelo ResNet, envolvendo a classe ResNet do
+[biblioteca timm](https://github.com/rwightman/pytorch-image-models) em um [`PreTrainedModel`].
+
+## Escrevendo uma configuração customizada
+
+Antes de mergulharmos no modelo, vamos primeiro escrever sua configuração. A configuração de um modelo é um objeto que
+terå todas as informaçÔes necessårias para construir o modelo. Como veremos na próxima seção, o modelo só pode
+ter um `config` para ser inicializado, entĂŁo realmente precisamos que esse objeto seja o mais completo possĂvel.
+
+Em nosso exemplo, pegaremos alguns argumentos da classe ResNet que podemos querer ajustar. Diferentes
+configuraçÔes nos darĂĄ os diferentes tipos de ResNets que sĂŁo possĂveis. Em seguida, apenas armazenamos esses argumentos,
+apĂłs verificar a validade de alguns deles.
+
+```python
+from transformers import PretrainedConfig
+from typing import List
+
+
+class ResnetConfig(PretrainedConfig):
+ model_type = "resnet"
+
+ def __init__(
+ self,
+ block_type="bottleneck",
+ layers: List[int] = [3, 4, 6, 3],
+ num_classes: int = 1000,
+ input_channels: int = 3,
+ cardinality: int = 1,
+ base_width: int = 64,
+ stem_width: int = 64,
+ stem_type: str = "",
+ avg_down: bool = False,
+ **kwargs,
+ ):
+ if block_type not in ["basic", "bottleneck"]:
+ raise ValueError(f"`block_type` must be 'basic' or bottleneck', got {block_type}.")
+ if stem_type not in ["", "deep", "deep-tiered"]:
+ raise ValueError(f"`stem_type` must be '', 'deep' or 'deep-tiered', got {stem_type}.")
+
+ self.block_type = block_type
+ self.layers = layers
+ self.num_classes = num_classes
+ self.input_channels = input_channels
+ self.cardinality = cardinality
+ self.base_width = base_width
+ self.stem_width = stem_width
+ self.stem_type = stem_type
+ self.avg_down = avg_down
+ super().__init__(**kwargs)
+```
+
+As trĂȘs coisas importantes a serem lembradas ao escrever sua prĂłpria configuração sĂŁo:
+- vocĂȘ tem que herdar de `PretrainedConfig`,
+- o `__init__` do seu `PretrainedConfig` deve aceitar quaisquer kwargs,
+- esses `kwargs` precisam ser passados para a superclasse `__init__`.
+
+A herança Ă© para garantir que vocĂȘ obtenha todas as funcionalidades da biblioteca đ€ Transformers, enquanto as outras duas
+restriçÔes vĂȘm do fato de um `PretrainedConfig` ter mais campos do que os que vocĂȘ estĂĄ configurando. Ao recarregar um
+config com o método `from_pretrained`, esses campos precisam ser aceitos pelo seu config e então enviados para a
+superclasse.
+
+Definir um `model_type` para sua configuração (aqui `model_type="resnet"`) nĂŁo Ă© obrigatĂłrio, a menos que vocĂȘ queira
+registrar seu modelo com as classes automĂĄticas (veja a Ășltima seção).
+
+Com isso feito, vocĂȘ pode facilmente criar e salvar sua configuração como faria com qualquer outra configuração de modelo da
+biblioteca. Aqui estå como podemos criar uma configuração resnet50d e salvå-la:
+
+```py
+resnet50d_config = ResnetConfig(block_type="bottleneck", stem_width=32, stem_type="deep", avg_down=True)
+resnet50d_config.save_pretrained("custom-resnet")
+```
+
+Isso salvarĂĄ um arquivo chamado `config.json` dentro da pasta `custom-resnet`. VocĂȘ pode entĂŁo recarregar sua configuração com o
+método `from_pretrained`:
+
+```py
+resnet50d_config = ResnetConfig.from_pretrained("custom-resnet")
+```
+
+VocĂȘ tambĂ©m pode usar qualquer outro mĂ©todo da classe [`PretrainedConfig`], como [`~PretrainedConfig.push_to_hub`] para
+carregar diretamente sua configuração para o Hub.
+
+## Escrevendo um modelo customizado
+
+Agora que temos nossa configuração ResNet, podemos continuar escrevendo o modelo. Na verdade, escreveremos dois: um que
+extrai os recursos ocultos de um lote de imagens (como [`BertModel`]) e um que é adequado para classificação de imagem
+(como [`BertForSequenceClassification`]).
+
+Como mencionamos antes, escreveremos apenas um wrapper solto do modelo para mantĂȘ-lo simples para este exemplo. A Ășnica
+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
+modelo é definido a partir da configuração passando tudo para a classe `ResNet`:
+
+```py
+from transformers import PreTrainedModel
+from timm.models.resnet import BasicBlock, Bottleneck, ResNet
+from .configuration_resnet import ResnetConfig
+
+
+BLOCK_MAPPING = {"basic": BasicBlock, "bottleneck": Bottleneck}
+
+
+class ResnetModel(PreTrainedModel):
+ config_class = ResnetConfig
+
+ def __init__(self, config):
+ super().__init__(config)
+ block_layer = BLOCK_MAPPING[config.block_type]
+ self.model = ResNet(
+ block_layer,
+ config.layers,
+ num_classes=config.num_classes,
+ in_chans=config.input_channels,
+ cardinality=config.cardinality,
+ base_width=config.base_width,
+ stem_width=config.stem_width,
+ stem_type=config.stem_type,
+ avg_down=config.avg_down,
+ )
+
+ def forward(self, tensor):
+ return self.model.forward_features(tensor)
+```
+
+Para o modelo que irå classificar as imagens, vamos apenas alterar o método forward:
+
+```py
+import torch
+
+
+class ResnetModelForImageClassification(PreTrainedModel):
+ config_class = ResnetConfig
+
+ def __init__(self, config):
+ super().__init__(config)
+ block_layer = BLOCK_MAPPING[config.block_type]
+ self.model = ResNet(
+ block_layer,
+ config.layers,
+ num_classes=config.num_classes,
+ in_chans=config.input_channels,
+ cardinality=config.cardinality,
+ base_width=config.base_width,
+ stem_width=config.stem_width,
+ stem_type=config.stem_type,
+ avg_down=config.avg_down,
+ )
+
+ def forward(self, tensor, labels=None):
+ logits = self.model(tensor)
+ if labels is not None:
+ loss = torch.nn.cross_entropy(logits, labels)
+ return {"loss": loss, "logits": logits}
+ return {"logits": logits}
+```
+
+Em ambos os casos, observe como herdamos de `PreTrainedModel` e chamamos a inicialização da superclasse com o `config`
+(um pouco parecido quando vocĂȘ escreve um `torch.nn.Module`). A linha que define o `config_class` nĂŁo Ă© obrigatĂłria, a menos que
+vocĂȘ deseje registrar seu modelo com as classes automĂĄticas (consulte a Ășltima seção).
+
+
+
+Se o seu modelo for muito semelhante a um modelo dentro da biblioteca, vocĂȘ poderĂĄ reutilizar a mesma configuração desse modelo.
+
+
+
+VocĂȘ pode fazer com que seu modelo retorne o que vocĂȘ quiser,porĂ©m retornando um dicionĂĄrio como fizemos para
+`ResnetModelForImageClassification`, com a função de perda incluĂda quando os rĂłtulos sĂŁo passados, vai tornar seu modelo diretamente
+utilizĂĄvel dentro da classe [`Trainer`]. VocĂȘ pode usar outro formato de saĂda, desde que esteja planejando usar seu prĂłprio
+laço de treinamento ou outra biblioteca para treinamento.
+
+Agora que temos nossa classe do modelo, vamos criar uma:
+
+```py
+resnet50d = ResnetModelForImageClassification(resnet50d_config)
+```
+
+Novamente, vocĂȘ pode usar qualquer um dos mĂ©todos do [`PreTrainedModel`], como [`~PreTrainedModel.save_pretrained`] ou
+[`~PreTrainedModel.push_to_hub`]. Usaremos o segundo na próxima seção e veremos como enviar os pesos e
+o código do nosso modelo. Mas primeiro, vamos carregar alguns pesos pré-treinados dentro do nosso modelo.
+
+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,
+usaremos a versão pré-treinada do resnet50d. Como nosso modelo é apenas um wrapper em torno dele, serå
+fĂĄcil de transferir esses pesos:
+
+```py
+import timm
+
+pretrained_model = timm.create_model("resnet50d", pretrained=True)
+resnet50d.model.load_state_dict(pretrained_model.state_dict())
+```
+
+Agora vamos ver como ter certeza de que quando fazemos [`~PreTrainedModel.save_pretrained`] ou [`~PreTrainedModel.push_to_hub`], o
+cĂłdigo do modelo Ă© salvo.
+
+## Enviando o cĂłdigo para o Hub
+
+
+
+Esta API é experimental e pode ter algumas pequenas alteraçÔes nas próximas versÔes.
+
+
+
+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
+desde que todos os arquivos estejam no mesmo diretĂłrio (ainda nĂŁo suportamos submĂłdulos para este recurso). Para o nosso exemplo,
+vamos definir um arquivo `modeling_resnet.py` e um arquivo `configuration_resnet.py` em uma pasta no
+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
+contém o código do `ResnetModel` e `ResnetModelForImageClassification`.
+
+```
+.
+âââ resnet_model
+ âââ __init__.py
+ âââ configuration_resnet.py
+ âââ modeling_resnet.py
+```
+
+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.
+
+
+
+Se estiver copiando arquivos de modelagem da biblioteca, vocĂȘ precisarĂĄ substituir todas as importaçÔes relativas na parte superior do arquivo
+para importar do pacote `transformers`.
+
+
+
+Observe que vocĂȘ pode reutilizar (ou subclasse) uma configuração/modelo existente.
+
+Para compartilhar seu modelo com a comunidade, siga estas etapas: primeiro importe o modelo ResNet e a configuração do
+arquivos criados:
+
+```py
+from resnet_model.configuration_resnet import ResnetConfig
+from resnet_model.modeling_resnet import ResnetModel, ResnetModelForImageClassification
+```
+
+EntĂŁo vocĂȘ tem que dizer Ă biblioteca que deseja copiar os arquivos de cĂłdigo desses objetos ao usar o `save_pretrained`
+e registrĂĄ-los corretamente com uma determinada classe automĂĄticas (especialmente para modelos), basta executar:
+
+```py
+ResnetConfig.register_for_auto_class()
+ResnetModel.register_for_auto_class("AutoModel")
+ResnetModelForImageClassification.register_for_auto_class("AutoModelForImageClassification")
+```
+
+Observe que não hå necessidade de especificar uma classe automåtica para a configuração (hå apenas uma classe automåtica,
+[`AutoConfig`]), mas Ă© diferente para os modelos. Seu modelo customizado pode ser adequado para muitas tarefas diferentes, entĂŁo vocĂȘ
+tem que especificar qual das classes automĂĄticas Ă© a correta para o seu modelo.
+
+Em seguida, vamos criar a configuração e os modelos como fizemos antes:
+
+```py
+resnet50d_config = ResnetConfig(block_type="bottleneck", stem_width=32, stem_type="deep", avg_down=True)
+resnet50d = ResnetModelForImageClassification(resnet50d_config)
+
+pretrained_model = timm.create_model("resnet50d", pretrained=True)
+resnet50d.model.load_state_dict(pretrained_model.state_dict())
+```
+
+Agora para enviar o modelo para o Hub, certifique-se de estar logado. Ou execute no seu terminal:
+
+```bash
+huggingface-cli login
+```
+
+ou a partir do notebook:
+
+```py
+from huggingface_hub import notebook_login
+
+notebook_login()
+```
+
+VocĂȘ pode entĂŁo enviar para seu prĂłprio namespace (ou uma organização da qual vocĂȘ Ă© membro) assim:
+
+
+```py
+resnet50d.push_to_hub("custom-resnet50d")
+```
+
+Além dos pesos do modelo e da configuração no formato json, isso também copiou o modelo e
+configuração `.py` na pasta `custom-resnet50d` e carregou o resultado para o Hub. VocĂȘ pode conferir o resultado
+neste [repositĂłrio de modelos](https://huggingface.co/sgugger/custom-resnet50d).
+
+Consulte o [tutorial de compartilhamento](model_sharing) para obter mais informaçÔes sobre o método push_to_hub.
+
+## Usando um modelo com cĂłdigo customizado
+
+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
+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
+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
+um modelo com cĂłdigo customizado:
+
+```py
+from transformers import AutoModelForImageClassification
+
+model = AutoModelForImageClassification.from_pretrained("sgugger/custom-resnet50d", trust_remote_code=True)
+```
+
+Também é fortemente recomendado passar um hash de confirmação como uma `revisão` para garantir que o autor dos modelos não
+atualize o cĂłdigo com novas linhas maliciosas (a menos que vocĂȘ confie totalmente nos autores dos modelos).
+
+
+```py
+commit_hash = "ed94a7c6247d8aedce4647f00f20de6875b5b292"
+model = AutoModelForImageClassification.from_pretrained(
+ "sgugger/custom-resnet50d", trust_remote_code=True, revision=commit_hash
+)
+```
+
+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
+hash de qualquer commit.
+
+## Registrando um modelo com cĂłdigo customizado para as classes automĂĄticas
+
+Se vocĂȘ estiver escrevendo uma biblioteca que estende đ€ Transformers, talvez queira estender as classes automĂĄticas para incluir seus prĂłprios
+modelos. Isso Ă© diferente de enviar o cĂłdigo para o Hub no sentido de que os usuĂĄrios precisarĂŁo importar sua biblioteca para
+obter os modelos customizados (ao contrĂĄrio de baixar automaticamente o cĂłdigo do modelo do Hub).
+
+Desde que sua configuração tenha um atributo `model_type` diferente dos tipos de modelo existentes e que as classes do seu modelo
+tenha os atributos `config_class` corretos, vocĂȘ pode simplesmente adicionĂĄ-los Ă s classes automĂĄticas assim:
+
+```py
+from transformers import AutoConfig, AutoModel, AutoModelForImageClassification
+
+AutoConfig.register("resnet", ResnetConfig)
+AutoModel.register(ResnetConfig, ResnetModel)
+AutoModelForImageClassification.register(ResnetConfig, ResnetModelForImageClassification)
+```
+
+Observe que o primeiro argumento usado ao registrar sua configuração customizada para [`AutoConfig`] precisa corresponder ao `model_type`
+de sua configuração customizada. E o primeiro argumento usado ao registrar seus modelos customizados, para qualquer necessidade de classe de modelo automåtico
+deve corresponder ao `config_class` desses modelos.
+
diff --git a/docs/source/pt/custom_models.mdx b/docs/source/pt/custom_models.mdx
deleted file mode 100644
index 59484dcc35eb..000000000000
--- a/docs/source/pt/custom_models.mdx
+++ /dev/null
@@ -1,354 +0,0 @@
-
-
-# Compartilhando modelos customizados
-
-A biblioteca đ€ Transformers foi projetada para ser facilmente extensĂvel. Cada modelo Ă© totalmente codificado em uma determinada subpasta
-do repositĂłrio sem abstração, para que vocĂȘ possa copiar facilmente um arquivo de modelagem e ajustĂĄ-lo Ă s suas necessidades.
-
-Se vocĂȘ estiver escrevendo um modelo totalmente novo, pode ser mais fĂĄcil começar do zero. Neste tutorial, mostraremos
-como escrever um modelo customizado e sua configuração para que possa ser usado com Transformers, e como vocĂȘ pode compartilhĂĄ-lo
-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.
-
-Ilustraremos tudo isso em um modelo ResNet, envolvendo a classe ResNet do
-[biblioteca timm](https://github.com/rwightman/pytorch-image-models) em um [`PreTrainedModel`].
-
-## Escrevendo uma configuração customizada
-
-Antes de mergulharmos no modelo, vamos primeiro escrever sua configuração. A configuração de um modelo é um objeto que
-terå todas as informaçÔes necessårias para construir o modelo. Como veremos na próxima seção, o modelo só pode
-ter um `config` para ser inicializado, entĂŁo realmente precisamos que esse objeto seja o mais completo possĂvel.
-
-Em nosso exemplo, pegaremos alguns argumentos da classe ResNet que podemos querer ajustar. Diferentes
-configuraçÔes nos darĂĄ os diferentes tipos de ResNets que sĂŁo possĂveis. Em seguida, apenas armazenamos esses argumentos,
-apĂłs verificar a validade de alguns deles.
-
-```python
-from transformers import PretrainedConfig
-from typing import List
-
-
-class ResnetConfig(PretrainedConfig):
- model_type = "resnet"
-
- def __init__(
- self,
- block_type="bottleneck",
- layers: List[int] = [3, 4, 6, 3],
- num_classes: int = 1000,
- input_channels: int = 3,
- cardinality: int = 1,
- base_width: int = 64,
- stem_width: int = 64,
- stem_type: str = "",
- avg_down: bool = False,
- **kwargs,
- ):
- if block_type not in ["basic", "bottleneck"]:
- raise ValueError(f"`block_type` must be 'basic' or bottleneck', got {block_type}.")
- if stem_type not in ["", "deep", "deep-tiered"]:
- raise ValueError(f"`stem_type` must be '', 'deep' or 'deep-tiered', got {stem_type}.")
-
- self.block_type = block_type
- self.layers = layers
- self.num_classes = num_classes
- self.input_channels = input_channels
- self.cardinality = cardinality
- self.base_width = base_width
- self.stem_width = stem_width
- self.stem_type = stem_type
- self.avg_down = avg_down
- super().__init__(**kwargs)
-```
-
-As trĂȘs coisas importantes a serem lembradas ao escrever sua prĂłpria configuração sĂŁo:
-- vocĂȘ tem que herdar de `PretrainedConfig`,
-- o `__init__` do seu `PretrainedConfig` deve aceitar quaisquer kwargs,
-- esses `kwargs` precisam ser passados para a superclasse `__init__`.
-
-A herança Ă© para garantir que vocĂȘ obtenha todas as funcionalidades da biblioteca đ€ Transformers, enquanto as outras duas
-restriçÔes vĂȘm do fato de um `PretrainedConfig` ter mais campos do que os que vocĂȘ estĂĄ configurando. Ao recarregar um
-config com o método `from_pretrained`, esses campos precisam ser aceitos pelo seu config e então enviados para a
-superclasse.
-
-Definir um `model_type` para sua configuração (aqui `model_type="resnet"`) nĂŁo Ă© obrigatĂłrio, a menos que vocĂȘ queira
-registrar seu modelo com as classes automĂĄticas (veja a Ășltima seção).
-
-Com isso feito, vocĂȘ pode facilmente criar e salvar sua configuração como faria com qualquer outra configuração de modelo da
-biblioteca. Aqui estå como podemos criar uma configuração resnet50d e salvå-la:
-
-```py
-resnet50d_config = ResnetConfig(block_type="bottleneck", stem_width=32, stem_type="deep", avg_down=True)
-resnet50d_config.save_pretrained("custom-resnet")
-```
-
-Isso salvarĂĄ um arquivo chamado `config.json` dentro da pasta `custom-resnet`. VocĂȘ pode entĂŁo recarregar sua configuração com o
-método `from_pretrained`:
-
-```py
-resnet50d_config = ResnetConfig.from_pretrained("custom-resnet")
-```
-
-VocĂȘ tambĂ©m pode usar qualquer outro mĂ©todo da classe [`PretrainedConfig`], como [`~PretrainedConfig.push_to_hub`] para
-carregar diretamente sua configuração para o Hub.
-
-## Escrevendo um modelo customizado
-
-Agora que temos nossa configuração ResNet, podemos continuar escrevendo o modelo. Na verdade, escreveremos dois: um que
-extrai os recursos ocultos de um lote de imagens (como [`BertModel`]) e um que é adequado para classificação de imagem
-(como [`BertForSequenceClassification`]).
-
-Como mencionamos antes, escreveremos apenas um wrapper solto do modelo para mantĂȘ-lo simples para este exemplo. A Ășnica
-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
-modelo é definido a partir da configuração passando tudo para a classe `ResNet`:
-
-```py
-from transformers import PreTrainedModel
-from timm.models.resnet import BasicBlock, Bottleneck, ResNet
-from .configuration_resnet import ResnetConfig
-
-
-BLOCK_MAPPING = {"basic": BasicBlock, "bottleneck": Bottleneck}
-
-
-class ResnetModel(PreTrainedModel):
- config_class = ResnetConfig
-
- def __init__(self, config):
- super().__init__(config)
- block_layer = BLOCK_MAPPING[config.block_type]
- self.model = ResNet(
- block_layer,
- config.layers,
- num_classes=config.num_classes,
- in_chans=config.input_channels,
- cardinality=config.cardinality,
- base_width=config.base_width,
- stem_width=config.stem_width,
- stem_type=config.stem_type,
- avg_down=config.avg_down,
- )
-
- def forward(self, tensor):
- return self.model.forward_features(tensor)
-```
-
-Para o modelo que irå classificar as imagens, vamos apenas alterar o método forward:
-
-```py
-import torch
-
-
-class ResnetModelForImageClassification(PreTrainedModel):
- config_class = ResnetConfig
-
- def __init__(self, config):
- super().__init__(config)
- block_layer = BLOCK_MAPPING[config.block_type]
- self.model = ResNet(
- block_layer,
- config.layers,
- num_classes=config.num_classes,
- in_chans=config.input_channels,
- cardinality=config.cardinality,
- base_width=config.base_width,
- stem_width=config.stem_width,
- stem_type=config.stem_type,
- avg_down=config.avg_down,
- )
-
- def forward(self, tensor, labels=None):
- logits = self.model(tensor)
- if labels is not None:
- loss = torch.nn.cross_entropy(logits, labels)
- return {"loss": loss, "logits": logits}
- return {"logits": logits}
-```
-
-Em ambos os casos, observe como herdamos de `PreTrainedModel` e chamamos a inicialização da superclasse com o `config`
-(um pouco parecido quando vocĂȘ escreve um `torch.nn.Module`). A linha que define o `config_class` nĂŁo Ă© obrigatĂłria, a menos que
-vocĂȘ deseje registrar seu modelo com as classes automĂĄticas (consulte a Ășltima seção).
-
-
-
-Se o seu modelo for muito semelhante a um modelo dentro da biblioteca, vocĂȘ poderĂĄ reutilizar a mesma configuração desse modelo.
-
-
-
-VocĂȘ pode fazer com que seu modelo retorne o que vocĂȘ quiser,porĂ©m retornando um dicionĂĄrio como fizemos para
-`ResnetModelForImageClassification`, com a função de perda incluĂda quando os rĂłtulos sĂŁo passados, vai tornar seu modelo diretamente
-utilizĂĄvel dentro da classe [`Trainer`]. VocĂȘ pode usar outro formato de saĂda, desde que esteja planejando usar seu prĂłprio
-laço de treinamento ou outra biblioteca para treinamento.
-
-Agora que temos nossa classe do modelo, vamos criar uma:
-
-```py
-resnet50d = ResnetModelForImageClassification(resnet50d_config)
-```
-
-Novamente, vocĂȘ pode usar qualquer um dos mĂ©todos do [`PreTrainedModel`], como [`~PreTrainedModel.save_pretrained`] ou
-[`~PreTrainedModel.push_to_hub`]. Usaremos o segundo na próxima seção e veremos como enviar os pesos e
-o código do nosso modelo. Mas primeiro, vamos carregar alguns pesos pré-treinados dentro do nosso modelo.
-
-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,
-usaremos a versão pré-treinada do resnet50d. Como nosso modelo é apenas um wrapper em torno dele, serå
-fĂĄcil de transferir esses pesos:
-
-```py
-import timm
-
-pretrained_model = timm.create_model("resnet50d", pretrained=True)
-resnet50d.model.load_state_dict(pretrained_model.state_dict())
-```
-
-Agora vamos ver como ter certeza de que quando fazemos [`~PreTrainedModel.save_pretrained`] ou [`~PreTrainedModel.push_to_hub`], o
-cĂłdigo do modelo Ă© salvo.
-
-## Enviando o cĂłdigo para o Hub
-
-
-
-Esta API é experimental e pode ter algumas pequenas alteraçÔes nas próximas versÔes.
-
-
-
-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
-desde que todos os arquivos estejam no mesmo diretĂłrio (ainda nĂŁo suportamos submĂłdulos para este recurso). Para o nosso exemplo,
-vamos definir um arquivo `modeling_resnet.py` e um arquivo `configuration_resnet.py` em uma pasta no
-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
-contém o código do `ResnetModel` e `ResnetModelForImageClassification`.
-
-```
-.
-âââ resnet_model
- âââ __init__.py
- âââ configuration_resnet.py
- âââ modeling_resnet.py
-```
-
-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.
-
-
-
-Se estiver copiando arquivos de modelagem da biblioteca, vocĂȘ precisarĂĄ substituir todas as importaçÔes relativas na parte superior do arquivo
-para importar do pacote `transformers`.
-
-
-
-Observe que vocĂȘ pode reutilizar (ou subclasse) uma configuração/modelo existente.
-
-Para compartilhar seu modelo com a comunidade, siga estas etapas: primeiro importe o modelo ResNet e a configuração do
-arquivos criados:
-
-```py
-from resnet_model.configuration_resnet import ResnetConfig
-from resnet_model.modeling_resnet import ResnetModel, ResnetModelForImageClassification
-```
-
-EntĂŁo vocĂȘ tem que dizer Ă biblioteca que deseja copiar os arquivos de cĂłdigo desses objetos ao usar o `save_pretrained`
-e registrĂĄ-los corretamente com uma determinada classe automĂĄticas (especialmente para modelos), basta executar:
-
-```py
-ResnetConfig.register_for_auto_class()
-ResnetModel.register_for_auto_class("AutoModel")
-ResnetModelForImageClassification.register_for_auto_class("AutoModelForImageClassification")
-```
-
-Observe que não hå necessidade de especificar uma classe automåtica para a configuração (hå apenas uma classe automåtica,
-[`AutoConfig`]), mas Ă© diferente para os modelos. Seu modelo customizado pode ser adequado para muitas tarefas diferentes, entĂŁo vocĂȘ
-tem que especificar qual das classes automĂĄticas Ă© a correta para o seu modelo.
-
-Em seguida, vamos criar a configuração e os modelos como fizemos antes:
-
-```py
-resnet50d_config = ResnetConfig(block_type="bottleneck", stem_width=32, stem_type="deep", avg_down=True)
-resnet50d = ResnetModelForImageClassification(resnet50d_config)
-
-pretrained_model = timm.create_model("resnet50d", pretrained=True)
-resnet50d.model.load_state_dict(pretrained_model.state_dict())
-```
-
-Agora para enviar o modelo para o Hub, certifique-se de estar logado. Ou execute no seu terminal:
-
-```bash
-huggingface-cli login
-```
-
-ou a partir do notebook:
-
-```py
-from huggingface_hub import notebook_login
-
-notebook_login()
-```
-
-VocĂȘ pode entĂŁo enviar para seu prĂłprio namespace (ou uma organização da qual vocĂȘ Ă© membro) assim:
-
-
-```py
-resnet50d.push_to_hub("custom-resnet50d")
-```
-
-Além dos pesos do modelo e da configuração no formato json, isso também copiou o modelo e
-configuração `.py` na pasta `custom-resnet50d` e carregou o resultado para o Hub. VocĂȘ pode conferir o resultado
-neste [repositĂłrio de modelos](https://huggingface.co/sgugger/custom-resnet50d).
-
-Consulte o [tutorial de compartilhamento](model_sharing) para obter mais informaçÔes sobre o método push_to_hub.
-
-## Usando um modelo com cĂłdigo customizado
-
-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
-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
-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
-um modelo com cĂłdigo customizado:
-
-```py
-from transformers import AutoModelForImageClassification
-
-model = AutoModelForImageClassification.from_pretrained("sgugger/custom-resnet50d", trust_remote_code=True)
-```
-
-Também é fortemente recomendado passar um hash de confirmação como uma `revisão` para garantir que o autor dos modelos não
-atualize o cĂłdigo com novas linhas maliciosas (a menos que vocĂȘ confie totalmente nos autores dos modelos).
-
-
-```py
-commit_hash = "ed94a7c6247d8aedce4647f00f20de6875b5b292"
-model = AutoModelForImageClassification.from_pretrained(
- "sgugger/custom-resnet50d", trust_remote_code=True, revision=commit_hash
-)
-```
-
-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
-hash de qualquer commit.
-
-## Registrando um modelo com cĂłdigo customizado para as classes automĂĄticas
-
-Se vocĂȘ estiver escrevendo uma biblioteca que estende đ€ Transformers, talvez queira estender as classes automĂĄticas para incluir seus prĂłprios
-modelos. Isso Ă© diferente de enviar o cĂłdigo para o Hub no sentido de que os usuĂĄrios precisarĂŁo importar sua biblioteca para
-obter os modelos customizados (ao contrĂĄrio de baixar automaticamente o cĂłdigo do modelo do Hub).
-
-Desde que sua configuração tenha um atributo `model_type` diferente dos tipos de modelo existentes e que as classes do seu modelo
-tenha os atributos `config_class` corretos, vocĂȘ pode simplesmente adicionĂĄ-los Ă s classes automĂĄticas assim:
-
-```py
-from transformers import AutoConfig, AutoModel, AutoModelForImageClassification
-
-AutoConfig.register("resnet", ResnetConfig)
-AutoModel.register(ResnetConfig, ResnetModel)
-AutoModelForImageClassification.register(ResnetConfig, ResnetModelForImageClassification)
-```
-
-Observe que o primeiro argumento usado ao registrar sua configuração customizada para [`AutoConfig`] precisa corresponder ao `model_type`
-de sua configuração customizada. E o primeiro argumento usado ao registrar seus modelos customizados, para qualquer necessidade de classe de modelo automåtico
-deve corresponder ao `config_class` desses modelos.
-
diff --git a/docs/source/pt/fast_tokenizers.md b/docs/source/pt/fast_tokenizers.md
new file mode 100644
index 000000000000..ea1da8a61571
--- /dev/null
+++ b/docs/source/pt/fast_tokenizers.md
@@ -0,0 +1,66 @@
+
+
+# Usando os Tokenizers do đ€ Tokenizers
+
+O [`PreTrainedTokenizerFast`] depende da biblioteca [đ€ Tokenizers](https://huggingface.co/docs/tokenizers). O Tokenizer obtido da biblioteca đ€ Tokenizers pode ser carregado facilmente pelo đ€ Transformers.
+
+Antes de entrar nos detalhes, vamos começar criando um tokenizer fictĂcio em algumas linhas:
+
+```python
+>>> from tokenizers import Tokenizer
+>>> from tokenizers.models import BPE
+>>> from tokenizers.trainers import BpeTrainer
+>>> from tokenizers.pre_tokenizers import Whitespace
+
+>>> tokenizer = Tokenizer(BPE(unk_token="[UNK]"))
+>>> trainer = BpeTrainer(special_tokens=["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]"])
+
+>>> tokenizer.pre_tokenizer = Whitespace()
+>>> files = [...]
+>>> tokenizer.train(files, trainer)
+```
+
+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.
+
+## Carregando diretamente de um objeto tokenizer
+
+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:
+
+```python
+>>> from transformers import PreTrainedTokenizerFast
+
+>>> fast_tokenizer = PreTrainedTokenizerFast(tokenizer_object=tokenizer)
+```
+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.
+
+## Carregando de um arquivo JSON
+
+Para carregar um tokenizer de um arquivo JSON vamos primeiro começar salvando nosso tokenizer:
+
+```python
+>>> tokenizer.save("tokenizer.json")
+```
+
+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:
+
+```python
+>>> from transformers import PreTrainedTokenizerFast
+
+>>> fast_tokenizer = PreTrainedTokenizerFast(tokenizer_file="tokenizer.json")
+```
+
+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.
\ No newline at end of file
diff --git a/docs/source/pt/fast_tokenizers.mdx b/docs/source/pt/fast_tokenizers.mdx
deleted file mode 100644
index aff9afb31f2b..000000000000
--- a/docs/source/pt/fast_tokenizers.mdx
+++ /dev/null
@@ -1,62 +0,0 @@
-
-
-# Usando os Tokenizers do đ€ Tokenizers
-
-O [`PreTrainedTokenizerFast`] depende da biblioteca [đ€ Tokenizers](https://huggingface.co/docs/tokenizers). O Tokenizer obtido da biblioteca đ€ Tokenizers pode ser carregado facilmente pelo đ€ Transformers.
-
-Antes de entrar nos detalhes, vamos começar criando um tokenizer fictĂcio em algumas linhas:
-
-```python
->>> from tokenizers import Tokenizer
->>> from tokenizers.models import BPE
->>> from tokenizers.trainers import BpeTrainer
->>> from tokenizers.pre_tokenizers import Whitespace
-
->>> tokenizer = Tokenizer(BPE(unk_token="[UNK]"))
->>> trainer = BpeTrainer(special_tokens=["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]"])
-
->>> tokenizer.pre_tokenizer = Whitespace()
->>> files = [...]
->>> tokenizer.train(files, trainer)
-```
-
-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.
-
-## Carregando diretamente de um objeto tokenizer
-
-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:
-
-```python
->>> from transformers import PreTrainedTokenizerFast
-
->>> fast_tokenizer = PreTrainedTokenizerFast(tokenizer_object=tokenizer)
-```
-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.
-
-## Carregando de um arquivo JSON
-
-Para carregar um tokenizer de um arquivo JSON vamos primeiro começar salvando nosso tokenizer:
-
-```python
->>> tokenizer.save("tokenizer.json")
-```
-
-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:
-
-```python
->>> from transformers import PreTrainedTokenizerFast
-
->>> fast_tokenizer = PreTrainedTokenizerFast(tokenizer_file="tokenizer.json")
-```
-
-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.
\ No newline at end of file
diff --git a/docs/source/pt/index.md b/docs/source/pt/index.md
new file mode 100644
index 000000000000..08575b0bea22
--- /dev/null
+++ b/docs/source/pt/index.md
@@ -0,0 +1,296 @@
+
+
+# đ€ Transformers
+
+
+Estado da Arte para Aprendizado de MĂĄquina em PyTorch, TensorFlow e JAX.
+O đ€ Transformers disponibiliza APIs para facilmente baixar e treinar modelos prĂ©-treinados de Ășltima geração.
+O uso de modelos pré-treinados pode diminuir os seus custos de computação, a sua pegada de carbono, além de economizar o
+tempo necessĂĄrio para se treinar um modelo do zero. Os modelos podem ser usados para diversas tarefas:
+
+* đ Textos: classificação, extração de informaçÔes, perguntas e respostas, resumir, traduzir e gerar textos em mais de 100 idiomas.
+* đŒ Imagens: classificação, deteção de objetos, e segmentação.
+* đŁ Audio: reconhecimento de fala e classificação de ĂĄudio.
+* đ Multimodal: perguntas tabeladas e respsostas, reconhecimento Ăłtico de charactĂ©res, extração de informação de
+documentos escaneados, classificação de vĂdeo, perguntas e respostas visuais.
+
+Nossa biblioteca aceita integração contĂnua entre trĂȘs das bibliotecas mais populares de aprendizado profundo:
+Our library supports seamless integration between three of the most popular deep learning libraries:
+[PyTorch](https://pytorch.org/), [TensorFlow](https://www.tensorflow.org/) e [JAX](https://jax.readthedocs.io/en/latest/).
+Treine seu modelo em trĂȘs linhas de cĂłdigo em um framework, e carregue-o para execução em outro.
+
+Cada arquitetura đ€ Transformers Ă© definida em um mĂłdulo individual do Python, para que seja facilmente customizĂĄvel para pesquisa e experimentos.
+
+## Se vocĂȘ estiver procurando suporte do time da Hugging Face, acesse
+
+
+
+
+
+## ConteĂșdo
+
+A documentação é dividida em cinco partes:
+ - **INĂCIO** contĂ©m um tour rĂĄpido de instalação e instruçÔes para te dar um empurrĂŁo inicial com os đ€ Transformers.
+ - **TUTORIAIS** são perfeitos para começar a aprender sobre a nossa biblioteca. Essa seção irå te ajudar a desenvolver
+ habilidades bĂĄsicas necessĂĄrias para usar o đ€ Transformers.
+ - **GUIAS PRĂTICOS** irĂŁo te mostrar como alcançar um certo objetivo, como o fine-tuning de um modelo prĂ©-treinado
+ para modelamento de idioma, ou como criar um cabeçalho personalizado para um modelo.
+ - **GUIAS CONCEITUAIS** te darão mais discussÔes e explicaçÔes dos conceitos fundamentais e idéias por trås dos modelos,
+ tarefas e da filosofia de design por trĂĄs do đ€ Transformers.
+ - **API** descreve o funcionamento de cada classe e função, agrupada em:
+
+ - **CLASSES PRINCIPAIS** para as classes que expÔe as APIs importantes da biblioteca.
+ - **MODELOS** para as classes e funçÔes relacionadas à cada modelo implementado na biblioteca.
+ - **AUXILIARES INTERNOS** para as classes e funçÔes usadas internamente.
+
+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:
+
+### Modelos atuais
+
+
+
+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://arxiv.org/abs/1909.11942), by Zhenzhong Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.
+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://arxiv.org/abs/1910.13461) by Mike Lewis, Yinhan Liu, Naman Goyal, Marjan Ghazvininejad, Abdelrahman Mohamed, Omer Levy, Ves Stoyanov and Luke Zettlemoyer.
+1. **[BARThez](model_doc/barthez)** (from Ăcole polytechnique) released with the paper [BARThez: a Skilled Pretrained French Sequence-to-Sequence Model](https://arxiv.org/abs/2010.12321) by Moussa Kamal Eddine, Antoine J.-P. Tixier, Michalis Vazirgiannis.
+1. **[BARTpho](model_doc/bartpho)** (from VinAI Research) released with the paper [BARTpho: Pre-trained Sequence-to-Sequence Models for Vietnamese](https://arxiv.org/abs/2109.09701) by Nguyen Luong Tran, Duong Minh Le and Dat Quoc Nguyen.
+1. **[BEiT](model_doc/beit)** (from Microsoft) released with the paper [BEiT: BERT Pre-Training of Image Transformers](https://arxiv.org/abs/2106.08254) by Hangbo Bao, Li Dong, Furu Wei.
+1. **[BERT](model_doc/bert)** (from Google) released with the paper [BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding](https://arxiv.org/abs/1810.04805) by Jacob Devlin, Ming-Wei Chang, Kenton Lee and Kristina Toutanova.
+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.
+1. **[BERT For Sequence Generation](model_doc/bert-generation)** (from Google) released with the paper [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://arxiv.org/abs/1907.12461) by Sascha Rothe, Shashi Narayan, Aliaksei Severyn.
+1. **[BigBird-RoBERTa](model_doc/big_bird)** (from Google Research) released with the paper [Big Bird: Transformers for Longer Sequences](https://arxiv.org/abs/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.
+1. **[BigBird-Pegasus](model_doc/bigbird_pegasus)** (from Google Research) released with the paper [Big Bird: Transformers for Longer Sequences](https://arxiv.org/abs/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.
+1. **[Blenderbot](model_doc/blenderbot)** (from Facebook) released with the paper [Recipes for building an open-domain chatbot](https://arxiv.org/abs/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.
+1. **[BlenderbotSmall](model_doc/blenderbot-small)** (from Facebook) released with the paper [Recipes for building an open-domain chatbot](https://arxiv.org/abs/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.
+1. **[BORT](model_doc/bort)** (from Alexa) released with the paper [Optimal Subarchitecture Extraction For BERT](https://arxiv.org/abs/2010.10499) by Adrian de Wynter and Daniel J. Perry.
+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://arxiv.org/abs/2105.13626) by Linting Xue, Aditya Barua, Noah Constant, Rami Al-Rfou, Sharan Narang, Mihir Kale, Adam Roberts, Colin Raffel.
+1. **[CamemBERT](model_doc/camembert)** (from Inria/Facebook/Sorbonne) released with the paper [CamemBERT: a Tasty French Language Model](https://arxiv.org/abs/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.
+1. **[CANINE](model_doc/canine)** (from Google Research) released with the paper [CANINE: Pre-training an Efficient Tokenization-Free Encoder for Language Representation](https://arxiv.org/abs/2103.06874) by Jonathan H. Clark, Dan Garrette, Iulia Turc, John Wieting.
+1. **[ConvNeXT](model_doc/convnext)** (from Facebook AI) released with the paper [A ConvNet for the 2020s](https://arxiv.org/abs/2201.03545) by Zhuang Liu, Hanzi Mao, Chao-Yuan Wu, Christoph Feichtenhofer, Trevor Darrell, Saining Xie.
+1. **[ConvNeXTV2](model_doc/convnextv2)** (from Facebook AI) released with the paper [ConvNeXt V2: Co-designing and Scaling ConvNets with Masked Autoencoders](https://arxiv.org/abs/2301.00808) by Sanghyun Woo, Shoubhik Debnath, Ronghang Hu, Xinlei Chen, Zhuang Liu, In So Kweon, Saining Xie.
+1. **[CLIP](model_doc/clip)** (from OpenAI) released with the paper [Learning Transferable Visual Models From Natural Language Supervision](https://arxiv.org/abs/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.
+1. **[ConvBERT](model_doc/convbert)** (from YituTech) released with the paper [ConvBERT: Improving BERT with Span-based Dynamic Convolution](https://arxiv.org/abs/2008.02496) by Zihang Jiang, Weihao Yu, Daquan Zhou, Yunpeng Chen, Jiashi Feng, Shuicheng Yan.
+1. **[CPM](model_doc/cpm)** (from Tsinghua University) released with the paper [CPM: A Large-scale Generative Chinese Pre-trained Language Model](https://arxiv.org/abs/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.
+1. **[CTRL](model_doc/ctrl)** (from Salesforce) released with the paper [CTRL: A Conditional Transformer Language Model for Controllable Generation](https://arxiv.org/abs/1909.05858) by Nitish Shirish Keskar*, Bryan McCann*, Lav R. Varshney, Caiming Xiong and Richard Socher.
+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://arxiv.org/abs/2202.03555) by Alexei Baevski, Wei-Ning Hsu, Qiantong Xu, Arun Babu, Jiatao Gu, Michael Auli.
+1. **[DeBERTa](model_doc/deberta)** (from Microsoft) released with the paper [DeBERTa: Decoding-enhanced BERT with Disentangled Attention](https://arxiv.org/abs/2006.03654) by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen.
+1. **[DeBERTa-v2](model_doc/deberta-v2)** (from Microsoft) released with the paper [DeBERTa: Decoding-enhanced BERT with Disentangled Attention](https://arxiv.org/abs/2006.03654) by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen.
+1. **[Decision Transformer](model_doc/decision_transformer)** (from Berkeley/Facebook/Google) released with the paper [Decision Transformer: Reinforcement Learning via Sequence Modeling](https://arxiv.org/abs/2106.01345) by Lili Chen, Kevin Lu, Aravind Rajeswaran, Kimin Lee, Aditya Grover, Michael Laskin, Pieter Abbeel, Aravind Srinivas, Igor Mordatch.
+1. **[DiT](model_doc/dit)** (from Microsoft Research) released with the paper [DiT: Self-supervised Pre-training for Document Image Transformer](https://arxiv.org/abs/2203.02378) by Junlong Li, Yiheng Xu, Tengchao Lv, Lei Cui, Cha Zhang, Furu Wei.
+1. **[DeiT](model_doc/deit)** (from Facebook) released with the paper [Training data-efficient image transformers & distillation through attention](https://arxiv.org/abs/2012.12877) by Hugo Touvron, Matthieu Cord, Matthijs Douze, Francisco Massa, Alexandre Sablayrolles, Hervé Jégou.
+1. **[DETR](model_doc/detr)** (from Facebook) released with the paper [End-to-End Object Detection with Transformers](https://arxiv.org/abs/2005.12872) by Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov, Sergey Zagoruyko.
+1. **[DialoGPT](model_doc/dialogpt)** (from Microsoft Research) released with the paper [DialoGPT: Large-Scale Generative Pre-training for Conversational Response Generation](https://arxiv.org/abs/1911.00536) by Yizhe Zhang, Siqi Sun, Michel Galley, Yen-Chun Chen, Chris Brockett, Xiang Gao, Jianfeng Gao, Jingjing Liu, Bill Dolan.
+1. **[DistilBERT](model_doc/distilbert)** (from HuggingFace), released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter](https://arxiv.org/abs/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/tree/main/examples/research_projects/distillation), RoBERTa into [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/research_projects/distillation), Multilingual BERT into [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/research_projects/distillation) and a German version of DistilBERT.
+1. **[DPR](model_doc/dpr)** (from Facebook) released with the paper [Dense Passage Retrieval for Open-Domain Question Answering](https://arxiv.org/abs/2004.04906) by Vladimir Karpukhin, Barlas OÄuz, Sewon Min, Patrick Lewis, Ledell Wu, Sergey Edunov, Danqi Chen, and Wen-tau Yih.
+1. **[DPT](master/model_doc/dpt)** (from Intel Labs) released with the paper [Vision Transformers for Dense Prediction](https://arxiv.org/abs/2103.13413) by René Ranftl, Alexey Bochkovskiy, Vladlen Koltun.
+1. **[EfficientNet](model_doc/efficientnet)** (from Google Research) released with the paper [EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks](https://arxiv.org/abs/1905.11946) by Mingxing Tan and Quoc V. Le.
+1. **[EncoderDecoder](model_doc/encoder-decoder)** (from Google Research) released with the paper [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://arxiv.org/abs/1907.12461) by Sascha Rothe, Shashi Narayan, Aliaksei Severyn.
+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://arxiv.org/abs/2003.10555) by Kevin Clark, Minh-Thang Luong, Quoc V. Le, Christopher D. Manning.
+1. **[FlauBERT](model_doc/flaubert)** (from CNRS) released with the paper [FlauBERT: Unsupervised Language Model Pre-training for French](https://arxiv.org/abs/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.
+1. **[FNet](model_doc/fnet)** (from Google Research) released with the paper [FNet: Mixing Tokens with Fourier Transforms](https://arxiv.org/abs/2105.03824) by James Lee-Thorp, Joshua Ainslie, Ilya Eckstein, Santiago Ontanon.
+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://arxiv.org/abs/2006.03236) by Zihang Dai, Guokun Lai, Yiming Yang, Quoc V. Le.
+1. **[GLPN](model_doc/glpn)** (from KAIST) released with the paper [Global-Local Path Networks for Monocular Depth Estimation with Vertical CutDepth](https://arxiv.org/abs/2201.07436) by Doyeon Kim, Woonghyun Ga, Pyungwhan Ahn, Donggyu Joo, Sehwan Chun, Junmo Kim.
+1. **[GPT](model_doc/openai-gpt)** (from OpenAI) released with the paper [Improving Language Understanding by Generative Pre-Training](https://blog.openai.com/language-unsupervised/) by Alec Radford, Karthik Narasimhan, Tim Salimans and Ilya Sutskever.
+1. **[GPT-2](model_doc/gpt2)** (from OpenAI) released with the paper [Language Models are Unsupervised Multitask Learners](https://blog.openai.com/better-language-models/) by Alec Radford*, Jeffrey Wu*, Rewon Child, David Luan, Dario Amodei** and Ilya Sutskever**.
+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.
+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.
+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).
+1. **[Hubert](model_doc/hubert)** (from Facebook) released with the paper [HuBERT: Self-Supervised Speech Representation Learning by Masked Prediction of Hidden Units](https://arxiv.org/abs/2106.07447) by Wei-Ning Hsu, Benjamin Bolte, Yao-Hung Hubert Tsai, Kushal Lakhotia, Ruslan Salakhutdinov, Abdelrahman Mohamed.
+1. **[I-BERT](model_doc/ibert)** (from Berkeley) released with the paper [I-BERT: Integer-only BERT Quantization](https://arxiv.org/abs/2101.01321) by Sehoon Kim, Amir Gholami, Zhewei Yao, Michael W. Mahoney, Kurt Keutzer.
+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.
+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://arxiv.org/abs/1912.13318) by Yiheng Xu, Minghao Li, Lei Cui, Shaohan Huang, Furu Wei, Ming Zhou.
+1. **[LayoutLMv2](model_doc/layoutlmv2)** (from Microsoft Research Asia) released with the paper [LayoutLMv2: Multi-modal Pre-training for Visually-Rich Document Understanding](https://arxiv.org/abs/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.
+1. **[LayoutXLM](model_doc/layoutxlm)** (from Microsoft Research Asia) released with the paper [LayoutXLM: Multimodal Pre-training for Multilingual Visually-rich Document Understanding](https://arxiv.org/abs/2104.08836) by Yiheng Xu, Tengchao Lv, Lei Cui, Guoxin Wang, Yijuan Lu, Dinei Florencio, Cha Zhang, Furu Wei.
+1. **[LED](model_doc/led)** (from AllenAI) released with the paper [Longformer: The Long-Document Transformer](https://arxiv.org/abs/2004.05150) by Iz Beltagy, Matthew E. Peters, Arman Cohan.
+1. **[Longformer](model_doc/longformer)** (from AllenAI) released with the paper [Longformer: The Long-Document Transformer](https://arxiv.org/abs/2004.05150) by Iz Beltagy, Matthew E. Peters, Arman Cohan.
+1. **[LUKE](model_doc/luke)** (from Studio Ousia) released with the paper [LUKE: Deep Contextualized Entity Representations with Entity-aware Self-attention](https://arxiv.org/abs/2010.01057) by Ikuya Yamada, Akari Asai, Hiroyuki Shindo, Hideaki Takeda, Yuji Matsumoto.
+1. **[mLUKE](model_doc/mluke)** (from Studio Ousia) released with the paper [mLUKE: The Power of Entity Representations in Multilingual Pretrained Language Models](https://arxiv.org/abs/2110.08151) by Ryokan Ri, Ikuya Yamada, and Yoshimasa Tsuruoka.
+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://arxiv.org/abs/1908.07490) by Hao Tan and Mohit Bansal.
+1. **[M2M100](model_doc/m2m_100)** (from Facebook) released with the paper [Beyond English-Centric Multilingual Machine Translation](https://arxiv.org/abs/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.
+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.
+1. **[Mask2Former](model_doc/mask2former)** (from FAIR and UIUC) released with the paper [Masked-attention Mask Transformer for Universal Image Segmentation](https://arxiv.org/abs/2112.01527) by Bowen Cheng, Ishan Misra, Alexander G. Schwing, Alexander Kirillov, Rohit Girdhar.
+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://arxiv.org/abs/2107.06278) by Bowen Cheng, Alexander G. Schwing, Alexander Kirillov.
+1. **[MBart](model_doc/mbart)** (from Facebook) released with the paper [Multilingual Denoising Pre-training for Neural Machine Translation](https://arxiv.org/abs/2001.08210) by Yinhan Liu, Jiatao Gu, Naman Goyal, Xian Li, Sergey Edunov, Marjan Ghazvininejad, Mike Lewis, Luke Zettlemoyer.
+1. **[MBart-50](model_doc/mbart)** (from Facebook) released with the paper [Multilingual Translation with Extensible Multilingual Pretraining and Finetuning](https://arxiv.org/abs/2008.00401) by Yuqing Tang, Chau Tran, Xian Li, Peng-Jen Chen, Naman Goyal, Vishrav Chaudhary, Jiatao Gu, Angela Fan.
+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://arxiv.org/abs/1909.08053) by Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper and Bryan Catanzaro.
+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://arxiv.org/abs/1909.08053) by Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper and Bryan Catanzaro.
+1. **[MPNet](model_doc/mpnet)** (from Microsoft Research) released with the paper [MPNet: Masked and Permuted Pre-training for Language Understanding](https://arxiv.org/abs/2004.09297) by Kaitao Song, Xu Tan, Tao Qin, Jianfeng Lu, Tie-Yan Liu.
+1. **[MT5](model_doc/mt5)** (from Google AI) released with the paper [mT5: A massively multilingual pre-trained text-to-text transformer](https://arxiv.org/abs/2010.11934) by Linting Xue, Noah Constant, Adam Roberts, Mihir Kale, Rami Al-Rfou, Aditya Siddhant, Aditya Barua, Colin Raffel.
+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://arxiv.org/abs/2102.03902) by Yunyang Xiong, Zhanpeng Zeng, Rudrasis Chakraborty, Mingxing Tan, Glenn Fung, Yin Li, Vikas Singh.
+1. **[OneFormer](model_doc/oneformer)** (from SHI Labs) released with the paper [OneFormer: One Transformer to Rule Universal Image Segmentation](https://arxiv.org/abs/2211.06220) by Jitesh Jain, Jiachen Li, MangTik Chiu, Ali Hassani, Nikita Orlov, Humphrey Shi.
+1. **[Pegasus](model_doc/pegasus)** (from Google) released with the paper [PEGASUS: Pre-training with Extracted Gap-sentences for Abstractive Summarization](https://arxiv.org/abs/1912.08777) by Jingqing Zhang, Yao Zhao, Mohammad Saleh and Peter J. Liu.
+1. **[Perceiver IO](model_doc/perceiver)** (from Deepmind) released with the paper [Perceiver IO: A General Architecture for Structured Inputs & Outputs](https://arxiv.org/abs/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.
+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.
+1. **[PLBart](model_doc/plbart)** (from UCLA NLP) released with the paper [Unified Pre-training for Program Understanding and Generation](https://arxiv.org/abs/2103.06333) by Wasi Uddin Ahmad, Saikat Chakraborty, Baishakhi Ray, Kai-Wei Chang.
+1. **[PoolFormer](model_doc/poolformer)** (from Sea AI Labs) released with the paper [MetaFormer is Actually What You Need for Vision](https://arxiv.org/abs/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.
+1. **[ProphetNet](model_doc/prophetnet)** (from Microsoft Research) released with the paper [ProphetNet: Predicting Future N-gram for Sequence-to-Sequence Pre-training](https://arxiv.org/abs/2001.04063) by Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang and Ming Zhou.
+1. **[QDQBert](model_doc/qdqbert)** (from NVIDIA) released with the paper [Integer Quantization for Deep Learning Inference: Principles and Empirical Evaluation](https://arxiv.org/abs/2004.09602) by Hao Wu, Patrick Judd, Xiaojie Zhang, Mikhail Isaev and Paulius Micikevicius.
+1. **[REALM](model_doc/realm.html)** (from Google Research) released with the paper [REALM: Retrieval-Augmented Language Model Pre-Training](https://arxiv.org/abs/2002.08909) by Kelvin Guu, Kenton Lee, Zora Tung, Panupong Pasupat and Ming-Wei Chang.
+1. **[Reformer](model_doc/reformer)** (from Google Research) released with the paper [Reformer: The Efficient Transformer](https://arxiv.org/abs/2001.04451) by Nikita Kitaev, Ćukasz Kaiser, Anselm Levskaya.
+1. **[RemBERT](model_doc/rembert)** (from Google Research) released with the paper [Rethinking embedding coupling in pre-trained language models](https://arxiv.org/abs/2010.12821) by Hyung Won Chung, Thibault Févry, Henry Tsai, M. Johnson, Sebastian Ruder.
+1. **[RegNet](model_doc/regnet)** (from META Platforms) released with the paper [Designing Network Design Space](https://arxiv.org/abs/2003.13678) by Ilija Radosavovic, Raj Prateek Kosaraju, Ross Girshick, Kaiming He, Piotr DollĂĄr.
+1. **[ResNet](model_doc/resnet)** (from Microsoft Research) released with the paper [Deep Residual Learning for Image Recognition](https://arxiv.org/abs/1512.03385) by Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun.
+1. **[RoBERTa](model_doc/roberta)** (from Facebook), released together with the paper [RoBERTa: A Robustly Optimized BERT Pretraining Approach](https://arxiv.org/abs/1907.11692) by Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Mandar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, Veselin Stoyanov.
+1. **[RoFormer](model_doc/roformer)** (from ZhuiyiTechnology), released together with the paper [RoFormer: Enhanced Transformer with Rotary Position Embedding](https://arxiv.org/abs/2104.09864) by Jianlin Su and Yu Lu and Shengfeng Pan and Bo Wen and Yunfeng Liu.
+1. **[SegFormer](model_doc/segformer)** (from NVIDIA) released with the paper [SegFormer: Simple and Efficient Design for Semantic Segmentation with Transformers](https://arxiv.org/abs/2105.15203) by Enze Xie, Wenhai Wang, Zhiding Yu, Anima Anandkumar, Jose M. Alvarez, Ping Luo.
+1. **[SEW](model_doc/sew)** (from ASAPP) released with the paper [Performance-Efficiency Trade-offs in Unsupervised Pre-training for Speech Recognition](https://arxiv.org/abs/2109.06870) by Felix Wu, Kwangyoun Kim, Jing Pan, Kyu Han, Kilian Q. Weinberger, Yoav Artzi.
+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://arxiv.org/abs/2109.06870) by Felix Wu, Kwangyoun Kim, Jing Pan, Kyu Han, Kilian Q. Weinberger, Yoav Artzi.
+1. **[SpeechToTextTransformer](model_doc/speech_to_text)** (from Facebook), released together with the paper [fairseq S2T: Fast Speech-to-Text Modeling with fairseq](https://arxiv.org/abs/2010.05171) by Changhan Wang, Yun Tang, Xutai Ma, Anne Wu, Dmytro Okhonko, Juan Pino.
+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://arxiv.org/abs/2104.06678) by Changhan Wang, Anne Wu, Juan Pino, Alexei Baevski, Michael Auli, Alexis Conneau.
+1. **[Splinter](model_doc/splinter)** (from Tel Aviv University), released together with the paper [Few-Shot Question Answering by Pretraining Span Selection](https://arxiv.org/abs/2101.00438) by Ori Ram, Yuval Kirstain, Jonathan Berant, Amir Globerson, Omer Levy.
+1. **[SqueezeBert](model_doc/squeezebert)** (from Berkeley) released with the paper [SqueezeBERT: What can computer vision teach NLP about efficient neural networks?](https://arxiv.org/abs/2006.11316) by Forrest N. Iandola, Albert E. Shaw, Ravi Krishna, and Kurt W. Keutzer.
+1. **[Swin Transformer](model_doc/swin)** (from Microsoft) released with the paper [Swin Transformer: Hierarchical Vision Transformer using Shifted Windows](https://arxiv.org/abs/2103.14030) by Ze Liu, Yutong Lin, Yue Cao, Han Hu, Yixuan Wei, Zheng Zhang, Stephen Lin, Baining Guo.
+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://arxiv.org/abs/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.
+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.
+1. **[TAPAS](model_doc/tapas)** (from Google AI) released with the paper [TAPAS: Weakly Supervised Table Parsing via Pre-training](https://arxiv.org/abs/2004.02349) by Jonathan Herzig, PaweĆ Krzysztof Nowak, Thomas MĂŒller, Francesco Piccinno and Julian Martin Eisenschlos.
+1. **[TAPEX](model_doc/tapex)** (from Microsoft Research) released with the paper [TAPEX: Table Pre-training via Learning a Neural SQL Executor](https://arxiv.org/abs/2107.07653) by Qian Liu, Bei Chen, Jiaqi Guo, Morteza Ziyadi, Zeqi Lin, Weizhu Chen, Jian-Guang Lou.
+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://arxiv.org/abs/1901.02860) by Zihang Dai*, Zhilin Yang*, Yiming Yang, Jaime Carbonell, Quoc V. Le, Ruslan Salakhutdinov.
+1. **[TrOCR](model_doc/trocr)** (from Microsoft), released together with the paper [TrOCR: Transformer-based Optical Character Recognition with Pre-trained Models](https://arxiv.org/abs/2109.10282) by Minghao Li, Tengchao Lv, Lei Cui, Yijuan Lu, Dinei Florencio, Cha Zhang, Zhoujun Li, Furu Wei.
+1. **[UniSpeech](model_doc/unispeech)** (from Microsoft Research) released with the paper [UniSpeech: Unified Speech Representation Learning with Labeled and Unlabeled Data](https://arxiv.org/abs/2101.07597) by Chengyi Wang, Yu Wu, Yao Qian, Kenichi Kumatani, Shujie Liu, Furu Wei, Michael Zeng, Xuedong Huang.
+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://arxiv.org/abs/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.
+1. **[VAN](model_doc/van)** (from Tsinghua University and Nankai University) released with the paper [Visual Attention Network](https://arxiv.org/abs/2202.09741) by Meng-Hao Guo, Cheng-Ze Lu, Zheng-Ning Liu, Ming-Ming Cheng, Shi-Min Hu.
+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://arxiv.org/abs/2102.03334) by Wonjae Kim, Bokyung Son, Ildoo Kim.
+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://arxiv.org/abs/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.
+1. **[ViTMAE](model_doc/vit_mae)** (from Meta AI) released with the paper [Masked Autoencoders Are Scalable Vision Learners](https://arxiv.org/abs/2111.06377) by Kaiming He, Xinlei Chen, Saining Xie, Yanghao Li, Piotr DollĂĄr, Ross Girshick.
+1. **[VisualBERT](model_doc/visual_bert)** (from UCLA NLP) released with the paper [VisualBERT: A Simple and Performant Baseline for Vision and Language](https://arxiv.org/pdf/1908.03557) by Liunian Harold Li, Mark Yatskar, Da Yin, Cho-Jui Hsieh, Kai-Wei Chang.
+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://arxiv.org/abs/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.
+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://arxiv.org/abs/2006.11477) by Alexei Baevski, Henry Zhou, Abdelrahman Mohamed, Michael Auli.
+1. **[Wav2Vec2Phoneme](model_doc/wav2vec2_phoneme)** (from Facebook AI) released with the paper [Simple and Effective Zero-shot Cross-lingual Phoneme Recognition](https://arxiv.org/abs/2109.11680) by Qiantong Xu, Alexei Baevski, Michael Auli.
+1. **[XGLM](model_doc/xglm)** (From Facebook AI) released with the paper [Few-shot Learning with Multilingual Language Models](https://arxiv.org/abs/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.
+1. **[XLM](model_doc/xlm)** (from Facebook) released together with the paper [Cross-lingual Language Model Pretraining](https://arxiv.org/abs/1901.07291) by Guillaume Lample and Alexis Conneau.
+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://arxiv.org/abs/2001.04063) by Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang and Ming Zhou.
+1. **[XLM-RoBERTa](model_doc/xlm-roberta)** (from Facebook AI), released together with the paper [Unsupervised Cross-lingual Representation Learning at Scale](https://arxiv.org/abs/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.
+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://arxiv.org/abs/2105.00572) by Naman Goyal, Jingfei Du, Myle Ott, Giri Anantharaman, Alexis Conneau.
+1. **[XLNet](model_doc/xlnet)** (from Google/CMU) released with the paper [âXLNet: Generalized Autoregressive Pretraining for Language Understanding](https://arxiv.org/abs/1906.08237) by Zhilin Yang*, Zihang Dai*, Yiming Yang, Jaime Carbonell, Ruslan Salakhutdinov, Quoc V. Le.
+1. **[XLSR-Wav2Vec2](model_doc/xlsr_wav2vec2)** (from Facebook AI) released with the paper [Unsupervised Cross-Lingual Representation Learning For Speech Recognition](https://arxiv.org/abs/2006.13979) by Alexis Conneau, Alexei Baevski, Ronan Collobert, Abdelrahman Mohamed, Michael Auli.
+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://arxiv.org/abs/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.
+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://arxiv.org/abs/2111.09714) by Zhanpeng Zeng, Yunyang Xiong, Sathya N. Ravi, Shailesh Acharya, Glenn Fung, Vikas Singh.
+
+
+### Frameworks aceitos
+
+A tabela abaixo representa a lista de suporte na biblioteca para cada um dos seguintes modelos, caso tenham um tokenizer
+do Python (chamado de "slow"), ou um tokenizer construĂdo em cima da biblioteca đ€ Tokenizers (chamado de "fast"). AlĂ©m
+disso, sĂŁo diferenciados pelo suporte em diferentes frameworks: JAX (por meio do Flax); PyTorch; e/ou Tensorflow.
+
+
+
+| Model | Tokenizer slow | Tokenizer fast | PyTorch support | TensorFlow support | Flax Support |
+|:---------------------------:|:--------------:|:--------------:|:---------------:|:------------------:|:------------:|
+| ALBERT | â
| â
| â
| â
| â
|
+| BART | â
| â
| â
| â
| â
|
+| BEiT | â | â | â
| â | â
|
+| BERT | â
| â
| â
| â
| â
|
+| Bert Generation | â
| â | â
| â | â |
+| BigBird | â
| â
| â
| â | â
|
+| BigBirdPegasus | â | â | â
| â | â |
+| Blenderbot | â
| â
| â
| â
| â
|
+| BlenderbotSmall | â
| â
| â
| â
| â
|
+| CamemBERT | â
| â
| â
| â
| â |
+| Canine | â
| â | â
| â | â |
+| CLIP | â
| â
| â
| â
| â
|
+| ConvBERT | â
| â
| â
| â
| â |
+| ConvNext | â | â | â
| â
| â |
+| CTRL | â
| â | â
| â
| â |
+| Data2VecAudio | â | â | â
| â | â |
+| Data2VecText | â | â | â
| â | â |
+| Data2VecVision | â | â | â
| â | â |
+| DeBERTa | â
| â
| â
| â
| â |
+| DeBERTa-v2 | â
| â
| â
| â
| â |
+| Decision Transformer | â | â | â
| â | â |
+| DeiT | â | â | â
| â | â |
+| DETR | â | â | â
| â | â |
+| DistilBERT | â
| â
| â
| â
| â
|
+| DPR | â
| â
| â
| â
| â |
+| DPT | â | â | â
| â | â |
+| ELECTRA | â
| â
| â
| â
| â
|
+| Encoder decoder | â | â | â
| â
| â
|
+| FairSeq Machine-Translation | â
| â | â
| â | â |
+| FlauBERT | â
| â | â
| â
| â |
+| FNet | â
| â
| â
| â | â |
+| Funnel Transformer | â
| â
| â
| â
| â |
+| GLPN | â | â | â
| â | â |
+| GPT Neo | â | â | â
| â | â
|
+| GPT-J | â | â | â
| â
| â
|
+| Hubert | â | â | â
| â
| â |
+| I-BERT | â | â | â
| â | â |
+| ImageGPT | â | â | â
| â | â |
+| LayoutLM | â
| â
| â
| â
| â |
+| LayoutLMv2 | â
| â
| â
| â | â |
+| LED | â
| â
| â
| â
| â |
+| Longformer | â
| â
| â
| â
| â |
+| LUKE | â
| â | â
| â | â |
+| LXMERT | â
| â
| â
| â
| â |
+| M2M100 | â
| â | â
| â | â |
+| Marian | â
| â | â
| â
| â
|
+| MaskFormer | â | â | â
| â | â |
+| mBART | â
| â
| â
| â
| â
|
+| MegatronBert | â | â | â
| â | â |
+| MobileBERT | â
| â
| â
| â
| â |
+| MPNet | â
| â
| â
| â
| â |
+| mT5 | â
| â
| â
| â
| â
|
+| Nystromformer | â | â | â
| â | â |
+| OpenAI GPT | â
| â
| â
| â
| â |
+| OpenAI GPT-2 | â
| â
| â
| â
| â
|
+| Pegasus | â
| â
| â
| â
| â
|
+| Perceiver | â
| â | â
| â | â |
+| PLBart | â
| â | â
| â | â |
+| PoolFormer | â | â | â
| â | â |
+| ProphetNet | â
| â | â
| â | â |
+| QDQBert | â | â | â
| â | â |
+| RAG | â
| â | â
| â
| â |
+| Realm | â
| â
| â
| â | â |
+| Reformer | â
| â
| â
| â | â |
+| RegNet | â | â | â
| â
| â
|
+| RemBERT | â
| â
| â
| â
| â |
+| ResNet | â | â | â
| â | â
|
+| RetriBERT | â
| â
| â
| â | â |
+| RoBERTa | â
| â
| â
| â
| â
|
+| RoFormer | â
| â
| â
| â
| â
|
+| SegFormer | â | â | â
| â | â |
+| SEW | â | â | â
| â | â |
+| SEW-D | â | â | â
| â | â |
+| Speech Encoder decoder | â | â | â
| â | â
|
+| Speech2Text | â
| â | â
| â
| â |
+| Speech2Text2 | â
| â | â | â | â |
+| Splinter | â
| â
| â
| â | â |
+| SqueezeBERT | â
| â
| â
| â | â |
+| Swin | â | â | â
| â | â |
+| T5 | â
| â
| â
| â
| â
|
+| TAPAS | â
| â | â
| â
| â |
+| TAPEX | â
| â
| â
| â
| â
|
+| Transformer-XL | â
| â | â
| â
| â |
+| TrOCR | â | â | â
| â | â |
+| UniSpeech | â | â | â
| â | â |
+| UniSpeechSat | â | â | â
| â | â |
+| VAN | â | â | â
| â | â |
+| ViLT | â | â | â
| â | â |
+| Vision Encoder decoder | â | â | â
| â
| â
|
+| VisionTextDualEncoder | â | â | â
| â | â
|
+| VisualBert | â | â | â
| â | â |
+| ViT | â | â | â
| â
| â
|
+| ViTMAE | â | â | â
| â
| â |
+| Wav2Vec2 | â
| â | â
| â
| â
|
+| WavLM | â | â | â
| â | â |
+| XGLM | â
| â
| â
| â | â
|
+| XLM | â
| â | â
| â
| â |
+| XLM-RoBERTa | â
| â
| â
| â
| â
|
+| XLM-RoBERTa-XL | â | â | â
| â | â |
+| XLMProphetNet | â
| â | â
| â | â |
+| XLNet | â
| â
| â
| â
| â |
+| YOSO | â | â | â
| â | â |
+
+
diff --git a/docs/source/pt/index.mdx b/docs/source/pt/index.mdx
deleted file mode 100644
index 9b5cbc12e610..000000000000
--- a/docs/source/pt/index.mdx
+++ /dev/null
@@ -1,292 +0,0 @@
-
-
-# đ€ Transformers
-
-
-Estado da Arte para Aprendizado de MĂĄquina em PyTorch, TensorFlow e JAX.
-O đ€ Transformers disponibiliza APIs para facilmente baixar e treinar modelos prĂ©-treinados de Ășltima geração.
-O uso de modelos pré-treinados pode diminuir os seus custos de computação, a sua pegada de carbono, além de economizar o
-tempo necessĂĄrio para se treinar um modelo do zero. Os modelos podem ser usados para diversas tarefas:
-
-* đ Textos: classificação, extração de informaçÔes, perguntas e respostas, resumir, traduzir e gerar textos em mais de 100 idiomas.
-* đŒ Imagens: classificação, deteção de objetos, e segmentação.
-* đŁ Audio: reconhecimento de fala e classificação de ĂĄudio.
-* đ Multimodal: perguntas tabeladas e respsostas, reconhecimento Ăłtico de charactĂ©res, extração de informação de
-documentos escaneados, classificação de vĂdeo, perguntas e respostas visuais.
-
-Nossa biblioteca aceita integração contĂnua entre trĂȘs das bibliotecas mais populares de aprendizado profundo:
-Our library supports seamless integration between three of the most popular deep learning libraries:
-[PyTorch](https://pytorch.org/), [TensorFlow](https://www.tensorflow.org/) e [JAX](https://jax.readthedocs.io/en/latest/).
-Treine seu modelo em trĂȘs linhas de cĂłdigo em um framework, e carregue-o para execução em outro.
-
-Cada arquitetura đ€ Transformers Ă© definida em um mĂłdulo individual do Python, para que seja facilmente customizĂĄvel para pesquisa e experimentos.
-
-## Se vocĂȘ estiver procurando suporte do time da Hugging Face, acesse
-
-
-
-
-
-## ConteĂșdo
-
-A documentação é dividida em cinco partes:
- - **INĂCIO** contĂ©m um tour rĂĄpido de instalação e instruçÔes para te dar um empurrĂŁo inicial com os đ€ Transformers.
- - **TUTORIAIS** são perfeitos para começar a aprender sobre a nossa biblioteca. Essa seção irå te ajudar a desenvolver
- habilidades bĂĄsicas necessĂĄrias para usar o đ€ Transformers.
- - **GUIAS PRĂTICOS** irĂŁo te mostrar como alcançar um certo objetivo, como o fine-tuning de um modelo prĂ©-treinado
- para modelamento de idioma, ou como criar um cabeçalho personalizado para um modelo.
- - **GUIAS CONCEITUAIS** te darão mais discussÔes e explicaçÔes dos conceitos fundamentais e idéias por trås dos modelos,
- tarefas e da filosofia de design por trĂĄs do đ€ Transformers.
- - **API** descreve o funcionamento de cada classe e função, agrupada em:
-
- - **CLASSES PRINCIPAIS** para as classes que expÔe as APIs importantes da biblioteca.
- - **MODELOS** para as classes e funçÔes relacionadas à cada modelo implementado na biblioteca.
- - **AUXILIARES INTERNOS** para as classes e funçÔes usadas internamente.
-
-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:
-
-### Modelos atuais
-
-
-
-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://arxiv.org/abs/1909.11942), by Zhenzhong Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.
-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://arxiv.org/abs/1910.13461) by Mike Lewis, Yinhan Liu, Naman Goyal, Marjan Ghazvininejad, Abdelrahman Mohamed, Omer Levy, Ves Stoyanov and Luke Zettlemoyer.
-1. **[BARThez](model_doc/barthez)** (from Ăcole polytechnique) released with the paper [BARThez: a Skilled Pretrained French Sequence-to-Sequence Model](https://arxiv.org/abs/2010.12321) by Moussa Kamal Eddine, Antoine J.-P. Tixier, Michalis Vazirgiannis.
-1. **[BARTpho](model_doc/bartpho)** (from VinAI Research) released with the paper [BARTpho: Pre-trained Sequence-to-Sequence Models for Vietnamese](https://arxiv.org/abs/2109.09701) by Nguyen Luong Tran, Duong Minh Le and Dat Quoc Nguyen.
-1. **[BEiT](model_doc/beit)** (from Microsoft) released with the paper [BEiT: BERT Pre-Training of Image Transformers](https://arxiv.org/abs/2106.08254) by Hangbo Bao, Li Dong, Furu Wei.
-1. **[BERT](model_doc/bert)** (from Google) released with the paper [BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding](https://arxiv.org/abs/1810.04805) by Jacob Devlin, Ming-Wei Chang, Kenton Lee and Kristina Toutanova.
-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.
-1. **[BERT For Sequence Generation](model_doc/bert-generation)** (from Google) released with the paper [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://arxiv.org/abs/1907.12461) by Sascha Rothe, Shashi Narayan, Aliaksei Severyn.
-1. **[BigBird-RoBERTa](model_doc/big_bird)** (from Google Research) released with the paper [Big Bird: Transformers for Longer Sequences](https://arxiv.org/abs/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.
-1. **[BigBird-Pegasus](model_doc/bigbird_pegasus)** (from Google Research) released with the paper [Big Bird: Transformers for Longer Sequences](https://arxiv.org/abs/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.
-1. **[Blenderbot](model_doc/blenderbot)** (from Facebook) released with the paper [Recipes for building an open-domain chatbot](https://arxiv.org/abs/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.
-1. **[BlenderbotSmall](model_doc/blenderbot-small)** (from Facebook) released with the paper [Recipes for building an open-domain chatbot](https://arxiv.org/abs/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.
-1. **[BORT](model_doc/bort)** (from Alexa) released with the paper [Optimal Subarchitecture Extraction For BERT](https://arxiv.org/abs/2010.10499) by Adrian de Wynter and Daniel J. Perry.
-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://arxiv.org/abs/2105.13626) by Linting Xue, Aditya Barua, Noah Constant, Rami Al-Rfou, Sharan Narang, Mihir Kale, Adam Roberts, Colin Raffel.
-1. **[CamemBERT](model_doc/camembert)** (from Inria/Facebook/Sorbonne) released with the paper [CamemBERT: a Tasty French Language Model](https://arxiv.org/abs/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.
-1. **[CANINE](model_doc/canine)** (from Google Research) released with the paper [CANINE: Pre-training an Efficient Tokenization-Free Encoder for Language Representation](https://arxiv.org/abs/2103.06874) by Jonathan H. Clark, Dan Garrette, Iulia Turc, John Wieting.
-1. **[ConvNeXT](model_doc/convnext)** (from Facebook AI) released with the paper [A ConvNet for the 2020s](https://arxiv.org/abs/2201.03545) by Zhuang Liu, Hanzi Mao, Chao-Yuan Wu, Christoph Feichtenhofer, Trevor Darrell, Saining Xie.
-1. **[ConvNeXTV2](model_doc/convnextv2)** (from Facebook AI) released with the paper [ConvNeXt V2: Co-designing and Scaling ConvNets with Masked Autoencoders](https://arxiv.org/abs/2301.00808) by Sanghyun Woo, Shoubhik Debnath, Ronghang Hu, Xinlei Chen, Zhuang Liu, In So Kweon, Saining Xie.
-1. **[CLIP](model_doc/clip)** (from OpenAI) released with the paper [Learning Transferable Visual Models From Natural Language Supervision](https://arxiv.org/abs/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.
-1. **[ConvBERT](model_doc/convbert)** (from YituTech) released with the paper [ConvBERT: Improving BERT with Span-based Dynamic Convolution](https://arxiv.org/abs/2008.02496) by Zihang Jiang, Weihao Yu, Daquan Zhou, Yunpeng Chen, Jiashi Feng, Shuicheng Yan.
-1. **[CPM](model_doc/cpm)** (from Tsinghua University) released with the paper [CPM: A Large-scale Generative Chinese Pre-trained Language Model](https://arxiv.org/abs/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.
-1. **[CTRL](model_doc/ctrl)** (from Salesforce) released with the paper [CTRL: A Conditional Transformer Language Model for Controllable Generation](https://arxiv.org/abs/1909.05858) by Nitish Shirish Keskar*, Bryan McCann*, Lav R. Varshney, Caiming Xiong and Richard Socher.
-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://arxiv.org/abs/2202.03555) by Alexei Baevski, Wei-Ning Hsu, Qiantong Xu, Arun Babu, Jiatao Gu, Michael Auli.
-1. **[DeBERTa](model_doc/deberta)** (from Microsoft) released with the paper [DeBERTa: Decoding-enhanced BERT with Disentangled Attention](https://arxiv.org/abs/2006.03654) by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen.
-1. **[DeBERTa-v2](model_doc/deberta-v2)** (from Microsoft) released with the paper [DeBERTa: Decoding-enhanced BERT with Disentangled Attention](https://arxiv.org/abs/2006.03654) by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen.
-1. **[Decision Transformer](model_doc/decision_transformer)** (from Berkeley/Facebook/Google) released with the paper [Decision Transformer: Reinforcement Learning via Sequence Modeling](https://arxiv.org/abs/2106.01345) by Lili Chen, Kevin Lu, Aravind Rajeswaran, Kimin Lee, Aditya Grover, Michael Laskin, Pieter Abbeel, Aravind Srinivas, Igor Mordatch.
-1. **[DiT](model_doc/dit)** (from Microsoft Research) released with the paper [DiT: Self-supervised Pre-training for Document Image Transformer](https://arxiv.org/abs/2203.02378) by Junlong Li, Yiheng Xu, Tengchao Lv, Lei Cui, Cha Zhang, Furu Wei.
-1. **[DeiT](model_doc/deit)** (from Facebook) released with the paper [Training data-efficient image transformers & distillation through attention](https://arxiv.org/abs/2012.12877) by Hugo Touvron, Matthieu Cord, Matthijs Douze, Francisco Massa, Alexandre Sablayrolles, Hervé Jégou.
-1. **[DETR](model_doc/detr)** (from Facebook) released with the paper [End-to-End Object Detection with Transformers](https://arxiv.org/abs/2005.12872) by Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov, Sergey Zagoruyko.
-1. **[DialoGPT](model_doc/dialogpt)** (from Microsoft Research) released with the paper [DialoGPT: Large-Scale Generative Pre-training for Conversational Response Generation](https://arxiv.org/abs/1911.00536) by Yizhe Zhang, Siqi Sun, Michel Galley, Yen-Chun Chen, Chris Brockett, Xiang Gao, Jianfeng Gao, Jingjing Liu, Bill Dolan.
-1. **[DistilBERT](model_doc/distilbert)** (from HuggingFace), released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter](https://arxiv.org/abs/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/tree/main/examples/research_projects/distillation), RoBERTa into [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/research_projects/distillation), Multilingual BERT into [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/research_projects/distillation) and a German version of DistilBERT.
-1. **[DPR](model_doc/dpr)** (from Facebook) released with the paper [Dense Passage Retrieval for Open-Domain Question Answering](https://arxiv.org/abs/2004.04906) by Vladimir Karpukhin, Barlas OÄuz, Sewon Min, Patrick Lewis, Ledell Wu, Sergey Edunov, Danqi Chen, and Wen-tau Yih.
-1. **[DPT](master/model_doc/dpt)** (from Intel Labs) released with the paper [Vision Transformers for Dense Prediction](https://arxiv.org/abs/2103.13413) by René Ranftl, Alexey Bochkovskiy, Vladlen Koltun.
-1. **[EfficientNet](model_doc/efficientnet)** (from Google Research) released with the paper [EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks](https://arxiv.org/abs/1905.11946) by Mingxing Tan and Quoc V. Le.
-1. **[EncoderDecoder](model_doc/encoder-decoder)** (from Google Research) released with the paper [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://arxiv.org/abs/1907.12461) by Sascha Rothe, Shashi Narayan, Aliaksei Severyn.
-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://arxiv.org/abs/2003.10555) by Kevin Clark, Minh-Thang Luong, Quoc V. Le, Christopher D. Manning.
-1. **[FlauBERT](model_doc/flaubert)** (from CNRS) released with the paper [FlauBERT: Unsupervised Language Model Pre-training for French](https://arxiv.org/abs/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.
-1. **[FNet](model_doc/fnet)** (from Google Research) released with the paper [FNet: Mixing Tokens with Fourier Transforms](https://arxiv.org/abs/2105.03824) by James Lee-Thorp, Joshua Ainslie, Ilya Eckstein, Santiago Ontanon.
-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://arxiv.org/abs/2006.03236) by Zihang Dai, Guokun Lai, Yiming Yang, Quoc V. Le.
-1. **[GLPN](model_doc/glpn)** (from KAIST) released with the paper [Global-Local Path Networks for Monocular Depth Estimation with Vertical CutDepth](https://arxiv.org/abs/2201.07436) by Doyeon Kim, Woonghyun Ga, Pyungwhan Ahn, Donggyu Joo, Sehwan Chun, Junmo Kim.
-1. **[GPT](model_doc/openai-gpt)** (from OpenAI) released with the paper [Improving Language Understanding by Generative Pre-Training](https://blog.openai.com/language-unsupervised/) by Alec Radford, Karthik Narasimhan, Tim Salimans and Ilya Sutskever.
-1. **[GPT-2](model_doc/gpt2)** (from OpenAI) released with the paper [Language Models are Unsupervised Multitask Learners](https://blog.openai.com/better-language-models/) by Alec Radford*, Jeffrey Wu*, Rewon Child, David Luan, Dario Amodei** and Ilya Sutskever**.
-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.
-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.
-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).
-1. **[Hubert](model_doc/hubert)** (from Facebook) released with the paper [HuBERT: Self-Supervised Speech Representation Learning by Masked Prediction of Hidden Units](https://arxiv.org/abs/2106.07447) by Wei-Ning Hsu, Benjamin Bolte, Yao-Hung Hubert Tsai, Kushal Lakhotia, Ruslan Salakhutdinov, Abdelrahman Mohamed.
-1. **[I-BERT](model_doc/ibert)** (from Berkeley) released with the paper [I-BERT: Integer-only BERT Quantization](https://arxiv.org/abs/2101.01321) by Sehoon Kim, Amir Gholami, Zhewei Yao, Michael W. Mahoney, Kurt Keutzer.
-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.
-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://arxiv.org/abs/1912.13318) by Yiheng Xu, Minghao Li, Lei Cui, Shaohan Huang, Furu Wei, Ming Zhou.
-1. **[LayoutLMv2](model_doc/layoutlmv2)** (from Microsoft Research Asia) released with the paper [LayoutLMv2: Multi-modal Pre-training for Visually-Rich Document Understanding](https://arxiv.org/abs/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.
-1. **[LayoutXLM](model_doc/layoutxlm)** (from Microsoft Research Asia) released with the paper [LayoutXLM: Multimodal Pre-training for Multilingual Visually-rich Document Understanding](https://arxiv.org/abs/2104.08836) by Yiheng Xu, Tengchao Lv, Lei Cui, Guoxin Wang, Yijuan Lu, Dinei Florencio, Cha Zhang, Furu Wei.
-1. **[LED](model_doc/led)** (from AllenAI) released with the paper [Longformer: The Long-Document Transformer](https://arxiv.org/abs/2004.05150) by Iz Beltagy, Matthew E. Peters, Arman Cohan.
-1. **[Longformer](model_doc/longformer)** (from AllenAI) released with the paper [Longformer: The Long-Document Transformer](https://arxiv.org/abs/2004.05150) by Iz Beltagy, Matthew E. Peters, Arman Cohan.
-1. **[LUKE](model_doc/luke)** (from Studio Ousia) released with the paper [LUKE: Deep Contextualized Entity Representations with Entity-aware Self-attention](https://arxiv.org/abs/2010.01057) by Ikuya Yamada, Akari Asai, Hiroyuki Shindo, Hideaki Takeda, Yuji Matsumoto.
-1. **[mLUKE](model_doc/mluke)** (from Studio Ousia) released with the paper [mLUKE: The Power of Entity Representations in Multilingual Pretrained Language Models](https://arxiv.org/abs/2110.08151) by Ryokan Ri, Ikuya Yamada, and Yoshimasa Tsuruoka.
-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://arxiv.org/abs/1908.07490) by Hao Tan and Mohit Bansal.
-1. **[M2M100](model_doc/m2m_100)** (from Facebook) released with the paper [Beyond English-Centric Multilingual Machine Translation](https://arxiv.org/abs/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.
-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.
-1. **[Mask2Former](model_doc/mask2former)** (from FAIR and UIUC) released with the paper [Masked-attention Mask Transformer for Universal Image Segmentation](https://arxiv.org/abs/2112.01527) by Bowen Cheng, Ishan Misra, Alexander G. Schwing, Alexander Kirillov, Rohit Girdhar.
-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://arxiv.org/abs/2107.06278) by Bowen Cheng, Alexander G. Schwing, Alexander Kirillov.
-1. **[MBart](model_doc/mbart)** (from Facebook) released with the paper [Multilingual Denoising Pre-training for Neural Machine Translation](https://arxiv.org/abs/2001.08210) by Yinhan Liu, Jiatao Gu, Naman Goyal, Xian Li, Sergey Edunov, Marjan Ghazvininejad, Mike Lewis, Luke Zettlemoyer.
-1. **[MBart-50](model_doc/mbart)** (from Facebook) released with the paper [Multilingual Translation with Extensible Multilingual Pretraining and Finetuning](https://arxiv.org/abs/2008.00401) by Yuqing Tang, Chau Tran, Xian Li, Peng-Jen Chen, Naman Goyal, Vishrav Chaudhary, Jiatao Gu, Angela Fan.
-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://arxiv.org/abs/1909.08053) by Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper and Bryan Catanzaro.
-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://arxiv.org/abs/1909.08053) by Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper and Bryan Catanzaro.
-1. **[MPNet](model_doc/mpnet)** (from Microsoft Research) released with the paper [MPNet: Masked and Permuted Pre-training for Language Understanding](https://arxiv.org/abs/2004.09297) by Kaitao Song, Xu Tan, Tao Qin, Jianfeng Lu, Tie-Yan Liu.
-1. **[MT5](model_doc/mt5)** (from Google AI) released with the paper [mT5: A massively multilingual pre-trained text-to-text transformer](https://arxiv.org/abs/2010.11934) by Linting Xue, Noah Constant, Adam Roberts, Mihir Kale, Rami Al-Rfou, Aditya Siddhant, Aditya Barua, Colin Raffel.
-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://arxiv.org/abs/2102.03902) by Yunyang Xiong, Zhanpeng Zeng, Rudrasis Chakraborty, Mingxing Tan, Glenn Fung, Yin Li, Vikas Singh.
-1. **[OneFormer](model_doc/oneformer)** (from SHI Labs) released with the paper [OneFormer: One Transformer to Rule Universal Image Segmentation](https://arxiv.org/abs/2211.06220) by Jitesh Jain, Jiachen Li, MangTik Chiu, Ali Hassani, Nikita Orlov, Humphrey Shi.
-1. **[Pegasus](model_doc/pegasus)** (from Google) released with the paper [PEGASUS: Pre-training with Extracted Gap-sentences for Abstractive Summarization](https://arxiv.org/abs/1912.08777) by Jingqing Zhang, Yao Zhao, Mohammad Saleh and Peter J. Liu.
-1. **[Perceiver IO](model_doc/perceiver)** (from Deepmind) released with the paper [Perceiver IO: A General Architecture for Structured Inputs & Outputs](https://arxiv.org/abs/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.
-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.
-1. **[PLBart](model_doc/plbart)** (from UCLA NLP) released with the paper [Unified Pre-training for Program Understanding and Generation](https://arxiv.org/abs/2103.06333) by Wasi Uddin Ahmad, Saikat Chakraborty, Baishakhi Ray, Kai-Wei Chang.
-1. **[PoolFormer](model_doc/poolformer)** (from Sea AI Labs) released with the paper [MetaFormer is Actually What You Need for Vision](https://arxiv.org/abs/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.
-1. **[ProphetNet](model_doc/prophetnet)** (from Microsoft Research) released with the paper [ProphetNet: Predicting Future N-gram for Sequence-to-Sequence Pre-training](https://arxiv.org/abs/2001.04063) by Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang and Ming Zhou.
-1. **[QDQBert](model_doc/qdqbert)** (from NVIDIA) released with the paper [Integer Quantization for Deep Learning Inference: Principles and Empirical Evaluation](https://arxiv.org/abs/2004.09602) by Hao Wu, Patrick Judd, Xiaojie Zhang, Mikhail Isaev and Paulius Micikevicius.
-1. **[REALM](model_doc/realm.html)** (from Google Research) released with the paper [REALM: Retrieval-Augmented Language Model Pre-Training](https://arxiv.org/abs/2002.08909) by Kelvin Guu, Kenton Lee, Zora Tung, Panupong Pasupat and Ming-Wei Chang.
-1. **[Reformer](model_doc/reformer)** (from Google Research) released with the paper [Reformer: The Efficient Transformer](https://arxiv.org/abs/2001.04451) by Nikita Kitaev, Ćukasz Kaiser, Anselm Levskaya.
-1. **[RemBERT](model_doc/rembert)** (from Google Research) released with the paper [Rethinking embedding coupling in pre-trained language models](https://arxiv.org/abs/2010.12821) by Hyung Won Chung, Thibault Févry, Henry Tsai, M. Johnson, Sebastian Ruder.
-1. **[RegNet](model_doc/regnet)** (from META Platforms) released with the paper [Designing Network Design Space](https://arxiv.org/abs/2003.13678) by Ilija Radosavovic, Raj Prateek Kosaraju, Ross Girshick, Kaiming He, Piotr DollĂĄr.
-1. **[ResNet](model_doc/resnet)** (from Microsoft Research) released with the paper [Deep Residual Learning for Image Recognition](https://arxiv.org/abs/1512.03385) by Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun.
-1. **[RoBERTa](model_doc/roberta)** (from Facebook), released together with the paper [RoBERTa: A Robustly Optimized BERT Pretraining Approach](https://arxiv.org/abs/1907.11692) by Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Mandar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, Veselin Stoyanov.
-1. **[RoFormer](model_doc/roformer)** (from ZhuiyiTechnology), released together with the paper [RoFormer: Enhanced Transformer with Rotary Position Embedding](https://arxiv.org/abs/2104.09864) by Jianlin Su and Yu Lu and Shengfeng Pan and Bo Wen and Yunfeng Liu.
-1. **[SegFormer](model_doc/segformer)** (from NVIDIA) released with the paper [SegFormer: Simple and Efficient Design for Semantic Segmentation with Transformers](https://arxiv.org/abs/2105.15203) by Enze Xie, Wenhai Wang, Zhiding Yu, Anima Anandkumar, Jose M. Alvarez, Ping Luo.
-1. **[SEW](model_doc/sew)** (from ASAPP) released with the paper [Performance-Efficiency Trade-offs in Unsupervised Pre-training for Speech Recognition](https://arxiv.org/abs/2109.06870) by Felix Wu, Kwangyoun Kim, Jing Pan, Kyu Han, Kilian Q. Weinberger, Yoav Artzi.
-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://arxiv.org/abs/2109.06870) by Felix Wu, Kwangyoun Kim, Jing Pan, Kyu Han, Kilian Q. Weinberger, Yoav Artzi.
-1. **[SpeechToTextTransformer](model_doc/speech_to_text)** (from Facebook), released together with the paper [fairseq S2T: Fast Speech-to-Text Modeling with fairseq](https://arxiv.org/abs/2010.05171) by Changhan Wang, Yun Tang, Xutai Ma, Anne Wu, Dmytro Okhonko, Juan Pino.
-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://arxiv.org/abs/2104.06678) by Changhan Wang, Anne Wu, Juan Pino, Alexei Baevski, Michael Auli, Alexis Conneau.
-1. **[Splinter](model_doc/splinter)** (from Tel Aviv University), released together with the paper [Few-Shot Question Answering by Pretraining Span Selection](https://arxiv.org/abs/2101.00438) by Ori Ram, Yuval Kirstain, Jonathan Berant, Amir Globerson, Omer Levy.
-1. **[SqueezeBert](model_doc/squeezebert)** (from Berkeley) released with the paper [SqueezeBERT: What can computer vision teach NLP about efficient neural networks?](https://arxiv.org/abs/2006.11316) by Forrest N. Iandola, Albert E. Shaw, Ravi Krishna, and Kurt W. Keutzer.
-1. **[Swin Transformer](model_doc/swin)** (from Microsoft) released with the paper [Swin Transformer: Hierarchical Vision Transformer using Shifted Windows](https://arxiv.org/abs/2103.14030) by Ze Liu, Yutong Lin, Yue Cao, Han Hu, Yixuan Wei, Zheng Zhang, Stephen Lin, Baining Guo.
-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://arxiv.org/abs/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.
-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.
-1. **[TAPAS](model_doc/tapas)** (from Google AI) released with the paper [TAPAS: Weakly Supervised Table Parsing via Pre-training](https://arxiv.org/abs/2004.02349) by Jonathan Herzig, PaweĆ Krzysztof Nowak, Thomas MĂŒller, Francesco Piccinno and Julian Martin Eisenschlos.
-1. **[TAPEX](model_doc/tapex)** (from Microsoft Research) released with the paper [TAPEX: Table Pre-training via Learning a Neural SQL Executor](https://arxiv.org/abs/2107.07653) by Qian Liu, Bei Chen, Jiaqi Guo, Morteza Ziyadi, Zeqi Lin, Weizhu Chen, Jian-Guang Lou.
-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://arxiv.org/abs/1901.02860) by Zihang Dai*, Zhilin Yang*, Yiming Yang, Jaime Carbonell, Quoc V. Le, Ruslan Salakhutdinov.
-1. **[TrOCR](model_doc/trocr)** (from Microsoft), released together with the paper [TrOCR: Transformer-based Optical Character Recognition with Pre-trained Models](https://arxiv.org/abs/2109.10282) by Minghao Li, Tengchao Lv, Lei Cui, Yijuan Lu, Dinei Florencio, Cha Zhang, Zhoujun Li, Furu Wei.
-1. **[UniSpeech](model_doc/unispeech)** (from Microsoft Research) released with the paper [UniSpeech: Unified Speech Representation Learning with Labeled and Unlabeled Data](https://arxiv.org/abs/2101.07597) by Chengyi Wang, Yu Wu, Yao Qian, Kenichi Kumatani, Shujie Liu, Furu Wei, Michael Zeng, Xuedong Huang.
-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://arxiv.org/abs/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.
-1. **[VAN](model_doc/van)** (from Tsinghua University and Nankai University) released with the paper [Visual Attention Network](https://arxiv.org/abs/2202.09741) by Meng-Hao Guo, Cheng-Ze Lu, Zheng-Ning Liu, Ming-Ming Cheng, Shi-Min Hu.
-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://arxiv.org/abs/2102.03334) by Wonjae Kim, Bokyung Son, Ildoo Kim.
-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://arxiv.org/abs/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.
-1. **[ViTMAE](model_doc/vit_mae)** (from Meta AI) released with the paper [Masked Autoencoders Are Scalable Vision Learners](https://arxiv.org/abs/2111.06377) by Kaiming He, Xinlei Chen, Saining Xie, Yanghao Li, Piotr DollĂĄr, Ross Girshick.
-1. **[VisualBERT](model_doc/visual_bert)** (from UCLA NLP) released with the paper [VisualBERT: A Simple and Performant Baseline for Vision and Language](https://arxiv.org/pdf/1908.03557) by Liunian Harold Li, Mark Yatskar, Da Yin, Cho-Jui Hsieh, Kai-Wei Chang.
-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://arxiv.org/abs/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.
-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://arxiv.org/abs/2006.11477) by Alexei Baevski, Henry Zhou, Abdelrahman Mohamed, Michael Auli.
-1. **[Wav2Vec2Phoneme](model_doc/wav2vec2_phoneme)** (from Facebook AI) released with the paper [Simple and Effective Zero-shot Cross-lingual Phoneme Recognition](https://arxiv.org/abs/2109.11680) by Qiantong Xu, Alexei Baevski, Michael Auli.
-1. **[XGLM](model_doc/xglm)** (From Facebook AI) released with the paper [Few-shot Learning with Multilingual Language Models](https://arxiv.org/abs/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.
-1. **[XLM](model_doc/xlm)** (from Facebook) released together with the paper [Cross-lingual Language Model Pretraining](https://arxiv.org/abs/1901.07291) by Guillaume Lample and Alexis Conneau.
-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://arxiv.org/abs/2001.04063) by Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang and Ming Zhou.
-1. **[XLM-RoBERTa](model_doc/xlm-roberta)** (from Facebook AI), released together with the paper [Unsupervised Cross-lingual Representation Learning at Scale](https://arxiv.org/abs/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.
-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://arxiv.org/abs/2105.00572) by Naman Goyal, Jingfei Du, Myle Ott, Giri Anantharaman, Alexis Conneau.
-1. **[XLNet](model_doc/xlnet)** (from Google/CMU) released with the paper [âXLNet: Generalized Autoregressive Pretraining for Language Understanding](https://arxiv.org/abs/1906.08237) by Zhilin Yang*, Zihang Dai*, Yiming Yang, Jaime Carbonell, Ruslan Salakhutdinov, Quoc V. Le.
-1. **[XLSR-Wav2Vec2](model_doc/xlsr_wav2vec2)** (from Facebook AI) released with the paper [Unsupervised Cross-Lingual Representation Learning For Speech Recognition](https://arxiv.org/abs/2006.13979) by Alexis Conneau, Alexei Baevski, Ronan Collobert, Abdelrahman Mohamed, Michael Auli.
-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://arxiv.org/abs/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.
-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://arxiv.org/abs/2111.09714) by Zhanpeng Zeng, Yunyang Xiong, Sathya N. Ravi, Shailesh Acharya, Glenn Fung, Vikas Singh.
-
-
-### Frameworks aceitos
-
-A tabela abaixo representa a lista de suporte na biblioteca para cada um dos seguintes modelos, caso tenham um tokenizer
-do Python (chamado de "slow"), ou um tokenizer construĂdo em cima da biblioteca đ€ Tokenizers (chamado de "fast"). AlĂ©m
-disso, sĂŁo diferenciados pelo suporte em diferentes frameworks: JAX (por meio do Flax); PyTorch; e/ou Tensorflow.
-
-
-
-| Model | Tokenizer slow | Tokenizer fast | PyTorch support | TensorFlow support | Flax Support |
-|:---------------------------:|:--------------:|:--------------:|:---------------:|:------------------:|:------------:|
-| ALBERT | â
| â
| â
| â
| â
|
-| BART | â
| â
| â
| â
| â
|
-| BEiT | â | â | â
| â | â
|
-| BERT | â
| â
| â
| â
| â
|
-| Bert Generation | â
| â | â
| â | â |
-| BigBird | â
| â
| â
| â | â
|
-| BigBirdPegasus | â | â | â
| â | â |
-| Blenderbot | â
| â
| â
| â
| â
|
-| BlenderbotSmall | â
| â
| â
| â
| â
|
-| CamemBERT | â
| â
| â
| â
| â |
-| Canine | â
| â | â
| â | â |
-| CLIP | â
| â
| â
| â
| â
|
-| ConvBERT | â
| â
| â
| â
| â |
-| ConvNext | â | â | â
| â
| â |
-| CTRL | â
| â | â
| â
| â |
-| Data2VecAudio | â | â | â
| â | â |
-| Data2VecText | â | â | â
| â | â |
-| Data2VecVision | â | â | â
| â | â |
-| DeBERTa | â
| â
| â
| â
| â |
-| DeBERTa-v2 | â
| â
| â
| â
| â |
-| Decision Transformer | â | â | â
| â | â |
-| DeiT | â | â | â
| â | â |
-| DETR | â | â | â
| â | â |
-| DistilBERT | â
| â
| â
| â
| â
|
-| DPR | â
| â
| â
| â
| â |
-| DPT | â | â | â
| â | â |
-| ELECTRA | â
| â
| â
| â
| â
|
-| Encoder decoder | â | â | â
| â
| â
|
-| FairSeq Machine-Translation | â
| â | â
| â | â |
-| FlauBERT | â
| â | â
| â
| â |
-| FNet | â
| â
| â
| â | â |
-| Funnel Transformer | â
| â
| â
| â
| â |
-| GLPN | â | â | â
| â | â |
-| GPT Neo | â | â | â
| â | â
|
-| GPT-J | â | â | â
| â
| â
|
-| Hubert | â | â | â
| â
| â |
-| I-BERT | â | â | â
| â | â |
-| ImageGPT | â | â | â
| â | â |
-| LayoutLM | â
| â
| â
| â
| â |
-| LayoutLMv2 | â
| â
| â
| â | â |
-| LED | â
| â
| â
| â
| â |
-| Longformer | â
| â
| â
| â
| â |
-| LUKE | â
| â | â
| â | â |
-| LXMERT | â
| â
| â
| â
| â |
-| M2M100 | â
| â | â
| â | â |
-| Marian | â
| â | â
| â
| â
|
-| MaskFormer | â | â | â
| â | â |
-| mBART | â
| â
| â
| â
| â
|
-| MegatronBert | â | â | â
| â | â |
-| MobileBERT | â
| â
| â
| â
| â |
-| MPNet | â
| â
| â
| â
| â |
-| mT5 | â
| â
| â
| â
| â
|
-| Nystromformer | â | â | â
| â | â |
-| OpenAI GPT | â
| â
| â
| â
| â |
-| OpenAI GPT-2 | â
| â
| â
| â
| â
|
-| Pegasus | â
| â
| â
| â
| â
|
-| Perceiver | â
| â | â
| â | â |
-| PLBart | â
| â | â
| â | â |
-| PoolFormer | â | â | â
| â | â |
-| ProphetNet | â
| â | â
| â | â |
-| QDQBert | â | â | â
| â | â |
-| RAG | â
| â | â
| â
| â |
-| Realm | â
| â
| â
| â | â |
-| Reformer | â
| â
| â
| â | â |
-| RegNet | â | â | â
| â
| â
|
-| RemBERT | â
| â
| â
| â
| â |
-| ResNet | â | â | â
| â | â
|
-| RetriBERT | â
| â
| â
| â | â |
-| RoBERTa | â
| â
| â
| â
| â
|
-| RoFormer | â
| â
| â
| â
| â
|
-| SegFormer | â | â | â
| â | â |
-| SEW | â | â | â
| â | â |
-| SEW-D | â | â | â
| â | â |
-| Speech Encoder decoder | â | â | â
| â | â
|
-| Speech2Text | â
| â | â
| â
| â |
-| Speech2Text2 | â
| â | â | â | â |
-| Splinter | â
| â
| â
| â | â |
-| SqueezeBERT | â
| â
| â
| â | â |
-| Swin | â | â | â
| â | â |
-| T5 | â
| â
| â
| â
| â
|
-| TAPAS | â
| â | â
| â
| â |
-| TAPEX | â
| â
| â
| â
| â
|
-| Transformer-XL | â
| â | â
| â
| â |
-| TrOCR | â | â | â
| â | â |
-| UniSpeech | â | â | â
| â | â |
-| UniSpeechSat | â | â | â
| â | â |
-| VAN | â | â | â
| â | â |
-| ViLT | â | â | â
| â | â |
-| Vision Encoder decoder | â | â | â
| â
| â
|
-| VisionTextDualEncoder | â | â | â
| â | â
|
-| VisualBert | â | â | â
| â | â |
-| ViT | â | â | â
| â
| â
|
-| ViTMAE | â | â | â
| â
| â |
-| Wav2Vec2 | â
| â | â
| â
| â
|
-| WavLM | â | â | â
| â | â |
-| XGLM | â
| â
| â
| â | â
|
-| XLM | â
| â | â
| â
| â |
-| XLM-RoBERTa | â
| â
| â
| â
| â
|
-| XLM-RoBERTa-XL | â | â | â
| â | â |
-| XLMProphetNet | â
| â | â
| â | â |
-| XLNet | â
| â
| â
| â
| â |
-| YOSO | â | â | â
| â | â |
-
-
diff --git a/docs/source/pt/installation.md b/docs/source/pt/installation.md
new file mode 100644
index 000000000000..15b59f7d8768
--- /dev/null
+++ b/docs/source/pt/installation.md
@@ -0,0 +1,262 @@
+
+
+# Guia de Instalação
+
+Neste guia poderĂĄ encontrar informaçÔes para a instalação do đ€ Transformers para qualquer biblioteca de
+Machine Learning com a qual esteja a trabalhar. AlĂ©m disso, poderĂĄ encontrar informaçÔes sobre como gerar cachĂȘs e
+configurar o đ€ Transformers para execução em modo offline (opcional).
+
+đ€ Transformers foi testado com Python 3.6+, PyTorch 1.1.0+, TensorFlow 2.0+, e Flax. Para instalar a biblioteca de
+deep learning com que deseja trabalhar, siga as instruçÔes correspondentes listadas a seguir:
+
+* [PyTorch](https://pytorch.org/get-started/locally/)
+* [TensorFlow 2.0](https://www.tensorflow.org/install/pip)
+* [Flax](https://flax.readthedocs.io/en/latest/)
+
+## Instalação pelo Pip
+
+Ă sugerido instalar o đ€ Transformers num [ambiente virtual](https://docs.python.org/3/library/venv.html). Se precisar
+de mais informaçÔes sobre ambientes virtuais em Python, consulte este [guia](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/).
+Um ambiente virtual facilitarĂĄ a manipulação e organização de projetos e evita problemas de compatibilidade entre dependĂȘncias.
+
+Comece criando um ambiente virtual no diretĂłrio do seu projeto:
+
+```bash
+python -m venv .env
+```
+
+E para ativar o ambiente virtual:
+
+```bash
+source .env/bin/activate
+```
+
+Agora Ă possĂvel instalar o đ€ Transformers com o comando a seguir:
+
+```bash
+pip install transformers
+```
+
+Somente para a CPU, Ă© possĂvel instalar o đ€ Transformers e a biblioteca de deep learning respectiva apenas numa linha.
+
+Por exemplo, para instalar o đ€ Transformers e o PyTorch, digite:
+
+```bash
+pip install transformers[torch]
+```
+
+đ€ Transformers e TensorFlow 2.0:
+
+```bash
+pip install transformers[tf-cpu]
+```
+
+đ€ Transformers e Flax:
+
+```bash
+pip install transformers[flax]
+```
+
+Por Ășltimo, verifique se o đ€ Transformers foi instalado com sucesso usando o seguinte comando para baixar um modelo prĂ©-treinado:
+
+```bash
+python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('we love you'))"
+```
+
+Em seguida, imprima um rótulo e sua pontuação:
+
+```bash
+[{'label': 'POSITIVE', 'score': 0.9998704791069031}]
+```
+
+## Instalação usando a fonte
+
+Para instalar o đ€ Transformers a partir da fonte use o seguinte comando:
+
+```bash
+pip install git+https://github.com/huggingface/transformers
+```
+
+O comando acima instalarĂĄ a versĂŁo `master` mais atual em vez da Ășltima versĂŁo estĂĄvel. A versĂŁo `master` Ă© Ăștil para
+utilizar os Ășltimos updates contidos em đ€ Transformers. Por exemplo, um erro recente pode ter sido corrigido somente
+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.
+A equipa trata de mantér a versão `master` operacional e a maioria dos erros são resolvidos em poucas horas ou dias.
+Se encontrar quaisquer problemas, por favor abra um [Issue](https://github.com/huggingface/transformers/issues) para que o
+mesmo possa ser corrigido o mais rĂĄpido possĂvel.
+
+Verifique que o đ€ Transformers estĂĄ instalado corretamente usando o seguinte comando:
+
+```bash
+python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('I love you'))"
+```
+
+## Instalação editåvel
+
+Uma instalação editåvel serå necessåria caso desejas um dos seguintes:
+* Usar a versĂŁo `master` do cĂłdigo fonte.
+* Contribuir ao đ€ Transformers e precisa testar mudanças ao cĂłdigo.
+
+Para tal, clone o repositĂłrio e instale o đ€ Transformers com os seguintes comandos:
+
+```bash
+git clone https://github.com/huggingface/transformers.git
+cd transformers
+pip install -e .
+```
+
+Estes comandos vĂŁo ligar o diretĂłrio para o qual foi clonado o repositĂłrio ao caminho de bibliotecas do Python.
+O Python agora buscarå dentro dos arquivos que foram clonados além dos caminhos normais da biblioteca.
+Por exemplo, se os pacotes do Python se encontram instalados no caminho `~/anaconda3/envs/main/lib/python3.7/site-packages/`,
+o Python também buscarå módulos no diretório onde clonamos o repositório `~/transformers/`.
+
+
+
+Ă necessĂĄrio manter o diretĂłrio `transformers` se desejas continuar usando a biblioteca.
+
+
+
+Assim, Ă possĂvel atualizar sua cĂłpia local para com a Ășltima versĂŁo do đ€ Transformers com o seguinte comando:
+
+```bash
+cd ~/transformers/
+git pull
+```
+
+O ambiente de Python que foi criado para a instalação do đ€ Transformers encontrarĂĄ a versĂŁo `master` em execuçÔes seguintes.
+
+## Instalação usando o Conda
+
+Ă possĂvel instalar o đ€ Transformers a partir do canal conda `huggingface` com o seguinte comando:
+
+```bash
+conda install -c huggingface transformers
+```
+
+## Configuração do CachĂȘ
+
+Os modelos prĂ©-treinados sĂŁo baixados e armazenados no cachĂȘ local, encontrado em `~/.cache/huggingface/transformers/`.
+Este Ă© o diretĂłrio padrĂŁo determinado pela variĂĄvel `TRANSFORMERS_CACHE` dentro do shell.
+No Windows, este diretório pré-definido é dado por `C:\Users\username\.cache\huggingface\transformers`.
+Ă possĂvel mudar as variĂĄveis dentro do shell em ordem de prioridade para especificar um diretĂłrio de cachĂȘ diferente:
+
+1. VariĂĄvel de ambiente do shell (por padrĂŁo): `TRANSFORMERS_CACHE`.
+2. VariĂĄvel de ambiente do shell:`HF_HOME` + `transformers/`.
+3. VariĂĄvel de ambiente do shell: `XDG_CACHE_HOME` + `/huggingface/transformers`.
+
+
+
+ O đ€ Transformers usarĂĄ as variĂĄveis de ambiente do shell `PYTORCH_TRANSFORMERS_CACHE` ou `PYTORCH_PRETRAINED_BERT_CACHE`
+ se estiver vindo de uma versĂŁo anterior da biblioteca que tenha configurado essas variĂĄveis de ambiente, a menos que
+ vocĂȘ especifique a variĂĄvel de ambiente do shell `TRANSFORMERS_CACHE`.
+
+
+
+
+## Modo Offline
+
+O đ€ Transformers tambĂ©m pode ser executado num ambiente de firewall ou fora da rede (offline) usando arquivos locais.
+Para tal, configure a variĂĄvel de ambiente de modo que `TRANSFORMERS_OFFLINE=1`.
+
+
+
+VocĂȘ pode adicionar o [đ€ Datasets](https://huggingface.co/docs/datasets/) ao pipeline de treinamento offline declarando
+ a variĂĄvel de ambiente `HF_DATASETS_OFFLINE=1`.
+
+
+
+Segue um exemplo de execução do programa numa rede padrão com firewall para instùncias externas, usando o seguinte comando:
+
+```bash
+python examples/pytorch/translation/run_translation.py --model_name_or_path t5-small --dataset_name wmt16 --dataset_config ro-en ...
+```
+
+Execute esse mesmo programa numa instĂąncia offline com o seguinte comando:
+
+```bash
+HF_DATASETS_OFFLINE=1 TRANSFORMERS_OFFLINE=1 \
+python examples/pytorch/translation/run_translation.py --model_name_or_path t5-small --dataset_name wmt16 --dataset_config ro-en ...
+```
+
+O script agora deve ser executado sem travar ou expirar, pois procurarĂĄ apenas por arquivos locais.
+
+### Obtendo modelos e tokenizers para uso offline
+
+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:
+
+* Baixe um arquivo por meio da interface de usuĂĄrio do [Model Hub](https://huggingface.co/models) clicando no Ăcone â.
+
+ 
+
+
+* Use o pipeline do [`PreTrainedModel.from_pretrained`] e [`PreTrainedModel.save_pretrained`]:
+ 1. Baixa os arquivos previamente com [`PreTrainedModel.from_pretrained`]:
+
+ ```py
+ >>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("bigscience/T0_3B")
+ >>> model = AutoModelForSeq2SeqLM.from_pretrained("bigscience/T0_3B")
+ ```
+
+
+ 2. Salve os arquivos em um diretĂłrio especĂfico com [`PreTrainedModel.save_pretrained`]:
+
+ ```py
+ >>> tokenizer.save_pretrained("./your/path/bigscience_t0")
+ >>> model.save_pretrained("./your/path/bigscience_t0")
+ ```
+
+ 3. Quando estiver offline, acesse os arquivos com [`PreTrainedModel.from_pretrained`] do diretĂłrio especificado:
+
+ ```py
+ >>> tokenizer = AutoTokenizer.from_pretrained("./your/path/bigscience_t0")
+ >>> model = AutoModel.from_pretrained("./your/path/bigscience_t0")
+ ```
+
+* Baixando arquivos programaticamente com a biblioteca [huggingface_hub](https://github.com/huggingface/huggingface_hub/tree/main/src/huggingface_hub):
+
+ 1. Instale a biblioteca [huggingface_hub](https://github.com/huggingface/huggingface_hub/tree/main/src/huggingface_hub) em seu ambiente virtual:
+
+ ```bash
+ python -m pip install huggingface_hub
+ ```
+
+ 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:
+
+ ```py
+ >>> from huggingface_hub import hf_hub_download
+
+ >>> hf_hub_download(repo_id="bigscience/T0_3B", filename="config.json", cache_dir="./your/path/bigscience_t0")
+ ```
+
+Depois que o arquivo for baixado e armazenado no cachĂȘ local, especifique seu caminho local para carregĂĄ-lo e usĂĄ-lo:
+
+```py
+>>> from transformers import AutoConfig
+
+>>> config = AutoConfig.from_pretrained("./your/path/bigscience_t0/config.json")
+```
+
+
+
+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).
+
+
diff --git a/docs/source/pt/installation.mdx b/docs/source/pt/installation.mdx
deleted file mode 100644
index 2325cc74afe2..000000000000
--- a/docs/source/pt/installation.mdx
+++ /dev/null
@@ -1,258 +0,0 @@
-
-
-# Guia de Instalação
-
-Neste guia poderĂĄ encontrar informaçÔes para a instalação do đ€ Transformers para qualquer biblioteca de
-Machine Learning com a qual esteja a trabalhar. AlĂ©m disso, poderĂĄ encontrar informaçÔes sobre como gerar cachĂȘs e
-configurar o đ€ Transformers para execução em modo offline (opcional).
-
-đ€ Transformers foi testado com Python 3.6+, PyTorch 1.1.0+, TensorFlow 2.0+, e Flax. Para instalar a biblioteca de
-deep learning com que deseja trabalhar, siga as instruçÔes correspondentes listadas a seguir:
-
-* [PyTorch](https://pytorch.org/get-started/locally/)
-* [TensorFlow 2.0](https://www.tensorflow.org/install/pip)
-* [Flax](https://flax.readthedocs.io/en/latest/)
-
-## Instalação pelo Pip
-
-Ă sugerido instalar o đ€ Transformers num [ambiente virtual](https://docs.python.org/3/library/venv.html). Se precisar
-de mais informaçÔes sobre ambientes virtuais em Python, consulte este [guia](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/).
-Um ambiente virtual facilitarĂĄ a manipulação e organização de projetos e evita problemas de compatibilidade entre dependĂȘncias.
-
-Comece criando um ambiente virtual no diretĂłrio do seu projeto:
-
-```bash
-python -m venv .env
-```
-
-E para ativar o ambiente virtual:
-
-```bash
-source .env/bin/activate
-```
-
-Agora Ă possĂvel instalar o đ€ Transformers com o comando a seguir:
-
-```bash
-pip install transformers
-```
-
-Somente para a CPU, Ă© possĂvel instalar o đ€ Transformers e a biblioteca de deep learning respectiva apenas numa linha.
-
-Por exemplo, para instalar o đ€ Transformers e o PyTorch, digite:
-
-```bash
-pip install transformers[torch]
-```
-
-đ€ Transformers e TensorFlow 2.0:
-
-```bash
-pip install transformers[tf-cpu]
-```
-
-đ€ Transformers e Flax:
-
-```bash
-pip install transformers[flax]
-```
-
-Por Ășltimo, verifique se o đ€ Transformers foi instalado com sucesso usando o seguinte comando para baixar um modelo prĂ©-treinado:
-
-```bash
-python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('we love you'))"
-```
-
-Em seguida, imprima um rótulo e sua pontuação:
-
-```bash
-[{'label': 'POSITIVE', 'score': 0.9998704791069031}]
-```
-
-## Instalação usando a fonte
-
-Para instalar o đ€ Transformers a partir da fonte use o seguinte comando:
-
-```bash
-pip install git+https://github.com/huggingface/transformers
-```
-
-O comando acima instalarĂĄ a versĂŁo `master` mais atual em vez da Ășltima versĂŁo estĂĄvel. A versĂŁo `master` Ă© Ăștil para
-utilizar os Ășltimos updates contidos em đ€ Transformers. Por exemplo, um erro recente pode ter sido corrigido somente
-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.
-A equipa trata de mantér a versão `master` operacional e a maioria dos erros são resolvidos em poucas horas ou dias.
-Se encontrar quaisquer problemas, por favor abra um [Issue](https://github.com/huggingface/transformers/issues) para que o
-mesmo possa ser corrigido o mais rĂĄpido possĂvel.
-
-Verifique que o đ€ Transformers estĂĄ instalado corretamente usando o seguinte comando:
-
-```bash
-python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('I love you'))"
-```
-
-## Instalação editåvel
-
-Uma instalação editåvel serå necessåria caso desejas um dos seguintes:
-* Usar a versĂŁo `master` do cĂłdigo fonte.
-* Contribuir ao đ€ Transformers e precisa testar mudanças ao cĂłdigo.
-
-Para tal, clone o repositĂłrio e instale o đ€ Transformers com os seguintes comandos:
-
-```bash
-git clone https://github.com/huggingface/transformers.git
-cd transformers
-pip install -e .
-```
-
-Estes comandos vĂŁo ligar o diretĂłrio para o qual foi clonado o repositĂłrio ao caminho de bibliotecas do Python.
-O Python agora buscarå dentro dos arquivos que foram clonados além dos caminhos normais da biblioteca.
-Por exemplo, se os pacotes do Python se encontram instalados no caminho `~/anaconda3/envs/main/lib/python3.7/site-packages/`,
-o Python também buscarå módulos no diretório onde clonamos o repositório `~/transformers/`.
-
-
-
-Ă necessĂĄrio manter o diretĂłrio `transformers` se desejas continuar usando a biblioteca.
-
-
-
-Assim, Ă possĂvel atualizar sua cĂłpia local para com a Ășltima versĂŁo do đ€ Transformers com o seguinte comando:
-
-```bash
-cd ~/transformers/
-git pull
-```
-
-O ambiente de Python que foi criado para a instalação do đ€ Transformers encontrarĂĄ a versĂŁo `master` em execuçÔes seguintes.
-
-## Instalação usando o Conda
-
-Ă possĂvel instalar o đ€ Transformers a partir do canal conda `huggingface` com o seguinte comando:
-
-```bash
-conda install -c huggingface transformers
-```
-
-## Configuração do CachĂȘ
-
-Os modelos prĂ©-treinados sĂŁo baixados e armazenados no cachĂȘ local, encontrado em `~/.cache/huggingface/transformers/`.
-Este Ă© o diretĂłrio padrĂŁo determinado pela variĂĄvel `TRANSFORMERS_CACHE` dentro do shell.
-No Windows, este diretório pré-definido é dado por `C:\Users\username\.cache\huggingface\transformers`.
-Ă possĂvel mudar as variĂĄveis dentro do shell em ordem de prioridade para especificar um diretĂłrio de cachĂȘ diferente:
-
-1. VariĂĄvel de ambiente do shell (por padrĂŁo): `TRANSFORMERS_CACHE`.
-2. VariĂĄvel de ambiente do shell:`HF_HOME` + `transformers/`.
-3. VariĂĄvel de ambiente do shell: `XDG_CACHE_HOME` + `/huggingface/transformers`.
-
-
-
- O đ€ Transformers usarĂĄ as variĂĄveis de ambiente do shell `PYTORCH_TRANSFORMERS_CACHE` ou `PYTORCH_PRETRAINED_BERT_CACHE`
- se estiver vindo de uma versĂŁo anterior da biblioteca que tenha configurado essas variĂĄveis de ambiente, a menos que
- vocĂȘ especifique a variĂĄvel de ambiente do shell `TRANSFORMERS_CACHE`.
-
-
-
-
-## Modo Offline
-
-O đ€ Transformers tambĂ©m pode ser executado num ambiente de firewall ou fora da rede (offline) usando arquivos locais.
-Para tal, configure a variĂĄvel de ambiente de modo que `TRANSFORMERS_OFFLINE=1`.
-
-
-
-VocĂȘ pode adicionar o [đ€ Datasets](https://huggingface.co/docs/datasets/) ao pipeline de treinamento offline declarando
- a variĂĄvel de ambiente `HF_DATASETS_OFFLINE=1`.
-
-
-
-Segue um exemplo de execução do programa numa rede padrão com firewall para instùncias externas, usando o seguinte comando:
-
-```bash
-python examples/pytorch/translation/run_translation.py --model_name_or_path t5-small --dataset_name wmt16 --dataset_config ro-en ...
-```
-
-Execute esse mesmo programa numa instĂąncia offline com o seguinte comando:
-
-```bash
-HF_DATASETS_OFFLINE=1 TRANSFORMERS_OFFLINE=1 \
-python examples/pytorch/translation/run_translation.py --model_name_or_path t5-small --dataset_name wmt16 --dataset_config ro-en ...
-```
-
-O script agora deve ser executado sem travar ou expirar, pois procurarĂĄ apenas por arquivos locais.
-
-### Obtendo modelos e tokenizers para uso offline
-
-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:
-
-* Baixe um arquivo por meio da interface de usuĂĄrio do [Model Hub](https://huggingface.co/models) clicando no Ăcone â.
-
- 
-
-
-* Use o pipeline do [`PreTrainedModel.from_pretrained`] e [`PreTrainedModel.save_pretrained`]:
- 1. Baixa os arquivos previamente com [`PreTrainedModel.from_pretrained`]:
-
- ```py
- >>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
-
- >>> tokenizer = AutoTokenizer.from_pretrained("bigscience/T0_3B")
- >>> model = AutoModelForSeq2SeqLM.from_pretrained("bigscience/T0_3B")
- ```
-
-
- 2. Salve os arquivos em um diretĂłrio especĂfico com [`PreTrainedModel.save_pretrained`]:
-
- ```py
- >>> tokenizer.save_pretrained("./your/path/bigscience_t0")
- >>> model.save_pretrained("./your/path/bigscience_t0")
- ```
-
- 3. Quando estiver offline, acesse os arquivos com [`PreTrainedModel.from_pretrained`] do diretĂłrio especificado:
-
- ```py
- >>> tokenizer = AutoTokenizer.from_pretrained("./your/path/bigscience_t0")
- >>> model = AutoModel.from_pretrained("./your/path/bigscience_t0")
- ```
-
-* Baixando arquivos programaticamente com a biblioteca [huggingface_hub](https://github.com/huggingface/huggingface_hub/tree/main/src/huggingface_hub):
-
- 1. Instale a biblioteca [huggingface_hub](https://github.com/huggingface/huggingface_hub/tree/main/src/huggingface_hub) em seu ambiente virtual:
-
- ```bash
- python -m pip install huggingface_hub
- ```
-
- 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:
-
- ```py
- >>> from huggingface_hub import hf_hub_download
-
- >>> hf_hub_download(repo_id="bigscience/T0_3B", filename="config.json", cache_dir="./your/path/bigscience_t0")
- ```
-
-Depois que o arquivo for baixado e armazenado no cachĂȘ local, especifique seu caminho local para carregĂĄ-lo e usĂĄ-lo:
-
-```py
->>> from transformers import AutoConfig
-
->>> config = AutoConfig.from_pretrained("./your/path/bigscience_t0/config.json")
-```
-
-
-
-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).
-
-
diff --git a/docs/source/pt/multilingual.md b/docs/source/pt/multilingual.md
new file mode 100644
index 000000000000..b6366b8c2289
--- /dev/null
+++ b/docs/source/pt/multilingual.md
@@ -0,0 +1,195 @@
+
+
+# Modelos multilinguĂsticos para inferĂȘncia
+
+[[open-in-colab]]
+
+Existem vĂĄrios modelos multilinguĂsticos no đ€ Transformers e seus usos para inferĂȘncia diferem dos modelos monolĂngues.
+No entanto, nem *todos* os usos dos modelos multilĂngues sĂŁo tĂŁo diferentes.
+Alguns modelos, como o [bert-base-multilingual-uncased](https://huggingface.co/bert-base-multilingual-uncased),
+podem ser usados como se fossem monolĂngues. Este guia irĂĄ te ajudar a usar modelos multilĂngues cujo uso difere
+para o propĂłsito de inferĂȘncia.
+
+## XLM
+
+O XLM tem dez checkpoints diferentes dos quais apenas um Ă© monolĂngue.
+Os nove checkpoints restantes do modelo sĂŁo subdivididos em duas categorias:
+checkpoints que usam de language embeddings e os que nĂŁo.
+
+### XLM com language embeddings
+
+Os seguintes modelos de XLM usam language embeddings para especificar a linguagem utilizada para a inferĂȘncia.
+
+- `xlm-mlm-ende-1024` (Masked language modeling, English-German)
+- `xlm-mlm-enfr-1024` (Masked language modeling, English-French)
+- `xlm-mlm-enro-1024` (Masked language modeling, English-Romanian)
+- `xlm-mlm-xnli15-1024` (Masked language modeling, XNLI languages)
+- `xlm-mlm-tlm-xnli15-1024` (Masked language modeling + translation, XNLI languages)
+- `xlm-clm-enfr-1024` (Causal language modeling, English-French)
+- `xlm-clm-ende-1024` (Causal language modeling, English-German)
+
+Os language embeddings sĂŁo representados por um tensor de mesma dimensĂŁo que os `input_ids` passados ao modelo.
+Os valores destes tensores dependem do idioma utilizado e se identificam pelos atributos `lang2id` e `id2lang` do tokenizador.
+
+Neste exemplo, carregamos o checkpoint `xlm-clm-enfr-1024`(Causal language modeling, English-French):
+
+```py
+>>> import torch
+>>> from transformers import XLMTokenizer, XLMWithLMHeadModel
+
+>>> tokenizer = XLMTokenizer.from_pretrained("xlm-clm-enfr-1024")
+>>> model = XLMWithLMHeadModel.from_pretrained("xlm-clm-enfr-1024")
+```
+
+O atributo `lang2id` do tokenizador mostra os idiomas deste modelo e seus ids:
+
+```py
+>>> print(tokenizer.lang2id)
+{'en': 0, 'fr': 1}
+```
+
+Em seguida, cria-se um input de exemplo:
+
+```py
+>>> input_ids = torch.tensor([tokenizer.encode("Wikipedia was used to")]) # batch size of 1
+```
+
+Estabelece-se o id do idioma, por exemplo `"en"`, e utiliza-se o mesmo para definir a language embedding.
+A language embedding Ă© um tensor preenchido com `0`, que Ă© o id de idioma para o inglĂȘs.
+Este tensor deve ser do mesmo tamanho que os `input_ids`.
+
+```py
+>>> language_id = tokenizer.lang2id["en"] # 0
+>>> langs = torch.tensor([language_id] * input_ids.shape[1]) # torch.tensor([0, 0, 0, ..., 0])
+
+>>> # We reshape it to be of size (batch_size, sequence_length)
+>>> langs = langs.view(1, -1) # is now of shape [1, sequence_length] (we have a batch size of 1)
+```
+
+Agora vocĂȘ pode passar os `input_ids` e a language embedding ao modelo:
+
+```py
+>>> outputs = model(input_ids, langs=langs)
+```
+
+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`.
+
+### XLM sem language embeddings
+
+Os seguintes modelos XLM nĂŁo requerem o uso de language embeddings durante a inferĂȘncia:
+
+- `xlm-mlm-17-1280` (Modelagem de linguagem com mĂĄscara, 17 idiomas)
+- `xlm-mlm-100-1280` (Modelagem de linguagem com mĂĄscara, 100 idiomas)
+
+Estes modelos são utilizados para representaçÔes genéricas de frase diferentemente dos checkpoints XLM anteriores.
+
+## BERT
+
+Os seguintes modelos do BERT podem ser utilizados para tarefas multilinguĂsticas:
+
+- `bert-base-multilingual-uncased` (Modelagem de linguagem com mĂĄscara + PrevisĂŁo de frases, 102 idiomas)
+- `bert-base-multilingual-cased` (Modelagem de linguagem com mĂĄscara + PrevisĂŁo de frases, 104 idiomas)
+
+Estes modelos nĂŁo requerem language embeddings durante a inferĂȘncia. Devem identificar a linguagem a partir
+do contexto e realizar a inferĂȘncia em sequĂȘncia.
+
+## XLM-RoBERTa
+
+Os seguintes modelos do XLM-RoBERTa podem ser utilizados para tarefas multilinguĂsticas:
+
+- `xlm-roberta-base` (Modelagem de linguagem com mĂĄscara, 100 idiomas)
+- `xlm-roberta-large` Modelagem de linguagem com mĂĄscara, 100 idiomas)
+
+O XLM-RoBERTa foi treinado com 2,5 TB de dados do CommonCrawl recém-criados e testados em 100 idiomas.
+Proporciona fortes vantagens sobre os modelos multilinguĂsticos publicados anteriormente como o mBERT e o XLM em tarefas
+subsequentes como a classificação, a rotulagem de sequĂȘncias e Ă respostas a perguntas.
+
+## M2M100
+
+Os seguintes modelos de M2M100 podem ser utilizados para traduçÔes multilinguĂsticas:
+
+- `facebook/m2m100_418M` (Tradução)
+- `facebook/m2m100_1.2B` (Tradução)
+
+Neste exemplo, o checkpoint `facebook/m2m100_418M` Ă© carregado para traduzir do mandarim ao inglĂȘs. Ă possĂvel
+estabelecer o idioma de origem no tokenizador:
+
+```py
+>>> from transformers import M2M100ForConditionalGeneration, M2M100Tokenizer
+
+>>> en_text = "Do not meddle in the affairs of wizards, for they are subtle and quick to anger."
+>>> chinese_text = "äžèŠææć·«ćž«çäșć, ć çșä»ćæŻćŸźćŠç, ćŸćż«ć°±æçŒæ."
+
+>>> tokenizer = M2M100Tokenizer.from_pretrained("facebook/m2m100_418M", src_lang="zh")
+>>> model = M2M100ForConditionalGeneration.from_pretrained("facebook/m2m100_418M")
+```
+
+Tokenização do texto:
+
+```py
+>>> encoded_zh = tokenizer(chinese_text, return_tensors="pt")
+```
+
+O M2M100 força o id do idioma de destino como o primeiro token gerado para traduzir ao idioma de destino.
+Ă definido o `forced_bos_token_id` como `en` no mĂ©todo `generate` para traduzir ao inglĂȘs.
+
+```py
+>>> generated_tokens = model.generate(**encoded_zh, forced_bos_token_id=tokenizer.get_lang_id("en"))
+>>> tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)
+'Do not interfere with the matters of the witches, because they are delicate and will soon be angry.'
+```
+
+## MBart
+
+Os seguintes modelos do MBart podem ser utilizados para tradução multilinguĂstica:
+
+- `facebook/mbart-large-50-one-to-many-mmt` (Tradução automĂĄtica multilinguĂstica de um a vĂĄrios, 50 idiomas)
+- `facebook/mbart-large-50-many-to-many-mmt` (Tradução automĂĄtica multilinguĂstica de vĂĄrios a vĂĄrios, 50 idiomas)
+- `facebook/mbart-large-50-many-to-one-mmt` (Tradução automĂĄtica multilinguĂstica vĂĄrios a um, 50 idiomas)
+- `facebook/mbart-large-50` (Tradução multilinguĂstica, 50 idiomas)
+- `facebook/mbart-large-cc25`
+
+Neste exemplo, carrega-se o checkpoint `facebook/mbart-large-50-many-to-many-mmt` para traduzir do finlandĂȘs ao inglĂȘs.
+Pode-se definir o idioma de origem no tokenizador:
+
+```py
+>>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
+
+>>> en_text = "Do not meddle in the affairs of wizards, for they are subtle and quick to anger."
+>>> fi_text = "ĂlĂ€ sekaannu velhojen asioihin, sillĂ€ ne ovat hienovaraisia ja nopeasti vihaisia."
+
+>>> tokenizer = AutoTokenizer.from_pretrained("facebook/mbart-large-50-many-to-many-mmt", src_lang="fi_FI")
+>>> model = AutoModelForSeq2SeqLM.from_pretrained("facebook/mbart-large-50-many-to-many-mmt")
+```
+
+Tokenizando o texto:
+
+```py
+>>> encoded_en = tokenizer(en_text, return_tensors="pt")
+```
+
+O MBart força o id do idioma de destino como o primeiro token gerado para traduzir ao idioma de destino.
+Ă definido o `forced_bos_token_id` como `en` no mĂ©todo `generate` para traduzir ao inglĂȘs.
+
+```py
+>>> generated_tokens = model.generate(**encoded_en, forced_bos_token_id=tokenizer.lang_code_to_id("en_XX"))
+>>> tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)
+"Don't interfere with the wizard's affairs, because they are subtle, will soon get angry."
+```
+
+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
+como sendo o primeiro token generado, caso contrĂĄrio a usagem Ă© a mesma.
diff --git a/docs/source/pt/multilingual.mdx b/docs/source/pt/multilingual.mdx
deleted file mode 100644
index 4db9b54dab34..000000000000
--- a/docs/source/pt/multilingual.mdx
+++ /dev/null
@@ -1,191 +0,0 @@
-
-
-# Modelos multilinguĂsticos para inferĂȘncia
-
-[[open-in-colab]]
-
-Existem vĂĄrios modelos multilinguĂsticos no đ€ Transformers e seus usos para inferĂȘncia diferem dos modelos monolĂngues.
-No entanto, nem *todos* os usos dos modelos multilĂngues sĂŁo tĂŁo diferentes.
-Alguns modelos, como o [bert-base-multilingual-uncased](https://huggingface.co/bert-base-multilingual-uncased),
-podem ser usados como se fossem monolĂngues. Este guia irĂĄ te ajudar a usar modelos multilĂngues cujo uso difere
-para o propĂłsito de inferĂȘncia.
-
-## XLM
-
-O XLM tem dez checkpoints diferentes dos quais apenas um Ă© monolĂngue.
-Os nove checkpoints restantes do modelo sĂŁo subdivididos em duas categorias:
-checkpoints que usam de language embeddings e os que nĂŁo.
-
-### XLM com language embeddings
-
-Os seguintes modelos de XLM usam language embeddings para especificar a linguagem utilizada para a inferĂȘncia.
-
-- `xlm-mlm-ende-1024` (Masked language modeling, English-German)
-- `xlm-mlm-enfr-1024` (Masked language modeling, English-French)
-- `xlm-mlm-enro-1024` (Masked language modeling, English-Romanian)
-- `xlm-mlm-xnli15-1024` (Masked language modeling, XNLI languages)
-- `xlm-mlm-tlm-xnli15-1024` (Masked language modeling + translation, XNLI languages)
-- `xlm-clm-enfr-1024` (Causal language modeling, English-French)
-- `xlm-clm-ende-1024` (Causal language modeling, English-German)
-
-Os language embeddings sĂŁo representados por um tensor de mesma dimensĂŁo que os `input_ids` passados ao modelo.
-Os valores destes tensores dependem do idioma utilizado e se identificam pelos atributos `lang2id` e `id2lang` do tokenizador.
-
-Neste exemplo, carregamos o checkpoint `xlm-clm-enfr-1024`(Causal language modeling, English-French):
-
-```py
->>> import torch
->>> from transformers import XLMTokenizer, XLMWithLMHeadModel
-
->>> tokenizer = XLMTokenizer.from_pretrained("xlm-clm-enfr-1024")
->>> model = XLMWithLMHeadModel.from_pretrained("xlm-clm-enfr-1024")
-```
-
-O atributo `lang2id` do tokenizador mostra os idiomas deste modelo e seus ids:
-
-```py
->>> print(tokenizer.lang2id)
-{'en': 0, 'fr': 1}
-```
-
-Em seguida, cria-se um input de exemplo:
-
-```py
->>> input_ids = torch.tensor([tokenizer.encode("Wikipedia was used to")]) # batch size of 1
-```
-
-Estabelece-se o id do idioma, por exemplo `"en"`, e utiliza-se o mesmo para definir a language embedding.
-A language embedding Ă© um tensor preenchido com `0`, que Ă© o id de idioma para o inglĂȘs.
-Este tensor deve ser do mesmo tamanho que os `input_ids`.
-
-```py
->>> language_id = tokenizer.lang2id["en"] # 0
->>> langs = torch.tensor([language_id] * input_ids.shape[1]) # torch.tensor([0, 0, 0, ..., 0])
-
->>> # We reshape it to be of size (batch_size, sequence_length)
->>> langs = langs.view(1, -1) # is now of shape [1, sequence_length] (we have a batch size of 1)
-```
-
-Agora vocĂȘ pode passar os `input_ids` e a language embedding ao modelo:
-
-```py
->>> outputs = model(input_ids, langs=langs)
-```
-
-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`.
-
-### XLM sem language embeddings
-
-Os seguintes modelos XLM nĂŁo requerem o uso de language embeddings durante a inferĂȘncia:
-
-- `xlm-mlm-17-1280` (Modelagem de linguagem com mĂĄscara, 17 idiomas)
-- `xlm-mlm-100-1280` (Modelagem de linguagem com mĂĄscara, 100 idiomas)
-
-Estes modelos são utilizados para representaçÔes genéricas de frase diferentemente dos checkpoints XLM anteriores.
-
-## BERT
-
-Os seguintes modelos do BERT podem ser utilizados para tarefas multilinguĂsticas:
-
-- `bert-base-multilingual-uncased` (Modelagem de linguagem com mĂĄscara + PrevisĂŁo de frases, 102 idiomas)
-- `bert-base-multilingual-cased` (Modelagem de linguagem com mĂĄscara + PrevisĂŁo de frases, 104 idiomas)
-
-Estes modelos nĂŁo requerem language embeddings durante a inferĂȘncia. Devem identificar a linguagem a partir
-do contexto e realizar a inferĂȘncia em sequĂȘncia.
-
-## XLM-RoBERTa
-
-Os seguintes modelos do XLM-RoBERTa podem ser utilizados para tarefas multilinguĂsticas:
-
-- `xlm-roberta-base` (Modelagem de linguagem com mĂĄscara, 100 idiomas)
-- `xlm-roberta-large` Modelagem de linguagem com mĂĄscara, 100 idiomas)
-
-O XLM-RoBERTa foi treinado com 2,5 TB de dados do CommonCrawl recém-criados e testados em 100 idiomas.
-Proporciona fortes vantagens sobre os modelos multilinguĂsticos publicados anteriormente como o mBERT e o XLM em tarefas
-subsequentes como a classificação, a rotulagem de sequĂȘncias e Ă respostas a perguntas.
-
-## M2M100
-
-Os seguintes modelos de M2M100 podem ser utilizados para traduçÔes multilinguĂsticas:
-
-- `facebook/m2m100_418M` (Tradução)
-- `facebook/m2m100_1.2B` (Tradução)
-
-Neste exemplo, o checkpoint `facebook/m2m100_418M` Ă© carregado para traduzir do mandarim ao inglĂȘs. Ă possĂvel
-estabelecer o idioma de origem no tokenizador:
-
-```py
->>> from transformers import M2M100ForConditionalGeneration, M2M100Tokenizer
-
->>> en_text = "Do not meddle in the affairs of wizards, for they are subtle and quick to anger."
->>> chinese_text = "äžèŠææć·«ćž«çäșć, ć çșä»ćæŻćŸźćŠç, ćŸćż«ć°±æçŒæ."
-
->>> tokenizer = M2M100Tokenizer.from_pretrained("facebook/m2m100_418M", src_lang="zh")
->>> model = M2M100ForConditionalGeneration.from_pretrained("facebook/m2m100_418M")
-```
-
-Tokenização do texto:
-
-```py
->>> encoded_zh = tokenizer(chinese_text, return_tensors="pt")
-```
-
-O M2M100 força o id do idioma de destino como o primeiro token gerado para traduzir ao idioma de destino.
-Ă definido o `forced_bos_token_id` como `en` no mĂ©todo `generate` para traduzir ao inglĂȘs.
-
-```py
->>> generated_tokens = model.generate(**encoded_zh, forced_bos_token_id=tokenizer.get_lang_id("en"))
->>> tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)
-'Do not interfere with the matters of the witches, because they are delicate and will soon be angry.'
-```
-
-## MBart
-
-Os seguintes modelos do MBart podem ser utilizados para tradução multilinguĂstica:
-
-- `facebook/mbart-large-50-one-to-many-mmt` (Tradução automĂĄtica multilinguĂstica de um a vĂĄrios, 50 idiomas)
-- `facebook/mbart-large-50-many-to-many-mmt` (Tradução automĂĄtica multilinguĂstica de vĂĄrios a vĂĄrios, 50 idiomas)
-- `facebook/mbart-large-50-many-to-one-mmt` (Tradução automĂĄtica multilinguĂstica vĂĄrios a um, 50 idiomas)
-- `facebook/mbart-large-50` (Tradução multilinguĂstica, 50 idiomas)
-- `facebook/mbart-large-cc25`
-
-Neste exemplo, carrega-se o checkpoint `facebook/mbart-large-50-many-to-many-mmt` para traduzir do finlandĂȘs ao inglĂȘs.
-Pode-se definir o idioma de origem no tokenizador:
-
-```py
->>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
-
->>> en_text = "Do not meddle in the affairs of wizards, for they are subtle and quick to anger."
->>> fi_text = "ĂlĂ€ sekaannu velhojen asioihin, sillĂ€ ne ovat hienovaraisia ja nopeasti vihaisia."
-
->>> tokenizer = AutoTokenizer.from_pretrained("facebook/mbart-large-50-many-to-many-mmt", src_lang="fi_FI")
->>> model = AutoModelForSeq2SeqLM.from_pretrained("facebook/mbart-large-50-many-to-many-mmt")
-```
-
-Tokenizando o texto:
-
-```py
->>> encoded_en = tokenizer(en_text, return_tensors="pt")
-```
-
-O MBart força o id do idioma de destino como o primeiro token gerado para traduzir ao idioma de destino.
-Ă definido o `forced_bos_token_id` como `en` no mĂ©todo `generate` para traduzir ao inglĂȘs.
-
-```py
->>> generated_tokens = model.generate(**encoded_en, forced_bos_token_id=tokenizer.lang_code_to_id("en_XX"))
->>> tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)
-"Don't interfere with the wizard's affairs, because they are subtle, will soon get angry."
-```
-
-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
-como sendo o primeiro token generado, caso contrĂĄrio a usagem Ă© a mesma.
diff --git a/docs/source/pt/pipeline_tutorial.md b/docs/source/pt/pipeline_tutorial.md
new file mode 100644
index 000000000000..a7ea71256808
--- /dev/null
+++ b/docs/source/pt/pipeline_tutorial.md
@@ -0,0 +1,157 @@
+
+
+# Pipelines para inferĂȘncia
+
+Um [pipeline] simplifica o uso dos modelos no [Model Hub](https://huggingface.co/models) para a inferĂȘncia de uma diversidade de tarefas,
+como a geração de texto, a segmentação de imagens e a classificação de åudio.
+Inclusive, se nĂŁo tem experiĂȘncia com alguma modalidade especĂfica ou nĂŁo compreende o cĂłdigo que forma os modelos,
+pode usar eles mesmo assim com o [pipeline]! Este tutorial te ensinarĂĄ a:
+
+* Utilizar um [`pipeline`] para inferĂȘncia.
+* Utilizar um tokenizador ou model especĂfico.
+* Utilizar um [`pipeline`] para tarefas de ĂĄudio e visĂŁo computacional.
+
+
+
+ Acesse a documentação do [`pipeline`] para obter uma lista completa de tarefas possĂveis.
+
+
+
+## Uso do pipeline
+
+Mesmo que cada tarefa tenha um [`pipeline`] associado, é mais simples usar a abstração geral do [`pipeline`] que
+contĂ©m todos os pipelines das tarefas mais especĂficas.
+O [`pipeline`] carrega automaticamenta um modelo predeterminado e um tokenizador com capacidade de inferĂȘncia para sua
+tarefa.
+
+1. Comece carregando um [`pipeline`] e especifique uma tarefa de inferĂȘncia:
+
+```py
+>>> from transformers import pipeline
+
+>>> generator = pipeline(task="text-generation")
+```
+
+2. Passe seu dado de entrada, no caso um texto, ao [`pipeline`]:
+
+```py
+>>> generator("Three Rings for the Elven-kings under the sky, Seven for the Dwarf-lords in their halls of stone")
+[{'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'}]
+```
+
+Se tiver mais de uma entrada, passe-a como uma lista:
+
+```py
+>>> generator(
+... [
+... "Three Rings for the Elven-kings under the sky, Seven for the Dwarf-lords in their halls of stone",
+... "Nine for Mortal Men, doomed to die, One for the Dark Lord on his dark throne",
+... ]
+... )
+```
+
+Qualquer parĂąmetro adicional para a sua tarefa tambĂ©m pode ser incluĂdo no [`pipeline`]. A tarefa `text-generation` tem um mĂ©todo
+[`~generation.GenerationMixin.generate`] com vĂĄrios parĂąmetros para controlar a saĂda.
+Por exemplo, se quiser gerar mais de uma saĂda, defina-a no parĂąmetro `num_return_sequences`:
+
+```py
+>>> generator(
+... "Three Rings for the Elven-kings under the sky, Seven for the Dwarf-lords in their halls of stone",
+... num_return_sequences=2,
+... )
+```
+
+### Selecionando um modelo e um tokenizador
+
+O [`pipeline`] aceita qualquer modelo do [Model Hub](https://huggingface.co/models). HĂĄ rĂłtulos adicionais no Model Hub
+que te permitem filtrar pelo modelo que gostaria de usar para sua tarefa. Uma vez que tiver escolhido o modelo apropriado,
+carregue-o com as classes `AutoModelFor` e [`AutoTokenizer'] correspondentes. Por exemplo, carregue a classe [`AutoModelForCausalLM`]
+para uma tarefa de modelagem de linguagem causal:
+
+```py
+>>> from transformers import AutoTokenizer, AutoModelForCausalLM
+
+>>> tokenizer = AutoTokenizer.from_pretrained("distilgpt2")
+>>> model = AutoModelForCausalLM.from_pretrained("distilgpt2")
+```
+
+Crie uma [`pipeline`] para a sua tarefa e especifĂque o modelo e o tokenizador que foram carregados:
+
+```py
+>>> from transformers import pipeline
+
+>>> generator = pipeline(task="text-generation", model=model, tokenizer=tokenizer)
+```
+
+Passe seu texto de entrada ao [`pipeline`] para gerar algum texto:
+
+```py
+>>> generator("Three Rings for the Elven-kings under the sky, Seven for the Dwarf-lords in their halls of stone")
+[{'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'}]
+```
+
+## Pipeline de audio
+
+A flexibilidade do [`pipeline`] significa que também pode-se extender às tarefas de åudio.
+La flexibilidad de [`pipeline`] significa que también se puede extender a tareas de audio.
+
+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
+Encontre um modelo de [audio classification](https://huggingface.co/models?pipeline_tag=audio-classification) para
+reconhecimento de emoçÔes no Model Hub e carregue-o usando o [`pipeline`]:
+
+```py
+>>> from transformers import pipeline
+
+>>> audio_classifier = pipeline(
+... task="audio-classification", model="ehcalabres/wav2vec2-lg-xlsr-en-speech-emotion-recognition"
+... )
+```
+
+Passe o arquivo de ĂĄudio ao [`pipeline`]:
+
+```py
+>>> audio_classifier("jfk_moon_speech.wav")
+[{'label': 'calm', 'score': 0.13856211304664612},
+ {'label': 'disgust', 'score': 0.13148026168346405},
+ {'label': 'happy', 'score': 0.12635163962841034},
+ {'label': 'angry', 'score': 0.12439591437578201},
+ {'label': 'fearful', 'score': 0.12404385954141617}]
+```
+
+## Pipeline de visĂŁo computacional
+
+Finalmente, utilizar um [`pipeline`] para tarefas de visĂŁo Ă© praticamente a mesma coisa.
+Especifique a sua tarefa de visĂŁo e passe a sua imagem ao classificador.
+A imagem pode ser um link ou uma rota local à imagem. Por exemplo, que espécie de gato estå presente na imagem?
+
+
+
+```py
+>>> from transformers import pipeline
+
+>>> vision_classifier = pipeline(task="image-classification")
+>>> vision_classifier(
+... images="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
+... )
+[{'label': 'lynx, catamount', 'score': 0.4403027892112732},
+ {'label': 'cougar, puma, catamount, mountain lion, painter, panther, Felis concolor',
+ 'score': 0.03433405980467796},
+ {'label': 'snow leopard, ounce, Panthera uncia',
+ 'score': 0.032148055732250214},
+ {'label': 'Egyptian cat', 'score': 0.02353910356760025},
+ {'label': 'tiger cat', 'score': 0.023034192621707916}]
+```
diff --git a/docs/source/pt/pipeline_tutorial.mdx b/docs/source/pt/pipeline_tutorial.mdx
deleted file mode 100644
index 2991bcecde4f..000000000000
--- a/docs/source/pt/pipeline_tutorial.mdx
+++ /dev/null
@@ -1,153 +0,0 @@
-
-
-# Pipelines para inferĂȘncia
-
-Um [pipeline] simplifica o uso dos modelos no [Model Hub](https://huggingface.co/models) para a inferĂȘncia de uma diversidade de tarefas,
-como a geração de texto, a segmentação de imagens e a classificação de åudio.
-Inclusive, se nĂŁo tem experiĂȘncia com alguma modalidade especĂfica ou nĂŁo compreende o cĂłdigo que forma os modelos,
-pode usar eles mesmo assim com o [pipeline]! Este tutorial te ensinarĂĄ a:
-
-* Utilizar um [`pipeline`] para inferĂȘncia.
-* Utilizar um tokenizador ou model especĂfico.
-* Utilizar um [`pipeline`] para tarefas de ĂĄudio e visĂŁo computacional.
-
-
-
- Acesse a documentação do [`pipeline`] para obter uma lista completa de tarefas possĂveis.
-
-
-
-## Uso do pipeline
-
-Mesmo que cada tarefa tenha um [`pipeline`] associado, é mais simples usar a abstração geral do [`pipeline`] que
-contĂ©m todos os pipelines das tarefas mais especĂficas.
-O [`pipeline`] carrega automaticamenta um modelo predeterminado e um tokenizador com capacidade de inferĂȘncia para sua
-tarefa.
-
-1. Comece carregando um [`pipeline`] e especifique uma tarefa de inferĂȘncia:
-
-```py
->>> from transformers import pipeline
-
->>> generator = pipeline(task="text-generation")
-```
-
-2. Passe seu dado de entrada, no caso um texto, ao [`pipeline`]:
-
-```py
->>> generator("Three Rings for the Elven-kings under the sky, Seven for the Dwarf-lords in their halls of stone")
-[{'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'}]
-```
-
-Se tiver mais de uma entrada, passe-a como uma lista:
-
-```py
->>> generator(
-... [
-... "Three Rings for the Elven-kings under the sky, Seven for the Dwarf-lords in their halls of stone",
-... "Nine for Mortal Men, doomed to die, One for the Dark Lord on his dark throne",
-... ]
-... )
-```
-
-Qualquer parĂąmetro adicional para a sua tarefa tambĂ©m pode ser incluĂdo no [`pipeline`]. A tarefa `text-generation` tem um mĂ©todo
-[`~generation.GenerationMixin.generate`] com vĂĄrios parĂąmetros para controlar a saĂda.
-Por exemplo, se quiser gerar mais de uma saĂda, defina-a no parĂąmetro `num_return_sequences`:
-
-```py
->>> generator(
-... "Three Rings for the Elven-kings under the sky, Seven for the Dwarf-lords in their halls of stone",
-... num_return_sequences=2,
-... )
-```
-
-### Selecionando um modelo e um tokenizador
-
-O [`pipeline`] aceita qualquer modelo do [Model Hub](https://huggingface.co/models). HĂĄ rĂłtulos adicionais no Model Hub
-que te permitem filtrar pelo modelo que gostaria de usar para sua tarefa. Uma vez que tiver escolhido o modelo apropriado,
-carregue-o com as classes `AutoModelFor` e [`AutoTokenizer'] correspondentes. Por exemplo, carregue a classe [`AutoModelForCausalLM`]
-para uma tarefa de modelagem de linguagem causal:
-
-```py
->>> from transformers import AutoTokenizer, AutoModelForCausalLM
-
->>> tokenizer = AutoTokenizer.from_pretrained("distilgpt2")
->>> model = AutoModelForCausalLM.from_pretrained("distilgpt2")
-```
-
-Crie uma [`pipeline`] para a sua tarefa e especifĂque o modelo e o tokenizador que foram carregados:
-
-```py
->>> from transformers import pipeline
-
->>> generator = pipeline(task="text-generation", model=model, tokenizer=tokenizer)
-```
-
-Passe seu texto de entrada ao [`pipeline`] para gerar algum texto:
-
-```py
->>> generator("Three Rings for the Elven-kings under the sky, Seven for the Dwarf-lords in their halls of stone")
-[{'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'}]
-```
-
-## Pipeline de audio
-
-A flexibilidade do [`pipeline`] significa que também pode-se extender às tarefas de åudio.
-La flexibilidad de [`pipeline`] significa que también se puede extender a tareas de audio.
-
-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.mdx
-Encontre um modelo de [audio classification](https://huggingface.co/models?pipeline_tag=audio-classification) para
-reconhecimento de emoçÔes no Model Hub e carregue-o usando o [`pipeline`]:
-
-```py
->>> from transformers import pipeline
-
->>> audio_classifier = pipeline(
-... task="audio-classification", model="ehcalabres/wav2vec2-lg-xlsr-en-speech-emotion-recognition"
-... )
-```
-
-Passe o arquivo de ĂĄudio ao [`pipeline`]:
-
-```py
->>> audio_classifier("jfk_moon_speech.wav")
-[{'label': 'calm', 'score': 0.13856211304664612},
- {'label': 'disgust', 'score': 0.13148026168346405},
- {'label': 'happy', 'score': 0.12635163962841034},
- {'label': 'angry', 'score': 0.12439591437578201},
- {'label': 'fearful', 'score': 0.12404385954141617}]
-```
-
-## Pipeline de visĂŁo computacional
-
-Finalmente, utilizar um [`pipeline`] para tarefas de visĂŁo Ă© praticamente a mesma coisa.
-Especifique a sua tarefa de visĂŁo e passe a sua imagem ao classificador.
-A imagem pode ser um link ou uma rota local à imagem. Por exemplo, que espécie de gato estå presente na imagem?
-
-
-
-```py
->>> from transformers import pipeline
-
->>> vision_classifier = pipeline(task="image-classification")
->>> vision_classifier(
-... images="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
-... )
-[{'label': 'lynx, catamount', 'score': 0.4403027892112732},
- {'label': 'cougar, puma, catamount, mountain lion, painter, panther, Felis concolor',
- 'score': 0.03433405980467796},
- {'label': 'snow leopard, ounce, Panthera uncia',
- 'score': 0.032148055732250214},
- {'label': 'Egyptian cat', 'score': 0.02353910356760025},
- {'label': 'tiger cat', 'score': 0.023034192621707916}]
-```
diff --git a/docs/source/pt/quicktour.md b/docs/source/pt/quicktour.md
new file mode 100644
index 000000000000..e807124de573
--- /dev/null
+++ b/docs/source/pt/quicktour.md
@@ -0,0 +1,395 @@
+
+
+# Tour rĂĄpido
+
+[[open-in-colab]]
+
+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.
+
+
+
+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.
+
+
+
+## Pipeline
+
+[`pipeline`] é a maneira mais fåcil de usar um modelo pré-treinado para uma dada tarefa.
+
+
+
+A [`pipeline`] apoia diversas tarefas fora da caixa:
+
+**Texto**:
+* AnĂĄlise sentimental: classifica a polaridade de um texto.
+* Geração de texto (em InglĂȘs): gera texto a partir de uma entrada.
+* Reconhecimento de entidade mencionada: legenda cada palavra com uma classe que a representa (pessoa, data, local, etc...)
+* Respostas: extrai uma resposta dado algum contexto e uma questĂŁo
+* Måscara de preenchimento: preenche o espaço, dado um texto com måscaras de palavras.
+* Sumarização: gera o resumo de um texto longo ou documento.
+* Tradução: traduz texto para outra lĂngua.
+* Extração de caracterĂsticas: cria um tensor que representa o texto.
+
+**Imagem**:
+* Classificação de imagens: classifica uma imagem.
+* Segmentação de imagem: classifica cada pixel da imagem.
+* Detecção de objetos: detecta objetos em uma imagem.
+
+**Audio**:
+* Classficação de åudio: legenda um trecho de åudio fornecido.
+* Reconhecimento de fala automĂĄtico: transcreve audio em texto.
+
+
+
+Para mais detalhes sobre a [`pipeline`] e tarefas associadas, siga a documentação [aqui](./main_classes/pipelines).
+
+
+
+### Uso da pipeline
+
+No exemplo a seguir, vocĂȘ usarĂĄ [`pipeline`] para anĂĄlise sentimental.
+
+Instale as seguintes dependĂȘncias se vocĂȘ ainda nĂŁo o fez:
+
+
+
+
+```bash
+pip install torch
+```
+
+
+```bash
+pip install tensorflow
+```
+
+
+
+Importe [`pipeline`] e especifique a tarefa que deseja completar:
+
+```py
+>>> from transformers import pipeline
+
+>>> classifier = pipeline("sentiment-analysis")
+```
+
+A pipeline baixa and armazena um [modelo prĂ©-treinado](https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english) padrĂŁo e tokenizer para anĂĄlise sentimental. Agora vocĂȘ pode usar `classifier` no texto alvo:
+
+```py
+>>> classifier("We are very happy to show you the đ€ Transformers library.")
+[{'label': 'POSITIVE', 'score': 0.9998}]
+```
+
+Para mais de uma sentença, passe uma lista para a [`pipeline`], a qual retornarå uma lista de dicionårios:
+
+```py
+>>> results = classifier(["We are very happy to show you the đ€ Transformers library.", "We hope you don't hate it."])
+>>> for result in results:
+... print(f"label: {result['label']}, with score: {round(result['score'], 4)}")
+label: POSITIVE, with score: 0.9998
+label: NEGATIVE, with score: 0.5309
+```
+
+A [`pipeline`] tambĂ©m pode iterar sobre um Dataset inteiro. Comece instalando a biblioteca de [đ€ Datasets](https://huggingface.co/docs/datasets/):
+
+```bash
+pip install datasets
+```
+
+Crie uma [`pipeline`] com a tarefa que deseja resolver e o modelo que deseja usar.
+
+```py
+>>> import torch
+>>> from transformers import pipeline
+
+>>> speech_recognizer = pipeline("automatic-speech-recognition", model="facebook/wav2vec2-base-960h")
+```
+
+A seguir, carregue uma base de dados (confira a đ€ [Iniciação em Datasets](https://huggingface.co/docs/datasets/quickstart.html) para mais detalhes) que vocĂȘ gostaria de iterar sobre. Por exemplo, vamos carregar o dataset [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14):
+
+```py
+>>> from datasets import load_dataset, Audio
+
+>>> dataset = load_dataset("PolyAI/minds14", name="en-US", split="train") # doctest: +IGNORE_RESULT
+```
+
+Precisamos garantir que a taxa de amostragem do conjunto de dados corresponda Ă taxa de amostragem em que o facebook/wav2vec2-base-960h foi treinado.
+
+```py
+>>> dataset = dataset.cast_column("audio", Audio(sampling_rate=speech_recognizer.feature_extractor.sampling_rate))
+```
+
+Os arquivos de ĂĄudio sĂŁo carregados e re-amostrados automaticamente ao chamar a coluna `"audio"`.
+Vamos extrair as arrays de formas de onda originais das primeiras 4 amostras e passĂĄ-las como uma lista para o pipeline:
+
+```py
+>>> result = speech_recognizer(dataset[:4]["audio"])
+>>> print([d["text"] for d in result])
+['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']
+```
+
+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.
+
+### Use outro modelo e tokenizer na pipeline
+
+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!
+
+```py
+>>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
+```
+
+
+
+Use o [`AutoModelForSequenceClassification`] e [`AutoTokenizer`] para carregar o modelo pré-treinado e seu tokenizer associado (mais em `AutoClass` abaixo):
+
+```py
+>>> from transformers import AutoTokenizer, AutoModelForSequenceClassification
+
+>>> model = AutoModelForSequenceClassification.from_pretrained(model_name)
+>>> tokenizer = AutoTokenizer.from_pretrained(model_name)
+```
+
+
+
+Use o [`TFAutoModelForSequenceClassification`] and [`AutoTokenizer`] para carregar o modelo pré-treinado e o tokenizer associado (mais em `TFAutoClass` abaixo):
+
+```py
+>>> from transformers import AutoTokenizer, TFAutoModelForSequenceClassification
+
+>>> model = TFAutoModelForSequenceClassification.from_pretrained(model_name)
+>>> tokenizer = AutoTokenizer.from_pretrained(model_name)
+```
+
+
+
+EntĂŁo vocĂȘ pode especificar o modelo e o tokenizador na [`pipeline`] e aplicar o `classifier` no seu texto alvo:
+
+```py
+>>> classifier = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer)
+>>> classifier("Nous sommes trĂšs heureux de vous prĂ©senter la bibliothĂšque đ€ Transformers.")
+[{'label': '5 stars', 'score': 0.7273}]
+```
+
+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! đ€
+
+## AutoClass
+
+
+
+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`].
+
+Vamos voltar ao nosso exemplo e ver como vocĂȘ pode usar a `AutoClass` para replicar os resultados do [`pipeline`].
+
+### AutoTokenizer
+
+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.
+
+Carregue um tokenizer com [`AutoTokenizer`]:
+
+```py
+>>> from transformers import AutoTokenizer
+
+>>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
+>>> tokenizer = AutoTokenizer.from_pretrained(model_name)
+```
+
+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.
+
+Passe o texto para o tokenizer:
+
+```py
+>>> encoding = tokenizer("We are very happy to show you the đ€ Transformers library.")
+>>> print(encoding)
+{'input_ids': [101, 11312, 10320, 12495, 19308, 10114, 11391, 10855, 10103, 100, 58263, 13299, 119, 102],
+ 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}
+```
+
+O tokenizer retornarĂĄ um dicionĂĄrio contendo:
+
+* [input_ids](./glossary#input-ids): representaçÔes numéricas de seus tokens.
+* [atttention_mask](.glossary#attention-mask): indica quais tokens devem ser atendidos.
+
+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:
+
+
+
+```py
+>>> pt_batch = tokenizer(
+... ["We are very happy to show you the đ€ transformers library.", "We hope you don't hate it."],
+... padding=True,
+... truncation=True,
+... max_length=512,
+... return_tensors="pt",
+... )
+```
+
+
+```py
+>>> tf_batch = tokenizer(
+... ["We are very happy to show you the đ€ Transformers library.", "We hope you don't hate it."],
+... padding=True,
+... truncation=True,
+... max_length=512,
+... return_tensors="tf",
+... )
+```
+
+
+
+Leia o tutorial de [pré-processamento](./pré-processamento) para obter mais detalhes sobre tokenização.
+
+### AutoModel
+
+
+
+đ€ 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`]:
+
+```py
+>>> from transformers import AutoModelForSequenceClassification
+
+>>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
+>>> pt_model = AutoModelForSequenceClassification.from_pretrained(model_name)
+```
+
+
+
+Veja o [sumĂĄrio de tarefas](./task_summary) para qual classe de [`AutoModel`] usar para cada tarefa.
+
+
+
+Agora vocĂȘ pode passar seu grupo de entradas prĂ©-processadas diretamente para o modelo. VocĂȘ apenas tem que descompactar o dicionĂĄrio usando `**`:
+
+```py
+>>> pt_outputs = pt_model(**pt_batch)
+```
+
+O modelo gera as ativaçÔes finais no atributo `logits`. Aplique a função softmax aos `logits` para recuperar as probabilidades:
+
+```py
+>>> from torch import nn
+
+>>> pt_predictions = nn.functional.softmax(pt_outputs.logits, dim=-1)
+>>> print(pt_predictions)
+tensor([[0.0021, 0.0018, 0.0115, 0.2121, 0.7725],
+ [0.2084, 0.1826, 0.1969, 0.1755, 0.2365]], grad_fn=)
+```
+
+
+đ€ 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`]:
+
+```py
+>>> from transformers import TFAutoModelForSequenceClassification
+
+>>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
+>>> tf_model = TFAutoModelForSequenceClassification.from_pretrained(model_name)
+```
+
+
+
+Veja o [sumĂĄrio de tarefas](./task_summary) para qual classe de [`AutoModel`] usar para cada tarefa.
+
+
+
+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.
+
+```py
+>>> tf_outputs = tf_model(tf_batch)
+```
+
+O modelo gera as ativaçÔes finais no atributo `logits`. Aplique a função softmax aos `logits` para recuperar as probabilidades:
+
+```py
+>>> import tensorflow as tf
+
+>>> tf_predictions = tf.nn.softmax(tf_outputs.logits, axis=-1)
+>>> tf_predictions # doctest: +IGNORE_RESULT
+```
+
+
+
+
+
+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.
+
+
+
+
+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.
+
+
+
+As saĂdas do modelo đ€ Transformers sĂŁo classes de dados especiais para que seus atributos sejam preenchidos automaticamente em um IDE.
+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.
+
+
+
+### Salvar um modelo
+
+
+
+Uma vez que seu modelo estiver afinado, vocĂȘ pode salvĂĄ-lo com seu Tokenizer usando [`PreTrainedModel.save_pretrained`]:
+
+```py
+>>> pt_save_directory = "./pt_save_pretrained"
+>>> tokenizer.save_pretrained(pt_save_directory) # doctest: +IGNORE_RESULT
+>>> pt_model.save_pretrained(pt_save_directory)
+```
+
+Quando vocĂȘ estiver pronto para usĂĄ-lo novamente, recarregue com [`PreTrainedModel.from_pretrained`]:
+
+```py
+>>> pt_model = AutoModelForSequenceClassification.from_pretrained("./pt_save_pretrained")
+```
+
+
+Uma vez que seu modelo estiver afinado, vocĂȘ pode salvĂĄ-lo com seu Tokenizer usando [`TFPreTrainedModel.save_pretrained`]:
+
+```py
+>>> tf_save_directory = "./tf_save_pretrained"
+>>> tokenizer.save_pretrained(tf_save_directory) # doctest: +IGNORE_RESULT
+>>> tf_model.save_pretrained(tf_save_directory)
+```
+
+Quando vocĂȘ estiver pronto para usĂĄ-lo novamente, recarregue com [`TFPreTrainedModel.from_pretrained`]
+
+```py
+>>> tf_model = TFAutoModelForSequenceClassification.from_pretrained("./tf_save_pretrained")
+```
+
+
+
+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:
+
+
+
+```py
+>>> from transformers import AutoModel
+
+>>> tokenizer = AutoTokenizer.from_pretrained(tf_save_directory)
+>>> pt_model = AutoModelForSequenceClassification.from_pretrained(tf_save_directory, from_tf=True)
+```
+
+
+```py
+>>> from transformers import TFAutoModel
+
+>>> tokenizer = AutoTokenizer.from_pretrained(pt_save_directory)
+>>> tf_model = TFAutoModelForSequenceClassification.from_pretrained(pt_save_directory, from_pt=True)
+```
+
+
\ No newline at end of file
diff --git a/docs/source/pt/quicktour.mdx b/docs/source/pt/quicktour.mdx
deleted file mode 100644
index 3c00a64b6652..000000000000
--- a/docs/source/pt/quicktour.mdx
+++ /dev/null
@@ -1,391 +0,0 @@
-
-
-# Tour rĂĄpido
-
-[[open-in-colab]]
-
-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.
-
-
-
-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.
-
-
-
-## Pipeline
-
-[`pipeline`] é a maneira mais fåcil de usar um modelo pré-treinado para uma dada tarefa.
-
-
-
-A [`pipeline`] apoia diversas tarefas fora da caixa:
-
-**Texto**:
-* AnĂĄlise sentimental: classifica a polaridade de um texto.
-* Geração de texto (em InglĂȘs): gera texto a partir de uma entrada.
-* Reconhecimento de entidade mencionada: legenda cada palavra com uma classe que a representa (pessoa, data, local, etc...)
-* Respostas: extrai uma resposta dado algum contexto e uma questĂŁo
-* Måscara de preenchimento: preenche o espaço, dado um texto com måscaras de palavras.
-* Sumarização: gera o resumo de um texto longo ou documento.
-* Tradução: traduz texto para outra lĂngua.
-* Extração de caracterĂsticas: cria um tensor que representa o texto.
-
-**Imagem**:
-* Classificação de imagens: classifica uma imagem.
-* Segmentação de imagem: classifica cada pixel da imagem.
-* Detecção de objetos: detecta objetos em uma imagem.
-
-**Audio**:
-* Classficação de åudio: legenda um trecho de åudio fornecido.
-* Reconhecimento de fala automĂĄtico: transcreve audio em texto.
-
-
-
-Para mais detalhes sobre a [`pipeline`] e tarefas associadas, siga a documentação [aqui](./main_classes/pipelines).
-
-
-
-### Uso da pipeline
-
-No exemplo a seguir, vocĂȘ usarĂĄ [`pipeline`] para anĂĄlise sentimental.
-
-Instale as seguintes dependĂȘncias se vocĂȘ ainda nĂŁo o fez:
-
-
-
-
-```bash
-pip install torch
-```
-
-
-```bash
-pip install tensorflow
-```
-
-
-
-Importe [`pipeline`] e especifique a tarefa que deseja completar:
-
-```py
->>> from transformers import pipeline
-
->>> classifier = pipeline("sentiment-analysis")
-```
-
-A pipeline baixa and armazena um [modelo prĂ©-treinado](https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english) padrĂŁo e tokenizer para anĂĄlise sentimental. Agora vocĂȘ pode usar `classifier` no texto alvo:
-
-```py
->>> classifier("We are very happy to show you the đ€ Transformers library.")
-[{'label': 'POSITIVE', 'score': 0.9998}]
-```
-
-Para mais de uma sentença, passe uma lista para a [`pipeline`], a qual retornarå uma lista de dicionårios:
-
-```py
->>> results = classifier(["We are very happy to show you the đ€ Transformers library.", "We hope you don't hate it."])
->>> for result in results:
-... print(f"label: {result['label']}, with score: {round(result['score'], 4)}")
-label: POSITIVE, with score: 0.9998
-label: NEGATIVE, with score: 0.5309
-```
-
-A [`pipeline`] tambĂ©m pode iterar sobre um Dataset inteiro. Comece instalando a biblioteca de [đ€ Datasets](https://huggingface.co/docs/datasets/):
-
-```bash
-pip install datasets
-```
-
-Crie uma [`pipeline`] com a tarefa que deseja resolver e o modelo que deseja usar.
-
-```py
->>> import torch
->>> from transformers import pipeline
-
->>> speech_recognizer = pipeline("automatic-speech-recognition", model="facebook/wav2vec2-base-960h")
-```
-
-A seguir, carregue uma base de dados (confira a đ€ [Iniciação em Datasets](https://huggingface.co/docs/datasets/quickstart.html) para mais detalhes) que vocĂȘ gostaria de iterar sobre. Por exemplo, vamos carregar o dataset [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14):
-
-```py
->>> from datasets import load_dataset, Audio
-
->>> dataset = load_dataset("PolyAI/minds14", name="en-US", split="train") # doctest: +IGNORE_RESULT
-```
-
-Precisamos garantir que a taxa de amostragem do conjunto de dados corresponda Ă taxa de amostragem em que o facebook/wav2vec2-base-960h foi treinado.
-
-```py
->>> dataset = dataset.cast_column("audio", Audio(sampling_rate=speech_recognizer.feature_extractor.sampling_rate))
-```
-
-Os arquivos de ĂĄudio sĂŁo carregados e re-amostrados automaticamente ao chamar a coluna `"audio"`.
-Vamos extrair as arrays de formas de onda originais das primeiras 4 amostras e passĂĄ-las como uma lista para o pipeline:
-
-```py
->>> result = speech_recognizer(dataset[:4]["audio"])
->>> print([d["text"] for d in result])
-['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']
-```
-
-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.
-
-### Use outro modelo e tokenizer na pipeline
-
-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!
-
-```py
->>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
-```
-
-
-
-Use o [`AutoModelForSequenceClassification`] e [`AutoTokenizer`] para carregar o modelo pré-treinado e seu tokenizer associado (mais em `AutoClass` abaixo):
-
-```py
->>> from transformers import AutoTokenizer, AutoModelForSequenceClassification
-
->>> model = AutoModelForSequenceClassification.from_pretrained(model_name)
->>> tokenizer = AutoTokenizer.from_pretrained(model_name)
-```
-
-
-
-Use o [`TFAutoModelForSequenceClassification`] and [`AutoTokenizer`] para carregar o modelo pré-treinado e o tokenizer associado (mais em `TFAutoClass` abaixo):
-
-```py
->>> from transformers import AutoTokenizer, TFAutoModelForSequenceClassification
-
->>> model = TFAutoModelForSequenceClassification.from_pretrained(model_name)
->>> tokenizer = AutoTokenizer.from_pretrained(model_name)
-```
-
-
-
-EntĂŁo vocĂȘ pode especificar o modelo e o tokenizador na [`pipeline`] e aplicar o `classifier` no seu texto alvo:
-
-```py
->>> classifier = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer)
->>> classifier("Nous sommes trĂšs heureux de vous prĂ©senter la bibliothĂšque đ€ Transformers.")
-[{'label': '5 stars', 'score': 0.7273}]
-```
-
-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! đ€
-
-## AutoClass
-
-
-
-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`].
-
-Vamos voltar ao nosso exemplo e ver como vocĂȘ pode usar a `AutoClass` para replicar os resultados do [`pipeline`].
-
-### AutoTokenizer
-
-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.
-
-Carregue um tokenizer com [`AutoTokenizer`]:
-
-```py
->>> from transformers import AutoTokenizer
-
->>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
->>> tokenizer = AutoTokenizer.from_pretrained(model_name)
-```
-
-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.
-
-Passe o texto para o tokenizer:
-
-```py
->>> encoding = tokenizer("We are very happy to show you the đ€ Transformers library.")
->>> print(encoding)
-{'input_ids': [101, 11312, 10320, 12495, 19308, 10114, 11391, 10855, 10103, 100, 58263, 13299, 119, 102],
- 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
- 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}
-```
-
-O tokenizer retornarĂĄ um dicionĂĄrio contendo:
-
-* [input_ids](./glossary#input-ids): representaçÔes numéricas de seus tokens.
-* [atttention_mask](.glossary#attention-mask): indica quais tokens devem ser atendidos.
-
-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:
-
-
-
-```py
->>> pt_batch = tokenizer(
-... ["We are very happy to show you the đ€ transformers library.", "We hope you don't hate it."],
-... padding=True,
-... truncation=True,
-... max_length=512,
-... return_tensors="pt",
-... )
-```
-
-
-```py
->>> tf_batch = tokenizer(
-... ["We are very happy to show you the đ€ Transformers library.", "We hope you don't hate it."],
-... padding=True,
-... truncation=True,
-... max_length=512,
-... return_tensors="tf",
-... )
-```
-
-
-
-Leia o tutorial de [pré-processamento](./pré-processamento) para obter mais detalhes sobre tokenização.
-
-### AutoModel
-
-
-
-đ€ 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`]:
-
-```py
->>> from transformers import AutoModelForSequenceClassification
-
->>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
->>> pt_model = AutoModelForSequenceClassification.from_pretrained(model_name)
-```
-
-
-
-Veja o [sumĂĄrio de tarefas](./task_summary) para qual classe de [`AutoModel`] usar para cada tarefa.
-
-
-
-Agora vocĂȘ pode passar seu grupo de entradas prĂ©-processadas diretamente para o modelo. VocĂȘ apenas tem que descompactar o dicionĂĄrio usando `**`:
-
-```py
->>> pt_outputs = pt_model(**pt_batch)
-```
-
-O modelo gera as ativaçÔes finais no atributo `logits`. Aplique a função softmax aos `logits` para recuperar as probabilidades:
-
-```py
->>> from torch import nn
-
->>> pt_predictions = nn.functional.softmax(pt_outputs.logits, dim=-1)
->>> print(pt_predictions)
-tensor([[0.0021, 0.0018, 0.0115, 0.2121, 0.7725],
- [0.2084, 0.1826, 0.1969, 0.1755, 0.2365]], grad_fn=)
-```
-
-
-đ€ 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`]:
-
-```py
->>> from transformers import TFAutoModelForSequenceClassification
-
->>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
->>> tf_model = TFAutoModelForSequenceClassification.from_pretrained(model_name)
-```
-
-
-
-Veja o [sumĂĄrio de tarefas](./task_summary) para qual classe de [`AutoModel`] usar para cada tarefa.
-
-
-
-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.
-
-```py
->>> tf_outputs = tf_model(tf_batch)
-```
-
-O modelo gera as ativaçÔes finais no atributo `logits`. Aplique a função softmax aos `logits` para recuperar as probabilidades:
-
-```py
->>> import tensorflow as tf
-
->>> tf_predictions = tf.nn.softmax(tf_outputs.logits, axis=-1)
->>> tf_predictions # doctest: +IGNORE_RESULT
-```
-
-
-
-
-
-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.
-
-
-
-
-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.
-
-
-
-As saĂdas do modelo đ€ Transformers sĂŁo classes de dados especiais para que seus atributos sejam preenchidos automaticamente em um IDE.
-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.
-
-
-
-### Salvar um modelo
-
-
-
-Uma vez que seu modelo estiver afinado, vocĂȘ pode salvĂĄ-lo com seu Tokenizer usando [`PreTrainedModel.save_pretrained`]:
-
-```py
->>> pt_save_directory = "./pt_save_pretrained"
->>> tokenizer.save_pretrained(pt_save_directory) # doctest: +IGNORE_RESULT
->>> pt_model.save_pretrained(pt_save_directory)
-```
-
-Quando vocĂȘ estiver pronto para usĂĄ-lo novamente, recarregue com [`PreTrainedModel.from_pretrained`]:
-
-```py
->>> pt_model = AutoModelForSequenceClassification.from_pretrained("./pt_save_pretrained")
-```
-
-
-Uma vez que seu modelo estiver afinado, vocĂȘ pode salvĂĄ-lo com seu Tokenizer usando [`TFPreTrainedModel.save_pretrained`]:
-
-```py
->>> tf_save_directory = "./tf_save_pretrained"
->>> tokenizer.save_pretrained(tf_save_directory) # doctest: +IGNORE_RESULT
->>> tf_model.save_pretrained(tf_save_directory)
-```
-
-Quando vocĂȘ estiver pronto para usĂĄ-lo novamente, recarregue com [`TFPreTrainedModel.from_pretrained`]
-
-```py
->>> tf_model = TFAutoModelForSequenceClassification.from_pretrained("./tf_save_pretrained")
-```
-
-
-
-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:
-
-
-
-```py
->>> from transformers import AutoModel
-
->>> tokenizer = AutoTokenizer.from_pretrained(tf_save_directory)
->>> pt_model = AutoModelForSequenceClassification.from_pretrained(tf_save_directory, from_tf=True)
-```
-
-
-```py
->>> from transformers import TFAutoModel
-
->>> tokenizer = AutoTokenizer.from_pretrained(pt_save_directory)
->>> tf_model = TFAutoModelForSequenceClassification.from_pretrained(pt_save_directory, from_pt=True)
-```
-
-
\ No newline at end of file
diff --git a/docs/source/pt/run_scripts.md b/docs/source/pt/run_scripts.md
new file mode 100644
index 000000000000..8d87c10c2713
--- /dev/null
+++ b/docs/source/pt/run_scripts.md
@@ -0,0 +1,354 @@
+
+
+# Treinamento a partir de um script
+
+Junto com os đ€ Transformers [notebooks](./noteboks/README), 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).
+
+VocĂȘ tambĂ©m encontrarĂĄ scripts que usamos em nossos [projetos de pesquisa](https://github.com/huggingface/transformers/tree/main/examples/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.
+
+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.
+
+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.
+
+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.
+
+## Configuração
+
+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:
+
+```bash
+git clone https://github.com/huggingface/transformers
+cd transformers
+pip install .
+```
+
+Para versÔes mais antigas dos scripts de exemplo, clique no botão abaixo:
+
+
+ Exemplos para versĂ”es antigas dos đ€ Transformers
+
+
+
+Em seguida, mude seu clone atual dos đ€ Transformers para uma versĂŁo especĂfica, como v3.5.1, por exemplo:
+
+```bash
+git checkout tags/v3.5.1
+```
+
+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:
+
+```bash
+pip install -r requirements.txt
+```
+
+## Executando um script
+
+
+
+
+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/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.
+
+```bash
+python examples/pytorch/summarization/run_summarization.py \
+ --model_name_or_path t5-small \
+ --do_train \
+ --do_eval \
+ --dataset_name cnn_dailymail \
+ --dataset_config "3.0.0" \
+ --source_prefix "summarize: " \
+ --output_dir /tmp/tst-summarization \
+ --per_device_train_batch_size=4 \
+ --per_device_eval_batch_size=4 \
+ --overwrite_output_dir \
+ --predict_with_generate
+```
+
+
+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/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.
+
+```bash
+python examples/tensorflow/summarization/run_summarization.py \
+ --model_name_or_path t5-small \
+ --dataset_name cnn_dailymail \
+ --dataset_config "3.0.0" \
+ --output_dir /tmp/tst-summarization \
+ --per_device_train_batch_size 8 \
+ --per_device_eval_batch_size 16 \
+ --num_train_epochs 3 \
+ --do_train \
+ --do_eval
+```
+
+
+
+## Treinamento distribuĂdo e precisĂŁo mista
+
+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:
+
+- Adicione o argumento `fp16` para habilitar a precisĂŁo mista.
+- Defina o nĂșmero de GPUs a serem usadas com o argumento `nproc_per_node`.
+
+```bash
+python -m torch.distributed.launch \
+ --nproc_per_node 8 pytorch/summarization/run_summarization.py \
+ --fp16 \
+ --model_name_or_path t5-small \
+ --do_train \
+ --do_eval \
+ --dataset_name cnn_dailymail \
+ --dataset_config "3.0.0" \
+ --source_prefix "summarize: " \
+ --output_dir /tmp/tst-summarization \
+ --per_device_train_batch_size=4 \
+ --per_device_eval_batch_size=4 \
+ --overwrite_output_dir \
+ --predict_with_generate
+```
+
+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.
+
+## Executando um script em uma TPU
+
+
+
+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.
+
+```bash
+python xla_spawn.py --num_cores 8 \
+ summarization/run_summarization.py \
+ --model_name_or_path t5-small \
+ --do_train \
+ --do_eval \
+ --dataset_name cnn_dailymail \
+ --dataset_config "3.0.0" \
+ --source_prefix "summarize: " \
+ --output_dir /tmp/tst-summarization \
+ --per_device_train_batch_size=4 \
+ --per_device_eval_batch_size=4 \
+ --overwrite_output_dir \
+ --predict_with_generate
+```
+
+
+
+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`.
+
+```bash
+python run_summarization.py \
+ --tpu name_of_tpu_resource \
+ --model_name_or_path t5-small \
+ --dataset_name cnn_dailymail \
+ --dataset_config "3.0.0" \
+ --output_dir /tmp/tst-summarization \
+ --per_device_train_batch_size 8 \
+ --per_device_eval_batch_size 16 \
+ --num_train_epochs 3 \
+ --do_train \
+ --do_eval
+```
+
+
+
+## Execute um script com đ€ Accelerate
+
+đ€ [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:
+
+> Nota: Como o Accelerate estĂĄ se desenvolvendo rapidamente, a versĂŁo git do Accelerate deve ser instalada para executar os scripts
+
+```bash
+pip install git+https://github.com/huggingface/accelerate
+```
+
+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:
+
+```bash
+accelerate config
+```
+
+Teste sua configuração para garantir que ela esteja corretamente configurada :
+
+```bash
+accelerate test
+```
+
+Agora vocĂȘ estĂĄ pronto para iniciar o treinamento:
+
+```bash
+accelerate launch run_summarization_no_trainer.py \
+ --model_name_or_path t5-small \
+ --dataset_name cnn_dailymail \
+ --dataset_config "3.0.0" \
+ --source_prefix "summarize: " \
+ --output_dir ~/tmp/tst-summarization
+```
+
+## Usando um conjunto de dados personalizado
+
+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:
+
+- `train_file` e `validation_file` especificam o caminho para seus arquivos de treinamento e validação respectivamente.
+- `text_column` é o texto de entrada para sumarização.
+- `summary_column` Ă© o texto de destino para saĂda.
+
+Um script para sumarização usando um conjunto de dados customizado ficaria assim:
+
+```bash
+python examples/pytorch/summarization/run_summarization.py \
+ --model_name_or_path t5-small \
+ --do_train \
+ --do_eval \
+ --train_file path_to_csv_or_jsonlines_file \
+ --validation_file path_to_csv_or_jsonlines_file \
+ --text_column text_column_name \
+ --summary_column summary_column_name \
+ --source_prefix "summarize: " \
+ --output_dir /tmp/tst-summarization \
+ --overwrite_output_dir \
+ --per_device_train_batch_size=4 \
+ --per_device_eval_batch_size=4 \
+ --predict_with_generate
+```
+
+## Testando um script
+
+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:
+
+- `max_train_samples`
+- `max_eval_samples`
+- `max_predict_samples`
+
+```bash
+python examples/pytorch/summarization/run_summarization.py \
+ --model_name_or_path t5-small \
+ --max_train_samples 50 \
+ --max_eval_samples 50 \
+ --max_predict_samples 50 \
+ --do_train \
+ --do_eval \
+ --dataset_name cnn_dailymail \
+ --dataset_config "3.0.0" \
+ --source_prefix "summarize: " \
+ --output_dir /tmp/tst-summarization \
+ --per_device_train_batch_size=4 \
+ --per_device_eval_batch_size=4 \
+ --overwrite_output_dir \
+ --predict_with_generate
+```
+
+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:
+
+```bash
+examples/pytorch/summarization/run_summarization.py -h
+```
+
+## Retomar o treinamento a partir de um checkpoint
+
+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.
+
+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`:
+
+```bash
+python examples/pytorch/summarization/run_summarization.py
+ --model_name_or_path t5-small \
+ --do_train \
+ --do_eval \
+ --dataset_name cnn_dailymail \
+ --dataset_config "3.0.0" \
+ --source_prefix "summarize: " \
+ --output_dir /tmp/tst-summarization \
+ --per_device_train_batch_size=4 \
+ --per_device_eval_batch_size=4 \
+ --output_dir previous_output_dir \
+ --predict_with_generate
+```
+
+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.
+
+```bash
+python examples/pytorch/summarization/run_summarization.py
+ --model_name_or_path t5-small \
+ --do_train \
+ --do_eval \
+ --dataset_name cnn_dailymail \
+ --dataset_config "3.0.0" \
+ --source_prefix "summarize: " \
+ --output_dir /tmp/tst-summarization \
+ --per_device_train_batch_size=4 \
+ --per_device_eval_batch_size=4 \
+ --overwrite_output_dir \
+ --resume_from_checkpoint path_to_specific_checkpoint \
+ --predict_with_generate
+```
+
+## Compartilhando seu modelo
+
+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:
+
+```bash
+huggingface-cli login
+```
+
+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`.
+
+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.
+
+O exemplo a seguir mostra como fazer upload de um modelo com um nome de repositĂłrio especĂfico:
+
+```bash
+python examples/pytorch/summarization/run_summarization.py
+ --model_name_or_path t5-small \
+ --do_train \
+ --do_eval \
+ --dataset_name cnn_dailymail \
+ --dataset_config "3.0.0" \
+ --source_prefix "summarize: " \
+ --push_to_hub \
+ --push_to_hub_model_id finetuned-t5-cnn_dailymail \
+ --output_dir /tmp/tst-summarization \
+ --per_device_train_batch_size=4 \
+ --per_device_eval_batch_size=4 \
+ --overwrite_output_dir \
+ --predict_with_generate
+```
diff --git a/docs/source/pt/run_scripts.mdx b/docs/source/pt/run_scripts.mdx
deleted file mode 100644
index e91c4fc87d2d..000000000000
--- a/docs/source/pt/run_scripts.mdx
+++ /dev/null
@@ -1,350 +0,0 @@
-
-
-# Treinamento a partir de um script
-
-Junto com os đ€ Transformers [notebooks](./noteboks/README), 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).
-
-VocĂȘ tambĂ©m encontrarĂĄ scripts que usamos em nossos [projetos de pesquisa](https://github.com/huggingface/transformers/tree/main/examples/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.
-
-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.
-
-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.
-
-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.
-
-## Configuração
-
-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:
-
-```bash
-git clone https://github.com/huggingface/transformers
-cd transformers
-pip install .
-```
-
-Para versÔes mais antigas dos scripts de exemplo, clique no botão abaixo:
-
-
- Exemplos para versĂ”es antigas dos đ€ Transformers
-
-
-
-Em seguida, mude seu clone atual dos đ€ Transformers para uma versĂŁo especĂfica, como v3.5.1, por exemplo:
-
-```bash
-git checkout tags/v3.5.1
-```
-
-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:
-
-```bash
-pip install -r requirements.txt
-```
-
-## Executando um script
-
-
-
-
-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/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.
-
-```bash
-python examples/pytorch/summarization/run_summarization.py \
- --model_name_or_path t5-small \
- --do_train \
- --do_eval \
- --dataset_name cnn_dailymail \
- --dataset_config "3.0.0" \
- --source_prefix "summarize: " \
- --output_dir /tmp/tst-summarization \
- --per_device_train_batch_size=4 \
- --per_device_eval_batch_size=4 \
- --overwrite_output_dir \
- --predict_with_generate
-```
-
-
-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/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.
-
-```bash
-python examples/tensorflow/summarization/run_summarization.py \
- --model_name_or_path t5-small \
- --dataset_name cnn_dailymail \
- --dataset_config "3.0.0" \
- --output_dir /tmp/tst-summarization \
- --per_device_train_batch_size 8 \
- --per_device_eval_batch_size 16 \
- --num_train_epochs 3 \
- --do_train \
- --do_eval
-```
-
-
-
-## Treinamento distribuĂdo e precisĂŁo mista
-
-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:
-
-- Adicione o argumento `fp16` para habilitar a precisĂŁo mista.
-- Defina o nĂșmero de GPUs a serem usadas com o argumento `nproc_per_node`.
-
-```bash
-python -m torch.distributed.launch \
- --nproc_per_node 8 pytorch/summarization/run_summarization.py \
- --fp16 \
- --model_name_or_path t5-small \
- --do_train \
- --do_eval \
- --dataset_name cnn_dailymail \
- --dataset_config "3.0.0" \
- --source_prefix "summarize: " \
- --output_dir /tmp/tst-summarization \
- --per_device_train_batch_size=4 \
- --per_device_eval_batch_size=4 \
- --overwrite_output_dir \
- --predict_with_generate
-```
-
-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.
-
-## Executando um script em uma TPU
-
-
-
-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.
-
-```bash
-python xla_spawn.py --num_cores 8 \
- summarization/run_summarization.py \
- --model_name_or_path t5-small \
- --do_train \
- --do_eval \
- --dataset_name cnn_dailymail \
- --dataset_config "3.0.0" \
- --source_prefix "summarize: " \
- --output_dir /tmp/tst-summarization \
- --per_device_train_batch_size=4 \
- --per_device_eval_batch_size=4 \
- --overwrite_output_dir \
- --predict_with_generate
-```
-
-
-
-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`.
-
-```bash
-python run_summarization.py \
- --tpu name_of_tpu_resource \
- --model_name_or_path t5-small \
- --dataset_name cnn_dailymail \
- --dataset_config "3.0.0" \
- --output_dir /tmp/tst-summarization \
- --per_device_train_batch_size 8 \
- --per_device_eval_batch_size 16 \
- --num_train_epochs 3 \
- --do_train \
- --do_eval
-```
-
-
-
-## Execute um script com đ€ Accelerate
-
-đ€ [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:
-
-> Nota: Como o Accelerate estĂĄ se desenvolvendo rapidamente, a versĂŁo git do Accelerate deve ser instalada para executar os scripts
-
-```bash
-pip install git+https://github.com/huggingface/accelerate
-```
-
-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:
-
-```bash
-accelerate config
-```
-
-Teste sua configuração para garantir que ela esteja corretamente configurada :
-
-```bash
-accelerate test
-```
-
-Agora vocĂȘ estĂĄ pronto para iniciar o treinamento:
-
-```bash
-accelerate launch run_summarization_no_trainer.py \
- --model_name_or_path t5-small \
- --dataset_name cnn_dailymail \
- --dataset_config "3.0.0" \
- --source_prefix "summarize: " \
- --output_dir ~/tmp/tst-summarization
-```
-
-## Usando um conjunto de dados personalizado
-
-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:
-
-- `train_file` e `validation_file` especificam o caminho para seus arquivos de treinamento e validação respectivamente.
-- `text_column` é o texto de entrada para sumarização.
-- `summary_column` Ă© o texto de destino para saĂda.
-
-Um script para sumarização usando um conjunto de dados customizado ficaria assim:
-
-```bash
-python examples/pytorch/summarization/run_summarization.py \
- --model_name_or_path t5-small \
- --do_train \
- --do_eval \
- --train_file path_to_csv_or_jsonlines_file \
- --validation_file path_to_csv_or_jsonlines_file \
- --text_column text_column_name \
- --summary_column summary_column_name \
- --source_prefix "summarize: " \
- --output_dir /tmp/tst-summarization \
- --overwrite_output_dir \
- --per_device_train_batch_size=4 \
- --per_device_eval_batch_size=4 \
- --predict_with_generate
-```
-
-## Testando um script
-
-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:
-
-- `max_train_samples`
-- `max_eval_samples`
-- `max_predict_samples`
-
-```bash
-python examples/pytorch/summarization/run_summarization.py \
- --model_name_or_path t5-small \
- --max_train_samples 50 \
- --max_eval_samples 50 \
- --max_predict_samples 50 \
- --do_train \
- --do_eval \
- --dataset_name cnn_dailymail \
- --dataset_config "3.0.0" \
- --source_prefix "summarize: " \
- --output_dir /tmp/tst-summarization \
- --per_device_train_batch_size=4 \
- --per_device_eval_batch_size=4 \
- --overwrite_output_dir \
- --predict_with_generate
-```
-
-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:
-
-```bash
-examples/pytorch/summarization/run_summarization.py -h
-```
-
-## Retomar o treinamento a partir de um checkpoint
-
-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.
-
-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`:
-
-```bash
-python examples/pytorch/summarization/run_summarization.py
- --model_name_or_path t5-small \
- --do_train \
- --do_eval \
- --dataset_name cnn_dailymail \
- --dataset_config "3.0.0" \
- --source_prefix "summarize: " \
- --output_dir /tmp/tst-summarization \
- --per_device_train_batch_size=4 \
- --per_device_eval_batch_size=4 \
- --output_dir previous_output_dir \
- --predict_with_generate
-```
-
-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.
-
-```bash
-python examples/pytorch/summarization/run_summarization.py
- --model_name_or_path t5-small \
- --do_train \
- --do_eval \
- --dataset_name cnn_dailymail \
- --dataset_config "3.0.0" \
- --source_prefix "summarize: " \
- --output_dir /tmp/tst-summarization \
- --per_device_train_batch_size=4 \
- --per_device_eval_batch_size=4 \
- --overwrite_output_dir \
- --resume_from_checkpoint path_to_specific_checkpoint \
- --predict_with_generate
-```
-
-## Compartilhando seu modelo
-
-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:
-
-```bash
-huggingface-cli login
-```
-
-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`.
-
-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.
-
-O exemplo a seguir mostra como fazer upload de um modelo com um nome de repositĂłrio especĂfico:
-
-```bash
-python examples/pytorch/summarization/run_summarization.py
- --model_name_or_path t5-small \
- --do_train \
- --do_eval \
- --dataset_name cnn_dailymail \
- --dataset_config "3.0.0" \
- --source_prefix "summarize: " \
- --push_to_hub \
- --push_to_hub_model_id finetuned-t5-cnn_dailymail \
- --output_dir /tmp/tst-summarization \
- --per_device_train_batch_size=4 \
- --per_device_eval_batch_size=4 \
- --overwrite_output_dir \
- --predict_with_generate
-```
diff --git a/docs/source/pt/serialization.md b/docs/source/pt/serialization.md
new file mode 100644
index 000000000000..d5a21c7f890d
--- /dev/null
+++ b/docs/source/pt/serialization.md
@@ -0,0 +1,502 @@
+
+
+# Exportando modelos para ONNX
+
+Se vocĂȘ precisar implantar modelos đ€ Transformers em ambientes de produção, recomendamos
+exporta-los para um formato serializado que pode ser carregado e executado em
+tempos de execução e hardware. Neste guia, mostraremos como exportar modelos đ€ Transformers
+para [ONNX (Open Neural Network eXchange)](http://onnx.ai).
+
+
+
+Uma vez exportado, um modelo pode ser otimizado para inferĂȘncia por meio de tĂ©cnicas como
+quantização e poda. Se vocĂȘ estiver interessado em otimizar seus modelos para serem executados com
+mĂĄxima eficiĂȘncia, confira a biblioteca [đ€ Optimum
+](https://github.com/huggingface/optimum).
+
+
+
+ONNX Ă© um padrĂŁo aberto que define um conjunto comum de operadores e um formato de arquivo comum
+para representar modelos de aprendizado profundo em uma ampla variedade de estruturas, incluindo PyTorch e
+TensorFlow. Quando um modelo Ă© exportado para o formato ONNX, esses operadores sĂŁo usados para
+construir um grafo computacional (muitas vezes chamado de _representação intermediåria_) que
+representa o fluxo de dados através da rede neural.
+
+Ao expor um grafo com operadores e tipos de dados padronizados, o ONNX facilita a
+alternar entre os frameworks. Por exemplo, um modelo treinado em PyTorch pode ser exportado para
+formato ONNX e depois importado no TensorFlow (e vice-versa).
+
+đ€ Transformers fornece um pacote [`transformers.onnx`](main_classes/onnx) que permite
+que vocĂȘ converta os checkpoints do modelo em um grafo ONNX aproveitando os objetos de configuração.
+Esses objetos de configuração vĂȘm prontos para vĂĄrias arquiteturas de modelo e sĂŁo
+projetado para ser facilmente extensĂvel a outras arquiteturas.
+
+As configuraçÔes prontas incluem as seguintes arquiteturas:
+
+
+
+- ALBERT
+- BART
+- BEiT
+- BERT
+- BigBird
+- BigBird-Pegasus
+- Blenderbot
+- BlenderbotSmall
+- BLOOM
+- CamemBERT
+- CLIP
+- CodeGen
+- Conditional DETR
+- ConvBERT
+- ConvNeXT
+- ConvNeXTV2
+- Data2VecText
+- Data2VecVision
+- DeBERTa
+- DeBERTa-v2
+- DeiT
+- DETR
+- DistilBERT
+- ELECTRA
+- ERNIE
+- FlauBERT
+- GPT Neo
+- GPT-J
+- GroupViT
+- I-BERT
+- LayoutLM
+- LayoutLMv3
+- LeViT
+- Longformer
+- LongT5
+- M2M100
+- Marian
+- mBART
+- MobileBERT
+- MobileViT
+- MT5
+- OpenAI GPT-2
+- OWL-ViT
+- Perceiver
+- PLBart
+- ResNet
+- RoBERTa
+- RoFormer
+- SegFormer
+- SqueezeBERT
+- Swin Transformer
+- T5
+- Table Transformer
+- Vision Encoder decoder
+- ViT
+- XLM
+- XLM-RoBERTa
+- XLM-RoBERTa-XL
+- YOLOS
+
+Nas próximas duas seçÔes, mostraremos como:
+
+* Exportar um modelo suportado usando o pacote `transformers.onnx`.
+* Exportar um modelo personalizado para uma arquitetura sem suporte.
+
+## Exportando um modelo para ONNX
+
+Para exportar um modelo đ€ Transformers para o ONNX, primeiro vocĂȘ precisa instalar algumas
+dependĂȘncias extras:
+
+```bash
+pip install transformers[onnx]
+```
+
+O pacote `transformers.onnx` pode entĂŁo ser usado como um mĂłdulo Python:
+
+```bash
+python -m transformers.onnx --help
+
+usage: Hugging Face Transformers ONNX exporter [-h] -m MODEL [--feature {causal-lm, ...}] [--opset OPSET] [--atol ATOL] output
+
+positional arguments:
+ output Path indicating where to store generated ONNX model.
+
+optional arguments:
+ -h, --help show this help message and exit
+ -m MODEL, --model MODEL
+ Model ID on huggingface.co or path on disk to load model from.
+ --feature {causal-lm, ...}
+ The type of features to export the model with.
+ --opset OPSET ONNX opset version to export the model with.
+ --atol ATOL Absolute difference tolerance when validating the model.
+```
+
+A exportação de um checkpoint usando uma configuração pronta pode ser feita da seguinte forma:
+
+```bash
+python -m transformers.onnx --model=distilbert-base-uncased onnx/
+```
+
+VocĂȘ deve ver os seguintes logs:
+
+```bash
+Validating ONNX model...
+ -[â] ONNX model output names match reference model ({'last_hidden_state'})
+ - Validating ONNX Model output "last_hidden_state":
+ -[â] (2, 8, 768) matches (2, 8, 768)
+ -[â] all values close (atol: 1e-05)
+All good, model saved at: onnx/model.onnx
+```
+
+Isso exporta um grafo ONNX do ponto de verificação definido pelo argumento `--model`. Nisso
+Por exemplo, Ă© `distilbert-base-uncased`, mas pode ser qualquer checkpoint no Hugging
+Face Hub ou um armazenado localmente.
+
+O arquivo `model.onnx` resultante pode ser executado em um dos [muitos
+aceleradores](https://onnx.ai/supported-tools.html#deployModel) que suportam o ONNX
+padrĂŁo. Por exemplo, podemos carregar e executar o modelo com [ONNX
+Tempo de execução](https://onnxruntime.ai/) da seguinte forma:
+
+```python
+>>> from transformers import AutoTokenizer
+>>> from onnxruntime import InferenceSession
+
+>>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
+>>> session = InferenceSession("onnx/model.onnx")
+>>> # ONNX Runtime expects NumPy arrays as input
+>>> inputs = tokenizer("Using DistilBERT with ONNX Runtime!", return_tensors="np")
+>>> outputs = session.run(output_names=["last_hidden_state"], input_feed=dict(inputs))
+```
+
+Os nomes de saĂda necessĂĄrios (como `["last_hidden_state"]`) podem ser obtidos pegando uma
+ configuração ONNX de cada modelo. Por exemplo, para DistilBERT temos:
+
+```python
+>>> from transformers.models.distilbert import DistilBertConfig, DistilBertOnnxConfig
+
+>>> config = DistilBertConfig()
+>>> onnx_config = DistilBertOnnxConfig(config)
+>>> print(list(onnx_config.outputs.keys()))
+["last_hidden_state"]
+```
+
+O processo Ă© idĂȘntico para os checkpoints do TensorFlow no Hub. Por exemplo, podemos
+exportar um checkpoint TensorFlow puro do [Keras
+](https://huggingface.co/keras-io) da seguinte forma:
+
+```bash
+python -m transformers.onnx --model=keras-io/transformers-qa onnx/
+```
+
+Para exportar um modelo armazenado localmente, vocĂȘ precisarĂĄ ter os pesos e
+arquivos tokenizer armazenados em um diretĂłrio. Por exemplo, podemos carregar e salvar um checkpoint como:
+
+```python
+>>> from transformers import AutoTokenizer, AutoModelForSequenceClassification
+
+>>> # Load tokenizer and PyTorch weights form the Hub
+>>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
+>>> pt_model = AutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased")
+>>> # Save to disk
+>>> tokenizer.save_pretrained("local-pt-checkpoint")
+>>> pt_model.save_pretrained("local-pt-checkpoint")
+```
+
+Uma vez que o checkpoint Ă© salvo, podemos exportĂĄ-lo para o ONNX apontando o `--model`
+argumento do pacote `transformers.onnx` para o diretĂłrio desejado:
+
+```bash
+python -m transformers.onnx --model=local-pt-checkpoint onnx/
+```
+
+```python
+>>> from transformers import AutoTokenizer, TFAutoModelForSequenceClassification
+
+>>> # Load tokenizer and TensorFlow weights from the Hub
+>>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
+>>> tf_model = TFAutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased")
+>>> # Save to disk
+>>> tokenizer.save_pretrained("local-tf-checkpoint")
+>>> tf_model.save_pretrained("local-tf-checkpoint")
+```
+
+Uma vez que o checkpoint Ă© salvo, podemos exportĂĄ-lo para o ONNX apontando o `--model`
+argumento do pacote `transformers.onnx` para o diretĂłrio desejado:
+
+```bash
+python -m transformers.onnx --model=local-tf-checkpoint onnx/
+```
+
+## Selecionando features para diferentes tarefas do modelo
+
+Cada configuração pronta vem com um conjunto de _features_ que permitem exportar
+modelos para diferentes tipos de tarefas. Conforme mostrado na tabela abaixo, cada recurso Ă©
+associado a uma `AutoClass` diferente:
+
+| Feature | Auto Class |
+| ------------------------------------ | ------------------------------------ |
+| `causal-lm`, `causal-lm-with-past` | `AutoModelForCausalLM` |
+| `default`, `default-with-past` | `AutoModel` |
+| `masked-lm` | `AutoModelForMaskedLM` |
+| `question-answering` | `AutoModelForQuestionAnswering` |
+| `seq2seq-lm`, `seq2seq-lm-with-past` | `AutoModelForSeq2SeqLM` |
+| `sequence-classification` | `AutoModelForSequenceClassification` |
+| `token-classification` | `AutoModelForTokenClassification` |
+
+Para cada configuração, vocĂȘ pode encontrar a lista de recursos suportados por meio do
+[`~transformers.onnx.FeaturesManager`]. Por exemplo, para DistilBERT temos:
+
+```python
+>>> from transformers.onnx.features import FeaturesManager
+
+>>> distilbert_features = list(FeaturesManager.get_supported_features_for_model_type("distilbert").keys())
+>>> print(distilbert_features)
+["default", "masked-lm", "causal-lm", "sequence-classification", "token-classification", "question-answering"]
+```
+
+VocĂȘ pode entĂŁo passar um desses recursos para o argumento `--feature` no
+pacote `transformers.onnx`. Por exemplo, para exportar um modelo de classificação de texto, podemos
+escolher um modelo ajustado no Hub e executar:
+
+```bash
+python -m transformers.onnx --model=distilbert-base-uncased-finetuned-sst-2-english \
+ --feature=sequence-classification onnx/
+```
+
+Isso exibe os seguintes logs:
+
+```bash
+Validating ONNX model...
+ -[â] ONNX model output names match reference model ({'logits'})
+ - Validating ONNX Model output "logits":
+ -[â] (2, 2) matches (2, 2)
+ -[â] all values close (atol: 1e-05)
+All good, model saved at: onnx/model.onnx
+```
+
+Observe que, neste caso, os nomes de saĂda do modelo ajustado sĂŁo `logits`
+em vez do `last_hidden_state` que vimos com o checkpoint `distilbert-base-uncased`
+mais cedo. Isso Ă© esperado, pois o modelo ajustado (fine-tuned) possui uma cabeça de classificação de sequĂȘncia.
+
+
+
+Os recursos que tĂȘm um sufixo `with-pass` (como `causal-lm-with-pass`) correspondem a
+classes de modelo com estados ocultos pré-computados (chave e valores nos blocos de atenção)
+que pode ser usado para decodificação autorregressiva råpida.
+
+
+
+
+
+Para modelos do tipo `VisionEncoderDecoder`, as partes do codificador e do decodificador sĂŁo
+exportados separadamente como dois arquivos ONNX chamados `encoder_model.onnx` e `decoder_model.onnx` respectivamente.
+
+
+
+## Exportando um modelo para uma arquitetura sem suporte
+
+Se vocĂȘ deseja exportar um modelo cuja arquitetura nĂŁo Ă© suportada nativamente pela
+biblioteca, hĂĄ trĂȘs etapas principais a seguir:
+
+1. Implemente uma configuração ONNX personalizada.
+2. Exporte o modelo para o ONNX.
+3. Valide as saĂdas do PyTorch e dos modelos exportados.
+
+Nesta seção, veremos como o DistilBERT foi implementado para mostrar o que estå envolvido
+em cada passo.
+
+### Implementando uma configuração ONNX personalizada
+
+Vamos começar com o objeto de configuração ONNX. Fornecemos trĂȘs classes abstratas que
+vocĂȘ deve herdar, dependendo do tipo de arquitetura de modelo que deseja exportar:
+
+* Modelos baseados em codificador herdam de [`~onnx.config.OnnxConfig`]
+* Modelos baseados em decodificador herdam de [`~onnx.config.OnnxConfigWithPast`]
+* Os modelos codificador-decodificador herdam de [`~onnx.config.OnnxSeq2SeqConfigWithPast`]
+
+
+
+Uma boa maneira de implementar uma configuração ONNX personalizada é observar as
+implementação no arquivo `configuration_.py` de uma arquitetura semelhante.
+
+
+
+Como o DistilBERT é um modelo baseado em codificador, sua configuração é herdada de
+`OnnxConfig`:
+
+```python
+>>> from typing import Mapping, OrderedDict
+>>> from transformers.onnx import OnnxConfig
+
+
+>>> class DistilBertOnnxConfig(OnnxConfig):
+... @property
+... def inputs(self) -> Mapping[str, Mapping[int, str]]:
+... return OrderedDict(
+... [
+... ("input_ids", {0: "batch", 1: "sequence"}),
+... ("attention_mask", {0: "batch", 1: "sequence"}),
+... ]
+... )
+```
+
+Todo objeto de configuração deve implementar a propriedade `inputs` e retornar um mapeamento,
+onde cada chave corresponde a uma entrada esperada e cada valor indica o eixo
+dessa entrada. Para o DistilBERT, podemos ver que duas entradas sĂŁo necessĂĄrias: `input_ids` e
+`attention_mask`. Essas entradas tĂȘm a mesma forma de `(batch_size, sequence_length)`
+é por isso que vemos os mesmos eixos usados na configuração.
+
+
+
+Notice that `inputs` property for `DistilBertOnnxConfig` returns an `OrderedDict`. This
+ensures that the inputs are matched with their relative position within the
+`PreTrainedModel.forward()` method when tracing the graph. We recommend using an
+`OrderedDict` for the `inputs` and `outputs` properties when implementing custom ONNX
+configurations.
+
+Observe que a propriedade `inputs` para `DistilBertOnnxConfig` retorna um `OrderedDict`. Este
+garante que as entradas sejam combinadas com sua posição relativa dentro do
+método `PreTrainedModel.forward()` ao traçar o grafo. Recomendamos o uso de um
+`OrderedDict` para as propriedades `inputs` e `outputs` ao implementar configuraçÔes personalizadas ONNX.
+
+
+
+Depois de implementar uma configuração ONNX, vocĂȘ pode instanciĂĄ-la fornecendo a
+configuração do modelo base da seguinte forma:
+
+```python
+>>> from transformers import AutoConfig
+
+>>> config = AutoConfig.from_pretrained("distilbert-base-uncased")
+>>> onnx_config = DistilBertOnnxConfig(config)
+```
+
+O objeto resultante tem vĂĄrias propriedades Ășteis. Por exemplo, vocĂȘ pode visualizar o conjunto de operadores ONNX
+ que serå usado durante a exportação:
+
+```python
+>>> print(onnx_config.default_onnx_opset)
+11
+```
+
+VocĂȘ tambĂ©m pode visualizar as saĂdas associadas ao modelo da seguinte forma:
+
+```python
+>>> print(onnx_config.outputs)
+OrderedDict([("last_hidden_state", {0: "batch", 1: "sequence"})])
+```
+
+Observe que a propriedade outputs segue a mesma estrutura das entradas; ele retorna um
+`OrderedDict` de saĂdas nomeadas e suas formas. A estrutura de saĂda estĂĄ ligada a
+escolha do recurso com o qual a configuração é inicializada. Por padrão, a configuração do ONNX
+é inicializada com o recurso `default` que corresponde à exportação de um
+modelo carregado com a classe `AutoModel`. Se vocĂȘ deseja exportar um modelo para outra tarefa,
+apenas forneça um recurso diferente para o argumento `task` quando vocĂȘ inicializar a configuração ONNX
+. Por exemplo, se quisermos exportar o DistilBERT com uma sequĂȘncia
+de classificação, poderĂamos usar:
+
+```python
+>>> from transformers import AutoConfig
+
+>>> config = AutoConfig.from_pretrained("distilbert-base-uncased")
+>>> onnx_config_for_seq_clf = DistilBertOnnxConfig(config, task="sequence-classification")
+>>> print(onnx_config_for_seq_clf.outputs)
+OrderedDict([('logits', {0: 'batch'})])
+```
+
+
+
+Todas as propriedades e métodos båsicos associados a [`~onnx.config.OnnxConfig`] e
+as outras classes de configuração podem ser substituĂdas se necessĂĄrio. Confira [`BartOnnxConfig`]
+para um exemplo avançado.
+
+
+
+### Exportando um modelo
+
+Depois de ter implementado a configuração do ONNX, o próximo passo é exportar o modelo.
+Aqui podemos usar a função `export()` fornecida pelo pacote `transformers.onnx`.
+Esta função espera a configuração do ONNX, juntamente com o modelo base e o tokenizer,
+e o caminho para salvar o arquivo exportado:
+
+```python
+>>> from pathlib import Path
+>>> from transformers.onnx import export
+>>> from transformers import AutoTokenizer, AutoModel
+
+>>> onnx_path = Path("model.onnx")
+>>> model_ckpt = "distilbert-base-uncased"
+>>> base_model = AutoModel.from_pretrained(model_ckpt)
+>>> tokenizer = AutoTokenizer.from_pretrained(model_ckpt)
+
+>>> onnx_inputs, onnx_outputs = export(tokenizer, base_model, onnx_config, onnx_config.default_onnx_opset, onnx_path)
+```
+
+Os `onnx_inputs` e `onnx_outputs` retornados pela função `export()` são listas de
+ chaves definidas nas propriedades `inputs` e `outputs` da configuração. Uma vez que o
+modelo Ă© exportado, vocĂȘ pode testar se o modelo estĂĄ bem formado da seguinte forma:
+
+```python
+>>> import onnx
+
+>>> onnx_model = onnx.load("model.onnx")
+>>> onnx.checker.check_model(onnx_model)
+```
+
+
+
+Se o seu modelo for maior que 2GB, vocĂȘ verĂĄ que muitos arquivos adicionais sĂŁo criados
+durante a exportação. Isso é _esperado_ porque o ONNX usa [Protocol
+Buffers](https://developers.google.com/protocol-buffers/) para armazenar o modelo e estes
+tĂȘm um limite de tamanho de 2GB. Veja a [ONNX
+documentação](https://github.com/onnx/onnx/blob/master/docs/ExternalData.md) para
+instruçÔes sobre como carregar modelos com dados externos.
+
+
+
+### Validando a saĂda dos modelos
+
+A etapa final Ă© validar se as saĂdas do modelo base e exportado concordam
+dentro de alguma tolerùncia absoluta. Aqui podemos usar a função `validate_model_outputs()`
+fornecida pelo pacote `transformers.onnx` da seguinte forma:
+
+```python
+>>> from transformers.onnx import validate_model_outputs
+
+>>> validate_model_outputs(
+... onnx_config, tokenizer, base_model, onnx_path, onnx_outputs, onnx_config.atol_for_validation
+... )
+```
+
+Esta função usa o método [`~transformers.onnx.OnnxConfig.generate_dummy_inputs`] para
+gerar entradas para o modelo base e o exportado, e a tolerĂąncia absoluta pode ser
+definida na configuração. Geralmente encontramos concordùncia numérica em 1e-6 a 1e-4
+de alcance, embora qualquer coisa menor que 1e-3 provavelmente esteja OK.
+
+## Contribuindo com uma nova configuração para đ€ Transformers
+
+Estamos procurando expandir o conjunto de configuraçÔes prontas e receber contribuiçÔes
+da comunidade! Se vocĂȘ gostaria de contribuir para a biblioteca, vocĂȘ
+precisarĂĄ:
+
+* Implemente a configuração do ONNX no arquivo `configuration_.py` correspondente
+Arquivo
+* Incluir a arquitetura do modelo e recursos correspondentes em
+ [`~onnx.features.FeatureManager`]
+* Adicione sua arquitetura de modelo aos testes em `test_onnx_v2.py`
+
+Confira como ficou a configuração do [IBERT
+](https://github.com/huggingface/transformers/pull/14868/files) para obter uma
+idéia do que estå envolvido.
diff --git a/docs/source/pt/serialization.mdx b/docs/source/pt/serialization.mdx
deleted file mode 100644
index 5e95d5951215..000000000000
--- a/docs/source/pt/serialization.mdx
+++ /dev/null
@@ -1,498 +0,0 @@
-
-
-# Exportando modelos para ONNX
-
-Se vocĂȘ precisar implantar modelos đ€ Transformers em ambientes de produção, recomendamos
-exporta-los para um formato serializado que pode ser carregado e executado em
-tempos de execução e hardware. Neste guia, mostraremos como exportar modelos đ€ Transformers
-para [ONNX (Open Neural Network eXchange)](http://onnx.ai).
-
-
-
-Uma vez exportado, um modelo pode ser otimizado para inferĂȘncia por meio de tĂ©cnicas como
-quantização e poda. Se vocĂȘ estiver interessado em otimizar seus modelos para serem executados com
-mĂĄxima eficiĂȘncia, confira a biblioteca [đ€ Optimum
-](https://github.com/huggingface/optimum).
-
-
-
-ONNX Ă© um padrĂŁo aberto que define um conjunto comum de operadores e um formato de arquivo comum
-para representar modelos de aprendizado profundo em uma ampla variedade de estruturas, incluindo PyTorch e
-TensorFlow. Quando um modelo Ă© exportado para o formato ONNX, esses operadores sĂŁo usados para
-construir um grafo computacional (muitas vezes chamado de _representação intermediåria_) que
-representa o fluxo de dados através da rede neural.
-
-Ao expor um grafo com operadores e tipos de dados padronizados, o ONNX facilita a
-alternar entre os frameworks. Por exemplo, um modelo treinado em PyTorch pode ser exportado para
-formato ONNX e depois importado no TensorFlow (e vice-versa).
-
-đ€ Transformers fornece um pacote [`transformers.onnx`](main_classes/onnx) que permite
-que vocĂȘ converta os checkpoints do modelo em um grafo ONNX aproveitando os objetos de configuração.
-Esses objetos de configuração vĂȘm prontos para vĂĄrias arquiteturas de modelo e sĂŁo
-projetado para ser facilmente extensĂvel a outras arquiteturas.
-
-As configuraçÔes prontas incluem as seguintes arquiteturas:
-
-
-
-- ALBERT
-- BART
-- BEiT
-- BERT
-- BigBird
-- BigBird-Pegasus
-- Blenderbot
-- BlenderbotSmall
-- BLOOM
-- CamemBERT
-- CLIP
-- CodeGen
-- Conditional DETR
-- ConvBERT
-- ConvNeXT
-- ConvNeXTV2
-- Data2VecText
-- Data2VecVision
-- DeBERTa
-- DeBERTa-v2
-- DeiT
-- DETR
-- DistilBERT
-- ELECTRA
-- ERNIE
-- FlauBERT
-- GPT Neo
-- GPT-J
-- GroupViT
-- I-BERT
-- LayoutLM
-- LayoutLMv3
-- LeViT
-- Longformer
-- LongT5
-- M2M100
-- Marian
-- mBART
-- MobileBERT
-- MobileViT
-- MT5
-- OpenAI GPT-2
-- OWL-ViT
-- Perceiver
-- PLBart
-- ResNet
-- RoBERTa
-- RoFormer
-- SegFormer
-- SqueezeBERT
-- Swin Transformer
-- T5
-- Table Transformer
-- Vision Encoder decoder
-- ViT
-- XLM
-- XLM-RoBERTa
-- XLM-RoBERTa-XL
-- YOLOS
-
-Nas próximas duas seçÔes, mostraremos como:
-
-* Exportar um modelo suportado usando o pacote `transformers.onnx`.
-* Exportar um modelo personalizado para uma arquitetura sem suporte.
-
-## Exportando um modelo para ONNX
-
-Para exportar um modelo đ€ Transformers para o ONNX, primeiro vocĂȘ precisa instalar algumas
-dependĂȘncias extras:
-
-```bash
-pip install transformers[onnx]
-```
-
-O pacote `transformers.onnx` pode entĂŁo ser usado como um mĂłdulo Python:
-
-```bash
-python -m transformers.onnx --help
-
-usage: Hugging Face Transformers ONNX exporter [-h] -m MODEL [--feature {causal-lm, ...}] [--opset OPSET] [--atol ATOL] output
-
-positional arguments:
- output Path indicating where to store generated ONNX model.
-
-optional arguments:
- -h, --help show this help message and exit
- -m MODEL, --model MODEL
- Model ID on huggingface.co or path on disk to load model from.
- --feature {causal-lm, ...}
- The type of features to export the model with.
- --opset OPSET ONNX opset version to export the model with.
- --atol ATOL Absolute difference tolerance when validating the model.
-```
-
-A exportação de um checkpoint usando uma configuração pronta pode ser feita da seguinte forma:
-
-```bash
-python -m transformers.onnx --model=distilbert-base-uncased onnx/
-```
-
-VocĂȘ deve ver os seguintes logs:
-
-```bash
-Validating ONNX model...
- -[â] ONNX model output names match reference model ({'last_hidden_state'})
- - Validating ONNX Model output "last_hidden_state":
- -[â] (2, 8, 768) matches (2, 8, 768)
- -[â] all values close (atol: 1e-05)
-All good, model saved at: onnx/model.onnx
-```
-
-Isso exporta um grafo ONNX do ponto de verificação definido pelo argumento `--model`. Nisso
-Por exemplo, Ă© `distilbert-base-uncased`, mas pode ser qualquer checkpoint no Hugging
-Face Hub ou um armazenado localmente.
-
-O arquivo `model.onnx` resultante pode ser executado em um dos [muitos
-aceleradores](https://onnx.ai/supported-tools.html#deployModel) que suportam o ONNX
-padrĂŁo. Por exemplo, podemos carregar e executar o modelo com [ONNX
-Tempo de execução](https://onnxruntime.ai/) da seguinte forma:
-
-```python
->>> from transformers import AutoTokenizer
->>> from onnxruntime import InferenceSession
-
->>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
->>> session = InferenceSession("onnx/model.onnx")
->>> # ONNX Runtime expects NumPy arrays as input
->>> inputs = tokenizer("Using DistilBERT with ONNX Runtime!", return_tensors="np")
->>> outputs = session.run(output_names=["last_hidden_state"], input_feed=dict(inputs))
-```
-
-Os nomes de saĂda necessĂĄrios (como `["last_hidden_state"]`) podem ser obtidos pegando uma
- configuração ONNX de cada modelo. Por exemplo, para DistilBERT temos:
-
-```python
->>> from transformers.models.distilbert import DistilBertConfig, DistilBertOnnxConfig
-
->>> config = DistilBertConfig()
->>> onnx_config = DistilBertOnnxConfig(config)
->>> print(list(onnx_config.outputs.keys()))
-["last_hidden_state"]
-```
-
-O processo Ă© idĂȘntico para os checkpoints do TensorFlow no Hub. Por exemplo, podemos
-exportar um checkpoint TensorFlow puro do [Keras
-](https://huggingface.co/keras-io) da seguinte forma:
-
-```bash
-python -m transformers.onnx --model=keras-io/transformers-qa onnx/
-```
-
-Para exportar um modelo armazenado localmente, vocĂȘ precisarĂĄ ter os pesos e
-arquivos tokenizer armazenados em um diretĂłrio. Por exemplo, podemos carregar e salvar um checkpoint como:
-
-```python
->>> from transformers import AutoTokenizer, AutoModelForSequenceClassification
-
->>> # Load tokenizer and PyTorch weights form the Hub
->>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
->>> pt_model = AutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased")
->>> # Save to disk
->>> tokenizer.save_pretrained("local-pt-checkpoint")
->>> pt_model.save_pretrained("local-pt-checkpoint")
-```
-
-Uma vez que o checkpoint Ă© salvo, podemos exportĂĄ-lo para o ONNX apontando o `--model`
-argumento do pacote `transformers.onnx` para o diretĂłrio desejado:
-
-```bash
-python -m transformers.onnx --model=local-pt-checkpoint onnx/
-```
-
-```python
->>> from transformers import AutoTokenizer, TFAutoModelForSequenceClassification
-
->>> # Load tokenizer and TensorFlow weights from the Hub
->>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
->>> tf_model = TFAutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased")
->>> # Save to disk
->>> tokenizer.save_pretrained("local-tf-checkpoint")
->>> tf_model.save_pretrained("local-tf-checkpoint")
-```
-
-Uma vez que o checkpoint Ă© salvo, podemos exportĂĄ-lo para o ONNX apontando o `--model`
-argumento do pacote `transformers.onnx` para o diretĂłrio desejado:
-
-```bash
-python -m transformers.onnx --model=local-tf-checkpoint onnx/
-```
-
-## Selecionando features para diferentes tarefas do modelo
-
-Cada configuração pronta vem com um conjunto de _features_ que permitem exportar
-modelos para diferentes tipos de tarefas. Conforme mostrado na tabela abaixo, cada recurso Ă©
-associado a uma `AutoClass` diferente:
-
-| Feature | Auto Class |
-| ------------------------------------ | ------------------------------------ |
-| `causal-lm`, `causal-lm-with-past` | `AutoModelForCausalLM` |
-| `default`, `default-with-past` | `AutoModel` |
-| `masked-lm` | `AutoModelForMaskedLM` |
-| `question-answering` | `AutoModelForQuestionAnswering` |
-| `seq2seq-lm`, `seq2seq-lm-with-past` | `AutoModelForSeq2SeqLM` |
-| `sequence-classification` | `AutoModelForSequenceClassification` |
-| `token-classification` | `AutoModelForTokenClassification` |
-
-Para cada configuração, vocĂȘ pode encontrar a lista de recursos suportados por meio do
-[`~transformers.onnx.FeaturesManager`]. Por exemplo, para DistilBERT temos:
-
-```python
->>> from transformers.onnx.features import FeaturesManager
-
->>> distilbert_features = list(FeaturesManager.get_supported_features_for_model_type("distilbert").keys())
->>> print(distilbert_features)
-["default", "masked-lm", "causal-lm", "sequence-classification", "token-classification", "question-answering"]
-```
-
-VocĂȘ pode entĂŁo passar um desses recursos para o argumento `--feature` no
-pacote `transformers.onnx`. Por exemplo, para exportar um modelo de classificação de texto, podemos
-escolher um modelo ajustado no Hub e executar:
-
-```bash
-python -m transformers.onnx --model=distilbert-base-uncased-finetuned-sst-2-english \
- --feature=sequence-classification onnx/
-```
-
-Isso exibe os seguintes logs:
-
-```bash
-Validating ONNX model...
- -[â] ONNX model output names match reference model ({'logits'})
- - Validating ONNX Model output "logits":
- -[â] (2, 2) matches (2, 2)
- -[â] all values close (atol: 1e-05)
-All good, model saved at: onnx/model.onnx
-```
-
-Observe que, neste caso, os nomes de saĂda do modelo ajustado sĂŁo `logits`
-em vez do `last_hidden_state` que vimos com o checkpoint `distilbert-base-uncased`
-mais cedo. Isso Ă© esperado, pois o modelo ajustado (fine-tuned) possui uma cabeça de classificação de sequĂȘncia.
-
-
-
-Os recursos que tĂȘm um sufixo `with-pass` (como `causal-lm-with-pass`) correspondem a
-classes de modelo com estados ocultos pré-computados (chave e valores nos blocos de atenção)
-que pode ser usado para decodificação autorregressiva råpida.
-
-
-
-
-
-Para modelos do tipo `VisionEncoderDecoder`, as partes do codificador e do decodificador sĂŁo
-exportados separadamente como dois arquivos ONNX chamados `encoder_model.onnx` e `decoder_model.onnx` respectivamente.
-
-
-
-## Exportando um modelo para uma arquitetura sem suporte
-
-Se vocĂȘ deseja exportar um modelo cuja arquitetura nĂŁo Ă© suportada nativamente pela
-biblioteca, hĂĄ trĂȘs etapas principais a seguir:
-
-1. Implemente uma configuração ONNX personalizada.
-2. Exporte o modelo para o ONNX.
-3. Valide as saĂdas do PyTorch e dos modelos exportados.
-
-Nesta seção, veremos como o DistilBERT foi implementado para mostrar o que estå envolvido
-em cada passo.
-
-### Implementando uma configuração ONNX personalizada
-
-Vamos começar com o objeto de configuração ONNX. Fornecemos trĂȘs classes abstratas que
-vocĂȘ deve herdar, dependendo do tipo de arquitetura de modelo que deseja exportar:
-
-* Modelos baseados em codificador herdam de [`~onnx.config.OnnxConfig`]
-* Modelos baseados em decodificador herdam de [`~onnx.config.OnnxConfigWithPast`]
-* Os modelos codificador-decodificador herdam de [`~onnx.config.OnnxSeq2SeqConfigWithPast`]
-
-
-
-Uma boa maneira de implementar uma configuração ONNX personalizada é observar as
-implementação no arquivo `configuration_.py` de uma arquitetura semelhante.
-
-
-
-Como o DistilBERT é um modelo baseado em codificador, sua configuração é herdada de
-`OnnxConfig`:
-
-```python
->>> from typing import Mapping, OrderedDict
->>> from transformers.onnx import OnnxConfig
-
-
->>> class DistilBertOnnxConfig(OnnxConfig):
-... @property
-... def inputs(self) -> Mapping[str, Mapping[int, str]]:
-... return OrderedDict(
-... [
-... ("input_ids", {0: "batch", 1: "sequence"}),
-... ("attention_mask", {0: "batch", 1: "sequence"}),
-... ]
-... )
-```
-
-Todo objeto de configuração deve implementar a propriedade `inputs` e retornar um mapeamento,
-onde cada chave corresponde a uma entrada esperada e cada valor indica o eixo
-dessa entrada. Para o DistilBERT, podemos ver que duas entradas sĂŁo necessĂĄrias: `input_ids` e
-`attention_mask`. Essas entradas tĂȘm a mesma forma de `(batch_size, sequence_length)`
-é por isso que vemos os mesmos eixos usados na configuração.
-
-
-
-Notice that `inputs` property for `DistilBertOnnxConfig` returns an `OrderedDict`. This
-ensures that the inputs are matched with their relative position within the
-`PreTrainedModel.forward()` method when tracing the graph. We recommend using an
-`OrderedDict` for the `inputs` and `outputs` properties when implementing custom ONNX
-configurations.
-
-Observe que a propriedade `inputs` para `DistilBertOnnxConfig` retorna um `OrderedDict`. Este
-garante que as entradas sejam combinadas com sua posição relativa dentro do
-método `PreTrainedModel.forward()` ao traçar o grafo. Recomendamos o uso de um
-`OrderedDict` para as propriedades `inputs` e `outputs` ao implementar configuraçÔes personalizadas ONNX.
-
-
-
-Depois de implementar uma configuração ONNX, vocĂȘ pode instanciĂĄ-la fornecendo a
-configuração do modelo base da seguinte forma:
-
-```python
->>> from transformers import AutoConfig
-
->>> config = AutoConfig.from_pretrained("distilbert-base-uncased")
->>> onnx_config = DistilBertOnnxConfig(config)
-```
-
-O objeto resultante tem vĂĄrias propriedades Ășteis. Por exemplo, vocĂȘ pode visualizar o conjunto de operadores ONNX
- que serå usado durante a exportação:
-
-```python
->>> print(onnx_config.default_onnx_opset)
-11
-```
-
-VocĂȘ tambĂ©m pode visualizar as saĂdas associadas ao modelo da seguinte forma:
-
-```python
->>> print(onnx_config.outputs)
-OrderedDict([("last_hidden_state", {0: "batch", 1: "sequence"})])
-```
-
-Observe que a propriedade outputs segue a mesma estrutura das entradas; ele retorna um
-`OrderedDict` de saĂdas nomeadas e suas formas. A estrutura de saĂda estĂĄ ligada a
-escolha do recurso com o qual a configuração é inicializada. Por padrão, a configuração do ONNX
-é inicializada com o recurso `default` que corresponde à exportação de um
-modelo carregado com a classe `AutoModel`. Se vocĂȘ deseja exportar um modelo para outra tarefa,
-apenas forneça um recurso diferente para o argumento `task` quando vocĂȘ inicializar a configuração ONNX
-. Por exemplo, se quisermos exportar o DistilBERT com uma sequĂȘncia
-de classificação, poderĂamos usar:
-
-```python
->>> from transformers import AutoConfig
-
->>> config = AutoConfig.from_pretrained("distilbert-base-uncased")
->>> onnx_config_for_seq_clf = DistilBertOnnxConfig(config, task="sequence-classification")
->>> print(onnx_config_for_seq_clf.outputs)
-OrderedDict([('logits', {0: 'batch'})])
-```
-
-
-
-Todas as propriedades e métodos båsicos associados a [`~onnx.config.OnnxConfig`] e
-as outras classes de configuração podem ser substituĂdas se necessĂĄrio. Confira [`BartOnnxConfig`]
-para um exemplo avançado.
-
-
-
-### Exportando um modelo
-
-Depois de ter implementado a configuração do ONNX, o próximo passo é exportar o modelo.
-Aqui podemos usar a função `export()` fornecida pelo pacote `transformers.onnx`.
-Esta função espera a configuração do ONNX, juntamente com o modelo base e o tokenizer,
-e o caminho para salvar o arquivo exportado:
-
-```python
->>> from pathlib import Path
->>> from transformers.onnx import export
->>> from transformers import AutoTokenizer, AutoModel
-
->>> onnx_path = Path("model.onnx")
->>> model_ckpt = "distilbert-base-uncased"
->>> base_model = AutoModel.from_pretrained(model_ckpt)
->>> tokenizer = AutoTokenizer.from_pretrained(model_ckpt)
-
->>> onnx_inputs, onnx_outputs = export(tokenizer, base_model, onnx_config, onnx_config.default_onnx_opset, onnx_path)
-```
-
-Os `onnx_inputs` e `onnx_outputs` retornados pela função `export()` são listas de
- chaves definidas nas propriedades `inputs` e `outputs` da configuração. Uma vez que o
-modelo Ă© exportado, vocĂȘ pode testar se o modelo estĂĄ bem formado da seguinte forma:
-
-```python
->>> import onnx
-
->>> onnx_model = onnx.load("model.onnx")
->>> onnx.checker.check_model(onnx_model)
-```
-
-
-
-Se o seu modelo for maior que 2GB, vocĂȘ verĂĄ que muitos arquivos adicionais sĂŁo criados
-durante a exportação. Isso é _esperado_ porque o ONNX usa [Protocol
-Buffers](https://developers.google.com/protocol-buffers/) para armazenar o modelo e estes
-tĂȘm um limite de tamanho de 2GB. Veja a [ONNX
-documentação](https://github.com/onnx/onnx/blob/master/docs/ExternalData.md) para
-instruçÔes sobre como carregar modelos com dados externos.
-
-
-
-### Validando a saĂda dos modelos
-
-A etapa final Ă© validar se as saĂdas do modelo base e exportado concordam
-dentro de alguma tolerùncia absoluta. Aqui podemos usar a função `validate_model_outputs()`
-fornecida pelo pacote `transformers.onnx` da seguinte forma:
-
-```python
->>> from transformers.onnx import validate_model_outputs
-
->>> validate_model_outputs(
-... onnx_config, tokenizer, base_model, onnx_path, onnx_outputs, onnx_config.atol_for_validation
-... )
-```
-
-Esta função usa o método [`~transformers.onnx.OnnxConfig.generate_dummy_inputs`] para
-gerar entradas para o modelo base e o exportado, e a tolerĂąncia absoluta pode ser
-definida na configuração. Geralmente encontramos concordùncia numérica em 1e-6 a 1e-4
-de alcance, embora qualquer coisa menor que 1e-3 provavelmente esteja OK.
-
-## Contribuindo com uma nova configuração para đ€ Transformers
-
-Estamos procurando expandir o conjunto de configuraçÔes prontas e receber contribuiçÔes
-da comunidade! Se vocĂȘ gostaria de contribuir para a biblioteca, vocĂȘ
-precisarĂĄ:
-
-* Implemente a configuração do ONNX no arquivo `configuration_.py` correspondente
-Arquivo
-* Incluir a arquitetura do modelo e recursos correspondentes em
- [`~onnx.features.FeatureManager`]
-* Adicione sua arquitetura de modelo aos testes em `test_onnx_v2.py`
-
-Confira como ficou a configuração do [IBERT
-](https://github.com/huggingface/transformers/pull/14868/files) para obter uma
-idéia do que estå envolvido.
diff --git a/docs/source/pt/tasks/sequence_classification.md b/docs/source/pt/tasks/sequence_classification.md
new file mode 100644
index 000000000000..cc04f5dbaece
--- /dev/null
+++ b/docs/source/pt/tasks/sequence_classification.md
@@ -0,0 +1,216 @@
+
+
+# Classificação de texto
+
+
+
+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.
+
+Este guia mostrarĂĄ como realizar o fine-tuning do [DistilBERT](https://huggingface.co/distilbert-base-uncased) no conjunto de dados [IMDb](https://huggingface.co/datasets/imdb) para determinar se a crĂtica de filme Ă© positiva ou negativa.
+
+
+
+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.
+
+
+
+## Carregue o conjunto de dados IMDb
+
+Carregue o conjunto de dados IMDb utilizando a biblioteca đ€ Datasets:
+
+```py
+>>> from datasets import load_dataset
+
+>>> imdb = load_dataset("imdb")
+```
+
+Em seguida, dĂȘ uma olhada em um exemplo:
+
+```py
+>>> imdb["test"][0]
+{
+ "label": 0,
+ "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.",
+}
+```
+
+Existem dois campos neste dataset:
+
+- `text`: uma string contendo o texto da crĂtica do filme.
+- `label`: um valor que pode ser `0` para uma crĂtica negativa ou `1` para uma crĂtica positiva.
+
+## Pré-processamento dos dados
+
+Carregue o tokenizador do DistilBERT para processar o campo `text`:
+
+```py
+>>> from transformers import AutoTokenizer
+
+>>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
+```
+
+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:
+
+```py
+>>> def preprocess_function(examples):
+... return tokenizer(examples["text"], truncation=True)
+```
+
+Use a função [`map`](https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.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:
+
+```py
+tokenized_imdb = imdb.map(preprocess_function, batched=True)
+```
+
+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.
+
+
+
+```py
+>>> from transformers import DataCollatorWithPadding
+
+>>> data_collator = DataCollatorWithPadding(tokenizer=tokenizer)
+```
+
+
+```py
+>>> from transformers import DataCollatorWithPadding
+
+>>> data_collator = DataCollatorWithPadding(tokenizer=tokenizer, return_tensors="tf")
+```
+
+
+
+## Train
+
+
+
+Carregue o DistilBERT com [`AutoModelForSequenceClassification`] junto com o nĂșmero de rĂłtulos esperados:
+
+```py
+>>> from transformers import AutoModelForSequenceClassification, TrainingArguments, Trainer
+
+>>> model = AutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased", num_labels=2)
+```
+
+
+
+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)!
+
+
+
+Nesse ponto, restam apenas trĂȘs passos:
+
+1. Definir seus hiperparĂąmetros de treinamento em [`TrainingArguments`].
+2. Passar os argumentos de treinamento para o [`Trainer`] junto com o modelo, conjunto de dados, tokenizador e o data collator.
+3. Chamar a função [`~Trainer.train`] para executar o fine-tuning do seu modelo.
+
+```py
+>>> training_args = TrainingArguments(
+... output_dir="./results",
+... learning_rate=2e-5,
+... per_device_train_batch_size=16,
+... per_device_eval_batch_size=16,
+... num_train_epochs=5,
+... weight_decay=0.01,
+... )
+
+>>> trainer = Trainer(
+... model=model,
+... args=training_args,
+... train_dataset=tokenized_imdb["train"],
+... eval_dataset=tokenized_imdb["test"],
+... tokenizer=tokenizer,
+... data_collator=data_collator,
+... )
+
+>>> trainer.train()
+```
+
+
+
+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.
+
+
+
+
+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.html#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:
+
+```py
+>>> tf_train_set = tokenized_imdb["train"].to_tf_dataset(
+... columns=["attention_mask", "input_ids", "label"],
+... shuffle=True,
+... batch_size=16,
+... collate_fn=data_collator,
+... )
+
+>>> tf_validation_set = tokenized_imdb["test"].to_tf_dataset(
+... columns=["attention_mask", "input_ids", "label"],
+... shuffle=False,
+... batch_size=16,
+... collate_fn=data_collator,
+... )
+```
+
+
+
+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)!
+
+
+
+Configure o otimizador e alguns hiperparĂąmetros de treinamento:
+
+```py
+>>> from transformers import create_optimizer
+>>> import tensorflow as tf
+
+>>> batch_size = 16
+>>> num_epochs = 5
+>>> batches_per_epoch = len(tokenized_imdb["train"]) // batch_size
+>>> total_train_steps = int(batches_per_epoch * num_epochs)
+>>> optimizer, schedule = create_optimizer(init_lr=2e-5, num_warmup_steps=0, num_train_steps=total_train_steps)
+```
+
+Carregue o DistilBERT com [`TFAutoModelForSequenceClassification`] junto com o nĂșmero de rĂłtulos esperados:
+
+```py
+>>> from transformers import TFAutoModelForSequenceClassification
+
+>>> model = TFAutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased", num_labels=2)
+```
+
+Configure o modelo para treinamento com o método [`compile`](https://keras.io/api/models/model_training_apis/#compile-method):
+
+```py
+>>> import tensorflow as tf
+
+>>> model.compile(optimizer=optimizer)
+```
+
+Chame o método [`fit`](https://keras.io/api/models/model_training_apis/#fit-method) para executar o fine-tuning do modelo:
+
+```py
+>>> model.fit(x=tf_train_set, validation_data=tf_validation_set, epochs=3)
+```
+
+
+
+
+
+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).
+
+
\ No newline at end of file
diff --git a/docs/source/pt/tasks/sequence_classification.mdx b/docs/source/pt/tasks/sequence_classification.mdx
deleted file mode 100644
index 7c443e700d4e..000000000000
--- a/docs/source/pt/tasks/sequence_classification.mdx
+++ /dev/null
@@ -1,212 +0,0 @@
-
-
-# Classificação de texto
-
-
-
-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.
-
-Este guia mostrarĂĄ como realizar o fine-tuning do [DistilBERT](https://huggingface.co/distilbert-base-uncased) no conjunto de dados [IMDb](https://huggingface.co/datasets/imdb) para determinar se a crĂtica de filme Ă© positiva ou negativa.
-
-
-
-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.
-
-
-
-## Carregue o conjunto de dados IMDb
-
-Carregue o conjunto de dados IMDb utilizando a biblioteca đ€ Datasets:
-
-```py
->>> from datasets import load_dataset
-
->>> imdb = load_dataset("imdb")
-```
-
-Em seguida, dĂȘ uma olhada em um exemplo:
-
-```py
->>> imdb["test"][0]
-{
- "label": 0,
- "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.",
-}
-```
-
-Existem dois campos neste dataset:
-
-- `text`: uma string contendo o texto da crĂtica do filme.
-- `label`: um valor que pode ser `0` para uma crĂtica negativa ou `1` para uma crĂtica positiva.
-
-## Pré-processamento dos dados
-
-Carregue o tokenizador do DistilBERT para processar o campo `text`:
-
-```py
->>> from transformers import AutoTokenizer
-
->>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
-```
-
-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:
-
-```py
->>> def preprocess_function(examples):
-... return tokenizer(examples["text"], truncation=True)
-```
-
-Use a função [`map`](https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.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:
-
-```py
-tokenized_imdb = imdb.map(preprocess_function, batched=True)
-```
-
-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.
-
-
-
-```py
->>> from transformers import DataCollatorWithPadding
-
->>> data_collator = DataCollatorWithPadding(tokenizer=tokenizer)
-```
-
-
-```py
->>> from transformers import DataCollatorWithPadding
-
->>> data_collator = DataCollatorWithPadding(tokenizer=tokenizer, return_tensors="tf")
-```
-
-
-
-## Train
-
-
-
-Carregue o DistilBERT com [`AutoModelForSequenceClassification`] junto com o nĂșmero de rĂłtulos esperados:
-
-```py
->>> from transformers import AutoModelForSequenceClassification, TrainingArguments, Trainer
-
->>> model = AutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased", num_labels=2)
-```
-
-
-
-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)!
-
-
-
-Nesse ponto, restam apenas trĂȘs passos:
-
-1. Definir seus hiperparĂąmetros de treinamento em [`TrainingArguments`].
-2. Passar os argumentos de treinamento para o [`Trainer`] junto com o modelo, conjunto de dados, tokenizador e o data collator.
-3. Chamar a função [`~Trainer.train`] para executar o fine-tuning do seu modelo.
-
-```py
->>> training_args = TrainingArguments(
-... output_dir="./results",
-... learning_rate=2e-5,
-... per_device_train_batch_size=16,
-... per_device_eval_batch_size=16,
-... num_train_epochs=5,
-... weight_decay=0.01,
-... )
-
->>> trainer = Trainer(
-... model=model,
-... args=training_args,
-... train_dataset=tokenized_imdb["train"],
-... eval_dataset=tokenized_imdb["test"],
-... tokenizer=tokenizer,
-... data_collator=data_collator,
-... )
-
->>> trainer.train()
-```
-
-
-
-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.
-
-
-
-
-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.html#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:
-
-```py
->>> tf_train_set = tokenized_imdb["train"].to_tf_dataset(
-... columns=["attention_mask", "input_ids", "label"],
-... shuffle=True,
-... batch_size=16,
-... collate_fn=data_collator,
-... )
-
->>> tf_validation_set = tokenized_imdb["test"].to_tf_dataset(
-... columns=["attention_mask", "input_ids", "label"],
-... shuffle=False,
-... batch_size=16,
-... collate_fn=data_collator,
-... )
-```
-
-
-
-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)!
-
-
-
-Configure o otimizador e alguns hiperparĂąmetros de treinamento:
-
-```py
->>> from transformers import create_optimizer
->>> import tensorflow as tf
-
->>> batch_size = 16
->>> num_epochs = 5
->>> batches_per_epoch = len(tokenized_imdb["train"]) // batch_size
->>> total_train_steps = int(batches_per_epoch * num_epochs)
->>> optimizer, schedule = create_optimizer(init_lr=2e-5, num_warmup_steps=0, num_train_steps=total_train_steps)
-```
-
-Carregue o DistilBERT com [`TFAutoModelForSequenceClassification`] junto com o nĂșmero de rĂłtulos esperados:
-
-```py
->>> from transformers import TFAutoModelForSequenceClassification
-
->>> model = TFAutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased", num_labels=2)
-```
-
-Configure o modelo para treinamento com o método [`compile`](https://keras.io/api/models/model_training_apis/#compile-method):
-
-```py
->>> import tensorflow as tf
-
->>> model.compile(optimizer=optimizer)
-```
-
-Chame o método [`fit`](https://keras.io/api/models/model_training_apis/#fit-method) para executar o fine-tuning do modelo:
-
-```py
->>> model.fit(x=tf_train_set, validation_data=tf_validation_set, epochs=3)
-```
-
-
-
-
-
-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).
-
-
\ No newline at end of file
diff --git a/docs/source/pt/tasks/token_classification.md b/docs/source/pt/tasks/token_classification.md
new file mode 100644
index 000000000000..1de82f4a509c
--- /dev/null
+++ b/docs/source/pt/tasks/token_classification.md
@@ -0,0 +1,272 @@
+
+
+# Classificação de tokens
+
+
+
+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.
+
+Este guia mostrarĂĄ como realizar o fine-tuning do [DistilBERT](https://huggingface.co/distilbert-base-uncased) no conjunto de dados [WNUT 17](https://huggingface.co/datasets/wnut_17) para detectar novas entidades.
+
+
+
+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.
+
+
+
+## Carregando o conjunto de dados WNUT 17
+
+Carregue o conjunto de dados WNUT 17 da biblioteca đ€ Datasets:
+
+```py
+>>> from datasets import load_dataset
+
+>>> wnut = load_dataset("wnut_17")
+```
+
+E dĂȘ uma olhada em um exemplo:
+
+```py
+>>> wnut["train"][0]
+{'id': '0',
+ '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],
+ 'tokens': ['@paulwalk', 'It', "'s", 'the', 'view', 'from', 'where', 'I', "'m", 'living', 'for', 'two', 'weeks', '.', 'Empire', 'State', 'Building', '=', 'ESB', '.', 'Pretty', 'bad', 'storm', 'here', 'last', 'evening', '.']
+}
+```
+
+Cada nĂșmero em `ner_tags` representa uma entidade. Converta o nĂșmero em um rĂłtulo para obter mais informaçÔes:
+
+```py
+>>> label_list = wnut["train"].features[f"ner_tags"].feature.names
+>>> label_list
+[
+ "O",
+ "B-corporation",
+ "I-corporation",
+ "B-creative-work",
+ "I-creative-work",
+ "B-group",
+ "I-group",
+ "B-location",
+ "I-location",
+ "B-person",
+ "I-person",
+ "B-product",
+ "I-product",
+]
+```
+
+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:
+
+- `B-` indica o inĂcio de uma entidade.
+- `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`).
+- `0` indica que o token nĂŁo corresponde a nenhuma entidade.
+
+## Pré-processamento
+
+
+
+Carregue o tokenizer do DistilBERT para processar os `tokens`:
+
+```py
+>>> from transformers import AutoTokenizer
+
+>>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
+```
+
+Como a entrada jĂĄ foi dividida em palavras, defina `is_split_into_words=True` para tokenizar as palavras em subpalavras:
+
+```py
+>>> tokenized_input = tokenizer(example["tokens"], is_split_into_words=True)
+>>> tokens = tokenizer.convert_ids_to_tokens(tokenized_input["input_ids"])
+>>> tokens
+['[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]']
+```
+
+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:
+
+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).
+2. Atribuindo o rótulo `-100` aos tokens especiais `[CLS]` e `[SEP]` para que a função de loss do PyTorch ignore eles.
+3. Rotular apenas o primeiro token de uma determinada palavra. Atribuindo `-100` a outros subtokens da mesma palavra.
+
+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:
+
+```py
+>>> def tokenize_and_align_labels(examples):
+... tokenized_inputs = tokenizer(examples["tokens"], truncation=True, is_split_into_words=True)
+
+... labels = []
+... for i, label in enumerate(examples[f"ner_tags"]):
+... word_ids = tokenized_inputs.word_ids(batch_index=i) # Map tokens to their respective word.
+... previous_word_idx = None
+... label_ids = []
+... for word_idx in word_ids: # Set the special tokens to -100.
+... if word_idx is None:
+... label_ids.append(-100)
+... elif word_idx != previous_word_idx: # Only label the first token of a given word.
+... label_ids.append(label[word_idx])
+... else:
+... label_ids.append(-100)
+... previous_word_idx = word_idx
+... labels.append(label_ids)
+
+... tokenized_inputs["labels"] = labels
+... return tokenized_inputs
+```
+
+Use a função [`map`](https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.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:
+
+```py
+>>> tokenized_wnut = wnut.map(tokenize_and_align_labels, batched=True)
+```
+
+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.
+
+
+
+```py
+>>> from transformers import DataCollatorForTokenClassification
+
+>>> data_collator = DataCollatorForTokenClassification(tokenizer=tokenizer)
+```
+
+
+```py
+>>> from transformers import DataCollatorForTokenClassification
+
+>>> data_collator = DataCollatorForTokenClassification(tokenizer=tokenizer, return_tensors="tf")
+```
+
+
+
+## Treinamento
+
+
+
+Carregue o DistilBERT com o [`AutoModelForTokenClassification`] junto com o nĂșmero de rĂłtulos esperados:
+
+```py
+>>> from transformers import AutoModelForTokenClassification, TrainingArguments, Trainer
+
+>>> model = AutoModelForTokenClassification.from_pretrained("distilbert-base-uncased", num_labels=14)
+```
+
+
+
+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)!
+
+
+
+Nesse ponto, restam apenas trĂȘs passos:
+
+1. Definir seus hiperparĂąmetros de treinamento em [`TrainingArguments`].
+2. Passar os argumentos de treinamento para o [`Trainer`] junto com o modelo, conjunto de dados, tokenizador e o data collator.
+3. Chamar a função [`~Trainer.train`] para executar o fine-tuning do seu modelo.
+
+```py
+>>> training_args = TrainingArguments(
+... output_dir="./results",
+... evaluation_strategy="epoch",
+... learning_rate=2e-5,
+... per_device_train_batch_size=16,
+... per_device_eval_batch_size=16,
+... num_train_epochs=3,
+... weight_decay=0.01,
+... )
+
+>>> trainer = Trainer(
+... model=model,
+... args=training_args,
+... train_dataset=tokenized_wnut["train"],
+... eval_dataset=tokenized_wnut["test"],
+... tokenizer=tokenizer,
+... data_collator=data_collator,
+... )
+
+>>> trainer.train()
+```
+
+
+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.html#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:
+
+```py
+>>> tf_train_set = tokenized_wnut["train"].to_tf_dataset(
+... columns=["attention_mask", "input_ids", "labels"],
+... shuffle=True,
+... batch_size=16,
+... collate_fn=data_collator,
+... )
+
+>>> tf_validation_set = tokenized_wnut["validation"].to_tf_dataset(
+... columns=["attention_mask", "input_ids", "labels"],
+... shuffle=False,
+... batch_size=16,
+... collate_fn=data_collator,
+... )
+```
+
+
+
+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)!
+
+
+
+Configure o otimizador e alguns hiperparĂąmetros de treinamento:
+
+```py
+>>> from transformers import create_optimizer
+
+>>> batch_size = 16
+>>> num_train_epochs = 3
+>>> num_train_steps = (len(tokenized_wnut["train"]) // batch_size) * num_train_epochs
+>>> optimizer, lr_schedule = create_optimizer(
+... init_lr=2e-5,
+... num_train_steps=num_train_steps,
+... weight_decay_rate=0.01,
+... num_warmup_steps=0,
+... )
+```
+
+Carregue o DistilBERT com o [`TFAutoModelForTokenClassification`] junto com o nĂșmero de rĂłtulos esperados:
+
+```py
+>>> from transformers import TFAutoModelForTokenClassification
+
+>>> model = TFAutoModelForTokenClassification.from_pretrained("distilbert-base-uncased", num_labels=2)
+```
+
+Configure o modelo para treinamento com o método [`compile`](https://keras.io/api/models/model_training_apis/#compile-method):
+
+```py
+>>> import tensorflow as tf
+
+>>> model.compile(optimizer=optimizer)
+```
+
+Chame o método [`fit`](https://keras.io/api/models/model_training_apis/#fit-method) para executar o fine-tuning do modelo:
+
+```py
+>>> model.fit(x=tf_train_set, validation_data=tf_validation_set, epochs=3)
+```
+
+
+
+
+
+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).
+
+
\ No newline at end of file
diff --git a/docs/source/pt/tasks/token_classification.mdx b/docs/source/pt/tasks/token_classification.mdx
deleted file mode 100644
index 780080a60dd3..000000000000
--- a/docs/source/pt/tasks/token_classification.mdx
+++ /dev/null
@@ -1,268 +0,0 @@
-
-
-# Classificação de tokens
-
-
-
-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.
-
-Este guia mostrarĂĄ como realizar o fine-tuning do [DistilBERT](https://huggingface.co/distilbert-base-uncased) no conjunto de dados [WNUT 17](https://huggingface.co/datasets/wnut_17) para detectar novas entidades.
-
-
-
-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.
-
-
-
-## Carregando o conjunto de dados WNUT 17
-
-Carregue o conjunto de dados WNUT 17 da biblioteca đ€ Datasets:
-
-```py
->>> from datasets import load_dataset
-
->>> wnut = load_dataset("wnut_17")
-```
-
-E dĂȘ uma olhada em um exemplo:
-
-```py
->>> wnut["train"][0]
-{'id': '0',
- '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],
- 'tokens': ['@paulwalk', 'It', "'s", 'the', 'view', 'from', 'where', 'I', "'m", 'living', 'for', 'two', 'weeks', '.', 'Empire', 'State', 'Building', '=', 'ESB', '.', 'Pretty', 'bad', 'storm', 'here', 'last', 'evening', '.']
-}
-```
-
-Cada nĂșmero em `ner_tags` representa uma entidade. Converta o nĂșmero em um rĂłtulo para obter mais informaçÔes:
-
-```py
->>> label_list = wnut["train"].features[f"ner_tags"].feature.names
->>> label_list
-[
- "O",
- "B-corporation",
- "I-corporation",
- "B-creative-work",
- "I-creative-work",
- "B-group",
- "I-group",
- "B-location",
- "I-location",
- "B-person",
- "I-person",
- "B-product",
- "I-product",
-]
-```
-
-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:
-
-- `B-` indica o inĂcio de uma entidade.
-- `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`).
-- `0` indica que o token nĂŁo corresponde a nenhuma entidade.
-
-## Pré-processamento
-
-
-
-Carregue o tokenizer do DistilBERT para processar os `tokens`:
-
-```py
->>> from transformers import AutoTokenizer
-
->>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
-```
-
-Como a entrada jĂĄ foi dividida em palavras, defina `is_split_into_words=True` para tokenizar as palavras em subpalavras:
-
-```py
->>> tokenized_input = tokenizer(example["tokens"], is_split_into_words=True)
->>> tokens = tokenizer.convert_ids_to_tokens(tokenized_input["input_ids"])
->>> tokens
-['[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]']
-```
-
-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:
-
-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).
-2. Atribuindo o rótulo `-100` aos tokens especiais `[CLS]` e `[SEP]` para que a função de loss do PyTorch ignore eles.
-3. Rotular apenas o primeiro token de uma determinada palavra. Atribuindo `-100` a outros subtokens da mesma palavra.
-
-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:
-
-```py
->>> def tokenize_and_align_labels(examples):
-... tokenized_inputs = tokenizer(examples["tokens"], truncation=True, is_split_into_words=True)
-
-... labels = []
-... for i, label in enumerate(examples[f"ner_tags"]):
-... word_ids = tokenized_inputs.word_ids(batch_index=i) # Map tokens to their respective word.
-... previous_word_idx = None
-... label_ids = []
-... for word_idx in word_ids: # Set the special tokens to -100.
-... if word_idx is None:
-... label_ids.append(-100)
-... elif word_idx != previous_word_idx: # Only label the first token of a given word.
-... label_ids.append(label[word_idx])
-... else:
-... label_ids.append(-100)
-... previous_word_idx = word_idx
-... labels.append(label_ids)
-
-... tokenized_inputs["labels"] = labels
-... return tokenized_inputs
-```
-
-Use a função [`map`](https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.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:
-
-```py
->>> tokenized_wnut = wnut.map(tokenize_and_align_labels, batched=True)
-```
-
-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.
-
-
-
-```py
->>> from transformers import DataCollatorForTokenClassification
-
->>> data_collator = DataCollatorForTokenClassification(tokenizer=tokenizer)
-```
-
-
-```py
->>> from transformers import DataCollatorForTokenClassification
-
->>> data_collator = DataCollatorForTokenClassification(tokenizer=tokenizer, return_tensors="tf")
-```
-
-
-
-## Treinamento
-
-
-
-Carregue o DistilBERT com o [`AutoModelForTokenClassification`] junto com o nĂșmero de rĂłtulos esperados:
-
-```py
->>> from transformers import AutoModelForTokenClassification, TrainingArguments, Trainer
-
->>> model = AutoModelForTokenClassification.from_pretrained("distilbert-base-uncased", num_labels=14)
-```
-
-
-
-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)!
-
-
-
-Nesse ponto, restam apenas trĂȘs passos:
-
-1. Definir seus hiperparĂąmetros de treinamento em [`TrainingArguments`].
-2. Passar os argumentos de treinamento para o [`Trainer`] junto com o modelo, conjunto de dados, tokenizador e o data collator.
-3. Chamar a função [`~Trainer.train`] para executar o fine-tuning do seu modelo.
-
-```py
->>> training_args = TrainingArguments(
-... output_dir="./results",
-... evaluation_strategy="epoch",
-... learning_rate=2e-5,
-... per_device_train_batch_size=16,
-... per_device_eval_batch_size=16,
-... num_train_epochs=3,
-... weight_decay=0.01,
-... )
-
->>> trainer = Trainer(
-... model=model,
-... args=training_args,
-... train_dataset=tokenized_wnut["train"],
-... eval_dataset=tokenized_wnut["test"],
-... tokenizer=tokenizer,
-... data_collator=data_collator,
-... )
-
->>> trainer.train()
-```
-
-
-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.html#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:
-
-```py
->>> tf_train_set = tokenized_wnut["train"].to_tf_dataset(
-... columns=["attention_mask", "input_ids", "labels"],
-... shuffle=True,
-... batch_size=16,
-... collate_fn=data_collator,
-... )
-
->>> tf_validation_set = tokenized_wnut["validation"].to_tf_dataset(
-... columns=["attention_mask", "input_ids", "labels"],
-... shuffle=False,
-... batch_size=16,
-... collate_fn=data_collator,
-... )
-```
-
-
-
-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)!
-
-
-
-Configure o otimizador e alguns hiperparĂąmetros de treinamento:
-
-```py
->>> from transformers import create_optimizer
-
->>> batch_size = 16
->>> num_train_epochs = 3
->>> num_train_steps = (len(tokenized_wnut["train"]) // batch_size) * num_train_epochs
->>> optimizer, lr_schedule = create_optimizer(
-... init_lr=2e-5,
-... num_train_steps=num_train_steps,
-... weight_decay_rate=0.01,
-... num_warmup_steps=0,
-... )
-```
-
-Carregue o DistilBERT com o [`TFAutoModelForTokenClassification`] junto com o nĂșmero de rĂłtulos esperados:
-
-```py
->>> from transformers import TFAutoModelForTokenClassification
-
->>> model = TFAutoModelForTokenClassification.from_pretrained("distilbert-base-uncased", num_labels=2)
-```
-
-Configure o modelo para treinamento com o método [`compile`](https://keras.io/api/models/model_training_apis/#compile-method):
-
-```py
->>> import tensorflow as tf
-
->>> model.compile(optimizer=optimizer)
-```
-
-Chame o método [`fit`](https://keras.io/api/models/model_training_apis/#fit-method) para executar o fine-tuning do modelo:
-
-```py
->>> model.fit(x=tf_train_set, validation_data=tf_validation_set, epochs=3)
-```
-
-
-
-
-
-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).
-
-
\ No newline at end of file
diff --git a/docs/source/pt/training.md b/docs/source/pt/training.md
new file mode 100644
index 000000000000..aa529ac948b8
--- /dev/null
+++ b/docs/source/pt/training.md
@@ -0,0 +1,416 @@
+
+
+# Fine-tuning de um modelo pré-treinado
+
+[[open-in-colab]]
+
+O uso de um modelo pré-treinado tem importantes vantagens. Redução do custo computacional, a pegada de carbono, e te
+permite utilizar modelos de Ășltima geração sem ter que treinar um novo desde o inĂcio.
+O đ€ Transformers proporciona acesso a milhares de modelos prĂ©-treinados numa ampla gama de tarefas.
+Quando utilizar um modelo prĂ©-treinado, treine-o com um dataset especĂfico para a sua tarefa.
+Isto é chamado de fine-tuning, uma técnica de treinamento incrivelmente poderosa. Neste tutorial faremos o fine-tuning
+de um modelo pré-treinado com um framework de Deep Learning da sua escolha:
+
+* Fine-tuning de um modelo prĂ©-treinado com o đ€ Transformers [`Trainer`].
+* Fine-tuning de um modelo pré-treinado no TensorFlow com o Keras.
+* Fine-tuning de um modelo pré-treinado em PyTorch nativo.
+
+
+
+## Preparando um dataset
+
+
+
+Antes de aplicar o fine-tuning a um modelo pré-treinado, baixe um dataset e prepare-o para o treinamento.
+O tutorial anterior ensinarĂĄ a processar os dados para o treinamento, e entĂŁo poderĂĄ ter a oportunidade de testar
+esse novo conhecimento em algo prĂĄtico.
+
+Comece carregando o dataset [Yelp Reviews](https://huggingface.co/datasets/yelp_review_full):
+
+```py
+>>> from datasets import load_dataset
+
+>>> dataset = load_dataset("yelp_review_full")
+>>> dataset[100]
+{'label': 0,
+ '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!'}
+```
+
+Como jå sabe, é necessårio ter um tokenizador para processar o texto e incluir uma estratégia de padding e truncamento,
+para manejar qualquer tamanho varĂavel de sequĂȘncia. Para processar o seu dataset em apenas um passo, utilize o mĂ©todo de
+đ€ Datasets [`map`](https://huggingface.co/docs/datasets/process.html#map) para aplicar uma função de preprocessamento sobre
+todo o dataset.
+
+```py
+>>> from transformers import AutoTokenizer
+
+>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
+
+
+>>> def tokenize_function(examples):
+... return tokenizer(examples["text"], padding="max_length", truncation=True)
+
+
+>>> tokenized_datasets = dataset.map(tokenize_function, batched=True)
+```
+
+Se desejar, Ă© possĂvel criar um subconjunto menor do dataset completo para aplicar o fine-tuning e assim reduzir o tempo necessĂĄrio.
+
+```py
+>>> small_train_dataset = tokenized_datasets["train"].shuffle(seed=42).select(range(1000))
+>>> small_eval_dataset = tokenized_datasets["test"].shuffle(seed=42).select(range(1000))
+```
+
+
+
+## Fine-tuning com o `Trainer`
+
+
+
+O đ€ Transformers proporciona uma classe [`Trainer`] otimizada para o treinamento de modelos de đ€ Transformers,
+facilitando os primeiros passos do treinamento sem a necessidade de escrever manualmente o seu prĂłprio ciclo.
+A API do [`Trainer`] suporta um grande conjunto de opçÔes de treinamento e funcionalidades, como o logging,
+o gradient accumulation e o mixed precision.
+
+Comece carregando seu modelo e especifique o nĂșmero de labels de previsĂŁo.
+A partir do [Card Dataset](https://huggingface.co/datasets/yelp_review_full#data-fields) do Yelp Reveiw, que ja
+sabemos ter 5 labels usamos o seguinte cĂłdigo:
+
+```py
+>>> from transformers import AutoModelForSequenceClassification
+
+>>> model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=5)
+```
+
+
+
+ VocĂȘ verĂĄ um alerta sobre alguns pesos prĂ©-treinados que nĂŁo estĂŁo sendo utilizados e que alguns pesos estĂŁo
+ sendo inicializados aleatoriamente. NĂŁo se preocupe, essa mensagem Ă© completamente normal.
+ O header/cabeçårio pré-treinado do modelo BERT é descartado e substitui-se por um header de classificação
+ inicializado aleatoriamente. Assim, pode aplicar o fine-tuning a este novo header do modelo em sua tarefa
+ de classificação de sequĂȘncias fazendo um transfer learning do modelo prĂ©-treinado.
+
+
+
+### HiperparĂąmetros de treinamento
+
+Em seguida, crie uma classe [`TrainingArguments`] que contenha todos os hiperparĂąmetros que possam ser ajustados, assim
+como os indicadores para ativar as diferentes opçÔes de treinamento. Para este tutorial, vocĂȘ pode começar o treinamento
+usando os [hiperparĂĄmetros](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments) padrĂŁo,
+porém, sinta-se livre para experimentar com eles e encontrar uma configuração ótima.
+
+Especifique onde salvar os checkpoints do treinamento:
+
+```py
+>>> from transformers import TrainingArguments
+
+>>> training_args = TrainingArguments(output_dir="test_trainer")
+```
+
+### Métricas
+
+O [`Trainer`] nĂŁo avalia automaticamente o rendimento do modelo durante o treinamento. SerĂĄ necessĂĄrio passar ao
+[`Trainer`] uma função para calcular e fazer um diagnĂłstico sobre as mĂ©tricas. A biblioteca đ€ Datasets proporciona
+uma função de [`accuracy`](https://huggingface.co/metrics/accuracy) simples que pode ser carregada com a função
+`load_metric` (ver este [tutorial](https://huggingface.co/docs/datasets/metrics.html) para mais informaçÔes):
+
+```py
+>>> import numpy as np
+>>> from datasets import load_metric
+
+>>> metric = load_metric("accuracy")
+```
+
+Defina a função `compute` dentro de `metric` para calcular a precisão das suas prediçÔes.
+Antes de passar as suas prediçÔes ao `compute`, é necessårio converter as prediçÔes à logits (lembre-se que
+todos os modelos de đ€ Transformers retornam logits).
+
+```py
+>>> def compute_metrics(eval_pred):
+... logits, labels = eval_pred
+... predictions = np.argmax(logits, axis=-1)
+... return metric.compute(predictions=predictions, references=labels)
+```
+
+Se quiser controlar as suas métricas de avaliação durante o fine-tuning, especifique o parùmetro `evaluation_strategy`
+nos seus argumentos de treinamento para que o modelo considere a métrica de avaliação ao final de cada época:
+
+```py
+>>> from transformers import TrainingArguments
+
+>>> training_args = TrainingArguments(output_dir="test_trainer", evaluation_strategy="epoch")
+```
+
+### Trainer
+
+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:
+
+```py
+>>> trainer = Trainer(
+... model=model,
+... args=training_args,
+... train_dataset=small_train_dataset,
+... eval_dataset=small_eval_dataset,
+... compute_metrics=compute_metrics,
+... )
+```
+
+Em seguida, aplique o fine-tuning a seu modelo chamado [`~transformers.Trainer.train`]:
+
+```py
+>>> trainer.train()
+```
+
+
+
+## Fine-tuning com Keras
+
+
+
+Os modelos de đ€ Transformers tambĂ©m permitem realizar o treinamento com o TensorFlow com a API do Keras.
+Contudo, serå necessårio fazer algumas mudanças antes de realizar o fine-tuning.
+
+### ConversĂŁo do dataset ao formato do TensorFlow
+
+O [`DefaultDataCollator`] junta os tensores em um batch para que o modelo possa ser treinado em cima deles.
+Assegure-se de especificar os `return_tensors` para retornar os tensores do TensorFlow:
+
+```py
+>>> from transformers import DefaultDataCollator
+
+>>> data_collator = DefaultDataCollator(return_tensors="tf")
+```
+
+
+
+ O [`Trainer`] utiliza [`DataCollatorWithPadding`] por padrĂŁo, entĂŁo vocĂȘ nĂŁo precisa especificar explicitamente um
+ colador de dados (data collator).
+
+
+
+Em seguida, converta os datasets tokenizados em datasets do TensorFlow com o método
+[`to_tf_dataset`](https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.to_tf_dataset).
+Especifique suas entradas em `columns` e seu rĂłtulo em `label_cols`:
+
+```py
+>>> tf_train_dataset = small_train_dataset.to_tf_dataset(
+... columns=["attention_mask", "input_ids", "token_type_ids"],
+... label_cols="labels",
+... shuffle=True,
+... collate_fn=data_collator,
+... batch_size=8,
+... )
+
+>>> tf_validation_dataset = small_eval_dataset.to_tf_dataset(
+... columns=["attention_mask", "input_ids", "token_type_ids"],
+... label_cols="labels",
+... shuffle=False,
+... collate_fn=data_collator,
+... batch_size=8,
+... )
+```
+
+### Compilação e ajustes
+
+Carregue um modelo do TensorFlow com o nĂșmero esperado de rĂłtulos:
+
+```py
+>>> import tensorflow as tf
+>>> from transformers import TFAutoModelForSequenceClassification
+
+>>> model = TFAutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=5)
+```
+
+A seguir, compile e ajuste o fine-tuning a seu modelo com [`fit`](https://keras.io/api/models/model_training_apis/) como
+faria com qualquer outro modelo do Keras:
+
+```py
+>>> model.compile(
+... optimizer=tf.keras.optimizers.Adam(learning_rate=5e-5),
+... loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
+... metrics=tf.metrics.SparseCategoricalAccuracy(),
+... )
+
+>>> model.fit(tf_train_dataset, validation_data=tf_validation_dataset, epochs=3)
+```
+
+
+
+## Fine-tune em PyTorch nativo
+
+
+
+O [`Trainer`] se encarrega do ciclo de treinamento e permite aplicar o fine-tuning a um modelo em uma linha de cĂłdigo apenas.
+Para os usuĂĄrios que preferirem escrever o seu prĂłprio ciclo de treinamento, tambĂ©m Ă© possĂvel aplicar o fine-tuning a um
+modelo de đ€ Transformers em PyTorch nativo.
+
+Neste momento, talvez ocorra a necessidade de reinicar seu notebook ou executar a seguinte linha de cĂłdigo para liberar
+memĂłria:
+
+```py
+del model
+del pytorch_model
+del trainer
+torch.cuda.empty_cache()
+```
+
+Em sequĂȘncia, faremos um post-processing manual do `tokenized_dataset` e assim preparĂĄ-lo para o treinamento.
+
+1. Apague a coluna de `text` porque o modelo nĂŁo aceita texto cru como entrada:
+
+ ```py
+ >>> tokenized_datasets = tokenized_datasets.remove_columns(["text"])
+ ```
+
+2. Troque o nome da coluna `label` para `labels`, pois o modelo espera um argumento de mesmo nome:
+
+ ```py
+ >>> tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
+ ```
+
+3. Defina o formato do dataset para retornar tensores do PyTorch no lugar de listas:
+
+ ```py
+ >>> tokenized_datasets.set_format("torch")
+ ```
+
+Em sequĂȘncia, crie um subconjunto menor do dataset, como foi mostrado anteriormente, para acelerĂĄ-lo o fine-tuning.
+
+```py
+>>> small_train_dataset = tokenized_datasets["train"].shuffle(seed=42).select(range(1000))
+>>> small_eval_dataset = tokenized_datasets["test"].shuffle(seed=42).select(range(1000))
+```
+
+### DataLoader
+
+Crie um `DataLoader` para os seus datasets de treinamento e de teste para poder iterar sobre batches de dados:
+
+```py
+>>> from torch.utils.data import DataLoader
+
+>>> train_dataloader = DataLoader(small_train_dataset, shuffle=True, batch_size=8)
+>>> eval_dataloader = DataLoader(small_eval_dataset, batch_size=8)
+```
+
+Carregue seu modelo com o nĂșmero de labels esperados:
+
+```py
+>>> from transformers import AutoModelForSequenceClassification
+
+>>> model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=5)
+```
+
+### Otimização e configuração do Learning Rate
+
+Crie um otimizador e um learning rate para aplicar o fine-tuning ao modelo.
+Iremos utilizar o otimizador [`AdamW`](https://pytorch.org/docs/stable/generated/torch.optim.AdamW.html) do PyTorch:
+
+```py
+>>> from torch.optim import AdamW
+
+>>> optimizer = AdamW(model.parameters(), lr=5e-5)
+```
+
+Defina o learning rate do [`Trainer`]:
+
+```py
+>>> from transformers import get_scheduler
+
+>>> num_epochs = 3
+>>> num_training_steps = num_epochs * len(train_dataloader)
+>>> lr_scheduler = get_scheduler(
+... name="linear", optimizer=optimizer, num_warmup_steps=0, num_training_steps=num_training_steps
+... )
+```
+
+Por Ășltimo, especifique o `device` do ambiente para utilizar uma GPU se tiver acesso Ă alguma. Caso contrĂĄrio, o treinamento
+em uma CPU pode acabar levando vĂĄrias horas em vez de minutos.
+
+```py
+>>> import torch
+
+>>> device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
+>>> model.to(device)
+```
+
+
+
+ Se necessĂĄrio, vocĂȘ pode obter o acesso gratuito a uma GPU na nĂșvem por meio de um notebook no
+ [Colaboratory](https://colab.research.google.com/) ou [SageMaker StudioLab](https://studiolab.sagemaker.aws/)
+ se nĂŁo tiver esse recurso de forma local.
+
+
+
+Perfeito, agora estamos prontos para começar o treinamento! đ„ł
+
+### Ciclo de treinamento
+
+Para visualizar melhor o processo de treinamento, utilize a biblioteca [tqdm](https://tqdm.github.io/) para adicionar
+uma barra de progresso sobre o nĂșmero de passos percorridos no treinamento atual:
+
+```py
+>>> from tqdm.auto import tqdm
+
+>>> progress_bar = tqdm(range(num_training_steps))
+
+>>> model.train()
+>>> for epoch in range(num_epochs):
+... for batch in train_dataloader:
+... batch = {k: v.to(device) for k, v in batch.items()}
+... outputs = model(**batch)
+... loss = outputs.loss
+... loss.backward()
+
+... optimizer.step()
+... lr_scheduler.step()
+... optimizer.zero_grad()
+... progress_bar.update(1)
+```
+
+### Métricas
+
+Da mesma forma que é necessårio adicionar uma função de avaliação ao [`Trainer`], é necessårio fazer o mesmo quando
+escrevendo o próprio ciclo de treinamento. Contudo, em vez de calcular e retornar a métrica final de cada época,
+vocĂȘ deverĂĄ adicionar todos os batches com [`add_batch`](https://huggingface.co/docs/datasets/package_reference/main_classes.html?highlight=add_batch#datasets.Metric.add_batch)
+e calcular a métrica apenas no final.
+
+```py
+>>> metric = load_metric("accuracy")
+>>> model.eval()
+>>> for batch in eval_dataloader:
+... batch = {k: v.to(device) for k, v in batch.items()}
+... with torch.no_grad():
+... outputs = model(**batch)
+
+... logits = outputs.logits
+... predictions = torch.argmax(logits, dim=-1)
+... metric.add_batch(predictions=predictions, references=batch["labels"])
+
+>>> metric.compute()
+```
+
+
+
+## Recursos adicionais
+
+Para mais exemplos de fine-tuning acesse:
+
+- [đ€ Transformers Examples](https://github.com/huggingface/transformers/tree/main/examples) inclui scripts
+para treinas tarefas comuns de NLP em PyTorch e TensorFlow.
+
+- [đ€ Transformers Notebooks](notebooks) contĂ©m vĂĄrios notebooks sobre como aplicar o fine-tuning a um modelo
+para tarefas especĂficas no PyTorch e TensorFlow.
diff --git a/docs/source/pt/training.mdx b/docs/source/pt/training.mdx
deleted file mode 100644
index d84f227aec28..000000000000
--- a/docs/source/pt/training.mdx
+++ /dev/null
@@ -1,412 +0,0 @@
-
-
-# Fine-tuning de um modelo pré-treinado
-
-[[open-in-colab]]
-
-O uso de um modelo pré-treinado tem importantes vantagens. Redução do custo computacional, a pegada de carbono, e te
-permite utilizar modelos de Ășltima geração sem ter que treinar um novo desde o inĂcio.
-O đ€ Transformers proporciona acesso a milhares de modelos prĂ©-treinados numa ampla gama de tarefas.
-Quando utilizar um modelo prĂ©-treinado, treine-o com um dataset especĂfico para a sua tarefa.
-Isto é chamado de fine-tuning, uma técnica de treinamento incrivelmente poderosa. Neste tutorial faremos o fine-tuning
-de um modelo pré-treinado com um framework de Deep Learning da sua escolha:
-
-* Fine-tuning de um modelo prĂ©-treinado com o đ€ Transformers [`Trainer`].
-* Fine-tuning de um modelo pré-treinado no TensorFlow com o Keras.
-* Fine-tuning de um modelo pré-treinado em PyTorch nativo.
-
-
-
-## Preparando um dataset
-
-
-
-Antes de aplicar o fine-tuning a um modelo pré-treinado, baixe um dataset e prepare-o para o treinamento.
-O tutorial anterior ensinarĂĄ a processar os dados para o treinamento, e entĂŁo poderĂĄ ter a oportunidade de testar
-esse novo conhecimento em algo prĂĄtico.
-
-Comece carregando o dataset [Yelp Reviews](https://huggingface.co/datasets/yelp_review_full):
-
-```py
->>> from datasets import load_dataset
-
->>> dataset = load_dataset("yelp_review_full")
->>> dataset[100]
-{'label': 0,
- '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!'}
-```
-
-Como jå sabe, é necessårio ter um tokenizador para processar o texto e incluir uma estratégia de padding e truncamento,
-para manejar qualquer tamanho varĂavel de sequĂȘncia. Para processar o seu dataset em apenas um passo, utilize o mĂ©todo de
-đ€ Datasets [`map`](https://huggingface.co/docs/datasets/process.html#map) para aplicar uma função de preprocessamento sobre
-todo o dataset.
-
-```py
->>> from transformers import AutoTokenizer
-
->>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
-
-
->>> def tokenize_function(examples):
-... return tokenizer(examples["text"], padding="max_length", truncation=True)
-
-
->>> tokenized_datasets = dataset.map(tokenize_function, batched=True)
-```
-
-Se desejar, Ă© possĂvel criar um subconjunto menor do dataset completo para aplicar o fine-tuning e assim reduzir o tempo necessĂĄrio.
-
-```py
->>> small_train_dataset = tokenized_datasets["train"].shuffle(seed=42).select(range(1000))
->>> small_eval_dataset = tokenized_datasets["test"].shuffle(seed=42).select(range(1000))
-```
-
-
-
-## Fine-tuning com o `Trainer`
-
-
-
-O đ€ Transformers proporciona uma classe [`Trainer`] otimizada para o treinamento de modelos de đ€ Transformers,
-facilitando os primeiros passos do treinamento sem a necessidade de escrever manualmente o seu prĂłprio ciclo.
-A API do [`Trainer`] suporta um grande conjunto de opçÔes de treinamento e funcionalidades, como o logging,
-o gradient accumulation e o mixed precision.
-
-Comece carregando seu modelo e especifique o nĂșmero de labels de previsĂŁo.
-A partir do [Card Dataset](https://huggingface.co/datasets/yelp_review_full#data-fields) do Yelp Reveiw, que ja
-sabemos ter 5 labels usamos o seguinte cĂłdigo:
-
-```py
->>> from transformers import AutoModelForSequenceClassification
-
->>> model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=5)
-```
-
-
-
- VocĂȘ verĂĄ um alerta sobre alguns pesos prĂ©-treinados que nĂŁo estĂŁo sendo utilizados e que alguns pesos estĂŁo
- sendo inicializados aleatoriamente. NĂŁo se preocupe, essa mensagem Ă© completamente normal.
- O header/cabeçårio pré-treinado do modelo BERT é descartado e substitui-se por um header de classificação
- inicializado aleatoriamente. Assim, pode aplicar o fine-tuning a este novo header do modelo em sua tarefa
- de classificação de sequĂȘncias fazendo um transfer learning do modelo prĂ©-treinado.
-
-
-
-### HiperparĂąmetros de treinamento
-
-Em seguida, crie uma classe [`TrainingArguments`] que contenha todos os hiperparĂąmetros que possam ser ajustados, assim
-como os indicadores para ativar as diferentes opçÔes de treinamento. Para este tutorial, vocĂȘ pode começar o treinamento
-usando os [hiperparĂĄmetros](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments) padrĂŁo,
-porém, sinta-se livre para experimentar com eles e encontrar uma configuração ótima.
-
-Especifique onde salvar os checkpoints do treinamento:
-
-```py
->>> from transformers import TrainingArguments
-
->>> training_args = TrainingArguments(output_dir="test_trainer")
-```
-
-### Métricas
-
-O [`Trainer`] nĂŁo avalia automaticamente o rendimento do modelo durante o treinamento. SerĂĄ necessĂĄrio passar ao
-[`Trainer`] uma função para calcular e fazer um diagnĂłstico sobre as mĂ©tricas. A biblioteca đ€ Datasets proporciona
-uma função de [`accuracy`](https://huggingface.co/metrics/accuracy) simples que pode ser carregada com a função
-`load_metric` (ver este [tutorial](https://huggingface.co/docs/datasets/metrics.html) para mais informaçÔes):
-
-```py
->>> import numpy as np
->>> from datasets import load_metric
-
->>> metric = load_metric("accuracy")
-```
-
-Defina a função `compute` dentro de `metric` para calcular a precisão das suas prediçÔes.
-Antes de passar as suas prediçÔes ao `compute`, é necessårio converter as prediçÔes à logits (lembre-se que
-todos os modelos de đ€ Transformers retornam logits).
-
-```py
->>> def compute_metrics(eval_pred):
-... logits, labels = eval_pred
-... predictions = np.argmax(logits, axis=-1)
-... return metric.compute(predictions=predictions, references=labels)
-```
-
-Se quiser controlar as suas métricas de avaliação durante o fine-tuning, especifique o parùmetro `evaluation_strategy`
-nos seus argumentos de treinamento para que o modelo considere a métrica de avaliação ao final de cada época:
-
-```py
->>> from transformers import TrainingArguments
-
->>> training_args = TrainingArguments(output_dir="test_trainer", evaluation_strategy="epoch")
-```
-
-### Trainer
-
-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:
-
-```py
->>> trainer = Trainer(
-... model=model,
-... args=training_args,
-... train_dataset=small_train_dataset,
-... eval_dataset=small_eval_dataset,
-... compute_metrics=compute_metrics,
-... )
-```
-
-Em seguida, aplique o fine-tuning a seu modelo chamado [`~transformers.Trainer.train`]:
-
-```py
->>> trainer.train()
-```
-
-
-
-## Fine-tuning com Keras
-
-
-
-Os modelos de đ€ Transformers tambĂ©m permitem realizar o treinamento com o TensorFlow com a API do Keras.
-Contudo, serå necessårio fazer algumas mudanças antes de realizar o fine-tuning.
-
-### ConversĂŁo do dataset ao formato do TensorFlow
-
-O [`DefaultDataCollator`] junta os tensores em um batch para que o modelo possa ser treinado em cima deles.
-Assegure-se de especificar os `return_tensors` para retornar os tensores do TensorFlow:
-
-```py
->>> from transformers import DefaultDataCollator
-
->>> data_collator = DefaultDataCollator(return_tensors="tf")
-```
-
-
-
- O [`Trainer`] utiliza [`DataCollatorWithPadding`] por padrĂŁo, entĂŁo vocĂȘ nĂŁo precisa especificar explicitamente um
- colador de dados (data collator).
-
-
-
-Em seguida, converta os datasets tokenizados em datasets do TensorFlow com o método
-[`to_tf_dataset`](https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.to_tf_dataset).
-Especifique suas entradas em `columns` e seu rĂłtulo em `label_cols`:
-
-```py
->>> tf_train_dataset = small_train_dataset.to_tf_dataset(
-... columns=["attention_mask", "input_ids", "token_type_ids"],
-... label_cols="labels",
-... shuffle=True,
-... collate_fn=data_collator,
-... batch_size=8,
-... )
-
->>> tf_validation_dataset = small_eval_dataset.to_tf_dataset(
-... columns=["attention_mask", "input_ids", "token_type_ids"],
-... label_cols="labels",
-... shuffle=False,
-... collate_fn=data_collator,
-... batch_size=8,
-... )
-```
-
-### Compilação e ajustes
-
-Carregue um modelo do TensorFlow com o nĂșmero esperado de rĂłtulos:
-
-```py
->>> import tensorflow as tf
->>> from transformers import TFAutoModelForSequenceClassification
-
->>> model = TFAutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=5)
-```
-
-A seguir, compile e ajuste o fine-tuning a seu modelo com [`fit`](https://keras.io/api/models/model_training_apis/) como
-faria com qualquer outro modelo do Keras:
-
-```py
->>> model.compile(
-... optimizer=tf.keras.optimizers.Adam(learning_rate=5e-5),
-... loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
-... metrics=tf.metrics.SparseCategoricalAccuracy(),
-... )
-
->>> model.fit(tf_train_dataset, validation_data=tf_validation_dataset, epochs=3)
-```
-
-
-
-## Fine-tune em PyTorch nativo
-
-
-
-O [`Trainer`] se encarrega do ciclo de treinamento e permite aplicar o fine-tuning a um modelo em uma linha de cĂłdigo apenas.
-Para os usuĂĄrios que preferirem escrever o seu prĂłprio ciclo de treinamento, tambĂ©m Ă© possĂvel aplicar o fine-tuning a um
-modelo de đ€ Transformers em PyTorch nativo.
-
-Neste momento, talvez ocorra a necessidade de reinicar seu notebook ou executar a seguinte linha de cĂłdigo para liberar
-memĂłria:
-
-```py
-del model
-del pytorch_model
-del trainer
-torch.cuda.empty_cache()
-```
-
-Em sequĂȘncia, faremos um post-processing manual do `tokenized_dataset` e assim preparĂĄ-lo para o treinamento.
-
-1. Apague a coluna de `text` porque o modelo nĂŁo aceita texto cru como entrada:
-
- ```py
- >>> tokenized_datasets = tokenized_datasets.remove_columns(["text"])
- ```
-
-2. Troque o nome da coluna `label` para `labels`, pois o modelo espera um argumento de mesmo nome:
-
- ```py
- >>> tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
- ```
-
-3. Defina o formato do dataset para retornar tensores do PyTorch no lugar de listas:
-
- ```py
- >>> tokenized_datasets.set_format("torch")
- ```
-
-Em sequĂȘncia, crie um subconjunto menor do dataset, como foi mostrado anteriormente, para acelerĂĄ-lo o fine-tuning.
-
-```py
->>> small_train_dataset = tokenized_datasets["train"].shuffle(seed=42).select(range(1000))
->>> small_eval_dataset = tokenized_datasets["test"].shuffle(seed=42).select(range(1000))
-```
-
-### DataLoader
-
-Crie um `DataLoader` para os seus datasets de treinamento e de teste para poder iterar sobre batches de dados:
-
-```py
->>> from torch.utils.data import DataLoader
-
->>> train_dataloader = DataLoader(small_train_dataset, shuffle=True, batch_size=8)
->>> eval_dataloader = DataLoader(small_eval_dataset, batch_size=8)
-```
-
-Carregue seu modelo com o nĂșmero de labels esperados:
-
-```py
->>> from transformers import AutoModelForSequenceClassification
-
->>> model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=5)
-```
-
-### Otimização e configuração do Learning Rate
-
-Crie um otimizador e um learning rate para aplicar o fine-tuning ao modelo.
-Iremos utilizar o otimizador [`AdamW`](https://pytorch.org/docs/stable/generated/torch.optim.AdamW.html) do PyTorch:
-
-```py
->>> from torch.optim import AdamW
-
->>> optimizer = AdamW(model.parameters(), lr=5e-5)
-```
-
-Defina o learning rate do [`Trainer`]:
-
-```py
->>> from transformers import get_scheduler
-
->>> num_epochs = 3
->>> num_training_steps = num_epochs * len(train_dataloader)
->>> lr_scheduler = get_scheduler(
-... name="linear", optimizer=optimizer, num_warmup_steps=0, num_training_steps=num_training_steps
-... )
-```
-
-Por Ășltimo, especifique o `device` do ambiente para utilizar uma GPU se tiver acesso Ă alguma. Caso contrĂĄrio, o treinamento
-em uma CPU pode acabar levando vĂĄrias horas em vez de minutos.
-
-```py
->>> import torch
-
->>> device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
->>> model.to(device)
-```
-
-
-
- Se necessĂĄrio, vocĂȘ pode obter o acesso gratuito a uma GPU na nĂșvem por meio de um notebook no
- [Colaboratory](https://colab.research.google.com/) ou [SageMaker StudioLab](https://studiolab.sagemaker.aws/)
- se nĂŁo tiver esse recurso de forma local.
-
-
-
-Perfeito, agora estamos prontos para começar o treinamento! đ„ł
-
-### Ciclo de treinamento
-
-Para visualizar melhor o processo de treinamento, utilize a biblioteca [tqdm](https://tqdm.github.io/) para adicionar
-uma barra de progresso sobre o nĂșmero de passos percorridos no treinamento atual:
-
-```py
->>> from tqdm.auto import tqdm
-
->>> progress_bar = tqdm(range(num_training_steps))
-
->>> model.train()
->>> for epoch in range(num_epochs):
-... for batch in train_dataloader:
-... batch = {k: v.to(device) for k, v in batch.items()}
-... outputs = model(**batch)
-... loss = outputs.loss
-... loss.backward()
-
-... optimizer.step()
-... lr_scheduler.step()
-... optimizer.zero_grad()
-... progress_bar.update(1)
-```
-
-### Métricas
-
-Da mesma forma que é necessårio adicionar uma função de avaliação ao [`Trainer`], é necessårio fazer o mesmo quando
-escrevendo o próprio ciclo de treinamento. Contudo, em vez de calcular e retornar a métrica final de cada época,
-vocĂȘ deverĂĄ adicionar todos os batches com [`add_batch`](https://huggingface.co/docs/datasets/package_reference/main_classes.html?highlight=add_batch#datasets.Metric.add_batch)
-e calcular a métrica apenas no final.
-
-```py
->>> metric = load_metric("accuracy")
->>> model.eval()
->>> for batch in eval_dataloader:
-... batch = {k: v.to(device) for k, v in batch.items()}
-... with torch.no_grad():
-... outputs = model(**batch)
-
-... logits = outputs.logits
-... predictions = torch.argmax(logits, dim=-1)
-... metric.add_batch(predictions=predictions, references=batch["labels"])
-
->>> metric.compute()
-```
-
-
-
-## Recursos adicionais
-
-Para mais exemplos de fine-tuning acesse:
-
-- [đ€ Transformers Examples](https://github.com/huggingface/transformers/tree/main/examples) inclui scripts
-para treinas tarefas comuns de NLP em PyTorch e TensorFlow.
-
-- [đ€ Transformers Notebooks](notebooks) contĂ©m vĂĄrios notebooks sobre como aplicar o fine-tuning a um modelo
-para tarefas especĂficas no PyTorch e TensorFlow.
diff --git a/docs/source/zh/index.md b/docs/source/zh/index.md
new file mode 100644
index 000000000000..38e758caf73c
--- /dev/null
+++ b/docs/source/zh/index.md
@@ -0,0 +1,398 @@
+
+
+# đ€ Transformersçźä»
+
+äžș[PyTorch](https://pytorch.org/), [TensorFlow](https://www.tensorflow.org/)ć[JAX](https://jax.readthedocs.io/en/latest/)æé çć
èżçæșćšćŠäč ć·„ć
·.
+
+đ€ Transformers æäŸäșćŻä»„蜻æŸć°äžèœœćč¶äžèźç»ć
èżçéąèźç»æšĄćçAPIćć·„ć
·. äœżçšéąèźç»æšĄććŻä»„ćć°èźĄçźæ¶èćçąłææŸ, ćč¶äžèçä»ć€Žèźç»æéèŠçæ¶éŽćè”æș. èżäșæšĄćæŻæäžćæšĄæäžçćžžè§ä»»ćĄïŒæŻćŠ:
+
+đ **èȘç¶èŻèšć€ç**: ææŹćç±», ćœććźäœèŻć«, éźç, èŻèšć»șæšĄ, æèŠ, çż»èŻ, ć€éĄč鿩㿿Źçæ.
+đŒïž **æșćšè§è§**: ćŸććç±», çźæ æŁæ”ćèŻäčććČ.
+đŁïž **éłéą**: èȘćšèŻéłèŻć«ćéłéąćç±».
+đ **〿šĄæ**: èĄšæ Œéźç, ć
ćŠć珊èŻć«, 仿«æææĄŁæć俥æŻ, è§éąćç±»ćè§è§éźç.
+
+đ€ TransformersæŻæćšPyTorch, TensorFlowćJAXäžçäșæäœæ§. èżç»ćšæšĄćçæŻäžȘé¶æź”äœżçšäžćçæĄæ¶ćžŠæ„äșç”æŽ»æ§; ćšäžäžȘæĄæ¶äžäœżçšć èĄä»Łç èźç»äžäžȘæšĄć, ç¶ććšćŠäžäžȘæĄæ¶äžć 蜜ćźćč¶èżèĄæšç. æšĄćäčćŻä»„èą«ćŻŒćșäžșONNXćTorchScriptæ ŒćŒ, çšäșćšçäș§çŻćąäžéšçœČ.
+
+驏äžć ć
„ćš[Hub](https://huggingface.co/models), [forum](https://discuss.huggingface.co/), æè
[Discord](https://discord.com/invite/JfAtkvEtRb)äžæŁćšćż«éćć±ç瀟ćșć§!
+
+## ćŠæäœ éèŠæ„èȘHugging FacećąéçäžȘæ§ćæŻæ
+
+
+
+
+
+## çźćœ
+
+èżçŻææĄŁèą«ç»ç»äžș仄äž5äžȘç« è:
+
+- **ćŒć§äœżçš** ć
ć«äșćșçćż«éäžæććźèŁ
èŻŽæ, äŸżäșé
çœźćèżèĄ.
+- **æçš** æŻäžäžȘććŠè
ćŒć§çć„œć°æč. æŹç« èć°ćžźć©äœ è·ćŸäœ äŒçšć°çäœżçšèżäžȘćșçćșæŹæèœ.
+- **æäœæć** ćäœ ć±ç€șćŠäœćźç°äžäžȘçčćźçźæ , æŻćŠäžșèŻèšć»șæšĄćŸźè°äžäžȘéąèźç»æšĄćæè
ćŠäœćé ćč¶ćäș«äžȘæ§ćæšĄć.
+- **æŠćż”æć** ćŻčđ€ TransformersçæšĄć, ä»»ćĄćèźŸèźĄçćż”èćçćșæŹæŠćż”ćææłćäșæŽć€çèźšèźșćè§Łé.
+- **APIä»ç»** æèż°äșææçç±»ććœæ°:
+
+ - **MAIN CLASSES** èŻŠèż°äșé
çœź(configuration)ăæšĄć(model)ăćèŻćš(tokenizer)ćæ”æ°Žçșż(pipeline)èżć äžȘæéèŠçç±».
+ - **MODELS** èŻŠèż°äșćšèżäžȘćșäžćæŻäžȘæšĄććźç°æć
łçç±»ććœæ°.
+ - **INTERNAL HELPERS** èŻŠèż°äșć
éšäœżçšçć·„ć
·ç±»ććœæ°.
+
+### æŻæçæšĄć
+
+
+
+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://arxiv.org/abs/1909.11942), by Zhenzhong Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.
+1. **[AltCLIP](model_doc/altclip)** (from BAAI) released with the paper [AltCLIP: Altering the Language Encoder in CLIP for Extended Language Capabilities](https://arxiv.org/abs/2211.06679) by Chen, Zhongzhi and Liu, Guang and Zhang, Bo-Wen and Ye, Fulong and Yang, Qinghong and Wu, Ledell.
+1. **[Audio Spectrogram Transformer](model_doc/audio-spectrogram-transformer)** (from MIT) released with the paper [AST: Audio Spectrogram Transformer](https://arxiv.org/abs/2104.01778) by Yuan Gong, Yu-An Chung, James Glass.
+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://arxiv.org/abs/1910.13461) by Mike Lewis, Yinhan Liu, Naman Goyal, Marjan Ghazvininejad, Abdelrahman Mohamed, Omer Levy, Ves Stoyanov and Luke Zettlemoyer.
+1. **[BARThez](model_doc/barthez)** (from Ăcole polytechnique) released with the paper [BARThez: a Skilled Pretrained French Sequence-to-Sequence Model](https://arxiv.org/abs/2010.12321) by Moussa Kamal Eddine, Antoine J.-P. Tixier, Michalis Vazirgiannis.
+1. **[BARTpho](model_doc/bartpho)** (from VinAI Research) released with the paper [BARTpho: Pre-trained Sequence-to-Sequence Models for Vietnamese](https://arxiv.org/abs/2109.09701) by Nguyen Luong Tran, Duong Minh Le and Dat Quoc Nguyen.
+1. **[BEiT](model_doc/beit)** (from Microsoft) released with the paper [BEiT: BERT Pre-Training of Image Transformers](https://arxiv.org/abs/2106.08254) by Hangbo Bao, Li Dong, Furu Wei.
+1. **[BERT](model_doc/bert)** (from Google) released with the paper [BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding](https://arxiv.org/abs/1810.04805) by Jacob Devlin, Ming-Wei Chang, Kenton Lee and Kristina Toutanova.
+1. **[BERT For Sequence Generation](model_doc/bert-generation)** (from Google) released with the paper [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://arxiv.org/abs/1907.12461) by Sascha Rothe, Shashi Narayan, Aliaksei Severyn.
+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.
+1. **[BigBird-Pegasus](model_doc/bigbird_pegasus)** (from Google Research) released with the paper [Big Bird: Transformers for Longer Sequences](https://arxiv.org/abs/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.
+1. **[BigBird-RoBERTa](model_doc/big_bird)** (from Google Research) released with the paper [Big Bird: Transformers for Longer Sequences](https://arxiv.org/abs/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.
+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.
+1. **[BiT](model_doc/bit)** (from Google AI) released with the paper [Big Transfer (BiT): General Visual Representation Learning](https://arxiv.org/abs/1912.11370) by Alexander Kolesnikov, Lucas Beyer, Xiaohua Zhai, Joan Puigcerver, Jessica Yung, Sylvain Gelly, Neil Houlsby.
+1. **[Blenderbot](model_doc/blenderbot)** (from Facebook) released with the paper [Recipes for building an open-domain chatbot](https://arxiv.org/abs/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.
+1. **[BlenderbotSmall](model_doc/blenderbot-small)** (from Facebook) released with the paper [Recipes for building an open-domain chatbot](https://arxiv.org/abs/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.
+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://arxiv.org/abs/2201.12086) by Junnan Li, Dongxu Li, Caiming Xiong, Steven Hoi.
+1. **[BLOOM](model_doc/bloom)** (from BigScience workshop) released by the [BigScience Workshop](https://bigscience.huggingface.co/).
+1. **[BORT](model_doc/bort)** (from Alexa) released with the paper [Optimal Subarchitecture Extraction For BERT](https://arxiv.org/abs/2010.10499) by Adrian de Wynter and Daniel J. Perry.
+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://arxiv.org/abs/2105.13626) by Linting Xue, Aditya Barua, Noah Constant, Rami Al-Rfou, Sharan Narang, Mihir Kale, Adam Roberts, Colin Raffel.
+1. **[CamemBERT](model_doc/camembert)** (from Inria/Facebook/Sorbonne) released with the paper [CamemBERT: a Tasty French Language Model](https://arxiv.org/abs/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.
+1. **[CANINE](model_doc/canine)** (from Google Research) released with the paper [CANINE: Pre-training an Efficient Tokenization-Free Encoder for Language Representation](https://arxiv.org/abs/2103.06874) by Jonathan H. Clark, Dan Garrette, Iulia Turc, John Wieting.
+1. **[Chinese-CLIP](model_doc/chinese_clip)** (from OFA-Sys) released with the paper [Chinese CLIP: Contrastive Vision-Language Pretraining in Chinese](https://arxiv.org/abs/2211.01335) by An Yang, Junshu Pan, Junyang Lin, Rui Men, Yichang Zhang, Jingren Zhou, Chang Zhou.
+1. **[CLIP](model_doc/clip)** (from OpenAI) released with the paper [Learning Transferable Visual Models From Natural Language Supervision](https://arxiv.org/abs/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.
+1. **[CLIPSeg](model_doc/clipseg)** (from University of Göttingen) released with the paper [Image Segmentation Using Text and Image Prompts](https://arxiv.org/abs/2112.10003) by Timo LĂŒddecke and Alexander Ecker.
+1. **[CodeGen](model_doc/codegen)** (from Salesforce) released with the paper [A Conversational Paradigm for Program Synthesis](https://arxiv.org/abs/2203.13474) by Erik Nijkamp, Bo Pang, Hiroaki Hayashi, Lifu Tu, Huan Wang, Yingbo Zhou, Silvio Savarese, Caiming Xiong.
+1. **[Conditional DETR](model_doc/conditional_detr)** (from Microsoft Research Asia) released with the paper [Conditional DETR for Fast Training Convergence](https://arxiv.org/abs/2108.06152) by Depu Meng, Xiaokang Chen, Zejia Fan, Gang Zeng, Houqiang Li, Yuhui Yuan, Lei Sun, Jingdong Wang.
+1. **[ConvBERT](model_doc/convbert)** (from YituTech) released with the paper [ConvBERT: Improving BERT with Span-based Dynamic Convolution](https://arxiv.org/abs/2008.02496) by Zihang Jiang, Weihao Yu, Daquan Zhou, Yunpeng Chen, Jiashi Feng, Shuicheng Yan.
+1. **[ConvNeXT](model_doc/convnext)** (from Facebook AI) released with the paper [A ConvNet for the 2020s](https://arxiv.org/abs/2201.03545) by Zhuang Liu, Hanzi Mao, Chao-Yuan Wu, Christoph Feichtenhofer, Trevor Darrell, Saining Xie.
+1. **[ConvNeXTV2](model_doc/convnextv2)** (from Facebook AI) released with the paper [ConvNeXt V2: Co-designing and Scaling ConvNets with Masked Autoencoders](https://arxiv.org/abs/2301.00808) by Sanghyun Woo, Shoubhik Debnath, Ronghang Hu, Xinlei Chen, Zhuang Liu, In So Kweon, Saining Xie.
+1. **[CPM](model_doc/cpm)** (from Tsinghua University) released with the paper [CPM: A Large-scale Generative Chinese Pre-trained Language Model](https://arxiv.org/abs/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.
+1. **[CTRL](model_doc/ctrl)** (from Salesforce) released with the paper [CTRL: A Conditional Transformer Language Model for Controllable Generation](https://arxiv.org/abs/1909.05858) by Nitish Shirish Keskar*, Bryan McCann*, Lav R. Varshney, Caiming Xiong and Richard Socher.
+1. **[CvT](model_doc/cvt)** (from Microsoft) released with the paper [CvT: Introducing Convolutions to Vision Transformers](https://arxiv.org/abs/2103.15808) by Haiping Wu, Bin Xiao, Noel Codella, Mengchen Liu, Xiyang Dai, Lu Yuan, Lei Zhang.
+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://arxiv.org/abs/2202.03555) by Alexei Baevski, Wei-Ning Hsu, Qiantong Xu, Arun Babu, Jiatao Gu, Michael Auli.
+1. **[DeBERTa](model_doc/deberta)** (from Microsoft) released with the paper [DeBERTa: Decoding-enhanced BERT with Disentangled Attention](https://arxiv.org/abs/2006.03654) by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen.
+1. **[DeBERTa-v2](model_doc/deberta-v2)** (from Microsoft) released with the paper [DeBERTa: Decoding-enhanced BERT with Disentangled Attention](https://arxiv.org/abs/2006.03654) by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen.
+1. **[Decision Transformer](model_doc/decision_transformer)** (from Berkeley/Facebook/Google) released with the paper [Decision Transformer: Reinforcement Learning via Sequence Modeling](https://arxiv.org/abs/2106.01345) by Lili Chen, Kevin Lu, Aravind Rajeswaran, Kimin Lee, Aditya Grover, Michael Laskin, Pieter Abbeel, Aravind Srinivas, Igor Mordatch.
+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://arxiv.org/abs/2010.04159) by Xizhou Zhu, Weijie Su, Lewei Lu, Bin Li, Xiaogang Wang, Jifeng Dai.
+1. **[DeiT](model_doc/deit)** (from Facebook) released with the paper [Training data-efficient image transformers & distillation through attention](https://arxiv.org/abs/2012.12877) by Hugo Touvron, Matthieu Cord, Matthijs Douze, Francisco Massa, Alexandre Sablayrolles, Hervé Jégou.
+1. **[DETR](model_doc/detr)** (from Facebook) released with the paper [End-to-End Object Detection with Transformers](https://arxiv.org/abs/2005.12872) by Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov, Sergey Zagoruyko.
+1. **[DialoGPT](model_doc/dialogpt)** (from Microsoft Research) released with the paper [DialoGPT: Large-Scale Generative Pre-training for Conversational Response Generation](https://arxiv.org/abs/1911.00536) by Yizhe Zhang, Siqi Sun, Michel Galley, Yen-Chun Chen, Chris Brockett, Xiang Gao, Jianfeng Gao, Jingjing Liu, Bill Dolan.
+1. **[DiNAT](model_doc/dinat)** (from SHI Labs) released with the paper [Dilated Neighborhood Attention Transformer](https://arxiv.org/abs/2209.15001) by Ali Hassani and Humphrey Shi.
+1. **[DistilBERT](model_doc/distilbert)** (from HuggingFace), released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter](https://arxiv.org/abs/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/tree/main/examples/research_projects/distillation), RoBERTa into [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/research_projects/distillation), Multilingual BERT into [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/research_projects/distillation) and a German version of DistilBERT.
+1. **[DiT](model_doc/dit)** (from Microsoft Research) released with the paper [DiT: Self-supervised Pre-training for Document Image Transformer](https://arxiv.org/abs/2203.02378) by Junlong Li, Yiheng Xu, Tengchao Lv, Lei Cui, Cha Zhang, Furu Wei.
+1. **[Donut](model_doc/donut)** (from NAVER), released together with the paper [OCR-free Document Understanding Transformer](https://arxiv.org/abs/2111.15664) by Geewook Kim, Teakgyu Hong, Moonbin Yim, Jeongyeon Nam, Jinyoung Park, Jinyeong Yim, Wonseok Hwang, Sangdoo Yun, Dongyoon Han, Seunghyun Park.
+1. **[DPR](model_doc/dpr)** (from Facebook) released with the paper [Dense Passage Retrieval for Open-Domain Question Answering](https://arxiv.org/abs/2004.04906) by Vladimir Karpukhin, Barlas OÄuz, Sewon Min, Patrick Lewis, Ledell Wu, Sergey Edunov, Danqi Chen, and Wen-tau Yih.
+1. **[DPT](master/model_doc/dpt)** (from Intel Labs) released with the paper [Vision Transformers for Dense Prediction](https://arxiv.org/abs/2103.13413) by René Ranftl, Alexey Bochkovskiy, Vladlen Koltun.
+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://arxiv.org/abs/2003.10555) by Kevin Clark, Minh-Thang Luong, Quoc V. Le, Christopher D. Manning.
+1. **[EncoderDecoder](model_doc/encoder-decoder)** (from Google Research) released with the paper [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://arxiv.org/abs/1907.12461) by Sascha Rothe, Shashi Narayan, Aliaksei Severyn.
+1. **[ERNIE](model_doc/ernie)** (from Baidu) released with the paper [ERNIE: Enhanced Representation through Knowledge Integration](https://arxiv.org/abs/1904.09223) by Yu Sun, Shuohuan Wang, Yukun Li, Shikun Feng, Xuyi Chen, Han Zhang, Xin Tian, Danxiang Zhu, Hao Tian, Hua Wu.
+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.
+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
+1. **[FlauBERT](model_doc/flaubert)** (from CNRS) released with the paper [FlauBERT: Unsupervised Language Model Pre-training for French](https://arxiv.org/abs/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.
+1. **[FLAVA](model_doc/flava)** (from Facebook AI) released with the paper [FLAVA: A Foundational Language And Vision Alignment Model](https://arxiv.org/abs/2112.04482) by Amanpreet Singh, Ronghang Hu, Vedanuj Goswami, Guillaume Couairon, Wojciech Galuba, Marcus Rohrbach, and Douwe Kiela.
+1. **[FNet](model_doc/fnet)** (from Google Research) released with the paper [FNet: Mixing Tokens with Fourier Transforms](https://arxiv.org/abs/2105.03824) by James Lee-Thorp, Joshua Ainslie, Ilya Eckstein, Santiago Ontanon.
+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://arxiv.org/abs/2006.03236) by Zihang Dai, Guokun Lai, Yiming Yang, Quoc V. Le.
+1. **[GIT](model_doc/git)** (from Microsoft Research) released with the paper [GIT: A Generative Image-to-text Transformer for Vision and Language](https://arxiv.org/abs/2205.14100) by Jianfeng Wang, Zhengyuan Yang, Xiaowei Hu, Linjie Li, Kevin Lin, Zhe Gan, Zicheng Liu, Ce Liu, Lijuan Wang.
+1. **[GLPN](model_doc/glpn)** (from KAIST) released with the paper [Global-Local Path Networks for Monocular Depth Estimation with Vertical CutDepth](https://arxiv.org/abs/2201.07436) by Doyeon Kim, Woonghyun Ga, Pyungwhan Ahn, Donggyu Joo, Sehwan Chun, Junmo Kim.
+1. **[GPT](model_doc/openai-gpt)** (from OpenAI) released with the paper [Improving Language Understanding by Generative Pre-Training](https://blog.openai.com/language-unsupervised/) by Alec Radford, Karthik Narasimhan, Tim Salimans and Ilya Sutskever.
+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.
+1. **[GPT NeoX](model_doc/gpt_neox)** (from EleutherAI) released with the paper [GPT-NeoX-20B: An Open-Source Autoregressive Language Model](https://arxiv.org/abs/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
+1. **[GPT NeoX Japanese](model_doc/gpt_neox_japanese)** (from ABEJA) released by Shinya Otani, Takayoshi Makabe, Anuj Arora, and Kyo Hattori.
+1. **[GPT-2](model_doc/gpt2)** (from OpenAI) released with the paper [Language Models are Unsupervised Multitask Learners](https://blog.openai.com/better-language-models/) by Alec Radford*, Jeffrey Wu*, Rewon Child, David Luan, Dario Amodei** and Ilya Sutskever**.
+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.
+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.
+1. **[GroupViT](model_doc/groupvit)** (from UCSD, NVIDIA) released with the paper [GroupViT: Semantic Segmentation Emerges from Text Supervision](https://arxiv.org/abs/2202.11094) by Jiarui Xu, Shalini De Mello, Sifei Liu, Wonmin Byeon, Thomas Breuel, Jan Kautz, Xiaolong Wang.
+1. **[Hubert](model_doc/hubert)** (from Facebook) released with the paper [HuBERT: Self-Supervised Speech Representation Learning by Masked Prediction of Hidden Units](https://arxiv.org/abs/2106.07447) by Wei-Ning Hsu, Benjamin Bolte, Yao-Hung Hubert Tsai, Kushal Lakhotia, Ruslan Salakhutdinov, Abdelrahman Mohamed.
+1. **[I-BERT](model_doc/ibert)** (from Berkeley) released with the paper [I-BERT: Integer-only BERT Quantization](https://arxiv.org/abs/2101.01321) by Sehoon Kim, Amir Gholami, Zhewei Yao, Michael W. Mahoney, Kurt Keutzer.
+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.
+1. **[Jukebox](model_doc/jukebox)** (from OpenAI) released with the paper [Jukebox: A Generative Model for Music](https://arxiv.org/pdf/2005.00341.pdf) by Prafulla Dhariwal, Heewoo Jun, Christine Payne, Jong Wook Kim, Alec Radford, Ilya Sutskever.
+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://arxiv.org/abs/1912.13318) by Yiheng Xu, Minghao Li, Lei Cui, Shaohan Huang, Furu Wei, Ming Zhou.
+1. **[LayoutLMv2](model_doc/layoutlmv2)** (from Microsoft Research Asia) released with the paper [LayoutLMv2: Multi-modal Pre-training for Visually-Rich Document Understanding](https://arxiv.org/abs/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.
+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://arxiv.org/abs/2204.08387) by Yupan Huang, Tengchao Lv, Lei Cui, Yutong Lu, Furu Wei.
+1. **[LayoutXLM](model_doc/layoutxlm)** (from Microsoft Research Asia) released with the paper [LayoutXLM: Multimodal Pre-training for Multilingual Visually-rich Document Understanding](https://arxiv.org/abs/2104.08836) by Yiheng Xu, Tengchao Lv, Lei Cui, Guoxin Wang, Yijuan Lu, Dinei Florencio, Cha Zhang, Furu Wei.
+1. **[LED](model_doc/led)** (from AllenAI) released with the paper [Longformer: The Long-Document Transformer](https://arxiv.org/abs/2004.05150) by Iz Beltagy, Matthew E. Peters, Arman Cohan.
+1. **[LeViT](model_doc/levit)** (from Meta AI) released with the paper [LeViT: A Vision Transformer in ConvNet's Clothing for Faster Inference](https://arxiv.org/abs/2104.01136) by Ben Graham, Alaaeldin El-Nouby, Hugo Touvron, Pierre Stock, Armand Joulin, Hervé Jégou, Matthijs Douze.
+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://arxiv.org/abs/2202.13669) by Jiapeng Wang, Lianwen Jin, Kai Ding.
+1. **[Longformer](model_doc/longformer)** (from AllenAI) released with the paper [Longformer: The Long-Document Transformer](https://arxiv.org/abs/2004.05150) by Iz Beltagy, Matthew E. Peters, Arman Cohan.
+1. **[LongT5](model_doc/longt5)** (from Google AI) released with the paper [LongT5: Efficient Text-To-Text Transformer for Long Sequences](https://arxiv.org/abs/2112.07916) by Mandy Guo, Joshua Ainslie, David Uthus, Santiago Ontanon, Jianmo Ni, Yun-Hsuan Sung, Yinfei Yang.
+1. **[LUKE](model_doc/luke)** (from Studio Ousia) released with the paper [LUKE: Deep Contextualized Entity Representations with Entity-aware Self-attention](https://arxiv.org/abs/2010.01057) by Ikuya Yamada, Akari Asai, Hiroyuki Shindo, Hideaki Takeda, Yuji Matsumoto.
+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://arxiv.org/abs/1908.07490) by Hao Tan and Mohit Bansal.
+1. **[M-CTC-T](model_doc/mctct)** (from Facebook) released with the paper [Pseudo-Labeling For Massively Multilingual Speech Recognition](https://arxiv.org/abs/2111.00161) by Loren Lugosch, Tatiana Likhomanenko, Gabriel Synnaeve, and Ronan Collobert.
+1. **[M2M100](model_doc/m2m_100)** (from Facebook) released with the paper [Beyond English-Centric Multilingual Machine Translation](https://arxiv.org/abs/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.
+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.
+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://arxiv.org/abs/2110.08518) by Junlong Li, Yiheng Xu, Lei Cui, Furu Wei.
+1. **[Mask2Former](model_doc/mask2former)** (from FAIR and UIUC) released with the paper [Masked-attention Mask Transformer for Universal Image Segmentation](https://arxiv.org/abs/2112.01527) by Bowen Cheng, Ishan Misra, Alexander G. Schwing, Alexander Kirillov, Rohit Girdhar.
+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://arxiv.org/abs/2107.06278) by Bowen Cheng, Alexander G. Schwing, Alexander Kirillov.
+1. **[mBART](model_doc/mbart)** (from Facebook) released with the paper [Multilingual Denoising Pre-training for Neural Machine Translation](https://arxiv.org/abs/2001.08210) by Yinhan Liu, Jiatao Gu, Naman Goyal, Xian Li, Sergey Edunov, Marjan Ghazvininejad, Mike Lewis, Luke Zettlemoyer.
+1. **[mBART-50](model_doc/mbart)** (from Facebook) released with the paper [Multilingual Translation with Extensible Multilingual Pretraining and Finetuning](https://arxiv.org/abs/2008.00401) by Yuqing Tang, Chau Tran, Xian Li, Peng-Jen Chen, Naman Goyal, Vishrav Chaudhary, Jiatao Gu, Angela Fan.
+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://arxiv.org/abs/1909.08053) by Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper and Bryan Catanzaro.
+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://arxiv.org/abs/1909.08053) by Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper and Bryan Catanzaro.
+1. **[mLUKE](model_doc/mluke)** (from Studio Ousia) released with the paper [mLUKE: The Power of Entity Representations in Multilingual Pretrained Language Models](https://arxiv.org/abs/2110.08151) by Ryokan Ri, Ikuya Yamada, and Yoshimasa Tsuruoka.
+1. **[MobileBERT](model_doc/mobilebert)** (from CMU/Google Brain) released with the paper [MobileBERT: a Compact Task-Agnostic BERT for Resource-Limited Devices](https://arxiv.org/abs/2004.02984) by Zhiqing Sun, Hongkun Yu, Xiaodan Song, Renjie Liu, Yiming Yang, and Denny Zhou.
+1. **[MobileNetV1](model_doc/mobilenet_v1)** (from Google Inc.) released with the paper [MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications](https://arxiv.org/abs/1704.04861) by Andrew G. Howard, Menglong Zhu, Bo Chen, Dmitry Kalenichenko, Weijun Wang, Tobias Weyand, Marco Andreetto, Hartwig Adam.
+1. **[MobileNetV2](model_doc/mobilenet_v2)** (from Google Inc.) released with the paper [MobileNetV2: Inverted Residuals and Linear Bottlenecks](https://arxiv.org/abs/1801.04381) by Mark Sandler, Andrew Howard, Menglong Zhu, Andrey Zhmoginov, Liang-Chieh Chen.
+1. **[MobileViT](model_doc/mobilevit)** (from Apple) released with the paper [MobileViT: Light-weight, General-purpose, and Mobile-friendly Vision Transformer](https://arxiv.org/abs/2110.02178) by Sachin Mehta and Mohammad Rastegari.
+1. **[MPNet](model_doc/mpnet)** (from Microsoft Research) released with the paper [MPNet: Masked and Permuted Pre-training for Language Understanding](https://arxiv.org/abs/2004.09297) by Kaitao Song, Xu Tan, Tao Qin, Jianfeng Lu, Tie-Yan Liu.
+1. **[MT5](model_doc/mt5)** (from Google AI) released with the paper [mT5: A massively multilingual pre-trained text-to-text transformer](https://arxiv.org/abs/2010.11934) by Linting Xue, Noah Constant, Adam Roberts, Mihir Kale, Rami Al-Rfou, Aditya Siddhant, Aditya Barua, Colin Raffel.
+1. **[MVP](model_doc/mvp)** (from RUC AI Box) released with the paper [MVP: Multi-task Supervised Pre-training for Natural Language Generation](https://arxiv.org/abs/2206.12131) by Tianyi Tang, Junyi Li, Wayne Xin Zhao and Ji-Rong Wen.
+1. **[NAT](model_doc/nat)** (from SHI Labs) released with the paper [Neighborhood Attention Transformer](https://arxiv.org/abs/2204.07143) by Ali Hassani, Steven Walton, Jiachen Li, Shen Li, and Humphrey Shi.
+1. **[Nezha](model_doc/nezha)** (from Huawei Noahâs Ark Lab) released with the paper [NEZHA: Neural Contextualized Representation for Chinese Language Understanding](https://arxiv.org/abs/1909.00204) by Junqiu Wei, Xiaozhe Ren, Xiaoguang Li, Wenyong Huang, Yi Liao, Yasheng Wang, Jiashu Lin, Xin Jiang, Xiao Chen and Qun Liu.
+1. **[NLLB](model_doc/nllb)** (from Meta) released with the paper [No Language Left Behind: Scaling Human-Centered Machine Translation](https://arxiv.org/abs/2207.04672) by the NLLB team.
+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://arxiv.org/abs/2102.03902) by Yunyang Xiong, Zhanpeng Zeng, Rudrasis Chakraborty, Mingxing Tan, Glenn Fung, Yin Li, Vikas Singh.
+1. **[OPT](master/model_doc/opt)** (from Meta AI) released with the paper [OPT: Open Pre-trained Transformer Language Models](https://arxiv.org/abs/2205.01068) by Susan Zhang, Stephen Roller, Naman Goyal, Mikel Artetxe, Moya Chen, Shuohui Chen et al.
+1. **[OWL-ViT](model_doc/owlvit)** (from Google AI) released with the paper [Simple Open-Vocabulary Object Detection with Vision Transformers](https://arxiv.org/abs/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.
+1. **[Pegasus](model_doc/pegasus)** (from Google) released with the paper [PEGASUS: Pre-training with Extracted Gap-sentences for Abstractive Summarization](https://arxiv.org/abs/1912.08777) by Jingqing Zhang, Yao Zhao, Mohammad Saleh and Peter J. Liu.
+1. **[PEGASUS-X](model_doc/pegasus_x)** (from Google) released with the paper [Investigating Efficiently Extending Transformers for Long Input Summarization](https://arxiv.org/abs/2208.04347) by Jason Phang, Yao Zhao, and Peter J. Liu.
+1. **[Perceiver IO](model_doc/perceiver)** (from Deepmind) released with the paper [Perceiver IO: A General Architecture for Structured Inputs & Outputs](https://arxiv.org/abs/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.
+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.
+1. **[PLBart](model_doc/plbart)** (from UCLA NLP) released with the paper [Unified Pre-training for Program Understanding and Generation](https://arxiv.org/abs/2103.06333) by Wasi Uddin Ahmad, Saikat Chakraborty, Baishakhi Ray, Kai-Wei Chang.
+1. **[PoolFormer](model_doc/poolformer)** (from Sea AI Labs) released with the paper [MetaFormer is Actually What You Need for Vision](https://arxiv.org/abs/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.
+1. **[ProphetNet](model_doc/prophetnet)** (from Microsoft Research) released with the paper [ProphetNet: Predicting Future N-gram for Sequence-to-Sequence Pre-training](https://arxiv.org/abs/2001.04063) by Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang and Ming Zhou.
+1. **[QDQBert](model_doc/qdqbert)** (from NVIDIA) released with the paper [Integer Quantization for Deep Learning Inference: Principles and Empirical Evaluation](https://arxiv.org/abs/2004.09602) by Hao Wu, Patrick Judd, Xiaojie Zhang, Mikhail Isaev and Paulius Micikevicius.
+1. **[RAG](model_doc/rag)** (from Facebook) released with the paper [Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks](https://arxiv.org/abs/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.
+1. **[REALM](model_doc/realm.html)** (from Google Research) released with the paper [REALM: Retrieval-Augmented Language Model Pre-Training](https://arxiv.org/abs/2002.08909) by Kelvin Guu, Kenton Lee, Zora Tung, Panupong Pasupat and Ming-Wei Chang.
+1. **[Reformer](model_doc/reformer)** (from Google Research) released with the paper [Reformer: The Efficient Transformer](https://arxiv.org/abs/2001.04451) by Nikita Kitaev, Ćukasz Kaiser, Anselm Levskaya.
+1. **[RegNet](model_doc/regnet)** (from META Platforms) released with the paper [Designing Network Design Space](https://arxiv.org/abs/2003.13678) by Ilija Radosavovic, Raj Prateek Kosaraju, Ross Girshick, Kaiming He, Piotr DollĂĄr.
+1. **[RemBERT](model_doc/rembert)** (from Google Research) released with the paper [Rethinking embedding coupling in pre-trained language models](https://arxiv.org/abs/2010.12821) by Hyung Won Chung, Thibault Févry, Henry Tsai, M. Johnson, Sebastian Ruder.
+1. **[ResNet](model_doc/resnet)** (from Microsoft Research) released with the paper [Deep Residual Learning for Image Recognition](https://arxiv.org/abs/1512.03385) by Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun.
+1. **[RoBERTa](model_doc/roberta)** (from Facebook), released together with the paper [RoBERTa: A Robustly Optimized BERT Pretraining Approach](https://arxiv.org/abs/1907.11692) by Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Mandar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, Veselin Stoyanov.
+1. **[RoBERTa-PreLayerNorm](model_doc/roberta-prelayernorm)** (from Facebook) released with the paper [fairseq: A Fast, Extensible Toolkit for Sequence Modeling](https://arxiv.org/abs/1904.01038) by Myle Ott, Sergey Edunov, Alexei Baevski, Angela Fan, Sam Gross, Nathan Ng, David Grangier, Michael Auli.
+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.
+1. **[RoFormer](model_doc/roformer)** (from ZhuiyiTechnology), released together with the paper [RoFormer: Enhanced Transformer with Rotary Position Embedding](https://arxiv.org/abs/2104.09864) by Jianlin Su and Yu Lu and Shengfeng Pan and Bo Wen and Yunfeng Liu.
+1. **[SegFormer](model_doc/segformer)** (from NVIDIA) released with the paper [SegFormer: Simple and Efficient Design for Semantic Segmentation with Transformers](https://arxiv.org/abs/2105.15203) by Enze Xie, Wenhai Wang, Zhiding Yu, Anima Anandkumar, Jose M. Alvarez, Ping Luo.
+1. **[SEW](model_doc/sew)** (from ASAPP) released with the paper [Performance-Efficiency Trade-offs in Unsupervised Pre-training for Speech Recognition](https://arxiv.org/abs/2109.06870) by Felix Wu, Kwangyoun Kim, Jing Pan, Kyu Han, Kilian Q. Weinberger, Yoav Artzi.
+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://arxiv.org/abs/2109.06870) by Felix Wu, Kwangyoun Kim, Jing Pan, Kyu Han, Kilian Q. Weinberger, Yoav Artzi.
+1. **[SpeechToTextTransformer](model_doc/speech_to_text)** (from Facebook), released together with the paper [fairseq S2T: Fast Speech-to-Text Modeling with fairseq](https://arxiv.org/abs/2010.05171) by Changhan Wang, Yun Tang, Xutai Ma, Anne Wu, Dmytro Okhonko, Juan Pino.
+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://arxiv.org/abs/2104.06678) by Changhan Wang, Anne Wu, Juan Pino, Alexei Baevski, Michael Auli, Alexis Conneau.
+1. **[Splinter](model_doc/splinter)** (from Tel Aviv University), released together with the paper [Few-Shot Question Answering by Pretraining Span Selection](https://arxiv.org/abs/2101.00438) by Ori Ram, Yuval Kirstain, Jonathan Berant, Amir Globerson, Omer Levy.
+1. **[SqueezeBERT](model_doc/squeezebert)** (from Berkeley) released with the paper [SqueezeBERT: What can computer vision teach NLP about efficient neural networks?](https://arxiv.org/abs/2006.11316) by Forrest N. Iandola, Albert E. Shaw, Ravi Krishna, and Kurt W. Keutzer.
+1. **[Swin Transformer](model_doc/swin)** (from Microsoft) released with the paper [Swin Transformer: Hierarchical Vision Transformer using Shifted Windows](https://arxiv.org/abs/2103.14030) by Ze Liu, Yutong Lin, Yue Cao, Han Hu, Yixuan Wei, Zheng Zhang, Stephen Lin, Baining Guo.
+1. **[Swin Transformer V2](model_doc/swinv2)** (from Microsoft) released with the paper [Swin Transformer V2: Scaling Up Capacity and Resolution](https://arxiv.org/abs/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.
+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://arxiv.org/abs/2209.11345) by Marcos V. Conde, Ui-Jin Choi, Maxime Burchi, Radu Timofte.
+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://arxiv.org/abs/2101.03961) by William Fedus, Barret Zoph, Noam Shazeer.
+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://arxiv.org/abs/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.
+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.
+1. **[Table Transformer](model_doc/table-transformer)** (from Microsoft Research) released with the paper [PubTables-1M: Towards Comprehensive Table Extraction From Unstructured Documents](https://arxiv.org/abs/2110.00061) by Brandon Smock, Rohith Pesala, Robin Abraham.
+1. **[TAPAS](model_doc/tapas)** (from Google AI) released with the paper [TAPAS: Weakly Supervised Table Parsing via Pre-training](https://arxiv.org/abs/2004.02349) by Jonathan Herzig, PaweĆ Krzysztof Nowak, Thomas MĂŒller, Francesco Piccinno and Julian Martin Eisenschlos.
+1. **[TAPEX](model_doc/tapex)** (from Microsoft Research) released with the paper [TAPEX: Table Pre-training via Learning a Neural SQL Executor](https://arxiv.org/abs/2107.07653) by Qian Liu, Bei Chen, Jiaqi Guo, Morteza Ziyadi, Zeqi Lin, Weizhu Chen, Jian-Guang Lou.
+1. **[Time Series Transformer](model_doc/time_series_transformer)** (from HuggingFace).
+1. **[TimeSformer](model_doc/timesformer)** (from Facebook) released with the paper [Is Space-Time Attention All You Need for Video Understanding?](https://arxiv.org/abs/2102.05095) by Gedas Bertasius, Heng Wang, Lorenzo Torresani.
+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://arxiv.org/abs/2106.02039) by Michael Janner, Qiyang Li, Sergey Levine
+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://arxiv.org/abs/1901.02860) by Zihang Dai*, Zhilin Yang*, Yiming Yang, Jaime Carbonell, Quoc V. Le, Ruslan Salakhutdinov.
+1. **[TrOCR](model_doc/trocr)** (from Microsoft), released together with the paper [TrOCR: Transformer-based Optical Character Recognition with Pre-trained Models](https://arxiv.org/abs/2109.10282) by Minghao Li, Tengchao Lv, Lei Cui, Yijuan Lu, Dinei Florencio, Cha Zhang, Zhoujun Li, Furu Wei.
+1. **[UL2](model_doc/ul2)** (from Google Research) released with the paper [Unifying Language Learning Paradigms](https://arxiv.org/abs/2205.05131v1) by Yi Tay, Mostafa Dehghani, Vinh Q. Tran, Xavier Garcia, Dara Bahri, Tal Schuster, Huaixiu Steven Zheng, Neil Houlsby, Donald Metzler
+1. **[UniSpeech](model_doc/unispeech)** (from Microsoft Research) released with the paper [UniSpeech: Unified Speech Representation Learning with Labeled and Unlabeled Data](https://arxiv.org/abs/2101.07597) by Chengyi Wang, Yu Wu, Yao Qian, Kenichi Kumatani, Shujie Liu, Furu Wei, Michael Zeng, Xuedong Huang.
+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://arxiv.org/abs/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.
+1. **[UPerNet](model_doc/upernet)** (from Peking University) released with the paper [Unified Perceptual Parsing for Scene Understanding](https://arxiv.org/abs/1807.10221) by Tete Xiao, Yingcheng Liu, Bolei Zhou, Yuning Jiang, Jian Sun.
+1. **[VAN](model_doc/van)** (from Tsinghua University and Nankai University) released with the paper [Visual Attention Network](https://arxiv.org/abs/2202.09741) by Meng-Hao Guo, Cheng-Ze Lu, Zheng-Ning Liu, Ming-Ming Cheng, Shi-Min Hu.
+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://arxiv.org/abs/2203.12602) by Zhan Tong, Yibing Song, Jue Wang, Limin Wang.
+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://arxiv.org/abs/2102.03334) by Wonjae Kim, Bokyung Son, Ildoo Kim.
+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://arxiv.org/abs/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.
+1. **[VisualBERT](model_doc/visual_bert)** (from UCLA NLP) released with the paper [VisualBERT: A Simple and Performant Baseline for Vision and Language](https://arxiv.org/pdf/1908.03557) by Liunian Harold Li, Mark Yatskar, Da Yin, Cho-Jui Hsieh, Kai-Wei Chang.
+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://arxiv.org/abs/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.
+1. **[ViTMAE](model_doc/vit_mae)** (from Meta AI) released with the paper [Masked Autoencoders Are Scalable Vision Learners](https://arxiv.org/abs/2111.06377) by Kaiming He, Xinlei Chen, Saining Xie, Yanghao Li, Piotr DollĂĄr, Ross Girshick.
+1. **[ViTMSN](model_doc/vit_msn)** (from Meta AI) released with the paper [Masked Siamese Networks for Label-Efficient Learning](https://arxiv.org/abs/2204.07141) by Mahmoud Assran, Mathilde Caron, Ishan Misra, Piotr Bojanowski, Florian Bordes, Pascal Vincent, Armand Joulin, Michael Rabbat, Nicolas Ballas.
+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://arxiv.org/abs/2006.11477) by Alexei Baevski, Henry Zhou, Abdelrahman Mohamed, Michael Auli.
+1. **[Wav2Vec2-Conformer](model_doc/wav2vec2-conformer)** (from Facebook AI) released with the paper [FAIRSEQ S2T: Fast Speech-to-Text Modeling with FAIRSEQ](https://arxiv.org/abs/2010.05171) by Changhan Wang, Yun Tang, Xutai Ma, Anne Wu, Sravya Popuri, Dmytro Okhonko, Juan Pino.
+1. **[Wav2Vec2Phoneme](model_doc/wav2vec2_phoneme)** (from Facebook AI) released with the paper [Simple and Effective Zero-shot Cross-lingual Phoneme Recognition](https://arxiv.org/abs/2109.11680) by Qiantong Xu, Alexei Baevski, Michael Auli.
+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://arxiv.org/abs/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.
+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.
+1. **[X-CLIP](model_doc/xclip)** (from Microsoft Research) released with the paper [Expanding Language-Image Pretrained Models for General Video Recognition](https://arxiv.org/abs/2208.02816) by Bolin Ni, Houwen Peng, Minghao Chen, Songyang Zhang, Gaofeng Meng, Jianlong Fu, Shiming Xiang, Haibin Ling.
+1. **[XGLM](model_doc/xglm)** (From Facebook AI) released with the paper [Few-shot Learning with Multilingual Language Models](https://arxiv.org/abs/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.
+1. **[XLM](model_doc/xlm)** (from Facebook) released together with the paper [Cross-lingual Language Model Pretraining](https://arxiv.org/abs/1901.07291) by Guillaume Lample and Alexis Conneau.
+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://arxiv.org/abs/2001.04063) by Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang and Ming Zhou.
+1. **[XLM-RoBERTa](model_doc/xlm-roberta)** (from Facebook AI), released together with the paper [Unsupervised Cross-lingual Representation Learning at Scale](https://arxiv.org/abs/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.
+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://arxiv.org/abs/2105.00572) by Naman Goyal, Jingfei Du, Myle Ott, Giri Anantharaman, Alexis Conneau.
+1. **[XLNet](model_doc/xlnet)** (from Google/CMU) released with the paper [âXLNet: Generalized Autoregressive Pretraining for Language Understanding](https://arxiv.org/abs/1906.08237) by Zhilin Yang*, Zihang Dai*, Yiming Yang, Jaime Carbonell, Ruslan Salakhutdinov, Quoc V. Le.
+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://arxiv.org/abs/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.
+1. **[XLSR-Wav2Vec2](model_doc/xlsr_wav2vec2)** (from Facebook AI) released with the paper [Unsupervised Cross-Lingual Representation Learning For Speech Recognition](https://arxiv.org/abs/2006.13979) by Alexis Conneau, Alexei Baevski, Ronan Collobert, Abdelrahman Mohamed, Michael Auli.
+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://arxiv.org/abs/2106.00666) by Yuxin Fang, Bencheng Liao, Xinggang Wang, Jiemin Fang, Jiyang Qi, Rui Wu, Jianwei Niu, Wenyu Liu.
+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://arxiv.org/abs/2111.09714) by Zhanpeng Zeng, Yunyang Xiong, Sathya N. Ravi, Shailesh Acharya, Glenn Fung, Vikas Singh.
+
+
+### æŻæçæĄæ¶
+
+äžèĄšć±ç€șäșćșäžćŻčæŻäžȘæšĄćçæŻææ
ć”, æŻćŠć
·æPythonćèŻćš (èĄšäžç"Tokenizer slow"). æŻćŠć
·æç±đ€ TokenizersćșæŻæçćż«éćèŻćš(èĄšäžç"Tokenizer fast"), æŻćпݿJax (éèż
+Flax), PyTorch, ć/æè
TensorFlow.
+
+
+
+| Model | Tokenizer slow | Tokenizer fast | PyTorch support | TensorFlow support | Flax Support |
+|:-----------------------------:|:--------------:|:--------------:|:---------------:|:------------------:|:------------:|
+| ALBERT | â
| â
| â
| â
| â
|
+| AltCLIP | â | â | â
| â | â |
+| Audio Spectrogram Transformer | â | â | â
| â | â |
+| BART | â
| â
| â
| â
| â
|
+| BEiT | â | â | â
| â | â
|
+| BERT | â
| â
| â
| â
| â
|
+| Bert Generation | â
| â | â
| â | â |
+| BigBird | â
| â
| â
| â | â
|
+| BigBird-Pegasus | â | â | â
| â | â |
+| BioGpt | â
| â | â
| â | â |
+| BiT | â | â | â
| â | â |
+| Blenderbot | â
| â
| â
| â
| â
|
+| BlenderbotSmall | â
| â
| â
| â
| â
|
+| BLIP | â | â | â
| â | â |
+| BLOOM | â | â
| â
| â | â |
+| CamemBERT | â
| â
| â
| â
| â |
+| CANINE | â
| â | â
| â | â |
+| Chinese-CLIP | â | â | â
| â | â |
+| CLIP | â
| â
| â
| â
| â
|
+| CLIPSeg | â | â | â
| â | â |
+| CodeGen | â
| â
| â
| â | â |
+| Conditional DETR | â | â | â
| â | â |
+| ConvBERT | â
| â
| â
| â
| â |
+| ConvNeXT | â | â | â
| â
| â |
+| CTRL | â
| â | â
| â
| â |
+| CvT | â | â | â
| â
| â |
+| Data2VecAudio | â | â | â
| â | â |
+| Data2VecText | â | â | â
| â | â |
+| Data2VecVision | â | â | â
| â
| â |
+| DeBERTa | â
| â
| â
| â
| â |
+| DeBERTa-v2 | â
| â
| â
| â
| â |
+| Decision Transformer | â | â | â
| â | â |
+| Deformable DETR | â | â | â
| â | â |
+| DeiT | â | â | â
| â
| â |
+| DETR | â | â | â
| â | â |
+| DiNAT | â | â | â
| â | â |
+| DistilBERT | â
| â
| â
| â
| â
|
+| DonutSwin | â | â | â
| â | â |
+| DPR | â
| â
| â
| â
| â |
+| DPT | â | â | â
| â | â |
+| ELECTRA | â
| â
| â
| â
| â
|
+| Encoder decoder | â | â | â
| â
| â
|
+| ERNIE | â | â | â
| â | â |
+| ESM | â
| â | â
| â
| â |
+| FairSeq Machine-Translation | â
| â | â
| â | â |
+| FlauBERT | â
| â | â
| â
| â |
+| FLAVA | â | â | â
| â | â |
+| FNet | â
| â
| â
| â | â |
+| Funnel Transformer | â
| â
| â
| â
| â |
+| GIT | â | â | â
| â | â |
+| GLPN | â | â | â
| â | â |
+| GPT Neo | â | â | â
| â | â
|
+| GPT NeoX | â | â
| â
| â | â |
+| GPT NeoX Japanese | â
| â | â
| â | â |
+| GPT-J | â | â | â
| â
| â
|
+| GPT-Sw3 | â
| â
| â
| â
| â
|
+| GroupViT | â | â | â
| â
| â |
+| Hubert | â | â | â
| â
| â |
+| I-BERT | â | â | â
| â | â |
+| ImageGPT | â | â | â
| â | â |
+| Jukebox | â
| â | â
| â | â |
+| LayoutLM | â
| â
| â
| â
| â |
+| LayoutLMv2 | â
| â
| â
| â | â |
+| LayoutLMv3 | â
| â
| â
| â
| â |
+| LED | â
| â
| â
| â
| â |
+| LeViT | â | â | â
| â | â |
+| LiLT | â | â | â
| â | â |
+| Longformer | â
| â
| â
| â
| â |
+| LongT5 | â | â | â
| â | â
|
+| LUKE | â
| â | â
| â | â |
+| LXMERT | â
| â
| â
| â
| â |
+| M-CTC-T | â | â | â
| â | â |
+| M2M100 | â
| â | â
| â | â |
+| Marian | â
| â | â
| â
| â
|
+| MarkupLM | â
| â
| â
| â | â |
+| Mask2Former | â | â | â
| â | â |
+| MaskFormer | â | â | â
| â | â |
+| MaskFormerSwin | â | â | â | â | â |
+| mBART | â
| â
| â
| â
| â
|
+| Megatron-BERT | â | â | â
| â | â |
+| MobileBERT | â
| â
| â
| â
| â |
+| MobileNetV1 | â | â | â
| â | â |
+| MobileNetV2 | â | â | â
| â | â |
+| MobileViT | â | â | â
| â
| â |
+| MPNet | â
| â
| â
| â
| â |
+| MT5 | â
| â
| â
| â
| â
|
+| MVP | â
| â
| â
| â | â |
+| NAT | â | â | â
| â | â |
+| Nezha | â | â | â
| â | â |
+| Nyströmformer | â | â | â
| â | â |
+| OpenAI GPT | â
| â
| â
| â
| â |
+| OpenAI GPT-2 | â
| â
| â
| â
| â
|
+| OPT | â | â | â
| â
| â
|
+| OWL-ViT | â | â | â
| â | â |
+| Pegasus | â
| â
| â
| â
| â
|
+| PEGASUS-X | â | â | â
| â | â |
+| Perceiver | â
| â | â
| â | â |
+| PLBart | â
| â | â
| â | â |
+| PoolFormer | â | â | â
| â | â |
+| ProphetNet | â
| â | â
| â | â |
+| QDQBert | â | â | â
| â | â |
+| RAG | â
| â | â
| â
| â |
+| REALM | â
| â
| â
| â | â |
+| Reformer | â
| â
| â
| â | â |
+| RegNet | â | â | â
| â
| â
|
+| RemBERT | â
| â
| â
| â
| â |
+| ResNet | â | â | â
| â
| â |
+| RetriBERT | â
| â
| â
| â | â |
+| RoBERTa | â
| â
| â
| â
| â
|
+| RoBERTa-PreLayerNorm | â | â | â
| â
| â
|
+| RoCBert | â
| â | â
| â | â |
+| RoFormer | â
| â
| â
| â
| â
|
+| SegFormer | â | â | â
| â
| â |
+| SEW | â | â | â
| â | â |
+| SEW-D | â | â | â
| â | â |
+| Speech Encoder decoder | â | â | â
| â | â
|
+| Speech2Text | â
| â | â
| â
| â |
+| Speech2Text2 | â
| â | â | â | â |
+| Splinter | â
| â
| â
| â | â |
+| SqueezeBERT | â
| â
| â
| â | â |
+| Swin Transformer | â | â | â
| â
| â |
+| Swin Transformer V2 | â | â | â
| â | â |
+| Swin2SR | â | â | â
| â | â |
+| SwitchTransformers | â | â | â
| â | â |
+| T5 | â
| â
| â
| â
| â
|
+| Table Transformer | â | â | â
| â | â |
+| TAPAS | â
| â | â
| â
| â |
+| Time Series Transformer | â | â | â
| â | â |
+| TimeSformer | â | â | â
| â | â |
+| Trajectory Transformer | â | â | â
| â | â |
+| Transformer-XL | â
| â | â
| â
| â |
+| TrOCR | â | â | â
| â | â |
+| UniSpeech | â | â | â
| â | â |
+| UniSpeechSat | â | â | â
| â | â |
+| UPerNet | â | â | â
| â | â |
+| VAN | â | â | â
| â | â |
+| VideoMAE | â | â | â
| â | â |
+| ViLT | â | â | â
| â | â |
+| Vision Encoder decoder | â | â | â
| â
| â
|
+| VisionTextDualEncoder | â | â | â
| â | â
|
+| VisualBERT | â | â | â
| â | â |
+| ViT | â | â | â
| â
| â
|
+| ViT Hybrid | â | â | â
| â | â |
+| ViTMAE | â | â | â
| â
| â |
+| ViTMSN | â | â | â
| â | â |
+| Wav2Vec2 | â
| â | â
| â
| â
|
+| Wav2Vec2-Conformer | â | â | â
| â | â |
+| WavLM | â | â | â
| â | â |
+| Whisper | â
| â | â
| â
| â |
+| X-CLIP | â | â | â
| â | â |
+| XGLM | â
| â
| â
| â
| â
|
+| XLM | â
| â | â
| â
| â |
+| XLM-ProphetNet | â
| â | â
| â | â |
+| XLM-RoBERTa | â
| â
| â
| â
| â
|
+| XLM-RoBERTa-XL | â | â | â
| â | â |
+| XLNet | â
| â
| â
| â
| â |
+| YOLOS | â | â | â
| â | â |
+| YOSO | â | â | â
| â | â |
+
+
\ No newline at end of file
diff --git a/docs/source/zh/index.mdx b/docs/source/zh/index.mdx
deleted file mode 100644
index 71f5d7e3b174..000000000000
--- a/docs/source/zh/index.mdx
+++ /dev/null
@@ -1,394 +0,0 @@
-
-
-# đ€ Transformersçźä»
-
-äžș[PyTorch](https://pytorch.org/), [TensorFlow](https://www.tensorflow.org/)ć[JAX](https://jax.readthedocs.io/en/latest/)æé çć
èżçæșćšćŠäč ć·„ć
·.
-
-đ€ Transformers æäŸäșćŻä»„蜻æŸć°äžèœœćč¶äžèźç»ć
èżçéąèźç»æšĄćçAPIćć·„ć
·. äœżçšéąèźç»æšĄććŻä»„ćć°èźĄçźæ¶èćçąłææŸ, ćč¶äžèçä»ć€Žèźç»æéèŠçæ¶éŽćè”æș. èżäșæšĄćæŻæäžćæšĄæäžçćžžè§ä»»ćĄïŒæŻćŠ:
-
-đ **èȘç¶èŻèšć€ç**: ææŹćç±», ćœććźäœèŻć«, éźç, èŻèšć»șæšĄ, æèŠ, çż»èŻ, ć€éĄč鿩㿿Źçæ.
-đŒïž **æșćšè§è§**: ćŸććç±», çźæ æŁæ”ćèŻäčććČ.
-đŁïž **éłéą**: èȘćšèŻéłèŻć«ćéłéąćç±».
-đ **〿šĄæ**: èĄšæ Œéźç, ć
ćŠć珊èŻć«, 仿«æææĄŁæć俥æŻ, è§éąćç±»ćè§è§éźç.
-
-đ€ TransformersæŻæćšPyTorch, TensorFlowćJAXäžçäșæäœæ§. èżç»ćšæšĄćçæŻäžȘé¶æź”äœżçšäžćçæĄæ¶ćžŠæ„äșç”æŽ»æ§; ćšäžäžȘæĄæ¶äžäœżçšć èĄä»Łç èźç»äžäžȘæšĄć, ç¶ććšćŠäžäžȘæĄæ¶äžć 蜜ćźćč¶èżèĄæšç. æšĄćäčćŻä»„èą«ćŻŒćșäžșONNXćTorchScriptæ ŒćŒ, çšäșćšçäș§çŻćąäžéšçœČ.
-
-驏äžć ć
„ćš[Hub](https://huggingface.co/models), [forum](https://discuss.huggingface.co/), æè
[Discord](https://discord.com/invite/JfAtkvEtRb)äžæŁćšćż«éćć±ç瀟ćșć§!
-
-## ćŠæäœ éèŠæ„èȘHugging FacećąéçäžȘæ§ćæŻæ
-
-
-
-
-
-## çźćœ
-
-èżçŻææĄŁèą«ç»ç»äžș仄äž5äžȘç« è:
-
-- **ćŒć§äœżçš** ć
ć«äșćșçćż«éäžæććźèŁ
èŻŽæ, äŸżäșé
çœźćèżèĄ.
-- **æçš** æŻäžäžȘććŠè
ćŒć§çć„œć°æč. æŹç« èć°ćžźć©äœ è·ćŸäœ äŒçšć°çäœżçšèżäžȘćșçćșæŹæèœ.
-- **æäœæć** ćäœ ć±ç€șćŠäœćźç°äžäžȘçčćźçźæ , æŻćŠäžșèŻèšć»șæšĄćŸźè°äžäžȘéąèźç»æšĄćæè
ćŠäœćé ćč¶ćäș«äžȘæ§ćæšĄć.
-- **æŠćż”æć** ćŻčđ€ TransformersçæšĄć, ä»»ćĄćèźŸèźĄçćż”èćçćșæŹæŠćż”ćææłćäșæŽć€çèźšèźșćè§Łé.
-- **APIä»ç»** æèż°äșææçç±»ććœæ°:
-
- - **MAIN CLASSES** èŻŠèż°äșé
çœź(configuration)ăæšĄć(model)ăćèŻćš(tokenizer)ćæ”æ°Žçșż(pipeline)èżć äžȘæéèŠçç±».
- - **MODELS** èŻŠèż°äșćšèżäžȘćșäžćæŻäžȘæšĄććźç°æć
łçç±»ććœæ°.
- - **INTERNAL HELPERS** èŻŠèż°äșć
éšäœżçšçć·„ć
·ç±»ććœæ°.
-
-### æŻæçæšĄć
-
-
-
-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://arxiv.org/abs/1909.11942), by Zhenzhong Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.
-1. **[AltCLIP](model_doc/altclip)** (from BAAI) released with the paper [AltCLIP: Altering the Language Encoder in CLIP for Extended Language Capabilities](https://arxiv.org/abs/2211.06679) by Chen, Zhongzhi and Liu, Guang and Zhang, Bo-Wen and Ye, Fulong and Yang, Qinghong and Wu, Ledell.
-1. **[Audio Spectrogram Transformer](model_doc/audio-spectrogram-transformer)** (from MIT) released with the paper [AST: Audio Spectrogram Transformer](https://arxiv.org/abs/2104.01778) by Yuan Gong, Yu-An Chung, James Glass.
-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://arxiv.org/abs/1910.13461) by Mike Lewis, Yinhan Liu, Naman Goyal, Marjan Ghazvininejad, Abdelrahman Mohamed, Omer Levy, Ves Stoyanov and Luke Zettlemoyer.
-1. **[BARThez](model_doc/barthez)** (from Ăcole polytechnique) released with the paper [BARThez: a Skilled Pretrained French Sequence-to-Sequence Model](https://arxiv.org/abs/2010.12321) by Moussa Kamal Eddine, Antoine J.-P. Tixier, Michalis Vazirgiannis.
-1. **[BARTpho](model_doc/bartpho)** (from VinAI Research) released with the paper [BARTpho: Pre-trained Sequence-to-Sequence Models for Vietnamese](https://arxiv.org/abs/2109.09701) by Nguyen Luong Tran, Duong Minh Le and Dat Quoc Nguyen.
-1. **[BEiT](model_doc/beit)** (from Microsoft) released with the paper [BEiT: BERT Pre-Training of Image Transformers](https://arxiv.org/abs/2106.08254) by Hangbo Bao, Li Dong, Furu Wei.
-1. **[BERT](model_doc/bert)** (from Google) released with the paper [BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding](https://arxiv.org/abs/1810.04805) by Jacob Devlin, Ming-Wei Chang, Kenton Lee and Kristina Toutanova.
-1. **[BERT For Sequence Generation](model_doc/bert-generation)** (from Google) released with the paper [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://arxiv.org/abs/1907.12461) by Sascha Rothe, Shashi Narayan, Aliaksei Severyn.
-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.
-1. **[BigBird-Pegasus](model_doc/bigbird_pegasus)** (from Google Research) released with the paper [Big Bird: Transformers for Longer Sequences](https://arxiv.org/abs/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.
-1. **[BigBird-RoBERTa](model_doc/big_bird)** (from Google Research) released with the paper [Big Bird: Transformers for Longer Sequences](https://arxiv.org/abs/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.
-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.
-1. **[BiT](model_doc/bit)** (from Google AI) released with the paper [Big Transfer (BiT): General Visual Representation Learning](https://arxiv.org/abs/1912.11370) by Alexander Kolesnikov, Lucas Beyer, Xiaohua Zhai, Joan Puigcerver, Jessica Yung, Sylvain Gelly, Neil Houlsby.
-1. **[Blenderbot](model_doc/blenderbot)** (from Facebook) released with the paper [Recipes for building an open-domain chatbot](https://arxiv.org/abs/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.
-1. **[BlenderbotSmall](model_doc/blenderbot-small)** (from Facebook) released with the paper [Recipes for building an open-domain chatbot](https://arxiv.org/abs/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.
-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://arxiv.org/abs/2201.12086) by Junnan Li, Dongxu Li, Caiming Xiong, Steven Hoi.
-1. **[BLOOM](model_doc/bloom)** (from BigScience workshop) released by the [BigScience Workshop](https://bigscience.huggingface.co/).
-1. **[BORT](model_doc/bort)** (from Alexa) released with the paper [Optimal Subarchitecture Extraction For BERT](https://arxiv.org/abs/2010.10499) by Adrian de Wynter and Daniel J. Perry.
-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://arxiv.org/abs/2105.13626) by Linting Xue, Aditya Barua, Noah Constant, Rami Al-Rfou, Sharan Narang, Mihir Kale, Adam Roberts, Colin Raffel.
-1. **[CamemBERT](model_doc/camembert)** (from Inria/Facebook/Sorbonne) released with the paper [CamemBERT: a Tasty French Language Model](https://arxiv.org/abs/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.
-1. **[CANINE](model_doc/canine)** (from Google Research) released with the paper [CANINE: Pre-training an Efficient Tokenization-Free Encoder for Language Representation](https://arxiv.org/abs/2103.06874) by Jonathan H. Clark, Dan Garrette, Iulia Turc, John Wieting.
-1. **[Chinese-CLIP](model_doc/chinese_clip)** (from OFA-Sys) released with the paper [Chinese CLIP: Contrastive Vision-Language Pretraining in Chinese](https://arxiv.org/abs/2211.01335) by An Yang, Junshu Pan, Junyang Lin, Rui Men, Yichang Zhang, Jingren Zhou, Chang Zhou.
-1. **[CLIP](model_doc/clip)** (from OpenAI) released with the paper [Learning Transferable Visual Models From Natural Language Supervision](https://arxiv.org/abs/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.
-1. **[CLIPSeg](model_doc/clipseg)** (from University of Göttingen) released with the paper [Image Segmentation Using Text and Image Prompts](https://arxiv.org/abs/2112.10003) by Timo LĂŒddecke and Alexander Ecker.
-1. **[CodeGen](model_doc/codegen)** (from Salesforce) released with the paper [A Conversational Paradigm for Program Synthesis](https://arxiv.org/abs/2203.13474) by Erik Nijkamp, Bo Pang, Hiroaki Hayashi, Lifu Tu, Huan Wang, Yingbo Zhou, Silvio Savarese, Caiming Xiong.
-1. **[Conditional DETR](model_doc/conditional_detr)** (from Microsoft Research Asia) released with the paper [Conditional DETR for Fast Training Convergence](https://arxiv.org/abs/2108.06152) by Depu Meng, Xiaokang Chen, Zejia Fan, Gang Zeng, Houqiang Li, Yuhui Yuan, Lei Sun, Jingdong Wang.
-1. **[ConvBERT](model_doc/convbert)** (from YituTech) released with the paper [ConvBERT: Improving BERT with Span-based Dynamic Convolution](https://arxiv.org/abs/2008.02496) by Zihang Jiang, Weihao Yu, Daquan Zhou, Yunpeng Chen, Jiashi Feng, Shuicheng Yan.
-1. **[ConvNeXT](model_doc/convnext)** (from Facebook AI) released with the paper [A ConvNet for the 2020s](https://arxiv.org/abs/2201.03545) by Zhuang Liu, Hanzi Mao, Chao-Yuan Wu, Christoph Feichtenhofer, Trevor Darrell, Saining Xie.
-1. **[ConvNeXTV2](model_doc/convnextv2)** (from Facebook AI) released with the paper [ConvNeXt V2: Co-designing and Scaling ConvNets with Masked Autoencoders](https://arxiv.org/abs/2301.00808) by Sanghyun Woo, Shoubhik Debnath, Ronghang Hu, Xinlei Chen, Zhuang Liu, In So Kweon, Saining Xie.
-1. **[CPM](model_doc/cpm)** (from Tsinghua University) released with the paper [CPM: A Large-scale Generative Chinese Pre-trained Language Model](https://arxiv.org/abs/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.
-1. **[CTRL](model_doc/ctrl)** (from Salesforce) released with the paper [CTRL: A Conditional Transformer Language Model for Controllable Generation](https://arxiv.org/abs/1909.05858) by Nitish Shirish Keskar*, Bryan McCann*, Lav R. Varshney, Caiming Xiong and Richard Socher.
-1. **[CvT](model_doc/cvt)** (from Microsoft) released with the paper [CvT: Introducing Convolutions to Vision Transformers](https://arxiv.org/abs/2103.15808) by Haiping Wu, Bin Xiao, Noel Codella, Mengchen Liu, Xiyang Dai, Lu Yuan, Lei Zhang.
-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://arxiv.org/abs/2202.03555) by Alexei Baevski, Wei-Ning Hsu, Qiantong Xu, Arun Babu, Jiatao Gu, Michael Auli.
-1. **[DeBERTa](model_doc/deberta)** (from Microsoft) released with the paper [DeBERTa: Decoding-enhanced BERT with Disentangled Attention](https://arxiv.org/abs/2006.03654) by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen.
-1. **[DeBERTa-v2](model_doc/deberta-v2)** (from Microsoft) released with the paper [DeBERTa: Decoding-enhanced BERT with Disentangled Attention](https://arxiv.org/abs/2006.03654) by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen.
-1. **[Decision Transformer](model_doc/decision_transformer)** (from Berkeley/Facebook/Google) released with the paper [Decision Transformer: Reinforcement Learning via Sequence Modeling](https://arxiv.org/abs/2106.01345) by Lili Chen, Kevin Lu, Aravind Rajeswaran, Kimin Lee, Aditya Grover, Michael Laskin, Pieter Abbeel, Aravind Srinivas, Igor Mordatch.
-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://arxiv.org/abs/2010.04159) by Xizhou Zhu, Weijie Su, Lewei Lu, Bin Li, Xiaogang Wang, Jifeng Dai.
-1. **[DeiT](model_doc/deit)** (from Facebook) released with the paper [Training data-efficient image transformers & distillation through attention](https://arxiv.org/abs/2012.12877) by Hugo Touvron, Matthieu Cord, Matthijs Douze, Francisco Massa, Alexandre Sablayrolles, Hervé Jégou.
-1. **[DETR](model_doc/detr)** (from Facebook) released with the paper [End-to-End Object Detection with Transformers](https://arxiv.org/abs/2005.12872) by Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov, Sergey Zagoruyko.
-1. **[DialoGPT](model_doc/dialogpt)** (from Microsoft Research) released with the paper [DialoGPT: Large-Scale Generative Pre-training for Conversational Response Generation](https://arxiv.org/abs/1911.00536) by Yizhe Zhang, Siqi Sun, Michel Galley, Yen-Chun Chen, Chris Brockett, Xiang Gao, Jianfeng Gao, Jingjing Liu, Bill Dolan.
-1. **[DiNAT](model_doc/dinat)** (from SHI Labs) released with the paper [Dilated Neighborhood Attention Transformer](https://arxiv.org/abs/2209.15001) by Ali Hassani and Humphrey Shi.
-1. **[DistilBERT](model_doc/distilbert)** (from HuggingFace), released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter](https://arxiv.org/abs/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/tree/main/examples/research_projects/distillation), RoBERTa into [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/research_projects/distillation), Multilingual BERT into [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/research_projects/distillation) and a German version of DistilBERT.
-1. **[DiT](model_doc/dit)** (from Microsoft Research) released with the paper [DiT: Self-supervised Pre-training for Document Image Transformer](https://arxiv.org/abs/2203.02378) by Junlong Li, Yiheng Xu, Tengchao Lv, Lei Cui, Cha Zhang, Furu Wei.
-1. **[Donut](model_doc/donut)** (from NAVER), released together with the paper [OCR-free Document Understanding Transformer](https://arxiv.org/abs/2111.15664) by Geewook Kim, Teakgyu Hong, Moonbin Yim, Jeongyeon Nam, Jinyoung Park, Jinyeong Yim, Wonseok Hwang, Sangdoo Yun, Dongyoon Han, Seunghyun Park.
-1. **[DPR](model_doc/dpr)** (from Facebook) released with the paper [Dense Passage Retrieval for Open-Domain Question Answering](https://arxiv.org/abs/2004.04906) by Vladimir Karpukhin, Barlas OÄuz, Sewon Min, Patrick Lewis, Ledell Wu, Sergey Edunov, Danqi Chen, and Wen-tau Yih.
-1. **[DPT](master/model_doc/dpt)** (from Intel Labs) released with the paper [Vision Transformers for Dense Prediction](https://arxiv.org/abs/2103.13413) by René Ranftl, Alexey Bochkovskiy, Vladlen Koltun.
-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://arxiv.org/abs/2003.10555) by Kevin Clark, Minh-Thang Luong, Quoc V. Le, Christopher D. Manning.
-1. **[EncoderDecoder](model_doc/encoder-decoder)** (from Google Research) released with the paper [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://arxiv.org/abs/1907.12461) by Sascha Rothe, Shashi Narayan, Aliaksei Severyn.
-1. **[ERNIE](model_doc/ernie)** (from Baidu) released with the paper [ERNIE: Enhanced Representation through Knowledge Integration](https://arxiv.org/abs/1904.09223) by Yu Sun, Shuohuan Wang, Yukun Li, Shikun Feng, Xuyi Chen, Han Zhang, Xin Tian, Danxiang Zhu, Hao Tian, Hua Wu.
-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.
-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
-1. **[FlauBERT](model_doc/flaubert)** (from CNRS) released with the paper [FlauBERT: Unsupervised Language Model Pre-training for French](https://arxiv.org/abs/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.
-1. **[FLAVA](model_doc/flava)** (from Facebook AI) released with the paper [FLAVA: A Foundational Language And Vision Alignment Model](https://arxiv.org/abs/2112.04482) by Amanpreet Singh, Ronghang Hu, Vedanuj Goswami, Guillaume Couairon, Wojciech Galuba, Marcus Rohrbach, and Douwe Kiela.
-1. **[FNet](model_doc/fnet)** (from Google Research) released with the paper [FNet: Mixing Tokens with Fourier Transforms](https://arxiv.org/abs/2105.03824) by James Lee-Thorp, Joshua Ainslie, Ilya Eckstein, Santiago Ontanon.
-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://arxiv.org/abs/2006.03236) by Zihang Dai, Guokun Lai, Yiming Yang, Quoc V. Le.
-1. **[GIT](model_doc/git)** (from Microsoft Research) released with the paper [GIT: A Generative Image-to-text Transformer for Vision and Language](https://arxiv.org/abs/2205.14100) by Jianfeng Wang, Zhengyuan Yang, Xiaowei Hu, Linjie Li, Kevin Lin, Zhe Gan, Zicheng Liu, Ce Liu, Lijuan Wang.
-1. **[GLPN](model_doc/glpn)** (from KAIST) released with the paper [Global-Local Path Networks for Monocular Depth Estimation with Vertical CutDepth](https://arxiv.org/abs/2201.07436) by Doyeon Kim, Woonghyun Ga, Pyungwhan Ahn, Donggyu Joo, Sehwan Chun, Junmo Kim.
-1. **[GPT](model_doc/openai-gpt)** (from OpenAI) released with the paper [Improving Language Understanding by Generative Pre-Training](https://blog.openai.com/language-unsupervised/) by Alec Radford, Karthik Narasimhan, Tim Salimans and Ilya Sutskever.
-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.
-1. **[GPT NeoX](model_doc/gpt_neox)** (from EleutherAI) released with the paper [GPT-NeoX-20B: An Open-Source Autoregressive Language Model](https://arxiv.org/abs/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
-1. **[GPT NeoX Japanese](model_doc/gpt_neox_japanese)** (from ABEJA) released by Shinya Otani, Takayoshi Makabe, Anuj Arora, and Kyo Hattori.
-1. **[GPT-2](model_doc/gpt2)** (from OpenAI) released with the paper [Language Models are Unsupervised Multitask Learners](https://blog.openai.com/better-language-models/) by Alec Radford*, Jeffrey Wu*, Rewon Child, David Luan, Dario Amodei** and Ilya Sutskever**.
-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.
-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.
-1. **[GroupViT](model_doc/groupvit)** (from UCSD, NVIDIA) released with the paper [GroupViT: Semantic Segmentation Emerges from Text Supervision](https://arxiv.org/abs/2202.11094) by Jiarui Xu, Shalini De Mello, Sifei Liu, Wonmin Byeon, Thomas Breuel, Jan Kautz, Xiaolong Wang.
-1. **[Hubert](model_doc/hubert)** (from Facebook) released with the paper [HuBERT: Self-Supervised Speech Representation Learning by Masked Prediction of Hidden Units](https://arxiv.org/abs/2106.07447) by Wei-Ning Hsu, Benjamin Bolte, Yao-Hung Hubert Tsai, Kushal Lakhotia, Ruslan Salakhutdinov, Abdelrahman Mohamed.
-1. **[I-BERT](model_doc/ibert)** (from Berkeley) released with the paper [I-BERT: Integer-only BERT Quantization](https://arxiv.org/abs/2101.01321) by Sehoon Kim, Amir Gholami, Zhewei Yao, Michael W. Mahoney, Kurt Keutzer.
-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.
-1. **[Jukebox](model_doc/jukebox)** (from OpenAI) released with the paper [Jukebox: A Generative Model for Music](https://arxiv.org/pdf/2005.00341.pdf) by Prafulla Dhariwal, Heewoo Jun, Christine Payne, Jong Wook Kim, Alec Radford, Ilya Sutskever.
-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://arxiv.org/abs/1912.13318) by Yiheng Xu, Minghao Li, Lei Cui, Shaohan Huang, Furu Wei, Ming Zhou.
-1. **[LayoutLMv2](model_doc/layoutlmv2)** (from Microsoft Research Asia) released with the paper [LayoutLMv2: Multi-modal Pre-training for Visually-Rich Document Understanding](https://arxiv.org/abs/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.
-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://arxiv.org/abs/2204.08387) by Yupan Huang, Tengchao Lv, Lei Cui, Yutong Lu, Furu Wei.
-1. **[LayoutXLM](model_doc/layoutxlm)** (from Microsoft Research Asia) released with the paper [LayoutXLM: Multimodal Pre-training for Multilingual Visually-rich Document Understanding](https://arxiv.org/abs/2104.08836) by Yiheng Xu, Tengchao Lv, Lei Cui, Guoxin Wang, Yijuan Lu, Dinei Florencio, Cha Zhang, Furu Wei.
-1. **[LED](model_doc/led)** (from AllenAI) released with the paper [Longformer: The Long-Document Transformer](https://arxiv.org/abs/2004.05150) by Iz Beltagy, Matthew E. Peters, Arman Cohan.
-1. **[LeViT](model_doc/levit)** (from Meta AI) released with the paper [LeViT: A Vision Transformer in ConvNet's Clothing for Faster Inference](https://arxiv.org/abs/2104.01136) by Ben Graham, Alaaeldin El-Nouby, Hugo Touvron, Pierre Stock, Armand Joulin, Hervé Jégou, Matthijs Douze.
-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://arxiv.org/abs/2202.13669) by Jiapeng Wang, Lianwen Jin, Kai Ding.
-1. **[Longformer](model_doc/longformer)** (from AllenAI) released with the paper [Longformer: The Long-Document Transformer](https://arxiv.org/abs/2004.05150) by Iz Beltagy, Matthew E. Peters, Arman Cohan.
-1. **[LongT5](model_doc/longt5)** (from Google AI) released with the paper [LongT5: Efficient Text-To-Text Transformer for Long Sequences](https://arxiv.org/abs/2112.07916) by Mandy Guo, Joshua Ainslie, David Uthus, Santiago Ontanon, Jianmo Ni, Yun-Hsuan Sung, Yinfei Yang.
-1. **[LUKE](model_doc/luke)** (from Studio Ousia) released with the paper [LUKE: Deep Contextualized Entity Representations with Entity-aware Self-attention](https://arxiv.org/abs/2010.01057) by Ikuya Yamada, Akari Asai, Hiroyuki Shindo, Hideaki Takeda, Yuji Matsumoto.
-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://arxiv.org/abs/1908.07490) by Hao Tan and Mohit Bansal.
-1. **[M-CTC-T](model_doc/mctct)** (from Facebook) released with the paper [Pseudo-Labeling For Massively Multilingual Speech Recognition](https://arxiv.org/abs/2111.00161) by Loren Lugosch, Tatiana Likhomanenko, Gabriel Synnaeve, and Ronan Collobert.
-1. **[M2M100](model_doc/m2m_100)** (from Facebook) released with the paper [Beyond English-Centric Multilingual Machine Translation](https://arxiv.org/abs/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.
-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.
-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://arxiv.org/abs/2110.08518) by Junlong Li, Yiheng Xu, Lei Cui, Furu Wei.
-1. **[Mask2Former](model_doc/mask2former)** (from FAIR and UIUC) released with the paper [Masked-attention Mask Transformer for Universal Image Segmentation](https://arxiv.org/abs/2112.01527) by Bowen Cheng, Ishan Misra, Alexander G. Schwing, Alexander Kirillov, Rohit Girdhar.
-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://arxiv.org/abs/2107.06278) by Bowen Cheng, Alexander G. Schwing, Alexander Kirillov.
-1. **[mBART](model_doc/mbart)** (from Facebook) released with the paper [Multilingual Denoising Pre-training for Neural Machine Translation](https://arxiv.org/abs/2001.08210) by Yinhan Liu, Jiatao Gu, Naman Goyal, Xian Li, Sergey Edunov, Marjan Ghazvininejad, Mike Lewis, Luke Zettlemoyer.
-1. **[mBART-50](model_doc/mbart)** (from Facebook) released with the paper [Multilingual Translation with Extensible Multilingual Pretraining and Finetuning](https://arxiv.org/abs/2008.00401) by Yuqing Tang, Chau Tran, Xian Li, Peng-Jen Chen, Naman Goyal, Vishrav Chaudhary, Jiatao Gu, Angela Fan.
-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://arxiv.org/abs/1909.08053) by Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper and Bryan Catanzaro.
-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://arxiv.org/abs/1909.08053) by Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper and Bryan Catanzaro.
-1. **[mLUKE](model_doc/mluke)** (from Studio Ousia) released with the paper [mLUKE: The Power of Entity Representations in Multilingual Pretrained Language Models](https://arxiv.org/abs/2110.08151) by Ryokan Ri, Ikuya Yamada, and Yoshimasa Tsuruoka.
-1. **[MobileBERT](model_doc/mobilebert)** (from CMU/Google Brain) released with the paper [MobileBERT: a Compact Task-Agnostic BERT for Resource-Limited Devices](https://arxiv.org/abs/2004.02984) by Zhiqing Sun, Hongkun Yu, Xiaodan Song, Renjie Liu, Yiming Yang, and Denny Zhou.
-1. **[MobileNetV1](model_doc/mobilenet_v1)** (from Google Inc.) released with the paper [MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications](https://arxiv.org/abs/1704.04861) by Andrew G. Howard, Menglong Zhu, Bo Chen, Dmitry Kalenichenko, Weijun Wang, Tobias Weyand, Marco Andreetto, Hartwig Adam.
-1. **[MobileNetV2](model_doc/mobilenet_v2)** (from Google Inc.) released with the paper [MobileNetV2: Inverted Residuals and Linear Bottlenecks](https://arxiv.org/abs/1801.04381) by Mark Sandler, Andrew Howard, Menglong Zhu, Andrey Zhmoginov, Liang-Chieh Chen.
-1. **[MobileViT](model_doc/mobilevit)** (from Apple) released with the paper [MobileViT: Light-weight, General-purpose, and Mobile-friendly Vision Transformer](https://arxiv.org/abs/2110.02178) by Sachin Mehta and Mohammad Rastegari.
-1. **[MPNet](model_doc/mpnet)** (from Microsoft Research) released with the paper [MPNet: Masked and Permuted Pre-training for Language Understanding](https://arxiv.org/abs/2004.09297) by Kaitao Song, Xu Tan, Tao Qin, Jianfeng Lu, Tie-Yan Liu.
-1. **[MT5](model_doc/mt5)** (from Google AI) released with the paper [mT5: A massively multilingual pre-trained text-to-text transformer](https://arxiv.org/abs/2010.11934) by Linting Xue, Noah Constant, Adam Roberts, Mihir Kale, Rami Al-Rfou, Aditya Siddhant, Aditya Barua, Colin Raffel.
-1. **[MVP](model_doc/mvp)** (from RUC AI Box) released with the paper [MVP: Multi-task Supervised Pre-training for Natural Language Generation](https://arxiv.org/abs/2206.12131) by Tianyi Tang, Junyi Li, Wayne Xin Zhao and Ji-Rong Wen.
-1. **[NAT](model_doc/nat)** (from SHI Labs) released with the paper [Neighborhood Attention Transformer](https://arxiv.org/abs/2204.07143) by Ali Hassani, Steven Walton, Jiachen Li, Shen Li, and Humphrey Shi.
-1. **[Nezha](model_doc/nezha)** (from Huawei Noahâs Ark Lab) released with the paper [NEZHA: Neural Contextualized Representation for Chinese Language Understanding](https://arxiv.org/abs/1909.00204) by Junqiu Wei, Xiaozhe Ren, Xiaoguang Li, Wenyong Huang, Yi Liao, Yasheng Wang, Jiashu Lin, Xin Jiang, Xiao Chen and Qun Liu.
-1. **[NLLB](model_doc/nllb)** (from Meta) released with the paper [No Language Left Behind: Scaling Human-Centered Machine Translation](https://arxiv.org/abs/2207.04672) by the NLLB team.
-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://arxiv.org/abs/2102.03902) by Yunyang Xiong, Zhanpeng Zeng, Rudrasis Chakraborty, Mingxing Tan, Glenn Fung, Yin Li, Vikas Singh.
-1. **[OPT](master/model_doc/opt)** (from Meta AI) released with the paper [OPT: Open Pre-trained Transformer Language Models](https://arxiv.org/abs/2205.01068) by Susan Zhang, Stephen Roller, Naman Goyal, Mikel Artetxe, Moya Chen, Shuohui Chen et al.
-1. **[OWL-ViT](model_doc/owlvit)** (from Google AI) released with the paper [Simple Open-Vocabulary Object Detection with Vision Transformers](https://arxiv.org/abs/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.
-1. **[Pegasus](model_doc/pegasus)** (from Google) released with the paper [PEGASUS: Pre-training with Extracted Gap-sentences for Abstractive Summarization](https://arxiv.org/abs/1912.08777) by Jingqing Zhang, Yao Zhao, Mohammad Saleh and Peter J. Liu.
-1. **[PEGASUS-X](model_doc/pegasus_x)** (from Google) released with the paper [Investigating Efficiently Extending Transformers for Long Input Summarization](https://arxiv.org/abs/2208.04347) by Jason Phang, Yao Zhao, and Peter J. Liu.
-1. **[Perceiver IO](model_doc/perceiver)** (from Deepmind) released with the paper [Perceiver IO: A General Architecture for Structured Inputs & Outputs](https://arxiv.org/abs/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.
-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.
-1. **[PLBart](model_doc/plbart)** (from UCLA NLP) released with the paper [Unified Pre-training for Program Understanding and Generation](https://arxiv.org/abs/2103.06333) by Wasi Uddin Ahmad, Saikat Chakraborty, Baishakhi Ray, Kai-Wei Chang.
-1. **[PoolFormer](model_doc/poolformer)** (from Sea AI Labs) released with the paper [MetaFormer is Actually What You Need for Vision](https://arxiv.org/abs/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.
-1. **[ProphetNet](model_doc/prophetnet)** (from Microsoft Research) released with the paper [ProphetNet: Predicting Future N-gram for Sequence-to-Sequence Pre-training](https://arxiv.org/abs/2001.04063) by Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang and Ming Zhou.
-1. **[QDQBert](model_doc/qdqbert)** (from NVIDIA) released with the paper [Integer Quantization for Deep Learning Inference: Principles and Empirical Evaluation](https://arxiv.org/abs/2004.09602) by Hao Wu, Patrick Judd, Xiaojie Zhang, Mikhail Isaev and Paulius Micikevicius.
-1. **[RAG](model_doc/rag)** (from Facebook) released with the paper [Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks](https://arxiv.org/abs/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.
-1. **[REALM](model_doc/realm.html)** (from Google Research) released with the paper [REALM: Retrieval-Augmented Language Model Pre-Training](https://arxiv.org/abs/2002.08909) by Kelvin Guu, Kenton Lee, Zora Tung, Panupong Pasupat and Ming-Wei Chang.
-1. **[Reformer](model_doc/reformer)** (from Google Research) released with the paper [Reformer: The Efficient Transformer](https://arxiv.org/abs/2001.04451) by Nikita Kitaev, Ćukasz Kaiser, Anselm Levskaya.
-1. **[RegNet](model_doc/regnet)** (from META Platforms) released with the paper [Designing Network Design Space](https://arxiv.org/abs/2003.13678) by Ilija Radosavovic, Raj Prateek Kosaraju, Ross Girshick, Kaiming He, Piotr DollĂĄr.
-1. **[RemBERT](model_doc/rembert)** (from Google Research) released with the paper [Rethinking embedding coupling in pre-trained language models](https://arxiv.org/abs/2010.12821) by Hyung Won Chung, Thibault Févry, Henry Tsai, M. Johnson, Sebastian Ruder.
-1. **[ResNet](model_doc/resnet)** (from Microsoft Research) released with the paper [Deep Residual Learning for Image Recognition](https://arxiv.org/abs/1512.03385) by Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun.
-1. **[RoBERTa](model_doc/roberta)** (from Facebook), released together with the paper [RoBERTa: A Robustly Optimized BERT Pretraining Approach](https://arxiv.org/abs/1907.11692) by Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Mandar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, Veselin Stoyanov.
-1. **[RoBERTa-PreLayerNorm](model_doc/roberta-prelayernorm)** (from Facebook) released with the paper [fairseq: A Fast, Extensible Toolkit for Sequence Modeling](https://arxiv.org/abs/1904.01038) by Myle Ott, Sergey Edunov, Alexei Baevski, Angela Fan, Sam Gross, Nathan Ng, David Grangier, Michael Auli.
-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.
-1. **[RoFormer](model_doc/roformer)** (from ZhuiyiTechnology), released together with the paper [RoFormer: Enhanced Transformer with Rotary Position Embedding](https://arxiv.org/abs/2104.09864) by Jianlin Su and Yu Lu and Shengfeng Pan and Bo Wen and Yunfeng Liu.
-1. **[SegFormer](model_doc/segformer)** (from NVIDIA) released with the paper [SegFormer: Simple and Efficient Design for Semantic Segmentation with Transformers](https://arxiv.org/abs/2105.15203) by Enze Xie, Wenhai Wang, Zhiding Yu, Anima Anandkumar, Jose M. Alvarez, Ping Luo.
-1. **[SEW](model_doc/sew)** (from ASAPP) released with the paper [Performance-Efficiency Trade-offs in Unsupervised Pre-training for Speech Recognition](https://arxiv.org/abs/2109.06870) by Felix Wu, Kwangyoun Kim, Jing Pan, Kyu Han, Kilian Q. Weinberger, Yoav Artzi.
-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://arxiv.org/abs/2109.06870) by Felix Wu, Kwangyoun Kim, Jing Pan, Kyu Han, Kilian Q. Weinberger, Yoav Artzi.
-1. **[SpeechToTextTransformer](model_doc/speech_to_text)** (from Facebook), released together with the paper [fairseq S2T: Fast Speech-to-Text Modeling with fairseq](https://arxiv.org/abs/2010.05171) by Changhan Wang, Yun Tang, Xutai Ma, Anne Wu, Dmytro Okhonko, Juan Pino.
-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://arxiv.org/abs/2104.06678) by Changhan Wang, Anne Wu, Juan Pino, Alexei Baevski, Michael Auli, Alexis Conneau.
-1. **[Splinter](model_doc/splinter)** (from Tel Aviv University), released together with the paper [Few-Shot Question Answering by Pretraining Span Selection](https://arxiv.org/abs/2101.00438) by Ori Ram, Yuval Kirstain, Jonathan Berant, Amir Globerson, Omer Levy.
-1. **[SqueezeBERT](model_doc/squeezebert)** (from Berkeley) released with the paper [SqueezeBERT: What can computer vision teach NLP about efficient neural networks?](https://arxiv.org/abs/2006.11316) by Forrest N. Iandola, Albert E. Shaw, Ravi Krishna, and Kurt W. Keutzer.
-1. **[Swin Transformer](model_doc/swin)** (from Microsoft) released with the paper [Swin Transformer: Hierarchical Vision Transformer using Shifted Windows](https://arxiv.org/abs/2103.14030) by Ze Liu, Yutong Lin, Yue Cao, Han Hu, Yixuan Wei, Zheng Zhang, Stephen Lin, Baining Guo.
-1. **[Swin Transformer V2](model_doc/swinv2)** (from Microsoft) released with the paper [Swin Transformer V2: Scaling Up Capacity and Resolution](https://arxiv.org/abs/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.
-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://arxiv.org/abs/2209.11345) by Marcos V. Conde, Ui-Jin Choi, Maxime Burchi, Radu Timofte.
-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://arxiv.org/abs/2101.03961) by William Fedus, Barret Zoph, Noam Shazeer.
-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://arxiv.org/abs/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.
-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.
-1. **[Table Transformer](model_doc/table-transformer)** (from Microsoft Research) released with the paper [PubTables-1M: Towards Comprehensive Table Extraction From Unstructured Documents](https://arxiv.org/abs/2110.00061) by Brandon Smock, Rohith Pesala, Robin Abraham.
-1. **[TAPAS](model_doc/tapas)** (from Google AI) released with the paper [TAPAS: Weakly Supervised Table Parsing via Pre-training](https://arxiv.org/abs/2004.02349) by Jonathan Herzig, PaweĆ Krzysztof Nowak, Thomas MĂŒller, Francesco Piccinno and Julian Martin Eisenschlos.
-1. **[TAPEX](model_doc/tapex)** (from Microsoft Research) released with the paper [TAPEX: Table Pre-training via Learning a Neural SQL Executor](https://arxiv.org/abs/2107.07653) by Qian Liu, Bei Chen, Jiaqi Guo, Morteza Ziyadi, Zeqi Lin, Weizhu Chen, Jian-Guang Lou.
-1. **[Time Series Transformer](model_doc/time_series_transformer)** (from HuggingFace).
-1. **[TimeSformer](model_doc/timesformer)** (from Facebook) released with the paper [Is Space-Time Attention All You Need for Video Understanding?](https://arxiv.org/abs/2102.05095) by Gedas Bertasius, Heng Wang, Lorenzo Torresani.
-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://arxiv.org/abs/2106.02039) by Michael Janner, Qiyang Li, Sergey Levine
-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://arxiv.org/abs/1901.02860) by Zihang Dai*, Zhilin Yang*, Yiming Yang, Jaime Carbonell, Quoc V. Le, Ruslan Salakhutdinov.
-1. **[TrOCR](model_doc/trocr)** (from Microsoft), released together with the paper [TrOCR: Transformer-based Optical Character Recognition with Pre-trained Models](https://arxiv.org/abs/2109.10282) by Minghao Li, Tengchao Lv, Lei Cui, Yijuan Lu, Dinei Florencio, Cha Zhang, Zhoujun Li, Furu Wei.
-1. **[UL2](model_doc/ul2)** (from Google Research) released with the paper [Unifying Language Learning Paradigms](https://arxiv.org/abs/2205.05131v1) by Yi Tay, Mostafa Dehghani, Vinh Q. Tran, Xavier Garcia, Dara Bahri, Tal Schuster, Huaixiu Steven Zheng, Neil Houlsby, Donald Metzler
-1. **[UniSpeech](model_doc/unispeech)** (from Microsoft Research) released with the paper [UniSpeech: Unified Speech Representation Learning with Labeled and Unlabeled Data](https://arxiv.org/abs/2101.07597) by Chengyi Wang, Yu Wu, Yao Qian, Kenichi Kumatani, Shujie Liu, Furu Wei, Michael Zeng, Xuedong Huang.
-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://arxiv.org/abs/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.
-1. **[UPerNet](model_doc/upernet)** (from Peking University) released with the paper [Unified Perceptual Parsing for Scene Understanding](https://arxiv.org/abs/1807.10221) by Tete Xiao, Yingcheng Liu, Bolei Zhou, Yuning Jiang, Jian Sun.
-1. **[VAN](model_doc/van)** (from Tsinghua University and Nankai University) released with the paper [Visual Attention Network](https://arxiv.org/abs/2202.09741) by Meng-Hao Guo, Cheng-Ze Lu, Zheng-Ning Liu, Ming-Ming Cheng, Shi-Min Hu.
-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://arxiv.org/abs/2203.12602) by Zhan Tong, Yibing Song, Jue Wang, Limin Wang.
-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://arxiv.org/abs/2102.03334) by Wonjae Kim, Bokyung Son, Ildoo Kim.
-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://arxiv.org/abs/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.
-1. **[VisualBERT](model_doc/visual_bert)** (from UCLA NLP) released with the paper [VisualBERT: A Simple and Performant Baseline for Vision and Language](https://arxiv.org/pdf/1908.03557) by Liunian Harold Li, Mark Yatskar, Da Yin, Cho-Jui Hsieh, Kai-Wei Chang.
-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://arxiv.org/abs/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.
-1. **[ViTMAE](model_doc/vit_mae)** (from Meta AI) released with the paper [Masked Autoencoders Are Scalable Vision Learners](https://arxiv.org/abs/2111.06377) by Kaiming He, Xinlei Chen, Saining Xie, Yanghao Li, Piotr DollĂĄr, Ross Girshick.
-1. **[ViTMSN](model_doc/vit_msn)** (from Meta AI) released with the paper [Masked Siamese Networks for Label-Efficient Learning](https://arxiv.org/abs/2204.07141) by Mahmoud Assran, Mathilde Caron, Ishan Misra, Piotr Bojanowski, Florian Bordes, Pascal Vincent, Armand Joulin, Michael Rabbat, Nicolas Ballas.
-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://arxiv.org/abs/2006.11477) by Alexei Baevski, Henry Zhou, Abdelrahman Mohamed, Michael Auli.
-1. **[Wav2Vec2-Conformer](model_doc/wav2vec2-conformer)** (from Facebook AI) released with the paper [FAIRSEQ S2T: Fast Speech-to-Text Modeling with FAIRSEQ](https://arxiv.org/abs/2010.05171) by Changhan Wang, Yun Tang, Xutai Ma, Anne Wu, Sravya Popuri, Dmytro Okhonko, Juan Pino.
-1. **[Wav2Vec2Phoneme](model_doc/wav2vec2_phoneme)** (from Facebook AI) released with the paper [Simple and Effective Zero-shot Cross-lingual Phoneme Recognition](https://arxiv.org/abs/2109.11680) by Qiantong Xu, Alexei Baevski, Michael Auli.
-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://arxiv.org/abs/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.
-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.
-1. **[X-CLIP](model_doc/xclip)** (from Microsoft Research) released with the paper [Expanding Language-Image Pretrained Models for General Video Recognition](https://arxiv.org/abs/2208.02816) by Bolin Ni, Houwen Peng, Minghao Chen, Songyang Zhang, Gaofeng Meng, Jianlong Fu, Shiming Xiang, Haibin Ling.
-1. **[XGLM](model_doc/xglm)** (From Facebook AI) released with the paper [Few-shot Learning with Multilingual Language Models](https://arxiv.org/abs/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.
-1. **[XLM](model_doc/xlm)** (from Facebook) released together with the paper [Cross-lingual Language Model Pretraining](https://arxiv.org/abs/1901.07291) by Guillaume Lample and Alexis Conneau.
-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://arxiv.org/abs/2001.04063) by Yu Yan, Weizhen Qi, Yeyun Gong, Dayiheng Liu, Nan Duan, Jiusheng Chen, Ruofei Zhang and Ming Zhou.
-1. **[XLM-RoBERTa](model_doc/xlm-roberta)** (from Facebook AI), released together with the paper [Unsupervised Cross-lingual Representation Learning at Scale](https://arxiv.org/abs/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.
-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://arxiv.org/abs/2105.00572) by Naman Goyal, Jingfei Du, Myle Ott, Giri Anantharaman, Alexis Conneau.
-1. **[XLNet](model_doc/xlnet)** (from Google/CMU) released with the paper [âXLNet: Generalized Autoregressive Pretraining for Language Understanding](https://arxiv.org/abs/1906.08237) by Zhilin Yang*, Zihang Dai*, Yiming Yang, Jaime Carbonell, Ruslan Salakhutdinov, Quoc V. Le.
-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://arxiv.org/abs/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.
-1. **[XLSR-Wav2Vec2](model_doc/xlsr_wav2vec2)** (from Facebook AI) released with the paper [Unsupervised Cross-Lingual Representation Learning For Speech Recognition](https://arxiv.org/abs/2006.13979) by Alexis Conneau, Alexei Baevski, Ronan Collobert, Abdelrahman Mohamed, Michael Auli.
-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://arxiv.org/abs/2106.00666) by Yuxin Fang, Bencheng Liao, Xinggang Wang, Jiemin Fang, Jiyang Qi, Rui Wu, Jianwei Niu, Wenyu Liu.
-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://arxiv.org/abs/2111.09714) by Zhanpeng Zeng, Yunyang Xiong, Sathya N. Ravi, Shailesh Acharya, Glenn Fung, Vikas Singh.
-
-
-### æŻæçæĄæ¶
-
-äžèĄšć±ç€șäșćșäžćŻčæŻäžȘæšĄćçæŻææ
ć”, æŻćŠć
·æPythonćèŻćš (èĄšäžç"Tokenizer slow"). æŻćŠć
·æç±đ€ TokenizersćșæŻæçćż«éćèŻćš(èĄšäžç"Tokenizer fast"), æŻćпݿJax (éèż
-Flax), PyTorch, ć/æè
TensorFlow.
-
-
-
-| Model | Tokenizer slow | Tokenizer fast | PyTorch support | TensorFlow support | Flax Support |
-|:-----------------------------:|:--------------:|:--------------:|:---------------:|:------------------:|:------------:|
-| ALBERT | â
| â
| â
| â
| â
|
-| AltCLIP | â | â | â
| â | â |
-| Audio Spectrogram Transformer | â | â | â
| â | â |
-| BART | â
| â
| â
| â
| â
|
-| BEiT | â | â | â
| â | â
|
-| BERT | â
| â
| â
| â
| â
|
-| Bert Generation | â
| â | â
| â | â |
-| BigBird | â
| â
| â
| â | â
|
-| BigBird-Pegasus | â | â | â
| â | â |
-| BioGpt | â
| â | â
| â | â |
-| BiT | â | â | â
| â | â |
-| Blenderbot | â
| â
| â
| â
| â
|
-| BlenderbotSmall | â
| â
| â
| â
| â
|
-| BLIP | â | â | â
| â | â |
-| BLOOM | â | â
| â
| â | â |
-| CamemBERT | â
| â
| â
| â
| â |
-| CANINE | â
| â | â
| â | â |
-| Chinese-CLIP | â | â | â
| â | â |
-| CLIP | â
| â
| â
| â
| â
|
-| CLIPSeg | â | â | â
| â | â |
-| CodeGen | â
| â
| â
| â | â |
-| Conditional DETR | â | â | â
| â | â |
-| ConvBERT | â
| â
| â
| â
| â |
-| ConvNeXT | â | â | â
| â
| â |
-| CTRL | â
| â | â
| â
| â |
-| CvT | â | â | â
| â
| â |
-| Data2VecAudio | â | â | â
| â | â |
-| Data2VecText | â | â | â
| â | â |
-| Data2VecVision | â | â | â
| â
| â |
-| DeBERTa | â
| â
| â
| â
| â |
-| DeBERTa-v2 | â
| â
| â
| â
| â |
-| Decision Transformer | â | â | â
| â | â |
-| Deformable DETR | â | â | â
| â | â |
-| DeiT | â | â | â
| â
| â |
-| DETR | â | â | â
| â | â |
-| DiNAT | â | â | â
| â | â |
-| DistilBERT | â
| â
| â
| â
| â
|
-| DonutSwin | â | â | â
| â | â |
-| DPR | â
| â
| â
| â
| â |
-| DPT | â | â | â
| â | â |
-| ELECTRA | â
| â
| â
| â
| â
|
-| Encoder decoder | â | â | â
| â
| â
|
-| ERNIE | â | â | â
| â | â |
-| ESM | â
| â | â
| â
| â |
-| FairSeq Machine-Translation | â
| â | â
| â | â |
-| FlauBERT | â
| â | â
| â
| â |
-| FLAVA | â | â | â
| â | â |
-| FNet | â
| â
| â
| â | â |
-| Funnel Transformer | â
| â
| â
| â
| â |
-| GIT | â | â | â
| â | â |
-| GLPN | â | â | â
| â | â |
-| GPT Neo | â | â | â
| â | â
|
-| GPT NeoX | â | â
| â
| â | â |
-| GPT NeoX Japanese | â
| â | â
| â | â |
-| GPT-J | â | â | â
| â
| â
|
-| GPT-Sw3 | â
| â
| â
| â
| â
|
-| GroupViT | â | â | â
| â
| â |
-| Hubert | â | â | â
| â
| â |
-| I-BERT | â | â | â
| â | â |
-| ImageGPT | â | â | â
| â | â |
-| Jukebox | â
| â | â
| â | â |
-| LayoutLM | â
| â
| â
| â
| â |
-| LayoutLMv2 | â
| â
| â
| â | â |
-| LayoutLMv3 | â
| â
| â
| â
| â |
-| LED | â
| â
| â
| â
| â |
-| LeViT | â | â | â
| â | â |
-| LiLT | â | â | â
| â | â |
-| Longformer | â
| â
| â
| â
| â |
-| LongT5 | â | â | â
| â | â
|
-| LUKE | â
| â | â
| â | â |
-| LXMERT | â
| â
| â
| â
| â |
-| M-CTC-T | â | â | â
| â | â |
-| M2M100 | â
| â | â
| â | â |
-| Marian | â
| â | â
| â
| â
|
-| MarkupLM | â
| â
| â
| â | â |
-| Mask2Former | â | â | â
| â | â |
-| MaskFormer | â | â | â
| â | â |
-| MaskFormerSwin | â | â | â | â | â |
-| mBART | â
| â
| â
| â
| â
|
-| Megatron-BERT | â | â | â
| â | â |
-| MobileBERT | â
| â
| â
| â
| â |
-| MobileNetV1 | â | â | â
| â | â |
-| MobileNetV2 | â | â | â
| â | â |
-| MobileViT | â | â | â
| â
| â |
-| MPNet | â
| â
| â
| â
| â |
-| MT5 | â
| â
| â
| â
| â
|
-| MVP | â
| â
| â
| â | â |
-| NAT | â | â | â
| â | â |
-| Nezha | â | â | â
| â | â |
-| Nyströmformer | â | â | â
| â | â |
-| OpenAI GPT | â
| â
| â
| â
| â |
-| OpenAI GPT-2 | â
| â
| â
| â
| â
|
-| OPT | â | â | â
| â
| â
|
-| OWL-ViT | â | â | â
| â | â |
-| Pegasus | â
| â
| â
| â
| â
|
-| PEGASUS-X | â | â | â
| â | â |
-| Perceiver | â
| â | â
| â | â |
-| PLBart | â
| â | â
| â | â |
-| PoolFormer | â | â | â
| â | â |
-| ProphetNet | â
| â | â
| â | â |
-| QDQBert | â | â | â
| â | â |
-| RAG | â
| â | â
| â
| â |
-| REALM | â
| â
| â
| â | â |
-| Reformer | â
| â
| â
| â | â |
-| RegNet | â | â | â
| â
| â
|
-| RemBERT | â
| â
| â
| â
| â |
-| ResNet | â | â | â
| â
| â |
-| RetriBERT | â
| â
| â
| â | â |
-| RoBERTa | â
| â
| â
| â
| â
|
-| RoBERTa-PreLayerNorm | â | â | â
| â
| â
|
-| RoCBert | â
| â | â
| â | â |
-| RoFormer | â
| â
| â
| â
| â
|
-| SegFormer | â | â | â
| â
| â |
-| SEW | â | â | â
| â | â |
-| SEW-D | â | â | â
| â | â |
-| Speech Encoder decoder | â | â | â
| â | â
|
-| Speech2Text | â
| â | â
| â
| â |
-| Speech2Text2 | â
| â | â | â | â |
-| Splinter | â
| â
| â
| â | â |
-| SqueezeBERT | â
| â
| â
| â | â |
-| Swin Transformer | â | â | â
| â
| â |
-| Swin Transformer V2 | â | â | â
| â | â |
-| Swin2SR | â | â | â
| â | â |
-| SwitchTransformers | â | â | â
| â | â |
-| T5 | â
| â
| â
| â
| â
|
-| Table Transformer | â | â | â
| â | â |
-| TAPAS | â
| â | â
| â
| â |
-| Time Series Transformer | â | â | â
| â | â |
-| TimeSformer | â | â | â
| â | â |
-| Trajectory Transformer | â | â | â
| â | â |
-| Transformer-XL | â
| â | â
| â
| â |
-| TrOCR | â | â | â
| â | â |
-| UniSpeech | â | â | â
| â | â |
-| UniSpeechSat | â | â | â
| â | â |
-| UPerNet | â | â | â
| â | â |
-| VAN | â | â | â
| â | â |
-| VideoMAE | â | â | â
| â | â |
-| ViLT | â | â | â
| â | â |
-| Vision Encoder decoder | â | â | â
| â
| â
|
-| VisionTextDualEncoder | â | â | â
| â | â
|
-| VisualBERT | â | â | â
| â | â |
-| ViT | â | â | â
| â
| â
|
-| ViT Hybrid | â | â | â
| â | â |
-| ViTMAE | â | â | â
| â
| â |
-| ViTMSN | â | â | â
| â | â |
-| Wav2Vec2 | â
| â | â
| â
| â
|
-| Wav2Vec2-Conformer | â | â | â
| â | â |
-| WavLM | â | â | â
| â | â |
-| Whisper | â
| â | â
| â
| â |
-| X-CLIP | â | â | â
| â | â |
-| XGLM | â
| â
| â
| â
| â
|
-| XLM | â
| â | â
| â
| â |
-| XLM-ProphetNet | â
| â | â
| â | â |
-| XLM-RoBERTa | â
| â
| â
| â
| â
|
-| XLM-RoBERTa-XL | â | â | â
| â | â |
-| XLNet | â
| â
| â
| â
| â |
-| YOLOS | â | â | â
| â | â |
-| YOSO | â | â | â
| â | â |
-
-
\ No newline at end of file
diff --git a/docs/source/zh/quicktour.md b/docs/source/zh/quicktour.md
new file mode 100644
index 000000000000..41688173116a
--- /dev/null
+++ b/docs/source/zh/quicktour.md
@@ -0,0 +1,542 @@
+
+
+# ćż«éäžæ
+
+[[open-in-colab]]
+
+ćż«æ„äœżçš đ€ Transformers ć§! æ èźșäœ æŻćŒćäșșćèżæŻæ„ćžžçšæ·, èżçŻćż«éäžææçšéœć°ćžźć©äœ ć
„éšćč¶äžćäœ ć±ç€șćŠäœäœżçš[`pipeline`]èżèĄæšç, äœżçš[AutoClass](./model_doc/auto)ć 蜜äžäžȘéąèźç»æšĄććéąć€çćš, 仄ćäœżçšPyTorchæTensorFlowćż«éèźç»äžäžȘæšĄć. ćŠæäœ æŻäžäžȘććŠè
, æä»Źć»șèźźäœ æ„äžæ„æ„çæä»Źçæçšæè
[èŻŸçš](https://huggingface.co/course/chapter1/1), æ„æŽæ·±ć
„ć°äșè§Łćšèżéä»ç»ć°çæŠćż”.
+
+ćšćŒć§äčć, 祟äżäœ ć·Čç»ćźèŁ
äșææćż
èŠçćș:
+
+```bash
+!pip install transformers datasets
+```
+
+äœ èżéèŠćźèŁ
ćæŹąçæșćšćŠäč æĄæ¶:
+
+
+
+```bash
+pip install torch
+```
+
+
+```bash
+pip install tensorflow
+```
+
+
+
+## Pipeline
+
+
+
+äœżçš[`pipeline`]æŻć©çšéąèźç»æšĄćèżèĄæšççæçźćçæčćŒ. äœ èœć€ć°[`pipeline`]ćŒçź±ćłçšć°çšäșè·šäžćæšĄæçć€ç§ä»»ćĄ. æ„ççćźæŻæçä»»ćĄćèĄš:
+
+| **ä»»ćĄ** | **æèż°** | **æšĄæ** | **Pipeline** |
+|------------------------------|--------------------------------------------------------------------------------------------------------------|-----------------|-----------------------------------------------|
+| ææŹćç±» | äžșç»ćźçææŹćșććé
äžäžȘæ çŸ | NLP | pipeline(task="sentiment-analysis") |
+| ææŹçæ | æ čæźç»ćźçæç€șçæææŹ | NLP | pipeline(task="text-generation") |
+| ćœććźäœèŻć« | äžșćșćéçæŻäžȘtokenćé
äžäžȘæ çŸ(äșș, ç»ç», ć°ćçç) | NLP | pipeline(task="ner") |
+| éźççł»ç» | éèżç»ćźçäžäžæćéźéą, ćšææŹäžæćçæĄ | NLP | pipeline(task="question-answering") |
+| æ©ç楫ć
| éąæ”ćșæŁçĄźçćšćșćäžè૿©ççtoken | NLP | pipeline(task="fill-mask") |
+| ææŹæèŠ | äžșææŹćșćæææĄŁçææ»ç» | NLP | pipeline(task="summarization") |
+| ææŹçż»èŻ | ć°ææŹä»äžç§èŻèšçż»èŻäžșćŠäžç§èŻèš | NLP | pipeline(task="translation") |
+| ćŸććç±» | äžșćŸććé
äžäžȘæ çŸ | Computer vision | pipeline(task="image-classification") |
+| ćŸćććČ | äžșćŸćäžæŻäžȘçŹç«çćçŽ ćé
æ çŸ(æŻæèŻäčăć
šæŻććźäŸććČ) | Computer vision | pipeline(task="image-segmentation") |
+| çźæ æŁæ” | éąæ”ćŸćäžçźæ ćŻčè±ĄçèŸčçæĄćç±»ć« | Computer vision | pipeline(task="object-detection") |
+| éłéąćç±» | ç»éłéąæä»¶ćé
äžäžȘæ çŸ | Audio | pipeline(task="audio-classification") |
+| èȘćšèŻéłèŻć« | ć°éłéąæä»¶äžçèŻéłæćäžșææŹ | Audio | pipeline(task="automatic-speech-recognition") |
+| è§è§éźç | ç»ćźäžäžȘćŸććäžäžȘéźéąïŒæŁçĄźć°ćçæć
łćŸćçéźéą | Multimodal | pipeline(task="vqa") |
+
+ćć»șäžäžȘ[`pipeline`]ćźäŸćč¶äžæćźäœ æłèŠć°ćźçšäșçä»»ćĄ, ć°±ćŻä»„ćŒć§äș. äœ ćŻä»„ć°[`pipeline`]çšäșä»»äœäžäžȘäžéąæć°çä»»ćĄ, ćŠææłç„éæŻæçä»»ćĄçćźæŽćèĄš, ćŻä»„æ„é
[pipeline API ćè](./main_classes/pipelines). äžèż, ćšèżçŻæçšäž, äœ ć°æ [`pipeline`]çšćšäžäžȘæ
æćæç€șäŸäž:
+
+```py
+>>> from transformers import pipeline
+
+>>> classifier = pipeline("sentiment-analysis")
+```
+
+[`pipeline`] äŒäžèœœćč¶çŒćäžäžȘçšäșæ
æćæçé»èź€ç[éąèźç»æšĄć](https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english)ććèŻćš. ç°ćšäœ ćŻä»„ćšçźæ ææŹäžäœżçš `classifier`äș:
+
+```py
+>>> classifier("We are very happy to show you the đ€ Transformers library.")
+[{'label': 'POSITIVE', 'score': 0.9998}]
+```
+
+ćŠæäœ æäžæąäžäžȘèŸć
„, ćŻä»„æææèŸć
„æŸć
„äžäžȘćèĄšç¶ćäŒ ç»[`pipeline`], ćźć°äŒèżćäžäžȘćć
žćèĄš:
+
+```py
+>>> results = classifier(["We are very happy to show you the đ€ Transformers library.", "We hope you don't hate it."])
+>>> for result in results:
+... print(f"label: {result['label']}, with score: {round(result['score'], 4)}")
+label: POSITIVE, with score: 0.9998
+label: NEGATIVE, with score: 0.5309
+```
+
+[`pipeline`] äčćŻä»„äžșä»»äœäœ ćæŹąçä»»ćĄéćæŽäžȘæ°æźé. ćšäžéąèżäžȘç€șäŸäž, èź©æä»Źéæ©èȘćšèŻéłèŻć«äœäžșæä»Źçä»»ćĄ:
+
+```py
+>>> import torch
+>>> from transformers import pipeline
+
+>>> speech_recognizer = pipeline("automatic-speech-recognition", model="facebook/wav2vec2-base-960h")
+```
+
+ć 蜜äžäžȘäœ æłéćçéłéąæ°æźé (æ„é
đ€ Datasets [ćż«éćŒć§](https://huggingface.co/docs/datasets/quickstart#audio) è·ćŸæŽć€äżĄæŻ). æŻćŠ, ć 蜜 [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) æ°æźé:
+
+```py
+>>> from datasets import load_dataset, Audio
+
+>>> dataset = load_dataset("PolyAI/minds14", name="en-US", split="train") # doctest: +IGNORE_RESULT
+```
+
+äœ éèŠçĄźäżæ°æźéäžçéłéąçéæ ·çäž [`facebook/wav2vec2-base-960h`](https://huggingface.co/facebook/wav2vec2-base-960h) èźç»çšć°çéłéąçéæ ·çäžèŽ:
+
+```py
+>>> dataset = dataset.cast_column("audio", Audio(sampling_rate=speech_recognizer.feature_extractor.sampling_rate))
+```
+
+ćœè°çš`"audio"` columnæ¶, éłéąæä»¶ć°äŒèȘćšć 蜜ćč¶ééæ ·.
+ä»ććäžȘæ ·æŹäžæććć§æłąćœąæ°ç», ć°ćźäœäžșćèĄšäŒ ç»pipeline:
+
+```py
+>>> result = speech_recognizer(dataset[:4]["audio"])
+>>> print([d["text"] for d in result])
+['I WOULD LIKE TO SET UP A JOINT ACCOUNT WITH MY PARTNER HOW DO I PROCEED WITH DOING THAT', "FODING 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 AP SO 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 THURN A JOIN A COUNT']
+```
+
+ćŻčäșèŸć
„éćžžćș性ç〧㿰æźé (æŻćŠèŻéłæè§è§), äœ äŒæłć°äœżçšäžäžȘçæćš, èäžæŻäžäžȘć°ææèŸć
„éœć 蜜èżć
ćçćèĄš. æ„é
[pipeline API ćè](./main_classes/pipelines) æ„è·ćæŽć€äżĄæŻ.
+
+### ćšpipelineäžäœżçšćŠäžäžȘæšĄćććèŻćš
+
+[`pipeline`]ćŻä»„ćźčçșł[Hub](https://huggingface.co/models)äžçä»»äœæšĄć, èżèź©[`pipeline`]æŽćźčæéçšäșć
¶ä»çšäŸ. æŻćŠ, äœ æłèŠäžäžȘèœć€ć€çæłèŻææŹçæšĄć, ć°±ćŻä»„äœżçšHubäžçæ èź°æ„çéćșćéçæšĄć. é ćççéç»æäŒèżćäžäžȘäžșæ
æćæćŸźè°çć€èŻèšç [BERT æšĄć](https://huggingface.co/nlptown/bert-base-multilingual-uncased-sentiment), äœ ćŻä»„ć°ćźçšäșæłèŻææŹ:
+
+```py
+>>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
+```
+
+
+
+äœżçš [`AutoModelForSequenceClassification`]ć[`AutoTokenizer`]æ„ć 蜜éąèźç»æšĄćććźć
łèçćèŻćš (æŽć€äżĄæŻćŻä»„ćèäžäžèç `AutoClass`):
+
+```py
+>>> from transformers import AutoTokenizer, AutoModelForSequenceClassification
+
+>>> model = AutoModelForSequenceClassification.from_pretrained(model_name)
+>>> tokenizer = AutoTokenizer.from_pretrained(model_name)
+```
+
+
+äœżçš [`TFAutoModelForSequenceClassification`]ć[`AutoTokenizer`] æ„ć 蜜éąèźç»æšĄćććźć
łèçćèŻćš (æŽć€äżĄæŻćŻä»„ćèäžäžèç `TFAutoClass`):
+
+```py
+>>> from transformers import AutoTokenizer, TFAutoModelForSequenceClassification
+
+>>> model = TFAutoModelForSequenceClassification.from_pretrained(model_name)
+>>> tokenizer = AutoTokenizer.from_pretrained(model_name)
+```
+
+
+
+ćš[`pipeline`]äžæćźæšĄćććèŻćš, ç°ćšäœ ć°±ćŻä»„ćšæłèŻææŹäžäœżçš `classifier`äș:
+
+```py
+>>> classifier = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer)
+>>> classifier("Nous sommes trĂšs heureux de vous prĂ©senter la bibliothĂšque đ€ Transformers.")
+[{'label': '5 stars', 'score': 0.7273}]
+```
+
+ćŠæäœ æČĄææŸć°éćäœ çæšĄć, ć°±éèŠćšäœ çæ°æźäžćŸźè°äžäžȘéąèźç»æšĄćäș. æ„ç[ćŸźè°æçš](./training) æ„ćŠäč ææ ·èżèĄćŸźè°. æć, ćŸźè°ćźæšĄćć, èèäžäžćšHubäžäžç€Ÿćș [ćäș«](./model_sharing) èżäžȘæšĄć, ææșćšćŠäč æźćć°æŻäžäžȘäșș! đ€
+
+## AutoClass
+
+
+
+ćšćčć, æŻç±[`AutoModelForSequenceClassification`]ć[`AutoTokenizer`]äžè”·æŻæäœ ćšäžéąçšć°ç[`pipeline`]. [AutoClass](./model_doc/auto) æŻäžäžȘèœć€éèżéąèźç»æšĄćçćç§°æè·ŻćŸèȘćšæ„æŸć
¶æ¶æçćż«æ·æčćŒ. äœ ćȘéèŠäžșäœ çä»»ćĄéæ©ćéç `AutoClass` ććźć
łèçéąć€çç±».
+
+èź©æä»Źćèżć€Žæ„çäžäžèçç€șäŸ, ççææ ·äœżçš `AutoClass` æ„éç°äœżçš[`pipeline`]çç»æ.
+
+### AutoTokenizer
+
+ćèŻćšèŽèŽŁéąć€çææŹ, ć°ææŹèœŹæąäžșçšäșèŸć
„æšĄćçæ°ćæ°ç». æć€äžȘçšæ„知çćèŻèżçšçè§ć, ć
æŹćŠäœæććèŻććšä»äčæ ·ççș§ć«äžæććèŻ (ćš [ćèŻćšæ»ç»](./tokenizer_summary)ćŠäč æŽć€ć
łäșćèŻç俥æŻ). èŠèź°äœæéèŠçæŻäœ éèŠćźäŸćçćèŻćšèŠäžæšĄćçćç§°çžć, æ„祟äżćæšĄćèźç»æ¶äœżçšçžćçćèŻè§ć.
+
+äœżçš[`AutoTokenizer`]ć 蜜äžäžȘćèŻćš:
+
+```py
+>>> from transformers import AutoTokenizer
+
+>>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
+>>> tokenizer = AutoTokenizer.from_pretrained(model_name)
+```
+
+ć°ææŹäŒ ć
„ćèŻćš:
+
+```py
+>>> encoding = tokenizer("We are very happy to show you the đ€ Transformers library.")
+>>> print(encoding)
+{'input_ids': [101, 11312, 10320, 12495, 19308, 10114, 11391, 10855, 10103, 100, 58263, 13299, 119, 102],
+ 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}
+```
+
+ćèŻćšèżćäș㫿ćŠäžć
ćźčçćć
ž:
+
+* [input_ids](./glossary#input-ids): çšæ°ćèĄšç€șçtoken.
+* [attention_mask](.glossary#attention-mask): ćșèŻ„ć
łæłšćȘäștokençæç€ș.
+
+ćèŻćšäčćŻä»„æ„ććèĄšäœäžșèŸć
„, ćč¶ćĄ«ć
ćæȘæææŹ, èżćć
·æç»äžéżćșŠçæčæŹĄ:
+
+
+
+```py
+>>> pt_batch = tokenizer(
+... ["We are very happy to show you the đ€ Transformers library.", "We hope you don't hate it."],
+... padding=True,
+... truncation=True,
+... max_length=512,
+... return_tensors="pt",
+... )
+```
+
+
+```py
+>>> tf_batch = tokenizer(
+... ["We are very happy to show you the đ€ Transformers library.", "We hope you don't hate it."],
+... padding=True,
+... truncation=True,
+... max_length=512,
+... return_tensors="tf",
+... )
+```
+
+
+
+
+
+æ„é
[éąć€ç](./preprocessing)æçšæ„è·ćŸæć
łćèŻçæŽèŻŠç»ç俥æŻ, 仄ććŠäœäœżçš[`AutoFeatureExtractor`]ć[`AutoProcessor`]æ„ć€çćŸć, éłéą, èżæć€æšĄćŒèŸć
„.
+
+
+
+### AutoModel
+
+
+
+đ€ Transformers æäŸäșäžç§çźćç»äžçæčćŒæ„ć 蜜éąèźç»çćźäŸ. èżèĄšç€șäœ ćŻä»„ćć 蜜[`AutoTokenizer`]äžæ ·ć 蜜[`AutoModel`]. ćŻäžäžćçć°æčæŻäžșäœ çä»»ćĄéæ©æŁçĄźç[`AutoModel`]. ćŻčäșææŹ (æćșć) ćç±», äœ ćșèŻ„ć 蜜[`AutoModelForSequenceClassification`]:
+
+```py
+>>> from transformers import AutoModelForSequenceClassification
+
+>>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
+>>> pt_model = AutoModelForSequenceClassification.from_pretrained(model_name)
+```
+
+
+
+éèż[ä»»ćĄæèŠ](./task_summary)æ„æŸ[`AutoModel`]æŻæçä»»ćĄ.
+
+
+
+ç°ćšćŻä»„æéąć€çć„œçèŸć
„æčæŹĄçŽæ„éèżæšĄć. äœ ćȘéèŠæ·»ć `**`æ„è§Łć
ćć
ž:
+
+```py
+>>> pt_outputs = pt_model(**pt_batch)
+```
+
+æšĄććš`logits`㱿§èŸćșæç»çæżæŽ»ç»æ. ćš `logits`äžćșçšsoftmaxćœæ°æ„æ„èŻąæŠç:
+
+```py
+>>> from torch import nn
+
+>>> pt_predictions = nn.functional.softmax(pt_outputs.logits, dim=-1)
+>>> print(pt_predictions)
+tensor([[0.0021, 0.0018, 0.0115, 0.2121, 0.7725],
+ [0.2084, 0.1826, 0.1969, 0.1755, 0.2365]], grad_fn=)
+```
+
+
+đ€ Transformers æäŸäșäžç§çźćç»äžçæčćŒæ„ć 蜜éąèźç»çćźäŸ. èżèĄšç€șäœ ćŻä»„ćć 蜜[`AutoTokenizer`]äžæ ·ć 蜜[`TFAutoModel`]. ćŻäžäžćçć°æčæŻäžșäœ çä»»ćĄéæ©æŁçĄźç[`TFAutoModel`], ćŻčäșææŹ (æćșć) ćç±», äœ ćșèŻ„ć 蜜[`TFAutoModelForSequenceClassification`]:
+
+```py
+>>> from transformers import TFAutoModelForSequenceClassification
+
+>>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
+>>> tf_model = TFAutoModelForSequenceClassification.from_pretrained(model_name)
+```
+
+
+
+éèż[ä»»ćĄæèŠ](./task_summary)æ„æŸ[`AutoModel`]æŻæçä»»ćĄ.
+
+
+
+ç°ćšéèżçŽæ„ć°ćć
žçéźäŒ ç»ćŒ éïŒć°éąć€ççèŸć
„æčæŹĄäŒ ç»æšĄć.
+
+```py
+>>> tf_outputs = tf_model(tf_batch)
+```
+
+æšĄććš`logits`㱿§èŸćșæç»çæżæŽ»ç»æ. ćš `logits`äžćșçšsoftmaxćœæ°æ„æ„èŻąæŠç:
+
+```py
+>>> import tensorflow as tf
+
+>>> tf_predictions = tf.nn.softmax(tf_outputs.logits, axis=-1)
+>>> tf_predictions # doctest: +IGNORE_RESULT
+```
+
+
+
+
+
+ææ đ€ Transformers æšĄć (PyTorch æ TensorFlow) ćšæç»çæżæŽ»ćœæ°(æŻćŠsoftmax)*äčć* èŸćșćŒ é,
+ć äžșæç»çæżæŽ»ćœæ°ćžžćžžäžlossèć. æšĄćçèŸćșæŻçčæźçæ°æźç±», æä»„ćźä»Źç㱿§ćŻä»„ćšIDEäžèą«èȘćšèĄ„ć
š. æšĄćçèŸćșć°±ćäžäžȘć
ç»æćć
ž (äœ ćŻä»„éèżæŽæ°ăćçæć珊äžČæ„玹ćŒćź), ćšèżç§æ
ć”äž, äžșNoneç㱿§äŒèą«ćżœç„.
+
+
+
+### äżćæšĄć
+
+
+
+ćœäœ çæšĄććŸźè°ćźæ, äœ ć°±ćŻä»„äœżçš[`PreTrainedModel.save_pretrained`]æćźććźçćèŻćšäżćäžæ„:
+
+```py
+>>> pt_save_directory = "./pt_save_pretrained"
+>>> tokenizer.save_pretrained(pt_save_directory) # doctest: +IGNORE_RESULT
+>>> pt_model.save_pretrained(pt_save_directory)
+```
+
+ćœäœ ćć€ćæŹĄäœżçšèżäžȘæšĄćæ¶, ć°±ćŻä»„äœżçš[`PreTrainedModel.from_pretrained`]ć 蜜ćźäș:
+
+```py
+>>> pt_model = AutoModelForSequenceClassification.from_pretrained("./pt_save_pretrained")
+```
+
+
+ćœäœ çæšĄććŸźè°ćźæ, äœ ć°±ćŻä»„äœżçš[`TFPreTrainedModel.save_pretrained`]æćźććźçćèŻćšäżćäžæ„:
+
+```py
+>>> tf_save_directory = "./tf_save_pretrained"
+>>> tokenizer.save_pretrained(tf_save_directory) # doctest: +IGNORE_RESULT
+>>> tf_model.save_pretrained(tf_save_directory)
+```
+
+ćœäœ ćć€ćæŹĄäœżçšèżäžȘæšĄćæ¶, ć°±ćŻä»„äœżçš[`TFPreTrainedModel.from_pretrained`]ć 蜜ćźäș:
+
+```py
+>>> tf_model = TFAutoModelForSequenceClassification.from_pretrained("./tf_save_pretrained")
+```
+
+
+
+đ€ TransformersæäžäžȘçčć«é
·çćèœ, ćźèœć€äżćäžäžȘæšĄć, ćč¶äžć°ćźć 蜜äžșPyTorchæTensorFlowæšĄć. `from_pt`æ`from_tf`ćæ°ćŻä»„ć°æšĄćä»äžäžȘæĄæ¶èœŹæąäžșćŠäžäžȘæĄæ¶:
+
+
+
+```py
+>>> from transformers import AutoModel
+
+>>> tokenizer = AutoTokenizer.from_pretrained(tf_save_directory)
+>>> pt_model = AutoModelForSequenceClassification.from_pretrained(tf_save_directory, from_tf=True)
+```
+
+
+```py
+>>> from transformers import TFAutoModel
+
+>>> tokenizer = AutoTokenizer.from_pretrained(pt_save_directory)
+>>> tf_model = TFAutoModelForSequenceClassification.from_pretrained(pt_save_directory, from_pt=True)
+```
+
+
+
+## èȘćźäčæšĄćæć»ș
+
+äœ ćŻä»„äżźæčæšĄćçé
çœźç±»æ„æčćæšĄćçæć»șæčćŒ. é
çœźææäșæšĄćç㱿§, æŻćŠéè㱿è
æłšæćć€Žçæ°é. ćœäœ ä»èȘćźäčçé
çœźç±»ćć§ćæšĄćæ¶, äœ ć°±ćŒć§èȘćźäčæšĄćæć»șäș. æšĄć㱿§æŻéæșćć§ćç, äœ éèŠć
èźç»æšĄć, ç¶ćæèœćŸć°ææäčçç»æ.
+
+éèżćŻŒć
„[`AutoConfig`]æ„ćŒć§, äčćć èœœäœ æłäżźæčçéąèźç»æšĄć. ćš[`AutoConfig.from_pretrained`]äž, äœ èœć€æćźæłèŠäżźæčç㱿§, æŻćŠæłšæćć€Žçæ°é:
+
+```py
+>>> from transformers import AutoConfig
+
+>>> my_config = AutoConfig.from_pretrained("distilbert-base-uncased", n_heads=12)
+```
+
+
+
+äœżçš[`AutoModel.from_config`]æ čæźäœ çèȘćźäčé
çœźćć»șäžäžȘæšĄć:
+
+```py
+>>> from transformers import AutoModel
+
+>>> my_model = AutoModel.from_config(my_config)
+```
+
+
+äœżçš[`TFAutoModel.from_config`]æ čæźäœ çèȘćźäčé
çœźćć»șäžäžȘæšĄć:
+
+```py
+>>> from transformers import TFAutoModel
+
+>>> my_model = TFAutoModel.from_config(my_config)
+```
+
+
+
+æ„é
[ćć»șäžäžȘèȘćźäčç»æ](./create_a_model)æćè·ćæŽć€ć
łäșæć»șèȘćźäčé
çœźç俥æŻ.
+
+## Trainer - PyTorchäŒćèźç»ćŸȘçŻ
+
+ææçæšĄćéœæŻæ ćç[`torch.nn.Module`](https://pytorch.org/docs/stable/nn.html#torch.nn.Module), æä»„äœ ćŻä»„ćšä»»äœć
žćçèźç»æšĄćäžäœżçšćźä»Ź. ćœäœ çŒćèȘć·±çèźç»ćŸȘçŻæ¶W, đ€ TransformersäžșPyTorchæäŸäșäžäžȘ[`Trainer`]ç±», ćźć
ć«äșćșçĄçèźç»ćŸȘçŻćč¶äžäžșèŻžćŠććžćŒèźç», æ··ćçČŸćșŠççčæ§ćąć äșéąć€çćèœ.
+
+ććłäșäœ çä»»ćĄ, äœ éćžžćŻä»„äŒ é仄äžçćæ°ç»[`Trainer`]:
+
+1. [`PreTrainedModel`]æè
[`torch.nn.Module`](https://pytorch.org/docs/stable/nn.html#torch.nn.Module):
+
+ ```py
+ >>> from transformers import AutoModelForSequenceClassification
+
+ >>> model = AutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased")
+ ```
+
+2. [`TrainingArguments`]ć«æäœ ćŻä»„äżźæčçæšĄćè¶
ćæ°, æŻćŠćŠäč ç, æčæŹĄć€§ć°ćèźç»æ¶çèżä»ŁæŹĄæ°. ćŠæäœ æČĄææćźèźç»ćæ°, éŁäčćźäŒäœżçšé»èź€ćŒ:
+
+ ```py
+ >>> from transformers import TrainingArguments
+
+ >>> training_args = TrainingArguments(
+ ... output_dir="path/to/save/folder/",
+ ... learning_rate=2e-5,
+ ... per_device_train_batch_size=8,
+ ... per_device_eval_batch_size=8,
+ ... num_train_epochs=2,
+ ... )
+ ```
+
+3. äžäžȘéąć€çç±», æŻćŠćèŻćš, çčćŸæććšæè
ć€çćš:
+
+ ```py
+ >>> from transformers import AutoTokenizer
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
+ ```
+
+4. ć 蜜äžäžȘæ°æźé:
+
+ ```py
+ >>> from datasets import load_dataset
+
+ >>> dataset = load_dataset("rotten_tomatoes") # doctest: +IGNORE_RESULT
+ ```
+
+5. ćć»șäžäžȘç»æ°æźéćèŻçćœæ°, ćč¶äžäœżçš[`~datasets.Dataset.map`]ćșçšć°æŽäžȘæ°æźé:
+
+ ```py
+ >>> def tokenize_dataset(dataset):
+ ... return tokenizer(dataset["text"])
+
+
+ >>> dataset = dataset.map(tokenize_dataset, batched=True)
+ ```
+
+6. çšæ„仿°æźéäžćć»șæčæŹĄç[`DataCollatorWithPadding`]:
+
+ ```py
+ >>> from transformers import DataCollatorWithPadding
+
+ >>> data_collator = DataCollatorWithPadding(tokenizer=tokenizer)
+ ```
+
+ç°ćšæææçç±»äŒ ç»[`Trainer`]:
+
+```py
+>>> from transformers import Trainer
+
+>>> trainer = Trainer(
+... model=model,
+... args=training_args,
+... train_dataset=dataset["train"],
+... eval_dataset=dataset["test"],
+... tokenizer=tokenizer,
+... data_collator=data_collator,
+... ) # doctest: +SKIP
+```
+
+äžććć€ć°±ç»Șć, è°çš[`~Trainer.train`]èżèĄèźç»:
+
+```py
+>>> trainer.train() # doctest: +SKIP
+```
+
+
+
+ćŻčäșćçż»èŻææèŠèżäșäœżçšćșćć°ćșćæšĄćçä»»ćĄ, çš[`Seq2SeqTrainer`]ć[`Seq2SeqTrainingArguments`]æ„æżä»Ł.
+
+
+
+äœ ćŻä»„éèżćç±»ć[`Trainer`]äžçæčæłæ„èȘćźäčèźç»ćŸȘçŻ. èżæ ·äœ ć°±ćŻä»„èȘćźäčćæć€±ćœæ°, äŒććšćè°ćșŠćšèżæ ·ççčæ§. æ„é
[`Trainer`]ćèæćäșè§ŁćȘäșæčæłèœć€èą«ćç±»ć.
+
+ćŠäžäžȘèȘćźäčèźç»ćŸȘçŻçæčćŒæŻéèż[ćè°](./main_classes/callbacks). äœ ćŻä»„äœżçšćè°æ„äžć
¶ä»ćșéæ, æ„çèźç»ćŸȘçŻæ„æ„ćèżćșŠææćç»æèźç». ćè°äžäŒäżźæčèźç»ćŸȘçŻ. ćŠææłèȘćźäčæć€±ćœæ°ç, ć°±éèŠćç±»ć[`Trainer`]äș.
+
+## äœżçšTensorflowèźç»
+
+æææšĄćéœæŻæ ćç[`tf.keras.Model`](https://www.tensorflow.org/api_docs/python/tf/keras/Model), æä»„äœ ćŻä»„éèż[Keras](https://keras.io/) APIćźç°ćšTensorflowäžèźç». đ€ TransformersæäŸäș[`~TFPreTrainedModel.prepare_tf_dataset`]æčæłæ„蜻æŸć°ć°æ°æźéć 蜜äžș`tf.data.Dataset`, èżæ ·äœ ć°±ćŻä»„äœżçšKerasç[`compile`](https://keras.io/api/models/model_training_apis/#compile-method)ć[`fit`](https://keras.io/api/models/model_training_apis/#fit-method)æčæłé©ŹäžćŒć§èźç».
+
+1. äœżçš[`TFPreTrainedModel`]æè
[`tf.keras.Model`](https://www.tensorflow.org/api_docs/python/tf/keras/Model)æ„ćŒć§:
+
+ ```py
+ >>> from transformers import TFAutoModelForSequenceClassification
+
+ >>> model = TFAutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased")
+ ```
+
+2. äžäžȘéąć€çç±», æŻćŠćèŻćš, çčćŸæććšæè
ć€çćš:
+
+ ```py
+ >>> from transformers import AutoTokenizer
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
+ ```
+
+3. ćć»șäžäžȘç»æ°æźéćèŻçćœæ°
+
+ ```py
+ >>> def tokenize_dataset(dataset):
+ ... return tokenizer(dataset["text"]) # doctest: +SKIP
+ ```
+
+4. äœżçš[`~datasets.Dataset.map`]ć°ćèŻćšćșçšć°æŽäžȘæ°æźé, äčćć°æ°æźéććèŻćšäŒ ç»[`~TFPreTrainedModel.prepare_tf_dataset`]. ćŠæäœ éèŠçèŻ, äčćŻä»„ćšèżéæčćæčæŹĄć€§ć°ćæŻćŠæä豿°æźé:
+
+ ```py
+ >>> dataset = dataset.map(tokenize_dataset) # doctest: +SKIP
+ >>> tf_dataset = model.prepare_tf_dataset(
+ ... dataset, batch_size=16, shuffle=True, tokenizer=tokenizer
+ ... ) # doctest: +SKIP
+ ```
+
+5. äžććć€ć°±ç»Șć, è°çš`compile`ć`fit`ćŒć§èźç»:
+
+ ```py
+ >>> from tensorflow.keras.optimizers import Adam
+
+ >>> model.compile(optimizer=Adam(3e-5))
+ >>> model.fit(dataset) # doctest: +SKIP
+ ```
+
+## æ„äžæ„ćä»äč?
+
+ç°ćšäœ ć·Čç»ćźæäș đ€ Transformers çćż«éäžææçš, æ„ççæä»Źçæććč¶äžćŠäč ćŠäœćäžäșæŽć
·äœçäșæ
, æŻćŠćäžäžȘèȘćźäčæšĄć, äžșæäžȘä»»ćĄćŸźè°äžäžȘæšĄć仄ććŠäœäœżçšèæŹæ„èźç»æšĄć. ćŠæäœ æć
Žè¶Łäșè§ŁæŽć€ đ€ Transformers çæ žćżç« è, éŁć°±ćæŻććĄç¶ćæ„ççæä»ŹçæŠćż”æćć§!
diff --git a/docs/source/zh/quicktour.mdx b/docs/source/zh/quicktour.mdx
deleted file mode 100644
index a9125136ced7..000000000000
--- a/docs/source/zh/quicktour.mdx
+++ /dev/null
@@ -1,538 +0,0 @@
-
-
-# ćż«éäžæ
-
-[[open-in-colab]]
-
-ćż«æ„äœżçš đ€ Transformers ć§! æ èźșäœ æŻćŒćäșșćèżæŻæ„ćžžçšæ·, èżçŻćż«éäžææçšéœć°ćžźć©äœ ć
„éšćč¶äžćäœ ć±ç€șćŠäœäœżçš[`pipeline`]èżèĄæšç, äœżçš[AutoClass](./model_doc/auto)ć 蜜äžäžȘéąèźç»æšĄććéąć€çćš, 仄ćäœżçšPyTorchæTensorFlowćż«éèźç»äžäžȘæšĄć. ćŠæäœ æŻäžäžȘććŠè
, æä»Źć»șèźźäœ æ„äžæ„æ„çæä»Źçæçšæè
[èŻŸçš](https://huggingface.co/course/chapter1/1), æ„æŽæ·±ć
„ć°äșè§Łćšèżéä»ç»ć°çæŠćż”.
-
-ćšćŒć§äčć, 祟äżäœ ć·Čç»ćźèŁ
äșææćż
èŠçćș:
-
-```bash
-!pip install transformers datasets
-```
-
-äœ èżéèŠćźèŁ
ćæŹąçæșćšćŠäč æĄæ¶:
-
-
-
-```bash
-pip install torch
-```
-
-
-```bash
-pip install tensorflow
-```
-
-
-
-## Pipeline
-
-
-
-äœżçš[`pipeline`]æŻć©çšéąèźç»æšĄćèżèĄæšççæçźćçæčćŒ. äœ èœć€ć°[`pipeline`]ćŒçź±ćłçšć°çšäșè·šäžćæšĄæçć€ç§ä»»ćĄ. æ„ççćźæŻæçä»»ćĄćèĄš:
-
-| **ä»»ćĄ** | **æèż°** | **æšĄæ** | **Pipeline** |
-|------------------------------|--------------------------------------------------------------------------------------------------------------|-----------------|-----------------------------------------------|
-| ææŹćç±» | äžșç»ćźçææŹćșććé
äžäžȘæ çŸ | NLP | pipeline(task="sentiment-analysis") |
-| ææŹçæ | æ čæźç»ćźçæç€șçæææŹ | NLP | pipeline(task="text-generation") |
-| ćœććźäœèŻć« | äžșćșćéçæŻäžȘtokenćé
äžäžȘæ çŸ(äșș, ç»ç», ć°ćçç) | NLP | pipeline(task="ner") |
-| éźççł»ç» | éèżç»ćźçäžäžæćéźéą, ćšææŹäžæćçæĄ | NLP | pipeline(task="question-answering") |
-| æ©ç楫ć
| éąæ”ćșæŁçĄźçćšćșćäžè૿©ççtoken | NLP | pipeline(task="fill-mask") |
-| ææŹæèŠ | äžșææŹćșćæææĄŁçææ»ç» | NLP | pipeline(task="summarization") |
-| ææŹçż»èŻ | ć°ææŹä»äžç§èŻèšçż»èŻäžșćŠäžç§èŻèš | NLP | pipeline(task="translation") |
-| ćŸććç±» | äžșćŸććé
äžäžȘæ çŸ | Computer vision | pipeline(task="image-classification") |
-| ćŸćććČ | äžșćŸćäžæŻäžȘçŹç«çćçŽ ćé
æ çŸ(æŻæèŻäčăć
šæŻććźäŸććČ) | Computer vision | pipeline(task="image-segmentation") |
-| çźæ æŁæ” | éąæ”ćŸćäžçźæ ćŻčè±ĄçèŸčçæĄćç±»ć« | Computer vision | pipeline(task="object-detection") |
-| éłéąćç±» | ç»éłéąæä»¶ćé
äžäžȘæ çŸ | Audio | pipeline(task="audio-classification") |
-| èȘćšèŻéłèŻć« | ć°éłéąæä»¶äžçèŻéłæćäžșææŹ | Audio | pipeline(task="automatic-speech-recognition") |
-| è§è§éźç | ç»ćźäžäžȘćŸććäžäžȘéźéąïŒæŁçĄźć°ćçæć
łćŸćçéźéą | Multimodal | pipeline(task="vqa") |
-
-ćć»șäžäžȘ[`pipeline`]ćźäŸćč¶äžæćźäœ æłèŠć°ćźçšäșçä»»ćĄ, ć°±ćŻä»„ćŒć§äș. äœ ćŻä»„ć°[`pipeline`]çšäșä»»äœäžäžȘäžéąæć°çä»»ćĄ, ćŠææłç„éæŻæçä»»ćĄçćźæŽćèĄš, ćŻä»„æ„é
[pipeline API ćè](./main_classes/pipelines). äžèż, ćšèżçŻæçšäž, äœ ć°æ [`pipeline`]çšćšäžäžȘæ
æćæç€șäŸäž:
-
-```py
->>> from transformers import pipeline
-
->>> classifier = pipeline("sentiment-analysis")
-```
-
-[`pipeline`] äŒäžèœœćč¶çŒćäžäžȘçšäșæ
æćæçé»èź€ç[éąèźç»æšĄć](https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english)ććèŻćš. ç°ćšäœ ćŻä»„ćšçźæ ææŹäžäœżçš `classifier`äș:
-
-```py
->>> classifier("We are very happy to show you the đ€ Transformers library.")
-[{'label': 'POSITIVE', 'score': 0.9998}]
-```
-
-ćŠæäœ æäžæąäžäžȘèŸć
„, ćŻä»„æææèŸć
„æŸć
„äžäžȘćèĄšç¶ćäŒ ç»[`pipeline`], ćźć°äŒèżćäžäžȘćć
žćèĄš:
-
-```py
->>> results = classifier(["We are very happy to show you the đ€ Transformers library.", "We hope you don't hate it."])
->>> for result in results:
-... print(f"label: {result['label']}, with score: {round(result['score'], 4)}")
-label: POSITIVE, with score: 0.9998
-label: NEGATIVE, with score: 0.5309
-```
-
-[`pipeline`] äčćŻä»„äžșä»»äœäœ ćæŹąçä»»ćĄéćæŽäžȘæ°æźé. ćšäžéąèżäžȘç€șäŸäž, èź©æä»Źéæ©èȘćšèŻéłèŻć«äœäžșæä»Źçä»»ćĄ:
-
-```py
->>> import torch
->>> from transformers import pipeline
-
->>> speech_recognizer = pipeline("automatic-speech-recognition", model="facebook/wav2vec2-base-960h")
-```
-
-ć 蜜äžäžȘäœ æłéćçéłéąæ°æźé (æ„é
đ€ Datasets [ćż«éćŒć§](https://huggingface.co/docs/datasets/quickstart#audio) è·ćŸæŽć€äżĄæŻ). æŻćŠ, ć 蜜 [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) æ°æźé:
-
-```py
->>> from datasets import load_dataset, Audio
-
->>> dataset = load_dataset("PolyAI/minds14", name="en-US", split="train") # doctest: +IGNORE_RESULT
-```
-
-äœ éèŠçĄźäżæ°æźéäžçéłéąçéæ ·çäž [`facebook/wav2vec2-base-960h`](https://huggingface.co/facebook/wav2vec2-base-960h) èźç»çšć°çéłéąçéæ ·çäžèŽ:
-
-```py
->>> dataset = dataset.cast_column("audio", Audio(sampling_rate=speech_recognizer.feature_extractor.sampling_rate))
-```
-
-ćœè°çš`"audio"` columnæ¶, éłéąæä»¶ć°äŒèȘćšć 蜜ćč¶ééæ ·.
-ä»ććäžȘæ ·æŹäžæććć§æłąćœąæ°ç», ć°ćźäœäžșćèĄšäŒ ç»pipeline:
-
-```py
->>> result = speech_recognizer(dataset[:4]["audio"])
->>> print([d["text"] for d in result])
-['I WOULD LIKE TO SET UP A JOINT ACCOUNT WITH MY PARTNER HOW DO I PROCEED WITH DOING THAT', "FODING 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 AP SO 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 THURN A JOIN A COUNT']
-```
-
-ćŻčäșèŸć
„éćžžćș性ç〧㿰æźé (æŻćŠèŻéłæè§è§), äœ äŒæłć°äœżçšäžäžȘçæćš, èäžæŻäžäžȘć°ææèŸć
„éœć 蜜èżć
ćçćèĄš. æ„é
[pipeline API ćè](./main_classes/pipelines) æ„è·ćæŽć€äżĄæŻ.
-
-### ćšpipelineäžäœżçšćŠäžäžȘæšĄćććèŻćš
-
-[`pipeline`]ćŻä»„ćźčçșł[Hub](https://huggingface.co/models)äžçä»»äœæšĄć, èżèź©[`pipeline`]æŽćźčæéçšäșć
¶ä»çšäŸ. æŻćŠ, äœ æłèŠäžäžȘèœć€ć€çæłèŻææŹçæšĄć, ć°±ćŻä»„äœżçšHubäžçæ èź°æ„çéćșćéçæšĄć. é ćççéç»æäŒèżćäžäžȘäžșæ
æćæćŸźè°çć€èŻèšç [BERT æšĄć](https://huggingface.co/nlptown/bert-base-multilingual-uncased-sentiment), äœ ćŻä»„ć°ćźçšäșæłèŻææŹ:
-
-```py
->>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
-```
-
-
-
-äœżçš [`AutoModelForSequenceClassification`]ć[`AutoTokenizer`]æ„ć 蜜éąèźç»æšĄćććźć
łèçćèŻćš (æŽć€äżĄæŻćŻä»„ćèäžäžèç `AutoClass`):
-
-```py
->>> from transformers import AutoTokenizer, AutoModelForSequenceClassification
-
->>> model = AutoModelForSequenceClassification.from_pretrained(model_name)
->>> tokenizer = AutoTokenizer.from_pretrained(model_name)
-```
-
-
-äœżçš [`TFAutoModelForSequenceClassification`]ć[`AutoTokenizer`] æ„ć 蜜éąèźç»æšĄćććźć
łèçćèŻćš (æŽć€äżĄæŻćŻä»„ćèäžäžèç `TFAutoClass`):
-
-```py
->>> from transformers import AutoTokenizer, TFAutoModelForSequenceClassification
-
->>> model = TFAutoModelForSequenceClassification.from_pretrained(model_name)
->>> tokenizer = AutoTokenizer.from_pretrained(model_name)
-```
-
-
-
-ćš[`pipeline`]äžæćźæšĄćććèŻćš, ç°ćšäœ ć°±ćŻä»„ćšæłèŻææŹäžäœżçš `classifier`äș:
-
-```py
->>> classifier = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer)
->>> classifier("Nous sommes trĂšs heureux de vous prĂ©senter la bibliothĂšque đ€ Transformers.")
-[{'label': '5 stars', 'score': 0.7273}]
-```
-
-ćŠæäœ æČĄææŸć°éćäœ çæšĄć, ć°±éèŠćšäœ çæ°æźäžćŸźè°äžäžȘéąèźç»æšĄćäș. æ„ç[ćŸźè°æçš](./training) æ„ćŠäč ææ ·èżèĄćŸźè°. æć, ćŸźè°ćźæšĄćć, èèäžäžćšHubäžäžç€Ÿćș [ćäș«](./model_sharing) èżäžȘæšĄć, ææșćšćŠäč æźćć°æŻäžäžȘäșș! đ€
-
-## AutoClass
-
-
-
-ćšćčć, æŻç±[`AutoModelForSequenceClassification`]ć[`AutoTokenizer`]äžè”·æŻæäœ ćšäžéąçšć°ç[`pipeline`]. [AutoClass](./model_doc/auto) æŻäžäžȘèœć€éèżéąèźç»æšĄćçćç§°æè·ŻćŸèȘćšæ„æŸć
¶æ¶æçćż«æ·æčćŒ. äœ ćȘéèŠäžșäœ çä»»ćĄéæ©ćéç `AutoClass` ććźć
łèçéąć€çç±».
-
-èź©æä»Źćèżć€Žæ„çäžäžèçç€șäŸ, ççææ ·äœżçš `AutoClass` æ„éç°äœżçš[`pipeline`]çç»æ.
-
-### AutoTokenizer
-
-ćèŻćšèŽèŽŁéąć€çææŹ, ć°ææŹèœŹæąäžșçšäșèŸć
„æšĄćçæ°ćæ°ç». æć€äžȘçšæ„知çćèŻèżçšçè§ć, ć
æŹćŠäœæććèŻććšä»äčæ ·ççș§ć«äžæććèŻ (ćš [ćèŻćšæ»ç»](./tokenizer_summary)ćŠäč æŽć€ć
łäșćèŻç俥æŻ). èŠèź°äœæéèŠçæŻäœ éèŠćźäŸćçćèŻćšèŠäžæšĄćçćç§°çžć, æ„祟äżćæšĄćèźç»æ¶äœżçšçžćçćèŻè§ć.
-
-äœżçš[`AutoTokenizer`]ć 蜜äžäžȘćèŻćš:
-
-```py
->>> from transformers import AutoTokenizer
-
->>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
->>> tokenizer = AutoTokenizer.from_pretrained(model_name)
-```
-
-ć°ææŹäŒ ć
„ćèŻćš:
-
-```py
->>> encoding = tokenizer("We are very happy to show you the đ€ Transformers library.")
->>> print(encoding)
-{'input_ids': [101, 11312, 10320, 12495, 19308, 10114, 11391, 10855, 10103, 100, 58263, 13299, 119, 102],
- 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
- 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}
-```
-
-ćèŻćšèżćäș㫿ćŠäžć
ćźčçćć
ž:
-
-* [input_ids](./glossary#input-ids): çšæ°ćèĄšç€șçtoken.
-* [attention_mask](.glossary#attention-mask): ćșèŻ„ć
łæłšćȘäștokençæç€ș.
-
-ćèŻćšäčćŻä»„æ„ććèĄšäœäžșèŸć
„, ćč¶ćĄ«ć
ćæȘæææŹ, èżćć
·æç»äžéżćșŠçæčæŹĄ:
-
-
-
-```py
->>> pt_batch = tokenizer(
-... ["We are very happy to show you the đ€ Transformers library.", "We hope you don't hate it."],
-... padding=True,
-... truncation=True,
-... max_length=512,
-... return_tensors="pt",
-... )
-```
-
-
-```py
->>> tf_batch = tokenizer(
-... ["We are very happy to show you the đ€ Transformers library.", "We hope you don't hate it."],
-... padding=True,
-... truncation=True,
-... max_length=512,
-... return_tensors="tf",
-... )
-```
-
-
-
-
-
-æ„é
[éąć€ç](./preprocessing)æçšæ„è·ćŸæć
łćèŻçæŽèŻŠç»ç俥æŻ, 仄ććŠäœäœżçš[`AutoFeatureExtractor`]ć[`AutoProcessor`]æ„ć€çćŸć, éłéą, èżæć€æšĄćŒèŸć
„.
-
-
-
-### AutoModel
-
-
-
-đ€ Transformers æäŸäșäžç§çźćç»äžçæčćŒæ„ć 蜜éąèźç»çćźäŸ. èżèĄšç€șäœ ćŻä»„ćć 蜜[`AutoTokenizer`]äžæ ·ć 蜜[`AutoModel`]. ćŻäžäžćçć°æčæŻäžșäœ çä»»ćĄéæ©æŁçĄźç[`AutoModel`]. ćŻčäșææŹ (æćșć) ćç±», äœ ćșèŻ„ć 蜜[`AutoModelForSequenceClassification`]:
-
-```py
->>> from transformers import AutoModelForSequenceClassification
-
->>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
->>> pt_model = AutoModelForSequenceClassification.from_pretrained(model_name)
-```
-
-
-
-éèż[ä»»ćĄæèŠ](./task_summary)æ„æŸ[`AutoModel`]æŻæçä»»ćĄ.
-
-
-
-ç°ćšćŻä»„æéąć€çć„œçèŸć
„æčæŹĄçŽæ„éèżæšĄć. äœ ćȘéèŠæ·»ć `**`æ„è§Łć
ćć
ž:
-
-```py
->>> pt_outputs = pt_model(**pt_batch)
-```
-
-æšĄććš`logits`㱿§èŸćșæç»çæżæŽ»ç»æ. ćš `logits`äžćșçšsoftmaxćœæ°æ„æ„èŻąæŠç:
-
-```py
->>> from torch import nn
-
->>> pt_predictions = nn.functional.softmax(pt_outputs.logits, dim=-1)
->>> print(pt_predictions)
-tensor([[0.0021, 0.0018, 0.0115, 0.2121, 0.7725],
- [0.2084, 0.1826, 0.1969, 0.1755, 0.2365]], grad_fn=)
-```
-
-
-đ€ Transformers æäŸäșäžç§çźćç»äžçæčćŒæ„ć 蜜éąèźç»çćźäŸ. èżèĄšç€șäœ ćŻä»„ćć 蜜[`AutoTokenizer`]äžæ ·ć 蜜[`TFAutoModel`]. ćŻäžäžćçć°æčæŻäžșäœ çä»»ćĄéæ©æŁçĄźç[`TFAutoModel`], ćŻčäșææŹ (æćșć) ćç±», äœ ćșèŻ„ć 蜜[`TFAutoModelForSequenceClassification`]:
-
-```py
->>> from transformers import TFAutoModelForSequenceClassification
-
->>> model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
->>> tf_model = TFAutoModelForSequenceClassification.from_pretrained(model_name)
-```
-
-
-
-éèż[ä»»ćĄæèŠ](./task_summary)æ„æŸ[`AutoModel`]æŻæçä»»ćĄ.
-
-
-
-ç°ćšéèżçŽæ„ć°ćć
žçéźäŒ ç»ćŒ éïŒć°éąć€ççèŸć
„æčæŹĄäŒ ç»æšĄć.
-
-```py
->>> tf_outputs = tf_model(tf_batch)
-```
-
-æšĄććš`logits`㱿§èŸćșæç»çæżæŽ»ç»æ. ćš `logits`äžćșçšsoftmaxćœæ°æ„æ„èŻąæŠç:
-
-```py
->>> import tensorflow as tf
-
->>> tf_predictions = tf.nn.softmax(tf_outputs.logits, axis=-1)
->>> tf_predictions # doctest: +IGNORE_RESULT
-```
-
-
-
-
-
-ææ đ€ Transformers æšĄć (PyTorch æ TensorFlow) ćšæç»çæżæŽ»ćœæ°(æŻćŠsoftmax)*äčć* èŸćșćŒ é,
-ć äžșæç»çæżæŽ»ćœæ°ćžžćžžäžlossèć. æšĄćçèŸćșæŻçčæźçæ°æźç±», æä»„ćźä»Źç㱿§ćŻä»„ćšIDEäžèą«èȘćšèĄ„ć
š. æšĄćçèŸćșć°±ćäžäžȘć
ç»æćć
ž (äœ ćŻä»„éèżæŽæ°ăćçæć珊äžČæ„玹ćŒćź), ćšèżç§æ
ć”äž, äžșNoneç㱿§äŒèą«ćżœç„.
-
-
-
-### äżćæšĄć
-
-
-
-ćœäœ çæšĄććŸźè°ćźæ, äœ ć°±ćŻä»„äœżçš[`PreTrainedModel.save_pretrained`]æćźććźçćèŻćšäżćäžæ„:
-
-```py
->>> pt_save_directory = "./pt_save_pretrained"
->>> tokenizer.save_pretrained(pt_save_directory) # doctest: +IGNORE_RESULT
->>> pt_model.save_pretrained(pt_save_directory)
-```
-
-ćœäœ ćć€ćæŹĄäœżçšèżäžȘæšĄćæ¶, ć°±ćŻä»„äœżçš[`PreTrainedModel.from_pretrained`]ć 蜜ćźäș:
-
-```py
->>> pt_model = AutoModelForSequenceClassification.from_pretrained("./pt_save_pretrained")
-```
-
-
-ćœäœ çæšĄććŸźè°ćźæ, äœ ć°±ćŻä»„äœżçš[`TFPreTrainedModel.save_pretrained`]æćźććźçćèŻćšäżćäžæ„:
-
-```py
->>> tf_save_directory = "./tf_save_pretrained"
->>> tokenizer.save_pretrained(tf_save_directory) # doctest: +IGNORE_RESULT
->>> tf_model.save_pretrained(tf_save_directory)
-```
-
-ćœäœ ćć€ćæŹĄäœżçšèżäžȘæšĄćæ¶, ć°±ćŻä»„äœżçš[`TFPreTrainedModel.from_pretrained`]ć 蜜ćźäș:
-
-```py
->>> tf_model = TFAutoModelForSequenceClassification.from_pretrained("./tf_save_pretrained")
-```
-
-
-
-đ€ TransformersæäžäžȘçčć«é
·çćèœ, ćźèœć€äżćäžäžȘæšĄć, ćč¶äžć°ćźć 蜜äžșPyTorchæTensorFlowæšĄć. `from_pt`æ`from_tf`ćæ°ćŻä»„ć°æšĄćä»äžäžȘæĄæ¶èœŹæąäžșćŠäžäžȘæĄæ¶:
-
-
-
-```py
->>> from transformers import AutoModel
-
->>> tokenizer = AutoTokenizer.from_pretrained(tf_save_directory)
->>> pt_model = AutoModelForSequenceClassification.from_pretrained(tf_save_directory, from_tf=True)
-```
-
-
-```py
->>> from transformers import TFAutoModel
-
->>> tokenizer = AutoTokenizer.from_pretrained(pt_save_directory)
->>> tf_model = TFAutoModelForSequenceClassification.from_pretrained(pt_save_directory, from_pt=True)
-```
-
-
-
-## èȘćźäčæšĄćæć»ș
-
-äœ ćŻä»„äżźæčæšĄćçé
çœźç±»æ„æčćæšĄćçæć»șæčćŒ. é
çœźææäșæšĄćç㱿§, æŻćŠéè㱿è
æłšæćć€Žçæ°é. ćœäœ ä»èȘćźäčçé
çœźç±»ćć§ćæšĄćæ¶, äœ ć°±ćŒć§èȘćźäčæšĄćæć»șäș. æšĄć㱿§æŻéæșćć§ćç, äœ éèŠć
èźç»æšĄć, ç¶ćæèœćŸć°ææäčçç»æ.
-
-éèżćŻŒć
„[`AutoConfig`]æ„ćŒć§, äčćć èœœäœ æłäżźæčçéąèźç»æšĄć. ćš[`AutoConfig.from_pretrained`]äž, äœ èœć€æćźæłèŠäżźæčç㱿§, æŻćŠæłšæćć€Žçæ°é:
-
-```py
->>> from transformers import AutoConfig
-
->>> my_config = AutoConfig.from_pretrained("distilbert-base-uncased", n_heads=12)
-```
-
-
-
-äœżçš[`AutoModel.from_config`]æ čæźäœ çèȘćźäčé
çœźćć»șäžäžȘæšĄć:
-
-```py
->>> from transformers import AutoModel
-
->>> my_model = AutoModel.from_config(my_config)
-```
-
-
-äœżçš[`TFAutoModel.from_config`]æ čæźäœ çèȘćźäčé
çœźćć»șäžäžȘæšĄć:
-
-```py
->>> from transformers import TFAutoModel
-
->>> my_model = TFAutoModel.from_config(my_config)
-```
-
-
-
-æ„é
[ćć»șäžäžȘèȘćźäčç»æ](./create_a_model)æćè·ćæŽć€ć
łäșæć»șèȘćźäčé
çœźç俥æŻ.
-
-## Trainer - PyTorchäŒćèźç»ćŸȘçŻ
-
-ææçæšĄćéœæŻæ ćç[`torch.nn.Module`](https://pytorch.org/docs/stable/nn.html#torch.nn.Module), æä»„äœ ćŻä»„ćšä»»äœć
žćçèźç»æšĄćäžäœżçšćźä»Ź. ćœäœ çŒćèȘć·±çèźç»ćŸȘçŻæ¶W, đ€ TransformersäžșPyTorchæäŸäșäžäžȘ[`Trainer`]ç±», ćźć
ć«äșćșçĄçèźç»ćŸȘçŻćč¶äžäžșèŻžćŠććžćŒèźç», æ··ćçČŸćșŠççčæ§ćąć äșéąć€çćèœ.
-
-ććłäșäœ çä»»ćĄ, äœ éćžžćŻä»„äŒ é仄äžçćæ°ç»[`Trainer`]:
-
-1. [`PreTrainedModel`]æè
[`torch.nn.Module`](https://pytorch.org/docs/stable/nn.html#torch.nn.Module):
-
- ```py
- >>> from transformers import AutoModelForSequenceClassification
-
- >>> model = AutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased")
- ```
-
-2. [`TrainingArguments`]ć«æäœ ćŻä»„äżźæčçæšĄćè¶
ćæ°, æŻćŠćŠäč ç, æčæŹĄć€§ć°ćèźç»æ¶çèżä»ŁæŹĄæ°. ćŠæäœ æČĄææćźèźç»ćæ°, éŁäčćźäŒäœżçšé»èź€ćŒ:
-
- ```py
- >>> from transformers import TrainingArguments
-
- >>> training_args = TrainingArguments(
- ... output_dir="path/to/save/folder/",
- ... learning_rate=2e-5,
- ... per_device_train_batch_size=8,
- ... per_device_eval_batch_size=8,
- ... num_train_epochs=2,
- ... )
- ```
-
-3. äžäžȘéąć€çç±», æŻćŠćèŻćš, çčćŸæććšæè
ć€çćš:
-
- ```py
- >>> from transformers import AutoTokenizer
-
- >>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
- ```
-
-4. ć 蜜äžäžȘæ°æźé:
-
- ```py
- >>> from datasets import load_dataset
-
- >>> dataset = load_dataset("rotten_tomatoes") # doctest: +IGNORE_RESULT
- ```
-
-5. ćć»șäžäžȘç»æ°æźéćèŻçćœæ°, ćč¶äžäœżçš[`~datasets.Dataset.map`]ćșçšć°æŽäžȘæ°æźé:
-
- ```py
- >>> def tokenize_dataset(dataset):
- ... return tokenizer(dataset["text"])
-
-
- >>> dataset = dataset.map(tokenize_dataset, batched=True)
- ```
-
-6. çšæ„仿°æźéäžćć»șæčæŹĄç[`DataCollatorWithPadding`]:
-
- ```py
- >>> from transformers import DataCollatorWithPadding
-
- >>> data_collator = DataCollatorWithPadding(tokenizer=tokenizer)
- ```
-
-ç°ćšæææçç±»äŒ ç»[`Trainer`]:
-
-```py
->>> from transformers import Trainer
-
->>> trainer = Trainer(
-... model=model,
-... args=training_args,
-... train_dataset=dataset["train"],
-... eval_dataset=dataset["test"],
-... tokenizer=tokenizer,
-... data_collator=data_collator,
-... ) # doctest: +SKIP
-```
-
-äžććć€ć°±ç»Șć, è°çš[`~Trainer.train`]èżèĄèźç»:
-
-```py
->>> trainer.train() # doctest: +SKIP
-```
-
-
-
-ćŻčäșćçż»èŻææèŠèżäșäœżçšćșćć°ćșćæšĄćçä»»ćĄ, çš[`Seq2SeqTrainer`]ć[`Seq2SeqTrainingArguments`]æ„æżä»Ł.
-
-
-
-äœ ćŻä»„éèżćç±»ć[`Trainer`]äžçæčæłæ„èȘćźäčèźç»ćŸȘçŻ. èżæ ·äœ ć°±ćŻä»„èȘćźäčćæć€±ćœæ°, äŒććšćè°ćșŠćšèżæ ·ççčæ§. æ„é
[`Trainer`]ćèæćäșè§ŁćȘäșæčæłèœć€èą«ćç±»ć.
-
-ćŠäžäžȘèȘćźäčèźç»ćŸȘçŻçæčćŒæŻéèż[ćè°](./main_classes/callbacks). äœ ćŻä»„äœżçšćè°æ„äžć
¶ä»ćșéæ, æ„çèźç»ćŸȘçŻæ„æ„ćèżćșŠææćç»æèźç». ćè°äžäŒäżźæčèźç»ćŸȘçŻ. ćŠææłèȘćźäčæć€±ćœæ°ç, ć°±éèŠćç±»ć[`Trainer`]äș.
-
-## äœżçšTensorflowèźç»
-
-æææšĄćéœæŻæ ćç[`tf.keras.Model`](https://www.tensorflow.org/api_docs/python/tf/keras/Model), æä»„äœ ćŻä»„éèż[Keras](https://keras.io/) APIćźç°ćšTensorflowäžèźç». đ€ TransformersæäŸäș[`~TFPreTrainedModel.prepare_tf_dataset`]æčæłæ„蜻æŸć°ć°æ°æźéć 蜜äžș`tf.data.Dataset`, èżæ ·äœ ć°±ćŻä»„äœżçšKerasç[`compile`](https://keras.io/api/models/model_training_apis/#compile-method)ć[`fit`](https://keras.io/api/models/model_training_apis/#fit-method)æčæłé©ŹäžćŒć§èźç».
-
-1. äœżçš[`TFPreTrainedModel`]æè
[`tf.keras.Model`](https://www.tensorflow.org/api_docs/python/tf/keras/Model)æ„ćŒć§:
-
- ```py
- >>> from transformers import TFAutoModelForSequenceClassification
-
- >>> model = TFAutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased")
- ```
-
-2. äžäžȘéąć€çç±», æŻćŠćèŻćš, çčćŸæććšæè
ć€çćš:
-
- ```py
- >>> from transformers import AutoTokenizer
-
- >>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
- ```
-
-3. ćć»șäžäžȘç»æ°æźéćèŻçćœæ°
-
- ```py
- >>> def tokenize_dataset(dataset):
- ... return tokenizer(dataset["text"]) # doctest: +SKIP
- ```
-
-4. äœżçš[`~datasets.Dataset.map`]ć°ćèŻćšćșçšć°æŽäžȘæ°æźé, äčćć°æ°æźéććèŻćšäŒ ç»[`~TFPreTrainedModel.prepare_tf_dataset`]. ćŠæäœ éèŠçèŻ, äčćŻä»„ćšèżéæčćæčæŹĄć€§ć°ćæŻćŠæä豿°æźé:
-
- ```py
- >>> dataset = dataset.map(tokenize_dataset) # doctest: +SKIP
- >>> tf_dataset = model.prepare_tf_dataset(
- ... dataset, batch_size=16, shuffle=True, tokenizer=tokenizer
- ... ) # doctest: +SKIP
- ```
-
-5. äžććć€ć°±ç»Șć, è°çš`compile`ć`fit`ćŒć§èźç»:
-
- ```py
- >>> from tensorflow.keras.optimizers import Adam
-
- >>> model.compile(optimizer=Adam(3e-5))
- >>> model.fit(dataset) # doctest: +SKIP
- ```
-
-## æ„äžæ„ćä»äč?
-
-ç°ćšäœ ć·Čç»ćźæäș đ€ Transformers çćż«éäžææçš, æ„ççæä»Źçæććč¶äžćŠäč ćŠäœćäžäșæŽć
·äœçäșæ
, æŻćŠćäžäžȘèȘćźäčæšĄć, äžșæäžȘä»»ćĄćŸźè°äžäžȘæšĄć仄ććŠäœäœżçšèæŹæ„èźç»æšĄć. ćŠæäœ æć
Žè¶Łäșè§ŁæŽć€ đ€ Transformers çæ žćżç« è, éŁć°±ćæŻććĄç¶ćæ„ççæä»ŹçæŠćż”æćć§!
diff --git a/examples/README.md b/examples/README.md
index c1cddd2e4734..f01a0f0d43d1 100644
--- a/examples/README.md
+++ b/examples/README.md
@@ -104,7 +104,7 @@ for running remotely as well. You can easily customize the example used, command
and type of compute hardware, and then run the script to automatically launch the example.
You can refer to
-[hardware setup](https://runhouse-docs.readthedocs-hosted.com/en/main/rh_primitives/cluster.html#hardware-setup)
+[hardware setup](https://runhouse-docs.readthedocs-hosted.com/en/latest/api/python/cluster.html#hardware-setup)
for more information about hardware and dependency setup with Runhouse, or this
[Colab tutorial](https://colab.research.google.com/drive/1sh_aNQzJX5BKAdNeXthTNGxKz7sM9VPc) for a more in-depth
walkthrough.
@@ -131,4 +131,4 @@ python run_on_remote.py --instance --provider \
--example
```
-You can also adapt the script to your own needs.
\ No newline at end of file
+You can also adapt the script to your own needs.
diff --git a/examples/flax/image-captioning/run_image_captioning_flax.py b/examples/flax/image-captioning/run_image_captioning_flax.py
index ef9c515da450..bbc79977a467 100644
--- a/examples/flax/image-captioning/run_image_captioning_flax.py
+++ b/examples/flax/image-captioning/run_image_captioning_flax.py
@@ -22,6 +22,7 @@
import os
import sys
import time
+import warnings
from dataclasses import asdict, dataclass, field
from enum import Enum
from functools import partial
@@ -53,7 +54,7 @@
HfArgumentParser,
is_tensorboard_available,
)
-from transformers.utils import get_full_repo_name, is_offline_mode, send_example_telemetry
+from transformers.utils import is_offline_mode, send_example_telemetry
logger = logging.getLogger(__name__)
@@ -182,12 +183,28 @@ class ModelArguments:
)
},
)
+ token: str = field(
+ default=None,
+ metadata={
+ "help": (
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
+ )
+ },
+ )
use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
+ trust_remote_code: bool = field(
default=False,
metadata={
"help": (
- "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
- "with private models)."
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
)
},
)
@@ -389,6 +406,12 @@ def main():
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_image_captioning", model_args, data_args, framework="flax")
@@ -424,14 +447,14 @@ def main():
# Handle the repository creation
if training_args.push_to_hub:
- if training_args.hub_model_id is None:
- repo_name = get_full_repo_name(
- Path(training_args.output_dir).absolute().name, token=training_args.hub_token
- )
- else:
- repo_name = training_args.hub_model_id
- create_repo(repo_name, exist_ok=True, token=training_args.hub_token)
- repo = Repository(training_args.output_dir, clone_from=repo_name, token=training_args.hub_token)
+ # Retrieve of infer repo_name
+ repo_name = training_args.hub_model_id
+ if repo_name is None:
+ repo_name = Path(training_args.output_dir).absolute().name
+ # Create repo and retrieve repo_id
+ repo_id = create_repo(repo_name, exist_ok=True, token=training_args.hub_token).repo_id
+ # Clone repo locally
+ repo = Repository(training_args.output_dir, clone_from=repo_id, token=training_args.hub_token)
# Get the datasets: you can either provide your own CSV/JSON training and evaluation files (see below)
# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
@@ -448,7 +471,7 @@ def main():
cache_dir=model_args.cache_dir,
keep_in_memory=False,
data_dir=data_args.data_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
else:
data_files = {}
@@ -465,7 +488,7 @@ def main():
extension,
data_files=data_files,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
# https://huggingface.co/docs/datasets/loading_datasets.html.
@@ -475,18 +498,21 @@ def main():
model_args.model_name_or_path,
seed=training_args.seed,
dtype=getattr(jnp, model_args.dtype),
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
image_processor = AutoImageProcessor.from_pretrained(
model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
tokenizer = AutoTokenizer.from_pretrained(
model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
use_fast=model_args.use_fast_tokenizer,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
tokenizer.pad_token = tokenizer.convert_ids_to_tokens(model.config.pad_token_id)
diff --git a/examples/flax/language-modeling/run_bart_dlm_flax.py b/examples/flax/language-modeling/run_bart_dlm_flax.py
index 4cb862bb37b9..259f67f0b17d 100644
--- a/examples/flax/language-modeling/run_bart_dlm_flax.py
+++ b/examples/flax/language-modeling/run_bart_dlm_flax.py
@@ -26,6 +26,7 @@
import os
import sys
import time
+import warnings
from dataclasses import asdict, dataclass, field
from enum import Enum
from itertools import chain
@@ -59,7 +60,7 @@
set_seed,
)
from transformers.models.bart.modeling_flax_bart import shift_tokens_right
-from transformers.utils import get_full_repo_name, send_example_telemetry
+from transformers.utils import send_example_telemetry
MODEL_CONFIG_CLASSES = list(FLAX_MODEL_FOR_MASKED_LM_MAPPING.keys())
@@ -168,15 +169,21 @@ class ModelArguments:
)
},
)
- use_auth_token: bool = field(
- default=False,
+ token: str = field(
+ default=None,
metadata={
"help": (
- "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
- "with private models)."
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
)
},
)
+ use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
@dataclass
@@ -242,10 +249,12 @@ def __post_init__(self):
else:
if self.train_file is not None:
extension = self.train_file.split(".")[-1]
- assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file."
+ if extension not in ["csv", "json", "txt"]:
+ raise ValueError("train_file` should be a csv, json or text file.")
if self.validation_file is not None:
extension = self.validation_file.split(".")[-1]
- assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file."
+ if extension not in ["csv", "json", "txt"]:
+ raise ValueError("`validation_file` should be a csv, json or text file.")
@flax.struct.dataclass
@@ -461,6 +470,12 @@ def main():
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_bart_dlm", model_args, data_args, framework="flax")
@@ -494,14 +509,14 @@ def main():
# Handle the repository creation
if training_args.push_to_hub:
- if training_args.hub_model_id is None:
- repo_name = get_full_repo_name(
- Path(training_args.output_dir).absolute().name, token=training_args.hub_token
- )
- else:
- repo_name = training_args.hub_model_id
- create_repo(repo_name, exist_ok=True, token=training_args.hub_token)
- repo = Repository(training_args.output_dir, clone_from=repo_name, token=training_args.hub_token)
+ # Retrieve of infer repo_name
+ repo_name = training_args.hub_model_id
+ if repo_name is None:
+ repo_name = Path(training_args.output_dir).absolute().name
+ # Create repo and retrieve repo_id
+ repo_id = create_repo(repo_name, exist_ok=True, token=training_args.hub_token).repo_id
+ # Clone repo locally
+ repo = Repository(training_args.output_dir, clone_from=repo_id, token=training_args.hub_token)
# Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
@@ -515,7 +530,7 @@ def main():
data_args.dataset_name,
data_args.dataset_config_name,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
if "validation" not in datasets.keys():
@@ -524,14 +539,14 @@ def main():
data_args.dataset_config_name,
split=f"train[:{data_args.validation_split_percentage}%]",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
datasets["train"] = load_dataset(
data_args.dataset_name,
data_args.dataset_config_name,
split=f"train[{data_args.validation_split_percentage}%:]",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
else:
data_files = {}
@@ -546,7 +561,7 @@ def main():
extension,
data_files=data_files,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
if "validation" not in datasets.keys():
@@ -555,14 +570,14 @@ def main():
data_files=data_files,
split=f"train[:{data_args.validation_split_percentage}%]",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
datasets["train"] = load_dataset(
extension,
data_files=data_files,
split=f"train[{data_args.validation_split_percentage}%:]",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
# https://huggingface.co/docs/datasets/loading_datasets.html.
@@ -574,14 +589,14 @@ def main():
model_args.tokenizer_name,
cache_dir=model_args.cache_dir,
use_fast=model_args.use_fast_tokenizer,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
elif model_args.model_name_or_path:
tokenizer = AutoTokenizer.from_pretrained(
model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
use_fast=model_args.use_fast_tokenizer,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
else:
raise ValueError(
@@ -594,13 +609,13 @@ def main():
model_args.config_name,
cache_dir=model_args.cache_dir,
vocab_size=len(tokenizer),
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
elif model_args.model_name_or_path:
config = BartConfig.from_pretrained(
model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
else:
config = CONFIG_MAPPING[model_args.model_type]()
@@ -705,7 +720,7 @@ def group_texts(examples):
config=config,
seed=training_args.seed,
dtype=getattr(jnp, model_args.dtype),
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
else:
config.vocab_size = len(tokenizer)
diff --git a/examples/flax/language-modeling/run_clm_flax.py b/examples/flax/language-modeling/run_clm_flax.py
index 952419dc9656..1a296a4fa992 100755
--- a/examples/flax/language-modeling/run_clm_flax.py
+++ b/examples/flax/language-modeling/run_clm_flax.py
@@ -27,6 +27,7 @@
import os
import sys
import time
+import warnings
from dataclasses import asdict, dataclass, field
from enum import Enum
from itertools import chain
@@ -58,7 +59,7 @@
set_seed,
)
from transformers.testing_utils import CaptureLogger
-from transformers.utils import get_full_repo_name, send_example_telemetry
+from transformers.utils import send_example_telemetry
logger = logging.getLogger(__name__)
@@ -169,12 +170,28 @@ class ModelArguments:
)
},
)
+ token: str = field(
+ default=None,
+ metadata={
+ "help": (
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
+ )
+ },
+ )
use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
+ trust_remote_code: bool = field(
default=False,
metadata={
"help": (
- "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
- "with private models)."
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
)
},
)
@@ -251,10 +268,12 @@ def __post_init__(self):
else:
if self.train_file is not None:
extension = self.train_file.split(".")[-1]
- assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file."
+ if extension not in ["csv", "json", "txt"]:
+ raise ValueError("train_file` should be a csv, json or text file.")
if self.validation_file is not None:
extension = self.validation_file.split(".")[-1]
- assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file."
+ if extension not in ["csv", "json", "txt"]:
+ raise ValueError("`validation_file` should be a csv, json or text file.")
class TrainState(train_state.TrainState):
@@ -332,6 +351,12 @@ def main():
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_clm", model_args, data_args, framework="flax")
@@ -370,14 +395,14 @@ def main():
# Handle the repository creation
if training_args.push_to_hub:
- if training_args.hub_model_id is None:
- repo_name = get_full_repo_name(
- Path(training_args.output_dir).absolute().name, token=training_args.hub_token
- )
- else:
- repo_name = training_args.hub_model_id
- create_repo(repo_name, exist_ok=True, token=training_args.hub_token)
- repo = Repository(training_args.output_dir, clone_from=repo_name, token=training_args.hub_token)
+ # Retrieve of infer repo_name
+ repo_name = training_args.hub_model_id
+ if repo_name is None:
+ repo_name = Path(training_args.output_dir).absolute().name
+ # Create repo and retrieve repo_id
+ repo_id = create_repo(repo_name, exist_ok=True, token=training_args.hub_token).repo_id
+ # Clone repo locally
+ repo = Repository(training_args.output_dir, clone_from=repo_id, token=training_args.hub_token)
# Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
@@ -395,7 +420,7 @@ def main():
data_args.dataset_config_name,
cache_dir=model_args.cache_dir,
keep_in_memory=False,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
if "validation" not in dataset.keys():
@@ -404,14 +429,14 @@ def main():
data_args.dataset_config_name,
split=f"train[:{data_args.validation_split_percentage}%]",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
dataset["train"] = load_dataset(
data_args.dataset_name,
data_args.dataset_config_name,
split=f"train[{data_args.validation_split_percentage}%:]",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
else:
data_files = {}
@@ -429,7 +454,7 @@ def main():
data_files=data_files,
cache_dir=model_args.cache_dir,
**dataset_args,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
if "validation" not in dataset.keys():
@@ -439,7 +464,7 @@ def main():
split=f"train[:{data_args.validation_split_percentage}%]",
cache_dir=model_args.cache_dir,
**dataset_args,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
dataset["train"] = load_dataset(
extension,
@@ -447,7 +472,7 @@ def main():
split=f"train[{data_args.validation_split_percentage}%:]",
cache_dir=model_args.cache_dir,
**dataset_args,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
# https://huggingface.co/docs/datasets/loading_datasets.html.
@@ -461,13 +486,15 @@ def main():
config = AutoConfig.from_pretrained(
model_args.config_name,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
elif model_args.model_name_or_path:
config = AutoConfig.from_pretrained(
model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
else:
config = CONFIG_MAPPING[model_args.model_type]()
@@ -478,14 +505,16 @@ def main():
model_args.tokenizer_name,
cache_dir=model_args.cache_dir,
use_fast=model_args.use_fast_tokenizer,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
elif model_args.model_name_or_path:
tokenizer = AutoTokenizer.from_pretrained(
model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
use_fast=model_args.use_fast_tokenizer,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
else:
raise ValueError(
@@ -499,13 +528,15 @@ def main():
config=config,
seed=training_args.seed,
dtype=getattr(jnp, model_args.dtype),
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
else:
model = FlaxAutoModelForCausalLM.from_config(
config,
seed=training_args.seed,
dtype=getattr(jnp, model_args.dtype),
+ trust_remote_code=model_args.trust_remote_code,
)
# Preprocessing the datasets.
diff --git a/examples/flax/language-modeling/run_mlm_flax.py b/examples/flax/language-modeling/run_mlm_flax.py
index ae289b84708f..0c49a2cff7b0 100755
--- a/examples/flax/language-modeling/run_mlm_flax.py
+++ b/examples/flax/language-modeling/run_mlm_flax.py
@@ -26,6 +26,7 @@
import os
import sys
import time
+import warnings
from dataclasses import asdict, dataclass, field
from enum import Enum
from itertools import chain
@@ -59,7 +60,7 @@
is_tensorboard_available,
set_seed,
)
-from transformers.utils import get_full_repo_name, send_example_telemetry
+from transformers.utils import send_example_telemetry
MODEL_CONFIG_CLASSES = list(FLAX_MODEL_FOR_MASKED_LM_MAPPING.keys())
@@ -174,12 +175,28 @@ class ModelArguments:
)
},
)
+ token: str = field(
+ default=None,
+ metadata={
+ "help": (
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
+ )
+ },
+ )
use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
+ trust_remote_code: bool = field(
default=False,
metadata={
"help": (
- "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
- "with private models)."
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
)
},
)
@@ -377,6 +394,12 @@ def main():
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_mlm", model_args, data_args, framework="flax")
@@ -410,14 +433,14 @@ def main():
# Handle the repository creation
if training_args.push_to_hub:
- if training_args.hub_model_id is None:
- repo_name = get_full_repo_name(
- Path(training_args.output_dir).absolute().name, token=training_args.hub_token
- )
- else:
- repo_name = training_args.hub_model_id
- create_repo(repo_name, exist_ok=True, token=training_args.hub_token)
- repo = Repository(training_args.output_dir, clone_from=repo_name, token=training_args.hub_token)
+ # Retrieve of infer repo_name
+ repo_name = training_args.hub_model_id
+ if repo_name is None:
+ repo_name = Path(training_args.output_dir).absolute().name
+ # Create repo and retrieve repo_id
+ repo_id = create_repo(repo_name, exist_ok=True, token=training_args.hub_token).repo_id
+ # Clone repo locally
+ repo = Repository(training_args.output_dir, clone_from=repo_id, token=training_args.hub_token)
# Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
@@ -434,7 +457,7 @@ def main():
data_args.dataset_name,
data_args.dataset_config_name,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
if "validation" not in datasets.keys():
@@ -443,14 +466,14 @@ def main():
data_args.dataset_config_name,
split=f"train[:{data_args.validation_split_percentage}%]",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
datasets["train"] = load_dataset(
data_args.dataset_name,
data_args.dataset_config_name,
split=f"train[{data_args.validation_split_percentage}%:]",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
else:
data_files = {}
@@ -465,7 +488,7 @@ def main():
extension,
data_files=data_files,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
if "validation" not in datasets.keys():
@@ -474,14 +497,14 @@ def main():
data_files=data_files,
split=f"train[:{data_args.validation_split_percentage}%]",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
datasets["train"] = load_dataset(
extension,
data_files=data_files,
split=f"train[{data_args.validation_split_percentage}%:]",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
# https://huggingface.co/docs/datasets/loading_datasets.html.
@@ -495,13 +518,15 @@ def main():
config = AutoConfig.from_pretrained(
model_args.config_name,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
elif model_args.model_name_or_path:
config = AutoConfig.from_pretrained(
model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
else:
config = CONFIG_MAPPING[model_args.model_type]()
@@ -512,14 +537,16 @@ def main():
model_args.tokenizer_name,
cache_dir=model_args.cache_dir,
use_fast=model_args.use_fast_tokenizer,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
elif model_args.model_name_or_path:
tokenizer = AutoTokenizer.from_pretrained(
model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
use_fast=model_args.use_fast_tokenizer,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
else:
raise ValueError(
@@ -638,13 +665,15 @@ def group_texts(examples):
config=config,
seed=training_args.seed,
dtype=getattr(jnp, model_args.dtype),
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
else:
model = FlaxAutoModelForMaskedLM.from_config(
config,
seed=training_args.seed,
dtype=getattr(jnp, model_args.dtype),
+ trust_remote_code=model_args.trust_remote_code,
)
if training_args.gradient_checkpointing:
diff --git a/examples/flax/language-modeling/run_t5_mlm_flax.py b/examples/flax/language-modeling/run_t5_mlm_flax.py
index 152760f4bf4b..c3afc58207b4 100755
--- a/examples/flax/language-modeling/run_t5_mlm_flax.py
+++ b/examples/flax/language-modeling/run_t5_mlm_flax.py
@@ -25,6 +25,7 @@
import os
import sys
import time
+import warnings
from dataclasses import asdict, dataclass, field
# You can also adapt this script on your own masked language modeling task. Pointers for this are left as comments.
@@ -59,7 +60,7 @@
set_seed,
)
from transformers.models.t5.modeling_flax_t5 import shift_tokens_right
-from transformers.utils import get_full_repo_name, send_example_telemetry
+from transformers.utils import send_example_telemetry
MODEL_CONFIG_CLASSES = list(FLAX_MODEL_FOR_MASKED_LM_MAPPING.keys())
@@ -168,15 +169,21 @@ class ModelArguments:
)
},
)
- use_auth_token: bool = field(
- default=False,
+ token: str = field(
+ default=None,
metadata={
"help": (
- "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
- "with private models)."
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
)
},
)
+ use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
@dataclass
@@ -418,13 +425,14 @@ def random_spans_noise_mask(self, length):
orig_length = length
num_noise_tokens = int(np.round(length * self.noise_density))
+ num_nonnoise_tokens = length - num_noise_tokens
# avoid degeneracy by ensuring positive numbers of noise and nonnoise tokens.
num_noise_tokens = min(max(num_noise_tokens, 1), length - 1)
- num_noise_spans = int(np.round(num_noise_tokens / self.mean_noise_span_length))
+ # num_noise_tokens should be less than num_noise_tokens and num_nonnoise_tokens
+ num_noise_spans = int(np.round(min(num_noise_tokens, num_nonnoise_tokens) / self.mean_noise_span_length))
# avoid degeneracy by ensuring positive number of noise spans
num_noise_spans = max(num_noise_spans, 1)
- num_nonnoise_tokens = length - num_noise_tokens
# pick the lengths of the noise spans and the non-noise spans
def _random_segmentation(num_items, num_segments):
@@ -503,6 +511,12 @@ def main():
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_t5_mlm", model_args, data_args, framework="flax")
@@ -536,14 +550,14 @@ def main():
# Handle the repository creation
if training_args.push_to_hub:
- if training_args.hub_model_id is None:
- repo_name = get_full_repo_name(
- Path(training_args.output_dir).absolute().name, token=training_args.hub_token
- )
- else:
- repo_name = training_args.hub_model_id
- create_repo(repo_name, exist_ok=True, token=training_args.hub_token)
- repo = Repository(training_args.output_dir, clone_from=repo_name, token=training_args.hub_token)
+ # Retrieve of infer repo_name
+ repo_name = training_args.hub_model_id
+ if repo_name is None:
+ repo_name = Path(training_args.output_dir).absolute().name
+ # Create repo and retrieve repo_id
+ repo_id = create_repo(repo_name, exist_ok=True, token=training_args.hub_token).repo_id
+ # Clone repo locally
+ repo = Repository(training_args.output_dir, clone_from=repo_id, token=training_args.hub_token)
# Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
@@ -557,7 +571,7 @@ def main():
data_args.dataset_name,
data_args.dataset_config_name,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
if "validation" not in datasets.keys():
@@ -566,14 +580,14 @@ def main():
data_args.dataset_config_name,
split=f"train[:{data_args.validation_split_percentage}%]",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
datasets["train"] = load_dataset(
data_args.dataset_name,
data_args.dataset_config_name,
split=f"train[{data_args.validation_split_percentage}%:]",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
else:
data_files = {}
@@ -588,7 +602,7 @@ def main():
extension,
data_files=data_files,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
if "validation" not in datasets.keys():
@@ -597,14 +611,14 @@ def main():
data_files=data_files,
split=f"train[:{data_args.validation_split_percentage}%]",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
datasets["train"] = load_dataset(
extension,
data_files=data_files,
split=f"train[{data_args.validation_split_percentage}%:]",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
# https://huggingface.co/docs/datasets/loading_datasets.html.
@@ -616,14 +630,14 @@ def main():
model_args.tokenizer_name,
cache_dir=model_args.cache_dir,
use_fast=model_args.use_fast_tokenizer,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
elif model_args.model_name_or_path:
tokenizer = AutoTokenizer.from_pretrained(
model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
use_fast=model_args.use_fast_tokenizer,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
else:
raise ValueError(
@@ -636,13 +650,13 @@ def main():
model_args.config_name,
cache_dir=model_args.cache_dir,
vocab_size=len(tokenizer),
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
elif model_args.model_name_or_path:
config = T5Config.from_pretrained(
model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
else:
config = CONFIG_MAPPING[model_args.model_type]()
@@ -737,7 +751,7 @@ def group_texts(examples):
config=config,
seed=training_args.seed,
dtype=getattr(jnp, model_args.dtype),
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
else:
config.vocab_size = len(tokenizer)
diff --git a/examples/flax/question-answering/run_qa.py b/examples/flax/question-answering/run_qa.py
index 5a9f5eb16e0f..77bd37bab879 100644
--- a/examples/flax/question-answering/run_qa.py
+++ b/examples/flax/question-answering/run_qa.py
@@ -25,6 +25,7 @@
import random
import sys
import time
+import warnings
from dataclasses import asdict, dataclass, field
from enum import Enum
from pathlib import Path
@@ -55,13 +56,13 @@
PreTrainedTokenizerFast,
is_tensorboard_available,
)
-from transformers.utils import check_min_version, get_full_repo_name, send_example_telemetry
+from transformers.utils import check_min_version, send_example_telemetry
logger = logging.getLogger(__name__)
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
-check_min_version("4.29.0.dev0")
+check_min_version("4.32.0.dev0")
Array = Any
Dataset = datasets.arrow_dataset.Dataset
@@ -155,12 +156,28 @@ class ModelArguments:
default="main",
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
)
+ token: str = field(
+ default=None,
+ metadata={
+ "help": (
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
+ )
+ },
+ )
use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
+ trust_remote_code: bool = field(
default=False,
metadata={
"help": (
- "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
- "with private models)."
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
)
},
)
@@ -438,6 +455,12 @@ def main():
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_qa", model_args, data_args, framework="flax")
@@ -462,14 +485,14 @@ def main():
# Handle the repository creation
if training_args.push_to_hub:
- if training_args.hub_model_id is None:
- repo_name = get_full_repo_name(
- Path(training_args.output_dir).absolute().name, token=training_args.hub_token
- )
- else:
- repo_name = training_args.hub_model_id
- create_repo(repo_name, exist_ok=True, token=training_args.hub_token)
- repo = Repository(training_args.output_dir, clone_from=repo_name, token=training_args.hub_token)
+ # Retrieve of infer repo_name
+ repo_name = training_args.hub_model_id
+ if repo_name is None:
+ repo_name = Path(training_args.output_dir).absolute().name
+ # Create repo and retrieve repo_id
+ repo_id = create_repo(repo_name, exist_ok=True, token=training_args.hub_token).repo_id
+ # Clone repo locally
+ repo = Repository(training_args.output_dir, clone_from=repo_id, token=training_args.hub_token)
# region Load Data
# Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
@@ -487,7 +510,7 @@ def main():
data_args.dataset_name,
data_args.dataset_config_name,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
else:
# Loading the dataset from local csv or json file.
@@ -507,7 +530,7 @@ def main():
data_files=data_files,
field="data",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
# https://huggingface.co/docs/datasets/loading_datasets.html.
@@ -520,14 +543,16 @@ def main():
model_args.config_name if model_args.config_name else model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
tokenizer = AutoTokenizer.from_pretrained(
model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
use_fast=True,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
# endregion
@@ -874,7 +899,8 @@ def write_eval_metric(summary_writer, eval_metrics, step):
config=config,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
seed=training_args.seed,
dtype=getattr(jnp, model_args.dtype),
)
diff --git a/examples/flax/summarization/run_summarization_flax.py b/examples/flax/summarization/run_summarization_flax.py
index 2d7e0acbf584..fc1595ac7ea9 100644
--- a/examples/flax/summarization/run_summarization_flax.py
+++ b/examples/flax/summarization/run_summarization_flax.py
@@ -24,6 +24,7 @@
import os
import sys
import time
+import warnings
from dataclasses import asdict, dataclass, field
from enum import Enum
from functools import partial
@@ -56,7 +57,7 @@
HfArgumentParser,
is_tensorboard_available,
)
-from transformers.utils import get_full_repo_name, is_offline_mode, send_example_telemetry
+from transformers.utils import is_offline_mode, send_example_telemetry
logger = logging.getLogger(__name__)
@@ -188,12 +189,28 @@ class ModelArguments:
)
},
)
+ token: str = field(
+ default=None,
+ metadata={
+ "help": (
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
+ )
+ },
+ )
use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
+ trust_remote_code: bool = field(
default=False,
metadata={
"help": (
- "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
- "with private models)."
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
)
},
)
@@ -417,6 +434,12 @@ def main():
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_summarization", model_args, data_args, framework="flax")
@@ -452,14 +475,14 @@ def main():
# Handle the repository creation
if training_args.push_to_hub:
- if training_args.hub_model_id is None:
- repo_name = get_full_repo_name(
- Path(training_args.output_dir).absolute().name, token=training_args.hub_token
- )
- else:
- repo_name = training_args.hub_model_id
- create_repo(repo_name, exist_ok=True, token=training_args.hub_token)
- repo = Repository(training_args.output_dir, clone_from=repo_name, token=training_args.hub_token)
+ # Retrieve of infer repo_name
+ repo_name = training_args.hub_model_id
+ if repo_name is None:
+ repo_name = Path(training_args.output_dir).absolute().name
+ # Create repo and retrieve repo_id
+ repo_id = create_repo(repo_name, exist_ok=True, token=training_args.hub_token).repo_id
+ # Clone repo locally
+ repo = Repository(training_args.output_dir, clone_from=repo_id, token=training_args.hub_token)
# Get the datasets: you can either provide your own CSV/JSON training and evaluation files (see below)
# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
@@ -475,7 +498,7 @@ def main():
data_args.dataset_config_name,
cache_dir=model_args.cache_dir,
keep_in_memory=False,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
else:
data_files = {}
@@ -492,7 +515,7 @@ def main():
extension,
data_files=data_files,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
# https://huggingface.co/docs/datasets/loading_datasets.html.
@@ -503,13 +526,15 @@ def main():
config = AutoConfig.from_pretrained(
model_args.config_name,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
elif model_args.model_name_or_path:
config = AutoConfig.from_pretrained(
model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
else:
config = CONFIG_MAPPING[model_args.model_type]()
@@ -520,14 +545,16 @@ def main():
model_args.tokenizer_name,
cache_dir=model_args.cache_dir,
use_fast=model_args.use_fast_tokenizer,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
elif model_args.model_name_or_path:
tokenizer = AutoTokenizer.from_pretrained(
model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
use_fast=model_args.use_fast_tokenizer,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
else:
raise ValueError(
@@ -541,13 +568,15 @@ def main():
config=config,
seed=training_args.seed,
dtype=getattr(jnp, model_args.dtype),
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
else:
model = FlaxAutoModelForSeq2SeqLM.from_config(
config,
seed=training_args.seed,
dtype=getattr(jnp, model_args.dtype),
+ trust_remote_code=model_args.trust_remote_code,
)
if training_args.gradient_checkpointing:
diff --git a/examples/flax/text-classification/run_flax_glue.py b/examples/flax/text-classification/run_flax_glue.py
index ffd98152d77c..b9a23f9dd5eb 100755
--- a/examples/flax/text-classification/run_flax_glue.py
+++ b/examples/flax/text-classification/run_flax_glue.py
@@ -21,6 +21,7 @@
import random
import sys
import time
+import warnings
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Callable, Dict, Optional, Tuple
@@ -49,12 +50,12 @@
TrainingArguments,
is_tensorboard_available,
)
-from transformers.utils import check_min_version, get_full_repo_name, send_example_telemetry
+from transformers.utils import check_min_version, send_example_telemetry
logger = logging.getLogger(__name__)
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
-check_min_version("4.29.0.dev0")
+check_min_version("4.32.0.dev0")
Array = Any
Dataset = datasets.arrow_dataset.Dataset
@@ -101,12 +102,28 @@ class ModelArguments:
default="main",
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
)
+ token: str = field(
+ default=None,
+ metadata={
+ "help": (
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
+ )
+ },
+ )
use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
+ trust_remote_code: bool = field(
default=False,
metadata={
"help": (
- "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
- "with private models)."
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
)
},
)
@@ -321,6 +338,12 @@ def main():
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_glue", model_args, data_args, framework="flax")
@@ -342,14 +365,14 @@ def main():
# Handle the repository creation
if training_args.push_to_hub:
- if training_args.hub_model_id is None:
- repo_name = get_full_repo_name(
- Path(training_args.output_dir).absolute().name, token=training_args.hub_token
- )
- else:
- repo_name = training_args.hub_model_id
- create_repo(repo_name, exist_ok=True, token=training_args.hub_token)
- repo = Repository(training_args.output_dir, clone_from=repo_name, token=training_args.hub_token)
+ # Retrieve of infer repo_name
+ repo_name = training_args.hub_model_id
+ if repo_name is None:
+ repo_name = Path(training_args.output_dir).absolute().name
+ # Create repo and retrieve repo_id
+ repo_id = create_repo(repo_name, exist_ok=True, token=training_args.hub_token).repo_id
+ # Clone repo locally
+ repo = Repository(training_args.output_dir, clone_from=repo_id, token=training_args.hub_token)
# Get the datasets: you can either provide your own CSV/JSON training and evaluation files (see below)
# or specify a GLUE benchmark task (the dataset will be downloaded automatically from the datasets Hub).
@@ -368,7 +391,7 @@ def main():
raw_datasets = load_dataset(
"glue",
data_args.task_name,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
else:
# Loading the dataset from local csv or json file.
@@ -381,7 +404,7 @@ def main():
raw_datasets = load_dataset(
extension,
data_files=data_files,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
# See more about loading any type of standard or custom dataset at
# https://huggingface.co/docs/datasets/loading_datasets.html.
@@ -411,17 +434,20 @@ def main():
model_args.model_name_or_path,
num_labels=num_labels,
finetuning_task=data_args.task_name,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
tokenizer = AutoTokenizer.from_pretrained(
model_args.model_name_or_path,
use_fast=not model_args.use_slow_tokenizer,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
model = FlaxAutoModelForSequenceClassification.from_pretrained(
model_args.model_name_or_path,
config=config,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
# Preprocessing the datasets
diff --git a/examples/flax/token-classification/run_flax_ner.py b/examples/flax/token-classification/run_flax_ner.py
index 8e038ac13679..e0a0cb1eff7c 100644
--- a/examples/flax/token-classification/run_flax_ner.py
+++ b/examples/flax/token-classification/run_flax_ner.py
@@ -21,6 +21,7 @@
import random
import sys
import time
+import warnings
from dataclasses import asdict, dataclass, field
from enum import Enum
from itertools import chain
@@ -49,13 +50,13 @@
HfArgumentParser,
is_tensorboard_available,
)
-from transformers.utils import check_min_version, get_full_repo_name, send_example_telemetry
+from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
logger = logging.getLogger(__name__)
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
-check_min_version("4.29.0.dev0")
+check_min_version("4.32.0.dev0")
require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/token-classification/requirements.txt")
@@ -149,12 +150,28 @@ class ModelArguments:
default="main",
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
)
+ token: str = field(
+ default=None,
+ metadata={
+ "help": (
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
+ )
+ },
+ )
use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
+ trust_remote_code: bool = field(
default=False,
metadata={
"help": (
- "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
- "with private models)."
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
)
},
)
@@ -377,6 +394,12 @@ def main():
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_ner", model_args, data_args, framework="flax")
@@ -398,14 +421,14 @@ def main():
# Handle the repository creation
if training_args.push_to_hub:
- if training_args.hub_model_id is None:
- repo_name = get_full_repo_name(
- Path(training_args.output_dir).absolute().name, token=training_args.hub_token
- )
- else:
- repo_name = training_args.hub_model_id
- create_repo(repo_name, exist_ok=True, token=training_args.hub_token)
- repo = Repository(training_args.output_dir, clone_from=repo_name, token=training_args.hub_token)
+ # Retrieve of infer repo_name
+ repo_name = training_args.hub_model_id
+ if repo_name is None:
+ repo_name = Path(training_args.output_dir).absolute().name
+ # Create repo and retrieve repo_id
+ repo_id = create_repo(repo_name, exist_ok=True, token=training_args.hub_token).repo_id
+ # Clone repo locally
+ repo = Repository(training_args.output_dir, clone_from=repo_id, token=training_args.hub_token)
# Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
# or just provide the name of one of the public datasets for token classification task available on the hub at https://huggingface.co/datasets/
@@ -422,7 +445,7 @@ def main():
data_args.dataset_name,
data_args.dataset_config_name,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
else:
# Loading the dataset from local csv or json file.
@@ -436,7 +459,7 @@ def main():
extension,
data_files=data_files,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
# See more about loading any type of standard or custom dataset at
# https://huggingface.co/docs/datasets/loading_datasets.html.
@@ -490,7 +513,8 @@ def get_label_list(labels):
finetuning_task=data_args.task_name,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
tokenizer_name_or_path = model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path
if config.model_type in {"gpt2", "roberta"}:
@@ -498,7 +522,8 @@ def get_label_list(labels):
tokenizer_name_or_path,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
add_prefix_space=True,
)
else:
@@ -506,14 +531,16 @@ def get_label_list(labels):
tokenizer_name_or_path,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
model = FlaxAutoModelForTokenClassification.from_pretrained(
model_args.model_name_or_path,
config=config,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
# Preprocessing the datasets
diff --git a/examples/flax/vision/requirements.txt b/examples/flax/vision/requirements.txt
index cf1859d75494..539ffdc6fa9f 100644
--- a/examples/flax/vision/requirements.txt
+++ b/examples/flax/vision/requirements.txt
@@ -3,6 +3,6 @@ jaxlib>=0.1.59
flax>=0.3.5
optax>=0.0.8
-f https://download.pytorch.org/whl/torch_stable.html
-torch==1.9.0+cpu
+torch==1.11.0+cpu
-f https://download.pytorch.org/whl/torch_stable.html
-torchvision==0.10.0+cpu
\ No newline at end of file
+torchvision==0.12.0+cpu
diff --git a/examples/flax/vision/run_image_classification.py b/examples/flax/vision/run_image_classification.py
index 6a88f0f8d67b..d3454f26723b 100644
--- a/examples/flax/vision/run_image_classification.py
+++ b/examples/flax/vision/run_image_classification.py
@@ -24,6 +24,7 @@
import os
import sys
import time
+import warnings
from dataclasses import asdict, dataclass, field
from enum import Enum
from pathlib import Path
@@ -54,7 +55,7 @@
is_tensorboard_available,
set_seed,
)
-from transformers.utils import get_full_repo_name, send_example_telemetry
+from transformers.utils import send_example_telemetry
logger = logging.getLogger(__name__)
@@ -159,12 +160,28 @@ class ModelArguments:
)
},
)
+ token: str = field(
+ default=None,
+ metadata={
+ "help": (
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
+ )
+ },
+ )
use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
+ trust_remote_code: bool = field(
default=False,
metadata={
"help": (
- "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
- "with private models)."
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
)
},
)
@@ -257,6 +274,12 @@ def main():
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_image_classification", model_args, data_args, framework="flax")
@@ -293,14 +316,14 @@ def main():
# Handle the repository creation
if training_args.push_to_hub:
- if training_args.hub_model_id is None:
- repo_name = get_full_repo_name(
- Path(training_args.output_dir).absolute().name, token=training_args.hub_token
- )
- else:
- repo_name = training_args.hub_model_id
- create_repo(repo_name, exist_ok=True, token=training_args.hub_token)
- repo = Repository(training_args.output_dir, clone_from=repo_name, token=training_args.hub_token)
+ # Retrieve of infer repo_name
+ repo_name = training_args.hub_model_id
+ if repo_name is None:
+ repo_name = Path(training_args.output_dir).absolute().name
+ # Create repo and retrieve repo_id
+ repo_id = create_repo(repo_name, exist_ok=True, token=training_args.hub_token).repo_id
+ # Clone repo locally
+ repo = Repository(training_args.output_dir, clone_from=repo_id, token=training_args.hub_token)
# Initialize datasets and pre-processing transforms
# We use torchvision here for faster pre-processing
@@ -338,7 +361,8 @@ def main():
num_labels=len(train_dataset.classes),
image_size=data_args.image_size,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
elif model_args.model_name_or_path:
config = AutoConfig.from_pretrained(
@@ -346,7 +370,8 @@ def main():
num_labels=len(train_dataset.classes),
image_size=data_args.image_size,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
else:
config = CONFIG_MAPPING[model_args.model_type]()
@@ -358,13 +383,15 @@ def main():
config=config,
seed=training_args.seed,
dtype=getattr(jnp, model_args.dtype),
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
else:
model = FlaxAutoModelForImageClassification.from_config(
config,
seed=training_args.seed,
dtype=getattr(jnp, model_args.dtype),
+ trust_remote_code=model_args.trust_remote_code,
)
# Store some constant
diff --git a/examples/pytorch/audio-classification/run_audio_classification.py b/examples/pytorch/audio-classification/run_audio_classification.py
index e9beb8dcf917..8be727200a99 100644
--- a/examples/pytorch/audio-classification/run_audio_classification.py
+++ b/examples/pytorch/audio-classification/run_audio_classification.py
@@ -45,7 +45,7 @@
logger = logging.getLogger(__name__)
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
-check_min_version("4.29.0.dev0")
+check_min_version("4.32.0.dev0")
require_version("datasets>=1.14.0", "To fix: pip install -r examples/pytorch/audio-classification/requirements.txt")
@@ -152,12 +152,28 @@ class ModelArguments:
attention_mask: bool = field(
default=True, metadata={"help": "Whether to generate an attention mask in the feature extractor."}
)
+ token: str = field(
+ default=None,
+ metadata={
+ "help": (
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
+ )
+ },
+ )
use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
+ trust_remote_code: bool = field(
default=False,
metadata={
"help": (
- "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
- "with private models)."
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
)
},
)
@@ -198,6 +214,12 @@ def main():
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_audio_classification", model_args, data_args)
@@ -222,7 +244,7 @@ def main():
# Log on each process the small summary:
logger.warning(
f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu} "
- + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
+ + f"distributed training: {training_args.parallel_mode.value == 'distributed'}, 16-bits training: {training_args.fp16}"
)
logger.info(f"Training/evaluation parameters {training_args}")
@@ -250,13 +272,13 @@ def main():
data_args.dataset_name,
data_args.dataset_config_name,
split=data_args.train_split_name,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
raw_datasets["eval"] = load_dataset(
data_args.dataset_name,
data_args.dataset_config_name,
split=data_args.eval_split_name,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
if data_args.audio_column_name not in raw_datasets["train"].column_names:
@@ -280,7 +302,8 @@ def main():
return_attention_mask=model_args.attention_mask,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
# `datasets` takes care of automatically loading and resampling the audio,
@@ -340,7 +363,8 @@ def compute_metrics(eval_pred):
finetuning_task="audio-classification",
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
model = AutoModelForAudioClassification.from_pretrained(
model_args.model_name_or_path,
@@ -348,7 +372,8 @@ def compute_metrics(eval_pred):
config=config,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
ignore_mismatched_sizes=model_args.ignore_mismatched_sizes,
)
diff --git a/examples/pytorch/contrastive-image-text/run_clip.py b/examples/pytorch/contrastive-image-text/run_clip.py
index c30349c37aaa..110f1bbaa643 100644
--- a/examples/pytorch/contrastive-image-text/run_clip.py
+++ b/examples/pytorch/contrastive-image-text/run_clip.py
@@ -26,6 +26,7 @@
import logging
import os
import sys
+import warnings
from dataclasses import dataclass, field
from typing import Optional
@@ -54,7 +55,7 @@
logger = logging.getLogger(__name__)
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
-check_min_version("4.29.0.dev0")
+check_min_version("4.32.0.dev0")
require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/contrastive-image-text/requirements.txt")
@@ -86,12 +87,28 @@ class ModelArguments:
default=True,
metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
)
+ token: str = field(
+ default=None,
+ metadata={
+ "help": (
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
+ )
+ },
+ )
use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
+ trust_remote_code: bool = field(
default=False,
metadata={
"help": (
- "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
- "with private models)."
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
)
},
)
@@ -235,6 +252,12 @@ def main():
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_clip", model_args, data_args)
@@ -259,7 +282,7 @@ def main():
# Log on each process the small summary:
logger.warning(
f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
- + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
+ + f"distributed training: {training_args.parallel_mode.value == 'distributed'}, 16-bits training: {training_args.fp16}"
)
logger.info(f"Training/evaluation parameters {training_args}")
@@ -294,7 +317,7 @@ def main():
cache_dir=model_args.cache_dir,
keep_in_memory=False,
data_dir=data_args.data_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
else:
data_files = {}
@@ -311,7 +334,7 @@ def main():
extension,
data_files=data_files,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
# https://huggingface.co/docs/datasets/loading_datasets.html.
@@ -319,11 +342,19 @@ def main():
# 5. Load pretrained model, tokenizer, and image processor
if model_args.tokenizer_name:
tokenizer = AutoTokenizer.from_pretrained(
- model_args.tokenizer_name, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
+ model_args.tokenizer_name,
+ cache_dir=model_args.cache_dir,
+ use_fast=model_args.use_fast_tokenizer,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
elif model_args.model_name_or_path:
tokenizer = AutoTokenizer.from_pretrained(
- model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
+ model_args.model_name_or_path,
+ cache_dir=model_args.cache_dir,
+ use_fast=model_args.use_fast_tokenizer,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
else:
raise ValueError(
@@ -336,14 +367,16 @@ def main():
model_args.image_processor_name or model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
model = AutoModel.from_pretrained(
model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
config = model.config
diff --git a/examples/pytorch/image-classification/run_image_classification.py b/examples/pytorch/image-classification/run_image_classification.py
index 4b4fee5b5175..a7fe144da269 100644
--- a/examples/pytorch/image-classification/run_image_classification.py
+++ b/examples/pytorch/image-classification/run_image_classification.py
@@ -16,6 +16,7 @@
import logging
import os
import sys
+import warnings
from dataclasses import dataclass, field
from typing import Optional
@@ -55,7 +56,7 @@
logger = logging.getLogger(__name__)
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
-check_min_version("4.29.0.dev0")
+check_min_version("4.32.0.dev0")
require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/image-classification/requirements.txt")
@@ -142,12 +143,28 @@ class ModelArguments:
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
)
image_processor_name: str = field(default=None, metadata={"help": "Name or path of preprocessor config."})
+ token: str = field(
+ default=None,
+ metadata={
+ "help": (
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
+ )
+ },
+ )
use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
+ trust_remote_code: bool = field(
default=False,
metadata={
"help": (
- "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
- "with private models)."
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
)
},
)
@@ -176,6 +193,12 @@ def main():
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_image_classification", model_args, data_args)
@@ -200,7 +223,7 @@ def main():
# Log on each process the small summary:
logger.warning(
f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
- + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
+ + f"distributed training: {training_args.parallel_mode.value == 'distributed'}, 16-bits training: {training_args.fp16}"
)
logger.info(f"Training/evaluation parameters {training_args}")
@@ -229,7 +252,7 @@ def main():
data_args.dataset_config_name,
cache_dir=model_args.cache_dir,
task="image-classification",
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
else:
data_files = {}
@@ -276,7 +299,8 @@ def compute_metrics(p):
finetuning_task="image-classification",
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
model = AutoModelForImageClassification.from_pretrained(
model_args.model_name_or_path,
@@ -284,14 +308,16 @@ def compute_metrics(p):
config=config,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
ignore_mismatched_sizes=model_args.ignore_mismatched_sizes,
)
image_processor = AutoImageProcessor.from_pretrained(
model_args.image_processor_name or model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
# Define torchvision transforms to be applied to each image.
diff --git a/examples/pytorch/image-classification/run_image_classification_no_trainer.py b/examples/pytorch/image-classification/run_image_classification_no_trainer.py
index e30699435431..e63dc7973335 100644
--- a/examples/pytorch/image-classification/run_image_classification_no_trainer.py
+++ b/examples/pytorch/image-classification/run_image_classification_no_trainer.py
@@ -42,12 +42,12 @@
import transformers
from transformers import AutoConfig, AutoImageProcessor, AutoModelForImageClassification, SchedulerType, get_scheduler
-from transformers.utils import check_min_version, get_full_repo_name, send_example_telemetry
+from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
-check_min_version("4.29.0.dev0")
+check_min_version("4.32.0.dev0")
logger = get_logger(__name__)
@@ -146,6 +146,16 @@ def parse_args():
"--hub_model_id", type=str, help="The name of the repository to keep in sync with the local `output_dir`."
)
parser.add_argument("--hub_token", type=str, help="The token to use to push to the Model Hub.")
+ parser.add_argument(
+ "--trust_remote_code",
+ type=bool,
+ default=False,
+ help=(
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
+ ),
+ )
parser.add_argument(
"--checkpointing_steps",
type=str,
@@ -210,7 +220,7 @@ def main():
if args.with_tracking:
accelerator_log_kwargs["log_with"] = args.report_to
- accelerator_log_kwargs["logging_dir"] = args.output_dir
+ accelerator_log_kwargs["project_dir"] = args.output_dir
accelerator = Accelerator(gradient_accumulation_steps=args.gradient_accumulation_steps, **accelerator_log_kwargs)
@@ -236,12 +246,14 @@ def main():
# Handle the repository creation
if accelerator.is_main_process:
if args.push_to_hub:
- if args.hub_model_id is None:
- repo_name = get_full_repo_name(Path(args.output_dir).name, token=args.hub_token)
- else:
- repo_name = args.hub_model_id
- create_repo(repo_name, exist_ok=True, token=args.hub_token)
- repo = Repository(args.output_dir, clone_from=repo_name, token=args.hub_token)
+ # Retrieve of infer repo_name
+ repo_name = args.hub_model_id
+ if repo_name is None:
+ repo_name = Path(args.output_dir).absolute().name
+ # Create repo and retrieve repo_id
+ repo_id = create_repo(repo_name, exist_ok=True, token=args.hub_token).repo_id
+ # Clone repo locally
+ repo = Repository(args.output_dir, clone_from=repo_id, token=args.hub_token)
with open(os.path.join(args.output_dir, ".gitignore"), "w+") as gitignore:
if "step_*" not in gitignore:
@@ -298,13 +310,18 @@ def main():
i2label=id2label,
label2id=label2id,
finetuning_task="image-classification",
+ trust_remote_code=args.trust_remote_code,
+ )
+ image_processor = AutoImageProcessor.from_pretrained(
+ args.model_name_or_path,
+ trust_remote_code=args.trust_remote_code,
)
- image_processor = AutoImageProcessor.from_pretrained(args.model_name_or_path)
model = AutoModelForImageClassification.from_pretrained(
args.model_name_or_path,
from_tf=bool(".ckpt" in args.model_name_or_path),
config=config,
ignore_mismatched_sizes=args.ignore_mismatched_sizes,
+ trust_remote_code=args.trust_remote_code,
)
# Preprocessing the datasets
@@ -437,36 +454,45 @@ def collate_fn(examples):
# Potentially load in the weights and states from a previous save
if args.resume_from_checkpoint:
if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
- accelerator.print(f"Resumed from checkpoint: {args.resume_from_checkpoint}")
- accelerator.load_state(args.resume_from_checkpoint)
+ checkpoint_path = args.resume_from_checkpoint
path = os.path.basename(args.resume_from_checkpoint)
else:
# Get the most recent checkpoint
dirs = [f.name for f in os.scandir(os.getcwd()) if f.is_dir()]
dirs.sort(key=os.path.getctime)
path = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last
+ checkpoint_path = path
+ path = os.path.basename(checkpoint_path)
+
+ accelerator.print(f"Resumed from checkpoint: {checkpoint_path}")
+ accelerator.load_state(path)
# Extract `epoch_{i}` or `step_{i}`
training_difference = os.path.splitext(path)[0]
if "epoch" in training_difference:
starting_epoch = int(training_difference.replace("epoch_", "")) + 1
resume_step = None
+ completed_steps = starting_epoch * num_update_steps_per_epoch
else:
- resume_step = int(training_difference.replace("step_", ""))
+ # need to multiply `gradient_accumulation_steps` to reflect real steps
+ resume_step = int(training_difference.replace("step_", "")) * args.gradient_accumulation_steps
starting_epoch = resume_step // len(train_dataloader)
resume_step -= starting_epoch * len(train_dataloader)
+ completed_steps = resume_step // args.gradient_accumulation_step
+
+ # update the progress_bar if load from checkpoint
+ progress_bar.update(completed_steps)
for epoch in range(starting_epoch, args.num_train_epochs):
model.train()
if args.with_tracking:
total_loss = 0
- for step, batch in enumerate(train_dataloader):
- # We need to skip steps until we reach the resumed step
- if args.resume_from_checkpoint and epoch == starting_epoch:
- if resume_step is not None and step < resume_step:
- completed_steps += 1
- continue
-
+ if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None:
+ # We skip the first `n` batches in the dataloader when resuming from a checkpoint
+ active_dataloader = accelerator.skip_first_batches(train_dataloader, resume_step)
+ else:
+ active_dataloader = train_dataloader
+ for step, batch in enumerate(active_dataloader):
with accelerator.accumulate(model):
outputs = model(**batch)
loss = outputs.loss
diff --git a/examples/pytorch/image-pretraining/run_mae.py b/examples/pytorch/image-pretraining/run_mae.py
index 3f7ef47c6a67..1c269fba3a2b 100644
--- a/examples/pytorch/image-pretraining/run_mae.py
+++ b/examples/pytorch/image-pretraining/run_mae.py
@@ -16,6 +16,7 @@
import logging
import os
import sys
+import warnings
from dataclasses import dataclass, field
from typing import Optional
@@ -43,7 +44,7 @@
logger = logging.getLogger(__name__)
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
-check_min_version("4.29.0.dev0")
+check_min_version("4.32.0.dev0")
require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt")
@@ -133,15 +134,21 @@ class ModelArguments:
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
)
image_processor_name: str = field(default=None, metadata={"help": "Name or path of preprocessor config."})
- use_auth_token: bool = field(
- default=False,
+ token: str = field(
+ default=None,
metadata={
"help": (
- "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
- "with private models)."
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
)
},
)
+ use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
mask_ratio: float = field(
default=0.75, metadata={"help": "The ratio of the number of masked tokens in the input sequence."}
)
@@ -175,6 +182,12 @@ def main():
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_mae", model_args, data_args)
@@ -199,7 +212,7 @@ def main():
# Log on each process the small summary:
logger.warning(
f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
- + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
+ + f"distributed training: {training_args.parallel_mode.value == 'distributed'}, 16-bits training: {training_args.fp16}"
)
logger.info(f"Training/evaluation parameters {training_args}")
@@ -224,7 +237,7 @@ def main():
data_args.dataset_config_name,
data_files=data_args.data_files,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
# If we don't have a validation split, split off a percentage of train as validation.
@@ -242,7 +255,7 @@ def main():
config_kwargs = {
"cache_dir": model_args.cache_dir,
"revision": model_args.model_revision,
- "use_auth_token": True if model_args.use_auth_token else None,
+ "token": model_args.token,
}
if model_args.config_name:
config = ViTMAEConfig.from_pretrained(model_args.config_name, **config_kwargs)
@@ -280,7 +293,7 @@ def main():
config=config,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
else:
logger.info("Training new model from scratch")
diff --git a/examples/pytorch/image-pretraining/run_mim.py b/examples/pytorch/image-pretraining/run_mim.py
index 874b7c651248..9fa3a1b68a83 100644
--- a/examples/pytorch/image-pretraining/run_mim.py
+++ b/examples/pytorch/image-pretraining/run_mim.py
@@ -16,6 +16,7 @@
import logging
import os
import sys
+import warnings
from dataclasses import dataclass, field
from typing import Optional
@@ -48,7 +49,7 @@
logger = logging.getLogger(__name__)
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
-check_min_version("4.29.0.dev0")
+check_min_version("4.32.0.dev0")
require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt")
@@ -153,12 +154,28 @@ class ModelArguments:
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
)
image_processor_name: str = field(default=None, metadata={"help": "Name or path of preprocessor config."})
+ token: str = field(
+ default=None,
+ metadata={
+ "help": (
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
+ )
+ },
+ )
use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
+ trust_remote_code: bool = field(
default=False,
metadata={
"help": (
- "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
- "with private models)."
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
)
},
)
@@ -239,6 +256,12 @@ def main():
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_mim", model_args, data_args)
@@ -263,7 +286,7 @@ def main():
# Log on each process the small summary:
logger.warning(
f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
- + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
+ + f"distributed training: {training_args.parallel_mode.value == 'distributed'}, 16-bits training: {training_args.fp16}"
)
logger.info(f"Training/evaluation parameters {training_args}")
@@ -288,7 +311,7 @@ def main():
data_args.dataset_config_name,
data_files=data_args.data_files,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
# If we don't have a validation split, split off a percentage of train as validation.
@@ -305,7 +328,8 @@ def main():
config_kwargs = {
"cache_dir": model_args.cache_dir,
"revision": model_args.model_revision,
- "use_auth_token": True if model_args.use_auth_token else None,
+ "token": model_args.token,
+ "trust_remote_code": model_args.trust_remote_code,
}
if model_args.config_name_or_path:
config = AutoConfig.from_pretrained(model_args.config_name_or_path, **config_kwargs)
@@ -357,11 +381,12 @@ def main():
config=config,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
else:
logger.info("Training new model from scratch")
- model = AutoModelForMaskedImageModeling.from_config(config)
+ model = AutoModelForMaskedImageModeling.from_config(config, trust_remote_code=model_args.trust_remote_code)
if training_args.do_train:
column_names = ds["train"].column_names
diff --git a/examples/pytorch/image-pretraining/run_mim_no_trainer.py b/examples/pytorch/image-pretraining/run_mim_no_trainer.py
new file mode 100644
index 000000000000..c853669c0dee
--- /dev/null
+++ b/examples/pytorch/image-pretraining/run_mim_no_trainer.py
@@ -0,0 +1,805 @@
+#!/usr/bin/env python
+# coding=utf-8
+# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+
+import argparse
+import logging
+import math
+import os
+import warnings
+from pathlib import Path
+
+import datasets
+import numpy as np
+import torch
+from accelerate import Accelerator, DistributedType
+from accelerate.utils import set_seed
+from datasets import load_dataset
+from huggingface_hub import Repository, create_repo
+from torch.utils.data import DataLoader
+from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor
+from tqdm.auto import tqdm
+
+import transformers
+from transformers import (
+ CONFIG_MAPPING,
+ IMAGE_PROCESSOR_MAPPING,
+ MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING,
+ AutoConfig,
+ AutoImageProcessor,
+ AutoModelForMaskedImageModeling,
+ SchedulerType,
+ get_scheduler,
+)
+from transformers.utils import check_min_version, send_example_telemetry
+from transformers.utils.versions import require_version
+
+
+""" Pre-training a đ€ Transformers model for simple masked image modeling (SimMIM)
+without using HuggingFace Trainer.
+Any model supported by the AutoModelForMaskedImageModeling API can be used.
+"""
+
+logger = logging.getLogger(__name__)
+
+# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
+check_min_version("4.32.0.dev0")
+
+require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt")
+
+MODEL_CONFIG_CLASSES = list(MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING.keys())
+MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
+
+
+def parse_args():
+ parser = argparse.ArgumentParser(
+ description="Finetune a transformers model on a simple Masked Image Modeling task"
+ )
+ parser.add_argument(
+ "--dataset_name",
+ type=str,
+ default="cifar10",
+ help="Name of a dataset from the datasets package",
+ )
+ parser.add_argument(
+ "--dataset_config_name",
+ type=str,
+ default=None,
+ help="The configuration name of the dataset to use (via the datasets library).",
+ )
+ parser.add_argument(
+ "--image_column_name",
+ type=str,
+ default=None,
+ help="The column name of the images in the files. If not set, will try to use 'image' or 'img'.",
+ )
+ parser.add_argument(
+ "--train_dir",
+ type=str,
+ default=None,
+ help="A folder containing the training data.",
+ )
+ parser.add_argument(
+ "--validation_dir",
+ type=None,
+ default=None,
+ help="A folder containing the validation data.",
+ )
+ parser.add_argument(
+ "--train_val_split",
+ type=float,
+ default=0.15,
+ help="Percent to split off of train for validation.",
+ )
+ parser.add_argument(
+ "--mask_patch_size",
+ type=int,
+ default=32,
+ help="The size of the square patches to use for masking.",
+ )
+ parser.add_argument(
+ "--mask_ratio",
+ type=float,
+ default=0.6,
+ help="Percentage of patches to mask.",
+ )
+ parser.add_argument(
+ "--max_train_samples",
+ type=int,
+ default=None,
+ help=(
+ "For debugging purposes or quicker training, truncate the number of training examples to this "
+ "value if set."
+ ),
+ )
+ parser.add_argument(
+ "--max_eval_samples",
+ type=int,
+ default=None,
+ help=(
+ "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
+ "value if set."
+ ),
+ )
+ parser.add_argument(
+ "--model_name_or_path",
+ type=str,
+ default=None,
+ help=(
+ "The model checkpoint for weights initialization. Can be a local path to a pytorch_model.bin or a "
+ "checkpoint identifier on the hub. "
+ "Don't set if you want to train a model from scratch."
+ ),
+ )
+ parser.add_argument(
+ "--model_type",
+ type=str,
+ default=None,
+ help="If training from scratch, pass a model type from the list: " + ", ".join(MODEL_TYPES),
+ )
+ parser.add_argument(
+ "--config_name_or_path",
+ type=str,
+ default=None,
+ help="Pretrained config name or path if not the same as model_name",
+ )
+ parser.add_argument(
+ "--config_overrides",
+ type=str,
+ default=None,
+ help=(
+ "Override some existing default config settings when a model is trained from scratch. Example: "
+ "n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index"
+ ),
+ )
+ parser.add_argument(
+ "--cache_dir",
+ type=str,
+ default=None,
+ help="Where do you want to store (cache) the pretrained models/datasets downloaded from the hub",
+ )
+ parser.add_argument(
+ "--model_revision",
+ type=str,
+ default="main",
+ help="The specific model version to use (can be a branch name, tag name or commit id).",
+ )
+ parser.add_argument(
+ "--gradient_accumulation_steps",
+ type=int,
+ default=1,
+ help="Number of updates steps to accumulate before performing a backward/update pass.",
+ )
+ parser.add_argument(
+ "--image_processor_name",
+ type=str,
+ default=None,
+ help="Name or path of preprocessor config.",
+ )
+ parser.add_argument(
+ "--token",
+ type=str,
+ default=None,
+ help=(
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
+ ),
+ )
+ parser.add_argument(
+ "--use_auth_token",
+ type=bool,
+ default=None,
+ help="The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`.",
+ )
+ parser.add_argument(
+ "--trust_remote_code",
+ type=bool,
+ default=False,
+ help=(
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
+ ),
+ )
+ parser.add_argument(
+ "--image_size",
+ type=int,
+ default=None,
+ help="The size (resolution) of each image. If not specified, will use `image_size` of the configuration.",
+ )
+ parser.add_argument(
+ "--patch_size",
+ type=int,
+ default=None,
+ help="The size (resolution) of each patch. If not specified, will use `patch_size` of the configuration.",
+ )
+ parser.add_argument(
+ "--encoder_stride",
+ type=int,
+ default=None,
+ help={"help": "Stride to use for the encoder."},
+ )
+ parser.add_argument(
+ "--push_to_hub",
+ action="store_true",
+ help="Whether or not to push the model to the Hub.",
+ )
+ parser.add_argument(
+ "--with_tracking",
+ action="store_true",
+ help="Whether to enable experiment trackers for logging.",
+ )
+ parser.add_argument(
+ "--report_to",
+ type=str,
+ default="all",
+ help=(
+ 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`,'
+ ' `"wandb"`, `"comet_ml"` and `"clearml"`. Use `"all"` (default) to report to all integrations.'
+ "Only applicable when `--with_tracking` is passed."
+ ),
+ )
+ parser.add_argument(
+ "--seed",
+ type=int,
+ default=None,
+ help="A seed for reproducible training.",
+ )
+ parser.add_argument(
+ "--per_device_train_batch_size",
+ type=int,
+ default=8,
+ help="Batch size (per device) for the training dataloader.",
+ )
+ parser.add_argument(
+ "--learning_rate",
+ type=float,
+ default=5e-5,
+ help="The initial learning rate for [`AdamW`] optimizer.",
+ )
+ parser.add_argument(
+ "--weight_decay",
+ type=float,
+ default=0.0,
+ help="Weight decay to use.",
+ )
+ parser.add_argument(
+ "--num_train_epochs",
+ type=float,
+ default=3.0,
+ help="Total number of training epochs to perform (if not an integer, will perform the decimal part percents of the last epoch before stopping training).",
+ )
+ parser.add_argument(
+ "--max_train_steps",
+ type=int,
+ default=None,
+ help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
+ )
+ parser.add_argument(
+ "--lr_scheduler_type",
+ type=SchedulerType,
+ default="linear",
+ help="The scheduler type to use.",
+ choices=["linear", "cosine", "cosine_with_restarts", "polynomial", "constant", "constant_with_warmup"],
+ )
+ parser.add_argument(
+ "--num_warmup_steps",
+ type=int,
+ default=0,
+ help="Number of steps for the warmup in the lr scheduler.",
+ )
+ parser.add_argument(
+ "--checkpointing_steps",
+ type=str,
+ default=None,
+ help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.",
+ )
+ parser.add_argument(
+ "--resume_from_checkpoint",
+ type=str,
+ default=None,
+ help="If the training should continue from a checkpoint folder.",
+ )
+ parser.add_argument(
+ "--per_device_eval_batch_size",
+ type=int,
+ default=8,
+ help="Batch size (per device) for the evaluation dataloader.",
+ )
+ parser.add_argument(
+ "--output_dir",
+ type=str,
+ default=None,
+ help="Where to store the final model.",
+ )
+ args = parser.parse_args()
+
+ # Sanity checks
+ data_files = {}
+ if args.train_dir is not None:
+ data_files["train"] = args.train_dir
+ if args.validation_dir is not None:
+ data_files["val"] = args.validation_dir
+ args.data_files = data_files if data_files else None
+
+ if args.push_to_hub:
+ assert args.output_dir is not None, "Need an `output_dir` to create a repo when `--push_to_hub` is passed."
+
+ return args
+
+
+class MaskGenerator:
+ """
+ A class to generate boolean masks for the pretraining task.
+
+ A mask is a 1D tensor of shape (model_patch_size**2,) where the value is either 0 or 1,
+ where 1 indicates "masked".
+ """
+
+ def __init__(self, input_size=192, mask_patch_size=32, model_patch_size=4, mask_ratio=0.6):
+ self.input_size = input_size
+ self.mask_patch_size = mask_patch_size
+ self.model_patch_size = model_patch_size
+ self.mask_ratio = mask_ratio
+
+ if self.input_size % self.mask_patch_size != 0:
+ raise ValueError("Input size must be divisible by mask patch size")
+ if self.mask_patch_size % self.model_patch_size != 0:
+ raise ValueError("Mask patch size must be divisible by model patch size")
+
+ self.rand_size = self.input_size // self.mask_patch_size
+ self.scale = self.mask_patch_size // self.model_patch_size
+
+ self.token_count = self.rand_size**2
+ self.mask_count = int(np.ceil(self.token_count * self.mask_ratio))
+
+ def __call__(self):
+ mask_idx = np.random.permutation(self.token_count)[: self.mask_count]
+ mask = np.zeros(self.token_count, dtype=int)
+ mask[mask_idx] = 1
+
+ mask = mask.reshape((self.rand_size, self.rand_size))
+ mask = mask.repeat(self.scale, axis=0).repeat(self.scale, axis=1)
+
+ return torch.tensor(mask.flatten())
+
+
+def collate_fn(examples):
+ pixel_values = torch.stack([example["pixel_values"] for example in examples])
+ mask = torch.stack([example["mask"] for example in examples])
+ return {"pixel_values": pixel_values, "bool_masked_pos": mask}
+
+
+def main():
+ args = parse_args()
+
+ if args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ args.token = args.use_auth_token
+
+ # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
+ # information sent is the one passed as arguments along with your Python/PyTorch versions.
+ send_example_telemetry("run_mim_no_trainer", args)
+
+ # Initialize the accelerator. We will let the accelerator handle device placement for us in this example.
+ # If we're using tracking, we also need to initialize it here and it will by default pick up all supported trackers
+ # in the environment
+ accelerator_log_kwargs = {}
+
+ if args.with_tracking:
+ accelerator_log_kwargs["log_with"] = args.report_to
+ accelerator_log_kwargs["project_dir"] = args.output_dir
+
+ accelerator = Accelerator(
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
+ **accelerator_log_kwargs,
+ )
+
+ # Make one log on every process with the configuration for debugging.
+ logging.basicConfig(
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
+ datefmt="%m/%d/%Y %H:%M:%S",
+ level=logging.INFO,
+ )
+ logger.info(accelerator.state)
+ if accelerator.is_local_main_process:
+ datasets.utils.logging.set_verbosity_warning()
+ transformers.utils.logging.set_verbosity_info()
+ else:
+ datasets.utils.logging.set_verbosity_error()
+ transformers.utils.logging.set_verbosity_error()
+
+ # If passed along, set the training seed now.
+ if args.seed is not None:
+ set_seed(args.seed)
+
+ # Handle the repository creation
+ if accelerator.is_main_process:
+ if args.push_to_hub:
+ # Retrieve of infer repo_name
+ repo_name = args.hub_model_id
+ if repo_name is None:
+ repo_name = Path(args.output_dir).absolute().name
+ # Create repo and retrieve repo_id
+ repo_id = create_repo(repo_name, exist_ok=True, token=args.hub_token).repo_id
+ # Clone repo locally
+ repo = Repository(args.output_dir, clone_from=repo_id, token=args.hub_token)
+
+ with open(os.path.join(args.output_dir, ".gitignore"), "w+") as gitignore:
+ if "step_*" not in gitignore:
+ gitignore.write("step_*\n")
+ if "epoch_*" not in gitignore:
+ gitignore.write("epoch_*\n")
+ elif args.output_dir is not None:
+ os.makedirs(args.output_dir, exist_ok=True)
+ accelerator.wait_for_everyone()
+
+ # Initialize our dataset.
+ ds = load_dataset(
+ args.dataset_name,
+ args.dataset_config_name,
+ data_files=args.data_files,
+ cache_dir=args.cache_dir,
+ token=args.token,
+ )
+
+ # If we don't have a validation split, split off a percentage of train as validation.
+ args.train_val_split = None if "validation" in ds.keys() else args.train_val_split
+ if isinstance(args.train_val_split, float) and args.train_val_split > 0.0:
+ split = ds["train"].train_test_split(args.train_val_split)
+ ds["train"] = split["train"]
+ ds["validation"] = split["test"]
+
+ # Create config
+ # Distributed training:
+ # The .from_pretrained methods guarantee that only one local process can concurrently
+ # download model & vocab.
+ config_kwargs = {
+ "cache_dir": args.cache_dir,
+ "revision": args.model_revision,
+ "token": args.token,
+ "trust_remote_code": args.trust_remote_code,
+ }
+ if args.config_name_or_path:
+ config = AutoConfig.from_pretrained(args.config_name_or_path, **config_kwargs)
+ elif args.model_name_or_path:
+ config = AutoConfig.from_pretrained(args.model_name_or_path, **config_kwargs)
+ else:
+ config = CONFIG_MAPPING[args.model_type]()
+ logger.warning("You are instantiating a new config instance from scratch.")
+ if args.config_overrides is not None:
+ logger.info(f"Overriding config: {args.config_overrides}")
+ config.update_from_string(args.config_overrides)
+ logger.info(f"New config: {config}")
+
+ # make sure the decoder_type is "simmim" (only relevant for BEiT)
+ if hasattr(config, "decoder_type"):
+ config.decoder_type = "simmim"
+
+ # adapt config
+ args.image_size = args.image_size if args.image_size is not None else config.image_size
+ args.patch_size = args.patch_size if args.patch_size is not None else config.patch_size
+ args.encoder_stride = args.encoder_stride if args.encoder_stride is not None else config.encoder_stride
+
+ config.update(
+ {
+ "image_size": args.image_size,
+ "patch_size": args.patch_size,
+ "encoder_stride": args.encoder_stride,
+ }
+ )
+
+ # create image processor
+ if args.image_processor_name:
+ image_processor = AutoImageProcessor.from_pretrained(args.image_processor_name, **config_kwargs)
+ elif args.model_name_or_path:
+ image_processor = AutoImageProcessor.from_pretrained(args.model_name_or_path, **config_kwargs)
+ else:
+ IMAGE_PROCESSOR_TYPES = {
+ conf.model_type: image_processor_class for conf, image_processor_class in IMAGE_PROCESSOR_MAPPING.items()
+ }
+ image_processor = IMAGE_PROCESSOR_TYPES[args.model_type]()
+
+ # create model
+ if args.model_name_or_path:
+ model = AutoModelForMaskedImageModeling.from_pretrained(
+ args.model_name_or_path,
+ from_tf=bool(".ckpt" in args.model_name_or_path),
+ config=config,
+ cache_dir=args.cache_dir,
+ revision=args.model_revision,
+ token=args.token,
+ trust_remote_code=args.trust_remote_code,
+ )
+ else:
+ logger.info("Training new model from scratch")
+ model = AutoModelForMaskedImageModeling.from_config(
+ config,
+ token=args.token,
+ trust_remote_code=args.trust_remote_code,
+ )
+
+ column_names = ds["train"].column_names
+
+ if args.image_column_name is not None:
+ image_column_name = args.image_column_name
+ elif "image" in column_names:
+ image_column_name = "image"
+ elif "img" in column_names:
+ image_column_name = "img"
+ else:
+ image_column_name = column_names[0]
+
+ # transformations as done in original SimMIM paper
+ # source: https://github.com/microsoft/SimMIM/blob/main/data/data_simmim.py
+ transforms = Compose(
+ [
+ Lambda(lambda img: img.convert("RGB")),
+ RandomResizedCrop(args.image_size, scale=(0.67, 1.0), ratio=(3.0 / 4.0, 4.0 / 3.0)),
+ RandomHorizontalFlip(),
+ ToTensor(),
+ Normalize(mean=image_processor.image_mean, std=image_processor.image_std),
+ ]
+ )
+
+ # create mask generator
+ mask_generator = MaskGenerator(
+ input_size=args.image_size,
+ mask_patch_size=args.mask_patch_size,
+ model_patch_size=args.patch_size,
+ mask_ratio=args.mask_ratio,
+ )
+
+ def preprocess_images(examples):
+ """Preprocess a batch of images by applying transforms + creating a corresponding mask, indicating
+ which patches to mask."""
+
+ examples["pixel_values"] = [transforms(image) for image in examples[image_column_name]]
+ examples["mask"] = [mask_generator() for i in range(len(examples[image_column_name]))]
+
+ return examples
+
+ if args.max_train_samples is not None:
+ ds["train"] = ds["train"].shuffle(seed=args.seed).select(range(args.max_train_samples))
+ # Set the training transforms
+ ds["train"].set_transform(preprocess_images)
+
+ if args.max_eval_samples is not None:
+ ds["validation"] = ds["validation"].shuffle(seed=args.seed).select(range(args.max_eval_samples))
+ # Set the validation transforms
+ ds["validation"].set_transform(preprocess_images)
+
+ # DataLoaders creation:
+ train_dataloader = DataLoader(
+ ds["train"],
+ shuffle=True,
+ collate_fn=collate_fn,
+ batch_size=args.per_device_train_batch_size,
+ )
+ eval_dataloader = DataLoader(
+ ds["validation"],
+ collate_fn=collate_fn,
+ batch_size=args.per_device_eval_batch_size,
+ )
+
+ # Optimizer
+ # Split weights in two groups, one with weight decay and the other not.
+ no_decay = ["bias", "LayerNorm.weight"]
+ optimizer_grouped_parameters = [
+ {
+ "params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)],
+ "weight_decay": args.weight_decay,
+ },
+ {
+ "params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)],
+ "weight_decay": 0.0,
+ },
+ ]
+ optimizer = torch.optim.AdamW(optimizer_grouped_parameters, lr=args.learning_rate)
+
+ # Note -> the training dataloader needs to be prepared before we grab his length below (cause its length will be
+ # shorter in multiprocess)
+
+ # Scheduler and math around the number of training steps.
+ overrode_max_train_steps = False
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
+ if args.max_train_steps is None:
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
+ overrode_max_train_steps = True
+
+ lr_scheduler = get_scheduler(
+ name=args.lr_scheduler_type,
+ optimizer=optimizer,
+ num_warmup_steps=args.num_warmup_steps * args.gradient_accumulation_steps,
+ num_training_steps=args.max_train_steps * args.gradient_accumulation_steps,
+ )
+
+ # Prepare everything with our `accelerator`.
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
+ model,
+ optimizer,
+ train_dataloader,
+ eval_dataloader,
+ lr_scheduler,
+ )
+
+ # On TPU, the tie weights in our model have been disconnected, so we need to restore the ties.
+ if accelerator.distributed_type == DistributedType.TPU:
+ model.tie_weights()
+
+ # We need to recalculate our total training steps as the size of the training dataloader may have changed.
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
+ if overrode_max_train_steps:
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
+ # Afterwards we recalculate our number of training epochs
+ args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
+
+ # Figure out how many steps we should save the Accelerator states
+ checkpointing_steps = args.checkpointing_steps
+ if checkpointing_steps is not None and checkpointing_steps.isdigit():
+ checkpointing_steps = int(checkpointing_steps)
+
+ # We need to initialize the trackers we use, and also store our configuration.
+ # The trackers initializes automatically on the main process.
+ if args.with_tracking:
+ experiment_config = vars(args)
+ # TensorBoard cannot log Enums, need the raw value
+ experiment_config["lr_scheduler_type"] = experiment_config["lr_scheduler_type"].value
+ accelerator.init_trackers("mim_no_trainer", experiment_config)
+
+ # Train!
+ total_batch_size = args.per_device_train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
+
+ logger.info("***** Running training *****")
+ logger.info(f" Num examples = {len(ds['train'])}")
+ logger.info(f" Num Epochs = {args.num_train_epochs}")
+ logger.info(f" Instantaneous batch size per device = {args.per_device_train_batch_size}")
+ logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
+ logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
+ logger.info(f" Total optimization steps = {args.max_train_steps}")
+ # Only show the progress bar once on each machine.
+ progress_bar = tqdm(range(int(args.max_train_steps)), disable=not accelerator.is_local_main_process)
+ completed_steps = 0
+ starting_epoch = 0
+
+ # Potentially load in the weights and states from a previous save
+ if args.resume_from_checkpoint:
+ if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
+ checkpoint_path = args.resume_from_checkpoint
+ path = os.path.basename(args.resume_from_checkpoint)
+ else:
+ # Get the most recent checkpoint
+ dirs = [f.name for f in os.scandir(os.getcwd()) if f.is_dir()]
+ dirs.sort(key=os.path.getctime)
+ path = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last
+ checkpoint_path = path
+ path = os.path.basename(checkpoint_path)
+
+ accelerator.print(f"Resumed from checkpoint: {checkpoint_path}")
+ accelerator.load_state(path)
+ # Extract `epoch_{i}` or `step_{i}`
+ training_difference = os.path.splitext(path)[0]
+
+ if "epoch" in training_difference:
+ starting_epoch = int(training_difference.replace("epoch_", "")) + 1
+ resume_step = None
+ completed_steps = starting_epoch * num_update_steps_per_epoch
+ else:
+ # need to multiply `gradient_accumulation_steps` to reflect real steps
+ resume_step = int(training_difference.replace("step_", "")) * args.gradient_accumulation_steps
+ starting_epoch = resume_step // len(train_dataloader)
+ resume_step -= starting_epoch * len(train_dataloader)
+ completed_steps = resume_step // args.gradient_accumulation_steps
+
+ # update the progress_bar if load from checkpoint
+ progress_bar.update(completed_steps)
+
+ for epoch in range(starting_epoch, args.num_train_epochs):
+ model.train()
+ if args.with_tracking:
+ total_loss = 0
+ if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None:
+ # We skip the first `n` batches in the dataloader when resuming from a checkpoint
+ active_dataloader = accelerator.skip_first_batches(train_dataloader, resume_step)
+ else:
+ active_dataloader = train_dataloader
+ for step, batch in enumerate(active_dataloader):
+ with accelerator.accumulate(model):
+ outputs = model(**batch)
+ loss = outputs.loss
+ # We keep track of the loss at each epoch
+ if args.with_tracking:
+ total_loss += loss.detach().float()
+ accelerator.backward(loss)
+ optimizer.step()
+ lr_scheduler.step()
+ optimizer.zero_grad()
+
+ # Checks if the accelerator has performed an optimization step behind the scenes
+ if accelerator.sync_gradients:
+ progress_bar.update(1)
+ completed_steps += 1
+
+ if isinstance(checkpointing_steps, int):
+ if completed_steps % checkpointing_steps == 0:
+ output_dir = f"step_{completed_steps }"
+ if args.output_dir is not None:
+ output_dir = os.path.join(args.output_dir, output_dir)
+ accelerator.save_state(output_dir)
+
+ if completed_steps >= args.max_train_steps:
+ break
+
+ model.eval()
+ losses = []
+ for step, batch in enumerate(eval_dataloader):
+ with torch.no_grad():
+ outputs = model(**batch)
+
+ loss = outputs.loss
+ losses.append(accelerator.gather_for_metrics(loss.repeat(args.per_device_eval_batch_size)))
+
+ losses = torch.cat(losses)
+ eval_loss = torch.mean(losses)
+
+ logger.info(f"epoch {epoch}: eval_loss: {eval_loss}")
+
+ if args.with_tracking:
+ accelerator.log(
+ {
+ "eval_loss": eval_loss,
+ "train_loss": total_loss.item() / len(train_dataloader),
+ "epoch": epoch,
+ "step": completed_steps,
+ },
+ step=completed_steps,
+ )
+
+ if args.push_to_hub and epoch < args.num_train_epochs - 1:
+ accelerator.wait_for_everyone()
+ unwrapped_model = accelerator.unwrap_model(model)
+ unwrapped_model.save_pretrained(
+ args.output_dir, is_main_process=accelerator.is_main_process, save_function=accelerator.save
+ )
+ if accelerator.is_main_process:
+ image_processor.save_pretrained(args.output_dir)
+ repo.push_to_hub(
+ commit_message=f"Training in progress epoch {epoch}", blocking=False, auto_lfs_prune=True
+ )
+
+ if args.checkpointing_steps == "epoch":
+ output_dir = f"epoch_{epoch}"
+ if args.output_dir is not None:
+ output_dir = os.path.join(args.output_dir, output_dir)
+ accelerator.save_state(output_dir)
+
+ if args.with_tracking:
+ accelerator.end_training()
+
+ if args.output_dir is not None:
+ accelerator.wait_for_everyone()
+ unwrapped_model = accelerator.unwrap_model(model)
+ unwrapped_model.save_pretrained(
+ args.output_dir, is_main_process=accelerator.is_main_process, save_function=accelerator.save
+ )
+ if accelerator.is_main_process:
+ image_processor.save_pretrained(args.output_dir)
+ if args.push_to_hub:
+ repo.push_to_hub(commit_message="End of training", auto_lfs_prune=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/pytorch/language-modeling/run_clm.py b/examples/pytorch/language-modeling/run_clm.py
index 020a6f10dde9..3d491f784c6e 100755
--- a/examples/pytorch/language-modeling/run_clm.py
+++ b/examples/pytorch/language-modeling/run_clm.py
@@ -25,6 +25,7 @@
import math
import os
import sys
+import warnings
from dataclasses import dataclass, field
from itertools import chain
from typing import Optional
@@ -55,7 +56,7 @@
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
-check_min_version("4.29.0.dev0")
+check_min_version("4.32.0.dev0")
require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/language-modeling/requirements.txt")
@@ -111,12 +112,28 @@ class ModelArguments:
default="main",
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
)
+ token: str = field(
+ default=None,
+ metadata={
+ "help": (
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
+ )
+ },
+ )
use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
+ trust_remote_code: bool = field(
default=False,
metadata={
"help": (
- "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
- "with private models)."
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
)
},
)
@@ -238,6 +255,12 @@ def main():
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_clm", model_args, data_args)
@@ -263,7 +286,7 @@ def main():
# Log on each process the small summary:
logger.warning(
f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
- + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
+ + f"distributed training: {training_args.parallel_mode.value == 'distributed'}, 16-bits training: {training_args.fp16}"
)
logger.info(f"Training/evaluation parameters {training_args}")
@@ -300,7 +323,7 @@ def main():
data_args.dataset_name,
data_args.dataset_config_name,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
streaming=data_args.streaming,
)
if "validation" not in raw_datasets.keys():
@@ -309,7 +332,7 @@ def main():
data_args.dataset_config_name,
split=f"train[:{data_args.validation_split_percentage}%]",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
streaming=data_args.streaming,
)
raw_datasets["train"] = load_dataset(
@@ -317,7 +340,7 @@ def main():
data_args.dataset_config_name,
split=f"train[{data_args.validation_split_percentage}%:]",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
streaming=data_args.streaming,
)
else:
@@ -339,7 +362,7 @@ def main():
extension,
data_files=data_files,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
**dataset_args,
)
# If no validation data is there, validation_split_percentage will be used to divide the dataset.
@@ -349,7 +372,7 @@ def main():
data_files=data_files,
split=f"train[:{data_args.validation_split_percentage}%]",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
**dataset_args,
)
raw_datasets["train"] = load_dataset(
@@ -357,7 +380,7 @@ def main():
data_files=data_files,
split=f"train[{data_args.validation_split_percentage}%:]",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
**dataset_args,
)
@@ -373,7 +396,8 @@ def main():
config_kwargs = {
"cache_dir": model_args.cache_dir,
"revision": model_args.model_revision,
- "use_auth_token": True if model_args.use_auth_token else None,
+ "token": model_args.token,
+ "trust_remote_code": model_args.trust_remote_code,
}
if model_args.config_name:
config = AutoConfig.from_pretrained(model_args.config_name, **config_kwargs)
@@ -391,7 +415,8 @@ def main():
"cache_dir": model_args.cache_dir,
"use_fast": model_args.use_fast_tokenizer,
"revision": model_args.model_revision,
- "use_auth_token": True if model_args.use_auth_token else None,
+ "token": model_args.token,
+ "trust_remote_code": model_args.trust_remote_code,
}
if model_args.tokenizer_name:
tokenizer = AutoTokenizer.from_pretrained(model_args.tokenizer_name, **tokenizer_kwargs)
@@ -415,12 +440,13 @@ def main():
config=config,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
torch_dtype=torch_dtype,
low_cpu_mem_usage=model_args.low_cpu_mem_usage,
)
else:
- model = AutoModelForCausalLM.from_config(config)
+ model = AutoModelForCausalLM.from_config(config, trust_remote_code=model_args.trust_remote_code)
n_params = sum({p.data_ptr(): p.numel() for p in model.parameters()}.values())
logger.info(f"Training new model from scratch - Total size={n_params/2**20:.2f}M params")
@@ -491,10 +517,9 @@ def group_texts(examples):
# Concatenate all texts.
concatenated_examples = {k: list(chain(*examples[k])) for k in examples.keys()}
total_length = len(concatenated_examples[list(examples.keys())[0]])
- # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can
- # customize this part to your needs.
- if total_length >= block_size:
- total_length = (total_length // block_size) * block_size
+ # We drop the small remainder, and if the total_length < block_size we exclude this batch and return an empty dict.
+ # We could add padding if the model supported it instead of this drop, you can customize this part to your needs.
+ total_length = (total_length // block_size) * block_size
# Split by chunks of max_len.
result = {
k: [t[i : i + block_size] for i in range(0, total_length, block_size)]
diff --git a/examples/pytorch/language-modeling/run_clm_no_trainer.py b/examples/pytorch/language-modeling/run_clm_no_trainer.py
index 4bb750a0b024..f3252e0dc759 100755
--- a/examples/pytorch/language-modeling/run_clm_no_trainer.py
+++ b/examples/pytorch/language-modeling/run_clm_no_trainer.py
@@ -52,12 +52,12 @@
default_data_collator,
get_scheduler,
)
-from transformers.utils import check_min_version, get_full_repo_name, send_example_telemetry
+from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
-check_min_version("4.29.0.dev0")
+check_min_version("4.32.0.dev0")
logger = get_logger(__name__)
@@ -82,10 +82,10 @@ def parse_args():
help="The configuration name of the dataset to use (via the datasets library).",
)
parser.add_argument(
- "--train_file", type=str, default=None, help="A csv or a json file containing the training data."
+ "--train_file", type=str, default=None, help="A csv, txt or a json file containing the training data."
)
parser.add_argument(
- "--validation_file", type=str, default=None, help="A csv or a json file containing the validation data."
+ "--validation_file", type=str, default=None, help="A csv, txt or a json file containing the validation data."
)
parser.add_argument(
"--validation_split_percentage",
@@ -193,6 +193,16 @@ def parse_args():
"--hub_model_id", type=str, help="The name of the repository to keep in sync with the local `output_dir`."
)
parser.add_argument("--hub_token", type=str, help="The token to use to push to the Model Hub.")
+ parser.add_argument(
+ "--trust_remote_code",
+ type=bool,
+ default=False,
+ help=(
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
+ ),
+ )
parser.add_argument(
"--checkpointing_steps",
type=str,
@@ -261,7 +271,7 @@ def main():
if args.with_tracking:
accelerator_log_kwargs["log_with"] = args.report_to
- accelerator_log_kwargs["logging_dir"] = args.output_dir
+ accelerator_log_kwargs["project_dir"] = args.output_dir
accelerator = Accelerator(gradient_accumulation_steps=args.gradient_accumulation_steps, **accelerator_log_kwargs)
@@ -286,12 +296,14 @@ def main():
# Handle the repository creation
if accelerator.is_main_process:
if args.push_to_hub:
- if args.hub_model_id is None:
- repo_name = get_full_repo_name(Path(args.output_dir).name, token=args.hub_token)
- else:
- repo_name = args.hub_model_id
- create_repo(repo_name, exist_ok=True, token=args.hub_token)
- repo = Repository(args.output_dir, clone_from=repo_name, token=args.hub_token)
+ # Retrieve of infer repo_name
+ repo_name = args.hub_model_id
+ if repo_name is None:
+ repo_name = Path(args.output_dir).absolute().name
+ # Create repo and retrieve repo_id
+ repo_id = create_repo(repo_name, exist_ok=True, token=args.hub_token).repo_id
+ # Clone repo locally
+ repo = Repository(args.output_dir, clone_from=repo_id, token=args.hub_token)
with open(os.path.join(args.output_dir, ".gitignore"), "w+") as gitignore:
if "step_*" not in gitignore:
@@ -360,17 +372,27 @@ def main():
# In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
# download model & vocab.
if args.config_name:
- config = AutoConfig.from_pretrained(args.config_name)
+ config = AutoConfig.from_pretrained(
+ args.config_name,
+ trust_remote_code=args.trust_remote_code,
+ )
elif args.model_name_or_path:
- config = AutoConfig.from_pretrained(args.model_name_or_path)
+ config = AutoConfig.from_pretrained(
+ args.model_name_or_path,
+ trust_remote_code=args.trust_remote_code,
+ )
else:
config = CONFIG_MAPPING[args.model_type]()
logger.warning("You are instantiating a new config instance from scratch.")
if args.tokenizer_name:
- tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=not args.use_slow_tokenizer)
+ tokenizer = AutoTokenizer.from_pretrained(
+ args.tokenizer_name, use_fast=not args.use_slow_tokenizer, trust_remote_code=args.trust_remote_code
+ )
elif args.model_name_or_path:
- tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path, use_fast=not args.use_slow_tokenizer)
+ tokenizer = AutoTokenizer.from_pretrained(
+ args.model_name_or_path, use_fast=not args.use_slow_tokenizer, trust_remote_code=args.trust_remote_code
+ )
else:
raise ValueError(
"You are instantiating a new tokenizer from scratch. This is not supported by this script."
@@ -383,10 +405,11 @@ def main():
from_tf=bool(".ckpt" in args.model_name_or_path),
config=config,
low_cpu_mem_usage=args.low_cpu_mem_usage,
+ trust_remote_code=args.trust_remote_code,
)
else:
logger.info("Training new model from scratch")
- model = AutoModelForCausalLM.from_config(config)
+ model = AutoModelForCausalLM.from_config(config, trust_remote_code=args.trust_remote_code)
# We resize the embeddings only when necessary to avoid index errors. If you are creating a model from scratch
# on a small vocab and want a smaller embedding size, remove this test.
@@ -434,10 +457,9 @@ def group_texts(examples):
# Concatenate all texts.
concatenated_examples = {k: list(chain(*examples[k])) for k in examples.keys()}
total_length = len(concatenated_examples[list(examples.keys())[0]])
- # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can
- # customize this part to your needs.
- if total_length >= block_size:
- total_length = (total_length // block_size) * block_size
+ # We drop the small remainder, and if the total_length < block_size we exclude this batch and return an empty dict.
+ # We could add padding if the model supported it instead of this drop, you can customize this part to your needs.
+ total_length = (total_length // block_size) * block_size
# Split by chunks of max_len.
result = {
k: [t[i : i + block_size] for i in range(0, total_length, block_size)]
@@ -553,43 +575,45 @@ def group_texts(examples):
# Potentially load in the weights and states from a previous save
if args.resume_from_checkpoint:
if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
- accelerator.print(f"Resumed from checkpoint: {args.resume_from_checkpoint}")
- accelerator.load_state(args.resume_from_checkpoint)
+ checkpoint_path = args.resume_from_checkpoint
path = os.path.basename(args.resume_from_checkpoint)
else:
# Get the most recent checkpoint
dirs = [f.name for f in os.scandir(os.getcwd()) if f.is_dir()]
dirs.sort(key=os.path.getctime)
path = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last
+ checkpoint_path = path
+ path = os.path.basename(checkpoint_path)
+
+ accelerator.print(f"Resumed from checkpoint: {checkpoint_path}")
+ accelerator.load_state(path)
# Extract `epoch_{i}` or `step_{i}`
training_difference = os.path.splitext(path)[0]
if "epoch" in training_difference:
starting_epoch = int(training_difference.replace("epoch_", "")) + 1
resume_step = None
+ completed_steps = starting_epoch * num_update_steps_per_epoch
else:
# need to multiply `gradient_accumulation_steps` to reflect real steps
resume_step = int(training_difference.replace("step_", "")) * args.gradient_accumulation_steps
starting_epoch = resume_step // len(train_dataloader)
resume_step -= starting_epoch * len(train_dataloader)
+ completed_steps = resume_step // args.gradient_accumulation_steps
# update the progress_bar if load from checkpoint
- progress_bar.update(starting_epoch * num_update_steps_per_epoch)
- completed_steps = starting_epoch * num_update_steps_per_epoch
+ progress_bar.update(completed_steps)
for epoch in range(starting_epoch, args.num_train_epochs):
model.train()
if args.with_tracking:
total_loss = 0
- for step, batch in enumerate(train_dataloader):
- # We need to skip steps until we reach the resumed step
- if args.resume_from_checkpoint and epoch == starting_epoch:
- if resume_step is not None and step < resume_step:
- if step % args.gradient_accumulation_steps == 0:
- progress_bar.update(1)
- completed_steps += 1
- continue
-
+ if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None:
+ # We skip the first `n` batches in the dataloader when resuming from a checkpoint
+ active_dataloader = accelerator.skip_first_batches(train_dataloader, resume_step)
+ else:
+ active_dataloader = train_dataloader
+ for step, batch in enumerate(active_dataloader):
with accelerator.accumulate(model):
outputs = model(**batch)
loss = outputs.loss
diff --git a/examples/pytorch/language-modeling/run_mlm.py b/examples/pytorch/language-modeling/run_mlm.py
index 7b8d67980251..84347804dbbb 100755
--- a/examples/pytorch/language-modeling/run_mlm.py
+++ b/examples/pytorch/language-modeling/run_mlm.py
@@ -25,6 +25,7 @@
import math
import os
import sys
+import warnings
from dataclasses import dataclass, field
from itertools import chain
from typing import Optional
@@ -53,7 +54,7 @@
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
-check_min_version("4.29.0.dev0")
+check_min_version("4.32.0.dev0")
require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/language-modeling/requirements.txt")
@@ -107,12 +108,28 @@ class ModelArguments:
default="main",
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
)
+ token: str = field(
+ default=None,
+ metadata={
+ "help": (
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
+ )
+ },
+ )
use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
+ trust_remote_code: bool = field(
default=False,
metadata={
"help": (
- "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
- "with private models)."
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
)
},
)
@@ -238,6 +255,12 @@ def main():
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_mlm", model_args, data_args)
@@ -263,7 +286,7 @@ def main():
# Log on each process the small summary:
logger.warning(
f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
- + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
+ + f"distributed training: {training_args.parallel_mode.value == 'distributed'}, 16-bits training: {training_args.fp16}"
)
# Set the verbosity to info of the Transformers logger (on main process only):
logger.info(f"Training/evaluation parameters {training_args}")
@@ -301,7 +324,7 @@ def main():
data_args.dataset_name,
data_args.dataset_config_name,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
streaming=data_args.streaming,
)
if "validation" not in raw_datasets.keys():
@@ -310,7 +333,7 @@ def main():
data_args.dataset_config_name,
split=f"train[:{data_args.validation_split_percentage}%]",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
streaming=data_args.streaming,
)
raw_datasets["train"] = load_dataset(
@@ -318,7 +341,7 @@ def main():
data_args.dataset_config_name,
split=f"train[{data_args.validation_split_percentage}%:]",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
streaming=data_args.streaming,
)
else:
@@ -335,7 +358,7 @@ def main():
extension,
data_files=data_files,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
# If no validation data is there, validation_split_percentage will be used to divide the dataset.
@@ -345,14 +368,14 @@ def main():
data_files=data_files,
split=f"train[:{data_args.validation_split_percentage}%]",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
raw_datasets["train"] = load_dataset(
extension,
data_files=data_files,
split=f"train[{data_args.validation_split_percentage}%:]",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
@@ -366,7 +389,8 @@ def main():
config_kwargs = {
"cache_dir": model_args.cache_dir,
"revision": model_args.model_revision,
- "use_auth_token": True if model_args.use_auth_token else None,
+ "token": model_args.token,
+ "trust_remote_code": model_args.trust_remote_code,
}
if model_args.config_name:
config = AutoConfig.from_pretrained(model_args.config_name, **config_kwargs)
@@ -384,7 +408,8 @@ def main():
"cache_dir": model_args.cache_dir,
"use_fast": model_args.use_fast_tokenizer,
"revision": model_args.model_revision,
- "use_auth_token": True if model_args.use_auth_token else None,
+ "token": model_args.token,
+ "trust_remote_code": model_args.trust_remote_code,
}
if model_args.tokenizer_name:
tokenizer = AutoTokenizer.from_pretrained(model_args.tokenizer_name, **tokenizer_kwargs)
@@ -403,12 +428,13 @@ def main():
config=config,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
low_cpu_mem_usage=model_args.low_cpu_mem_usage,
)
else:
logger.info("Training new model from scratch")
- model = AutoModelForMaskedLM.from_config(config)
+ model = AutoModelForMaskedLM.from_config(config, trust_remote_code=model_args.trust_remote_code)
# We resize the embeddings only when necessary to avoid index errors. If you are creating a model from scratch
# on a small vocab and want a smaller embedding size, remove this test.
@@ -506,10 +532,9 @@ def group_texts(examples):
# Concatenate all texts.
concatenated_examples = {k: list(chain(*examples[k])) for k in examples.keys()}
total_length = len(concatenated_examples[list(examples.keys())[0]])
- # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can
- # customize this part to your needs.
- if total_length >= max_seq_length:
- total_length = (total_length // max_seq_length) * max_seq_length
+ # We drop the small remainder, and if the total_length < max_seq_length we exclude this batch and return an empty dict.
+ # We could add padding if the model supported it instead of this drop, you can customize this part to your needs.
+ total_length = (total_length // max_seq_length) * max_seq_length
# Split by chunks of max_len.
result = {
k: [t[i : i + max_seq_length] for i in range(0, total_length, max_seq_length)]
diff --git a/examples/pytorch/language-modeling/run_mlm_no_trainer.py b/examples/pytorch/language-modeling/run_mlm_no_trainer.py
index 9334de8c0331..863a74ab2b36 100755
--- a/examples/pytorch/language-modeling/run_mlm_no_trainer.py
+++ b/examples/pytorch/language-modeling/run_mlm_no_trainer.py
@@ -52,12 +52,12 @@
SchedulerType,
get_scheduler,
)
-from transformers.utils import check_min_version, get_full_repo_name, send_example_telemetry
+from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
-check_min_version("4.29.0.dev0")
+check_min_version("4.32.0.dev0")
logger = get_logger(__name__)
require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/language-modeling/requirements.txt")
@@ -200,6 +200,16 @@ def parse_args():
"--hub_model_id", type=str, help="The name of the repository to keep in sync with the local `output_dir`."
)
parser.add_argument("--hub_token", type=str, help="The token to use to push to the Model Hub.")
+ parser.add_argument(
+ "--trust_remote_code",
+ type=bool,
+ default=False,
+ help=(
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
+ ),
+ )
parser.add_argument(
"--checkpointing_steps",
type=str,
@@ -270,7 +280,7 @@ def main():
if args.with_tracking:
accelerator_log_kwargs["log_with"] = args.report_to
- accelerator_log_kwargs["logging_dir"] = args.output_dir
+ accelerator_log_kwargs["project_dir"] = args.output_dir
accelerator = Accelerator(gradient_accumulation_steps=args.gradient_accumulation_steps, **accelerator_log_kwargs)
@@ -295,12 +305,14 @@ def main():
# Handle the repository creation
if accelerator.is_main_process:
if args.push_to_hub:
- if args.hub_model_id is None:
- repo_name = get_full_repo_name(Path(args.output_dir).name, token=args.hub_token)
- else:
- repo_name = args.hub_model_id
- create_repo(repo_name, exist_ok=True, token=args.hub_token)
- repo = Repository(args.output_dir, clone_from=repo_name, token=args.hub_token)
+ # Retrieve of infer repo_name
+ repo_name = args.hub_model_id
+ if repo_name is None:
+ repo_name = Path(args.output_dir).absolute().name
+ # Create repo and retrieve repo_id
+ repo_id = create_repo(repo_name, exist_ok=True, token=args.hub_token).repo_id
+ # Clone repo locally
+ repo = Repository(args.output_dir, clone_from=repo_id, token=args.hub_token)
with open(os.path.join(args.output_dir, ".gitignore"), "w+") as gitignore:
if "step_*" not in gitignore:
@@ -365,17 +377,21 @@ def main():
# In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
# download model & vocab.
if args.config_name:
- config = AutoConfig.from_pretrained(args.config_name)
+ config = AutoConfig.from_pretrained(args.config_name, trust_remote_code=args.trust_remote_code)
elif args.model_name_or_path:
- config = AutoConfig.from_pretrained(args.model_name_or_path)
+ config = AutoConfig.from_pretrained(args.model_name_or_path, trust_remote_code=args.trust_remote_code)
else:
config = CONFIG_MAPPING[args.model_type]()
logger.warning("You are instantiating a new config instance from scratch.")
if args.tokenizer_name:
- tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=not args.use_slow_tokenizer)
+ tokenizer = AutoTokenizer.from_pretrained(
+ args.tokenizer_name, use_fast=not args.use_slow_tokenizer, trust_remote_code=args.trust_remote_code
+ )
elif args.model_name_or_path:
- tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path, use_fast=not args.use_slow_tokenizer)
+ tokenizer = AutoTokenizer.from_pretrained(
+ args.model_name_or_path, use_fast=not args.use_slow_tokenizer, trust_remote_code=args.trust_remote_code
+ )
else:
raise ValueError(
"You are instantiating a new tokenizer from scratch. This is not supported by this script."
@@ -388,10 +404,11 @@ def main():
from_tf=bool(".ckpt" in args.model_name_or_path),
config=config,
low_cpu_mem_usage=args.low_cpu_mem_usage,
+ trust_remote_code=args.trust_remote_code,
)
else:
logger.info("Training new model from scratch")
- model = AutoModelForMaskedLM.from_config(config)
+ model = AutoModelForMaskedLM.from_config(config, trust_remote_code=args.trust_remote_code)
# We resize the embeddings only when necessary to avoid index errors. If you are creating a model from scratch
# on a small vocab and want a smaller embedding size, remove this test.
@@ -472,10 +489,9 @@ def group_texts(examples):
# Concatenate all texts.
concatenated_examples = {k: list(chain(*examples[k])) for k in examples.keys()}
total_length = len(concatenated_examples[list(examples.keys())[0]])
- # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can
- # customize this part to your needs.
- if total_length >= max_seq_length:
- total_length = (total_length // max_seq_length) * max_seq_length
+ # We drop the small remainder, and if the total_length < max_seq_length we exclude this batch and return an empty dict.
+ # We could add padding if the model supported it instead of this drop, you can customize this part to your needs.
+ total_length = (total_length // max_seq_length) * max_seq_length
# Split by chunks of max_len.
result = {
k: [t[i : i + max_seq_length] for i in range(0, total_length, max_seq_length)]
@@ -597,43 +613,45 @@ def group_texts(examples):
# Potentially load in the weights and states from a previous save
if args.resume_from_checkpoint:
if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
- accelerator.print(f"Resumed from checkpoint: {args.resume_from_checkpoint}")
- accelerator.load_state(args.resume_from_checkpoint)
+ checkpoint_path = args.resume_from_checkpoint
path = os.path.basename(args.resume_from_checkpoint)
else:
# Get the most recent checkpoint
dirs = [f.name for f in os.scandir(os.getcwd()) if f.is_dir()]
dirs.sort(key=os.path.getctime)
path = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last
+ checkpoint_path = path
+ path = os.path.basename(checkpoint_path)
+
+ accelerator.print(f"Resumed from checkpoint: {checkpoint_path}")
+ accelerator.load_state(path)
# Extract `epoch_{i}` or `step_{i}`
training_difference = os.path.splitext(path)[0]
if "epoch" in training_difference:
starting_epoch = int(training_difference.replace("epoch_", "")) + 1
resume_step = None
+ completed_steps = starting_epoch * num_update_steps_per_epoch
else:
# need to multiply `gradient_accumulation_steps` to reflect real steps
resume_step = int(training_difference.replace("step_", "")) * args.gradient_accumulation_steps
starting_epoch = resume_step // len(train_dataloader)
resume_step -= starting_epoch * len(train_dataloader)
+ completed_steps = resume_step // args.gradient_accumulation_steps
# update the progress_bar if load from checkpoint
- progress_bar.update(starting_epoch * num_update_steps_per_epoch)
- completed_steps = starting_epoch * num_update_steps_per_epoch
+ progress_bar.update(completed_steps)
for epoch in range(starting_epoch, args.num_train_epochs):
model.train()
if args.with_tracking:
total_loss = 0
- for step, batch in enumerate(train_dataloader):
- # We need to skip steps until we reach the resumed step
- if args.resume_from_checkpoint and epoch == starting_epoch:
- if resume_step is not None and step < resume_step:
- if step % args.gradient_accumulation_steps == 0:
- progress_bar.update(1)
- completed_steps += 1
- continue
-
+ if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None:
+ # We skip the first `n` batches in the dataloader when resuming from a checkpoint
+ active_dataloader = accelerator.skip_first_batches(train_dataloader, resume_step)
+ else:
+ active_dataloader = train_dataloader
+ for step, batch in enumerate(active_dataloader):
with accelerator.accumulate(model):
outputs = model(**batch)
loss = outputs.loss
diff --git a/examples/pytorch/language-modeling/run_plm.py b/examples/pytorch/language-modeling/run_plm.py
index ab955d5b941a..30ac5d422578 100755
--- a/examples/pytorch/language-modeling/run_plm.py
+++ b/examples/pytorch/language-modeling/run_plm.py
@@ -22,6 +22,7 @@
import math
import os
import sys
+import warnings
from dataclasses import dataclass, field
from itertools import chain
from typing import Optional
@@ -47,7 +48,7 @@
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
-check_min_version("4.29.0.dev0")
+check_min_version("4.32.0.dev0")
require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/language-modeling/requirements.txt")
@@ -95,15 +96,21 @@ class ModelArguments:
default="main",
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
)
- use_auth_token: bool = field(
- default=False,
+ token: str = field(
+ default=None,
metadata={
"help": (
- "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
- "with private models)."
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
)
},
)
+ use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
low_cpu_mem_usage: bool = field(
default=False,
metadata={
@@ -229,6 +236,12 @@ def main():
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_plm", model_args, data_args)
@@ -254,7 +267,7 @@ def main():
# Log on each process the small summary:
logger.warning(
f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
- + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
+ + f"distributed training: {training_args.parallel_mode.value == 'distributed'}, 16-bits training: {training_args.fp16}"
)
logger.info(f"Training/evaluation parameters {training_args}")
@@ -291,7 +304,7 @@ def main():
data_args.dataset_name,
data_args.dataset_config_name,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
if "validation" not in raw_datasets.keys():
raw_datasets["validation"] = load_dataset(
@@ -299,14 +312,14 @@ def main():
data_args.dataset_config_name,
split=f"train[:{data_args.validation_split_percentage}%]",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
raw_datasets["train"] = load_dataset(
data_args.dataset_name,
data_args.dataset_config_name,
split=f"train[{data_args.validation_split_percentage}%:]",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
else:
data_files = {}
@@ -325,14 +338,14 @@ def main():
data_files=data_files,
split=f"train[:{data_args.validation_split_percentage}%]",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
raw_datasets["train"] = load_dataset(
extension,
data_files=data_files,
split=f"train[{data_args.validation_split_percentage}%:]",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
@@ -346,7 +359,7 @@ def main():
config_kwargs = {
"cache_dir": model_args.cache_dir,
"revision": model_args.model_revision,
- "use_auth_token": True if model_args.use_auth_token else None,
+ "token": model_args.token,
}
if model_args.config_name:
config = AutoConfig.from_pretrained(model_args.config_name, **config_kwargs)
@@ -364,7 +377,7 @@ def main():
"cache_dir": model_args.cache_dir,
"use_fast": model_args.use_fast_tokenizer,
"revision": model_args.model_revision,
- "use_auth_token": True if model_args.use_auth_token else None,
+ "token": model_args.token,
}
if model_args.tokenizer_name:
tokenizer = AutoTokenizer.from_pretrained(model_args.tokenizer_name, **tokenizer_kwargs)
@@ -383,7 +396,7 @@ def main():
config=config,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
low_cpu_mem_usage=model_args.low_cpu_mem_usage,
)
else:
@@ -450,10 +463,9 @@ def group_texts(examples):
# Concatenate all texts.
concatenated_examples = {k: list(chain(*examples[k])) for k in examples.keys()}
total_length = len(concatenated_examples[list(examples.keys())[0]])
- # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can
- # customize this part to your needs.
- if total_length >= max_seq_length:
- total_length = (total_length // max_seq_length) * max_seq_length
+ # We drop the small remainder, and if the total_length < max_seq_length we exclude this batch and return an empty dict.
+ # We could add padding if the model supported it instead of this drop, you can customize this part to your needs.
+ total_length = (total_length // max_seq_length) * max_seq_length
# Split by chunks of max_len.
result = {
k: [t[i : i + max_seq_length] for i in range(0, total_length, max_seq_length)]
diff --git a/examples/pytorch/multiple-choice/README.md b/examples/pytorch/multiple-choice/README.md
index 735d1f5f33a0..8d56ccfe3dbd 100644
--- a/examples/pytorch/multiple-choice/README.md
+++ b/examples/pytorch/multiple-choice/README.md
@@ -28,7 +28,7 @@ python examples/multiple-choice/run_swag.py \
--learning_rate 5e-5 \
--num_train_epochs 3 \
--output_dir /tmp/swag_base \
---per_gpu_eval_batch_size=16 \
+--per_device_eval_batch_size=16 \
--per_device_train_batch_size=16 \
--overwrite_output
```
diff --git a/examples/pytorch/multiple-choice/run_swag.py b/examples/pytorch/multiple-choice/run_swag.py
index a0660f0085f3..d5f4be569956 100755
--- a/examples/pytorch/multiple-choice/run_swag.py
+++ b/examples/pytorch/multiple-choice/run_swag.py
@@ -21,6 +21,7 @@
import logging
import os
import sys
+import warnings
from dataclasses import dataclass, field
from itertools import chain
from typing import Optional, Union
@@ -47,7 +48,7 @@
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
-check_min_version("4.29.0.dev0")
+check_min_version("4.32.0.dev0")
logger = logging.getLogger(__name__)
@@ -79,12 +80,28 @@ class ModelArguments:
default="main",
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
)
+ token: str = field(
+ default=None,
+ metadata={
+ "help": (
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
+ )
+ },
+ )
use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
+ trust_remote_code: bool = field(
default=False,
metadata={
"help": (
- "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
- "with private models)."
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
)
},
)
@@ -225,6 +242,12 @@ def main():
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_swag", model_args, data_args)
@@ -250,7 +273,7 @@ def main():
# Log on each process the small summary:
logger.warning(
f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
- + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
+ + f"distributed training: {training_args.parallel_mode.value == 'distributed'}, 16-bits training: {training_args.fp16}"
)
logger.info(f"Training/evaluation parameters {training_args}")
@@ -292,7 +315,7 @@ def main():
extension,
data_files=data_files,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
else:
# Downloading and loading the swag dataset from the hub.
@@ -300,7 +323,7 @@ def main():
"swag",
"regular",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
# https://huggingface.co/docs/datasets/loading_datasets.html.
@@ -314,14 +337,16 @@ def main():
model_args.config_name if model_args.config_name else model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
tokenizer = AutoTokenizer.from_pretrained(
model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
use_fast=model_args.use_fast_tokenizer,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
model = AutoModelForMultipleChoice.from_pretrained(
model_args.model_name_or_path,
@@ -329,7 +354,8 @@ def main():
config=config,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
# When using your own dataset or a different dataset from swag, you will probably need to change this.
diff --git a/examples/pytorch/multiple-choice/run_swag_no_trainer.py b/examples/pytorch/multiple-choice/run_swag_no_trainer.py
index 6d3987c8feb4..be7498503235 100755
--- a/examples/pytorch/multiple-choice/run_swag_no_trainer.py
+++ b/examples/pytorch/multiple-choice/run_swag_no_trainer.py
@@ -52,11 +52,11 @@
default_data_collator,
get_scheduler,
)
-from transformers.utils import PaddingStrategy, check_min_version, get_full_repo_name, send_example_telemetry
+from transformers.utils import PaddingStrategy, check_min_version, send_example_telemetry
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
-check_min_version("4.29.0.dev0")
+check_min_version("4.32.0.dev0")
logger = get_logger(__name__)
# You should update this to your particular problem to have better documentation of `model_type`
@@ -182,6 +182,16 @@ def parse_args():
"--hub_model_id", type=str, help="The name of the repository to keep in sync with the local `output_dir`."
)
parser.add_argument("--hub_token", type=str, help="The token to use to push to the Model Hub.")
+ parser.add_argument(
+ "--trust_remote_code",
+ type=bool,
+ default=False,
+ help=(
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
+ ),
+ )
parser.add_argument(
"--checkpointing_steps",
type=str,
@@ -288,7 +298,7 @@ def main():
if args.with_tracking:
accelerator_log_kwargs["log_with"] = args.report_to
- accelerator_log_kwargs["logging_dir"] = args.output_dir
+ accelerator_log_kwargs["project_dir"] = args.output_dir
accelerator = Accelerator(gradient_accumulation_steps=args.gradient_accumulation_steps, **accelerator_log_kwargs)
@@ -313,12 +323,14 @@ def main():
# Handle the repository creation
if accelerator.is_main_process:
if args.push_to_hub:
- if args.hub_model_id is None:
- repo_name = get_full_repo_name(Path(args.output_dir).name, token=args.hub_token)
- else:
- repo_name = args.hub_model_id
- create_repo(repo_name, exist_ok=True, token=args.hub_token)
- repo = Repository(args.output_dir, clone_from=repo_name, token=args.hub_token)
+ # Retrieve of infer repo_name
+ repo_name = args.hub_model_id
+ if repo_name is None:
+ repo_name = Path(args.output_dir).absolute().name
+ # Create repo and retrieve repo_id
+ repo_id = create_repo(repo_name, exist_ok=True, token=args.hub_token).repo_id
+ # Clone repo locally
+ repo = Repository(args.output_dir, clone_from=repo_id, token=args.hub_token)
with open(os.path.join(args.output_dir, ".gitignore"), "w+") as gitignore:
if "step_*" not in gitignore:
@@ -372,17 +384,21 @@ def main():
# In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
# download model & vocab.
if args.config_name:
- config = AutoConfig.from_pretrained(args.model_name_or_path)
+ config = AutoConfig.from_pretrained(args.model_name_or_path, trust_remote_code=args.trust_remote_code)
elif args.model_name_or_path:
- config = AutoConfig.from_pretrained(args.model_name_or_path)
+ config = AutoConfig.from_pretrained(args.model_name_or_path, trust_remote_code=args.trust_remote_code)
else:
config = CONFIG_MAPPING[args.model_type]()
logger.warning("You are instantiating a new config instance from scratch.")
if args.tokenizer_name:
- tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=not args.use_slow_tokenizer)
+ tokenizer = AutoTokenizer.from_pretrained(
+ args.tokenizer_name, use_fast=not args.use_slow_tokenizer, trust_remote_code=args.trust_remote_code
+ )
elif args.model_name_or_path:
- tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path, use_fast=not args.use_slow_tokenizer)
+ tokenizer = AutoTokenizer.from_pretrained(
+ args.model_name_or_path, use_fast=not args.use_slow_tokenizer, trust_remote_code=args.trust_remote_code
+ )
else:
raise ValueError(
"You are instantiating a new tokenizer from scratch. This is not supported by this script."
@@ -394,10 +410,11 @@ def main():
args.model_name_or_path,
from_tf=bool(".ckpt" in args.model_name_or_path),
config=config,
+ trust_remote_code=args.trust_remote_code,
)
else:
logger.info("Training new model from scratch")
- model = AutoModelForMultipleChoice.from_config(config)
+ model = AutoModelForMultipleChoice.from_config(config, trust_remote_code=args.trust_remote_code)
# We resize the embeddings only when necessary to avoid index errors. If you are creating a model from scratch
# on a small vocab and want a smaller embedding size, remove this test.
@@ -543,36 +560,45 @@ def preprocess_function(examples):
# Potentially load in the weights and states from a previous save
if args.resume_from_checkpoint:
if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
- accelerator.print(f"Resumed from checkpoint: {args.resume_from_checkpoint}")
- accelerator.load_state(args.resume_from_checkpoint)
+ checkpoint_path = args.resume_from_checkpoint
path = os.path.basename(args.resume_from_checkpoint)
else:
# Get the most recent checkpoint
dirs = [f.name for f in os.scandir(os.getcwd()) if f.is_dir()]
dirs.sort(key=os.path.getctime)
path = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last
+ checkpoint_path = path
+ path = os.path.basename(checkpoint_path)
+
+ accelerator.print(f"Resumed from checkpoint: {checkpoint_path}")
+ accelerator.load_state(path)
# Extract `epoch_{i}` or `step_{i}`
training_difference = os.path.splitext(path)[0]
if "epoch" in training_difference:
starting_epoch = int(training_difference.replace("epoch_", "")) + 1
resume_step = None
+ completed_steps = starting_epoch * num_update_steps_per_epoch
else:
- resume_step = int(training_difference.replace("step_", ""))
+ # need to multiply `gradient_accumulation_steps` to reflect real steps
+ resume_step = int(training_difference.replace("step_", "")) * args.gradient_accumulation_steps
starting_epoch = resume_step // len(train_dataloader)
resume_step -= starting_epoch * len(train_dataloader)
+ completed_steps = resume_step // args.gradient_accumulation_stepp
+
+ # update the progress_bar if load from checkpoint
+ progress_bar.update(completed_steps)
for epoch in range(starting_epoch, args.num_train_epochs):
model.train()
if args.with_tracking:
total_loss = 0
- for step, batch in enumerate(train_dataloader):
- # We need to skip steps until we reach the resumed step
- if args.resume_from_checkpoint and epoch == starting_epoch:
- if resume_step is not None and step < resume_step:
- completed_steps += 1
- continue
-
+ if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None:
+ # We skip the first `n` batches in the dataloader when resuming from a checkpoint
+ active_dataloader = accelerator.skip_first_batches(train_dataloader, resume_step)
+ else:
+ active_dataloader = train_dataloader
+ for step, batch in enumerate(active_dataloader):
with accelerator.accumulate(model):
outputs = model(**batch)
loss = outputs.loss
diff --git a/examples/pytorch/test_xla_examples.py b/examples/pytorch/old_test_xla_examples.py
similarity index 100%
rename from examples/pytorch/test_xla_examples.py
rename to examples/pytorch/old_test_xla_examples.py
diff --git a/examples/pytorch/question-answering/run_qa.py b/examples/pytorch/question-answering/run_qa.py
index d3377611bdfd..76f836ece6d3 100755
--- a/examples/pytorch/question-answering/run_qa.py
+++ b/examples/pytorch/question-answering/run_qa.py
@@ -21,6 +21,7 @@
import logging
import os
import sys
+import warnings
from dataclasses import dataclass, field
from typing import Optional
@@ -49,7 +50,7 @@
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
-check_min_version("4.29.0.dev0")
+check_min_version("4.32.0.dev0")
require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/question-answering/requirements.txt")
@@ -79,12 +80,28 @@ class ModelArguments:
default="main",
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
)
+ token: str = field(
+ default=None,
+ metadata={
+ "help": (
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
+ )
+ },
+ )
use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
+ trust_remote_code: bool = field(
default=False,
metadata={
"help": (
- "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
- "with private models)."
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
)
},
)
@@ -227,6 +244,12 @@ def main():
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_qa", model_args, data_args)
@@ -252,7 +275,7 @@ def main():
# Log on each process the small summary:
logger.warning(
f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
- + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
+ + f"distributed training: {training_args.parallel_mode.value == 'distributed'}, 16-bits training: {training_args.fp16}"
)
logger.info(f"Training/evaluation parameters {training_args}")
@@ -289,7 +312,7 @@ def main():
data_args.dataset_name,
data_args.dataset_config_name,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
else:
data_files = {}
@@ -308,7 +331,7 @@ def main():
data_files=data_files,
field="data",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
# https://huggingface.co/docs/datasets/loading_datasets.html.
@@ -322,14 +345,16 @@ def main():
model_args.config_name if model_args.config_name else model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
tokenizer = AutoTokenizer.from_pretrained(
model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
use_fast=True,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
model = AutoModelForQuestionAnswering.from_pretrained(
model_args.model_name_or_path,
@@ -337,7 +362,8 @@ def main():
config=config,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
# Tokenizer check: this script requires a fast tokenizer.
@@ -590,12 +616,12 @@ def post_processing_function(examples, features, predictions, stage="eval"):
# Format the result to the format the metric expects.
if data_args.version_2_with_negative:
formatted_predictions = [
- {"id": k, "prediction_text": v, "no_answer_probability": 0.0} for k, v in predictions.items()
+ {"id": str(k), "prediction_text": v, "no_answer_probability": 0.0} for k, v in predictions.items()
]
else:
- formatted_predictions = [{"id": k, "prediction_text": v} for k, v in predictions.items()]
+ formatted_predictions = [{"id": str(k), "prediction_text": v} for k, v in predictions.items()]
- references = [{"id": ex["id"], "answers": ex[answer_column_name]} for ex in examples]
+ references = [{"id": str(ex["id"]), "answers": ex[answer_column_name]} for ex in examples]
return EvalPrediction(predictions=formatted_predictions, label_ids=references)
metric = evaluate.load("squad_v2" if data_args.version_2_with_negative else "squad")
diff --git a/examples/pytorch/question-answering/run_qa_beam_search.py b/examples/pytorch/question-answering/run_qa_beam_search.py
index fc4b0e0288be..c12dd53ab7aa 100755
--- a/examples/pytorch/question-answering/run_qa_beam_search.py
+++ b/examples/pytorch/question-answering/run_qa_beam_search.py
@@ -21,6 +21,7 @@
import logging
import os
import sys
+import warnings
from dataclasses import dataclass, field
from typing import Optional
@@ -48,7 +49,7 @@
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
-check_min_version("4.29.0.dev0")
+check_min_version("4.32.0.dev0")
require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/question-answering/requirements.txt")
@@ -78,15 +79,21 @@ class ModelArguments:
default="main",
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
)
- use_auth_token: bool = field(
- default=False,
+ token: str = field(
+ default=None,
metadata={
"help": (
- "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
- "with private models)."
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
)
},
)
+ use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
@dataclass
@@ -226,6 +233,12 @@ def main():
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_qa_beam_search", model_args, data_args)
@@ -251,7 +264,7 @@ def main():
# Log on each process the small summary:
logger.warning(
f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
- + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
+ + f"distributed training: {training_args.parallel_mode.value == 'distributed'}, 16-bits training: {training_args.fp16}"
)
logger.info(f"Training/evaluation parameters {training_args}")
@@ -288,7 +301,7 @@ def main():
data_args.dataset_name,
data_args.dataset_config_name,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
else:
data_files = {}
@@ -306,7 +319,7 @@ def main():
data_files=data_files,
field="data",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
# https://huggingface.co/docs/datasets/loading_datasets.html.
@@ -320,13 +333,13 @@ def main():
model_args.config_name if model_args.config_name else model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
tokenizer = XLNetTokenizerFast.from_pretrained(
model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
model = XLNetForQuestionAnswering.from_pretrained(
model_args.model_name_or_path,
@@ -334,7 +347,7 @@ def main():
config=config,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
# Preprocessing the datasets.
diff --git a/examples/pytorch/question-answering/run_qa_beam_search_no_trainer.py b/examples/pytorch/question-answering/run_qa_beam_search_no_trainer.py
index ba7e82cc6470..83a3b0357d2c 100644
--- a/examples/pytorch/question-answering/run_qa_beam_search_no_trainer.py
+++ b/examples/pytorch/question-answering/run_qa_beam_search_no_trainer.py
@@ -51,12 +51,12 @@
default_data_collator,
get_scheduler,
)
-from transformers.utils import check_min_version, get_full_repo_name, send_example_telemetry
+from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
-check_min_version("4.29.0.dev0")
+check_min_version("4.32.0.dev0")
require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/question-answering/requirements.txt")
@@ -303,7 +303,7 @@ def main():
if args.with_tracking:
accelerator_log_kwargs["log_with"] = args.report_to
- accelerator_log_kwargs["logging_dir"] = args.output_dir
+ accelerator_log_kwargs["project_dir"] = args.output_dir
accelerator = Accelerator(gradient_accumulation_steps=args.gradient_accumulation_steps, **accelerator_log_kwargs)
@@ -328,12 +328,14 @@ def main():
# Handle the repository creation
if accelerator.is_main_process:
if args.push_to_hub:
- if args.hub_model_id is None:
- repo_name = get_full_repo_name(Path(args.output_dir).name, token=args.hub_token)
- else:
- repo_name = args.hub_model_id
- create_repo(repo_name, exist_ok=True, token=args.hub_token)
- repo = Repository(args.output_dir, clone_from=repo_name, token=args.hub_token)
+ # Retrieve of infer repo_name
+ repo_name = args.hub_model_id
+ if repo_name is None:
+ repo_name = Path(args.output_dir).absolute().name
+ # Create repo and retrieve repo_id
+ repo_id = create_repo(repo_name, exist_ok=True, token=args.hub_token).repo_id
+ # Clone repo locally
+ repo = Repository(args.output_dir, clone_from=repo_id, token=args.hub_token)
with open(os.path.join(args.output_dir, ".gitignore"), "w+") as gitignore:
if "step_*" not in gitignore:
@@ -795,36 +797,45 @@ def create_and_fill_np_array(start_or_end_logits, dataset, max_len):
# Potentially load in the weights and states from a previous save
if args.resume_from_checkpoint:
if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
- accelerator.print(f"Resumed from checkpoint: {args.resume_from_checkpoint}")
- accelerator.load_state(args.resume_from_checkpoint)
+ checkpoint_path = args.resume_from_checkpoint
path = os.path.basename(args.resume_from_checkpoint)
else:
# Get the most recent checkpoint
dirs = [f.name for f in os.scandir(os.getcwd()) if f.is_dir()]
dirs.sort(key=os.path.getctime)
path = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last
+ checkpoint_path = path
+ path = os.path.basename(checkpoint_path)
+
+ accelerator.print(f"Resumed from checkpoint: {checkpoint_path}")
+ accelerator.load_state(path)
# Extract `epoch_{i}` or `step_{i}`
training_difference = os.path.splitext(path)[0]
if "epoch" in training_difference:
starting_epoch = int(training_difference.replace("epoch_", "")) + 1
resume_step = None
+ completed_steps = starting_epoch * num_update_steps_per_epoch
else:
- resume_step = int(training_difference.replace("step_", ""))
+ # need to multiply `gradient_accumulation_steps` to reflect real steps
+ resume_step = int(training_difference.replace("step_", "")) * args.gradient_accumulation_steps
starting_epoch = resume_step // len(train_dataloader)
resume_step -= starting_epoch * len(train_dataloader)
+ completed_steps = resume_step // args.gradient_accumulation_stepp
+
+ # update the progress_bar if load from checkpoint
+ progress_bar.update(completed_steps)
for epoch in range(starting_epoch, args.num_train_epochs):
model.train()
if args.with_tracking:
total_loss = 0
- for step, batch in enumerate(train_dataloader):
- # We need to skip steps until we reach the resumed step
- if args.resume_from_checkpoint and epoch == starting_epoch:
- if resume_step is not None and step < resume_step:
- completed_steps += 1
- continue
-
+ if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None:
+ # We skip the first `n` batches in the dataloader when resuming from a checkpoint
+ active_dataloader = accelerator.skip_first_batches(train_dataloader, resume_step)
+ else:
+ active_dataloader = train_dataloader
+ for step, batch in enumerate(active_dataloader):
with accelerator.accumulate(model):
outputs = model(**batch)
loss = outputs.loss
diff --git a/examples/pytorch/question-answering/run_qa_no_trainer.py b/examples/pytorch/question-answering/run_qa_no_trainer.py
index 67d9fb8b455d..920dd1664b9c 100755
--- a/examples/pytorch/question-answering/run_qa_no_trainer.py
+++ b/examples/pytorch/question-answering/run_qa_no_trainer.py
@@ -52,12 +52,12 @@
default_data_collator,
get_scheduler,
)
-from transformers.utils import check_min_version, get_full_repo_name, send_example_telemetry
+from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
-check_min_version("4.29.0.dev0")
+check_min_version("4.32.0.dev0")
require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/question-answering/requirements.txt")
@@ -273,6 +273,16 @@ def parse_args():
"--hub_model_id", type=str, help="The name of the repository to keep in sync with the local `output_dir`."
)
parser.add_argument("--hub_token", type=str, help="The token to use to push to the Model Hub.")
+ parser.add_argument(
+ "--trust_remote_code",
+ type=bool,
+ default=False,
+ help=(
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
+ ),
+ )
parser.add_argument(
"--checkpointing_steps",
type=str,
@@ -341,7 +351,7 @@ def main():
if args.with_tracking:
accelerator_log_kwargs["log_with"] = args.report_to
- accelerator_log_kwargs["logging_dir"] = args.output_dir
+ accelerator_log_kwargs["project_dir"] = args.output_dir
accelerator = Accelerator(gradient_accumulation_steps=args.gradient_accumulation_steps, **accelerator_log_kwargs)
@@ -366,12 +376,14 @@ def main():
# Handle the repository creation
if accelerator.is_main_process:
if args.push_to_hub:
- if args.hub_model_id is None:
- repo_name = get_full_repo_name(Path(args.output_dir).name, token=args.hub_token)
- else:
- repo_name = args.hub_model_id
- create_repo(repo_name, exist_ok=True, token=args.hub_token)
- repo = Repository(args.output_dir, clone_from=repo_name, token=args.hub_token)
+ # Retrieve of infer repo_name
+ repo_name = args.hub_model_id
+ if repo_name is None:
+ repo_name = Path(args.output_dir).absolute().name
+ # Create repo and retrieve repo_id
+ repo_id = create_repo(repo_name, exist_ok=True, token=args.hub_token).repo_id
+ # Clone repo locally
+ repo = Repository(args.output_dir, clone_from=repo_id, token=args.hub_token)
with open(os.path.join(args.output_dir, ".gitignore"), "w+") as gitignore:
if "step_*" not in gitignore:
@@ -413,17 +425,21 @@ def main():
# download model & vocab.
if args.config_name:
- config = AutoConfig.from_pretrained(args.config_name)
+ config = AutoConfig.from_pretrained(args.config_name, trust_remote_code=args.trust_remote_code)
elif args.model_name_or_path:
- config = AutoConfig.from_pretrained(args.model_name_or_path)
+ config = AutoConfig.from_pretrained(args.model_name_or_path, trust_remote_code=args.trust_remote_code)
else:
config = CONFIG_MAPPING[args.model_type]()
logger.warning("You are instantiating a new config instance from scratch.")
if args.tokenizer_name:
- tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=True)
+ tokenizer = AutoTokenizer.from_pretrained(
+ args.tokenizer_name, use_fast=True, trust_remote_code=args.trust_remote_code
+ )
elif args.model_name_or_path:
- tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path, use_fast=True)
+ tokenizer = AutoTokenizer.from_pretrained(
+ args.model_name_or_path, use_fast=True, trust_remote_code=args.trust_remote_code
+ )
else:
raise ValueError(
"You are instantiating a new tokenizer from scratch. This is not supported by this script."
@@ -435,10 +451,11 @@ def main():
args.model_name_or_path,
from_tf=bool(".ckpt" in args.model_name_or_path),
config=config,
+ trust_remote_code=args.trust_remote_code,
)
else:
logger.info("Training new model from scratch")
- model = AutoModelForQuestionAnswering.from_config(config)
+ model = AutoModelForQuestionAnswering.from_config(config, trust_remote_code=args.trust_remote_code)
# Preprocessing the datasets.
# Preprocessing is slighlty different for training and evaluation.
@@ -811,36 +828,44 @@ def create_and_fill_np_array(start_or_end_logits, dataset, max_len):
# Potentially load in the weights and states from a previous save
if args.resume_from_checkpoint:
if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
- accelerator.print(f"Resumed from checkpoint: {args.resume_from_checkpoint}")
- accelerator.load_state(args.resume_from_checkpoint)
+ checkpoint_path = args.resume_from_checkpoint
path = os.path.basename(args.resume_from_checkpoint)
else:
# Get the most recent checkpoint
dirs = [f.name for f in os.scandir(os.getcwd()) if f.is_dir()]
dirs.sort(key=os.path.getctime)
path = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last
+ checkpoint_path = path
+ path = os.path.basename(checkpoint_path)
+
+ accelerator.print(f"Resumed from checkpoint: {checkpoint_path}")
+ accelerator.load_state(path)
# Extract `epoch_{i}` or `step_{i}`
training_difference = os.path.splitext(path)[0]
if "epoch" in training_difference:
starting_epoch = int(training_difference.replace("epoch_", "")) + 1
resume_step = None
+ completed_steps = starting_epoch * num_update_steps_per_epoch
else:
resume_step = int(training_difference.replace("step_", ""))
starting_epoch = resume_step // len(train_dataloader)
resume_step -= starting_epoch * len(train_dataloader)
+ completed_steps = resume_step // args.gradient_accumulation_stepp
+
+ # update the progress_bar if load from checkpoint
+ progress_bar.update(completed_steps)
for epoch in range(starting_epoch, args.num_train_epochs):
model.train()
if args.with_tracking:
total_loss = 0
- for step, batch in enumerate(train_dataloader):
- # We need to skip steps until we reach the resumed step
- if args.resume_from_checkpoint and epoch == starting_epoch:
- if resume_step is not None and step < resume_step:
- completed_steps += 1
- continue
-
+ if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None:
+ # We skip the first `n` batches in the dataloader when resuming from a checkpoint
+ active_dataloader = accelerator.skip_first_batches(train_dataloader, resume_step)
+ else:
+ active_dataloader = train_dataloader
+ for step, batch in enumerate(active_dataloader):
with accelerator.accumulate(model):
outputs = model(**batch)
loss = outputs.loss
diff --git a/examples/pytorch/question-answering/run_seq2seq_qa.py b/examples/pytorch/question-answering/run_seq2seq_qa.py
index 3c0ac4dfbc22..404a27ba3aad 100644
--- a/examples/pytorch/question-answering/run_seq2seq_qa.py
+++ b/examples/pytorch/question-answering/run_seq2seq_qa.py
@@ -21,6 +21,7 @@
import logging
import os
import sys
+import warnings
from dataclasses import dataclass, field
from typing import List, Optional, Tuple
@@ -46,7 +47,7 @@
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
-check_min_version("4.29.0.dev0")
+check_min_version("4.32.0.dev0")
require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/question-answering/requirements.txt")
@@ -80,12 +81,28 @@ class ModelArguments:
default="main",
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
)
+ token: str = field(
+ default=None,
+ metadata={
+ "help": (
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
+ )
+ },
+ )
use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
+ trust_remote_code: bool = field(
default=False,
metadata={
"help": (
- "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
- "with private models)."
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
)
},
)
@@ -273,6 +290,12 @@ def main():
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_seq2seq_qa", model_args, data_args)
@@ -298,7 +321,7 @@ def main():
# Log on each process the small summary:
logger.warning(
f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
- + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
+ + f"distributed training: {training_args.parallel_mode.value == 'distributed'}, 16-bits training: {training_args.fp16}"
)
logger.info(f"Training/evaluation parameters {training_args}")
@@ -335,7 +358,7 @@ def main():
data_args.dataset_name,
data_args.dataset_config_name,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
else:
data_files = {}
@@ -353,7 +376,7 @@ def main():
data_files=data_files,
field="data",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
# https://huggingface.co/docs/datasets/loading_datasets.html.
@@ -367,14 +390,16 @@ def main():
model_args.config_name if model_args.config_name else model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
tokenizer = AutoTokenizer.from_pretrained(
model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
use_fast=model_args.use_fast_tokenizer,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
model = AutoModelForSeq2SeqLM.from_pretrained(
model_args.model_name_or_path,
@@ -382,7 +407,8 @@ def main():
config=config,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
# We resize the embeddings only when necessary to avoid index errors. If you are creating a model from scratch
diff --git a/examples/pytorch/semantic-segmentation/run_semantic_segmentation.py b/examples/pytorch/semantic-segmentation/run_semantic_segmentation.py
index e1027f5d67b4..a7bde9eb21d1 100644
--- a/examples/pytorch/semantic-segmentation/run_semantic_segmentation.py
+++ b/examples/pytorch/semantic-segmentation/run_semantic_segmentation.py
@@ -18,6 +18,7 @@
import os
import random
import sys
+import warnings
from dataclasses import dataclass, field
from typing import Optional
@@ -51,7 +52,7 @@
logger = logging.getLogger(__name__)
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
-check_min_version("4.29.0.dev0")
+check_min_version("4.32.0.dev0")
require_version("datasets>=2.0.0", "To fix: pip install -r examples/pytorch/semantic-segmentation/requirements.txt")
@@ -241,12 +242,28 @@ class ModelArguments:
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
)
image_processor_name: str = field(default=None, metadata={"help": "Name or path of preprocessor config."})
+ token: str = field(
+ default=None,
+ metadata={
+ "help": (
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
+ )
+ },
+ )
use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
+ trust_remote_code: bool = field(
default=False,
metadata={
"help": (
- "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
- "with private models)."
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
)
},
)
@@ -265,6 +282,12 @@ def main():
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_semantic_segmentation", model_args, data_args)
@@ -289,7 +312,7 @@ def main():
# Log on each process the small summary:
logger.warning(
f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
- + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
+ + f"distributed training: {training_args.parallel_mode.value == 'distributed'}, 16-bits training: {training_args.fp16}"
)
logger.info(f"Training/evaluation parameters {training_args}")
@@ -379,7 +402,8 @@ def compute_metrics(eval_pred):
id2label=id2label,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
model = AutoModelForSemanticSegmentation.from_pretrained(
model_args.model_name_or_path,
@@ -387,13 +411,15 @@ def compute_metrics(eval_pred):
config=config,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
image_processor = AutoImageProcessor.from_pretrained(
model_args.image_processor_name or model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
# Define torchvision transforms to be applied to each image + target.
diff --git a/examples/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py b/examples/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py
index 00d115646ac4..98bec7de43f7 100644
--- a/examples/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py
+++ b/examples/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py
@@ -45,12 +45,12 @@
default_data_collator,
get_scheduler,
)
-from transformers.utils import check_min_version, get_full_repo_name, send_example_telemetry
+from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
-check_min_version("4.29.0.dev0")
+check_min_version("4.32.0.dev0")
logger = get_logger(__name__)
@@ -273,6 +273,16 @@ def parse_args():
"--hub_model_id", type=str, help="The name of the repository to keep in sync with the local `output_dir`."
)
parser.add_argument("--hub_token", type=str, help="The token to use to push to the Model Hub.")
+ parser.add_argument(
+ "--trust_remote_code",
+ type=bool,
+ default=False,
+ help=(
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
+ ),
+ )
parser.add_argument(
"--checkpointing_steps",
type=str,
@@ -330,7 +340,7 @@ def main():
if args.with_tracking:
accelerator_log_kwargs["log_with"] = args.report_to
- accelerator_log_kwargs["logging_dir"] = args.output_dir
+ accelerator_log_kwargs["project_dir"] = args.output_dir
accelerator = Accelerator(gradient_accumulation_steps=args.gradient_accumulation_steps, **accelerator_log_kwargs)
@@ -350,12 +360,14 @@ def main():
# Handle the repository creation
if accelerator.is_main_process:
if args.push_to_hub:
- if args.hub_model_id is None:
- repo_name = get_full_repo_name(Path(args.output_dir).name, token=args.hub_token)
- else:
- repo_name = args.hub_model_id
- create_repo(repo_name, exist_ok=True, token=args.hub_token)
- repo = Repository(args.output_dir, clone_from=repo_name, token=args.hub_token)
+ # Retrieve of infer repo_name
+ repo_name = args.hub_model_id
+ if repo_name is None:
+ repo_name = Path(args.output_dir).absolute().name
+ # Create repo and retrieve repo_id
+ repo_id = create_repo(repo_name, exist_ok=True, token=args.hub_token).repo_id
+ # Clone repo locally
+ repo = Repository(args.output_dir, clone_from=repo_id, token=args.hub_token)
with open(os.path.join(args.output_dir, ".gitignore"), "w+") as gitignore:
if "step_*" not in gitignore:
@@ -398,9 +410,15 @@ def main():
label2id = {v: k for k, v in id2label.items()}
# Load pretrained model and image processor
- config = AutoConfig.from_pretrained(args.model_name_or_path, id2label=id2label, label2id=label2id)
- image_processor = AutoImageProcessor.from_pretrained(args.model_name_or_path)
- model = AutoModelForSemanticSegmentation.from_pretrained(args.model_name_or_path, config=config)
+ config = AutoConfig.from_pretrained(
+ args.model_name_or_path, id2label=id2label, label2id=label2id, trust_remote_code=args.trust_remote_code
+ )
+ image_processor = AutoImageProcessor.from_pretrained(
+ args.model_name_or_path, trust_remote_code=args.trust_remote_code
+ )
+ model = AutoModelForSemanticSegmentation.from_pretrained(
+ args.model_name_or_path, config=config, trust_remote_code=args.trust_remote_code
+ )
# Preprocessing the datasets
# Define torchvision transforms to be applied to each image + target.
@@ -540,36 +558,45 @@ def preprocess_val(example_batch):
# Potentially load in the weights and states from a previous save
if args.resume_from_checkpoint:
if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
- accelerator.print(f"Resumed from checkpoint: {args.resume_from_checkpoint}")
- accelerator.load_state(args.resume_from_checkpoint)
+ checkpoint_path = args.resume_from_checkpoint
path = os.path.basename(args.resume_from_checkpoint)
else:
# Get the most recent checkpoint
dirs = [f.name for f in os.scandir(os.getcwd()) if f.is_dir()]
dirs.sort(key=os.path.getctime)
path = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last
+ checkpoint_path = path
+ path = os.path.basename(checkpoint_path)
+
+ accelerator.print(f"Resumed from checkpoint: {checkpoint_path}")
+ accelerator.load_state(path)
# Extract `epoch_{i}` or `step_{i}`
training_difference = os.path.splitext(path)[0]
if "epoch" in training_difference:
starting_epoch = int(training_difference.replace("epoch_", "")) + 1
resume_step = None
+ completed_steps = starting_epoch * num_update_steps_per_epoch
else:
- resume_step = int(training_difference.replace("step_", ""))
+ # need to multiply `gradient_accumulation_steps` to reflect real steps
+ resume_step = int(training_difference.replace("step_", "")) * args.gradient_accumulation_steps
starting_epoch = resume_step // len(train_dataloader)
resume_step -= starting_epoch * len(train_dataloader)
+ completed_steps = resume_step // args.gradient_accumulation_stepp
+
+ # update the progress_bar if load from checkpoint
+ progress_bar.update(completed_steps)
for epoch in range(starting_epoch, args.num_train_epochs):
+ model.train()
if args.with_tracking:
total_loss = 0
- model.train()
- for step, batch in enumerate(train_dataloader):
- # We need to skip steps until we reach the resumed step
- if args.resume_from_checkpoint and epoch == starting_epoch:
- if resume_step is not None and step < resume_step:
- completed_steps += 1
- continue
-
+ if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None:
+ # We skip the first `n` batches in the dataloader when resuming from a checkpoint
+ active_dataloader = accelerator.skip_first_batches(train_dataloader, resume_step)
+ else:
+ active_dataloader = train_dataloader
+ for step, batch in enumerate(active_dataloader):
with accelerator.accumulate(model):
outputs = model(**batch)
loss = outputs.loss
@@ -682,7 +709,9 @@ def preprocess_val(example_batch):
if args.push_to_hub:
repo.push_to_hub(commit_message="End of training", auto_lfs_prune=True)
- all_results = {f"eval_{k}": v for k, v in eval_metrics.items()}
+ all_results = {
+ f"eval_{k}": v.tolist() if isinstance(v, np.ndarray) else v for k, v in eval_metrics.items()
+ }
with open(os.path.join(args.output_dir, "all_results.json"), "w") as f:
json.dump(all_results, f)
diff --git a/examples/pytorch/speech-pretraining/run_wav2vec2_pretraining_no_trainer.py b/examples/pytorch/speech-pretraining/run_wav2vec2_pretraining_no_trainer.py
index 603202e696cf..6bde6d2b7d0f 100755
--- a/examples/pytorch/speech-pretraining/run_wav2vec2_pretraining_no_trainer.py
+++ b/examples/pytorch/speech-pretraining/run_wav2vec2_pretraining_no_trainer.py
@@ -43,7 +43,7 @@
set_seed,
)
from transformers.models.wav2vec2.modeling_wav2vec2 import _compute_mask_indices, _sample_negative_indices
-from transformers.utils import get_full_repo_name, send_example_telemetry
+from transformers.utils import send_example_telemetry
logger = get_logger(__name__)
@@ -418,12 +418,14 @@ def main():
# Handle the repository creation
if accelerator.is_main_process:
if args.push_to_hub and not args.preprocessing_only:
- if args.hub_model_id is None:
- repo_name = get_full_repo_name(Path(args.output_dir).name, token=args.hub_token)
- else:
- repo_name = args.hub_model_id
- create_repo(repo_name, exist_ok=True, token=args.hub_token)
- repo = Repository(args.output_dir, clone_from=repo_name, token=args.hub_token)
+ # Retrieve of infer repo_name
+ repo_name = args.hub_model_id
+ if repo_name is None:
+ repo_name = Path(args.output_dir).absolute().name
+ # Create repo and retrieve repo_id
+ repo_id = create_repo(repo_name, exist_ok=True, token=args.hub_token).repo_id
+ # Clone repo locally
+ repo = Repository(args.output_dir, clone_from=repo_id, token=args.hub_token)
elif args.output_dir is not None:
os.makedirs(args.output_dir, exist_ok=True)
accelerator.wait_for_everyone()
diff --git a/examples/pytorch/speech-recognition/README.md b/examples/pytorch/speech-recognition/README.md
index cf5a05c01783..6ae2e1abef60 100644
--- a/examples/pytorch/speech-recognition/README.md
+++ b/examples/pytorch/speech-recognition/README.md
@@ -26,6 +26,10 @@ limitations under the License.
- [Librispeech](#librispeech-ctc)
- [Common Voice](#common-voice-ctc)
- [Multilingual Librispeech](#multilingual-librispeech-ctc)
+- [Automatic Speech Recognition with CTC and Adapter Layers](#connectionist-temporal-classification-with-adapters)
+ - [Massive Multilingual Speech (MMS)](#mms-model)
+ - [Examples](#examples-ctc-adapter)
+ - [Common Voice](#common-voice-ctc-adapter)
- [Automatic Speech Recognition with Sequence-to-Sequence](#sequence-to-sequence)
- [Whisper Model](#whisper-model)
- [Speech-Encoder-Decoder Model](#warm-started-speech-encoder-decoder-model)
@@ -243,6 +247,111 @@ they can serve as a baseline to improve upon.
| [Multilingual Librispeech](https://huggingface.co/datasets/multilingual_librispeech)| `"german"` | [facebook/wav2vec2-large-xlsr-53](https://huggingface.co/facebook/wav2vec2-large-xlsr-53) | 0.13 | - | 1 GPU Titan 24 GB RAM | 15h04 | [here](https://huggingface.co/patrickvonplaten/wav2vec2-xlsr-53-300m-mls-german-ft) | [run.sh](https://huggingface.co/patrickvonplaten/wav2vec2-xlsr-53-300m-mls-german-ft/blob/main/run.sh) |
| [Multilingual Librispeech](https://huggingface.co/datasets/multilingual_librispeech)| `"german"` | [facebook/wav2vec2-xls-r-300m](https://huggingface.co/facebook/wav2vec2-xls-r-300m) | 0.15 | - | 1 GPU Titan 24 GB RAM | 15h04 | [here](https://huggingface.co/patrickvonplaten/wav2vec2-300m-mls-german-ft) | [run.sh](https://huggingface.co/patrickvonplaten/wav2vec2-300m-mls-german-ft/blob/main/run.sh) |
+## Connectionist Temporal Classification With Adapters
+
+The script [`run_speech_recognition_ctc_adapter.py`](https://github.com/huggingface/transformers/blob/main/examples/pytorch/speech-recognition/run_speech_recognition_ctc_adapter.py) can be used to fine-tune adapter layers for [Wav2Vec2-like models like MMS](https://huggingface.co/docs/transformers/main/en/model_doc/mms) for automatic speech recognition.
+
+### MMS Model
+
+The [Massive Multilingual Speech (MMS) model](https://huggingface.co/facebook/mms-1b-all) has been pre-trained and fine-tuned
+on 1000+ languages. The model makes use of adapter attention layers to fine-tune only a small part
+of the model on a specific language. The model already comes with fine-tuned adapter layers for 1000+ languages and
+can be used for inference for 1000+ languages out of the box.
+
+However, for improved performance or more specific use cases one can re-initialize the adapter weights, freeze all
+other weights and fine-tune them on a specific dataset as shown in the [example below](#examples-ctc-adapter).
+
+Note that the adapter weights include low dimensional linear layers for every attention block as well as the final language
+model head layers.
+
+### Examples CTC Adapter
+
+In the following we will look at how one can fine-tune adapter weights for any of the
+[MMS CTC checkpoints](https://huggingface.co/models?pipeline_tag=automatic-speech-recognition&other=mms&sort=downloads) in less than 1 hour.
+
+#### Common Voice CTC Adapter
+
+As in the examples [above](#examples-ctc), we fine-tune on Common Voice's 6 dataset in Turkish as an example.
+Contrary to [`run_speech_recognition_ctc.py`](https://github.com/huggingface/transformers/blob/main/examples/pytorch/speech-recognition/run_speech_recognition_ctc.py) before there is a `--target_language` which has to be defined to state for which
+language or concept the adapter layers shall be trained. The adapter weights will then
+accordingly be called `adapter.{=1.18.0", "To fix: pip install -r examples/pytorch/speech-recognition/requirements.txt")
@@ -229,12 +229,28 @@ class DataTrainingArguments:
)
},
)
+ token: str = field(
+ default=None,
+ metadata={
+ "help": (
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
+ )
+ },
+ )
use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
+ trust_remote_code: bool = field(
default=False,
metadata={
"help": (
- "If :obj:`True`, will use the token generated when running"
- ":obj:`huggingface-cli login` as HTTP bearer authorization for remote files."
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
)
},
)
@@ -379,6 +395,12 @@ def main():
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if data_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if data_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ data_args.token = data_args.use_auth_token
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_speech_recognition_ctc", model_args, data_args)
@@ -409,7 +431,7 @@ def main():
# Log on each process the small summary:
logger.warning(
f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
- f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
+ f"distributed training: {training_args.parallel_mode.value == 'distributed'}, 16-bits training: {training_args.fp16}"
)
# Set the verbosity to info of the Transformers logger (on main process only):
if is_main_process(training_args.local_rank):
@@ -427,7 +449,7 @@ def main():
data_args.dataset_name,
data_args.dataset_config_name,
split=data_args.train_split_name,
- use_auth_token=data_args.use_auth_token,
+ token=data_args.token,
)
if data_args.audio_column_name not in raw_datasets["train"].column_names:
@@ -452,7 +474,7 @@ def main():
data_args.dataset_name,
data_args.dataset_config_name,
split=data_args.eval_split_name,
- use_auth_token=data_args.use_auth_token,
+ token=data_args.token,
)
if data_args.max_eval_samples is not None:
@@ -490,7 +512,10 @@ def remove_special_characters(batch):
# the tokenizer
# load config
config = AutoConfig.from_pretrained(
- model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_auth_token=data_args.use_auth_token
+ model_args.model_name_or_path,
+ cache_dir=model_args.cache_dir,
+ token=data_args.token,
+ trust_remote_code=data_args.trust_remote_code,
)
# 4. Next, if no tokenizer file is defined,
@@ -546,11 +571,15 @@ def remove_special_characters(batch):
# load feature_extractor and tokenizer
tokenizer = AutoTokenizer.from_pretrained(
tokenizer_name_or_path,
- use_auth_token=data_args.use_auth_token,
+ token=data_args.token,
+ trust_remote_code=data_args.trust_remote_code,
**tokenizer_kwargs,
)
feature_extractor = AutoFeatureExtractor.from_pretrained(
- model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_auth_token=data_args.use_auth_token
+ model_args.model_name_or_path,
+ cache_dir=model_args.cache_dir,
+ token=data_args.token,
+ trust_remote_code=data_args.trust_remote_code,
)
# adapt config
@@ -578,7 +607,8 @@ def remove_special_characters(batch):
model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
config=config,
- use_auth_token=data_args.use_auth_token,
+ token=data_args.token,
+ trust_remote_code=data_args.trust_remote_code,
)
# freeze encoder
@@ -705,7 +735,7 @@ def compute_metrics(pred):
compute_metrics=compute_metrics,
train_dataset=vectorized_datasets["train"] if training_args.do_train else None,
eval_dataset=vectorized_datasets["eval"] if training_args.do_eval else None,
- tokenizer=feature_extractor,
+ tokenizer=processor,
)
# 8. Finally, we can start training
diff --git a/examples/pytorch/speech-recognition/run_speech_recognition_ctc_adapter.py b/examples/pytorch/speech-recognition/run_speech_recognition_ctc_adapter.py
new file mode 100755
index 000000000000..b91fc87d05f0
--- /dev/null
+++ b/examples/pytorch/speech-recognition/run_speech_recognition_ctc_adapter.py
@@ -0,0 +1,833 @@
+#!/usr/bin/env python
+# coding=utf-8
+# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+""" Fine-tuning a đ€ Transformers CTC adapter model for automatic speech recognition"""
+
+import functools
+import json
+import logging
+import os
+import re
+import sys
+import warnings
+from dataclasses import dataclass, field
+from typing import Dict, List, Optional, Union
+
+import datasets
+import evaluate
+import numpy as np
+import torch
+from datasets import DatasetDict, load_dataset
+from safetensors.torch import save_file as safe_save_file
+
+import transformers
+from transformers import (
+ AutoConfig,
+ AutoFeatureExtractor,
+ AutoModelForCTC,
+ AutoProcessor,
+ AutoTokenizer,
+ HfArgumentParser,
+ Trainer,
+ TrainingArguments,
+ Wav2Vec2Processor,
+ set_seed,
+)
+from transformers.models.wav2vec2.modeling_wav2vec2 import WAV2VEC2_ADAPTER_SAFE_FILE
+from transformers.trainer_utils import get_last_checkpoint, is_main_process
+from transformers.utils import check_min_version, send_example_telemetry
+from transformers.utils.versions import require_version
+
+
+# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
+check_min_version("4.32.0.dev0")
+
+require_version("datasets>=1.18.0", "To fix: pip install -r examples/pytorch/speech-recognition/requirements.txt")
+
+
+logger = logging.getLogger(__name__)
+
+
+def list_field(default=None, metadata=None):
+ return field(default_factory=lambda: default, metadata=metadata)
+
+
+@dataclass
+class ModelArguments:
+ """
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
+ """
+
+ model_name_or_path: str = field(
+ metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
+ )
+ tokenizer_name_or_path: Optional[str] = field(
+ default=None,
+ metadata={"help": "Path to pretrained tokenizer or tokenizer identifier from huggingface.co/models"},
+ )
+ cache_dir: Optional[str] = field(
+ default=None,
+ metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"},
+ )
+ final_dropout: float = field(
+ default=0.0,
+ metadata={"help": "The dropout probability for the final projection layer."},
+ )
+ mask_time_prob: float = field(
+ default=0.05,
+ metadata={
+ "help": (
+ "Probability of each feature vector along the time axis to be chosen as the start of the vector"
+ "span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature"
+ "vectors will be masked along the time axis."
+ )
+ },
+ )
+ mask_time_length: int = field(
+ default=10,
+ metadata={"help": "Length of vector span to mask along the time axis."},
+ )
+ mask_feature_prob: float = field(
+ default=0.0,
+ metadata={
+ "help": (
+ "Probability of each feature vector along the feature axis to be chosen as the start of the vectorspan"
+ " to be masked. Approximately ``mask_feature_prob * sequence_length // mask_feature_length`` feature"
+ " bins will be masked along the time axis."
+ )
+ },
+ )
+ mask_feature_length: int = field(
+ default=10,
+ metadata={"help": "Length of vector span to mask along the feature axis."},
+ )
+ layerdrop: float = field(default=0.0, metadata={"help": "The LayerDrop probability."})
+ ctc_loss_reduction: Optional[str] = field(
+ default="mean", metadata={"help": "The way the ctc loss should be reduced. Should be one of 'mean' or 'sum'."}
+ )
+ adapter_attn_dim: int = field(
+ default=16,
+ metadata={
+ "help": "The hidden dimension of the adapter layers that will be randomly initialized and trained. The higher the dimension, the more capacity is given to the adapter weights. Note that only the adapter weights are fine-tuned."
+ },
+ )
+
+
+@dataclass
+class DataTrainingArguments:
+ """
+ Arguments pertaining to what data we are going to input our model for training and eval.
+
+ Using `HfArgumentParser` we can turn this class
+ into argparse arguments to be able to specify them on
+ the command line.
+ """
+
+ dataset_name: str = field(
+ metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
+ )
+ target_language: Optional[str] = field(
+ metadata={
+ "help": (
+ "The target language on which the adapter attention layers"
+ " should be trained on in ISO 693-3 code, e.g. `tur` for Turkish"
+ " Wav2Vec2's MMS ISO codes can be looked up here: https://dl.fbaipublicfiles.com/mms/misc/language_coverage_mms.html"
+ " If you are not training the adapter layers on a language, simply choose"
+ " another accronym that fits your data."
+ )
+ },
+ )
+ dataset_config_name: str = field(
+ default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
+ )
+ train_split_name: str = field(
+ default="train+validation",
+ metadata={
+ "help": (
+ "The name of the training data set split to use (via the datasets library). Defaults to "
+ "'train+validation'"
+ )
+ },
+ )
+ eval_split_name: str = field(
+ default="test",
+ metadata={
+ "help": "The name of the evaluation data set split to use (via the datasets library). Defaults to 'test'"
+ },
+ )
+ audio_column_name: str = field(
+ default="audio",
+ metadata={"help": "The name of the dataset column containing the audio data. Defaults to 'audio'"},
+ )
+ text_column_name: str = field(
+ default="text",
+ metadata={"help": "The name of the dataset column containing the text data. Defaults to 'text'"},
+ )
+ overwrite_cache: bool = field(
+ default=False, metadata={"help": "Overwrite the cached preprocessed datasets or not."}
+ )
+ preprocessing_num_workers: Optional[int] = field(
+ default=None,
+ metadata={"help": "The number of processes to use for the preprocessing."},
+ )
+ max_train_samples: Optional[int] = field(
+ default=None,
+ metadata={
+ "help": (
+ "For debugging purposes or quicker training, truncate the number of training examples to this "
+ "value if set."
+ )
+ },
+ )
+ max_eval_samples: Optional[int] = field(
+ default=None,
+ metadata={
+ "help": (
+ "For debugging purposes or quicker training, truncate the number of validation examples to this "
+ "value if set."
+ )
+ },
+ )
+ chars_to_ignore: Optional[List[str]] = list_field(
+ default=None,
+ metadata={"help": "A list of characters to remove from the transcripts."},
+ )
+ eval_metrics: List[str] = list_field(
+ default=["wer"],
+ metadata={"help": "A list of metrics the model should be evaluated on. E.g. `'wer cer'`"},
+ )
+ max_duration_in_seconds: float = field(
+ default=20.0,
+ metadata={
+ "help": (
+ "Filter audio files that are longer than `max_duration_in_seconds` seconds to"
+ " 'max_duration_in_seconds`"
+ )
+ },
+ )
+ min_duration_in_seconds: float = field(
+ default=0.0, metadata={"help": "Filter audio files that are shorter than `min_duration_in_seconds` seconds"}
+ )
+ preprocessing_only: bool = field(
+ default=False,
+ metadata={
+ "help": (
+ "Whether to only do data preprocessing and skip training. This is especially useful when data"
+ " preprocessing errors out in distributed training due to timeout. In this case, one should run the"
+ " preprocessing in a non-distributed setup with `preprocessing_only=True` so that the cached datasets"
+ " can consequently be loaded in distributed training"
+ )
+ },
+ )
+ token: str = field(
+ default=None,
+ metadata={
+ "help": (
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
+ )
+ },
+ )
+ use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
+ trust_remote_code: bool = field(
+ default=False,
+ metadata={
+ "help": (
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
+ )
+ },
+ )
+ unk_token: str = field(
+ default="[UNK]",
+ metadata={"help": "The unk token for the tokenizer"},
+ )
+ pad_token: str = field(
+ default="[PAD]",
+ metadata={"help": "The padding token for the tokenizer"},
+ )
+ word_delimiter_token: str = field(
+ default="|",
+ metadata={"help": "The word delimiter token for the tokenizer"},
+ )
+ overwrite_lang_vocab: bool = field(
+ default=False,
+ metadata={"help": ("If :obj:`True`, will overwrite existing `target_language` vocabulary of tokenizer.")},
+ )
+
+
+@dataclass
+class DataCollatorCTCWithPadding:
+ """
+ Data collator that will dynamically pad the inputs received.
+ Args:
+ processor (:class:`~transformers.AutoProcessor`)
+ The processor used for proccessing the data.
+ padding (:obj:`bool`, :obj:`str` or :class:`~transformers.tokenization_utils_base.PaddingStrategy`, `optional`, defaults to :obj:`True`):
+ Select a strategy to pad the returned sequences (according to the model's padding side and padding index)
+ among:
+ * :obj:`True` or :obj:`'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
+ sequence if provided).
+ * :obj:`'max_length'`: Pad to a maximum length specified with the argument :obj:`max_length` or to the
+ maximum acceptable input length for the model if that argument is not provided.
+ * :obj:`False` or :obj:`'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of
+ different lengths).
+ max_length (:obj:`int`, `optional`):
+ Maximum length of the ``input_values`` of the returned list and optionally padding length (see above).
+ max_length_labels (:obj:`int`, `optional`):
+ Maximum length of the ``labels`` returned list and optionally padding length (see above).
+ pad_to_multiple_of (:obj:`int`, `optional`):
+ If set will pad the sequence to a multiple of the provided value.
+ This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability >=
+ 7.5 (Volta).
+ """
+
+ processor: AutoProcessor
+ padding: Union[bool, str] = "longest"
+ pad_to_multiple_of: Optional[int] = None
+ pad_to_multiple_of_labels: Optional[int] = None
+
+ def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:
+ # split inputs and labels since they have to be of different lenghts and need
+ # different padding methods
+ input_features = [{"input_values": feature["input_values"]} for feature in features]
+ label_features = [{"input_ids": feature["labels"]} for feature in features]
+
+ batch = self.processor.pad(
+ input_features,
+ padding=self.padding,
+ pad_to_multiple_of=self.pad_to_multiple_of,
+ return_tensors="pt",
+ )
+
+ labels_batch = self.processor.pad(
+ labels=label_features,
+ padding=self.padding,
+ pad_to_multiple_of=self.pad_to_multiple_of_labels,
+ return_tensors="pt",
+ )
+
+ # replace padding with -100 to ignore loss correctly
+ labels = labels_batch["input_ids"].masked_fill(labels_batch.attention_mask.ne(1), -100)
+
+ batch["labels"] = labels
+ if "attention_mask" in batch:
+ batch["attention_mask"] = batch["attention_mask"].to(torch.long)
+
+ return batch
+
+
+def create_vocabulary_from_data(
+ datasets: DatasetDict,
+ word_delimiter_token: Optional[str] = None,
+ unk_token: Optional[str] = None,
+ pad_token: Optional[str] = None,
+):
+ # Given training and test labels create vocabulary
+ def extract_all_chars(batch):
+ all_text = " ".join(batch["target_text"])
+ vocab = list(set(all_text))
+ return {"vocab": [vocab], "all_text": [all_text]}
+
+ vocabs = datasets.map(
+ extract_all_chars,
+ batched=True,
+ batch_size=-1,
+ keep_in_memory=True,
+ remove_columns=datasets["train"].column_names,
+ )
+
+ # take union of all unique characters in each dataset
+ vocab_set = functools.reduce(
+ lambda vocab_1, vocab_2: set(vocab_1["vocab"][0]) | set(vocab_2["vocab"][0]), vocabs.values()
+ )
+
+ vocab_dict = {v: k for k, v in enumerate(sorted(vocab_set))}
+
+ # replace white space with delimiter token
+ if word_delimiter_token is not None:
+ vocab_dict[word_delimiter_token] = vocab_dict[" "]
+ del vocab_dict[" "]
+
+ # add unk and pad token
+ if unk_token is not None:
+ vocab_dict[unk_token] = len(vocab_dict)
+
+ if pad_token is not None:
+ vocab_dict[pad_token] = len(vocab_dict)
+
+ return vocab_dict
+
+
+def main():
+ # See all possible arguments in src/transformers/training_args.py
+ # or by passing the --help flag to this script.
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
+
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
+ # If we pass only one argument to the script and it's the path to a json file,
+ # let's parse it to get our arguments.
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
+ else:
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+
+ if data_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if data_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ data_args.token = data_args.use_auth_token
+
+ # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
+ # information sent is the one passed as arguments along with your Python/PyTorch versions.
+ send_example_telemetry("run_speech_recognition_ctc_adapter", model_args, data_args)
+
+ # Detecting last checkpoint.
+ last_checkpoint = None
+ if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
+ last_checkpoint = get_last_checkpoint(training_args.output_dir)
+ if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
+ raise ValueError(
+ f"Output directory ({training_args.output_dir}) already exists and is not empty. "
+ "Use --overwrite_output_dir to overcome."
+ )
+ elif last_checkpoint is not None:
+ logger.info(
+ f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
+ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
+ )
+
+ # Setup logging
+ logging.basicConfig(
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
+ datefmt="%m/%d/%Y %H:%M:%S",
+ handlers=[logging.StreamHandler(sys.stdout)],
+ )
+ logger.setLevel(logging.INFO if is_main_process(training_args.local_rank) else logging.WARN)
+
+ # Log on each process the small summary:
+ logger.warning(
+ f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
+ f"distributed training: {training_args.parallel_mode.value == 'distributed'}, 16-bits training: {training_args.fp16}"
+ )
+ # Set the verbosity to info of the Transformers logger (on main process only):
+ if is_main_process(training_args.local_rank):
+ transformers.utils.logging.set_verbosity_info()
+ logger.info("Training/evaluation parameters %s", training_args)
+
+ # Set seed before initializing model.
+ set_seed(training_args.seed)
+
+ # 1. First, let's load the dataset
+ raw_datasets = DatasetDict()
+
+ if training_args.do_train:
+ raw_datasets["train"] = load_dataset(
+ data_args.dataset_name,
+ data_args.dataset_config_name,
+ split=data_args.train_split_name,
+ token=data_args.token,
+ )
+
+ if data_args.audio_column_name not in raw_datasets["train"].column_names:
+ raise ValueError(
+ f"--audio_column_name '{data_args.audio_column_name}' not found in dataset '{data_args.dataset_name}'."
+ " Make sure to set `--audio_column_name` to the correct audio column - one of"
+ f" {', '.join(raw_datasets['train'].column_names)}."
+ )
+
+ if data_args.text_column_name not in raw_datasets["train"].column_names:
+ raise ValueError(
+ f"--text_column_name {data_args.text_column_name} not found in dataset '{data_args.dataset_name}'. "
+ "Make sure to set `--text_column_name` to the correct text column - one of "
+ f"{', '.join(raw_datasets['train'].column_names)}."
+ )
+
+ if data_args.max_train_samples is not None:
+ raw_datasets["train"] = raw_datasets["train"].select(range(data_args.max_train_samples))
+
+ if training_args.do_eval:
+ raw_datasets["eval"] = load_dataset(
+ data_args.dataset_name,
+ data_args.dataset_config_name,
+ split=data_args.eval_split_name,
+ token=data_args.token,
+ )
+
+ if data_args.max_eval_samples is not None:
+ raw_datasets["eval"] = raw_datasets["eval"].select(range(data_args.max_eval_samples))
+
+ # 2. We remove some special characters from the datasets
+ # that make training complicated and do not help in transcribing the speech
+ # E.g. characters, such as `,` and `.` do not really have an acoustic characteristic
+ # that could be easily picked up by the model
+ chars_to_ignore_regex = (
+ f'[{"".join(data_args.chars_to_ignore)}]' if data_args.chars_to_ignore is not None else None
+ )
+ text_column_name = data_args.text_column_name
+
+ def remove_special_characters(batch):
+ if chars_to_ignore_regex is not None:
+ batch["target_text"] = re.sub(chars_to_ignore_regex, "", batch[text_column_name]).lower() + " "
+ else:
+ batch["target_text"] = batch[text_column_name].lower() + " "
+ return batch
+
+ with training_args.main_process_first(desc="dataset map special characters removal"):
+ raw_datasets = raw_datasets.map(
+ remove_special_characters,
+ remove_columns=[text_column_name],
+ desc="remove special characters from datasets",
+ )
+
+ # save special tokens for tokenizer
+ word_delimiter_token = data_args.word_delimiter_token
+ unk_token = data_args.unk_token
+ pad_token = data_args.pad_token
+
+ # 3. Next, let's load the config as we might need it to create
+ # the tokenizer
+ # load config
+ config = AutoConfig.from_pretrained(
+ model_args.model_name_or_path,
+ cache_dir=model_args.cache_dir,
+ token=data_args.token,
+ trust_remote_code=data_args.trust_remote_code,
+ )
+
+ # 4. Next, if no tokenizer file is defined,
+ # we create the vocabulary of the model by extracting all unique characters from
+ # the training and evaluation datasets
+ # We need to make sure that only first rank saves vocabulary
+ # make sure all processes wait until vocab is created
+ tokenizer_name_or_path = model_args.tokenizer_name_or_path
+ tokenizer_kwargs = {}
+
+ vocab_dict = {}
+ if tokenizer_name_or_path is not None:
+ # load vocabulary of other adapter languages so that new language can be appended
+ tokenizer = AutoTokenizer.from_pretrained(
+ tokenizer_name_or_path,
+ token=data_args.token,
+ trust_remote_code=data_args.trust_remote_code,
+ )
+ vocab_dict = tokenizer.vocab.copy()
+ if tokenizer.target_lang is None:
+ raise ValueError("Make sure to load a multi-lingual tokenizer with a set target language.")
+
+ if data_args.target_language in tokenizer.vocab and not data_args.overwrite_lang_vocab:
+ logger.info(
+ "Adapter language already exists."
+ " Skipping vocabulary creating. If you want to create a new vocabulary"
+ f" for {data_args.target_language} make sure to add '--overwrite_lang_vocab'"
+ )
+ else:
+ tokenizer_name_or_path = None
+
+ if tokenizer_name_or_path is None:
+ # save vocab in training output dir
+ tokenizer_name_or_path = training_args.output_dir
+
+ vocab_file = os.path.join(tokenizer_name_or_path, "vocab.json")
+
+ with training_args.main_process_first():
+ if training_args.overwrite_output_dir and os.path.isfile(vocab_file):
+ try:
+ os.remove(vocab_file)
+ except OSError:
+ # in shared file-systems it might be the case that
+ # two processes try to delete the vocab file at the some time
+ pass
+
+ with training_args.main_process_first(desc="dataset map vocabulary creation"):
+ if not os.path.isfile(vocab_file):
+ os.makedirs(tokenizer_name_or_path, exist_ok=True)
+ lang_dict = create_vocabulary_from_data(
+ raw_datasets,
+ word_delimiter_token=word_delimiter_token,
+ unk_token=unk_token,
+ pad_token=pad_token,
+ )
+
+ # if we doing adapter language training, save
+ # vocab with adpter language
+ if data_args.target_language is not None:
+ vocab_dict[data_args.target_language] = lang_dict
+
+ # save vocab dict to be loaded into tokenizer
+ with open(vocab_file, "w") as file:
+ json.dump(vocab_dict, file)
+
+ # if tokenizer has just been created
+ # it is defined by `tokenizer_class` if present in config else by `model_type`
+ tokenizer_kwargs = {
+ "config": config if config.tokenizer_class is not None else None,
+ "tokenizer_type": config.model_type if config.tokenizer_class is None else None,
+ "unk_token": unk_token,
+ "pad_token": pad_token,
+ "word_delimiter_token": word_delimiter_token,
+ "target_lang": data_args.target_language,
+ }
+
+ # 5. Now we can instantiate the feature extractor, tokenizer and model
+ # Note for distributed training, the .from_pretrained methods guarantee that only
+ # one local process can concurrently download model & vocab.
+
+ # load feature_extractor and tokenizer
+ tokenizer = AutoTokenizer.from_pretrained(
+ tokenizer_name_or_path,
+ token=data_args.token,
+ trust_remote_code=data_args.trust_remote_code,
+ **tokenizer_kwargs,
+ )
+ feature_extractor = AutoFeatureExtractor.from_pretrained(
+ model_args.model_name_or_path,
+ cache_dir=model_args.cache_dir,
+ token=data_args.token,
+ trust_remote_code=data_args.trust_remote_code,
+ )
+
+ # adapt config
+ config.update(
+ {
+ "final_dropout": model_args.final_dropout,
+ "mask_time_prob": model_args.mask_time_prob,
+ "mask_time_length": model_args.mask_time_length,
+ "mask_feature_prob": model_args.mask_feature_prob,
+ "mask_feature_length": model_args.mask_feature_length,
+ "gradient_checkpointing": training_args.gradient_checkpointing,
+ "layerdrop": model_args.layerdrop,
+ "ctc_loss_reduction": model_args.ctc_loss_reduction,
+ "pad_token_id": tokenizer.pad_token_id,
+ "vocab_size": len(tokenizer),
+ "adapter_attn_dim": model_args.adapter_attn_dim,
+ }
+ )
+
+ # create model
+ model = AutoModelForCTC.from_pretrained(
+ model_args.model_name_or_path,
+ cache_dir=model_args.cache_dir,
+ config=config,
+ token=data_args.token,
+ trust_remote_code=data_args.trust_remote_code,
+ ignore_mismatched_sizes=True,
+ )
+
+ # if attn adapter is defined, freeze all non-adapter weights
+ if model.config.adapter_attn_dim is not None:
+ model.init_adapter_layers()
+ # first we freeze the whole base model
+ model.freeze_base_model()
+
+ # next we unfreeze all adapter layers
+ adapter_weights = model._get_adapters()
+ for param in adapter_weights.values():
+ param.requires_grad = True
+
+ # 6. Now we preprocess the datasets including loading the audio, resampling and normalization
+ # Thankfully, `datasets` takes care of automatically loading and resampling the audio,
+ # so that we just need to set the correct target sampling rate and normalize the input
+ # via the `feature_extractor`
+
+ # make sure that dataset decodes audio with correct sampling rate
+ dataset_sampling_rate = next(iter(raw_datasets.values())).features[data_args.audio_column_name].sampling_rate
+ if dataset_sampling_rate != feature_extractor.sampling_rate:
+ raw_datasets = raw_datasets.cast_column(
+ data_args.audio_column_name, datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate)
+ )
+
+ # derive max & min input length for sample rate & max duration
+ max_input_length = data_args.max_duration_in_seconds * feature_extractor.sampling_rate
+ min_input_length = data_args.min_duration_in_seconds * feature_extractor.sampling_rate
+ audio_column_name = data_args.audio_column_name
+ num_workers = data_args.preprocessing_num_workers
+
+ # Preprocessing the datasets.
+ # We need to read the audio files as arrays and tokenize the targets.
+ def prepare_dataset(batch):
+ # load audio
+ sample = batch[audio_column_name]
+
+ inputs = feature_extractor(sample["array"], sampling_rate=sample["sampling_rate"])
+ batch["input_values"] = inputs.input_values[0]
+ batch["input_length"] = len(batch["input_values"])
+
+ # encode targets
+ batch["labels"] = tokenizer(batch["target_text"]).input_ids
+ return batch
+
+ with training_args.main_process_first(desc="dataset map preprocessing"):
+ vectorized_datasets = raw_datasets.map(
+ prepare_dataset,
+ remove_columns=next(iter(raw_datasets.values())).column_names,
+ num_proc=num_workers,
+ desc="preprocess datasets",
+ )
+
+ def is_audio_in_length_range(length):
+ return length > min_input_length and length < max_input_length
+
+ # filter data that is shorter than min_input_length
+ vectorized_datasets = vectorized_datasets.filter(
+ is_audio_in_length_range,
+ num_proc=num_workers,
+ input_columns=["input_length"],
+ )
+
+ # 7. Next, we can prepare the training.
+ # Let's use word error rate (WER) as our evaluation metric,
+ # instantiate a data collator and the trainer
+
+ # Define evaluation metrics during training, *i.e.* word error rate, character error rate
+ eval_metrics = {metric: evaluate.load(metric) for metric in data_args.eval_metrics}
+
+ # for large datasets it is advised to run the preprocessing on a
+ # single machine first with ``args.preprocessing_only`` since there will mostly likely
+ # be a timeout when running the script in distributed mode.
+ # In a second step ``args.preprocessing_only`` can then be set to `False` to load the
+ # cached dataset
+ if data_args.preprocessing_only:
+ logger.info(f"Data preprocessing finished. Files cached at {vectorized_datasets.cache_files}")
+ return
+
+ def compute_metrics(pred):
+ pred_logits = pred.predictions
+ pred_ids = np.argmax(pred_logits, axis=-1)
+
+ pred.label_ids[pred.label_ids == -100] = tokenizer.pad_token_id
+
+ pred_str = tokenizer.batch_decode(pred_ids)
+ # we do not want to group tokens when computing the metrics
+ label_str = tokenizer.batch_decode(pred.label_ids, group_tokens=False)
+
+ metrics = {k: v.compute(predictions=pred_str, references=label_str) for k, v in eval_metrics.items()}
+
+ return metrics
+
+ # Now save everything to be able to create a single processor later
+ # make sure all processes wait until data is saved
+ with training_args.main_process_first():
+ # only the main process saves them
+ if is_main_process(training_args.local_rank):
+ # save feature extractor, tokenizer and config
+ feature_extractor.save_pretrained(training_args.output_dir)
+ tokenizer.save_pretrained(training_args.output_dir)
+ config.save_pretrained(training_args.output_dir)
+
+ try:
+ processor = AutoProcessor.from_pretrained(training_args.output_dir)
+ except (OSError, KeyError):
+ warnings.warn(
+ "Loading a processor from a feature extractor config that does not"
+ " include a `processor_class` attribute is deprecated and will be removed in v5. Please add the following "
+ " attribute to your `preprocessor_config.json` file to suppress this warning: "
+ " `'processor_class': 'Wav2Vec2Processor'`",
+ FutureWarning,
+ )
+ processor = Wav2Vec2Processor.from_pretrained(training_args.output_dir)
+
+ # Instantiate custom data collator
+ data_collator = DataCollatorCTCWithPadding(processor=processor)
+
+ # Initialize Trainer
+ trainer = Trainer(
+ model=model,
+ data_collator=data_collator,
+ args=training_args,
+ compute_metrics=compute_metrics,
+ train_dataset=vectorized_datasets["train"] if training_args.do_train else None,
+ eval_dataset=vectorized_datasets["eval"] if training_args.do_eval else None,
+ tokenizer=processor,
+ )
+
+ # 8. Finally, we can start training
+
+ # Training
+ if training_args.do_train:
+ # use last checkpoint if exist
+ if last_checkpoint is not None:
+ checkpoint = last_checkpoint
+ elif os.path.isdir(model_args.model_name_or_path):
+ checkpoint = model_args.model_name_or_path
+ else:
+ checkpoint = None
+
+ train_result = trainer.train(resume_from_checkpoint=checkpoint)
+ trainer.save_model()
+
+ metrics = train_result.metrics
+ max_train_samples = (
+ data_args.max_train_samples
+ if data_args.max_train_samples is not None
+ else len(vectorized_datasets["train"])
+ )
+ metrics["train_samples"] = min(max_train_samples, len(vectorized_datasets["train"]))
+
+ trainer.log_metrics("train", metrics)
+ trainer.save_metrics("train", metrics)
+ trainer.save_state()
+
+ # Evaluation
+ results = {}
+ if training_args.do_eval:
+ logger.info("*** Evaluate ***")
+ metrics = trainer.evaluate()
+ max_eval_samples = (
+ data_args.max_eval_samples if data_args.max_eval_samples is not None else len(vectorized_datasets["eval"])
+ )
+ metrics["eval_samples"] = min(max_eval_samples, len(vectorized_datasets["eval"]))
+
+ trainer.log_metrics("eval", metrics)
+ trainer.save_metrics("eval", metrics)
+
+ # Write model card and (optionally) push to hub
+ config_name = data_args.dataset_config_name if data_args.dataset_config_name is not None else "na"
+ kwargs = {
+ "finetuned_from": model_args.model_name_or_path,
+ "tasks": "automatic-speech-recognition",
+ "tags": ["automatic-speech-recognition", data_args.dataset_name, "mms"],
+ "dataset_args": (
+ f"Config: {config_name}, Training split: {data_args.train_split_name}, Eval split:"
+ f" {data_args.eval_split_name}"
+ ),
+ "dataset": f"{data_args.dataset_name.upper()} - {config_name.upper()}",
+ }
+ if "common_voice" in data_args.dataset_name:
+ kwargs["language"] = config_name
+
+ # make sure that adapter weights are saved seperately
+ adapter_file = WAV2VEC2_ADAPTER_SAFE_FILE.format(data_args.target_language)
+ adapter_file = os.path.join(training_args.output_dir, adapter_file)
+ logger.info(f"Saving adapter weights under {adapter_file}...")
+ safe_save_file(model._get_adapters(), adapter_file, metadata={"format": "pt"})
+
+ if training_args.push_to_hub:
+ trainer.push_to_hub(**kwargs)
+ else:
+ trainer.create_model_card(**kwargs)
+
+ return results
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/pytorch/speech-recognition/run_speech_recognition_seq2seq.py b/examples/pytorch/speech-recognition/run_speech_recognition_seq2seq.py
index 419be107b164..f9744994ad8e 100755
--- a/examples/pytorch/speech-recognition/run_speech_recognition_seq2seq.py
+++ b/examples/pytorch/speech-recognition/run_speech_recognition_seq2seq.py
@@ -22,6 +22,7 @@
import logging
import os
import sys
+import warnings
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Union
@@ -48,7 +49,7 @@
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
-check_min_version("4.29.0.dev0")
+check_min_version("4.32.0.dev0")
require_version("datasets>=1.18.0", "To fix: pip install -r examples/pytorch/speech-recognition/requirements.txt")
@@ -85,12 +86,28 @@ class ModelArguments:
default="main",
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
)
+ token: str = field(
+ default=None,
+ metadata={
+ "help": (
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
+ )
+ },
+ )
use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
+ trust_remote_code: bool = field(
default=False,
metadata={
"help": (
- "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
- "with private models)."
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
)
},
)
@@ -278,6 +295,12 @@ def main():
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_speech_recognition_seq2seq", model_args, data_args)
@@ -300,7 +323,7 @@ def main():
# Log on each process the small summary:
logger.warning(
f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
- f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
+ f"distributed training: {training_args.parallel_mode.value == 'distributed'}, 16-bits training: {training_args.fp16}"
)
logger.info(f"Training/evaluation parameters {training_args}")
@@ -336,7 +359,7 @@ def main():
data_args.dataset_config_name,
split=data_args.train_split_name,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
if training_args.do_eval:
@@ -345,7 +368,7 @@ def main():
data_args.dataset_config_name,
split=data_args.eval_split_name,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
if data_args.audio_column_name not in next(iter(raw_datasets.values())).column_names:
@@ -370,7 +393,8 @@ def main():
model_args.config_name if model_args.config_name else model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
config.update({"forced_decoder_ids": model_args.forced_decoder_ids, "suppress_tokens": model_args.suppress_tokens})
@@ -383,21 +407,24 @@ def main():
model_args.feature_extractor_name if model_args.feature_extractor_name else model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
tokenizer = AutoTokenizer.from_pretrained(
model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
use_fast=model_args.use_fast_tokenizer,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
model = AutoModelForSpeechSeq2Seq.from_pretrained(
model_args.model_name_or_path,
config=config,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
if model.config.decoder_start_token_id is None:
diff --git a/examples/pytorch/summarization/run_summarization.py b/examples/pytorch/summarization/run_summarization.py
index e083e68848ef..d145a8549de2 100755
--- a/examples/pytorch/summarization/run_summarization.py
+++ b/examples/pytorch/summarization/run_summarization.py
@@ -21,6 +21,7 @@
import logging
import os
import sys
+import warnings
from dataclasses import dataclass, field
from typing import Optional
@@ -52,7 +53,7 @@
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
-check_min_version("4.29.0.dev0")
+check_min_version("4.32.0.dev0")
require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/summarization/requirements.txt")
@@ -99,12 +100,28 @@ class ModelArguments:
default="main",
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
)
+ token: str = field(
+ default=None,
+ metadata={
+ "help": (
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
+ )
+ },
+ )
use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
+ trust_remote_code: bool = field(
default=False,
metadata={
"help": (
- "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
- "with private models)."
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
)
},
)
@@ -312,6 +329,12 @@ def main():
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_summarization", model_args, data_args)
@@ -337,7 +360,7 @@ def main():
# Log on each process the small summary:
logger.warning(
f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
- + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
+ + f"distributed training: {training_args.parallel_mode.value == 'distributed'}, 16-bits training: {training_args.fp16}"
)
logger.info(f"Training/evaluation parameters {training_args}")
@@ -386,7 +409,7 @@ def main():
data_args.dataset_name,
data_args.dataset_config_name,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
else:
data_files = {}
@@ -403,7 +426,7 @@ def main():
extension,
data_files=data_files,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
# https://huggingface.co/docs/datasets/loading_datasets.html.
@@ -417,14 +440,16 @@ def main():
model_args.config_name if model_args.config_name else model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
tokenizer = AutoTokenizer.from_pretrained(
model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
use_fast=model_args.use_fast_tokenizer,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
model = AutoModelForSeq2SeqLM.from_pretrained(
model_args.model_name_or_path,
@@ -432,7 +457,8 @@ def main():
config=config,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
# We resize the embeddings only when necessary to avoid index errors. If you are creating a model from scratch
@@ -692,7 +718,13 @@ def compute_metrics(eval_preds):
results = {}
if training_args.do_eval:
logger.info("*** Evaluate ***")
- metrics = trainer.evaluate(metric_key_prefix="eval")
+ if isinstance(eval_dataset, dict):
+ metrics = {}
+ for eval_ds_name, eval_ds in eval_dataset.items():
+ dataset_metrics = trainer.evaluate(eval_dataset=eval_ds, metric_key_prefix=f"eval_{eval_ds_name}")
+ metrics.update(dataset_metrics)
+ else:
+ metrics = trainer.evaluate(metric_key_prefix="eval")
max_eval_samples = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(eval_dataset)
metrics["eval_samples"] = min(max_eval_samples, len(eval_dataset))
diff --git a/examples/pytorch/summarization/run_summarization_no_trainer.py b/examples/pytorch/summarization/run_summarization_no_trainer.py
index 37ea3bcfbb9e..e4b390c22a3f 100644
--- a/examples/pytorch/summarization/run_summarization_no_trainer.py
+++ b/examples/pytorch/summarization/run_summarization_no_trainer.py
@@ -51,12 +51,12 @@
SchedulerType,
get_scheduler,
)
-from transformers.utils import check_min_version, get_full_repo_name, is_offline_mode, send_example_telemetry
+from transformers.utils import check_min_version, is_offline_mode, send_example_telemetry
from transformers.utils.versions import require_version
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
-check_min_version("4.29.0.dev0")
+check_min_version("4.32.0.dev0")
logger = get_logger(__name__)
require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/summarization/requirements.txt")
@@ -266,6 +266,16 @@ def parse_args():
"--hub_model_id", type=str, help="The name of the repository to keep in sync with the local `output_dir`."
)
parser.add_argument("--hub_token", type=str, help="The token to use to push to the Model Hub.")
+ parser.add_argument(
+ "--trust_remote_code",
+ type=bool,
+ default=False,
+ help=(
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
+ ),
+ )
parser.add_argument(
"--checkpointing_steps",
type=str,
@@ -325,7 +335,7 @@ def main():
if args.with_tracking:
accelerator_log_kwargs["log_with"] = args.report_to
- accelerator_log_kwargs["logging_dir"] = args.output_dir
+ accelerator_log_kwargs["project_dir"] = args.output_dir
accelerator = Accelerator(gradient_accumulation_steps=args.gradient_accumulation_steps, **accelerator_log_kwargs)
if args.source_prefix is None and args.model_name_or_path in [
@@ -360,12 +370,14 @@ def main():
# Handle the repository creation
if accelerator.is_main_process:
if args.push_to_hub:
- if args.hub_model_id is None:
- repo_name = get_full_repo_name(Path(args.output_dir).name, token=args.hub_token)
- else:
- repo_name = args.hub_model_id
- create_repo(repo_name, exist_ok=True, token=args.hub_token)
- repo = Repository(args.output_dir, clone_from=repo_name, token=args.hub_token)
+ # Retrieve of infer repo_name
+ repo_name = args.hub_model_id
+ if repo_name is None:
+ repo_name = Path(args.output_dir).absolute().name
+ # Create repo and retrieve repo_id
+ repo_id = create_repo(repo_name, exist_ok=True, token=args.hub_token).repo_id
+ # Clone repo locally
+ repo = Repository(args.output_dir, clone_from=repo_id, token=args.hub_token)
with open(os.path.join(args.output_dir, ".gitignore"), "w+") as gitignore:
if "step_*" not in gitignore:
@@ -404,17 +416,21 @@ def main():
# In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
# download model & vocab.
if args.config_name:
- config = AutoConfig.from_pretrained(args.config_name)
+ config = AutoConfig.from_pretrained(args.config_name, trust_remote_code=args.trust_remote_code)
elif args.model_name_or_path:
- config = AutoConfig.from_pretrained(args.model_name_or_path)
+ config = AutoConfig.from_pretrained(args.model_name_or_path, trust_remote_code=args.trust_remote_code)
else:
config = CONFIG_MAPPING[args.model_type]()
logger.warning("You are instantiating a new config instance from scratch.")
if args.tokenizer_name:
- tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=not args.use_slow_tokenizer)
+ tokenizer = AutoTokenizer.from_pretrained(
+ args.tokenizer_name, use_fast=not args.use_slow_tokenizer, trust_remote_code=args.trust_remote_code
+ )
elif args.model_name_or_path:
- tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path, use_fast=not args.use_slow_tokenizer)
+ tokenizer = AutoTokenizer.from_pretrained(
+ args.model_name_or_path, use_fast=not args.use_slow_tokenizer, trust_remote_code=args.trust_remote_code
+ )
else:
raise ValueError(
"You are instantiating a new tokenizer from scratch. This is not supported by this script."
@@ -426,10 +442,11 @@ def main():
args.model_name_or_path,
from_tf=bool(".ckpt" in args.model_name_or_path),
config=config,
+ trust_remote_code=args.trust_remote_code,
)
else:
logger.info("Training new model from scratch")
- model = AutoModelForSeq2SeqLM.from_config(config)
+ model = AutoModelForSeq2SeqLM.from_config(config, trust_remote_code=args.trust_remote_code)
# We resize the embeddings only when necessary to avoid index errors. If you are creating a model from scratch
# on a small vocab and want a smaller embedding size, remove this test.
@@ -612,36 +629,45 @@ def postprocess_text(preds, labels):
# Potentially load in the weights and states from a previous save
if args.resume_from_checkpoint:
if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
- accelerator.print(f"Resumed from checkpoint: {args.resume_from_checkpoint}")
- accelerator.load_state(args.resume_from_checkpoint)
+ checkpoint_path = args.resume_from_checkpoint
path = os.path.basename(args.resume_from_checkpoint)
else:
# Get the most recent checkpoint
dirs = [f.name for f in os.scandir(os.getcwd()) if f.is_dir()]
dirs.sort(key=os.path.getctime)
path = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last
+ checkpoint_path = path
+ path = os.path.basename(checkpoint_path)
+
+ accelerator.print(f"Resumed from checkpoint: {checkpoint_path}")
+ accelerator.load_state(path)
# Extract `epoch_{i}` or `step_{i}`
training_difference = os.path.splitext(path)[0]
if "epoch" in training_difference:
starting_epoch = int(training_difference.replace("epoch_", "")) + 1
resume_step = None
+ completed_steps = starting_epoch * num_update_steps_per_epoch
else:
- resume_step = int(training_difference.replace("step_", ""))
+ # need to multiply `gradient_accumulation_steps` to reflect real steps
+ resume_step = int(training_difference.replace("step_", "")) * args.gradient_accumulation_steps
starting_epoch = resume_step // len(train_dataloader)
resume_step -= starting_epoch * len(train_dataloader)
+ completed_steps = resume_step // args.gradient_accumulation_stepp
+
+ # update the progress_bar if load from checkpoint
+ progress_bar.update(completed_steps)
for epoch in range(starting_epoch, args.num_train_epochs):
model.train()
if args.with_tracking:
total_loss = 0
- for step, batch in enumerate(train_dataloader):
- # We need to skip steps until we reach the resumed step
- if args.resume_from_checkpoint and epoch == starting_epoch:
- if resume_step is not None and step < resume_step:
- completed_steps += 1
- continue
-
+ if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None:
+ # We skip the first `n` batches in the dataloader when resuming from a checkpoint
+ active_dataloader = accelerator.skip_first_batches(train_dataloader, resume_step)
+ else:
+ active_dataloader = train_dataloader
+ for step, batch in enumerate(active_dataloader):
with accelerator.accumulate(model):
outputs = model(**batch)
loss = outputs.loss
diff --git a/examples/pytorch/test_accelerate_examples.py b/examples/pytorch/test_accelerate_examples.py
index d88a2ead64b4..4cfe45b02294 100644
--- a/examples/pytorch/test_accelerate_examples.py
+++ b/examples/pytorch/test_accelerate_examples.py
@@ -21,6 +21,7 @@
import shutil
import sys
import tempfile
+import unittest
from unittest import mock
import torch
@@ -176,6 +177,7 @@ def test_run_ner_no_trainer(self):
self.assertTrue(os.path.exists(os.path.join(tmp_dir, "epoch_0")))
self.assertTrue(os.path.exists(os.path.join(tmp_dir, "ner_no_trainer")))
+ @unittest.skip(reason="Fix me @muellerzr")
@mock.patch.dict(os.environ, {"WANDB_MODE": "offline"})
def test_run_squad_no_trainer(self):
tmp_dir = self.get_auto_remove_tmp_dir()
@@ -268,6 +270,7 @@ def test_run_translation_no_trainer(self):
--output_dir {tmp_dir}
--max_train_steps=50
--num_warmup_steps=8
+ --num_beams=6
--learning_rate=3e-3
--per_device_train_batch_size=2
--per_device_eval_batch_size=1
diff --git a/examples/pytorch/test_pytorch_examples.py b/examples/pytorch/test_pytorch_examples.py
index f4682b8933e7..269d7844f79f 100644
--- a/examples/pytorch/test_pytorch_examples.py
+++ b/examples/pytorch/test_pytorch_examples.py
@@ -14,7 +14,6 @@
# limitations under the License.
-import argparse
import json
import logging
import os
@@ -63,6 +62,7 @@
import run_semantic_segmentation
import run_seq2seq_qa as run_squad_seq2seq
import run_speech_recognition_ctc
+ import run_speech_recognition_ctc_adapter
import run_speech_recognition_seq2seq
import run_summarization
import run_swag
@@ -75,13 +75,6 @@
logger = logging.getLogger()
-def get_setup_file():
- parser = argparse.ArgumentParser()
- parser.add_argument("-f")
- args = parser.parse_args()
- return args.f
-
-
def get_results(output_dir):
results = {}
path = os.path.join(output_dir, "all_results.json")
@@ -152,8 +145,8 @@ def test_run_clm(self):
# Skipping because there are not enough batches to train the model + would need a drop_last to work.
return
- if torch_device != "cuda":
- testargs.append("--no_cuda")
+ if torch_device == "cpu":
+ testargs.append("--use_cpu")
with patch.object(sys, "argv", testargs):
run_clm.main()
@@ -174,8 +167,8 @@ def test_run_clm_config_overrides(self):
--config_overrides n_embd=10,n_head=2
""".split()
- if torch_device != "cuda":
- testargs.append("--no_cuda")
+ if torch_device == "cpu":
+ testargs.append("--use_cpu")
logger = run_clm.logger
with patch.object(sys, "argv", testargs):
@@ -200,8 +193,8 @@ def test_run_mlm(self):
--num_train_epochs=1
""".split()
- if torch_device != "cuda":
- testargs.append("--no_cuda")
+ if torch_device == "cpu":
+ testargs.append("--use_cpu")
with patch.object(sys, "argv", testargs):
run_mlm.main()
@@ -230,8 +223,8 @@ def test_run_ner(self):
--seed 7
""".split()
- if torch_device != "cuda":
- testargs.append("--no_cuda")
+ if torch_device == "cpu":
+ testargs.append("--use_cpu")
with patch.object(sys, "argv", testargs):
run_ner.main()
@@ -446,6 +439,38 @@ def test_run_speech_recognition_ctc(self):
result = get_results(tmp_dir)
self.assertLess(result["eval_loss"], result["train_loss"])
+ def test_run_speech_recognition_ctc_adapter(self):
+ tmp_dir = self.get_auto_remove_tmp_dir()
+ testargs = f"""
+ run_speech_recognition_ctc_adapter.py
+ --output_dir {tmp_dir}
+ --model_name_or_path hf-internal-testing/tiny-random-wav2vec2
+ --dataset_name hf-internal-testing/librispeech_asr_dummy
+ --dataset_config_name clean
+ --train_split_name validation
+ --eval_split_name validation
+ --do_train
+ --do_eval
+ --learning_rate 1e-4
+ --per_device_train_batch_size 2
+ --per_device_eval_batch_size 1
+ --remove_unused_columns False
+ --overwrite_output_dir True
+ --preprocessing_num_workers 16
+ --max_steps 10
+ --target_language tur
+ --seed 42
+ """.split()
+
+ if is_cuda_and_apex_available():
+ testargs.append("--fp16")
+
+ with patch.object(sys, "argv", testargs):
+ run_speech_recognition_ctc_adapter.main()
+ result = get_results(tmp_dir)
+ self.assertTrue(os.path.isfile(os.path.join(tmp_dir, "./adapter.tur.safetensors")))
+ self.assertLess(result["eval_loss"], result["train_loss"])
+
def test_run_speech_recognition_seq2seq(self):
tmp_dir = self.get_auto_remove_tmp_dir()
testargs = f"""
diff --git a/examples/pytorch/text-classification/README.md b/examples/pytorch/text-classification/README.md
index 1bc01b416b74..3e0d190e516e 100644
--- a/examples/pytorch/text-classification/README.md
+++ b/examples/pytorch/text-classification/README.md
@@ -81,6 +81,55 @@ python run_glue.py \
> If your model classification head dimensions do not fit the number of labels in the dataset, you can specify `--ignore_mismatched_sizes` to adapt it.
+## Text classification
+As an alternative, we can use the script [`run_classification.py`](./run_classification.py) to fine-tune models on a single/multi-label classification task.
+
+The following example fine-tunes BERT on the `en` subset of [`amazon_reviews_multi`](https://huggingface.co/datasets/amazon_reviews_multi) dataset.
+We can specify the metric, the label column and aso choose which text columns to use jointly for classification.
+```bash
+dataset="amazon_reviews_multi"
+subset="en"
+python run_classification.py \
+ --model_name_or_path bert-base-uncased \
+ --dataset_name ${dataset} \
+ --dataset_config_name ${subset} \
+ --shuffle_train_dataset \
+ --metric_name accuracy \
+ --text_column_name "review_title,review_body,product_category" \
+ --text_column_delimiter "\n" \
+ --label_column_name stars \
+ --do_train \
+ --do_eval \
+ --max_seq_length 512 \
+ --per_device_train_batch_size 32 \
+ --learning_rate 2e-5 \
+ --num_train_epochs 1 \
+ --output_dir /tmp/${dataset}_${subset}/
+```
+Training for 1 epoch results in acc of around 0.5958 for review_body only and 0.659 for title+body+category.
+
+The following is a multi-label classification example. It fine-tunes BERT on the `reuters21578` dataset hosted on our [hub](https://huggingface.co/datasets/reuters21578):
+```bash
+dataset="reuters21578"
+subset="ModApte"
+python run_classification.py \
+ --model_name_or_path bert-base-uncased \
+ --dataset_name ${dataset} \
+ --dataset_config_name ${subset} \
+ --shuffle_train_dataset \
+ --remove_splits "unused" \
+ --metric_name f1 \
+ --text_column_name text \
+ --label_column_name topics \
+ --do_train \
+ --do_eval \
+ --max_seq_length 512 \
+ --per_device_train_batch_size 32 \
+ --learning_rate 2e-5 \
+ --num_train_epochs 15 \
+ --output_dir /tmp/${dataset}_${subset}/
+```
+ It results in a Micro F1 score of around 0.82 without any text and label filtering. Note that you have to explictly remove the "unused" split from the dataset, since it is not used for classification.
### Mixed precision training
diff --git a/examples/pytorch/text-classification/run_classification.py b/examples/pytorch/text-classification/run_classification.py
new file mode 100755
index 000000000000..68d2475fd567
--- /dev/null
+++ b/examples/pytorch/text-classification/run_classification.py
@@ -0,0 +1,757 @@
+#!/usr/bin/env python
+# coding=utf-8
+# Copyright 2020 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+""" Finetuning the library models for text classification."""
+# You can also adapt this script on your own text classification task. Pointers for this are left as comments.
+
+import logging
+import os
+import random
+import sys
+import warnings
+from dataclasses import dataclass, field
+from typing import List, Optional
+
+import datasets
+import evaluate
+import numpy as np
+from datasets import Value, load_dataset
+
+import transformers
+from transformers import (
+ AutoConfig,
+ AutoModelForSequenceClassification,
+ AutoTokenizer,
+ DataCollatorWithPadding,
+ EvalPrediction,
+ HfArgumentParser,
+ Trainer,
+ TrainingArguments,
+ default_data_collator,
+ set_seed,
+)
+from transformers.trainer_utils import get_last_checkpoint
+from transformers.utils import check_min_version, send_example_telemetry
+from transformers.utils.versions import require_version
+
+
+# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
+check_min_version("4.32.0.dev0")
+
+require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/text-classification/requirements.txt")
+
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass
+class DataTrainingArguments:
+ """
+ Arguments pertaining to what data we are going to input our model for training and eval.
+
+ Using `HfArgumentParser` we can turn this class
+ into argparse arguments to be able to specify them on
+ the command line.
+ """
+
+ dataset_name: Optional[str] = field(
+ default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
+ )
+ dataset_config_name: Optional[str] = field(
+ default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
+ )
+ do_regression: bool = field(
+ default=None,
+ metadata={
+ "help": "Whether to do regression instead of classification. If None, will be inferred from the dataset."
+ },
+ )
+ text_column_names: Optional[str] = field(
+ default=None,
+ metadata={
+ "help": (
+ "The name of the text column in the input dataset or a CSV/JSON file."
+ 'If not specified, will use the "sentence" column for single/multi-label classifcation task.'
+ )
+ },
+ )
+ text_column_delimiter: Optional[str] = field(
+ default=" ", metadata={"help": "THe delimiter to use to join text columns into a single sentence."}
+ )
+ train_split_name: Optional[str] = field(
+ default=None,
+ metadata={
+ "help": 'The name of the train split in the input dataset. If not specified, will use the "train" split when do_train is enabled'
+ },
+ )
+ validation_split_name: Optional[str] = field(
+ default=None,
+ metadata={
+ "help": 'The name of the validation split in the input dataset. If not specified, will use the "validation" split when do_eval is enabled'
+ },
+ )
+ test_split_name: Optional[str] = field(
+ default=None,
+ metadata={
+ "help": 'The name of the test split in the input dataset. If not specified, will use the "test" split when do_predict is enabled'
+ },
+ )
+ remove_splits: Optional[str] = field(
+ default=None,
+ metadata={"help": "The splits to remove from the dataset. Multiple splits should be separated by commas."},
+ )
+ remove_columns: Optional[str] = field(
+ default=None,
+ metadata={"help": "The columns to remove from the dataset. Multiple columns should be separated by commas."},
+ )
+ label_column_name: Optional[str] = field(
+ default=None,
+ metadata={
+ "help": (
+ "The name of the label column in the input dataset or a CSV/JSON file."
+ 'If not specified, will use the "label" column for single/multi-label classifcation task'
+ )
+ },
+ )
+ max_seq_length: int = field(
+ default=128,
+ metadata={
+ "help": (
+ "The maximum total input sequence length after tokenization. Sequences longer "
+ "than this will be truncated, sequences shorter will be padded."
+ )
+ },
+ )
+ overwrite_cache: bool = field(
+ default=False, metadata={"help": "Overwrite the cached preprocessed datasets or not."}
+ )
+ pad_to_max_length: bool = field(
+ default=True,
+ metadata={
+ "help": (
+ "Whether to pad all samples to `max_seq_length`. "
+ "If False, will pad the samples dynamically when batching to the maximum length in the batch."
+ )
+ },
+ )
+ shuffle_train_dataset: bool = field(
+ default=False, metadata={"help": "Whether to shuffle the train dataset or not."}
+ )
+ shuffle_seed: int = field(
+ default=42, metadata={"help": "Random seed that will be used to shuffle the train dataset."}
+ )
+ max_train_samples: Optional[int] = field(
+ default=None,
+ metadata={
+ "help": (
+ "For debugging purposes or quicker training, truncate the number of training examples to this "
+ "value if set."
+ )
+ },
+ )
+ max_eval_samples: Optional[int] = field(
+ default=None,
+ metadata={
+ "help": (
+ "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
+ "value if set."
+ )
+ },
+ )
+ max_predict_samples: Optional[int] = field(
+ default=None,
+ metadata={
+ "help": (
+ "For debugging purposes or quicker training, truncate the number of prediction examples to this "
+ "value if set."
+ )
+ },
+ )
+ metric_name: Optional[str] = field(default=None, metadata={"help": "The metric to use for evaluation."})
+ train_file: Optional[str] = field(
+ default=None, metadata={"help": "A csv or a json file containing the training data."}
+ )
+ validation_file: Optional[str] = field(
+ default=None, metadata={"help": "A csv or a json file containing the validation data."}
+ )
+ test_file: Optional[str] = field(default=None, metadata={"help": "A csv or a json file containing the test data."})
+
+ def __post_init__(self):
+ if self.dataset_name is None:
+ if self.train_file is None or self.validation_file is None:
+ raise ValueError(" training/validation file or a dataset name.")
+
+ train_extension = self.train_file.split(".")[-1]
+ assert train_extension in ["csv", "json"], "`train_file` should be a csv or a json file."
+ validation_extension = self.validation_file.split(".")[-1]
+ assert (
+ validation_extension == train_extension
+ ), "`validation_file` should have the same extension (csv or json) as `train_file`."
+
+
+@dataclass
+class ModelArguments:
+ """
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
+ """
+
+ model_name_or_path: str = field(
+ metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
+ )
+ config_name: Optional[str] = field(
+ default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
+ )
+ tokenizer_name: Optional[str] = field(
+ default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
+ )
+ cache_dir: Optional[str] = field(
+ default=None,
+ metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"},
+ )
+ use_fast_tokenizer: bool = field(
+ default=True,
+ metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
+ )
+ model_revision: str = field(
+ default="main",
+ metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
+ )
+ token: str = field(
+ default=None,
+ metadata={
+ "help": (
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
+ )
+ },
+ )
+ use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
+ trust_remote_code: bool = field(
+ default=False,
+ metadata={
+ "help": (
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
+ )
+ },
+ )
+ ignore_mismatched_sizes: bool = field(
+ default=False,
+ metadata={"help": "Will enable to load a pretrained model whose head dimensions are different."},
+ )
+
+
+def get_label_list(raw_dataset, split="train") -> List[str]:
+ """Get the list of labels from a mutli-label dataset"""
+
+ if isinstance(raw_dataset[split]["label"][0], list):
+ label_list = [label for sample in raw_dataset[split]["label"] for label in sample]
+ label_list = list(set(label_list))
+ else:
+ label_list = raw_dataset[split].unique("label")
+ # we will treat the label list as a list of string instead of int, consistent with model.config.label2id
+ label_list = [str(label) for label in label_list]
+ return label_list
+
+
+def main():
+ # See all possible arguments in src/transformers/training_args.py
+ # or by passing the --help flag to this script.
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
+
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
+ # If we pass only one argument to the script and it's the path to a json file,
+ # let's parse it to get our arguments.
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
+ else:
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
+ # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
+ # information sent is the one passed as arguments along with your Python/PyTorch versions.
+ send_example_telemetry("run_classification", model_args, data_args)
+
+ # Setup logging
+ logging.basicConfig(
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
+ datefmt="%m/%d/%Y %H:%M:%S",
+ handlers=[logging.StreamHandler(sys.stdout)],
+ )
+
+ if training_args.should_log:
+ # The default of training_args.log_level is passive, so we set log level at info here to have that default.
+ transformers.utils.logging.set_verbosity_info()
+
+ log_level = training_args.get_process_log_level()
+ logger.setLevel(log_level)
+ datasets.utils.logging.set_verbosity(log_level)
+ transformers.utils.logging.set_verbosity(log_level)
+ transformers.utils.logging.enable_default_handler()
+ transformers.utils.logging.enable_explicit_format()
+
+ # Log on each process the small summary:
+ logger.warning(
+ f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
+ + f"distributed training: {training_args.parallel_mode.value == 'distributed'}, 16-bits training: {training_args.fp16}"
+ )
+ logger.info(f"Training/evaluation parameters {training_args}")
+
+ # Detecting last checkpoint.
+ last_checkpoint = None
+ if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
+ last_checkpoint = get_last_checkpoint(training_args.output_dir)
+ if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
+ raise ValueError(
+ f"Output directory ({training_args.output_dir}) already exists and is not empty. "
+ "Use --overwrite_output_dir to overcome."
+ )
+ elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
+ logger.info(
+ f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
+ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
+ )
+
+ # Set seed before initializing model.
+ set_seed(training_args.seed)
+
+ # Get the datasets: you can either provide your own CSV/JSON training and evaluation files, or specify a dataset name
+ # to load from huggingface/datasets. In ether case, you can specify a the key of the column(s) containing the text and
+ # the key of the column containing the label. If multiple columns are specified for the text, they will be joined togather
+ # for the actual text value.
+ # In distributed training, the load_dataset function guarantee that only one local process can concurrently
+ # download the dataset.
+ if data_args.dataset_name is not None:
+ # Downloading and loading a dataset from the hub.
+ raw_datasets = load_dataset(
+ data_args.dataset_name,
+ data_args.dataset_config_name,
+ cache_dir=model_args.cache_dir,
+ token=model_args.token,
+ )
+ # Try print some info about the dataset
+ logger.info(f"Dataset loaded: {raw_datasets}")
+ logger.info(raw_datasets)
+ else:
+ # Loading a dataset from your local files.
+ # CSV/JSON training and evaluation files are needed.
+ data_files = {"train": data_args.train_file, "validation": data_args.validation_file}
+
+ # Get the test dataset: you can provide your own CSV/JSON test file
+ if training_args.do_predict:
+ if data_args.test_file is not None:
+ train_extension = data_args.train_file.split(".")[-1]
+ test_extension = data_args.test_file.split(".")[-1]
+ assert (
+ test_extension == train_extension
+ ), "`test_file` should have the same extension (csv or json) as `train_file`."
+ data_files["test"] = data_args.test_file
+ else:
+ raise ValueError("Need either a dataset name or a test file for `do_predict`.")
+
+ for key in data_files.keys():
+ logger.info(f"load a local file for {key}: {data_files[key]}")
+
+ if data_args.train_file.endswith(".csv"):
+ # Loading a dataset from local csv files
+ raw_datasets = load_dataset(
+ "csv",
+ data_files=data_files,
+ cache_dir=model_args.cache_dir,
+ token=model_args.token,
+ )
+ else:
+ # Loading a dataset from local json files
+ raw_datasets = load_dataset(
+ "json",
+ data_files=data_files,
+ cache_dir=model_args.cache_dir,
+ token=model_args.token,
+ )
+
+ # See more about loading any type of standard or custom dataset at
+ # https://huggingface.co/docs/datasets/loading_datasets.html.
+
+ if data_args.remove_splits is not None:
+ for split in data_args.remove_splits.split(","):
+ logger.info(f"removing split {split}")
+ raw_datasets.pop(split)
+
+ if data_args.train_split_name is not None:
+ logger.info(f"using {data_args.validation_split_name} as validation set")
+ raw_datasets["train"] = raw_datasets[data_args.train_split_name]
+ raw_datasets.pop(data_args.train_split_name)
+
+ if data_args.validation_split_name is not None:
+ logger.info(f"using {data_args.validation_split_name} as validation set")
+ raw_datasets["validation"] = raw_datasets[data_args.validation_split_name]
+ raw_datasets.pop(data_args.validation_split_name)
+
+ if data_args.test_split_name is not None:
+ logger.info(f"using {data_args.test_split_name} as test set")
+ raw_datasets["test"] = raw_datasets[data_args.test_split_name]
+ raw_datasets.pop(data_args.test_split_name)
+
+ if data_args.remove_columns is not None:
+ for split in raw_datasets.keys():
+ for column in data_args.remove_columns.split(","):
+ logger.info(f"removing column {column} from split {split}")
+ raw_datasets[split].remove_columns(column)
+
+ if data_args.label_column_name is not None and data_args.label_column_name != "label":
+ for key in raw_datasets.keys():
+ raw_datasets[key] = raw_datasets[key].rename_column(data_args.label_column_name, "label")
+
+ # Trying to have good defaults here, don't hesitate to tweak to your needs.
+
+ is_regression = (
+ raw_datasets["train"].features["label"].dtype in ["float32", "float64"]
+ if data_args.do_regression is None
+ else data_args.do_regression
+ )
+
+ is_multi_label = False
+ if is_regression:
+ label_list = None
+ num_labels = 1
+ # regession requires float as label type, let's cast it if needed
+ for split in raw_datasets.keys():
+ if raw_datasets[split].features["label"].dtype not in ["float32", "float64"]:
+ logger.warning(
+ f"Label type for {split} set to float32, was {raw_datasets[split].features['label'].dtype}"
+ )
+ features = raw_datasets[split].features
+ features.update({"label": Value("float32")})
+ try:
+ raw_datasets[split] = raw_datasets[split].cast(features)
+ except TypeError as error:
+ logger.error(
+ f"Unable to cast {split} set to float32, please check the labels are correct, or maybe try with --do_regression=False"
+ )
+ raise error
+
+ else: # classification
+ if raw_datasets["train"].features["label"].dtype == "list": # multi-label classification
+ is_multi_label = True
+ logger.info("Label type is list, doing multi-label classification")
+ # Trying to find the number of labels in a multi-label classification task
+ # We have to deal with common cases that labels appear in the training set but not in the validation/test set.
+ # So we build the label list from the union of labels in train/val/test.
+ label_list = get_label_list(raw_datasets, split="train")
+ for split in ["validation", "test"]:
+ if split in raw_datasets:
+ val_or_test_labels = get_label_list(raw_datasets, split=split)
+ diff = set(val_or_test_labels).difference(set(label_list))
+ if len(diff) > 0:
+ # add the labels that appear in val/test but not in train, throw a warning
+ logger.warning(
+ f"Labels {diff} in {split} set but not in training set, adding them to the label list"
+ )
+ label_list += list(diff)
+ # if label is -1, we throw a warning and remove it from the label list
+ for label in label_list:
+ if label == -1:
+ logger.warning("Label -1 found in label list, removing it.")
+ label_list.remove(label)
+
+ label_list.sort()
+ num_labels = len(label_list)
+ if num_labels <= 1:
+ raise ValueError("You need more than one label to do classification.")
+
+ # Load pretrained model and tokenizer
+ # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
+ # download model & vocab.
+ config = AutoConfig.from_pretrained(
+ model_args.config_name if model_args.config_name else model_args.model_name_or_path,
+ num_labels=num_labels,
+ finetuning_task="text-classification",
+ cache_dir=model_args.cache_dir,
+ revision=model_args.model_revision,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
+ )
+
+ if is_regression:
+ config.problem_type = "regression"
+ logger.info("setting problem type to regression")
+ elif is_multi_label:
+ config.problem_type = "multi_label_classification"
+ logger.info("setting problem type to multi label classification")
+ else:
+ config.problem_type = "single_label_classification"
+ logger.info("setting problem type to single label classification")
+
+ tokenizer = AutoTokenizer.from_pretrained(
+ model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
+ cache_dir=model_args.cache_dir,
+ use_fast=model_args.use_fast_tokenizer,
+ revision=model_args.model_revision,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
+ )
+ model = AutoModelForSequenceClassification.from_pretrained(
+ model_args.model_name_or_path,
+ from_tf=bool(".ckpt" in model_args.model_name_or_path),
+ config=config,
+ cache_dir=model_args.cache_dir,
+ revision=model_args.model_revision,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
+ ignore_mismatched_sizes=model_args.ignore_mismatched_sizes,
+ )
+
+ # Padding strategy
+ if data_args.pad_to_max_length:
+ padding = "max_length"
+ else:
+ # We will pad later, dynamically at batch creation, to the max sequence length in each batch
+ padding = False
+
+ # for training ,we will update the config with label infos,
+ # if do_train is not set, we will use the label infos in the config
+ if training_args.do_train and not is_regression: # classification, training
+ label_to_id = {v: i for i, v in enumerate(label_list)}
+ # update config with label infos
+ if model.config.label2id != label_to_id:
+ logger.warning(
+ "The label2id key in the model config.json is not equal to the label2id key of this "
+ "run. You can ignore this if you are doing finetuning."
+ )
+ model.config.label2id = label_to_id
+ model.config.id2label = {id: label for label, id in config.label2id.items()}
+ elif not is_regression: # classification, but not training
+ logger.info("using label infos in the model config")
+ logger.info("label2id: {}".format(model.config.label2id))
+ label_to_id = model.config.label2id
+ else: # regression
+ label_to_id = None
+
+ if data_args.max_seq_length > tokenizer.model_max_length:
+ logger.warning(
+ f"The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the"
+ f"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}."
+ )
+ max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length)
+
+ def multi_labels_to_ids(labels: List[str]) -> List[float]:
+ ids = [0.0] * len(label_to_id) # BCELoss requires float as target type
+ for label in labels:
+ ids[label_to_id[label]] = 1.0
+ return ids
+
+ def preprocess_function(examples):
+ if data_args.text_column_names is not None:
+ text_column_names = data_args.text_column_names.split(",")
+ # join together text columns into "sentence" column
+ examples["sentence"] = examples[text_column_names[0]]
+ for column in text_column_names[1:]:
+ for i in range(len(examples[column])):
+ examples["sentence"][i] += data_args.text_column_delimiter + examples[column][i]
+ # Tokenize the texts
+ result = tokenizer(examples["sentence"], padding=padding, max_length=max_seq_length, truncation=True)
+ if label_to_id is not None and "label" in examples:
+ if is_multi_label:
+ result["label"] = [multi_labels_to_ids(l) for l in examples["label"]]
+ else:
+ result["label"] = [(label_to_id[str(l)] if l != -1 else -1) for l in examples["label"]]
+ return result
+
+ # Running the preprocessing pipeline on all the datasets
+ with training_args.main_process_first(desc="dataset map pre-processing"):
+ raw_datasets = raw_datasets.map(
+ preprocess_function,
+ batched=True,
+ load_from_cache_file=not data_args.overwrite_cache,
+ desc="Running tokenizer on dataset",
+ )
+
+ if training_args.do_train:
+ if "train" not in raw_datasets:
+ raise ValueError("--do_train requires a train dataset.")
+ train_dataset = raw_datasets["train"]
+ if data_args.shuffle_train_dataset:
+ logger.info("Shuffling the training dataset")
+ train_dataset = train_dataset.shuffle(seed=data_args.shuffle_seed)
+ if data_args.max_train_samples is not None:
+ max_train_samples = min(len(train_dataset), data_args.max_train_samples)
+ train_dataset = train_dataset.select(range(max_train_samples))
+
+ if training_args.do_eval:
+ if "validation" not in raw_datasets and "validation_matched" not in raw_datasets:
+ if "test" not in raw_datasets and "test_matched" not in raw_datasets:
+ raise ValueError("--do_eval requires a validation or test dataset if validation is not defined.")
+ else:
+ logger.warning("Validation dataset not found. Falling back to test dataset for validation.")
+ eval_dataset = raw_datasets["test"]
+ else:
+ eval_dataset = raw_datasets["validation"]
+
+ if data_args.max_eval_samples is not None:
+ max_eval_samples = min(len(eval_dataset), data_args.max_eval_samples)
+ eval_dataset = eval_dataset.select(range(max_eval_samples))
+
+ if training_args.do_predict or data_args.test_file is not None:
+ if "test" not in raw_datasets:
+ raise ValueError("--do_predict requires a test dataset")
+ predict_dataset = raw_datasets["test"]
+ # remove label column if it exists
+ if data_args.max_predict_samples is not None:
+ max_predict_samples = min(len(predict_dataset), data_args.max_predict_samples)
+ predict_dataset = predict_dataset.select(range(max_predict_samples))
+
+ # Log a few random samples from the training set:
+ if training_args.do_train:
+ for index in random.sample(range(len(train_dataset)), 3):
+ logger.info(f"Sample {index} of the training set: {train_dataset[index]}.")
+
+ if data_args.metric_name is not None:
+ metric = (
+ evaluate.load(data_args.metric_name, config_name="multilabel")
+ if is_multi_label
+ else evaluate.load(data_args.metric_name)
+ )
+ logger.info(f"Using metric {data_args.metric_name} for evaluation.")
+ else:
+ if is_regression:
+ metric = evaluate.load("mse")
+ logger.info("Using mean squared error (mse) as regression score, you can use --metric_name to overwrite.")
+ else:
+ if is_multi_label:
+ metric = evaluate.load("f1", config_name="multilabel")
+ logger.info(
+ "Using multilabel F1 for multi-label classification task, you can use --metric_name to overwrite."
+ )
+ else:
+ metric = evaluate.load("accuracy")
+ logger.info("Using accuracy as classification score, you can use --metric_name to overwrite.")
+
+ def compute_metrics(p: EvalPrediction):
+ preds = p.predictions[0] if isinstance(p.predictions, tuple) else p.predictions
+ if is_regression:
+ preds = np.squeeze(preds)
+ result = metric.compute(predictions=preds, references=p.label_ids)
+ elif is_multi_label:
+ preds = np.array([np.where(p > 0.5, 1, 0) for p in preds])
+ # Micro F1 is commonly used in multi-label classification
+ result = metric.compute(predictions=preds, references=p.label_ids, average="micro")
+ else:
+ preds = np.argmax(preds, axis=1)
+ result = metric.compute(predictions=preds, references=p.label_ids)
+ if len(result) > 1:
+ result["combined_score"] = np.mean(list(result.values())).item()
+ return result
+
+ # Data collator will default to DataCollatorWithPadding when the tokenizer is passed to Trainer, so we change it if
+ # we already did the padding.
+ if data_args.pad_to_max_length:
+ data_collator = default_data_collator
+ elif training_args.fp16:
+ data_collator = DataCollatorWithPadding(tokenizer, pad_to_multiple_of=8)
+ else:
+ data_collator = None
+
+ # Initialize our Trainer
+ trainer = Trainer(
+ model=model,
+ args=training_args,
+ train_dataset=train_dataset if training_args.do_train else None,
+ eval_dataset=eval_dataset if training_args.do_eval else None,
+ compute_metrics=compute_metrics,
+ tokenizer=tokenizer,
+ data_collator=data_collator,
+ )
+
+ # Training
+ if training_args.do_train:
+ checkpoint = None
+ if training_args.resume_from_checkpoint is not None:
+ checkpoint = training_args.resume_from_checkpoint
+ elif last_checkpoint is not None:
+ checkpoint = last_checkpoint
+ train_result = trainer.train(resume_from_checkpoint=checkpoint)
+ metrics = train_result.metrics
+ max_train_samples = (
+ data_args.max_train_samples if data_args.max_train_samples is not None else len(train_dataset)
+ )
+ metrics["train_samples"] = min(max_train_samples, len(train_dataset))
+ trainer.save_model() # Saves the tokenizer too for easy upload
+ trainer.log_metrics("train", metrics)
+ trainer.save_metrics("train", metrics)
+ trainer.save_state()
+
+ # Evaluation
+ if training_args.do_eval:
+ logger.info("*** Evaluate ***")
+ metrics = trainer.evaluate(eval_dataset=eval_dataset)
+ max_eval_samples = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(eval_dataset)
+ metrics["eval_samples"] = min(max_eval_samples, len(eval_dataset))
+ trainer.log_metrics("eval", metrics)
+ trainer.save_metrics("eval", metrics)
+
+ if training_args.do_predict:
+ logger.info("*** Predict ***")
+ # Removing the `label` columns if exists because it might contains -1 and Trainer won't like that.
+ if "label" in predict_dataset.features:
+ predict_dataset = predict_dataset.remove_columns("label")
+ predictions = trainer.predict(predict_dataset, metric_key_prefix="predict").predictions
+ if is_regression:
+ predictions = np.squeeze(predictions)
+ elif is_multi_label:
+ predictions = np.array([np.where(p > 0.5, 1, 0) for p in predictions])
+ else:
+ predictions = np.argmax(predictions, axis=1)
+ output_predict_file = os.path.join(training_args.output_dir, "predict_results.txt")
+ if trainer.is_world_process_zero():
+ with open(output_predict_file, "w") as writer:
+ logger.info("***** Predict results *****")
+ writer.write("index\tprediction\n")
+ for index, item in enumerate(predictions):
+ if is_regression:
+ writer.write(f"{index}\t{item:3.3f}\n")
+ elif is_multi_label:
+ # recover from multi-hot encoding
+ item = [label_list[i] for i in range(len(item)) if item[i] == 1]
+ writer.write(f"{index}\t{item}\n")
+ else:
+ item = label_list[item]
+ writer.write(f"{index}\t{item}\n")
+ logger.info("Predict results saved at {}".format(output_predict_file))
+ kwargs = {"finetuned_from": model_args.model_name_or_path, "tasks": "text-classification"}
+
+ if training_args.push_to_hub:
+ trainer.push_to_hub(**kwargs)
+ else:
+ trainer.create_model_card(**kwargs)
+
+
+def _mp_fn(index):
+ # For xla_spawn (TPUs)
+ main()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/pytorch/text-classification/run_glue.py b/examples/pytorch/text-classification/run_glue.py
index 1bb4c7bee7b8..1d702ef524ab 100755
--- a/examples/pytorch/text-classification/run_glue.py
+++ b/examples/pytorch/text-classification/run_glue.py
@@ -20,6 +20,7 @@
import os
import random
import sys
+import warnings
from dataclasses import dataclass, field
from typing import Optional
@@ -48,7 +49,7 @@
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
-check_min_version("4.29.0.dev0")
+check_min_version("4.32.0.dev0")
require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/text-classification/requirements.txt")
@@ -188,12 +189,28 @@ class ModelArguments:
default="main",
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
)
+ token: str = field(
+ default=None,
+ metadata={
+ "help": (
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
+ )
+ },
+ )
use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
+ trust_remote_code: bool = field(
default=False,
metadata={
"help": (
- "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
- "with private models)."
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
)
},
)
@@ -216,6 +233,12 @@ def main():
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_glue", model_args, data_args)
@@ -241,7 +264,7 @@ def main():
# Log on each process the small summary:
logger.warning(
f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
- + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
+ + f"distributed training: {training_args.parallel_mode.value == 'distributed'}, 16-bits training: {training_args.fp16}"
)
logger.info(f"Training/evaluation parameters {training_args}")
@@ -281,7 +304,7 @@ def main():
"glue",
data_args.task_name,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
elif data_args.dataset_name is not None:
# Downloading and loading a dataset from the hub.
@@ -289,7 +312,7 @@ def main():
data_args.dataset_name,
data_args.dataset_config_name,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
else:
# Loading a dataset from your local files.
@@ -318,7 +341,7 @@ def main():
"csv",
data_files=data_files,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
else:
# Loading a dataset from local json files
@@ -326,7 +349,7 @@ def main():
"json",
data_files=data_files,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
# See more about loading any type of standard or custom dataset at
# https://huggingface.co/docs/datasets/loading_datasets.html.
@@ -361,14 +384,16 @@ def main():
finetuning_task=data_args.task_name,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
tokenizer = AutoTokenizer.from_pretrained(
model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
use_fast=model_args.use_fast_tokenizer,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
model = AutoModelForSequenceClassification.from_pretrained(
model_args.model_name_or_path,
@@ -376,7 +401,8 @@ def main():
config=config,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
ignore_mismatched_sizes=model_args.ignore_mismatched_sizes,
)
@@ -486,6 +512,8 @@ def preprocess_function(examples):
# Get the metric function
if data_args.task_name is not None:
metric = evaluate.load("glue", data_args.task_name)
+ elif is_regression:
+ metric = evaluate.load("mse")
else:
metric = evaluate.load("accuracy")
@@ -494,15 +522,10 @@ def preprocess_function(examples):
def compute_metrics(p: EvalPrediction):
preds = p.predictions[0] if isinstance(p.predictions, tuple) else p.predictions
preds = np.squeeze(preds) if is_regression else np.argmax(preds, axis=1)
- if data_args.task_name is not None:
- result = metric.compute(predictions=preds, references=p.label_ids)
- if len(result) > 1:
- result["combined_score"] = np.mean(list(result.values())).item()
- return result
- elif is_regression:
- return {"mse": ((preds - p.label_ids) ** 2).mean().item()}
- else:
- return {"accuracy": (preds == p.label_ids).astype(np.float32).mean().item()}
+ result = metric.compute(predictions=preds, references=p.label_ids)
+ if len(result) > 1:
+ result["combined_score"] = np.mean(list(result.values())).item()
+ return result
# Data collator will default to DataCollatorWithPadding when the tokenizer is passed to Trainer, so we change it if
# we already did the padding.
diff --git a/examples/pytorch/text-classification/run_glue_no_trainer.py b/examples/pytorch/text-classification/run_glue_no_trainer.py
index c71581f7811c..d649cf00b79a 100644
--- a/examples/pytorch/text-classification/run_glue_no_trainer.py
+++ b/examples/pytorch/text-classification/run_glue_no_trainer.py
@@ -43,12 +43,12 @@
default_data_collator,
get_scheduler,
)
-from transformers.utils import check_min_version, get_full_repo_name, send_example_telemetry
+from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
-check_min_version("4.29.0.dev0")
+check_min_version("4.32.0.dev0")
logger = get_logger(__name__)
@@ -156,6 +156,16 @@ def parse_args():
"--hub_model_id", type=str, help="The name of the repository to keep in sync with the local `output_dir`."
)
parser.add_argument("--hub_token", type=str, help="The token to use to push to the Model Hub.")
+ parser.add_argument(
+ "--trust_remote_code",
+ type=bool,
+ default=False,
+ help=(
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
+ ),
+ )
parser.add_argument(
"--checkpointing_steps",
type=str,
@@ -217,7 +227,7 @@ def main():
# If we're using tracking, we also need to initialize it here and it will by default pick up all supported trackers
# in the environment
accelerator = (
- Accelerator(log_with=args.report_to, logging_dir=args.output_dir) if args.with_tracking else Accelerator()
+ Accelerator(log_with=args.report_to, project_dir=args.output_dir) if args.with_tracking else Accelerator()
)
# Make one log on every process with the configuration for debugging.
logging.basicConfig(
@@ -240,12 +250,14 @@ def main():
# Handle the repository creation
if accelerator.is_main_process:
if args.push_to_hub:
- if args.hub_model_id is None:
- repo_name = get_full_repo_name(Path(args.output_dir).name, token=args.hub_token)
- else:
- repo_name = args.hub_model_id
- create_repo(repo_name, exist_ok=True, token=args.hub_token)
- repo = Repository(args.output_dir, clone_from=repo_name, token=args.hub_token)
+ # Retrieve of infer repo_name
+ repo_name = args.hub_model_id
+ if repo_name is None:
+ repo_name = Path(args.output_dir).absolute().name
+ # Create repo and retrieve repo_id
+ repo_id = create_repo(repo_name, exist_ok=True, token=args.hub_token).repo_id
+ # Clone repo locally
+ repo = Repository(args.output_dir, clone_from=repo_id, token=args.hub_token)
with open(os.path.join(args.output_dir, ".gitignore"), "w+") as gitignore:
if "step_*" not in gitignore:
@@ -307,13 +319,21 @@ def main():
#
# In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
# download model & vocab.
- config = AutoConfig.from_pretrained(args.model_name_or_path, num_labels=num_labels, finetuning_task=args.task_name)
- tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path, use_fast=not args.use_slow_tokenizer)
+ config = AutoConfig.from_pretrained(
+ args.model_name_or_path,
+ num_labels=num_labels,
+ finetuning_task=args.task_name,
+ trust_remote_code=args.trust_remote_code,
+ )
+ tokenizer = AutoTokenizer.from_pretrained(
+ args.model_name_or_path, use_fast=not args.use_slow_tokenizer, trust_remote_code=args.trust_remote_code
+ )
model = AutoModelForSequenceClassification.from_pretrained(
args.model_name_or_path,
from_tf=bool(".ckpt" in args.model_name_or_path),
config=config,
ignore_mismatched_sizes=args.ignore_mismatched_sizes,
+ trust_remote_code=args.trust_remote_code,
)
# Preprocessing the datasets
@@ -487,35 +507,45 @@ def preprocess_function(examples):
# Potentially load in the weights and states from a previous save
if args.resume_from_checkpoint:
if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
- accelerator.print(f"Resumed from checkpoint: {args.resume_from_checkpoint}")
- accelerator.load_state(args.resume_from_checkpoint)
+ checkpoint_path = args.resume_from_checkpoint
path = os.path.basename(args.resume_from_checkpoint)
else:
# Get the most recent checkpoint
dirs = [f.name for f in os.scandir(os.getcwd()) if f.is_dir()]
dirs.sort(key=os.path.getctime)
path = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last
+ checkpoint_path = path
+ path = os.path.basename(checkpoint_path)
+
+ accelerator.print(f"Resumed from checkpoint: {checkpoint_path}")
+ accelerator.load_state(path)
# Extract `epoch_{i}` or `step_{i}`
training_difference = os.path.splitext(path)[0]
if "epoch" in training_difference:
starting_epoch = int(training_difference.replace("epoch_", "")) + 1
resume_step = None
+ completed_steps = starting_epoch * num_update_steps_per_epoch
else:
- resume_step = int(training_difference.replace("step_", ""))
+ # need to multiply `gradient_accumulation_steps` to reflect real steps
+ resume_step = int(training_difference.replace("step_", "")) * args.gradient_accumulation_steps
starting_epoch = resume_step // len(train_dataloader)
resume_step -= starting_epoch * len(train_dataloader)
+ completed_steps = resume_step // args.gradient_accumulation_step
+
+ # update the progress_bar if load from checkpoint
+ progress_bar.update(completed_steps)
for epoch in range(starting_epoch, args.num_train_epochs):
model.train()
if args.with_tracking:
total_loss = 0
- for step, batch in enumerate(train_dataloader):
- # We need to skip steps until we reach the resumed step
- if args.resume_from_checkpoint and epoch == starting_epoch:
- if resume_step is not None and step < resume_step:
- completed_steps += 1
- continue
+ if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None:
+ # We skip the first `n` batches in the dataloader when resuming from a checkpoint
+ active_dataloader = accelerator.skip_first_batches(train_dataloader, resume_step)
+ else:
+ active_dataloader = train_dataloader
+ for step, batch in enumerate(active_dataloader):
outputs = model(**batch)
loss = outputs.loss
# We keep track of the loss at each epoch
diff --git a/examples/pytorch/text-classification/run_xnli.py b/examples/pytorch/text-classification/run_xnli.py
index 88139986b286..1fae632518c7 100755
--- a/examples/pytorch/text-classification/run_xnli.py
+++ b/examples/pytorch/text-classification/run_xnli.py
@@ -21,6 +21,7 @@
import os
import random
import sys
+import warnings
from dataclasses import dataclass, field
from typing import Optional
@@ -48,7 +49,7 @@
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
-check_min_version("4.29.0.dev0")
+check_min_version("4.32.0.dev0")
require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/text-classification/requirements.txt")
@@ -152,12 +153,28 @@ class ModelArguments:
default="main",
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
)
+ token: str = field(
+ default=None,
+ metadata={
+ "help": (
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
+ )
+ },
+ )
use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
+ trust_remote_code: bool = field(
default=False,
metadata={
"help": (
- "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
- "with private models)."
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
)
},
)
@@ -175,6 +192,12 @@ def main():
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_xnli", model_args)
@@ -200,7 +223,7 @@ def main():
# Log on each process the small summary:
logger.warning(
f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
- + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
+ + f"distributed training: {training_args.parallel_mode.value == 'distributed'}, 16-bits training: {training_args.fp16}"
)
logger.info(f"Training/evaluation parameters {training_args}")
@@ -232,7 +255,7 @@ def main():
model_args.language,
split="train",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
else:
train_dataset = load_dataset(
@@ -240,7 +263,7 @@ def main():
model_args.train_language,
split="train",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
label_list = train_dataset.features["label"].names
@@ -250,7 +273,7 @@ def main():
model_args.language,
split="validation",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
label_list = eval_dataset.features["label"].names
@@ -260,7 +283,7 @@ def main():
model_args.language,
split="test",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
label_list = predict_dataset.features["label"].names
@@ -278,7 +301,8 @@ def main():
finetuning_task="xnli",
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
tokenizer = AutoTokenizer.from_pretrained(
model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
@@ -286,7 +310,8 @@ def main():
cache_dir=model_args.cache_dir,
use_fast=model_args.use_fast_tokenizer,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
model = AutoModelForSequenceClassification.from_pretrained(
model_args.model_name_or_path,
@@ -294,7 +319,8 @@ def main():
config=config,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
ignore_mismatched_sizes=model_args.ignore_mismatched_sizes,
)
diff --git a/examples/pytorch/text-generation/README.md b/examples/pytorch/text-generation/README.md
index 2177c45c3b88..fce4aef86b14 100644
--- a/examples/pytorch/text-generation/README.md
+++ b/examples/pytorch/text-generation/README.md
@@ -18,7 +18,7 @@ limitations under the License.
Based on the script [`run_generation.py`](https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-generation/run_generation.py).
-Conditional text generation using the auto-regressive models of the library: GPT, GPT-2, Transformer-XL, XLNet, CTRL.
+Conditional text generation using the auto-regressive models of the library: GPT, GPT-2, GPTJ, Transformer-XL, XLNet, CTRL, BLOOM, LLAMA, OPT.
A similar script is used for our official demo [Write With Transfomer](https://transformer.huggingface.co), where you
can try out the different models available in the library.
diff --git a/examples/pytorch/text-generation/requirements.txt b/examples/pytorch/text-generation/requirements.txt
index 0ef50f181f64..324a8cfb1c29 100644
--- a/examples/pytorch/text-generation/requirements.txt
+++ b/examples/pytorch/text-generation/requirements.txt
@@ -1,3 +1,4 @@
+accelerate >= 0.21.0
sentencepiece != 0.1.92
protobuf
torch >= 1.3
diff --git a/examples/pytorch/text-generation/run_generation.py b/examples/pytorch/text-generation/run_generation.py
index e0dda0ec0c2f..557b75572c99 100755
--- a/examples/pytorch/text-generation/run_generation.py
+++ b/examples/pytorch/text-generation/run_generation.py
@@ -19,20 +19,29 @@
import argparse
+import inspect
import logging
from typing import Tuple
-import numpy as np
import torch
+from accelerate import PartialState
+from accelerate.utils import set_seed
from transformers import (
+ AutoTokenizer,
+ BloomForCausalLM,
+ BloomTokenizerFast,
CTRLLMHeadModel,
CTRLTokenizer,
GenerationMixin,
GPT2LMHeadModel,
GPT2Tokenizer,
+ GPTJForCausalLM,
+ LlamaForCausalLM,
+ LlamaTokenizer,
OpenAIGPTLMHeadModel,
OpenAIGPTTokenizer,
+ OPTForCausalLM,
TransfoXLLMHeadModel,
TransfoXLTokenizer,
XLMTokenizer,
@@ -59,6 +68,10 @@
"xlnet": (XLNetLMHeadModel, XLNetTokenizer),
"transfo-xl": (TransfoXLLMHeadModel, TransfoXLTokenizer),
"xlm": (XLMWithLMHeadModel, XLMTokenizer),
+ "gptj": (GPTJForCausalLM, AutoTokenizer),
+ "bloom": (BloomForCausalLM, BloomTokenizerFast),
+ "llama": (LlamaForCausalLM, LlamaTokenizer),
+ "opt": (OPTForCausalLM, GPT2Tokenizer),
}
# Padding text to help Transformer-XL and XLNet with short prompts as proposed by Aman Rusia
@@ -76,13 +89,6 @@
with people, even a bishop, begging for his blessing. """
-def set_seed(args):
- np.random.seed(args.seed)
- torch.manual_seed(args.seed)
- if args.n_gpu > 0:
- torch.cuda.manual_seed_all(args.seed)
-
-
#
# Functions to prepare models' input
#
@@ -173,23 +179,26 @@ def sparse_model_config(model_config):
raise ValueError("Check the model config")
num_embedding_size_per_head = int(embedding_size / num_head)
- num_layer = model_config.n_layer
+ if hasattr(model_config, "n_layer"):
+ num_layer = model_config.n_layer
+ elif hasattr(model_config, "num_hidden_layers"):
+ num_layer = model_config.num_hidden_layers
+ else:
+ raise ValueError("Number of hidden layers couldn't be determined from the model config")
return num_layer, num_head, num_embedding_size_per_head
-def prepare_jit_inputs(inputs, model, tokenizer):
- num_batch = len(inputs)
- dummy_input = tokenizer.batch_encode_plus(inputs, return_tensors="pt", padding=True)
+def generate_past_key_values(model, batch_size, seq_len):
num_block_layers, num_attention_heads, num_embedding_size_per_head = sparse_model_config(model.config)
if model.config.model_type == "bloom":
past_key_values = tuple(
(
- torch.zeros(int(num_attention_heads * num_batch), num_embedding_size_per_head, 1)
- .to(model.config.torch_dtype)
+ torch.empty(int(num_attention_heads * batch_size), num_embedding_size_per_head, seq_len)
+ .to(model.dtype)
.to(model.device),
- torch.zeros(int(num_attention_heads * num_batch), 1, num_embedding_size_per_head)
- .to(model.config.torch_dtype)
+ torch.empty(int(num_attention_heads * batch_size), seq_len, num_embedding_size_per_head)
+ .to(model.dtype)
.to(model.device),
)
for _ in range(num_block_layers)
@@ -197,37 +206,34 @@ def prepare_jit_inputs(inputs, model, tokenizer):
else:
past_key_values = tuple(
(
- torch.zeros(num_batch, num_attention_heads, 1, num_embedding_size_per_head)
- .to(model.config.torch_dtype)
+ torch.empty(batch_size, num_attention_heads, seq_len, num_embedding_size_per_head)
+ .to(model.dtype)
.to(model.device),
- torch.zeros(num_batch, num_attention_heads, 1, num_embedding_size_per_head)
- .to(model.config.torch_dtype)
+ torch.empty(batch_size, num_attention_heads, seq_len, num_embedding_size_per_head)
+ .to(model.dtype)
.to(model.device),
)
for _ in range(num_block_layers)
)
+ return past_key_values
+
+def prepare_jit_inputs(inputs, model, tokenizer):
+ batch_size = len(inputs)
+ dummy_input = tokenizer.batch_encode_plus(inputs, return_tensors="pt")
+ dummy_input = dummy_input.to(model.device)
+ if model.config.use_cache:
+ dummy_input["past_key_values"] = generate_past_key_values(model, batch_size, 1)
dummy_input["attention_mask"] = torch.cat(
[
- torch.zeros(dummy_input["attention_mask"].shape[0], 1).to(dummy_input["attention_mask"].dtype),
+ torch.zeros(dummy_input["attention_mask"].shape[0], 1)
+ .to(dummy_input["attention_mask"].dtype)
+ .to(model.device),
dummy_input["attention_mask"],
],
-1,
)
-
- if model.config.use_cache:
- jit_inputs = (
- dummy_input["input_ids"].to(model.device),
- past_key_values,
- dummy_input["attention_mask"].to(model.device),
- )
- else:
- jit_inputs = (
- dummy_input["input_ids"].to(model.device),
- dummy_input["attention_mask"].to(model.device),
- )
-
- return jit_inputs
+ return dummy_input
class _ModelFallbackWrapper(GenerationMixin):
@@ -238,15 +244,13 @@ def __init__(self, optimized, default):
self._default = default
def __call__(self, *args, **kwargs):
- if kwargs["past_key_values"] is None:
- return self._default(*args, **kwargs)
- trace_graph_inputs = []
+ if kwargs["past_key_values"] is None and self._default.config.use_cache:
+ kwargs["past_key_values"] = generate_past_key_values(self._default, kwargs["input_ids"].shape[0], 0)
kwargs.pop("position_ids", None)
- for k, v in kwargs.items():
- if v is not None and not isinstance(v, bool):
- trace_graph_inputs.append(v)
- trace_graph_inputs = tuple(trace_graph_inputs)
- outputs = self._optimized(*trace_graph_inputs)
+ for k in list(kwargs.keys()):
+ if kwargs[k] is None or isinstance(kwargs[k], bool):
+ kwargs.pop(k)
+ outputs = self._optimized(**kwargs)
lm_logits = outputs[0]
past_key_values = outputs[1]
fixed_output = CausalLMOutputWithPast(
@@ -317,24 +321,27 @@ def main():
parser.add_argument("--xlm_language", type=str, default="", help="Optional language when used with the XLM model.")
parser.add_argument("--seed", type=int, default=42, help="random seed for initialization")
- parser.add_argument("--no_cuda", action="store_true", help="Avoid using CUDA when available")
+ parser.add_argument(
+ "--use_cpu",
+ action="store_true",
+ help="Whether or not to use cpu. If set to False, " "we will use gpu/npu or mps device if available",
+ )
parser.add_argument("--num_return_sequences", type=int, default=1, help="The number of samples to generate.")
parser.add_argument(
"--fp16",
action="store_true",
help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit",
)
- parser.add_argument(
- "--jit", type=bool, default=False, help="Whether or not to use jit trace to accelerate inference"
- )
+ parser.add_argument("--jit", action="store_true", help="Whether or not to use jit trace to accelerate inference")
args = parser.parse_args()
- args.device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu")
- args.n_gpu = 0 if args.no_cuda else torch.cuda.device_count()
+ # Initialize the distributed state.
+ distributed_state = PartialState(cpu=args.use_cpu)
- logger.warning(f"device: {args.device}, n_gpu: {args.n_gpu}, 16-bits training: {args.fp16}")
+ logger.warning(f"device: {distributed_state.device}, 16-bits inference: {args.fp16}")
- set_seed(args)
+ if args.seed is not None:
+ set_seed(args.seed)
# Initialize the model and tokenizer
try:
@@ -347,12 +354,14 @@ def main():
if tokenizer.pad_token is None:
tokenizer.pad_token = tokenizer.eos_token
model = model_class.from_pretrained(args.model_name_or_path)
- model.to(args.device)
+
+ # Set the model to the right device
+ model.to(distributed_state.device)
if args.fp16:
model.half()
-
- args.length = adjust_length_to_model(args.length, max_sequence_length=model.config.max_position_embeddings)
+ max_seq_length = getattr(model.config, "max_position_embeddings", 0)
+ args.length = adjust_length_to_model(args.length, max_sequence_length=max_seq_length)
logger.info(args)
prompt_text = args.prompt if args.prompt else input("Model prompt >>> ")
@@ -374,7 +383,7 @@ def main():
else:
prefix = args.prefix if args.prefix else args.padding_text
encoded_prompt = tokenizer.encode(prefix + prompt_text, add_special_tokens=False, return_tensors="pt")
- encoded_prompt = encoded_prompt.to(args.device)
+ encoded_prompt = encoded_prompt.to(distributed_state.device)
if encoded_prompt.size()[-1] == 0:
input_ids = None
@@ -382,10 +391,15 @@ def main():
input_ids = encoded_prompt
if args.jit:
- jit_input_texts = ["jit"]
+ jit_input_texts = ["enable jit"]
jit_inputs = prepare_jit_inputs(jit_input_texts, model, tokenizer)
torch._C._jit_set_texpr_fuser_enabled(False)
model.config.return_dict = False
+ if hasattr(model, "forward"):
+ sig = inspect.signature(model.forward)
+ else:
+ sig = inspect.signature(model.__call__)
+ jit_inputs = tuple(jit_inputs[key] for key in sig.parameters if jit_inputs.get(key, None) is not None)
traced_model = torch.jit.trace(model, jit_inputs, strict=False)
traced_model = torch.jit.freeze(traced_model.eval())
traced_model(*jit_inputs)
diff --git a/examples/pytorch/text-generation/run_generation_contrastive_search.py b/examples/pytorch/text-generation/run_generation_contrastive_search.py
index 117f063a6dd9..91781f05185f 100755
--- a/examples/pytorch/text-generation/run_generation_contrastive_search.py
+++ b/examples/pytorch/text-generation/run_generation_contrastive_search.py
@@ -23,8 +23,8 @@
import argparse
import logging
-import numpy as np
-import torch
+from accelerate import PartialState
+from accelerate.utils import set_seed
from transformers import AutoModelForCausalLM, AutoTokenizer
@@ -37,13 +37,6 @@
logger = logging.getLogger(__name__)
-def set_seed(args):
- np.random.seed(args.seed)
- torch.manual_seed(args.seed)
- if args.n_gpu > 0:
- torch.cuda.manual_seed_all(args.seed)
-
-
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
@@ -73,7 +66,11 @@ def main():
parser.add_argument("--xlm_language", type=str, default="", help="Optional language when used with the XLM model.")
parser.add_argument("--seed", type=int, default=42, help="random seed for initialization")
- parser.add_argument("--no_cuda", action="store_true", help="Avoid using CUDA when available")
+ parser.add_argument(
+ "--use_cpu",
+ action="store_true",
+ help="Whether or not to use cpu. If set to False, " "we will use gpu/npu or mps device if available",
+ )
parser.add_argument(
"--fp16",
action="store_true",
@@ -81,12 +78,13 @@ def main():
)
args = parser.parse_args()
- args.device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu")
- args.n_gpu = 0 if args.no_cuda else torch.cuda.device_count()
+ # Initialize the distributed state.
+ distributed_state = PartialState(cpu=args.use_cpu)
- logger.warning(f"device: {args.device}, n_gpu: {args.n_gpu}, 16-bits training: {args.fp16}")
+ logger.warning(f"device: {distributed_state.device}, 16-bits inference: {args.fp16}")
- set_seed(args)
+ if args.seed is not None:
+ set_seed(args.seed)
# Initialize the model and tokenizer
tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path)
@@ -94,7 +92,8 @@ def main():
# tokenizer = GPT2Tokenizer.from_pretrained(args.model_name_or_path)
# model = OPTForCausalLM.from_pretrained(args.model_name_or_path)
- model.to(args.device)
+ # Set the model to the right device
+ model.to(distributed_state.device)
if args.fp16:
model.half()
@@ -103,7 +102,7 @@ def main():
prompt_text = args.prompt if args.prompt else input("Model prompt >>> ")
inputs = tokenizer(prompt_text, return_tensors="pt", add_special_tokens=False)
- inputs = {key: value.to(args.device) for key, value in inputs.items()}
+ inputs = {key: value.to(distributed_state.device) for key, value in inputs.items()}
output_sequences = model.generate(
**inputs,
diff --git a/examples/pytorch/token-classification/run_ner.py b/examples/pytorch/token-classification/run_ner.py
index 9e5dd8d31bd2..fae5142c0ce6 100755
--- a/examples/pytorch/token-classification/run_ner.py
+++ b/examples/pytorch/token-classification/run_ner.py
@@ -22,6 +22,7 @@
import logging
import os
import sys
+import warnings
from dataclasses import dataclass, field
from typing import Optional
@@ -49,7 +50,7 @@
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
-check_min_version("4.29.0.dev0")
+check_min_version("4.32.0.dev0")
require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/token-classification/requirements.txt")
@@ -79,12 +80,28 @@ class ModelArguments:
default="main",
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
)
+ token: str = field(
+ default=None,
+ metadata={
+ "help": (
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
+ )
+ },
+ )
use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
+ trust_remote_code: bool = field(
default=False,
metadata={
"help": (
- "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
- "with private models)."
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
)
},
)
@@ -217,6 +234,12 @@ def main():
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_ner", model_args, data_args)
@@ -242,7 +265,7 @@ def main():
# Log on each process the small summary:
logger.warning(
f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
- + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
+ + f"distributed training: {training_args.parallel_mode.value == 'distributed'}, 16-bits training: {training_args.fp16}"
)
logger.info(f"Training/evaluation parameters {training_args}")
@@ -279,7 +302,7 @@ def main():
data_args.dataset_name,
data_args.dataset_config_name,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
else:
data_files = {}
@@ -348,7 +371,8 @@ def get_label_list(labels):
finetuning_task=data_args.task_name,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
tokenizer_name_or_path = model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path
@@ -358,7 +382,8 @@ def get_label_list(labels):
cache_dir=model_args.cache_dir,
use_fast=True,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
add_prefix_space=True,
)
else:
@@ -367,7 +392,8 @@ def get_label_list(labels):
cache_dir=model_args.cache_dir,
use_fast=True,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
model = AutoModelForTokenClassification.from_pretrained(
@@ -376,7 +402,8 @@ def get_label_list(labels):
config=config,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
ignore_mismatched_sizes=model_args.ignore_mismatched_sizes,
)
diff --git a/examples/pytorch/token-classification/run_ner_no_trainer.py b/examples/pytorch/token-classification/run_ner_no_trainer.py
index 800312839440..02431d43d8f6 100755
--- a/examples/pytorch/token-classification/run_ner_no_trainer.py
+++ b/examples/pytorch/token-classification/run_ner_no_trainer.py
@@ -28,6 +28,7 @@
import datasets
import evaluate
+import numpy as np
import torch
from accelerate import Accelerator
from accelerate.logging import get_logger
@@ -50,12 +51,12 @@
default_data_collator,
get_scheduler,
)
-from transformers.utils import check_min_version, get_full_repo_name, send_example_telemetry
+from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
-check_min_version("4.29.0.dev0")
+check_min_version("4.32.0.dev0")
logger = get_logger(__name__)
require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/token-classification/requirements.txt")
@@ -209,6 +210,16 @@ def parse_args():
"--hub_model_id", type=str, help="The name of the repository to keep in sync with the local `output_dir`."
)
parser.add_argument("--hub_token", type=str, help="The token to use to push to the Model Hub.")
+ parser.add_argument(
+ "--trust_remote_code",
+ type=bool,
+ default=False,
+ help=(
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
+ ),
+ )
parser.add_argument(
"--checkpointing_steps",
type=str,
@@ -271,7 +282,7 @@ def main():
# If we're using tracking, we also need to initialize it here and it will by default pick up all supported trackers
# in the environment
accelerator = (
- Accelerator(log_with=args.report_to, logging_dir=args.output_dir) if args.with_tracking else Accelerator()
+ Accelerator(log_with=args.report_to, project_dir=args.output_dir) if args.with_tracking else Accelerator()
)
# Make one log on every process with the configuration for debugging.
logging.basicConfig(
@@ -294,12 +305,14 @@ def main():
# Handle the repository creation
if accelerator.is_main_process:
if args.push_to_hub:
- if args.hub_model_id is None:
- repo_name = get_full_repo_name(Path(args.output_dir).name, token=args.hub_token)
- else:
- repo_name = args.hub_model_id
- create_repo(repo_name, exist_ok=True, token=args.hub_token)
- repo = Repository(args.output_dir, clone_from=repo_name, token=args.hub_token)
+ # Retrieve of infer repo_name
+ repo_name = args.hub_model_id
+ if repo_name is None:
+ repo_name = Path(args.output_dir).absolute().name
+ # Create repo and retrieve repo_id
+ repo_id = create_repo(repo_name, exist_ok=True, token=args.hub_token).repo_id
+ # Clone repo locally
+ repo = Repository(args.output_dir, clone_from=repo_id, token=args.hub_token)
with open(os.path.join(args.output_dir, ".gitignore"), "w+") as gitignore:
if "step_*" not in gitignore:
@@ -385,9 +398,13 @@ def get_label_list(labels):
# In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
# download model & vocab.
if args.config_name:
- config = AutoConfig.from_pretrained(args.config_name, num_labels=num_labels)
+ config = AutoConfig.from_pretrained(
+ args.config_name, num_labels=num_labels, trust_remote_code=args.trust_remote_code
+ )
elif args.model_name_or_path:
- config = AutoConfig.from_pretrained(args.model_name_or_path, num_labels=num_labels)
+ config = AutoConfig.from_pretrained(
+ args.model_name_or_path, num_labels=num_labels, trust_remote_code=args.trust_remote_code
+ )
else:
config = CONFIG_MAPPING[args.model_type]()
logger.warning("You are instantiating a new config instance from scratch.")
@@ -400,9 +417,13 @@ def get_label_list(labels):
)
if config.model_type in {"bloom", "gpt2", "roberta"}:
- tokenizer = AutoTokenizer.from_pretrained(tokenizer_name_or_path, use_fast=True, add_prefix_space=True)
+ tokenizer = AutoTokenizer.from_pretrained(
+ tokenizer_name_or_path, use_fast=True, add_prefix_space=True, trust_remote_code=args.trust_remote_code
+ )
else:
- tokenizer = AutoTokenizer.from_pretrained(tokenizer_name_or_path, use_fast=True)
+ tokenizer = AutoTokenizer.from_pretrained(
+ tokenizer_name_or_path, use_fast=True, trust_remote_code=args.trust_remote_code
+ )
if args.model_name_or_path:
model = AutoModelForTokenClassification.from_pretrained(
@@ -410,10 +431,11 @@ def get_label_list(labels):
from_tf=bool(".ckpt" in args.model_name_or_path),
config=config,
ignore_mismatched_sizes=args.ignore_mismatched_sizes,
+ trust_remote_code=args.trust_remote_code,
)
else:
logger.info("Training new model from scratch")
- model = AutoModelForTokenClassification.from_config(config)
+ model = AutoModelForTokenClassification.from_config(config, trust_remote_code=args.trust_remote_code)
# We resize the embeddings only when necessary to avoid index errors. If you are creating a model from scratch
# on a small vocab and want a smaller embedding size, remove this test.
@@ -645,35 +667,45 @@ def compute_metrics():
# Potentially load in the weights and states from a previous save
if args.resume_from_checkpoint:
if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
- accelerator.print(f"Resumed from checkpoint: {args.resume_from_checkpoint}")
- accelerator.load_state(args.resume_from_checkpoint)
+ checkpoint_path = args.resume_from_checkpoint
path = os.path.basename(args.resume_from_checkpoint)
else:
# Get the most recent checkpoint
dirs = [f.name for f in os.scandir(os.getcwd()) if f.is_dir()]
dirs.sort(key=os.path.getctime)
path = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last
+ checkpoint_path = path
+ path = os.path.basename(checkpoint_path)
+
+ accelerator.print(f"Resumed from checkpoint: {checkpoint_path}")
+ accelerator.load_state(path)
# Extract `epoch_{i}` or `step_{i}`
training_difference = os.path.splitext(path)[0]
if "epoch" in training_difference:
starting_epoch = int(training_difference.replace("epoch_", "")) + 1
resume_step = None
+ completed_steps = starting_epoch * num_update_steps_per_epoch
else:
- resume_step = int(training_difference.replace("step_", ""))
+ # need to multiply `gradient_accumulation_steps` to reflect real steps
+ resume_step = int(training_difference.replace("step_", "")) * args.gradient_accumulation_steps
starting_epoch = resume_step // len(train_dataloader)
resume_step -= starting_epoch * len(train_dataloader)
+ completed_steps = resume_step // args.gradient_accumulation_stepp
+
+ # update the progress_bar if load from checkpoint
+ progress_bar.update(completed_steps)
for epoch in range(starting_epoch, args.num_train_epochs):
model.train()
if args.with_tracking:
total_loss = 0
- for step, batch in enumerate(train_dataloader):
- # We need to skip steps until we reach the resumed step
- if args.resume_from_checkpoint and epoch == starting_epoch:
- if resume_step is not None and step < resume_step:
- completed_steps += 1
- continue
+ if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None:
+ # We skip the first `n` batches in the dataloader when resuming from a checkpoint
+ active_dataloader = accelerator.skip_first_batches(train_dataloader, resume_step)
+ else:
+ active_dataloader = train_dataloader
+ for step, batch in enumerate(active_dataloader):
outputs = model(**batch)
loss = outputs.loss
# We keep track of the loss at each epoch
@@ -771,6 +803,12 @@ def compute_metrics():
if args.with_tracking:
all_results.update({"train_loss": total_loss.item() / len(train_dataloader)})
with open(os.path.join(args.output_dir, "all_results.json"), "w") as f:
+ # Convert all float64 & int64 type numbers to float & int for json serialization
+ for key, value in all_results.items():
+ if isinstance(value, np.float64):
+ all_results[key] = float(value)
+ elif isinstance(value, np.int64):
+ all_results[key] = int(value)
json.dump(all_results, f)
diff --git a/examples/pytorch/translation/run_translation.py b/examples/pytorch/translation/run_translation.py
index d31a6a8ca035..1e39ab31bac9 100755
--- a/examples/pytorch/translation/run_translation.py
+++ b/examples/pytorch/translation/run_translation.py
@@ -21,6 +21,7 @@
import logging
import os
import sys
+import warnings
from dataclasses import dataclass, field
from typing import Optional
@@ -52,7 +53,7 @@
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
-check_min_version("4.29.0.dev0")
+check_min_version("4.32.0.dev0")
require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/translation/requirements.txt")
@@ -89,12 +90,28 @@ class ModelArguments:
default="main",
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
)
+ token: str = field(
+ default=None,
+ metadata={
+ "help": (
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
+ )
+ },
+ )
use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
+ trust_remote_code: bool = field(
default=False,
metadata={
"help": (
- "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
- "with private models)."
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
)
},
)
@@ -261,6 +278,12 @@ def main():
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_translation", model_args, data_args)
@@ -286,7 +309,7 @@ def main():
# Log on each process the small summary:
logger.warning(
f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
- + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
+ + f"distributed training: {training_args.parallel_mode.value == 'distributed'}, 16-bits training: {training_args.fp16}"
)
logger.info(f"Training/evaluation parameters {training_args}")
@@ -335,7 +358,7 @@ def main():
data_args.dataset_name,
data_args.dataset_config_name,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
else:
data_files = {}
@@ -352,7 +375,7 @@ def main():
extension,
data_files=data_files,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
# https://huggingface.co/docs/datasets/loading_datasets.html.
@@ -366,14 +389,16 @@ def main():
model_args.config_name if model_args.config_name else model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
tokenizer = AutoTokenizer.from_pretrained(
model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
use_fast=model_args.use_fast_tokenizer,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
model = AutoModelForSeq2SeqLM.from_pretrained(
model_args.model_name_or_path,
@@ -381,7 +406,8 @@ def main():
config=config,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
# We resize the embeddings only when necessary to avoid index errors. If you are creating a model from scratch
diff --git a/examples/pytorch/translation/run_translation_no_trainer.py b/examples/pytorch/translation/run_translation_no_trainer.py
index 29f3e49f0a07..243d35b3c161 100644
--- a/examples/pytorch/translation/run_translation_no_trainer.py
+++ b/examples/pytorch/translation/run_translation_no_trainer.py
@@ -52,12 +52,12 @@
default_data_collator,
get_scheduler,
)
-from transformers.utils import check_min_version, get_full_repo_name, send_example_telemetry
+from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
-check_min_version("4.29.0.dev0")
+check_min_version("4.32.0.dev0")
logger = get_logger(__name__)
require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/translation/requirements.txt")
@@ -257,6 +257,16 @@ def parse_args():
"--hub_model_id", type=str, help="The name of the repository to keep in sync with the local `output_dir`."
)
parser.add_argument("--hub_token", type=str, help="The token to use to push to the Model Hub.")
+ parser.add_argument(
+ "--trust_remote_code",
+ type=bool,
+ default=False,
+ help=(
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
+ ),
+ )
parser.add_argument(
"--checkpointing_steps",
type=str,
@@ -316,7 +326,7 @@ def main():
# If we're using tracking, we also need to initialize it here and it will by default pick up all supported trackers
# in the environment
accelerator = (
- Accelerator(log_with=args.report_to, logging_dir=args.output_dir) if args.with_tracking else Accelerator()
+ Accelerator(log_with=args.report_to, project_dir=args.output_dir) if args.with_tracking else Accelerator()
)
# Make one log on every process with the configuration for debugging.
@@ -340,12 +350,14 @@ def main():
# Handle the repository creation
if accelerator.is_main_process:
if args.push_to_hub:
- if args.hub_model_id is None:
- repo_name = get_full_repo_name(Path(args.output_dir).name, token=args.hub_token)
- else:
- repo_name = args.hub_model_id
- create_repo(repo_name, exist_ok=True, token=args.hub_token)
- repo = Repository(args.output_dir, clone_from=repo_name, token=args.hub_token)
+ # Retrieve of infer repo_name
+ repo_name = args.hub_model_id
+ if repo_name is None:
+ repo_name = Path(args.output_dir).absolute().name
+ # Create repo and retrieve repo_id
+ repo_id = create_repo(repo_name, exist_ok=True, token=args.hub_token).repo_id
+ # Clone repo locally
+ repo = Repository(args.output_dir, clone_from=repo_id, token=args.hub_token)
with open(os.path.join(args.output_dir, ".gitignore"), "w+") as gitignore:
if "step_*" not in gitignore:
@@ -384,17 +396,21 @@ def main():
# In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
# download model & vocab.
if args.config_name:
- config = AutoConfig.from_pretrained(args.config_name)
+ config = AutoConfig.from_pretrained(args.config_name, trust_remote_code=args.trust_remote_code)
elif args.model_name_or_path:
- config = AutoConfig.from_pretrained(args.model_name_or_path)
+ config = AutoConfig.from_pretrained(args.model_name_or_path, trust_remote_code=args.trust_remote_code)
else:
config = CONFIG_MAPPING[args.model_type]()
logger.warning("You are instantiating a new config instance from scratch.")
if args.tokenizer_name:
- tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=not args.use_slow_tokenizer)
+ tokenizer = AutoTokenizer.from_pretrained(
+ args.tokenizer_name, use_fast=not args.use_slow_tokenizer, trust_remote_code=args.trust_remote_code
+ )
elif args.model_name_or_path:
- tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path, use_fast=not args.use_slow_tokenizer)
+ tokenizer = AutoTokenizer.from_pretrained(
+ args.model_name_or_path, use_fast=not args.use_slow_tokenizer, trust_remote_code=args.trust_remote_code
+ )
else:
raise ValueError(
"You are instantiating a new tokenizer from scratch. This is not supported by this script."
@@ -406,10 +422,11 @@ def main():
args.model_name_or_path,
from_tf=bool(".ckpt" in args.model_name_or_path),
config=config,
+ trust_remote_code=args.trust_remote_code,
)
else:
logger.info("Training new model from scratch")
- model = AutoModelForSeq2SeqLM.from_config(config)
+ model = AutoModelForSeq2SeqLM.from_config(config, trust_remote_code=args.trust_remote_code)
# We resize the embeddings only when necessary to avoid index errors. If you are creating a model from scratch
# on a small vocab and want a smaller embedding size, remove this test.
@@ -593,42 +610,45 @@ def postprocess_text(preds, labels):
# Potentially load in the weights and states from a previous save
if args.resume_from_checkpoint:
if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
- accelerator.print(f"Resumed from checkpoint: {args.resume_from_checkpoint}")
- accelerator.load_state(args.resume_from_checkpoint)
+ checkpoint_path = args.resume_from_checkpoint
path = os.path.basename(args.resume_from_checkpoint)
else:
# Get the most recent checkpoint
dirs = [f.name for f in os.scandir(os.getcwd()) if f.is_dir()]
dirs.sort(key=os.path.getctime)
path = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last
+ checkpoint_path = path
+ path = os.path.basename(checkpoint_path)
+
+ accelerator.print(f"Resumed from checkpoint: {checkpoint_path}")
+ accelerator.load_state(path)
# Extract `epoch_{i}` or `step_{i}`
training_difference = os.path.splitext(path)[0]
if "epoch" in training_difference:
starting_epoch = int(training_difference.replace("epoch_", "")) + 1
resume_step = None
+ completed_steps = starting_epoch * num_update_steps_per_epoch
else:
# need to multiply `gradient_accumulation_steps` to reflect real steps
resume_step = int(training_difference.replace("step_", "")) * args.gradient_accumulation_steps
starting_epoch = resume_step // len(train_dataloader)
resume_step -= starting_epoch * len(train_dataloader)
+ completed_steps = resume_step // args.gradient_accumulation_stepp
# update the progress_bar if load from checkpoint
- progress_bar.update(starting_epoch * num_update_steps_per_epoch)
- completed_steps = starting_epoch * num_update_steps_per_epoch
+ progress_bar.update(completed_steps)
for epoch in range(starting_epoch, args.num_train_epochs):
model.train()
if args.with_tracking:
total_loss = 0
- for step, batch in enumerate(train_dataloader):
- # We need to skip steps until we reach the resumed step
- if args.resume_from_checkpoint and epoch == starting_epoch:
- if resume_step is not None and step < resume_step:
- if step % args.gradient_accumulation_steps == 0:
- progress_bar.update(1)
- completed_steps += 1
- continue
+ if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None:
+ # We skip the first `n` batches in the dataloader when resuming from a checkpoint
+ active_dataloader = accelerator.skip_first_batches(train_dataloader, resume_step)
+ else:
+ active_dataloader = train_dataloader
+ for step, batch in enumerate(active_dataloader):
outputs = model(**batch)
loss = outputs.loss
# We keep track of the loss at each epoch
diff --git a/examples/research_projects/bert-loses-patience/pabee/modeling_pabee_albert.py b/examples/research_projects/bert-loses-patience/pabee/modeling_pabee_albert.py
index 5e17352dc19b..57b649ec067b 100644
--- a/examples/research_projects/bert-loses-patience/pabee/modeling_pabee_albert.py
+++ b/examples/research_projects/bert-loses-patience/pabee/modeling_pabee_albert.py
@@ -253,7 +253,7 @@ def forward(
Returns:
:obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:class:`~transformers.AlbertConfig`) and inputs:
- loss: (`optional`, returned when ``labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:
+ loss (`optional`, returned when ``labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:
Classification (or regression if config.num_labels==1) loss.
logits ``torch.FloatTensor`` of shape ``(batch_size, config.num_labels)``
Classification (or regression if config.num_labels==1) scores (before SoftMax).
diff --git a/examples/research_projects/codeparrot/scripts/codeparrot_training.py b/examples/research_projects/codeparrot/scripts/codeparrot_training.py
index 2510e02c9470..16f6077f2415 100644
--- a/examples/research_projects/codeparrot/scripts/codeparrot_training.py
+++ b/examples/research_projects/codeparrot/scripts/codeparrot_training.py
@@ -7,6 +7,7 @@
import datasets
import torch
from accelerate import Accelerator, DistributedType
+from accelerate.utils import ProjectConfiguration
from arguments import TrainingArguments
from datasets import load_dataset
from huggingface_hub import Repository
@@ -195,7 +196,8 @@ def evaluate(args):
args = parser.parse_args()
# Accelerator
-accelerator = Accelerator(log_with=["wandb", "tensorboard"], logging_dir=f"{args.save_dir}/log")
+config = ProjectConfiguration(project_dir=args.save_dir, logging_dir="log")
+accelerator = Accelerator(log_with=["wandb", "tensorboard"], project_config=config)
acc_state = {str(k): str(v) for k, v in accelerator.state.__dict__.items()}
args = Namespace(**vars(args), **acc_state)
diff --git a/examples/research_projects/codeparrot/scripts/human_eval.py b/examples/research_projects/codeparrot/scripts/human_eval.py
index 157079881d5f..ef217a597e33 100644
--- a/examples/research_projects/codeparrot/scripts/human_eval.py
+++ b/examples/research_projects/codeparrot/scripts/human_eval.py
@@ -60,7 +60,7 @@ def __call__(self, input_ids, scores, **kwargs):
decoded_generations = self.tokenizer.batch_decode(input_ids[:, self.start_length :])
done = []
for decoded_generation in decoded_generations:
- done.append(any([stop_string in decoded_generation for stop_string in self.eof_strings]))
+ done.append(any(stop_string in decoded_generation for stop_string in self.eof_strings))
return all(done)
diff --git a/examples/research_projects/decision_transformer/requirements.txt b/examples/research_projects/decision_transformer/requirements.txt
index 3cf50951975c..88cd41d42b6f 100644
--- a/examples/research_projects/decision_transformer/requirements.txt
+++ b/examples/research_projects/decision_transformer/requirements.txt
@@ -1,5 +1,5 @@
absl-py==1.0.0
-aiohttp==3.8.1
+aiohttp==3.8.5
aiosignal==1.2.0
alembic==1.7.7
appdirs==1.4.4
@@ -20,7 +20,7 @@ boto3==1.16.34
botocore==1.19.63
Brotli==1.0.9
cachetools==5.0.0
-certifi==2022.12.7
+certifi==2023.7.22
cffi==1.15.0
chardet==4.0.0
charset-normalizer==2.0.12
@@ -34,7 +34,7 @@ cmd2==2.4.0
codecarbon==1.2.0
colorlog==6.6.0
cookiecutter==2.1.1
-cryptography==39.0.1
+cryptography==41.0.2
csvw==2.0.0
cycler==0.11.0
Cython==0.29.28
@@ -157,7 +157,7 @@ pycodestyle==2.8.0
pycparser==2.21
pyctcdecode==0.3.0
pyflakes==2.4.0
-Pygments==2.11.2
+Pygments==2.15.0
pygtrie==2.4.2
pynvml==11.4.1
pyOpenSSL==22.0.0
@@ -177,7 +177,7 @@ PyYAML==6.0
ray==1.11.0
redis==4.5.4
regex==2022.3.15
-requests==2.27.1
+requests==2.31.0
requests-oauthlib==1.3.1
resampy==0.2.2
responses==0.18.0
diff --git a/examples/research_projects/fsner/src/fsner/tokenizer_utils.py b/examples/research_projects/fsner/src/fsner/tokenizer_utils.py
index bc5f6650ccd9..b281ae6cfb89 100644
--- a/examples/research_projects/fsner/src/fsner/tokenizer_utils.py
+++ b/examples/research_projects/fsner/src/fsner/tokenizer_utils.py
@@ -17,7 +17,7 @@ def tokenize(self, x):
`transformers.tokenization_utils_base.BatchEncoding` dict with additional keys and values for start_token_id, end_token_id and sizes of example lists for each entity type
"""
- if isinstance(x, list) and all([isinstance(_x, list) for _x in x]):
+ if isinstance(x, list) and all(isinstance(_x, list) for _x in x):
d = None
for l in x:
t = self.tokenizer(
@@ -37,7 +37,7 @@ def tokenize(self, x):
d["start_token_id"] = torch.tensor(self.tokenizer.convert_tokens_to_ids("[E]"))
d["end_token_id"] = torch.tensor(self.tokenizer.convert_tokens_to_ids("[/E]"))
- elif isinstance(x, list) and all([isinstance(_x, str) for _x in x]):
+ elif isinstance(x, list) and all(isinstance(_x, str) for _x in x):
d = self.tokenizer(
x,
padding="max_length",
diff --git a/examples/research_projects/jax-projects/big_bird/prepare_natural_questions.py b/examples/research_projects/jax-projects/big_bird/prepare_natural_questions.py
index 6a202ba77522..ebbb184ccb6b 100644
--- a/examples/research_projects/jax-projects/big_bird/prepare_natural_questions.py
+++ b/examples/research_projects/jax-projects/big_bird/prepare_natural_questions.py
@@ -50,7 +50,7 @@ def choose_first(answer, is_long_answer=False):
answer["remove_it"] = False
cols = ["start_token", "end_token", "start_byte", "end_byte", "text"]
- if not all([isinstance(answer[k], list) for k in cols]):
+ if not all(isinstance(answer[k], list) for k in cols):
raise ValueError("Issue in ID", example["id"])
return answer
diff --git a/examples/research_projects/luke/run_luke_ner_no_trainer.py b/examples/research_projects/luke/run_luke_ner_no_trainer.py
index 4c5227d2c7e0..f12a7d76d80c 100644
--- a/examples/research_projects/luke/run_luke_ner_no_trainer.py
+++ b/examples/research_projects/luke/run_luke_ner_no_trainer.py
@@ -29,7 +29,7 @@
import torch
from accelerate import Accelerator, DistributedDataParallelKwargs
from datasets import ClassLabel, load_dataset, load_metric
-from huggingface_hub import Repository
+from huggingface_hub import Repository, create_repo
from luke_utils import DataCollatorForLukeTokenClassification, is_punctuation, padding_tensor
from torch.utils.data import DataLoader
from tqdm.auto import tqdm
@@ -45,7 +45,6 @@
get_scheduler,
set_seed,
)
-from transformers.file_utils import get_full_repo_name
from transformers.utils.versions import require_version
@@ -258,11 +257,14 @@ def main():
# Handle the repository creation
if accelerator.is_main_process:
if args.push_to_hub:
- if args.hub_model_id is None:
- repo_name = get_full_repo_name(Path(args.output_dir).name, token=args.hub_token)
- else:
- repo_name = args.hub_model_id
- repo = Repository(args.output_dir, clone_from=repo_name)
+ # Retrieve of infer repo_name
+ repo_name = args.hub_model_id
+ if repo_name is None:
+ repo_name = Path(args.output_dir).absolute().name
+ # Create repo and retrieve repo_id
+ repo_id = create_repo(repo_name, exist_ok=True, token=args.hub_token).repo_id
+ # Clone repo locally
+ repo = Repository(args.output_dir, clone_from=repo_id, token=args.hub_token)
elif args.output_dir is not None:
os.makedirs(args.output_dir, exist_ok=True)
accelerator.wait_for_everyone()
@@ -610,7 +612,7 @@ def get_luke_labels(outputs, ner_tags, original_entity_spans):
predicted_sequence = [label_list[0]] * len(true_tags)
for _, span, label in sorted(predictions, key=lambda o: o[0], reverse=True):
- if all([o == label_list[0] for o in predicted_sequence[span[0] : span[1]]]):
+ if all(o == label_list[0] for o in predicted_sequence[span[0] : span[1]]):
predicted_sequence[span[0]] = label
if span[1] - span[0] > 1:
predicted_sequence[span[0] + 1 : span[1]] = [label] * (span[1] - span[0] - 1)
diff --git a/examples/research_projects/lxmert/modeling_frcnn.py b/examples/research_projects/lxmert/modeling_frcnn.py
index edbd224cbe08..943588a5ed8c 100644
--- a/examples/research_projects/lxmert/modeling_frcnn.py
+++ b/examples/research_projects/lxmert/modeling_frcnn.py
@@ -554,8 +554,8 @@ def __init__(
assert thresholds[0] > 0
thresholds.insert(0, -float("inf"))
thresholds.append(float("inf"))
- assert all([low <= high for (low, high) in zip(thresholds[:-1], thresholds[1:])])
- assert all([label_i in [-1, 0, 1] for label_i in labels])
+ assert all(low <= high for (low, high) in zip(thresholds[:-1], thresholds[1:]))
+ assert all(label_i in [-1, 0, 1] for label_i in labels)
assert len(labels) == len(thresholds) - 1
self.thresholds = thresholds
self.labels = labels
diff --git a/examples/research_projects/lxmert/requirements.txt b/examples/research_projects/lxmert/requirements.txt
index 0d483b6d1892..3e7dc5b1b675 100644
--- a/examples/research_projects/lxmert/requirements.txt
+++ b/examples/research_projects/lxmert/requirements.txt
@@ -4,7 +4,7 @@ async-generator==1.10
attrs==20.2.0
backcall==0.2.0
CacheControl==0.12.6
-certifi==2022.12.7
+certifi==2023.7.22
cffi==1.14.2
chardet==3.0.4
click==7.1.2
@@ -75,7 +75,7 @@ pyzmq==19.0.2
qtconsole==4.7.7
QtPy==1.9.0
regex==2020.7.14
-requests==2.22.0
+requests==2.31.0
retrying==1.3.3
sacremoses==0.0.43
Send2Trash==1.5.0
@@ -86,7 +86,7 @@ testpath==0.4.4
tokenizers==0.8.1rc2
torch==1.6.0
torchvision==0.7.0
-tornado==6.0.4
+tornado==6.3.2
tqdm==4.48.2
traitlets
git+https://github.com/huggingface/transformers.git
diff --git a/examples/research_projects/visual_bert/modeling_frcnn.py b/examples/research_projects/visual_bert/modeling_frcnn.py
index edbd224cbe08..943588a5ed8c 100644
--- a/examples/research_projects/visual_bert/modeling_frcnn.py
+++ b/examples/research_projects/visual_bert/modeling_frcnn.py
@@ -554,8 +554,8 @@ def __init__(
assert thresholds[0] > 0
thresholds.insert(0, -float("inf"))
thresholds.append(float("inf"))
- assert all([low <= high for (low, high) in zip(thresholds[:-1], thresholds[1:])])
- assert all([label_i in [-1, 0, 1] for label_i in labels])
+ assert all(low <= high for (low, high) in zip(thresholds[:-1], thresholds[1:]))
+ assert all(label_i in [-1, 0, 1] for label_i in labels)
assert len(labels) == len(thresholds) - 1
self.thresholds = thresholds
self.labels = labels
diff --git a/examples/research_projects/visual_bert/requirements.txt b/examples/research_projects/visual_bert/requirements.txt
index 0d483b6d1892..3e7dc5b1b675 100644
--- a/examples/research_projects/visual_bert/requirements.txt
+++ b/examples/research_projects/visual_bert/requirements.txt
@@ -4,7 +4,7 @@ async-generator==1.10
attrs==20.2.0
backcall==0.2.0
CacheControl==0.12.6
-certifi==2022.12.7
+certifi==2023.7.22
cffi==1.14.2
chardet==3.0.4
click==7.1.2
@@ -75,7 +75,7 @@ pyzmq==19.0.2
qtconsole==4.7.7
QtPy==1.9.0
regex==2020.7.14
-requests==2.22.0
+requests==2.31.0
retrying==1.3.3
sacremoses==0.0.43
Send2Trash==1.5.0
@@ -86,7 +86,7 @@ testpath==0.4.4
tokenizers==0.8.1rc2
torch==1.6.0
torchvision==0.7.0
-tornado==6.0.4
+tornado==6.3.2
tqdm==4.48.2
traitlets
git+https://github.com/huggingface/transformers.git
diff --git a/examples/run_on_remote.py b/examples/run_on_remote.py
index 9d42ed845c9e..46f87065d761 100644
--- a/examples/run_on_remote.py
+++ b/examples/run_on_remote.py
@@ -21,7 +21,7 @@
if __name__ == "__main__":
- # Refer to https://runhouse-docs.readthedocs-hosted.com/en/main/rh_primitives/cluster.html#hardware-setup for cloud access
+ # Refer to https://runhouse-docs.readthedocs-hosted.com/en/latest/api/python/cluster.html#hardware-setup for cloud access
# setup instructions, if using on-demand hardware
# If user passes --user --host --key_path , fill them in as BYO cluster
diff --git a/examples/tensorflow/_tests_requirements.txt b/examples/tensorflow/_tests_requirements.txt
index d44a342b4f32..e28367c01c52 100644
--- a/examples/tensorflow/_tests_requirements.txt
+++ b/examples/tensorflow/_tests_requirements.txt
@@ -1,4 +1,4 @@
-tensorflow<2.13
+tensorflow<2.14
tensorboard
scikit-learn
seqeval
diff --git a/examples/tensorflow/contrastive-image-text/run_clip.py b/examples/tensorflow/contrastive-image-text/run_clip.py
index 35359a2fa708..bbbb6d75977d 100644
--- a/examples/tensorflow/contrastive-image-text/run_clip.py
+++ b/examples/tensorflow/contrastive-image-text/run_clip.py
@@ -26,6 +26,7 @@
import logging
import os
import sys
+import warnings
from dataclasses import dataclass, field
from typing import Optional
@@ -51,7 +52,7 @@
logger = logging.getLogger(__name__)
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
-check_min_version("4.29.0.dev0")
+check_min_version("4.32.0.dev0")
require_version(
"datasets>=1.8.0", "To fix: pip install -r examples/tensorflow/contrastive-image-text/requirements.txt"
@@ -92,12 +93,28 @@ class ModelArguments:
default=True,
metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
)
+ token: str = field(
+ default=None,
+ metadata={
+ "help": (
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
+ )
+ },
+ )
use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
+ trust_remote_code: bool = field(
default=False,
metadata={
"help": (
- "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
- "with private models)."
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
)
},
)
@@ -245,6 +262,12 @@ def main():
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
if model_args.model_name_or_path is not None:
if model_args.vision_model_name_or_path is not None or model_args.text_model_name_or_path is not None:
raise ValueError(
@@ -315,7 +338,7 @@ def main():
cache_dir=model_args.cache_dir,
keep_in_memory=False,
data_dir=data_args.data_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
else:
data_files = {}
@@ -332,7 +355,7 @@ def main():
extension,
data_files=data_files,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
# https://huggingface.co/docs/datasets/loading_datasets.html.
@@ -340,15 +363,27 @@ def main():
# 5. Load pretrained model, tokenizer, and image processor
if model_args.tokenizer_name:
tokenizer = AutoTokenizer.from_pretrained(
- model_args.tokenizer_name, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
+ model_args.tokenizer_name,
+ cache_dir=model_args.cache_dir,
+ use_fast=model_args.use_fast_tokenizer,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
elif model_args.model_name_or_path:
tokenizer = AutoTokenizer.from_pretrained(
- model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
+ model_args.model_name_or_path,
+ cache_dir=model_args.cache_dir,
+ use_fast=model_args.use_fast_tokenizer,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
elif model_args.text_model_name_or_path:
tokenizer = AutoTokenizer.from_pretrained(
- model_args.text_model_name_or_path, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
+ model_args.text_model_name_or_path,
+ cache_dir=model_args.cache_dir,
+ use_fast=model_args.use_fast_tokenizer,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
else:
raise ValueError(
@@ -362,14 +397,16 @@ def main():
model_args.image_processor_name or model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
with training_args.strategy.scope():
model = TFAutoModel.from_pretrained(
model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
else:
# Load image_processor, in this script we only use this to get the mean and std for normalization.
@@ -377,14 +414,16 @@ def main():
model_args.image_processor_name or model_args.vision_model_name_or_path,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
with training_args.strategy.scope():
model = TFVisionTextDualEncoderModel.from_vision_text_pretrained(
vision_model_name_or_path=model_args.vision_model_name_or_path,
text_model_name_or_path=model_args.text_model_name_or_path,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
config = model.config
@@ -561,6 +600,8 @@ def filter_corrupt_images(examples):
weight_decay_rate=training_args.weight_decay,
adam_global_clipnorm=training_args.max_grad_norm,
)
+ # Transformers models compute the right loss for their task by default when labels are passed, and will
+ # use this for training unless you specify your own loss function in compile().
model.compile(optimizer=optimizer, jit_compile=training_args.xla)
if not training_args.do_eval:
diff --git a/examples/tensorflow/image-classification/run_image_classification.py b/examples/tensorflow/image-classification/run_image_classification.py
index ee6ebfb46901..5223b7db0b3a 100644
--- a/examples/tensorflow/image-classification/run_image_classification.py
+++ b/examples/tensorflow/image-classification/run_image_classification.py
@@ -23,6 +23,7 @@
import logging
import os
import sys
+import warnings
from dataclasses import dataclass, field
from typing import Optional
@@ -54,7 +55,7 @@
logger = logging.getLogger(__name__)
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
-check_min_version("4.29.0.dev0")
+check_min_version("4.32.0.dev0")
require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/image-classification/requirements.txt")
@@ -157,12 +158,28 @@ class ModelArguments:
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
)
image_processor_name: str = field(default=None, metadata={"help": "Name or path of preprocessor config."})
+ token: str = field(
+ default=None,
+ metadata={
+ "help": (
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
+ )
+ },
+ )
use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
+ trust_remote_code: bool = field(
default=False,
metadata={
"help": (
- "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
- "with private models)."
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
)
},
)
@@ -226,6 +243,12 @@ def main():
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
if not (training_args.do_train or training_args.do_eval or training_args.do_predict):
exit("Must specify at least one of --do_train, --do_eval or --do_predict!")
@@ -275,7 +298,7 @@ def main():
data_args.dataset_config_name,
cache_dir=model_args.cache_dir,
task="image-classification",
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
else:
data_files = {}
@@ -309,13 +332,15 @@ def main():
finetuning_task="image-classification",
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
image_processor = AutoImageProcessor.from_pretrained(
model_args.image_processor_name or model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
# If we don't have a validation split, split off a percentage of train as validation.
@@ -435,7 +460,8 @@ def compute_metrics(p):
from_pt=bool(".bin" in model_path),
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
ignore_mismatched_sizes=model_args.ignore_mismatched_sizes,
)
num_replicas = training_args.strategy.num_replicas_in_sync
@@ -497,6 +523,8 @@ def compute_metrics(p):
collate_fn=collate_fn,
).with_options(dataset_options)
+ # Transformers models compute the right loss for their task by default when labels are passed, and will
+ # use this for training unless you specify your own loss function in compile().
model.compile(optimizer=optimizer, jit_compile=training_args.xla, metrics=["accuracy"])
push_to_hub_model_id = training_args.push_to_hub_model_id
@@ -543,6 +571,7 @@ def compute_metrics(p):
logging.info(f"{metric_name}: {value:.3f}")
if training_args.output_dir is not None:
+ os.makedirs(training_args.output_dir, exist_ok=True)
with open(os.path.join(training_args.output_dir, "all_results.json"), "w") as f:
f.write(json.dumps(eval_metrics))
diff --git a/examples/tensorflow/language-modeling-tpu/run_mlm.py b/examples/tensorflow/language-modeling-tpu/run_mlm.py
index 30923b982e1e..e9e9862a6da4 100644
--- a/examples/tensorflow/language-modeling-tpu/run_mlm.py
+++ b/examples/tensorflow/language-modeling-tpu/run_mlm.py
@@ -235,8 +235,10 @@ def main(args):
num_warmup_steps=total_train_steps // 20,
init_lr=args.learning_rate,
weight_decay_rate=args.weight_decay_rate,
- # TODO Add the other Adam parameters?
)
+
+ # Transformers models compute the right loss for their task by default when labels are passed, and will
+ # use this for training unless you specify your own loss function in compile().
model.compile(optimizer=optimizer, metrics=["accuracy"])
def decode_fn(example):
diff --git a/examples/tensorflow/language-modeling/run_clm.py b/examples/tensorflow/language-modeling/run_clm.py
index 645dae55be86..1614bbd4b124 100755
--- a/examples/tensorflow/language-modeling/run_clm.py
+++ b/examples/tensorflow/language-modeling/run_clm.py
@@ -30,6 +30,7 @@
import os
import random
import sys
+import warnings
from dataclasses import dataclass, field
from itertools import chain
from pathlib import Path
@@ -112,12 +113,28 @@ class ModelArguments:
default="main",
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
)
+ token: str = field(
+ default=None,
+ metadata={
+ "help": (
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
+ )
+ },
+ )
use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
+ trust_remote_code: bool = field(
default=False,
metadata={
"help": (
- "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
- "with private models)."
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
)
},
)
@@ -220,6 +237,12 @@ def main():
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_clm", model_args, data_args, framework="tensorflow")
@@ -287,7 +310,7 @@ def main():
data_args.dataset_name,
data_args.dataset_config_name,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
if "validation" not in raw_datasets.keys():
raw_datasets["validation"] = load_dataset(
@@ -295,14 +318,14 @@ def main():
data_args.dataset_config_name,
split=f"train[:{data_args.validation_split_percentage}%]",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
raw_datasets["train"] = load_dataset(
data_args.dataset_name,
data_args.dataset_config_name,
split=f"train[{data_args.validation_split_percentage}%:]",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
else:
data_files = {}
@@ -323,7 +346,7 @@ def main():
extension,
data_files=data_files,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
**dataset_args,
)
# If no validation data is there, validation_split_percentage will be used to divide the dataset.
@@ -333,7 +356,7 @@ def main():
data_files=data_files,
split=f"train[:{data_args.validation_split_percentage}%]",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
**dataset_args,
)
raw_datasets["train"] = load_dataset(
@@ -341,7 +364,7 @@ def main():
data_files=data_files,
split=f"train[{data_args.validation_split_percentage}%:]",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
**dataset_args,
)
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
@@ -353,17 +376,27 @@ def main():
# In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
# download model & vocab.
if model_args.config_name:
- config = AutoConfig.from_pretrained(model_args.config_name)
+ config = AutoConfig.from_pretrained(
+ model_args.config_name,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
+ )
elif model_args.model_name_or_path:
- config = AutoConfig.from_pretrained(model_args.model_name_or_path)
+ config = AutoConfig.from_pretrained(
+ model_args.model_name_or_path, token=model_args.token, trust_remote_code=model_args.trust_remote_code
+ )
else:
config = CONFIG_MAPPING[model_args.model_type]()
logger.warning("You are instantiating a new config instance from scratch.")
if model_args.tokenizer_name:
- tokenizer = AutoTokenizer.from_pretrained(model_args.tokenizer_name)
+ tokenizer = AutoTokenizer.from_pretrained(
+ model_args.tokenizer_name, token=model_args.token, trust_remote_code=model_args.trust_remote_code
+ )
elif model_args.model_name_or_path:
- tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path)
+ tokenizer = AutoTokenizer.from_pretrained(
+ model_args.model_name_or_path, token=model_args.token, trust_remote_code=model_args.trust_remote_code
+ )
else:
raise ValueError(
"You are instantiating a new tokenizer from scratch. This is not supported by this script."
@@ -466,12 +499,21 @@ def group_texts(examples):
with training_args.strategy.scope():
# region Prepare model
if checkpoint is not None:
- model = TFAutoModelForCausalLM.from_pretrained(checkpoint, config=config)
+ model = TFAutoModelForCausalLM.from_pretrained(
+ checkpoint, config=config, token=model_args.token, trust_remote_code=model_args.trust_remote_code
+ )
elif model_args.model_name_or_path:
- model = TFAutoModelForCausalLM.from_pretrained(model_args.model_name_or_path, config=config)
+ model = TFAutoModelForCausalLM.from_pretrained(
+ model_args.model_name_or_path,
+ config=config,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
+ )
else:
logger.info("Training new model from scratch")
- model = TFAutoModelForCausalLM.from_config(config)
+ model = TFAutoModelForCausalLM.from_config(
+ config, token=model_args.token, trust_remote_code=model_args.trust_remote_code
+ )
# We resize the embeddings only when necessary to avoid index errors. If you are creating a model from scratch
# on a small vocab and want a smaller embedding size, remove this test.
@@ -537,7 +579,8 @@ def group_texts(examples):
adam_global_clipnorm=training_args.max_grad_norm,
)
- # no user-specified loss = will use the model internal loss
+ # Transformers models compute the right loss for their task by default when labels are passed, and will
+ # use this for training unless you specify your own loss function in compile().
model.compile(optimizer=optimizer, jit_compile=training_args.xla)
# endregion
diff --git a/examples/tensorflow/language-modeling/run_mlm.py b/examples/tensorflow/language-modeling/run_mlm.py
index cff0f51df09e..671331745de7 100755
--- a/examples/tensorflow/language-modeling/run_mlm.py
+++ b/examples/tensorflow/language-modeling/run_mlm.py
@@ -28,6 +28,7 @@
import os
import random
import sys
+import warnings
from dataclasses import dataclass, field
from itertools import chain
from pathlib import Path
@@ -110,12 +111,28 @@ class ModelArguments:
default="main",
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
)
+ token: str = field(
+ default=None,
+ metadata={
+ "help": (
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
+ )
+ },
+ )
use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
+ trust_remote_code: bool = field(
default=False,
metadata={
"help": (
- "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
- "with private models)."
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
)
},
)
@@ -226,6 +243,12 @@ def main():
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_mlm", model_args, data_args, framework="tensorflow")
@@ -296,20 +319,20 @@ def main():
raw_datasets = load_dataset(
data_args.dataset_name,
data_args.dataset_config_name,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
if "validation" not in raw_datasets.keys():
raw_datasets["validation"] = load_dataset(
data_args.dataset_name,
data_args.dataset_config_name,
split=f"train[:{data_args.validation_split_percentage}%]",
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
raw_datasets["train"] = load_dataset(
data_args.dataset_name,
data_args.dataset_config_name,
split=f"train[{data_args.validation_split_percentage}%:]",
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
else:
data_files = {}
@@ -323,7 +346,7 @@ def main():
raw_datasets = load_dataset(
extension,
data_files=data_files,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
@@ -335,19 +358,29 @@ def main():
# In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
# download model & vocab.
if checkpoint is not None:
- config = AutoConfig.from_pretrained(checkpoint)
+ config = AutoConfig.from_pretrained(
+ checkpoint, token=model_args.token, trust_remote_code=model_args.trust_remote_code
+ )
elif model_args.config_name:
- config = AutoConfig.from_pretrained(model_args.config_name)
+ config = AutoConfig.from_pretrained(
+ model_args.config_name, token=model_args.token, trust_remote_code=model_args.trust_remote_code
+ )
elif model_args.model_name_or_path:
- config = AutoConfig.from_pretrained(model_args.model_name_or_path)
+ config = AutoConfig.from_pretrained(
+ model_args.model_name_or_path, token=model_args.token, trust_remote_code=model_args.trust_remote_code
+ )
else:
config = CONFIG_MAPPING[model_args.model_type]()
logger.warning("You are instantiating a new config instance from scratch.")
if model_args.tokenizer_name:
- tokenizer = AutoTokenizer.from_pretrained(model_args.tokenizer_name)
+ tokenizer = AutoTokenizer.from_pretrained(
+ model_args.tokenizer_name, token=model_args.token, trust_remote_code=model_args.trust_remote_code
+ )
elif model_args.model_name_or_path:
- tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path)
+ tokenizer = AutoTokenizer.from_pretrained(
+ model_args.model_name_or_path, token=model_args.token, trust_remote_code=model_args.trust_remote_code
+ )
else:
raise ValueError(
"You are instantiating a new tokenizer from scratch. This is not supported by this script."
@@ -482,12 +515,21 @@ def group_texts(examples):
with training_args.strategy.scope():
# region Prepare model
if checkpoint is not None:
- model = TFAutoModelForMaskedLM.from_pretrained(checkpoint, config=config)
+ model = TFAutoModelForMaskedLM.from_pretrained(
+ checkpoint, config=config, token=model_args.token, trust_remote_code=model_args.trust_remote_code
+ )
elif model_args.model_name_or_path:
- model = TFAutoModelForMaskedLM.from_pretrained(model_args.model_name_or_path, config=config)
+ model = TFAutoModelForMaskedLM.from_pretrained(
+ model_args.model_name_or_path,
+ config=config,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
+ )
else:
logger.info("Training new model from scratch")
- model = TFAutoModelForMaskedLM.from_config(config)
+ model = TFAutoModelForMaskedLM.from_config(
+ config, token=model_args.token, trust_remote_code=model_args.trust_remote_code
+ )
# We resize the embeddings only when necessary to avoid index errors. If you are creating a model from scratch
# on a small vocab and want a smaller embedding size, remove this test.
@@ -559,8 +601,9 @@ def group_texts(examples):
adam_global_clipnorm=training_args.max_grad_norm,
)
- # no user-specified loss = will use the model internal loss
- model.compile(optimizer=optimizer, jit_compile=training_args.xla, run_eagerly=True)
+ # Transformers models compute the right loss for their task by default when labels are passed, and will
+ # use this for training unless you specify your own loss function in compile().
+ model.compile(optimizer=optimizer, jit_compile=training_args.xla)
# endregion
# region Preparing push_to_hub and model card
diff --git a/examples/tensorflow/multiple-choice/run_swag.py b/examples/tensorflow/multiple-choice/run_swag.py
index 9c6a90f1dc1b..d78060dfa4dc 100644
--- a/examples/tensorflow/multiple-choice/run_swag.py
+++ b/examples/tensorflow/multiple-choice/run_swag.py
@@ -22,6 +22,7 @@
import logging
import os
import sys
+import warnings
from dataclasses import dataclass, field
from itertools import chain
from pathlib import Path
@@ -50,7 +51,7 @@
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
-check_min_version("4.29.0.dev0")
+check_min_version("4.32.0.dev0")
logger = logging.getLogger(__name__)
@@ -146,12 +147,28 @@ class ModelArguments:
default="main",
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
)
+ token: str = field(
+ default=None,
+ metadata={
+ "help": (
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
+ )
+ },
+ )
use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
+ trust_remote_code: bool = field(
default=False,
metadata={
"help": (
- "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
- "with private models)."
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
)
},
)
@@ -239,6 +256,12 @@ def main():
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_swag", model_args, data_args, framework="tensorflow")
@@ -301,7 +324,7 @@ def main():
extension,
data_files=data_files,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
else:
# Downloading and loading the swag dataset from the hub.
@@ -309,7 +332,7 @@ def main():
"swag",
"regular",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
# https://huggingface.co/docs/datasets/loading_datasets.html.
@@ -335,14 +358,16 @@ def main():
config_path,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
tokenizer = AutoTokenizer.from_pretrained(
model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
use_fast=model_args.use_fast_tokenizer,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
# endregion
@@ -428,7 +453,8 @@ def preprocess_function(examples):
config=config,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
num_replicas = training_args.strategy.num_replicas_in_sync
@@ -455,6 +481,8 @@ def preprocess_function(examples):
)
else:
optimizer = None
+ # Transformers models compute the right loss for their task by default when labels are passed, and will
+ # use this for training unless you specify your own loss function in compile().
model.compile(optimizer=optimizer, metrics=["accuracy"], jit_compile=training_args.xla)
# endregion
diff --git a/examples/tensorflow/question-answering/run_qa.py b/examples/tensorflow/question-answering/run_qa.py
index 7059a9a03212..6152263d6b24 100755
--- a/examples/tensorflow/question-answering/run_qa.py
+++ b/examples/tensorflow/question-answering/run_qa.py
@@ -22,6 +22,7 @@
import logging
import os
import sys
+import warnings
from dataclasses import dataclass, field
from pathlib import Path
from typing import Optional
@@ -48,7 +49,7 @@
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
-check_min_version("4.29.0.dev0")
+check_min_version("4.32.0.dev0")
logger = logging.getLogger(__name__)
@@ -77,12 +78,28 @@ class ModelArguments:
default="main",
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
)
+ token: str = field(
+ default=None,
+ metadata={
+ "help": (
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
+ )
+ },
+ )
use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
+ trust_remote_code: bool = field(
default=False,
metadata={
"help": (
- "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
- "with private models)."
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
)
},
)
@@ -245,6 +262,12 @@ def main():
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_qa", model_args, data_args, framework="tensorflow")
@@ -304,7 +327,7 @@ def main():
data_args.dataset_name,
data_args.dataset_config_name,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
else:
data_files = {}
@@ -323,7 +346,7 @@ def main():
data_files=data_files,
field="data",
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
# https://huggingface.co/docs/datasets/loading_datasets.html.
@@ -338,14 +361,16 @@ def main():
model_args.config_name if model_args.config_name else model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
tokenizer = AutoTokenizer.from_pretrained(
model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
use_fast=True,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
# endregion
@@ -625,7 +650,8 @@ def compute_metrics(p: EvalPrediction):
config=config,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
if training_args.do_train:
training_dataset = model.prepare_tf_dataset(
@@ -656,7 +682,8 @@ def compute_metrics(p: EvalPrediction):
adam_global_clipnorm=training_args.max_grad_norm,
)
- # no user-specified loss = will use the model internal loss
+ # Transformers models compute the right loss for their task by default when labels are passed, and will
+ # use this for training unless you specify your own loss function in compile().
model.compile(optimizer=optimizer, jit_compile=training_args.xla, metrics=["accuracy"])
else:
diff --git a/examples/tensorflow/summarization/run_summarization.py b/examples/tensorflow/summarization/run_summarization.py
index b60a2129166d..03c434330b85 100644
--- a/examples/tensorflow/summarization/run_summarization.py
+++ b/examples/tensorflow/summarization/run_summarization.py
@@ -22,6 +22,7 @@
import logging
import os
import sys
+import warnings
from dataclasses import dataclass, field
from typing import Optional
@@ -53,7 +54,7 @@
# region Checking dependencies
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
-check_min_version("4.29.0.dev0")
+check_min_version("4.32.0.dev0")
require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/summarization/requirements.txt")
@@ -99,12 +100,28 @@ class ModelArguments:
default="main",
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
)
+ token: str = field(
+ default=None,
+ metadata={
+ "help": (
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
+ )
+ },
+ )
use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
+ trust_remote_code: bool = field(
default=False,
metadata={
"help": (
- "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
- "with private models)."
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
)
},
)
@@ -287,6 +304,12 @@ def main():
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_summarization", model_args, data_args, framework="tensorflow")
@@ -355,7 +378,7 @@ def main():
data_args.dataset_name,
data_args.dataset_config_name,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
else:
data_files = {}
@@ -372,7 +395,7 @@ def main():
extension,
data_files=data_files,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
# https://huggingface.co/docs/datasets/loading_datasets.html.
@@ -388,14 +411,16 @@ def main():
model_args.config_name if model_args.config_name else model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
tokenizer = AutoTokenizer.from_pretrained(
model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
use_fast=model_args.use_fast_tokenizer,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
prefix = data_args.source_prefix if data_args.source_prefix is not None else ""
@@ -513,7 +538,8 @@ def postprocess_text(preds, labels):
config=config,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
# We resize the embeddings only when necessary to avoid index errors. If you are creating a model from scratch
@@ -674,6 +700,8 @@ def compute_metrics(preds):
# endregion
# region Training
+ # Transformers models compute the right loss for their task by default when labels are passed, and will
+ # use this for training unless you specify your own loss function in compile().
model.compile(optimizer=optimizer, jit_compile=training_args.xla)
eval_metrics = None
if training_args.do_train:
diff --git a/examples/tensorflow/text-classification/run_glue.py b/examples/tensorflow/text-classification/run_glue.py
index 8aa3d4c7fe80..785e88a71d6b 100644
--- a/examples/tensorflow/text-classification/run_glue.py
+++ b/examples/tensorflow/text-classification/run_glue.py
@@ -20,6 +20,7 @@
import logging
import os
import sys
+import warnings
from dataclasses import dataclass, field
from typing import Optional
@@ -47,7 +48,7 @@
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
-check_min_version("4.29.0.dev0")
+check_min_version("4.32.0.dev0")
task_to_keys = {
"cola": ("sentence", None),
@@ -164,12 +165,28 @@ class ModelArguments:
default="main",
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
)
+ token: str = field(
+ default=None,
+ metadata={
+ "help": (
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
+ )
+ },
+ )
use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
+ trust_remote_code: bool = field(
default=False,
metadata={
"help": (
- "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
- "with private models)."
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
)
},
)
@@ -192,6 +209,12 @@ def main():
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_glue", model_args, data_args, framework="tensorflow")
@@ -242,7 +265,7 @@ def main():
"glue",
data_args.task_name,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
# See more about loading any type of standard or custom dataset at
# https://huggingface.co/docs/datasets/loading_datasets.html.
@@ -284,14 +307,16 @@ def main():
finetuning_task=data_args.task_name,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
tokenizer = AutoTokenizer.from_pretrained(
model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
use_fast=model_args.use_fast_tokenizer,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
# endregion
@@ -374,7 +399,8 @@ def compute_metrics(preds, label_ids):
config=config,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
# endregion
@@ -453,6 +479,8 @@ def compute_metrics(preds, label_ids):
metrics = []
else:
metrics = ["accuracy"]
+ # Transformers models compute the right loss for their task by default when labels are passed, and will
+ # use this for training unless you specify your own loss function in compile().
model.compile(optimizer=optimizer, metrics=metrics, jit_compile=training_args.xla)
# endregion
diff --git a/examples/tensorflow/text-classification/run_text_classification.py b/examples/tensorflow/text-classification/run_text_classification.py
index 64799eda3c02..0d2ea87b96cb 100644
--- a/examples/tensorflow/text-classification/run_text_classification.py
+++ b/examples/tensorflow/text-classification/run_text_classification.py
@@ -20,6 +20,7 @@
import logging
import os
import sys
+import warnings
from dataclasses import dataclass, field
from pathlib import Path
from typing import Optional
@@ -170,12 +171,28 @@ class ModelArguments:
default="main",
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
)
+ token: str = field(
+ default=None,
+ metadata={
+ "help": (
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
+ )
+ },
+ )
use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
+ trust_remote_code: bool = field(
default=False,
metadata={
"help": (
- "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
- "with private models)."
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
)
},
)
@@ -198,6 +215,12 @@ def main():
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_text_classification", model_args, data_args, framework="tensorflow")
@@ -258,7 +281,7 @@ def main():
"csv",
data_files=data_files,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
else:
# Loading a dataset from local json files
@@ -301,20 +324,23 @@ def main():
num_labels=num_labels,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
else:
config = AutoConfig.from_pretrained(
config_path,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
tokenizer = AutoTokenizer.from_pretrained(
model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
# endregion
@@ -402,7 +428,8 @@ def preprocess_function(examples):
config=config,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
# endregion
@@ -487,6 +514,8 @@ def preprocess_function(examples):
metrics = []
else:
metrics = ["accuracy"]
+ # Transformers models compute the right loss for their task by default when labels are passed, and will
+ # use this for training unless you specify your own loss function in compile().
model.compile(optimizer=optimizer, metrics=metrics)
# endregion
diff --git a/examples/tensorflow/token-classification/run_ner.py b/examples/tensorflow/token-classification/run_ner.py
index a358cd12dd63..f04dae721825 100644
--- a/examples/tensorflow/token-classification/run_ner.py
+++ b/examples/tensorflow/token-classification/run_ner.py
@@ -21,6 +21,7 @@
import logging
import os
import random
+import warnings
from dataclasses import dataclass, field
from typing import Optional
@@ -75,12 +76,28 @@ class ModelArguments:
default="main",
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
)
+ token: str = field(
+ default=None,
+ metadata={
+ "help": (
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
+ )
+ },
+ )
use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
+ trust_remote_code: bool = field(
default=False,
metadata={
"help": (
- "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
- "with private models)."
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
)
},
)
@@ -196,6 +213,12 @@ def main():
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments))
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_ner", model_args, data_args, framework="tensorflow")
@@ -228,7 +251,7 @@ def main():
raw_datasets = load_dataset(
data_args.dataset_name,
data_args.dataset_config_name,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
else:
data_files = {}
@@ -240,7 +263,7 @@ def main():
raw_datasets = load_dataset(
extension,
data_files=data_files,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
# https://huggingface.co/docs/datasets/loading_datasets.html.
@@ -291,9 +314,19 @@ def get_label_list(labels):
# In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
# download model & vocab.
if model_args.config_name:
- config = AutoConfig.from_pretrained(model_args.config_name, num_labels=num_labels)
+ config = AutoConfig.from_pretrained(
+ model_args.config_name,
+ num_labels=num_labels,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
+ )
elif model_args.model_name_or_path:
- config = AutoConfig.from_pretrained(model_args.model_name_or_path, num_labels=num_labels)
+ config = AutoConfig.from_pretrained(
+ model_args.model_name_or_path,
+ num_labels=num_labels,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
+ )
else:
config = CONFIG_MAPPING[model_args.model_type]()
logger.warning("You are instantiating a new config instance from scratch.")
@@ -306,9 +339,20 @@ def get_label_list(labels):
)
if config.model_type in {"gpt2", "roberta"}:
- tokenizer = AutoTokenizer.from_pretrained(tokenizer_name_or_path, use_fast=True, add_prefix_space=True)
+ tokenizer = AutoTokenizer.from_pretrained(
+ tokenizer_name_or_path,
+ use_fast=True,
+ add_prefix_space=True,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
+ )
else:
- tokenizer = AutoTokenizer.from_pretrained(tokenizer_name_or_path, use_fast=True)
+ tokenizer = AutoTokenizer.from_pretrained(
+ tokenizer_name_or_path,
+ use_fast=True,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
+ )
# endregion
# region Preprocessing the raw datasets
@@ -379,10 +423,14 @@ def tokenize_and_align_labels(examples):
model = TFAutoModelForTokenClassification.from_pretrained(
model_args.model_name_or_path,
config=config,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
else:
logger.info("Training new model from scratch")
- model = TFAutoModelForTokenClassification.from_config(config)
+ model = TFAutoModelForTokenClassification.from_config(
+ config, token=model_args.token, trust_remote_code=model_args.trust_remote_code
+ )
# We resize the embeddings only when necessary to avoid index errors. If you are creating a model from scratch
# on a small vocab and want a smaller embedding size, remove this test.
@@ -454,7 +502,8 @@ def tokenize_and_align_labels(examples):
weight_decay_rate=training_args.weight_decay,
adam_global_clipnorm=training_args.max_grad_norm,
)
-
+ # Transformers models compute the right loss for their task by default when labels are passed, and will
+ # use this for training unless you specify your own loss function in compile().
model.compile(optimizer=optimizer, jit_compile=training_args.xla)
# endregion
diff --git a/examples/tensorflow/translation/run_translation.py b/examples/tensorflow/translation/run_translation.py
index 5f45f752c503..2673983ec9fa 100644
--- a/examples/tensorflow/translation/run_translation.py
+++ b/examples/tensorflow/translation/run_translation.py
@@ -22,6 +22,7 @@
import logging
import os
import sys
+import warnings
from dataclasses import dataclass, field
from typing import Optional
@@ -56,7 +57,7 @@
# region Dependencies and constants
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
-check_min_version("4.29.0.dev0")
+check_min_version("4.32.0.dev0")
require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/summarization/requirements.txt")
@@ -93,12 +94,28 @@ class ModelArguments:
default="main",
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
)
+ token: str = field(
+ default=None,
+ metadata={
+ "help": (
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
+ )
+ },
+ )
use_auth_token: bool = field(
+ default=None,
+ metadata={
+ "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token`."
+ },
+ )
+ trust_remote_code: bool = field(
default=False,
metadata={
"help": (
- "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
- "with private models)."
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
+ "execute code present on the Hub on your local machine."
)
},
)
@@ -268,6 +285,12 @@ def main():
else:
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+ if model_args.use_auth_token is not None:
+ warnings.warn("The `use_auth_token` argument is deprecated and will be removed in v4.34.", FutureWarning)
+ if model_args.token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ model_args.token = model_args.use_auth_token
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry("run_translation", model_args, data_args, framework="tensorflow")
@@ -322,7 +345,7 @@ def main():
data_args.dataset_name,
data_args.dataset_config_name,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
else:
data_files = {}
@@ -336,10 +359,10 @@ def main():
extension,
data_files=data_files,
cache_dir=model_args.cache_dir,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
)
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
- # https://huggingface.co/docs/datasets/loading_datasets.html.
+ # https://huggingface.co/docs/datasets/loading
# endregion
# region Load model config and tokenizer
@@ -352,14 +375,16 @@ def main():
model_args.config_name if model_args.config_name else model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
tokenizer = AutoTokenizer.from_pretrained(
model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
use_fast=model_args.use_fast_tokenizer,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
prefix = data_args.source_prefix if data_args.source_prefix is not None else ""
@@ -466,7 +491,8 @@ def preprocess_function(examples):
config=config,
cache_dir=model_args.cache_dir,
revision=model_args.model_revision,
- use_auth_token=True if model_args.use_auth_token else None,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
)
# We resize the embeddings only when necessary to avoid index errors. If you are creating a model from scratch
@@ -643,6 +669,8 @@ def compute_metrics(preds):
# region Training
eval_metrics = None
+ # Transformers models compute the right loss for their task by default when labels are passed, and will
+ # use this for training unless you specify your own loss function in compile().
model.compile(optimizer=optimizer, jit_compile=training_args.xla)
if training_args.do_train:
diff --git a/notebooks/README.md b/notebooks/README.md
index 97f804eb6d93..18ffc682b51c 100644
--- a/notebooks/README.md
+++ b/notebooks/README.md
@@ -80,12 +80,20 @@ You can open any page of the documentation as a notebook in Colab (there is a bu
| [How to fine-tune a speech recognition model in any language](https://github.com/huggingface/notebooks/blob/main/examples/multi_lingual_speech_recognition.ipynb)| Show how to preprocess the data and fine-tune a multi-lingually pretrained speech model on Common Voice | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/multi_lingual_speech_recognition.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/multi_lingual_speech_recognition.ipynb)|
| [How to fine-tune a model on audio classification](https://github.com/huggingface/notebooks/blob/main/examples/audio_classification.ipynb)| Show how to preprocess the data and fine-tune a pretrained Speech model on Keyword Spotting | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/audio_classification.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/audio_classification.ipynb)|
-#### Other modalities[[pytorch-other]]
+#### Biological Sequences[[pytorch-bio]]
| Notebook | Description | | |
|:----------|:----------------------------------------------------------------------------------------|:-------------|------:|
| [How to fine-tune a pre-trained protein model](https://github.com/huggingface/notebooks/blob/main/examples/protein_language_modeling.ipynb) | See how to tokenize proteins and fine-tune a large pre-trained protein "language" model | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/protein_language_modeling.ipynb) | [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/protein_language_modeling.ipynb) |
| [How to generate protein folds](https://github.com/huggingface/notebooks/blob/main/examples/protein_folding.ipynb) | See how to go from protein sequence to a full protein model and PDB file | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/protein_folding.ipynb) | [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/protein_folding.ipynb) |
+| [How to fine-tune a Nucleotide Transformer model](https://github.com/huggingface/notebooks/blob/main/examples/nucleotide_transformer_dna_sequence_modelling.ipynb) | See how to tokenize DNA and fine-tune a large pre-trained DNA "language" model | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/nucleotide_transformer_dna_sequence_modelling.ipynb) | [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/nucleotide_transformer_dna_sequence_modelling.ipynb) |
+| [Fine-tune a Nucleotide Transformer model with LoRA](https://github.com/huggingface/notebooks/blob/main/examples/nucleotide_transformer_dna_sequence_modelling_with_peft.ipynb) | Train even larger DNA models in a memory-efficient way | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/nucleotide_transformer_dna_sequence_modelling_with_peft.ipynb) | [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/nucleotide_transformer_dna_sequence_modelling_with_peft.ipynb) |
+
+
+#### Other modalities[[pytorch-other]]
+
+| Notebook | Description | | |
+|:----------|:----------------------------------------------------------------------------------------|:-------------|------:|
| [Probabilistic Time Series Forecasting](https://github.com/huggingface/notebooks/blob/main/examples/time-series-transformers.ipynb) | See how to train Time Series Transformer on a custom dataset | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/time-series-transformers.ipynb) | [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/time-series-transformers.ipynb) |
#### Utility notebooks[[pytorch-utility]]
@@ -118,7 +126,7 @@ You can open any page of the documentation as a notebook in Colab (there is a bu
| [How to fine-tune a model on image classification](https://github.com/huggingface/notebooks/blob/main/examples/image_classification-tf.ipynb) | Show how to preprocess the data and fine-tune any pretrained Vision model on Image Classification | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification-tf.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/image_classification-tf.ipynb)|
| [How to fine-tune a SegFormer model on semantic segmentation](https://github.com/huggingface/notebooks/blob/main/examples/semantic_segmentation-tf.ipynb) | Show how to preprocess the data and fine-tune a pretrained SegFormer model on Semantic Segmentation | [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/semantic_segmentation-tf.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/semantic_segmentation-tf.ipynb)|
-#### Other modalities[[tensorflow-other]]
+#### Biological Sequences[[tensorflow-bio]]
| Notebook | Description | | |
|:----------|:-------------|:-------------|------:|
diff --git a/scripts/tatoeba/README.md b/scripts/tatoeba/README.md
index 7c492ec4f46e..94bb167d51bb 100644
--- a/scripts/tatoeba/README.md
+++ b/scripts/tatoeba/README.md
@@ -54,7 +54,7 @@ To upload all converted models,
1. Install [git-lfs](https://git-lfs.github.com/).
-2. Login to `transformers-cli`
+2. Login to `huggingface-cli`
```bash
huggingface-cli login
diff --git a/setup.cfg b/setup.cfg
index 5f47c5c6be69..ffe8973dd21c 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -1,2 +1,3 @@
[tool:pytest]
doctest_optionflags=NUMBER NORMALIZE_WHITESPACE ELLIPSIS
+doctest_glob=**/*.md
\ No newline at end of file
diff --git a/setup.py b/setup.py
index 1eaee04a67b9..5047727141e5 100644
--- a/setup.py
+++ b/setup.py
@@ -38,14 +38,9 @@
7. Build both the sources and the wheel. Do not change anything in setup.py between
creating the wheel and the source distribution (obviously).
- Clean up your build and dist folders (to avoid re-uploading oldies):
- rm -rf dist
- rm -rf build
+ Run `make build-release`. This will build the release and do some sanity checks for you. If this ends with an error
+ message, you need to fix things before going further.
- For the wheel, run: "python setup.py bdist_wheel" in the top level directory.
- (this will build a wheel for the python version you use to build it).
-
- For the sources, run: "python setup.py sdist"
You should now have a /dist directory with both .whl and .tar.gz source versions.
8. Check that everything looks correct by uploading the package to the pypi test server:
@@ -61,6 +56,7 @@
Check you can run the following commands:
python -c "from transformers import pipeline; classifier = pipeline('text-classification'); print(classifier('What a nice release'))"
python -c "from transformers import *"
+ python utils/check_build.py --check_lib
If making a patch release, double check the bug you are patching is indeed resolved.
@@ -101,8 +97,8 @@
# 1. all dependencies should be listed here with their version requirements if any
# 2. once modified, run: `make deps_table_update` to update src/transformers/dependency_versions_table.py
_deps = [
- "Pillow",
- "accelerate>=0.17.0",
+ "Pillow<10.0.0",
+ "accelerate>=0.20.3",
"av==9.2.0", # Latest version of PyAV (10.0.0) has issues with audio stream.
"beautifulsoup4",
"black~=23.1",
@@ -111,24 +107,25 @@
"dataclasses",
"datasets!=2.5.0",
"decord==0.6.0",
- "deepspeed>=0.8.3",
+ "deepspeed>=0.9.3",
+ "diffusers",
"dill<0.3.5",
"evaluate>=0.2.0",
"fairscale>0.3",
"faiss-cpu",
"fastapi",
"filelock",
- "flax>=0.4.1,<=0.6.9",
+ "flax>=0.4.1,<=0.7.0",
"ftfy",
"fugashi>=1.0",
"GitPython<3.1.19",
"hf-doc-builder>=0.3.0",
- "huggingface-hub>=0.11.0,<1.0",
+ "huggingface-hub>=0.15.1,<1.0",
"importlib_metadata",
"ipadic>=1.0.0,<2.0",
"isort>=5.5.4",
- "jax>=0.2.8,!=0.3.2,<=0.3.6",
- "jaxlib>=0.1.65,<=0.3.6",
+ "jax>=0.4.1,<=0.4.13",
+ "jaxlib>=0.4.1,<=0.4.13",
"jieba",
"kenlm",
"keras-nlp>=0.3.1",
@@ -139,29 +136,30 @@
"onnxconverter-common",
"onnxruntime-tools>=1.4.2",
"onnxruntime>=1.4.0",
+ "opencv-python",
"optuna",
"optax>=0.0.8,<=0.1.4",
"packaging>=20.0",
"parameterized",
"phonemizer",
- "protobuf<=3.20.2",
+ "protobuf",
"psutil",
"pyyaml>=5.1",
- "pydantic",
- "pytest",
+ "pydantic<2",
+ "pytest>=7.2.0",
"pytest-timeout",
"pytest-xdist",
- "python>=3.7.0",
+ "python>=3.8.0",
"ray[tune]",
"regex!=2019.12.17",
"requests",
- "rhoknp>=1.1.0",
+ "rhoknp>=1.1.0,<1.3.1",
"rjieba",
"rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1",
"ruff>=0.0.241,<=0.0.259",
"sacrebleu>=1.4.12,<2.0.0",
"sacremoses",
- "safetensors>=0.2.1",
+ "safetensors>=0.3.1",
"sagemaker>=2.31.0",
"scikit-learn",
"sentencepiece>=0.1.91,!=0.1.92",
@@ -170,9 +168,9 @@
"sudachipy>=0.6.6",
"sudachidict_core>=20220729",
# TensorFlow pin. When changing this value, update examples/tensorflow/_tests_requirements.txt accordingly
- "tensorflow-cpu>=2.4,<2.13",
- "tensorflow>=2.4,<2.13",
- "tensorflow-text<2.13",
+ "tensorflow-cpu>=2.6,<2.14",
+ "tensorflow>=2.6,<2.14",
+ "tensorflow-text<2.14",
"tf2onnx",
"timeout-decorator",
"timm",
@@ -184,6 +182,7 @@
"tqdm>=4.27",
"unidic>=1.0.2",
"unidic_lite>=1.0.7",
+ "urllib3<2.0.0",
"uvicorn",
]
@@ -320,7 +319,6 @@ def run(self):
"protobuf", # Can be removed once we can unpin protobuf
"sacremoses",
"rjieba",
- "safetensors",
"beautifulsoup4",
)
+ extras["retrieval"]
@@ -329,7 +327,7 @@ def run(self):
extras["deepspeed-testing"] = extras["deepspeed"] + extras["testing"] + extras["optuna"] + extras["sentencepiece"]
-extras["quality"] = deps_list("black", "datasets", "isort", "ruff", "GitPython", "hf-doc-builder")
+extras["quality"] = deps_list("black", "datasets", "isort", "ruff", "GitPython", "hf-doc-builder", "urllib3")
extras["all"] = (
extras["tf"]
@@ -409,9 +407,12 @@ def run(self):
"tqdm",
)
+extras["agents"] = deps_list(
+ "diffusers", "accelerate", "datasets", "torch", "sentencepiece", "opencv-python", "Pillow"
+)
+
# when modifying the following list, make sure to update src/transformers/dependency_versions_check.py
install_requires = [
- deps["importlib_metadata"] + ";python_version<'3.8'", # importlib_metadata for Python versions that don't have it
deps["filelock"], # filesystem locks, e.g., to prevent parallel downloads
deps["huggingface-hub"],
deps["numpy"],
@@ -420,12 +421,13 @@ def run(self):
deps["regex"], # for OpenAI GPT
deps["requests"], # for downloading models over HTTPS
deps["tokenizers"],
+ deps["safetensors"],
deps["tqdm"], # progress bars in model download and training scripts
]
setup(
name="transformers",
- version="4.29.0.dev0", # expected format is one of x.y.z.dev0, or x.y.z.rc1 or x.y.z (no to dashes, yes to dots)
+ version="4.32.0.dev0", # expected format is one of x.y.z.dev0, or x.y.z.rc1 or x.y.z (no to dashes, yes to dots)
author="The Hugging Face team (past and future) with the help of all our contributors (https://github.com/huggingface/transformers/graphs/contributors)",
author_email="transformers@huggingface.co",
description="State-of-the-art Machine Learning for JAX, PyTorch and TensorFlow",
@@ -437,12 +439,12 @@ def run(self):
package_dir={"": "src"},
packages=find_packages("src"),
include_package_data=True,
- package_data={"transformers": ["*.cu", "*.cpp", "*.cuh", "*.h", "*.pyx"]},
+ package_data={"": ["**/*.cu", "**/*.cpp", "**/*.cuh", "**/*.h", "**/*.pyx"]},
zip_safe=False,
extras_require=extras,
entry_points={"console_scripts": ["transformers-cli=transformers.commands.transformers_cli:main"]},
- python_requires=">=3.7.0",
- install_requires=install_requires,
+ python_requires=">=3.8.0",
+ install_requires=list(install_requires),
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
@@ -451,7 +453,6 @@ def run(self):
"License :: OSI Approved :: Apache Software License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
- "Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
diff --git a/src/transformers/__init__.py b/src/transformers/__init__.py
index 445fbb53e269..695e51fbe293 100644
--- a/src/transformers/__init__.py
+++ b/src/transformers/__init__.py
@@ -18,7 +18,7 @@
# to defer the actual importing for when the objects are requested. This way `import transformers` provides the names
# in the namespace without actually importing anything (and especially none of the backends).
-__version__ = "4.29.0.dev0"
+__version__ = "4.32.0.dev0"
from typing import TYPE_CHECKING
@@ -98,6 +98,7 @@
"file_utils": [],
"generation": ["GenerationConfig", "TextIteratorStreamer", "TextStreamer"],
"hf_argparser": ["HfArgumentParser"],
+ "hyperparameter_search": [],
"image_transforms": [],
"integrations": [
"is_clearml_available",
@@ -155,6 +156,17 @@
"AutoProcessor",
"AutoTokenizer",
],
+ "models.autoformer": [
+ "AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP",
+ "AutoformerConfig",
+ ],
+ "models.bark": [
+ "BarkCoarseConfig",
+ "BarkConfig",
+ "BarkFineConfig",
+ "BarkProcessor",
+ "BarkSemanticConfig",
+ ],
"models.bart": ["BartConfig", "BartTokenizer"],
"models.barthez": [],
"models.bartpho": [],
@@ -197,7 +209,6 @@
"Blip2VisionConfig",
],
"models.bloom": ["BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP", "BloomConfig"],
- "models.bort": [],
"models.bridgetower": [
"BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP",
"BridgeTowerConfig",
@@ -258,10 +269,32 @@
"models.decision_transformer": ["DECISION_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "DecisionTransformerConfig"],
"models.deformable_detr": ["DEFORMABLE_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP", "DeformableDetrConfig"],
"models.deit": ["DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "DeiTConfig"],
+ "models.deprecated": [],
+ "models.deprecated.bort": [],
+ "models.deprecated.mctct": [
+ "MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP",
+ "MCTCTConfig",
+ "MCTCTFeatureExtractor",
+ "MCTCTProcessor",
+ ],
+ "models.deprecated.mmbt": ["MMBTConfig"],
+ "models.deprecated.open_llama": ["OPEN_LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP", "OpenLlamaConfig"],
+ "models.deprecated.retribert": [
+ "RETRIBERT_PRETRAINED_CONFIG_ARCHIVE_MAP",
+ "RetriBertConfig",
+ "RetriBertTokenizer",
+ ],
+ "models.deprecated.tapex": ["TapexTokenizer"],
+ "models.deprecated.trajectory_transformer": [
+ "TRAJECTORY_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP",
+ "TrajectoryTransformerConfig",
+ ],
+ "models.deprecated.van": ["VAN_PRETRAINED_CONFIG_ARCHIVE_MAP", "VanConfig"],
"models.deta": ["DETA_PRETRAINED_CONFIG_ARCHIVE_MAP", "DetaConfig"],
"models.detr": ["DETR_PRETRAINED_CONFIG_ARCHIVE_MAP", "DetrConfig"],
"models.dialogpt": [],
"models.dinat": ["DINAT_PRETRAINED_CONFIG_ARCHIVE_MAP", "DinatConfig"],
+ "models.dinov2": ["DINOV2_PRETRAINED_CONFIG_ARCHIVE_MAP", "Dinov2Config"],
"models.distilbert": ["DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "DistilBertConfig", "DistilBertTokenizer"],
"models.dit": [],
"models.donut": ["DONUT_SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP", "DonutProcessor", "DonutSwinConfig"],
@@ -277,6 +310,11 @@
"models.efficientformer": ["EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "EfficientFormerConfig"],
"models.efficientnet": ["EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "EfficientNetConfig"],
"models.electra": ["ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP", "ElectraConfig", "ElectraTokenizer"],
+ "models.encodec": [
+ "ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP",
+ "EncodecConfig",
+ "EncodecFeatureExtractor",
+ ],
"models.encoder_decoder": ["EncoderDecoderConfig"],
"models.ernie": [
"ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP",
@@ -284,6 +322,7 @@
],
"models.ernie_m": ["ERNIE_M_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieMConfig"],
"models.esm": ["ESM_PRETRAINED_CONFIG_ARCHIVE_MAP", "EsmConfig", "EsmTokenizer"],
+ "models.falcon": ["FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP", "FalconConfig"],
"models.flaubert": ["FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "FlaubertConfig", "FlaubertTokenizer"],
"models.flava": [
"FLAVA_PRETRAINED_CONFIG_ARCHIVE_MAP",
@@ -323,6 +362,13 @@
"models.ibert": ["IBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "IBertConfig"],
"models.imagegpt": ["IMAGEGPT_PRETRAINED_CONFIG_ARCHIVE_MAP", "ImageGPTConfig"],
"models.informer": ["INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "InformerConfig"],
+ "models.instructblip": [
+ "INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP",
+ "InstructBlipConfig",
+ "InstructBlipProcessor",
+ "InstructBlipQFormerConfig",
+ "InstructBlipVisionConfig",
+ ],
"models.jukebox": [
"JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP",
"JukeboxConfig",
@@ -372,19 +418,25 @@
"models.maskformer": ["MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "MaskFormerConfig", "MaskFormerSwinConfig"],
"models.mbart": ["MBartConfig"],
"models.mbart50": [],
- "models.mctct": ["MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP", "MCTCTConfig", "MCTCTProcessor"],
"models.mega": ["MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP", "MegaConfig"],
"models.megatron_bert": ["MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "MegatronBertConfig"],
"models.megatron_gpt2": [],
"models.mgp_str": ["MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP", "MgpstrConfig", "MgpstrProcessor", "MgpstrTokenizer"],
"models.mluke": [],
- "models.mmbt": ["MMBTConfig"],
"models.mobilebert": ["MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "MobileBertConfig", "MobileBertTokenizer"],
"models.mobilenet_v1": ["MOBILENET_V1_PRETRAINED_CONFIG_ARCHIVE_MAP", "MobileNetV1Config"],
"models.mobilenet_v2": ["MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP", "MobileNetV2Config"],
"models.mobilevit": ["MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "MobileViTConfig"],
+ "models.mobilevitv2": ["MOBILEVITV2_PRETRAINED_CONFIG_ARCHIVE_MAP", "MobileViTV2Config"],
"models.mpnet": ["MPNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "MPNetConfig", "MPNetTokenizer"],
+ "models.mpt": ["MPT_PRETRAINED_CONFIG_ARCHIVE_MAP", "MptConfig"],
+ "models.mra": ["MRA_PRETRAINED_CONFIG_ARCHIVE_MAP", "MraConfig"],
"models.mt5": ["MT5Config"],
+ "models.musicgen": [
+ "MUSICGEN_PRETRAINED_CONFIG_ARCHIVE_MAP",
+ "MusicgenConfig",
+ "MusicgenDecoderConfig",
+ ],
"models.mvp": ["MvpConfig", "MvpTokenizer"],
"models.nat": ["NAT_PRETRAINED_CONFIG_ARCHIVE_MAP", "NatConfig"],
"models.nezha": ["NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP", "NezhaConfig"],
@@ -395,7 +447,6 @@
"NystromformerConfig",
],
"models.oneformer": ["ONEFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "OneFormerConfig", "OneFormerProcessor"],
- "models.open_llama": ["OPEN_LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP", "OpenLlamaConfig"],
"models.openai": ["OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP", "OpenAIGPTConfig", "OpenAIGPTTokenizer"],
"models.opt": ["OPTConfig"],
"models.owlvit": [
@@ -419,6 +470,7 @@
"models.plbart": ["PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP", "PLBartConfig"],
"models.poolformer": ["POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "PoolFormerConfig"],
"models.prophetnet": ["PROPHETNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "ProphetNetConfig", "ProphetNetTokenizer"],
+ "models.pvt": ["PVT_PRETRAINED_CONFIG_ARCHIVE_MAP", "PvtConfig"],
"models.qdqbert": ["QDQBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "QDQBertConfig"],
"models.rag": ["RagConfig", "RagRetriever", "RagTokenizer"],
"models.realm": ["REALM_PRETRAINED_CONFIG_ARCHIVE_MAP", "RealmConfig", "RealmTokenizer"],
@@ -426,11 +478,11 @@
"models.regnet": ["REGNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "RegNetConfig"],
"models.rembert": ["REMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "RemBertConfig"],
"models.resnet": ["RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "ResNetConfig"],
- "models.retribert": ["RETRIBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "RetriBertConfig", "RetriBertTokenizer"],
"models.roberta": ["ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP", "RobertaConfig", "RobertaTokenizer"],
"models.roberta_prelayernorm": ["ROBERTA_PRELAYERNORM_PRETRAINED_CONFIG_ARCHIVE_MAP", "RobertaPreLayerNormConfig"],
"models.roc_bert": ["ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "RoCBertConfig", "RoCBertTokenizer"],
"models.roformer": ["ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "RoFormerConfig", "RoFormerTokenizer"],
+ "models.rwkv": ["RWKV_PRETRAINED_CONFIG_ARCHIVE_MAP", "RwkvConfig"],
"models.sam": [
"SAM_PRETRAINED_CONFIG_ARCHIVE_MAP",
"SamConfig",
@@ -458,11 +510,13 @@
"SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP",
"SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP",
"SpeechT5Config",
+ "SpeechT5FeatureExtractor",
"SpeechT5HifiGanConfig",
"SpeechT5Processor",
],
"models.splinter": ["SPLINTER_PRETRAINED_CONFIG_ARCHIVE_MAP", "SplinterConfig", "SplinterTokenizer"],
"models.squeezebert": ["SQUEEZEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "SqueezeBertConfig", "SqueezeBertTokenizer"],
+ "models.swiftformer": ["SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "SwiftFormerConfig"],
"models.swin": ["SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP", "SwinConfig"],
"models.swin2sr": ["SWIN2SR_PRETRAINED_CONFIG_ARCHIVE_MAP", "Swin2SRConfig"],
"models.swinv2": ["SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP", "Swinv2Config"],
@@ -470,16 +524,12 @@
"models.t5": ["T5_PRETRAINED_CONFIG_ARCHIVE_MAP", "T5Config"],
"models.table_transformer": ["TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "TableTransformerConfig"],
"models.tapas": ["TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP", "TapasConfig", "TapasTokenizer"],
- "models.tapex": ["TapexTokenizer"],
"models.time_series_transformer": [
"TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP",
"TimeSeriesTransformerConfig",
],
"models.timesformer": ["TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "TimesformerConfig"],
- "models.trajectory_transformer": [
- "TRAJECTORY_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP",
- "TrajectoryTransformerConfig",
- ],
+ "models.timm_backbone": ["TimmBackboneConfig"],
"models.transfo_xl": [
"TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP",
"TransfoXLConfig",
@@ -494,8 +544,10 @@
"models.tvlt": [
"TVLT_PRETRAINED_CONFIG_ARCHIVE_MAP",
"TvltConfig",
+ "TvltFeatureExtractor",
"TvltProcessor",
],
+ "models.umt5": ["UMT5Config"],
"models.unispeech": [
"UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP",
"UniSpeechConfig",
@@ -505,7 +557,6 @@
"UniSpeechSatConfig",
],
"models.upernet": ["UperNetConfig"],
- "models.van": ["VAN_PRETRAINED_CONFIG_ARCHIVE_MAP", "VanConfig"],
"models.videomae": ["VIDEOMAE_PRETRAINED_CONFIG_ARCHIVE_MAP", "VideoMAEConfig"],
"models.vilt": [
"VILT_PRETRAINED_CONFIG_ARCHIVE_MAP",
@@ -521,6 +572,10 @@
"models.vit_hybrid": ["VIT_HYBRID_PRETRAINED_CONFIG_ARCHIVE_MAP", "ViTHybridConfig"],
"models.vit_mae": ["VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ViTMAEConfig"],
"models.vit_msn": ["VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP", "ViTMSNConfig"],
+ "models.vivit": [
+ "VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP",
+ "VivitConfig",
+ ],
"models.wav2vec2": [
"WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP",
"Wav2Vec2Config",
@@ -609,6 +664,18 @@
"SpecialTokensMixin",
"TokenSpan",
],
+ "tools": [
+ "Agent",
+ "AzureOpenAiAgent",
+ "HfAgent",
+ "LocalAgent",
+ "OpenAiAgent",
+ "PipelineTool",
+ "RemoteTool",
+ "Tool",
+ "launch_gradio_demo",
+ "load_tool",
+ ],
"trainer_callback": [
"DefaultFlowCallback",
"EarlyStoppingCallback",
@@ -657,13 +724,14 @@
"is_tokenizers_available",
"is_torch_available",
"is_torch_neuroncore_available",
+ "is_torch_npu_available",
"is_torch_tpu_available",
"is_torchvision_available",
"is_vision_available",
"logging",
],
"utils.bitsandbytes": [],
- "utils.quantization_config": ["BitsAndBytesConfig"],
+ "utils.quantization_config": ["BitsAndBytesConfig", "GPTQConfig"],
}
# sentencepiece-backed objects
@@ -736,6 +804,7 @@
_import_structure["models.cpm"].append("CpmTokenizerFast")
_import_structure["models.deberta"].append("DebertaTokenizerFast")
_import_structure["models.deberta_v2"].append("DebertaV2TokenizerFast")
+ _import_structure["models.deprecated.retribert"].append("RetriBertTokenizerFast")
_import_structure["models.distilbert"].append("DistilBertTokenizerFast")
_import_structure["models.dpr"].extend(
["DPRContextEncoderTokenizerFast", "DPRQuestionEncoderTokenizerFast", "DPRReaderTokenizerFast"]
@@ -768,7 +837,6 @@
_import_structure["models.realm"].append("RealmTokenizerFast")
_import_structure["models.reformer"].append("ReformerTokenizerFast")
_import_structure["models.rembert"].append("RemBertTokenizerFast")
- _import_structure["models.retribert"].append("RetriBertTokenizerFast")
_import_structure["models.roberta"].append("RobertaTokenizerFast")
_import_structure["models.roformer"].append("RoFormerTokenizerFast")
_import_structure["models.splinter"].append("SplinterTokenizerFast")
@@ -805,10 +873,7 @@
]
else:
_import_structure["models.audio_spectrogram_transformer"].append("ASTFeatureExtractor")
- _import_structure["models.mctct"].append("MCTCTFeatureExtractor")
_import_structure["models.speech_to_text"].append("Speech2TextFeatureExtractor")
- _import_structure["models.speecht5"].append("SpeechT5FeatureExtractor")
- _import_structure["models.tvlt"].append("TvltFeatureExtractor")
# Tensorflow-text-specific objects
try:
@@ -885,6 +950,7 @@
_import_structure["models.perceiver"].extend(["PerceiverFeatureExtractor", "PerceiverImageProcessor"])
_import_structure["models.pix2struct"].extend(["Pix2StructImageProcessor"])
_import_structure["models.poolformer"].extend(["PoolFormerFeatureExtractor", "PoolFormerImageProcessor"])
+ _import_structure["models.pvt"].extend(["PvtImageProcessor"])
_import_structure["models.sam"].extend(["SamImageProcessor"])
_import_structure["models.segformer"].extend(["SegformerFeatureExtractor", "SegformerImageProcessor"])
_import_structure["models.swin2sr"].append("Swin2SRImageProcessor")
@@ -893,6 +959,7 @@
_import_structure["models.vilt"].extend(["ViltFeatureExtractor", "ViltImageProcessor", "ViltProcessor"])
_import_structure["models.vit"].extend(["ViTFeatureExtractor", "ViTImageProcessor"])
_import_structure["models.vit_hybrid"].extend(["ViTHybridImageProcessor"])
+ _import_structure["models.vivit"].append("VivitImageProcessor")
_import_structure["models.yolos"].extend(["YolosFeatureExtractor", "YolosImageProcessor"])
@@ -945,6 +1012,7 @@
"PhrasalConstraint",
"PrefixConstrainedLogitsProcessor",
"RepetitionPenaltyLogitsProcessor",
+ "SequenceBiasLogitsProcessor",
"StoppingCriteria",
"StoppingCriteriaList",
"TemperatureLogitsWarper",
@@ -1002,6 +1070,7 @@
_import_structure["models.auto"].extend(
[
"MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING",
+ "MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING",
"MODEL_FOR_AUDIO_XVECTOR_MAPPING",
"MODEL_FOR_BACKBONE_MAPPING",
"MODEL_FOR_CAUSAL_IMAGE_MODELING_MAPPING",
@@ -1025,6 +1094,7 @@
"MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING",
"MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING",
"MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING",
+ "MODEL_FOR_TEXT_ENCODING_MAPPING",
"MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING",
"MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING",
"MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING",
@@ -1059,6 +1129,7 @@
"AutoModelForSequenceClassification",
"AutoModelForSpeechSeq2Seq",
"AutoModelForTableQuestionAnswering",
+ "AutoModelForTextEncoding",
"AutoModelForTokenClassification",
"AutoModelForUniversalSegmentation",
"AutoModelForVideoClassification",
@@ -1069,6 +1140,25 @@
"AutoModelWithLMHead",
]
)
+ _import_structure["models.autoformer"].extend(
+ [
+ "AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST",
+ "AutoformerForPrediction",
+ "AutoformerModel",
+ "AutoformerPreTrainedModel",
+ ]
+ )
+ _import_structure["models.bark"].extend(
+ [
+ "BARK_PRETRAINED_MODEL_ARCHIVE_LIST",
+ "BarkCausalModel",
+ "BarkCoarseModel",
+ "BarkFineModel",
+ "BarkModel",
+ "BarkPreTrainedModel",
+ "BarkSemanticModel",
+ ]
+ )
_import_structure["models.bart"].extend(
[
"BART_PRETRAINED_MODEL_ARCHIVE_LIST",
@@ -1078,6 +1168,7 @@
"BartForSequenceClassification",
"BartModel",
"BartPretrainedModel",
+ "BartPreTrainedModel",
"PretrainedBartModel",
]
)
@@ -1440,6 +1531,36 @@
"DeiTPreTrainedModel",
]
)
+ _import_structure["models.deprecated.mctct"].extend(
+ [
+ "MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST",
+ "MCTCTForCTC",
+ "MCTCTModel",
+ "MCTCTPreTrainedModel",
+ ]
+ )
+ _import_structure["models.deprecated.mmbt"].extend(["MMBTForClassification", "MMBTModel", "ModalEmbeddings"])
+ _import_structure["models.deprecated.open_llama"].extend(
+ ["OpenLlamaForCausalLM", "OpenLlamaForSequenceClassification", "OpenLlamaModel", "OpenLlamaPreTrainedModel"]
+ )
+ _import_structure["models.deprecated.retribert"].extend(
+ ["RETRIBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "RetriBertModel", "RetriBertPreTrainedModel"]
+ )
+ _import_structure["models.deprecated.trajectory_transformer"].extend(
+ [
+ "TRAJECTORY_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST",
+ "TrajectoryTransformerModel",
+ "TrajectoryTransformerPreTrainedModel",
+ ]
+ )
+ _import_structure["models.deprecated.van"].extend(
+ [
+ "VAN_PRETRAINED_MODEL_ARCHIVE_LIST",
+ "VanForImageClassification",
+ "VanModel",
+ "VanPreTrainedModel",
+ ]
+ )
_import_structure["models.deta"].extend(
[
"DETA_PRETRAINED_MODEL_ARCHIVE_LIST",
@@ -1466,6 +1587,14 @@
"DinatPreTrainedModel",
]
)
+ _import_structure["models.dinov2"].extend(
+ [
+ "DINOV2_PRETRAINED_MODEL_ARCHIVE_LIST",
+ "Dinov2ForImageClassification",
+ "Dinov2Model",
+ "Dinov2PreTrainedModel",
+ ]
+ )
_import_structure["models.distilbert"].extend(
[
"DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST",
@@ -1540,6 +1669,13 @@
"load_tf_weights_in_electra",
]
)
+ _import_structure["models.encodec"].extend(
+ [
+ "ENCODEC_PRETRAINED_MODEL_ARCHIVE_LIST",
+ "EncodecModel",
+ "EncodecPreTrainedModel",
+ ]
+ )
_import_structure["models.encoder_decoder"].append("EncoderDecoderModel")
_import_structure["models.ernie"].extend(
[
@@ -1580,6 +1716,17 @@
"EsmPreTrainedModel",
]
)
+ _import_structure["models.falcon"].extend(
+ [
+ "FALCON_PRETRAINED_MODEL_ARCHIVE_LIST",
+ "FalconForCausalLM",
+ "FalconForQuestionAnswering",
+ "FalconForSequenceClassification",
+ "FalconForTokenClassification",
+ "FalconModel",
+ "FalconPreTrainedModel",
+ ]
+ )
_import_structure["models.flaubert"].extend(
[
"FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST",
@@ -1623,6 +1770,7 @@
_import_structure["models.focalnet"].extend(
[
"FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST",
+ "FocalNetBackbone",
"FocalNetForImageClassification",
"FocalNetForMaskedImageModeling",
"FocalNetModel",
@@ -1689,6 +1837,7 @@
[
"GPT_NEO_PRETRAINED_MODEL_ARCHIVE_LIST",
"GPTNeoForCausalLM",
+ "GPTNeoForQuestionAnswering",
"GPTNeoForSequenceClassification",
"GPTNeoForTokenClassification",
"GPTNeoModel",
@@ -1700,6 +1849,7 @@
[
"GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST",
"GPTNeoXForCausalLM",
+ "GPTNeoXForQuestionAnswering",
"GPTNeoXForSequenceClassification",
"GPTNeoXForTokenClassification",
"GPTNeoXLayer",
@@ -1790,6 +1940,15 @@
"InformerPreTrainedModel",
]
)
+ _import_structure["models.instructblip"].extend(
+ [
+ "INSTRUCTBLIP_PRETRAINED_MODEL_ARCHIVE_LIST",
+ "InstructBlipForConditionalGeneration",
+ "InstructBlipPreTrainedModel",
+ "InstructBlipQFormerModel",
+ "InstructBlipVisionModel",
+ ]
+ )
_import_structure["models.jukebox"].extend(
[
"JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST",
@@ -1956,14 +2115,6 @@
"MBartPreTrainedModel",
]
)
- _import_structure["models.mctct"].extend(
- [
- "MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST",
- "MCTCTForCTC",
- "MCTCTModel",
- "MCTCTPreTrainedModel",
- ]
- )
_import_structure["models.mega"].extend(
[
"MEGA_PRETRAINED_MODEL_ARCHIVE_LIST",
@@ -2000,7 +2151,6 @@
"MgpstrPreTrainedModel",
]
)
- _import_structure["models.mmbt"].extend(["MMBTForClassification", "MMBTModel", "ModalEmbeddings"])
_import_structure["models.mobilebert"].extend(
[
"MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST",
@@ -2045,6 +2195,15 @@
"MobileViTPreTrainedModel",
]
)
+ _import_structure["models.mobilevitv2"].extend(
+ [
+ "MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST",
+ "MobileViTV2ForImageClassification",
+ "MobileViTV2ForSemanticSegmentation",
+ "MobileViTV2Model",
+ "MobileViTV2PreTrainedModel",
+ ]
+ )
_import_structure["models.mpnet"].extend(
[
"MPNET_PRETRAINED_MODEL_ARCHIVE_LIST",
@@ -2058,8 +2217,48 @@
"MPNetPreTrainedModel",
]
)
+ _import_structure["models.mpt"].extend(
+ [
+ "MPT_PRETRAINED_MODEL_ARCHIVE_LIST",
+ "MptForCausalLM",
+ "MptForQuestionAnswering",
+ "MptForSequenceClassification",
+ "MptForTokenClassification",
+ "MptModel",
+ "MptPreTrainedModel",
+ ]
+ )
+ _import_structure["models.mra"].extend(
+ [
+ "MRA_PRETRAINED_MODEL_ARCHIVE_LIST",
+ "MraForMaskedLM",
+ "MraForMultipleChoice",
+ "MraForQuestionAnswering",
+ "MraForSequenceClassification",
+ "MraForTokenClassification",
+ "MraModel",
+ "MraPreTrainedModel",
+ ]
+ )
_import_structure["models.mt5"].extend(
- ["MT5EncoderModel", "MT5ForConditionalGeneration", "MT5Model", "MT5PreTrainedModel"]
+ [
+ "MT5EncoderModel",
+ "MT5ForConditionalGeneration",
+ "MT5ForQuestionAnswering",
+ "MT5ForSequenceClassification",
+ "MT5Model",
+ "MT5PreTrainedModel",
+ ]
+ )
+ _import_structure["models.musicgen"].extend(
+ [
+ "MUSICGEN_PRETRAINED_MODEL_ARCHIVE_LIST",
+ "MusicgenForCausalLM",
+ "MusicgenForConditionalGeneration",
+ "MusicgenModel",
+ "MusicgenPreTrainedModel",
+ "MusicgenProcessor",
+ ]
)
_import_structure["models.mvp"].extend(
[
@@ -2126,9 +2325,6 @@
"OneFormerPreTrainedModel",
]
)
- _import_structure["models.open_llama"].extend(
- ["OpenLlamaForCausalLM", "OpenLlamaForSequenceClassification", "OpenLlamaModel", "OpenLlamaPreTrainedModel"]
- )
_import_structure["models.openai"].extend(
[
"OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST",
@@ -2224,6 +2420,14 @@
"ProphetNetPreTrainedModel",
]
)
+ _import_structure["models.pvt"].extend(
+ [
+ "PVT_PRETRAINED_MODEL_ARCHIVE_LIST",
+ "PvtForImageClassification",
+ "PvtModel",
+ "PvtPreTrainedModel",
+ ]
+ )
_import_structure["models.qdqbert"].extend(
[
"QDQBERT_PRETRAINED_MODEL_ARCHIVE_LIST",
@@ -2301,9 +2505,6 @@
"ResNetPreTrainedModel",
]
)
- _import_structure["models.retribert"].extend(
- ["RETRIBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "RetriBertModel", "RetriBertPreTrainedModel"]
- )
_import_structure["models.roberta"].extend(
[
"ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST",
@@ -2361,6 +2562,14 @@
"load_tf_weights_in_roformer",
]
)
+ _import_structure["models.rwkv"].extend(
+ [
+ "RWKV_PRETRAINED_MODEL_ARCHIVE_LIST",
+ "RwkvForCausalLM",
+ "RwkvModel",
+ "RwkvPreTrainedModel",
+ ]
+ )
_import_structure["models.sam"].extend(
[
"SAM_PRETRAINED_MODEL_ARCHIVE_LIST",
@@ -2441,6 +2650,14 @@
"SqueezeBertPreTrainedModel",
]
)
+ _import_structure["models.swiftformer"].extend(
+ [
+ "SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST",
+ "SwiftFormerForImageClassification",
+ "SwiftFormerModel",
+ "SwiftFormerPreTrainedModel",
+ ]
+ )
_import_structure["models.swin"].extend(
[
"SWIN_PRETRAINED_MODEL_ARCHIVE_LIST",
@@ -2484,6 +2701,8 @@
"T5_PRETRAINED_MODEL_ARCHIVE_LIST",
"T5EncoderModel",
"T5ForConditionalGeneration",
+ "T5ForQuestionAnswering",
+ "T5ForSequenceClassification",
"T5Model",
"T5PreTrainedModel",
"load_tf_weights_in_t5",
@@ -2524,13 +2743,7 @@
"TimesformerPreTrainedModel",
]
)
- _import_structure["models.trajectory_transformer"].extend(
- [
- "TRAJECTORY_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST",
- "TrajectoryTransformerModel",
- "TrajectoryTransformerPreTrainedModel",
- ]
- )
+ _import_structure["models.timm_backbone"].extend(["TimmBackbone"])
_import_structure["models.transfo_xl"].extend(
[
"TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST",
@@ -2554,6 +2767,16 @@
"TvltPreTrainedModel",
]
)
+ _import_structure["models.umt5"].extend(
+ [
+ "UMT5EncoderModel",
+ "UMT5ForConditionalGeneration",
+ "UMT5ForQuestionAnswering",
+ "UMT5ForSequenceClassification",
+ "UMT5Model",
+ "UMT5PreTrainedModel",
+ ]
+ )
_import_structure["models.unispeech"].extend(
[
"UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST",
@@ -2582,14 +2805,6 @@
"UperNetPreTrainedModel",
]
)
- _import_structure["models.van"].extend(
- [
- "VAN_PRETRAINED_MODEL_ARCHIVE_LIST",
- "VanForImageClassification",
- "VanModel",
- "VanPreTrainedModel",
- ]
- )
_import_structure["models.videomae"].extend(
[
"VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST",
@@ -2661,6 +2876,14 @@
"ViTMSNPreTrainedModel",
]
)
+ _import_structure["models.vivit"].extend(
+ [
+ "VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST",
+ "VivitForVideoClassification",
+ "VivitModel",
+ "VivitPreTrainedModel",
+ ]
+ )
_import_structure["models.wav2vec2"].extend(
[
"WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST",
@@ -2896,11 +3119,13 @@
)
_import_structure["models.auto"].extend(
[
+ "TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING",
"TF_MODEL_FOR_CAUSAL_LM_MAPPING",
"TF_MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING",
"TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING",
"TF_MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING",
"TF_MODEL_FOR_MASKED_LM_MAPPING",
+ "TF_MODEL_FOR_MASK_GENERATION_MAPPING",
"TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING",
"TF_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING",
"TF_MODEL_FOR_PRETRAINING_MAPPING",
@@ -2910,16 +3135,20 @@
"TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING",
"TF_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING",
"TF_MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING",
+ "TF_MODEL_FOR_TEXT_ENCODING_MAPPING",
"TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING",
"TF_MODEL_FOR_VISION_2_SEQ_MAPPING",
"TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING",
"TF_MODEL_MAPPING",
"TF_MODEL_WITH_LM_HEAD_MAPPING",
"TFAutoModel",
+ "TFAutoModelForAudioClassification",
"TFAutoModelForCausalLM",
"TFAutoModelForDocumentQuestionAnswering",
"TFAutoModelForImageClassification",
+ "TFAutoModelForMaskedImageModeling",
"TFAutoModelForMaskedLM",
+ "TFAutoModelForMaskGeneration",
"TFAutoModelForMultipleChoice",
"TFAutoModelForNextSentencePrediction",
"TFAutoModelForPreTraining",
@@ -2929,6 +3158,7 @@
"TFAutoModelForSequenceClassification",
"TFAutoModelForSpeechSeq2Seq",
"TFAutoModelForTableQuestionAnswering",
+ "TFAutoModelForTextEncoding",
"TFAutoModelForTokenClassification",
"TFAutoModelForVision2Seq",
"TFAutoModelForZeroShotImageClassification",
@@ -3098,6 +3328,15 @@
"TFDPRReader",
]
)
+ _import_structure["models.efficientformer"].extend(
+ [
+ "TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST",
+ "TFEfficientFormerForImageClassification",
+ "TFEfficientFormerForImageClassificationWithTeacher",
+ "TFEfficientFormerModel",
+ "TFEfficientFormerPreTrainedModel",
+ ]
+ )
_import_structure["models.electra"].extend(
[
"TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST",
@@ -3374,6 +3613,13 @@
"TFRoFormerPreTrainedModel",
]
)
+ _import_structure["models.sam"].extend(
+ [
+ "TF_SAM_PRETRAINED_MODEL_ARCHIVE_LIST",
+ "TFSamModel",
+ "TFSamPreTrainedModel",
+ ]
+ )
_import_structure["models.segformer"].extend(
[
"TF_SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST",
@@ -3558,6 +3804,7 @@
)
_import_structure["models.auto"].extend(
[
+ "FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING",
"FLAX_MODEL_FOR_CAUSAL_LM_MAPPING",
"FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING",
"FLAX_MODEL_FOR_MASKED_LM_MAPPING",
@@ -3646,6 +3893,13 @@
"FlaxBlenderbotSmallPreTrainedModel",
]
)
+ _import_structure["models.bloom"].extend(
+ [
+ "FlaxBloomForCausalLM",
+ "FlaxBloomModel",
+ "FlaxBloomPreTrainedModel",
+ ]
+ )
_import_structure["models.clip"].extend(
[
"FlaxCLIPModel",
@@ -3776,6 +4030,7 @@
"FlaxWhisperForConditionalGeneration",
"FlaxWhisperModel",
"FlaxWhisperPreTrainedModel",
+ "FlaxWhisperForAudioClassification",
]
)
_import_structure["models.xglm"].extend(
@@ -3906,6 +4161,17 @@
AutoProcessor,
AutoTokenizer,
)
+ from .models.autoformer import (
+ AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
+ AutoformerConfig,
+ )
+ from .models.bark import (
+ BarkCoarseConfig,
+ BarkConfig,
+ BarkFineConfig,
+ BarkProcessor,
+ BarkSemanticConfig,
+ )
from .models.bart import BartConfig, BartTokenizer
from .models.beit import BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, BeitConfig
from .models.bert import (
@@ -4005,9 +4271,29 @@
)
from .models.deformable_detr import DEFORMABLE_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP, DeformableDetrConfig
from .models.deit import DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, DeiTConfig
+ from .models.deprecated.mctct import (
+ MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP,
+ MCTCTConfig,
+ MCTCTFeatureExtractor,
+ MCTCTProcessor,
+ )
+ from .models.deprecated.mmbt import MMBTConfig
+ from .models.deprecated.open_llama import OPEN_LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP, OpenLlamaConfig
+ from .models.deprecated.retribert import (
+ RETRIBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
+ RetriBertConfig,
+ RetriBertTokenizer,
+ )
+ from .models.deprecated.tapex import TapexTokenizer
+ from .models.deprecated.trajectory_transformer import (
+ TRAJECTORY_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
+ TrajectoryTransformerConfig,
+ )
+ from .models.deprecated.van import VAN_PRETRAINED_CONFIG_ARCHIVE_MAP, VanConfig
from .models.deta import DETA_PRETRAINED_CONFIG_ARCHIVE_MAP, DetaConfig
from .models.detr import DETR_PRETRAINED_CONFIG_ARCHIVE_MAP, DetrConfig
from .models.dinat import DINAT_PRETRAINED_CONFIG_ARCHIVE_MAP, DinatConfig
+ from .models.dinov2 import DINOV2_PRETRAINED_CONFIG_ARCHIVE_MAP, Dinov2Config
from .models.distilbert import DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DistilBertConfig, DistilBertTokenizer
from .models.donut import DONUT_SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP, DonutProcessor, DonutSwinConfig
from .models.dpr import (
@@ -4022,10 +4308,16 @@
from .models.efficientformer import EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientFormerConfig
from .models.efficientnet import EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientNetConfig
from .models.electra import ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ElectraConfig, ElectraTokenizer
+ from .models.encodec import (
+ ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP,
+ EncodecConfig,
+ EncodecFeatureExtractor,
+ )
from .models.encoder_decoder import EncoderDecoderConfig
from .models.ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig
from .models.ernie_m import ERNIE_M_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieMConfig
from .models.esm import ESM_PRETRAINED_CONFIG_ARCHIVE_MAP, EsmConfig, EsmTokenizer
+ from .models.falcon import FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP, FalconConfig
from .models.flaubert import FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, FlaubertConfig, FlaubertTokenizer
from .models.flava import (
FLAVA_PRETRAINED_CONFIG_ARCHIVE_MAP,
@@ -4064,6 +4356,13 @@
from .models.ibert import IBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, IBertConfig
from .models.imagegpt import IMAGEGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ImageGPTConfig
from .models.informer import INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, InformerConfig
+ from .models.instructblip import (
+ INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP,
+ InstructBlipConfig,
+ InstructBlipProcessor,
+ InstructBlipQFormerConfig,
+ InstructBlipVisionConfig,
+ )
from .models.jukebox import (
JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP,
JukeboxConfig,
@@ -4109,24 +4408,29 @@
from .models.mask2former import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, Mask2FormerConfig
from .models.maskformer import MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskFormerConfig, MaskFormerSwinConfig
from .models.mbart import MBartConfig
- from .models.mctct import MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP, MCTCTConfig, MCTCTProcessor
from .models.mega import MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP, MegaConfig
from .models.megatron_bert import MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MegatronBertConfig
from .models.mgp_str import MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP, MgpstrConfig, MgpstrProcessor, MgpstrTokenizer
- from .models.mmbt import MMBTConfig
from .models.mobilebert import MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileBertConfig, MobileBertTokenizer
from .models.mobilenet_v1 import MOBILENET_V1_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileNetV1Config
from .models.mobilenet_v2 import MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileNetV2Config
from .models.mobilevit import MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileViTConfig
+ from .models.mobilevitv2 import MOBILEVITV2_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileViTV2Config
from .models.mpnet import MPNET_PRETRAINED_CONFIG_ARCHIVE_MAP, MPNetConfig, MPNetTokenizer
+ from .models.mpt import MPT_PRETRAINED_CONFIG_ARCHIVE_MAP, MptConfig
+ from .models.mra import MRA_PRETRAINED_CONFIG_ARCHIVE_MAP, MraConfig
from .models.mt5 import MT5Config
+ from .models.musicgen import (
+ MUSICGEN_PRETRAINED_CONFIG_ARCHIVE_MAP,
+ MusicgenConfig,
+ MusicgenDecoderConfig,
+ )
from .models.mvp import MvpConfig, MvpTokenizer
from .models.nat import NAT_PRETRAINED_CONFIG_ARCHIVE_MAP, NatConfig
from .models.nezha import NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP, NezhaConfig
from .models.nllb_moe import NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP, NllbMoeConfig
from .models.nystromformer import NYSTROMFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, NystromformerConfig
from .models.oneformer import ONEFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, OneFormerConfig, OneFormerProcessor
- from .models.open_llama import OPEN_LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP, OpenLlamaConfig
from .models.openai import OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, OpenAIGPTConfig, OpenAIGPTTokenizer
from .models.opt import OPTConfig
from .models.owlvit import (
@@ -4150,6 +4454,7 @@
from .models.plbart import PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP, PLBartConfig
from .models.poolformer import POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, PoolFormerConfig
from .models.prophetnet import PROPHETNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ProphetNetConfig, ProphetNetTokenizer
+ from .models.pvt import PVT_PRETRAINED_CONFIG_ARCHIVE_MAP, PvtConfig
from .models.qdqbert import QDQBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, QDQBertConfig
from .models.rag import RagConfig, RagRetriever, RagTokenizer
from .models.realm import REALM_PRETRAINED_CONFIG_ARCHIVE_MAP, RealmConfig, RealmTokenizer
@@ -4157,7 +4462,6 @@
from .models.regnet import REGNET_PRETRAINED_CONFIG_ARCHIVE_MAP, RegNetConfig
from .models.rembert import REMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RemBertConfig
from .models.resnet import RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ResNetConfig
- from .models.retribert import RETRIBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RetriBertConfig, RetriBertTokenizer
from .models.roberta import ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, RobertaConfig, RobertaTokenizer
from .models.roberta_prelayernorm import (
ROBERTA_PRELAYERNORM_PRETRAINED_CONFIG_ARCHIVE_MAP,
@@ -4165,6 +4469,7 @@
)
from .models.roc_bert import ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RoCBertConfig, RoCBertTokenizer
from .models.roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerTokenizer
+ from .models.rwkv import RWKV_PRETRAINED_CONFIG_ARCHIVE_MAP, RwkvConfig
from .models.sam import (
SAM_PRETRAINED_CONFIG_ARCHIVE_MAP,
SamConfig,
@@ -4192,11 +4497,13 @@
SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP,
SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP,
SpeechT5Config,
+ SpeechT5FeatureExtractor,
SpeechT5HifiGanConfig,
SpeechT5Processor,
)
from .models.splinter import SPLINTER_PRETRAINED_CONFIG_ARCHIVE_MAP, SplinterConfig, SplinterTokenizer
from .models.squeezebert import SQUEEZEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, SqueezeBertConfig, SqueezeBertTokenizer
+ from .models.swiftformer import SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, SwiftFormerConfig
from .models.swin import SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP, SwinConfig
from .models.swin2sr import SWIN2SR_PRETRAINED_CONFIG_ARCHIVE_MAP, Swin2SRConfig
from .models.swinv2 import SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP, Swinv2Config
@@ -4204,16 +4511,12 @@
from .models.t5 import T5_PRETRAINED_CONFIG_ARCHIVE_MAP, T5Config
from .models.table_transformer import TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TableTransformerConfig
from .models.tapas import TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP, TapasConfig, TapasTokenizer
- from .models.tapex import TapexTokenizer
from .models.time_series_transformer import (
TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
TimeSeriesTransformerConfig,
)
from .models.timesformer import TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimesformerConfig
- from .models.trajectory_transformer import (
- TRAJECTORY_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
- TrajectoryTransformerConfig,
- )
+ from .models.timm_backbone import TimmBackboneConfig
from .models.transfo_xl import (
TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP,
TransfoXLConfig,
@@ -4221,11 +4524,11 @@
TransfoXLTokenizer,
)
from .models.trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig, TrOCRProcessor
- from .models.tvlt import TVLT_PRETRAINED_CONFIG_ARCHIVE_MAP, TvltConfig, TvltProcessor
+ from .models.tvlt import TVLT_PRETRAINED_CONFIG_ARCHIVE_MAP, TvltConfig, TvltFeatureExtractor, TvltProcessor
+ from .models.umt5 import UMT5Config
from .models.unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig
from .models.unispeech_sat import UNISPEECH_SAT_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechSatConfig
from .models.upernet import UperNetConfig
- from .models.van import VAN_PRETRAINED_CONFIG_ARCHIVE_MAP, VanConfig
from .models.videomae import VIDEOMAE_PRETRAINED_CONFIG_ARCHIVE_MAP, VideoMAEConfig
from .models.vilt import (
VILT_PRETRAINED_CONFIG_ARCHIVE_MAP,
@@ -4241,6 +4544,7 @@
from .models.vit_hybrid import VIT_HYBRID_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTHybridConfig
from .models.vit_mae import VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMAEConfig
from .models.vit_msn import VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMSNConfig
+ from .models.vivit import VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, VivitConfig
from .models.wav2vec2 import (
WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP,
Wav2Vec2Config,
@@ -4326,6 +4630,20 @@
TokenSpan,
)
+ # Tools
+ from .tools import (
+ Agent,
+ AzureOpenAiAgent,
+ HfAgent,
+ LocalAgent,
+ OpenAiAgent,
+ PipelineTool,
+ RemoteTool,
+ Tool,
+ launch_gradio_demo,
+ load_tool,
+ )
+
# Trainer
from .trainer_callback import (
DefaultFlowCallback,
@@ -4377,6 +4695,7 @@
is_tokenizers_available,
is_torch_available,
is_torch_neuroncore_available,
+ is_torch_npu_available,
is_torch_tpu_available,
is_torchvision_available,
is_vision_available,
@@ -4384,7 +4703,7 @@
)
# bitsandbytes config
- from .utils.quantization_config import BitsAndBytesConfig
+ from .utils.quantization_config import BitsAndBytesConfig, GPTQConfig
try:
if not is_sentencepiece_available():
@@ -4445,6 +4764,7 @@
from .models.cpm import CpmTokenizerFast
from .models.deberta import DebertaTokenizerFast
from .models.deberta_v2 import DebertaV2TokenizerFast
+ from .models.deprecated.retribert import RetriBertTokenizerFast
from .models.distilbert import DistilBertTokenizerFast
from .models.dpr import DPRContextEncoderTokenizerFast, DPRQuestionEncoderTokenizerFast, DPRReaderTokenizerFast
from .models.electra import ElectraTokenizerFast
@@ -4475,7 +4795,6 @@
from .models.realm import RealmTokenizerFast
from .models.reformer import ReformerTokenizerFast
from .models.rembert import RemBertTokenizerFast
- from .models.retribert import RetriBertTokenizerFast
from .models.roberta import RobertaTokenizerFast
from .models.roformer import RoFormerTokenizerFast
from .models.splinter import SplinterTokenizerFast
@@ -4502,10 +4821,7 @@
from .utils.dummy_speech_objects import *
else:
from .models.audio_spectrogram_transformer import ASTFeatureExtractor
- from .models.mctct import MCTCTFeatureExtractor
from .models.speech_to_text import Speech2TextFeatureExtractor
- from .models.speecht5 import SpeechT5FeatureExtractor
- from .models.tvlt import TvltFeatureExtractor
try:
if not is_tensorflow_text_available():
@@ -4563,6 +4879,7 @@
from .models.perceiver import PerceiverFeatureExtractor, PerceiverImageProcessor
from .models.pix2struct import Pix2StructImageProcessor
from .models.poolformer import PoolFormerFeatureExtractor, PoolFormerImageProcessor
+ from .models.pvt import PvtImageProcessor
from .models.sam import SamImageProcessor
from .models.segformer import SegformerFeatureExtractor, SegformerImageProcessor
from .models.swin2sr import Swin2SRImageProcessor
@@ -4571,6 +4888,7 @@
from .models.vilt import ViltFeatureExtractor, ViltImageProcessor, ViltProcessor
from .models.vit import ViTFeatureExtractor, ViTImageProcessor
from .models.vit_hybrid import ViTHybridImageProcessor
+ from .models.vivit import VivitImageProcessor
from .models.yolos import YolosFeatureExtractor, YolosImageProcessor
# Modeling
@@ -4618,6 +4936,7 @@
PhrasalConstraint,
PrefixConstrainedLogitsProcessor,
RepetitionPenaltyLogitsProcessor,
+ SequenceBiasLogitsProcessor,
StoppingCriteria,
StoppingCriteriaList,
TemperatureLogitsWarper,
@@ -4663,6 +4982,7 @@
)
from .models.auto import (
MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING,
+ MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING,
MODEL_FOR_AUDIO_XVECTOR_MAPPING,
MODEL_FOR_BACKBONE_MAPPING,
MODEL_FOR_CAUSAL_IMAGE_MODELING_MAPPING,
@@ -4686,6 +5006,7 @@
MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING,
MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING,
+ MODEL_FOR_TEXT_ENCODING_MAPPING,
MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING,
MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING,
@@ -4720,6 +5041,7 @@
AutoModelForSequenceClassification,
AutoModelForSpeechSeq2Seq,
AutoModelForTableQuestionAnswering,
+ AutoModelForTextEncoding,
AutoModelForTokenClassification,
AutoModelForUniversalSegmentation,
AutoModelForVideoClassification,
@@ -4729,6 +5051,21 @@
AutoModelForZeroShotObjectDetection,
AutoModelWithLMHead,
)
+ from .models.autoformer import (
+ AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
+ AutoformerForPrediction,
+ AutoformerModel,
+ AutoformerPreTrainedModel,
+ )
+ from .models.bark import (
+ BARK_PRETRAINED_MODEL_ARCHIVE_LIST,
+ BarkCausalModel,
+ BarkCoarseModel,
+ BarkFineModel,
+ BarkModel,
+ BarkPreTrainedModel,
+ BarkSemanticModel,
+ )
from .models.bart import (
BART_PRETRAINED_MODEL_ARCHIVE_LIST,
BartForCausalLM,
@@ -4736,6 +5073,7 @@
BartForQuestionAnswering,
BartForSequenceClassification,
BartModel,
+ BartPreTrainedModel,
BartPretrainedModel,
PretrainedBartModel,
)
@@ -5032,6 +5370,35 @@
DeiTModel,
DeiTPreTrainedModel,
)
+ from .models.deprecated.mctct import (
+ MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST,
+ MCTCTForCTC,
+ MCTCTModel,
+ MCTCTPreTrainedModel,
+ )
+ from .models.deprecated.mmbt import MMBTForClassification, MMBTModel, ModalEmbeddings
+ from .models.deprecated.open_llama import (
+ OpenLlamaForCausalLM,
+ OpenLlamaForSequenceClassification,
+ OpenLlamaModel,
+ OpenLlamaPreTrainedModel,
+ )
+ from .models.deprecated.retribert import (
+ RETRIBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
+ RetriBertModel,
+ RetriBertPreTrainedModel,
+ )
+ from .models.deprecated.trajectory_transformer import (
+ TRAJECTORY_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
+ TrajectoryTransformerModel,
+ TrajectoryTransformerPreTrainedModel,
+ )
+ from .models.deprecated.van import (
+ VAN_PRETRAINED_MODEL_ARCHIVE_LIST,
+ VanForImageClassification,
+ VanModel,
+ VanPreTrainedModel,
+ )
from .models.deta import (
DETA_PRETRAINED_MODEL_ARCHIVE_LIST,
DetaForObjectDetection,
@@ -5052,6 +5419,12 @@
DinatModel,
DinatPreTrainedModel,
)
+ from .models.dinov2 import (
+ DINOV2_PRETRAINED_MODEL_ARCHIVE_LIST,
+ Dinov2ForImageClassification,
+ Dinov2Model,
+ Dinov2PreTrainedModel,
+ )
from .models.distilbert import (
DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
DistilBertForMaskedLM,
@@ -5108,6 +5481,11 @@
ElectraPreTrainedModel,
load_tf_weights_in_electra,
)
+ from .models.encodec import (
+ ENCODEC_PRETRAINED_MODEL_ARCHIVE_LIST,
+ EncodecModel,
+ EncodecPreTrainedModel,
+ )
from .models.encoder_decoder import EncoderDecoderModel
from .models.ernie import (
ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST,
@@ -5142,6 +5520,15 @@
EsmModel,
EsmPreTrainedModel,
)
+ from .models.falcon import (
+ FALCON_PRETRAINED_MODEL_ARCHIVE_LIST,
+ FalconForCausalLM,
+ FalconForQuestionAnswering,
+ FalconForSequenceClassification,
+ FalconForTokenClassification,
+ FalconModel,
+ FalconPreTrainedModel,
+ )
from .models.flaubert import (
FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
FlaubertForMultipleChoice,
@@ -5178,6 +5565,7 @@
)
from .models.focalnet import (
FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST,
+ FocalNetBackbone,
FocalNetForImageClassification,
FocalNetForMaskedImageModeling,
FocalNetModel,
@@ -5232,6 +5620,7 @@
from .models.gpt_neo import (
GPT_NEO_PRETRAINED_MODEL_ARCHIVE_LIST,
GPTNeoForCausalLM,
+ GPTNeoForQuestionAnswering,
GPTNeoForSequenceClassification,
GPTNeoForTokenClassification,
GPTNeoModel,
@@ -5241,6 +5630,7 @@
from .models.gpt_neox import (
GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST,
GPTNeoXForCausalLM,
+ GPTNeoXForQuestionAnswering,
GPTNeoXForSequenceClassification,
GPTNeoXForTokenClassification,
GPTNeoXLayer,
@@ -5312,6 +5702,13 @@
InformerModel,
InformerPreTrainedModel,
)
+ from .models.instructblip import (
+ INSTRUCTBLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
+ InstructBlipForConditionalGeneration,
+ InstructBlipPreTrainedModel,
+ InstructBlipQFormerModel,
+ InstructBlipVisionModel,
+ )
from .models.jukebox import (
JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST,
JukeboxModel,
@@ -5444,7 +5841,6 @@
MBartModel,
MBartPreTrainedModel,
)
- from .models.mctct import MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST, MCTCTForCTC, MCTCTModel, MCTCTPreTrainedModel
from .models.mega import (
MEGA_PRETRAINED_MODEL_ARCHIVE_LIST,
MegaForCausalLM,
@@ -5475,7 +5871,6 @@
MgpstrModel,
MgpstrPreTrainedModel,
)
- from .models.mmbt import MMBTForClassification, MMBTModel, ModalEmbeddings
from .models.mobilebert import (
MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
MobileBertForMaskedLM,
@@ -5512,6 +5907,13 @@
MobileViTModel,
MobileViTPreTrainedModel,
)
+ from .models.mobilevitv2 import (
+ MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST,
+ MobileViTV2ForImageClassification,
+ MobileViTV2ForSemanticSegmentation,
+ MobileViTV2Model,
+ MobileViTV2PreTrainedModel,
+ )
from .models.mpnet import (
MPNET_PRETRAINED_MODEL_ARCHIVE_LIST,
MPNetForMaskedLM,
@@ -5523,7 +5925,41 @@
MPNetModel,
MPNetPreTrainedModel,
)
- from .models.mt5 import MT5EncoderModel, MT5ForConditionalGeneration, MT5Model, MT5PreTrainedModel
+ from .models.mpt import (
+ MPT_PRETRAINED_MODEL_ARCHIVE_LIST,
+ MptForCausalLM,
+ MptForQuestionAnswering,
+ MptForSequenceClassification,
+ MptForTokenClassification,
+ MptModel,
+ MptPreTrainedModel,
+ )
+ from .models.mra import (
+ MRA_PRETRAINED_MODEL_ARCHIVE_LIST,
+ MraForMaskedLM,
+ MraForMultipleChoice,
+ MraForQuestionAnswering,
+ MraForSequenceClassification,
+ MraForTokenClassification,
+ MraModel,
+ MraPreTrainedModel,
+ )
+ from .models.mt5 import (
+ MT5EncoderModel,
+ MT5ForConditionalGeneration,
+ MT5ForQuestionAnswering,
+ MT5ForSequenceClassification,
+ MT5Model,
+ MT5PreTrainedModel,
+ )
+ from .models.musicgen import (
+ MUSICGEN_PRETRAINED_MODEL_ARCHIVE_LIST,
+ MusicgenForCausalLM,
+ MusicgenForConditionalGeneration,
+ MusicgenModel,
+ MusicgenPreTrainedModel,
+ MusicgenProcessor,
+ )
from .models.mvp import (
MVP_PRETRAINED_MODEL_ARCHIVE_LIST,
MvpForCausalLM,
@@ -5577,12 +6013,6 @@
OneFormerModel,
OneFormerPreTrainedModel,
)
- from .models.open_llama import (
- OpenLlamaForCausalLM,
- OpenLlamaForSequenceClassification,
- OpenLlamaModel,
- OpenLlamaPreTrainedModel,
- )
from .models.openai import (
OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST,
OpenAIGPTDoubleHeadsModel,
@@ -5663,6 +6093,12 @@
ProphetNetModel,
ProphetNetPreTrainedModel,
)
+ from .models.pvt import (
+ PVT_PRETRAINED_MODEL_ARCHIVE_LIST,
+ PvtForImageClassification,
+ PvtModel,
+ PvtPreTrainedModel,
+ )
from .models.qdqbert import (
QDQBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
QDQBertForMaskedLM,
@@ -5726,7 +6162,6 @@
ResNetModel,
ResNetPreTrainedModel,
)
- from .models.retribert import RETRIBERT_PRETRAINED_MODEL_ARCHIVE_LIST, RetriBertModel, RetriBertPreTrainedModel
from .models.roberta import (
ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST,
RobertaForCausalLM,
@@ -5776,6 +6211,12 @@
RoFormerPreTrainedModel,
load_tf_weights_in_roformer,
)
+ from .models.rwkv import (
+ RWKV_PRETRAINED_MODEL_ARCHIVE_LIST,
+ RwkvForCausalLM,
+ RwkvModel,
+ RwkvPreTrainedModel,
+ )
from .models.sam import (
SAM_PRETRAINED_MODEL_ARCHIVE_LIST,
SamModel,
@@ -5840,6 +6281,12 @@
SqueezeBertModule,
SqueezeBertPreTrainedModel,
)
+ from .models.swiftformer import (
+ SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
+ SwiftFormerForImageClassification,
+ SwiftFormerModel,
+ SwiftFormerPreTrainedModel,
+ )
from .models.swin import (
SWIN_PRETRAINED_MODEL_ARCHIVE_LIST,
SwinBackbone,
@@ -5874,6 +6321,8 @@
T5_PRETRAINED_MODEL_ARCHIVE_LIST,
T5EncoderModel,
T5ForConditionalGeneration,
+ T5ForQuestionAnswering,
+ T5ForSequenceClassification,
T5Model,
T5PreTrainedModel,
load_tf_weights_in_t5,
@@ -5905,11 +6354,7 @@
TimesformerModel,
TimesformerPreTrainedModel,
)
- from .models.trajectory_transformer import (
- TRAJECTORY_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
- TrajectoryTransformerModel,
- TrajectoryTransformerPreTrainedModel,
- )
+ from .models.timm_backbone import TimmBackbone
from .models.transfo_xl import (
TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST,
AdaptiveEmbedding,
@@ -5927,6 +6372,14 @@
TvltModel,
TvltPreTrainedModel,
)
+ from .models.umt5 import (
+ UMT5EncoderModel,
+ UMT5ForConditionalGeneration,
+ UMT5ForQuestionAnswering,
+ UMT5ForSequenceClassification,
+ UMT5Model,
+ UMT5PreTrainedModel,
+ )
from .models.unispeech import (
UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST,
UniSpeechForCTC,
@@ -5946,12 +6399,6 @@
UniSpeechSatPreTrainedModel,
)
from .models.upernet import UperNetForSemanticSegmentation, UperNetPreTrainedModel
- from .models.van import (
- VAN_PRETRAINED_MODEL_ARCHIVE_LIST,
- VanForImageClassification,
- VanModel,
- VanPreTrainedModel,
- )
from .models.videomae import (
VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST,
VideoMAEForPreTraining,
@@ -6009,6 +6456,12 @@
ViTMSNModel,
ViTMSNPreTrainedModel,
)
+ from .models.vivit import (
+ VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST,
+ VivitForVideoClassification,
+ VivitModel,
+ VivitPreTrainedModel,
+ )
from .models.wav2vec2 import (
WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST,
Wav2Vec2ForAudioFrameClassification,
@@ -6203,9 +6656,11 @@
TFAlbertPreTrainedModel,
)
from .models.auto import (
+ TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING,
TF_MODEL_FOR_CAUSAL_LM_MAPPING,
TF_MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING,
TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
+ TF_MODEL_FOR_MASK_GENERATION_MAPPING,
TF_MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING,
TF_MODEL_FOR_MASKED_LM_MAPPING,
TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
@@ -6217,16 +6672,20 @@
TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
TF_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING,
TF_MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING,
+ TF_MODEL_FOR_TEXT_ENCODING_MAPPING,
TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
TF_MODEL_FOR_VISION_2_SEQ_MAPPING,
TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING,
TF_MODEL_MAPPING,
TF_MODEL_WITH_LM_HEAD_MAPPING,
TFAutoModel,
+ TFAutoModelForAudioClassification,
TFAutoModelForCausalLM,
TFAutoModelForDocumentQuestionAnswering,
TFAutoModelForImageClassification,
+ TFAutoModelForMaskedImageModeling,
TFAutoModelForMaskedLM,
+ TFAutoModelForMaskGeneration,
TFAutoModelForMultipleChoice,
TFAutoModelForNextSentencePrediction,
TFAutoModelForPreTraining,
@@ -6236,6 +6695,7 @@
TFAutoModelForSequenceClassification,
TFAutoModelForSpeechSeq2Seq,
TFAutoModelForTableQuestionAnswering,
+ TFAutoModelForTextEncoding,
TFAutoModelForTokenClassification,
TFAutoModelForVision2Seq,
TFAutoModelForZeroShotImageClassification,
@@ -6379,6 +6839,13 @@
TFDPRQuestionEncoder,
TFDPRReader,
)
+ from .models.efficientformer import (
+ TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
+ TFEfficientFormerForImageClassification,
+ TFEfficientFormerForImageClassificationWithTeacher,
+ TFEfficientFormerModel,
+ TFEfficientFormerPreTrainedModel,
+ )
from .models.electra import (
TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST,
TFElectraForMaskedLM,
@@ -6594,6 +7061,11 @@
TFRoFormerModel,
TFRoFormerPreTrainedModel,
)
+ from .models.sam import (
+ TF_SAM_PRETRAINED_MODEL_ARCHIVE_LIST,
+ TFSamModel,
+ TFSamPreTrainedModel,
+ )
from .models.segformer import (
TF_SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
TFSegformerDecodeHead,
@@ -6736,6 +7208,7 @@
FlaxAlbertPreTrainedModel,
)
from .models.auto import (
+ FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING,
FLAX_MODEL_FOR_CAUSAL_LM_MAPPING,
FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
FLAX_MODEL_FOR_MASKED_LM_MAPPING,
@@ -6811,6 +7284,7 @@
FlaxBlenderbotSmallModel,
FlaxBlenderbotSmallPreTrainedModel,
)
+ from .models.bloom import FlaxBloomForCausalLM, FlaxBloomModel, FlaxBloomPreTrainedModel
from .models.clip import (
FlaxCLIPModel,
FlaxCLIPPreTrainedModel,
@@ -6897,7 +7371,12 @@
FlaxWav2Vec2Model,
FlaxWav2Vec2PreTrainedModel,
)
- from .models.whisper import FlaxWhisperForConditionalGeneration, FlaxWhisperModel, FlaxWhisperPreTrainedModel
+ from .models.whisper import (
+ FlaxWhisperForAudioClassification,
+ FlaxWhisperForConditionalGeneration,
+ FlaxWhisperModel,
+ FlaxWhisperPreTrainedModel,
+ )
from .models.xglm import FlaxXGLMForCausalLM, FlaxXGLMModel, FlaxXGLMPreTrainedModel
from .models.xlm_roberta import (
FLAX_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST,
diff --git a/src/transformers/audio_utils.py b/src/transformers/audio_utils.py
index 73bc041d6961..a34892af4123 100644
--- a/src/transformers/audio_utils.py
+++ b/src/transformers/audio_utils.py
@@ -1,5 +1,5 @@
# coding=utf-8
-# Copyright 2023 The HuggingFace Inc. team.
+# Copyright 2023 The HuggingFace Inc. team and the librosa & torchaudio authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -13,66 +13,61 @@
# See the License for the specific language governing permissions and
# limitations under the License.
"""
- Audio processing functions to extract feature from a raw audio. Should all be in numpy to support all frameworks, and
- remmove unecessary dependencies.
+Audio processing functions to extract features from audio waveforms. This code is pure numpy to support all frameworks
+and remove unnecessary dependencies.
"""
-import math
import warnings
-from typing import Optional
+from typing import Optional, Union
import numpy as np
-from numpy.fft import fft
-def hertz_to_mel(freq: float, mel_scale: str = "htk") -> float:
- """Convert Hertz to Mels.
+def hertz_to_mel(freq: Union[float, np.ndarray], mel_scale: str = "htk") -> Union[float, np.ndarray]:
+ """
+ Convert frequency from hertz to mels.
Args:
- freqs (`float`):
- Frequencies in Hertz
+ freq (`float` or `np.ndarray`):
+ The frequency, or multiple frequencies, in hertz (Hz).
mel_scale (`str`, *optional*, defaults to `"htk"`):
- Scale to use, `htk` or `slaney`.
+ The mel frequency scale to use, `"htk"` or `"slaney"`.
Returns:
- mels (`float`):
- Frequency in Mels
+ `float` or `np.ndarray`: The frequencies on the mel scale.
"""
if mel_scale not in ["slaney", "htk"]:
raise ValueError('mel_scale should be one of "htk" or "slaney".')
if mel_scale == "htk":
- return 2595.0 * math.log10(1.0 + (freq / 700.0))
-
- # Fill in the linear part
- frequency_min = 0.0
- f_sp = 200.0 / 3
+ return 2595.0 * np.log10(1.0 + (freq / 700.0))
- mels = (freq - frequency_min) / f_sp
-
- # Fill in the log-scale part
min_log_hertz = 1000.0
- min_log_mel = (min_log_hertz - frequency_min) / f_sp
- logstep = math.log(6.4) / 27.0
+ min_log_mel = 15.0
+ logstep = 27.0 / np.log(6.4)
+ mels = 3.0 * freq / 200.0
- if freq >= min_log_hertz:
- mels = min_log_mel + math.log(freq / min_log_hertz) / logstep
+ if isinstance(freq, np.ndarray):
+ log_region = freq >= min_log_hertz
+ mels[log_region] = min_log_mel + np.log(freq[log_region] / min_log_hertz) * logstep
+ elif freq >= min_log_hertz:
+ mels = min_log_mel + np.log(freq / min_log_hertz) * logstep
return mels
-def mel_to_hertz(mels: np.array, mel_scale: str = "htk") -> np.array:
- """Convert mel bin numbers to frequencies.
+def mel_to_hertz(mels: Union[float, np.ndarray], mel_scale: str = "htk") -> Union[float, np.ndarray]:
+ """
+ Convert frequency from mels to hertz.
Args:
- mels (`np.array`):
- Mel frequencies
+ mels (`float` or `np.ndarray`):
+ The frequency, or multiple frequencies, in mels.
mel_scale (`str`, *optional*, `"htk"`):
- Scale to use: `htk` or `slaney`.
+ The mel frequency scale to use, `"htk"` or `"slaney"`.
Returns:
- freqs (`np.array`):
- Mels converted to Hertz
+ `float` or `np.ndarray`: The frequencies in hertz.
"""
if mel_scale not in ["slaney", "htk"]:
@@ -81,171 +76,509 @@ def mel_to_hertz(mels: np.array, mel_scale: str = "htk") -> np.array:
if mel_scale == "htk":
return 700.0 * (10.0 ** (mels / 2595.0) - 1.0)
- # Fill in the linear scale
- frequency_min = 0.0
- f_sp = 200.0 / 3
- freqs = frequency_min + f_sp * mels
-
- # And now the nonlinear scale
min_log_hertz = 1000.0
- min_log_mel = (min_log_hertz - frequency_min) / f_sp
- logstep = math.log(6.4) / 27.0
+ min_log_mel = 15.0
+ logstep = np.log(6.4) / 27.0
+ freq = 200.0 * mels / 3.0
- log_t = mels >= min_log_mel
- freqs[log_t] = min_log_hertz * np.exp(logstep * (mels[log_t] - min_log_mel))
+ if isinstance(mels, np.ndarray):
+ log_region = mels >= min_log_mel
+ freq[log_region] = min_log_hertz * np.exp(logstep * (mels[log_region] - min_log_mel))
+ elif mels >= min_log_mel:
+ freq = min_log_hertz * np.exp(logstep * (mels - min_log_mel))
- return freqs
+ return freq
-def _create_triangular_filterbank(
- all_freqs: np.array,
- f_pts: np.array,
-) -> np.array:
- """Create a triangular filter bank.
+def _create_triangular_filter_bank(fft_freqs: np.ndarray, filter_freqs: np.ndarray) -> np.ndarray:
+ """
+ Creates a triangular filter bank.
+ Adapted from *torchaudio* and *librosa*.
Args:
- all_freqs (`np.array` of shape (`nb_frequency_bins`, )):
- Discrete frequencies used when the STFT was computed.
- f_pts (`np.array`, of shape (`nb_mel_filters`, )):
- Coordinates of the middle points of the triangular filters to create.
+ fft_freqs (`np.ndarray` of shape `(num_frequency_bins,)`):
+ Discrete frequencies of the FFT bins in Hz.
+ filter_freqs (`np.ndarray` of shape `(num_mel_filters,)`):
+ Center frequencies of the triangular filters to create, in Hz.
Returns:
- fb (np.array):
- The filter bank of size (`nb_frequency_bins`, `nb_mel_filters`).
+ `np.ndarray` of shape `(num_frequency_bins, num_mel_filters)`
"""
- # Adapted from Librosa
- # calculate the difference between each filter mid point and each stft freq point in hertz
- f_diff = f_pts[1:] - f_pts[:-1] # (n_filter + 1)
- slopes = np.expand_dims(f_pts, 0) - np.expand_dims(all_freqs, 1) # (nb_frequency_bins, n_filter + 2)
- # create overlapping triangles
- zero = np.zeros(1)
- down_slopes = (-1.0 * slopes[:, :-2]) / f_diff[:-1] # (nb_frequency_bins, n_filter)
- up_slopes = slopes[:, 2:] / f_diff[1:] # (nb_frequency_bins, n_filter)
- fb = np.maximum(zero, np.minimum(down_slopes, up_slopes))
-
- return fb
-
-
-def get_mel_filter_banks(
- nb_frequency_bins: int,
- nb_mel_filters: int,
- frequency_min: float,
- frequency_max: float,
- sample_rate: int,
+ filter_diff = np.diff(filter_freqs)
+ slopes = np.expand_dims(filter_freqs, 0) - np.expand_dims(fft_freqs, 1)
+ down_slopes = -slopes[:, :-2] / filter_diff[:-1]
+ up_slopes = slopes[:, 2:] / filter_diff[1:]
+ return np.maximum(np.zeros(1), np.minimum(down_slopes, up_slopes))
+
+
+def mel_filter_bank(
+ num_frequency_bins: int,
+ num_mel_filters: int,
+ min_frequency: float,
+ max_frequency: float,
+ sampling_rate: int,
norm: Optional[str] = None,
mel_scale: str = "htk",
-) -> np.array:
+) -> np.ndarray:
"""
- Create a frequency bin conversion matrix used to obtain the Mel Spectrogram. This is called a *mel filter bank*,
- and various implementation exist, which differ in the number of filters, the shape of the filters, the way the
- filters are spaced, the bandwidth of the filters, and the manner in which the spectrum is warped. The goal of these
+ Creates a frequency bin conversion matrix used to obtain a mel spectrogram. This is called a *mel filter bank*, and
+ various implementation exist, which differ in the number of filters, the shape of the filters, the way the filters
+ are spaced, the bandwidth of the filters, and the manner in which the spectrum is warped. The goal of these
features is to approximate the non-linear human perception of the variation in pitch with respect to the frequency.
- This code is heavily inspired from the *torchaudio* implementation, see
- [here](https://pytorch.org/audio/stable/transforms.html) for more details.
-
-
- Tips:
- - Different banks of Mel filters were introduced in the litterature. The following variation are supported:
- - MFCC FB-20: introduced in 1980 by Davis and Mermelstein, it assumes a sampling frequency of 10 kHertz
- and a speech bandwidth of `[0, 4600]` Hertz
- - MFCC FB-24 HTK: from the Cambridge HMM Toolkit (HTK) (1995) uses a filter bank of 24 filters for a
- speech bandwidth `[0, 8000]` Hertz (sampling rate â„ 16 kHertz).
- - MFCC FB-40: from the Auditory Toolbox for MATLAB written by Slaney in 1998, assumes a sampling rate
- of 16 kHertz, and speech bandwidth [133, 6854] Hertz. This version also includes an area normalization.
- - HFCC-E FB-29 (Human Factor Cepstral Coefficients) of Skowronski and Harris (2004), assumes sampling
- rate of 12.5 kHertz and speech bandwidth [0, 6250] Hertz
- - The default parameters of `torchaudio`'s mel filterbanks implement the `"htk"` filers while `torchlibrosa`
- uses the `"slaney"` implementation.
+
+ Different banks of mel filters were introduced in the literature. The following variations are supported:
+
+ - MFCC FB-20: introduced in 1980 by Davis and Mermelstein, it assumes a sampling frequency of 10 kHz and a speech
+ bandwidth of `[0, 4600]` Hz.
+ - MFCC FB-24 HTK: from the Cambridge HMM Toolkit (HTK) (1995) uses a filter bank of 24 filters for a speech
+ bandwidth of `[0, 8000]` Hz. This assumes sampling rate â„ 16 kHz.
+ - MFCC FB-40: from the Auditory Toolbox for MATLAB written by Slaney in 1998, assumes a sampling rate of 16 kHz and
+ speech bandwidth of `[133, 6854]` Hz. This version also includes area normalization.
+ - HFCC-E FB-29 (Human Factor Cepstral Coefficients) of Skowronski and Harris (2004), assumes a sampling rate of
+ 12.5 kHz and speech bandwidth of `[0, 6250]` Hz.
+
+ This code is adapted from *torchaudio* and *librosa*. Note that the default parameters of torchaudio's
+ `melscale_fbanks` implement the `"htk"` filters while librosa uses the `"slaney"` implementation.
Args:
- nb_frequency_bins (`int`):
+ num_frequency_bins (`int`):
Number of frequencies used to compute the spectrogram (should be the same as in `stft`).
- nb_mel_filters (`int`):
- Number of Mel filers to generate.
- frequency_min (`float`):
- Minimum frequency of interest(Hertz).
- frequency_max (`float`):
- Maximum frequency of interest(Hertz).
- sample_rate (`int`):
+ num_mel_filters (`int`):
+ Number of mel filters to generate.
+ min_frequency (`float`):
+ Lowest frequency of interest in Hz.
+ max_frequency (`float`):
+ Highest frequency of interest in Hz. This should not exceed `sampling_rate / 2`.
+ sampling_rate (`int`):
Sample rate of the audio waveform.
norm (`str`, *optional*):
- If "slaney", divide the triangular Mel weights by the width of the mel band (area normalization).
+ If `"slaney"`, divide the triangular mel weights by the width of the mel band (area normalization).
mel_scale (`str`, *optional*, defaults to `"htk"`):
- Scale to use: `"htk"` or `"slaney"`.
+ The mel frequency scale to use, `"htk"` or `"slaney"`.
Returns:
- `np.ndarray`: Triangular filter banks (fb matrix) of shape (`nb_frequency_bins`, `nb_mel_filters`). This matrix
- is a projection matrix to go from a spectrogram to a Mel Spectrogram.
-
+ `np.ndarray` of shape (`num_frequency_bins`, `num_mel_filters`): Triangular filter bank matrix. This is a
+ projection matrix to go from a spectrogram to a mel spectrogram.
"""
-
if norm is not None and norm != "slaney":
raise ValueError('norm must be one of None or "slaney"')
- # freqency bins
- all_freqs = np.linspace(0, sample_rate // 2, nb_frequency_bins)
-
- # Compute mim and max frequencies in mel scale
- m_min = hertz_to_mel(frequency_min, mel_scale=mel_scale)
- m_max = hertz_to_mel(frequency_max, mel_scale=mel_scale)
+ # frequencies of FFT bins in Hz
+ fft_freqs = np.linspace(0, sampling_rate // 2, num_frequency_bins)
- # create the centers of the triangular mel filters.
- m_pts = np.linspace(m_min, m_max, nb_mel_filters + 2)
- f_pts = mel_to_hertz(m_pts, mel_scale=mel_scale)
+ # center points of the triangular mel filters
+ mel_min = hertz_to_mel(min_frequency, mel_scale=mel_scale)
+ mel_max = hertz_to_mel(max_frequency, mel_scale=mel_scale)
+ mel_freqs = np.linspace(mel_min, mel_max, num_mel_filters + 2)
+ filter_freqs = mel_to_hertz(mel_freqs, mel_scale=mel_scale)
- # create the filterbank
- filterbank = _create_triangular_filterbank(all_freqs, f_pts)
+ mel_filters = _create_triangular_filter_bank(fft_freqs, filter_freqs)
if norm is not None and norm == "slaney":
# Slaney-style mel is scaled to be approx constant energy per channel
- enorm = 2.0 / (f_pts[2 : nb_mel_filters + 2] - f_pts[:nb_mel_filters])
- filterbank *= np.expand_dims(enorm, 0)
+ enorm = 2.0 / (filter_freqs[2 : num_mel_filters + 2] - filter_freqs[:num_mel_filters])
+ mel_filters *= np.expand_dims(enorm, 0)
- if (filterbank.max(axis=0) == 0.0).any():
+ if (mel_filters.max(axis=0) == 0.0).any():
warnings.warn(
- "At least one mel filterbank has all zero values. "
- f"The value for `nb_mel_filters` ({nb_mel_filters}) may be set too high. "
- f"Or, the value for `nb_frequency_bins` ({nb_frequency_bins}) may be set too low."
+ "At least one mel filter has all zero values. "
+ f"The value for `num_mel_filters` ({num_mel_filters}) may be set too high. "
+ f"Or, the value for `num_frequency_bins` ({num_frequency_bins}) may be set too low."
+ )
+
+ return mel_filters
+
+
+def optimal_fft_length(window_length: int) -> int:
+ """
+ Finds the best FFT input size for a given `window_length`. This function takes a given window length and, if not
+ already a power of two, rounds it up to the next power or two.
+
+ The FFT algorithm works fastest when the length of the input is a power of two, which may be larger than the size
+ of the window or analysis frame. For example, if the window is 400 samples, using an FFT input size of 512 samples
+ is more optimal than an FFT size of 400 samples. Using a larger FFT size does not affect the detected frequencies,
+ it simply gives a higher frequency resolution (i.e. the frequency bins are smaller).
+ """
+ return 2 ** int(np.ceil(np.log2(window_length)))
+
+
+def window_function(
+ window_length: int,
+ name: str = "hann",
+ periodic: bool = True,
+ frame_length: Optional[int] = None,
+ center: bool = True,
+) -> np.ndarray:
+ """
+ Returns an array containing the specified window. This window is intended to be used with `stft`.
+
+ The following window types are supported:
+
+ - `"boxcar"`: a rectangular window
+ - `"hamming"`: the Hamming window
+ - `"hann"`: the Hann window
+
+ Args:
+ window_length (`int`):
+ The length of the window in samples.
+ name (`str`, *optional*, defaults to `"hann"`):
+ The name of the window function.
+ periodic (`bool`, *optional*, defaults to `True`):
+ Whether the window is periodic or symmetric.
+ frame_length (`int`, *optional*):
+ The length of the analysis frames in samples. Provide a value for `frame_length` if the window is smaller
+ than the frame length, so that it will be zero-padded.
+ center (`bool`, *optional*, defaults to `True`):
+ Whether to center the window inside the FFT buffer. Only used when `frame_length` is provided.
+
+ Returns:
+ `np.ndarray` of shape `(window_length,)` or `(frame_length,)` containing the window.
+ """
+ length = window_length + 1 if periodic else window_length
+
+ if name == "boxcar":
+ window = np.ones(length)
+ elif name in ["hamming", "hamming_window"]:
+ window = np.hamming(length)
+ elif name in ["hann", "hann_window"]:
+ window = np.hanning(length)
+ else:
+ raise ValueError(f"Unknown window function '{name}'")
+
+ if periodic:
+ window = window[:-1]
+
+ if frame_length is None:
+ return window
+
+ if window_length > frame_length:
+ raise ValueError(
+ f"Length of the window ({window_length}) may not be larger than frame_length ({frame_length})"
)
- return filterbank
+ padded_window = np.zeros(frame_length)
+ offset = (frame_length - window_length) // 2 if center else 0
+ padded_window[offset : offset + window_length] = window
+ return padded_window
+
+
+# TODO This method does not support batching yet as we are mainly focused on inference.
+def spectrogram(
+ waveform: np.ndarray,
+ window: np.ndarray,
+ frame_length: int,
+ hop_length: int,
+ fft_length: Optional[int] = None,
+ power: Optional[float] = 1.0,
+ center: bool = True,
+ pad_mode: str = "reflect",
+ onesided: bool = True,
+ preemphasis: Optional[float] = None,
+ mel_filters: Optional[np.ndarray] = None,
+ mel_floor: float = 1e-10,
+ log_mel: Optional[str] = None,
+ reference: float = 1.0,
+ min_value: float = 1e-10,
+ db_range: Optional[float] = None,
+ dtype: np.dtype = np.float32,
+) -> np.ndarray:
+ """
+ Calculates a spectrogram over one waveform using the Short-Time Fourier Transform.
+
+ This function can create the following kinds of spectrograms:
+
+ - amplitude spectrogram (`power = 1.0`)
+ - power spectrogram (`power = 2.0`)
+ - complex-valued spectrogram (`power = None`)
+ - log spectrogram (use `log_mel` argument)
+ - mel spectrogram (provide `mel_filters`)
+ - log-mel spectrogram (provide `mel_filters` and `log_mel`)
+
+ How this works:
+
+ 1. The input waveform is split into frames of size `frame_length` that are partially overlapping by `frame_length
+ - hop_length` samples.
+ 2. Each frame is multiplied by the window and placed into a buffer of size `fft_length`.
+ 3. The DFT is taken of each windowed frame.
+ 4. The results are stacked into a spectrogram.
+
+ We make a distinction between the following "blocks" of sample data, each of which may have a different lengths:
+
+ - The analysis frame. This is the size of the time slices that the input waveform is split into.
+ - The window. Each analysis frame is multiplied by the window to avoid spectral leakage.
+ - The FFT input buffer. The length of this determines how many frequency bins are in the spectrogram.
+
+ In this implementation, the window is assumed to be zero-padded to have the same size as the analysis frame. A
+ padded window can be obtained from `window_function()`. The FFT input buffer may be larger than the analysis frame,
+ typically the next power of two.
+
+ Note: This function is not optimized for speed yet. It should be mostly compatible with `librosa.stft` and
+ `torchaudio.functional.transforms.Spectrogram`, although it is more flexible due to the different ways spectrograms
+ can be constructed.
+
+ Args:
+ waveform (`np.ndarray` of shape `(length,)`):
+ The input waveform. This must be a single real-valued, mono waveform.
+ window (`np.ndarray` of shape `(frame_length,)`):
+ The windowing function to apply, including zero-padding if necessary. The actual window length may be
+ shorter than `frame_length`, but we're assuming the array has already been zero-padded.
+ frame_length (`int`):
+ The length of the analysis frames in samples. With librosa this is always equal to `fft_length` but we also
+ allow smaller sizes.
+ hop_length (`int`):
+ The stride between successive analysis frames in samples.
+ fft_length (`int`, *optional*):
+ The size of the FFT buffer in samples. This determines how many frequency bins the spectrogram will have.
+ For optimal speed, this should be a power of two. If `None`, uses `frame_length`.
+ power (`float`, *optional*, defaults to 1.0):
+ If 1.0, returns the amplitude spectrogram. If 2.0, returns the power spectrogram. If `None`, returns
+ complex numbers.
+ center (`bool`, *optional*, defaults to `True`):
+ Whether to pad the waveform so that frame `t` is centered around time `t * hop_length`. If `False`, frame
+ `t` will start at time `t * hop_length`.
+ pad_mode (`str`, *optional*, defaults to `"reflect"`):
+ Padding mode used when `center` is `True`. Possible values are: `"constant"` (pad with zeros), `"edge"`
+ (pad with edge values), `"reflect"` (pads with mirrored values).
+ onesided (`bool`, *optional*, defaults to `True`):
+ If True, only computes the positive frequencies and returns a spectrogram containing `fft_length // 2 + 1`
+ frequency bins. If False, also computes the negative frequencies and returns `fft_length` frequency bins.
+ preemphasis (`float`, *optional*)
+ Coefficient for a low-pass filter that applies pre-emphasis before the DFT.
+ mel_filters (`np.ndarray` of shape `(num_freq_bins, num_mel_filters)`, *optional*):
+ The mel filter bank. If supplied, applies a this filter bank to create a mel spectrogram.
+ mel_floor (`float`, *optional*, defaults to 1e-10):
+ Minimum value of mel frequency banks.
+ log_mel (`str`, *optional*):
+ How to convert the spectrogram to log scale. Possible options are: `None` (don't convert), `"log"` (take
+ the natural logarithm) `"log10"` (take the base-10 logarithm), `"dB"` (convert to decibels). Can only be
+ used when `power` is not `None`.
+ reference (`float`, *optional*, defaults to 1.0):
+ Sets the input spectrogram value that corresponds to 0 dB. For example, use `np.max(spectrogram)` to set
+ the loudest part to 0 dB. Must be greater than zero.
+ min_value (`float`, *optional*, defaults to `1e-10`):
+ The spectrogram will be clipped to this minimum value before conversion to decibels, to avoid taking
+ `log(0)`. For a power spectrogram, the default of `1e-10` corresponds to a minimum of -100 dB. For an
+ amplitude spectrogram, the value `1e-5` corresponds to -100 dB. Must be greater than zero.
+ db_range (`float`, *optional*):
+ Sets the maximum dynamic range in decibels. For example, if `db_range = 80`, the difference between the
+ peak value and the smallest value will never be more than 80 dB. Must be greater than zero.
+ dtype (`np.dtype`, *optional*, defaults to `np.float32`):
+ Data type of the spectrogram tensor. If `power` is None, this argument is ignored and the dtype will be
+ `np.complex64`.
+
+ Returns:
+ `nd.array` containing a spectrogram of shape `(num_frequency_bins, length)` for a regular spectrogram or shape
+ `(num_mel_filters, length)` for a mel spectrogram.
+ """
+ window_length = len(window)
+
+ if fft_length is None:
+ fft_length = frame_length
+
+ if frame_length > fft_length:
+ raise ValueError(f"frame_length ({frame_length}) may not be larger than fft_length ({fft_length})")
+ if window_length != frame_length:
+ raise ValueError(f"Length of the window ({window_length}) must equal frame_length ({frame_length})")
-def power_to_db(mel_spectrogram, top_db=None, a_min=1e-10, ref=1.0):
+ if hop_length <= 0:
+ raise ValueError("hop_length must be greater than zero")
+
+ if waveform.ndim != 1:
+ raise ValueError(f"Input waveform must have only one dimension, shape is {waveform.shape}")
+
+ if np.iscomplexobj(waveform):
+ raise ValueError("Complex-valued input waveforms are not currently supported")
+
+ # center pad the waveform
+ if center:
+ padding = [(int(frame_length // 2), int(frame_length // 2))]
+ waveform = np.pad(waveform, padding, mode=pad_mode)
+
+ # promote to float64, since np.fft uses float64 internally
+ waveform = waveform.astype(np.float64)
+ window = window.astype(np.float64)
+
+ # split waveform into frames of frame_length size
+ num_frames = int(1 + np.floor((waveform.size - frame_length) / hop_length))
+
+ num_frequency_bins = (fft_length // 2) + 1 if onesided else fft_length
+ spectrogram = np.empty((num_frames, num_frequency_bins), dtype=np.complex64)
+
+ # rfft is faster than fft
+ fft_func = np.fft.rfft if onesided else np.fft.fft
+ buffer = np.zeros(fft_length)
+
+ timestep = 0
+ for frame_idx in range(num_frames):
+ buffer[:frame_length] = waveform[timestep : timestep + frame_length]
+
+ if preemphasis is not None:
+ buffer[1:frame_length] -= preemphasis * buffer[: frame_length - 1]
+ buffer[0] *= 1 - preemphasis
+
+ buffer[:frame_length] *= window
+
+ spectrogram[frame_idx] = fft_func(buffer)
+ timestep += hop_length
+
+ # note: ** is much faster than np.power
+ if power is not None:
+ spectrogram = np.abs(spectrogram, dtype=np.float64) ** power
+
+ spectrogram = spectrogram.T
+
+ if mel_filters is not None:
+ spectrogram = np.maximum(mel_floor, np.dot(mel_filters.T, spectrogram))
+
+ if power is not None and log_mel is not None:
+ if log_mel == "log":
+ spectrogram = np.log(spectrogram)
+ elif log_mel == "log10":
+ spectrogram = np.log10(spectrogram)
+ elif log_mel == "dB":
+ if power == 1.0:
+ spectrogram = amplitude_to_db(spectrogram, reference, min_value, db_range)
+ elif power == 2.0:
+ spectrogram = power_to_db(spectrogram, reference, min_value, db_range)
+ else:
+ raise ValueError(f"Cannot use log_mel option '{log_mel}' with power {power}")
+ else:
+ raise ValueError(f"Unknown log_mel option: {log_mel}")
+
+ spectrogram = np.asarray(spectrogram, dtype)
+
+ return spectrogram
+
+
+def power_to_db(
+ spectrogram: np.ndarray,
+ reference: float = 1.0,
+ min_value: float = 1e-10,
+ db_range: Optional[float] = None,
+) -> np.ndarray:
+ """
+ Converts a power spectrogram to the decibel scale. This computes `10 * log10(spectrogram / reference)`, using basic
+ logarithm properties for numerical stability.
+
+ The motivation behind applying the log function on the (mel) spectrogram is that humans do not hear loudness on a
+ linear scale. Generally to double the perceived volume of a sound we need to put 8 times as much energy into it.
+ This means that large variations in energy may not sound all that different if the sound is loud to begin with.
+ This compression operation makes the (mel) spectrogram features match more closely what humans actually hear.
+
+ Based on the implementation of `librosa.power_to_db`.
+
+ Args:
+ spectrogram (`np.ndarray`):
+ The input power (mel) spectrogram. Note that a power spectrogram has the amplitudes squared!
+ reference (`float`, *optional*, defaults to 1.0):
+ Sets the input spectrogram value that corresponds to 0 dB. For example, use `np.max(spectrogram)` to set
+ the loudest part to 0 dB. Must be greater than zero.
+ min_value (`float`, *optional*, defaults to `1e-10`):
+ The spectrogram will be clipped to this minimum value before conversion to decibels, to avoid taking
+ `log(0)`. The default of `1e-10` corresponds to a minimum of -100 dB. Must be greater than zero.
+ db_range (`float`, *optional*):
+ Sets the maximum dynamic range in decibels. For example, if `db_range = 80`, the difference between the
+ peak value and the smallest value will never be more than 80 dB. Must be greater than zero.
+
+ Returns:
+ `np.ndarray`: the spectrogram in decibels
"""
- Convert a mel spectrogram from power to db scale, this function is the numpy implementation of librosa.power_to_lb.
- It computes `10 * log10(mel_spectrogram / ref)`, using basic log properties for stability.
+ if reference <= 0.0:
+ raise ValueError("reference must be greater than zero")
+ if min_value <= 0.0:
+ raise ValueError("min_value must be greater than zero")
- Tips:
- - The motivation behind applying the log function on the mel spectrogram is that humans do not hear loudness on
- a
- linear scale. Generally to double the percieved volume of a sound we need to put 8 times as much energy into
- it.
- - This means that large variations in energy may not sound all that different if the sound is loud to begin
- with. This compression operation makes the mel features match more closely what humans actually hear.
+ reference = max(min_value, reference)
+
+ spectrogram = np.clip(spectrogram, a_min=min_value, a_max=None)
+ spectrogram = 10.0 * (np.log10(spectrogram) - np.log10(reference))
+
+ if db_range is not None:
+ if db_range <= 0.0:
+ raise ValueError("db_range must be greater than zero")
+ spectrogram = np.clip(spectrogram, a_min=spectrogram.max() - db_range, a_max=None)
+
+ return spectrogram
+
+
+def amplitude_to_db(
+ spectrogram: np.ndarray,
+ reference: float = 1.0,
+ min_value: float = 1e-5,
+ db_range: Optional[float] = None,
+) -> np.ndarray:
+ """
+ Converts an amplitude spectrogram to the decibel scale. This computes `20 * log10(spectrogram / reference)`, using
+ basic logarithm properties for numerical stability.
+
+ The motivation behind applying the log function on the (mel) spectrogram is that humans do not hear loudness on a
+ linear scale. Generally to double the perceived volume of a sound we need to put 8 times as much energy into it.
+ This means that large variations in energy may not sound all that different if the sound is loud to begin with.
+ This compression operation makes the (mel) spectrogram features match more closely what humans actually hear.
Args:
- mel_spectrogram (`np.array`):
- Input mel spectrogram.
- top_db (`int`, *optional*):
- The maximum decibel value.
- a_min (`int`, *optional*, default to 1e-10):
- Minimum value to use when cliping the mel spectrogram.
- ref (`float`, *optional*, default to 1.0):
- Maximum reference value used to scale the mel_spectrogram.
+ spectrogram (`np.ndarray`):
+ The input amplitude (mel) spectrogram.
+ reference (`float`, *optional*, defaults to 1.0):
+ Sets the input spectrogram value that corresponds to 0 dB. For example, use `np.max(spectrogram)` to set
+ the loudest part to 0 dB. Must be greater than zero.
+ min_value (`float`, *optional*, defaults to `1e-5`):
+ The spectrogram will be clipped to this minimum value before conversion to decibels, to avoid taking
+ `log(0)`. The default of `1e-5` corresponds to a minimum of -100 dB. Must be greater than zero.
+ db_range (`float`, *optional*):
+ Sets the maximum dynamic range in decibels. For example, if `db_range = 80`, the difference between the
+ peak value and the smallest value will never be more than 80 dB. Must be greater than zero.
+ Returns:
+ `np.ndarray`: the spectrogram in decibels
"""
- log_spec = 10 * np.log10(np.clip(mel_spectrogram, a_min=a_min, a_max=None))
- log_spec -= 10.0 * np.log10(np.maximum(a_min, ref))
- if top_db is not None:
- if top_db < 0:
- raise ValueError("top_db must be non-negative")
- log_spec = np.clip(log_spec, min=np.maximum(log_spec) - top_db, max=np.inf)
- return log_spec
+ if reference <= 0.0:
+ raise ValueError("reference must be greater than zero")
+ if min_value <= 0.0:
+ raise ValueError("min_value must be greater than zero")
+
+ reference = max(min_value, reference)
+
+ spectrogram = np.clip(spectrogram, a_min=min_value, a_max=None)
+ spectrogram = 20.0 * (np.log10(spectrogram) - np.log10(reference))
+
+ if db_range is not None:
+ if db_range <= 0.0:
+ raise ValueError("db_range must be greater than zero")
+ spectrogram = np.clip(spectrogram, a_min=spectrogram.max() - db_range, a_max=None)
+
+ return spectrogram
+
+
+### deprecated functions below this line ###
+
+
+def get_mel_filter_banks(
+ nb_frequency_bins: int,
+ nb_mel_filters: int,
+ frequency_min: float,
+ frequency_max: float,
+ sample_rate: int,
+ norm: Optional[str] = None,
+ mel_scale: str = "htk",
+) -> np.array:
+ warnings.warn(
+ "The function `get_mel_filter_banks` is deprecated and will be removed in version 4.31.0 of Transformers",
+ FutureWarning,
+ )
+ return mel_filter_bank(
+ num_frequency_bins=nb_frequency_bins,
+ num_mel_filters=nb_mel_filters,
+ min_frequency=frequency_min,
+ max_frequency=frequency_max,
+ sampling_rate=sample_rate,
+ norm=norm,
+ mel_scale=mel_scale,
+ )
-# TODO @ArthurZucker: This method does not support batching yet as we are mainly focus on inference.
def fram_wave(waveform: np.array, hop_length: int = 160, fft_window_size: int = 400, center: bool = True):
"""
In order to compute the short time fourier transform, the waveform needs to be split in overlapping windowed
@@ -270,6 +603,10 @@ def fram_wave(waveform: np.array, hop_length: int = 160, fft_window_size: int =
framed_waveform (`np.array` of shape `(waveform.shape // hop_length , fft_window_size)`):
The framed waveforms that can be fed to `np.fft`.
"""
+ warnings.warn(
+ "The function `fram_wave` is deprecated and will be removed in version 4.31.0 of Transformers",
+ FutureWarning,
+ )
frames = []
for i in range(0, waveform.shape[0] + 1, hop_length):
if center:
@@ -298,9 +635,6 @@ def fram_wave(waveform: np.array, hop_length: int = 160, fft_window_size: int =
return frames
-# TODO @ArthurZucker: This method does not support batching yet as we are mainly focus on inference.
-
-
def stft(frames: np.array, windowing_function: np.array, fft_window_size: int = None):
"""
Calculates the complex Short-Time Fourier Transform (STFT) of the given framed signal. Should give the same results
@@ -337,6 +671,10 @@ def stft(frames: np.array, windowing_function: np.array, fft_window_size: int =
spectrogram (`np.ndarray`):
A spectrogram of shape `(num_frames, nb_frequency_bins)` obtained using the STFT algorithm
"""
+ warnings.warn(
+ "The function `stft` is deprecated and will be removed in version 4.31.0 of Transformers",
+ FutureWarning,
+ )
frame_size = frames.shape[1]
if fft_window_size is None:
@@ -355,5 +693,5 @@ def stft(frames: np.array, windowing_function: np.array, fft_window_size: int =
np.multiply(frame, windowing_function, out=fft_signal[:frame_size])
else:
fft_signal[:frame_size] = frame
- spectrogram[f] = fft(fft_signal, axis=0)[:nb_frequency_bins]
+ spectrogram[f] = np.fft.fft(fft_signal, axis=0)[:nb_frequency_bins]
return spectrogram.T
diff --git a/src/transformers/benchmark/benchmark_args_utils.py b/src/transformers/benchmark/benchmark_args_utils.py
index d9233906d281..48fcb311b437 100644
--- a/src/transformers/benchmark/benchmark_args_utils.py
+++ b/src/transformers/benchmark/benchmark_args_utils.py
@@ -147,11 +147,12 @@ def to_json_string(self):
return json.dumps(dataclasses.asdict(self), indent=2)
@property
- def model_names(self):
- assert len(self.models) > 0, (
- "Please make sure you provide at least one model name / model identifier, *e.g.* `--models"
- " bert-base-cased` or `args.models = ['bert-base-cased']."
- )
+ def model_names(self) -> List[str]:
+ if len(self.models) <= 0:
+ raise ValueError(
+ "Please make sure you provide at least one model name / model identifier, *e.g.* `--models"
+ " bert-base-cased` or `args.models = ['bert-base-cased']."
+ )
return self.models
@property
diff --git a/src/transformers/benchmark/benchmark_tf.py b/src/transformers/benchmark/benchmark_tf.py
index 126172ffbd30..c813591be0be 100644
--- a/src/transformers/benchmark/benchmark_tf.py
+++ b/src/transformers/benchmark/benchmark_tf.py
@@ -60,9 +60,10 @@ def run_in_graph_mode(*args, **kwargs):
return func(*args, **kwargs)
if do_eager_mode is True:
- assert (
- use_xla is False
- ), "Cannot run model in XLA, if `args.eager_mode` is set to `True`. Please set `args.eager_mode=False`."
+ if use_xla is not False:
+ raise ValueError(
+ "Cannot run model in XLA, if `args.eager_mode` is set to `True`. Please set `args.eager_mode=False`."
+ )
return run_in_eager_mode
else:
return run_in_graph_mode
@@ -88,13 +89,15 @@ def framework_version(self):
def _inference_speed(self, model_name: str, batch_size: int, sequence_length: int) -> float:
# initialize GPU on separate process
strategy = self.args.strategy
- assert strategy is not None, "A device strategy has to be initialized before using TensorFlow."
+ if strategy is None:
+ raise ValueError("A device strategy has to be initialized before using TensorFlow.")
_inference = self._prepare_inference_func(model_name, batch_size, sequence_length)
return self._measure_speed(_inference)
def _train_speed(self, model_name: str, batch_size: int, sequence_length: int) -> float:
strategy = self.args.strategy
- assert strategy is not None, "A device strategy has to be initialized before using TensorFlow."
+ if strategy is None:
+ raise ValueError("A device strategy has to be initialized before using TensorFlow.")
_train = self._prepare_train_func(model_name, batch_size, sequence_length)
return self._measure_speed(_train)
@@ -105,7 +108,8 @@ def _inference_memory(
if self.args.is_gpu:
tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx], True)
strategy = self.args.strategy
- assert strategy is not None, "A device strategy has to be initialized before using TensorFlow."
+ if strategy is None:
+ raise ValueError("A device strategy has to be initialized before using TensorFlow.")
_inference = self._prepare_inference_func(model_name, batch_size, sequence_length)
return self._measure_memory(_inference)
@@ -115,7 +119,8 @@ def _train_memory(
if self.args.is_gpu:
tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx], True)
strategy = self.args.strategy
- assert strategy is not None, "A device strategy has to be initialized before using TensorFlow."
+ if strategy is None:
+ raise ValueError("A device strategy has to be initialized before using TensorFlow.")
_train = self._prepare_train_func(model_name, batch_size, sequence_length)
return self._measure_memory(_train)
@@ -164,9 +169,8 @@ def encoder_forward():
def _prepare_train_func(self, model_name: str, batch_size: int, sequence_length: int) -> Callable[[], None]:
config = self.config_dict[model_name]
- assert (
- self.args.eager_mode is False
- ), "Training cannot be done in eager mode. Please make sure that `args.eager_mode = False`."
+ if self.args.eager_mode is not False:
+ raise ValueError("Training cannot be done in eager mode. Please make sure that `args.eager_mode = False`.")
if self.args.fp16:
raise NotImplementedError("Mixed precision is currently not supported.")
@@ -240,10 +244,11 @@ def _measure_memory(self, func: Callable[[], None]) -> [Memory, MemorySummary]:
with self.args.strategy.scope():
try:
if self.args.trace_memory_line_by_line:
- assert self.args.eager_mode, (
- "`args.eager_mode` is set to `False`. Make sure to run model in eager mode to measure memory"
- " consumption line by line."
- )
+ if not self.args.eager_mode:
+ raise ValueError(
+ "`args.eager_mode` is set to `False`. Make sure to run model in eager mode to measure memory"
+ " consumption line by line."
+ )
trace = start_memory_tracing("transformers")
if self.args.is_tpu:
diff --git a/src/transformers/benchmark/benchmark_utils.py b/src/transformers/benchmark/benchmark_utils.py
index b7008a7ab755..a71b1fb65a23 100644
--- a/src/transformers/benchmark/benchmark_utils.py
+++ b/src/transformers/benchmark/benchmark_utils.py
@@ -890,7 +890,8 @@ def save_to_csv(self, result_dict, filename):
return
self.print_fn("Saving results to csv.")
with open(filename, mode="w") as csv_file:
- assert len(self.args.model_names) > 0, f"At least 1 model should be defined, but got {self.model_names}"
+ if len(self.args.model_names) <= 0:
+ raise ValueError(f"At least 1 model should be defined, but got {self.model_names}")
fieldnames = ["model", "batch_size", "sequence_length"]
writer = csv.DictWriter(csv_file, fieldnames=fieldnames + ["result"])
diff --git a/src/transformers/commands/add_new_model.py b/src/transformers/commands/add_new_model.py
index 85d053a14873..87949827d9f8 100644
--- a/src/transformers/commands/add_new_model.py
+++ b/src/transformers/commands/add_new_model.py
@@ -183,8 +183,8 @@ def remove_copy_lines(path):
os.remove(f"{directory}/test_modeling_flax_{lowercase_model_name}.py")
shutil.move(
- f"{directory}/{lowercase_model_name}.mdx",
- f"{path_to_transformer_root}/docs/source/en/model_doc/{lowercase_model_name}.mdx",
+ f"{directory}/{lowercase_model_name}.md",
+ f"{path_to_transformer_root}/docs/source/en/model_doc/{lowercase_model_name}.md",
)
shutil.move(
diff --git a/src/transformers/commands/add_new_model_like.py b/src/transformers/commands/add_new_model_like.py
index 91ce8a143c59..df86a22799a5 100644
--- a/src/transformers/commands/add_new_model_like.py
+++ b/src/transformers/commands/add_new_model_like.py
@@ -23,6 +23,8 @@
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Pattern, Tuple, Union
+import yaml
+
from ..models import auto as auto_module
from ..models.auto.configuration_auto import model_type_to_module_name
from ..utils import is_flax_available, is_tf_available, is_torch_available, logging
@@ -646,7 +648,7 @@ def get_model_files(model_type: str, frameworks: Optional[List[str]] = None) ->
model_files = list(model_module.glob("*.py"))
model_files = filter_framework_files(model_files, frameworks=frameworks)
- doc_file = REPO_PATH / "docs" / "source" / "en" / "model_doc" / f"{model_type}.mdx"
+ doc_file = REPO_PATH / "docs" / "source" / "en" / "model_doc" / f"{model_type}.md"
# Basic pattern for test files
test_files = [
@@ -1185,7 +1187,7 @@ def duplicate_doc_file(
old_model_patterns (`ModelPatterns`): The patterns for the old model.
new_model_patterns (`ModelPatterns`): The patterns for the new model.
dest_file (`str` or `os.PathLike`, *optional*): Path to the new doc file.
- Will default to the a file named `{new_model_patterns.model_type}.mdx` in the same folder as `module_file`.
+ Will default to the a file named `{new_model_patterns.model_type}.md` in the same folder as `module_file`.
frameworks (`List[str]`, *optional*):
If passed, will only keep the model classes corresponding to this list of frameworks in the new doc file.
"""
@@ -1196,7 +1198,7 @@ def duplicate_doc_file(
if frameworks is None:
frameworks = get_default_frameworks()
if dest_file is None:
- dest_file = Path(doc_file).parent / f"{new_model_patterns.model_type}.mdx"
+ dest_file = Path(doc_file).parent / f"{new_model_patterns.model_type}.md"
# Parse the doc file in blocks. One block per section/header
lines = content.split("\n")
@@ -1268,6 +1270,56 @@ def duplicate_doc_file(
f.write("\n".join(new_blocks))
+def insert_model_in_doc_toc(old_model_patterns, new_model_patterns):
+ """
+ Insert the new model in the doc TOC, in the same section as the old model.
+
+ Args:
+ old_model_patterns (`ModelPatterns`): The patterns for the old model.
+ new_model_patterns (`ModelPatterns`): The patterns for the new model.
+ """
+ toc_file = REPO_PATH / "docs" / "source" / "en" / "_toctree.yml"
+ with open(toc_file, "r", encoding="utf8") as f:
+ content = yaml.safe_load(f)
+
+ # Get to the model API doc
+ api_idx = 0
+ while content[api_idx]["title"] != "API":
+ api_idx += 1
+ api_doc = content[api_idx]["sections"]
+
+ model_idx = 0
+ while api_doc[model_idx]["title"] != "Models":
+ model_idx += 1
+ model_doc = api_doc[model_idx]["sections"]
+
+ # Find the base model in the Toc
+ old_model_type = old_model_patterns.model_type
+ section_idx = 0
+ while section_idx < len(model_doc):
+ sections = [entry["local"] for entry in model_doc[section_idx]["sections"]]
+ if f"model_doc/{old_model_type}" in sections:
+ break
+
+ section_idx += 1
+
+ if section_idx == len(model_doc):
+ old_model = old_model_patterns.model_name
+ new_model = new_model_patterns.model_name
+ print(f"Did not find {old_model} in the table of content, so you will need to add {new_model} manually.")
+ return
+
+ # Add the new model in the same toc
+ toc_entry = {"local": f"model_doc/{new_model_patterns.model_type}", "title": new_model_patterns.model_name}
+ model_doc[section_idx]["sections"].append(toc_entry)
+ model_doc[section_idx]["sections"] = sorted(model_doc[section_idx]["sections"], key=lambda s: s["title"].lower())
+ api_doc[model_idx]["sections"] = model_doc
+ content[api_idx]["sections"] = api_doc
+
+ with open(toc_file, "w", encoding="utf-8") as f:
+ f.write(yaml.dump(content, allow_unicode=True))
+
+
def create_new_model_like(
model_type: str,
new_model_patterns: ModelPatterns,
@@ -1405,8 +1457,9 @@ def disable_fx_test(filename: Path) -> bool:
add_model_to_auto_classes(old_model_patterns, new_model_patterns, model_classes)
# 5. Add doc file
- doc_file = REPO_PATH / "docs" / "source" / "en" / "model_doc" / f"{old_model_patterns.model_type}.mdx"
+ doc_file = REPO_PATH / "docs" / "source" / "en" / "model_doc" / f"{old_model_patterns.model_type}.md"
duplicate_doc_file(doc_file, old_model_patterns, new_model_patterns, frameworks=frameworks)
+ insert_model_in_doc_toc(old_model_patterns, new_model_patterns)
# 6. Warn the user for duplicate patterns
if old_model_patterns.model_type == old_model_patterns.checkpoint:
diff --git a/src/transformers/commands/download.py b/src/transformers/commands/download.py
index 3c224555dfd5..8af3c6397b44 100644
--- a/src/transformers/commands/download.py
+++ b/src/transformers/commands/download.py
@@ -18,7 +18,7 @@
def download_command_factory(args):
- return DownloadCommand(args.model, args.cache_dir, args.force)
+ return DownloadCommand(args.model, args.cache_dir, args.force, args.trust_remote_code)
class DownloadCommand(BaseTransformersCLICommand):
@@ -31,16 +31,26 @@ def register_subcommand(parser: ArgumentParser):
download_parser.add_argument(
"--force", action="store_true", help="Force the model to be download even if already in cache-dir"
)
+ download_parser.add_argument(
+ "--trust-remote-code",
+ action="store_true",
+ help="Whether or not to allow for custom models defined on the Hub in their own modeling files. Use only if you've reviewed the code as it will execute on your local machine",
+ )
download_parser.add_argument("model", type=str, help="Name of the model to download")
download_parser.set_defaults(func=download_command_factory)
- def __init__(self, model: str, cache: str, force: bool):
+ def __init__(self, model: str, cache: str, force: bool, trust_remote_code: bool):
self._model = model
self._cache = cache
self._force = force
+ self._trust_remote_code = trust_remote_code
def run(self):
from ..models.auto import AutoModel, AutoTokenizer
- AutoModel.from_pretrained(self._model, cache_dir=self._cache, force_download=self._force)
- AutoTokenizer.from_pretrained(self._model, cache_dir=self._cache, force_download=self._force)
+ AutoModel.from_pretrained(
+ self._model, cache_dir=self._cache, force_download=self._force, trust_remote_code=self._trust_remote_code
+ )
+ AutoTokenizer.from_pretrained(
+ self._model, cache_dir=self._cache, force_download=self._force, trust_remote_code=self._trust_remote_code
+ )
diff --git a/src/transformers/commands/env.py b/src/transformers/commands/env.py
index aa0dccb579cc..8567bbcf5b61 100644
--- a/src/transformers/commands/env.py
+++ b/src/transformers/commands/env.py
@@ -13,13 +13,20 @@
# limitations under the License.
import importlib.util
+import os
import platform
from argparse import ArgumentParser
import huggingface_hub
from .. import __version__ as version
-from ..utils import is_flax_available, is_safetensors_available, is_tf_available, is_torch_available
+from ..utils import (
+ is_accelerate_available,
+ is_flax_available,
+ is_safetensors_available,
+ is_tf_available,
+ is_torch_available,
+)
from . import BaseTransformersCLICommand
@@ -27,11 +34,24 @@ def info_command_factory(_):
return EnvironmentCommand()
+def download_command_factory(args):
+ return EnvironmentCommand(args.accelerate_config_file)
+
+
class EnvironmentCommand(BaseTransformersCLICommand):
@staticmethod
def register_subcommand(parser: ArgumentParser):
download_parser = parser.add_parser("env")
download_parser.set_defaults(func=info_command_factory)
+ download_parser.add_argument(
+ "--accelerate-config_file",
+ default=None,
+ help="The accelerate config file to use for the default values in the launching script.",
+ )
+ download_parser.set_defaults(func=download_command_factory)
+
+ def __init__(self, accelerate_config_file, *args) -> None:
+ self._accelerate_config_file = accelerate_config_file
def run(self):
safetensors_version = "not installed"
@@ -44,6 +64,23 @@ def run(self):
safetensors_version = f"{safetensors.__version__} but is ignored because of PyTorch version too old."
+ accelerate_version = "not installed"
+ accelerate_config = accelerate_config_str = "not found"
+ if is_accelerate_available():
+ import accelerate
+ from accelerate.commands.config import default_config_file, load_config_from_file
+
+ accelerate_version = accelerate.__version__
+ # Get the default from the config file.
+ if self._accelerate_config_file is not None or os.path.isfile(default_config_file):
+ accelerate_config = load_config_from_file(self._accelerate_config_file).to_dict()
+
+ accelerate_config_str = (
+ "\n".join([f"\t- {prop}: {val}" for prop, val in accelerate_config.items()])
+ if isinstance(accelerate_config, dict)
+ else f"\t{accelerate_config}"
+ )
+
pt_version = "not installed"
pt_cuda_available = "NA"
if is_torch_available():
@@ -85,6 +122,8 @@ def run(self):
"Python version": platform.python_version(),
"Huggingface_hub version": huggingface_hub.__version__,
"Safetensors version": f"{safetensors_version}",
+ "Accelerate version": f"{accelerate_version}",
+ "Accelerate config": f"{accelerate_config_str}",
"PyTorch version (GPU?)": f"{pt_version} ({pt_cuda_available})",
"Tensorflow version (GPU?)": f"{tf_version} ({tf_cuda_available})",
"Flax version (CPU?/GPU?/TPU?)": f"{flax_version} ({jax_backend})",
diff --git a/src/transformers/configuration_utils.py b/src/transformers/configuration_utils.py
index 6f670a5a509e..00f9b5610e6b 100755
--- a/src/transformers/configuration_utils.py
+++ b/src/transformers/configuration_utils.py
@@ -119,7 +119,7 @@ class PretrainedConfig(PushToHubMixin):
max_length (`int`, *optional*, defaults to 20):
Maximum length that will be used by default in the `generate` method of the model.
- min_length (`int`, *optional*, defaults to 10):
+ min_length (`int`, *optional*, defaults to 0):
Minimum length that will be used by default in the `generate` method of the model.
do_sample (`bool`, *optional*, defaults to `False`):
Flag that will be used by default in the `generate` method of the model. Whether or not to use sampling ;
@@ -136,7 +136,7 @@ class PretrainedConfig(PushToHubMixin):
diversity_penalty (`float`, *optional*, defaults to 0.0):
Value to control diversity for group beam search. that will be used by default in the `generate` method of
the model. 0 means no diversity penalty. The higher the penalty, the more diverse are the outputs.
- temperature (`float`, *optional*, defaults to 1):
+ temperature (`float`, *optional*, defaults to 1.0):
The value used to module the next token probabilities that will be used by default in the `generate` method
of the model. Must be strictly positive.
top_k (`int`, *optional*, defaults to 50):
@@ -432,9 +432,11 @@ def save_pretrained(self, save_directory: Union[str, os.PathLike], push_to_hub:
Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the
repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
namespace).
- kwargs:
+ kwargs (`Dict[str, Any]`, *optional*):
Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
"""
+ self._set_token_in_kwargs(kwargs)
+
if os.path.isfile(save_directory):
raise AssertionError(f"Provided path ({save_directory}) should be a directory, not a file")
@@ -463,11 +465,46 @@ def save_pretrained(self, save_directory: Union[str, os.PathLike], push_to_hub:
repo_id,
files_timestamps,
commit_message=commit_message,
- token=kwargs.get("use_auth_token"),
+ token=kwargs.get("token"),
)
+ @staticmethod
+ def _set_token_in_kwargs(kwargs, token=None):
+ """Temporary method to deal with `token` and `use_auth_token`.
+
+ This method is to avoid apply the same changes in all model config classes that overwrite `from_pretrained`.
+
+ Need to clean up `use_auth_token` in a follow PR.
+ """
+ # Some model config classes like CLIP define their own `from_pretrained` without the new argument `token` yet.
+ if token is None:
+ token = kwargs.pop("token", None)
+ use_auth_token = kwargs.pop("use_auth_token", None)
+
+ if use_auth_token is not None:
+ warnings.warn(
+ "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers.", FutureWarning
+ )
+ if token is not None:
+ raise ValueError(
+ "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
+ )
+ token = use_auth_token
+
+ if token is not None:
+ kwargs["token"] = token
+
@classmethod
- def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
+ def from_pretrained(
+ cls,
+ pretrained_model_name_or_path: Union[str, os.PathLike],
+ cache_dir: Optional[Union[str, os.PathLike]] = None,
+ force_download: bool = False,
+ local_files_only: bool = False,
+ token: Optional[Union[str, bool]] = None,
+ revision: str = "main",
+ **kwargs,
+ ) -> "PretrainedConfig":
r"""
Instantiate a [`PretrainedConfig`] (or a derived class) from a pretrained model configuration.
@@ -493,7 +530,7 @@ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike],
proxies (`Dict[str, str]`, *optional*):
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
- use_auth_token (`str` or `bool`, *optional*):
+ token (`str` or `bool`, *optional*):
The token to use as HTTP bearer authorization for remote files. If `True`, or not specified, will use
the token generated when running `huggingface-cli login` (stored in `~/.huggingface`).
revision (`str`, *optional*, defaults to `"main"`):
@@ -544,6 +581,13 @@ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike],
assert config.output_attentions == True
assert unused_kwargs == {"foo": False}
```"""
+ kwargs["cache_dir"] = cache_dir
+ kwargs["force_download"] = force_download
+ kwargs["local_files_only"] = local_files_only
+ kwargs["revision"] = revision
+
+ cls._set_token_in_kwargs(kwargs, token)
+
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
logger.warning(
@@ -569,6 +613,8 @@ def get_config_dict(
`Tuple[Dict, Dict]`: The dictionary(ies) that will be used to instantiate the configuration object.
"""
+ cls._set_token_in_kwargs(kwargs)
+
original_kwargs = copy.deepcopy(kwargs)
# Get config dict associated with the base config file
config_dict, kwargs = cls._get_config_dict(pretrained_model_name_or_path, **kwargs)
@@ -592,7 +638,7 @@ def _get_config_dict(
force_download = kwargs.pop("force_download", False)
resume_download = kwargs.pop("resume_download", False)
proxies = kwargs.pop("proxies", None)
- use_auth_token = kwargs.pop("use_auth_token", None)
+ token = kwargs.pop("token", None)
local_files_only = kwargs.pop("local_files_only", False)
revision = kwargs.pop("revision", None)
trust_remote_code = kwargs.pop("trust_remote_code", None)
@@ -634,7 +680,7 @@ def _get_config_dict(
proxies=proxies,
resume_download=resume_download,
local_files_only=local_files_only,
- use_auth_token=use_auth_token,
+ token=token,
user_agent=user_agent,
revision=revision,
subfolder=subfolder,
@@ -716,6 +762,10 @@ def from_dict(cls, config_dict: Dict[str, Any], **kwargs) -> "PretrainedConfig":
to_remove = []
for key, value in kwargs.items():
if hasattr(config, key):
+ current_attr = getattr(config, key)
+ # To authorize passing a custom subconfig as kwarg in models that have nested configs.
+ if isinstance(current_attr, PretrainedConfig) and isinstance(value, dict):
+ value = current_attr.__class__(**value)
setattr(config, key, value)
if key != "torch_dtype":
to_remove.append(key)
@@ -777,6 +827,18 @@ def to_diff_dict(self) -> Dict[str, Any]:
# only serialize values that differ from the default config
for key, value in config_dict.items():
if (
+ isinstance(getattr(self, key, None), PretrainedConfig)
+ and key in class_config_dict
+ and isinstance(class_config_dict[key], dict)
+ ):
+ # For nested configs we need to clean the diff recursively
+ diff = recursive_diff_dict(value, class_config_dict[key], config_obj=getattr(self, key, None))
+ if "model_type" in value:
+ # Needs to be set even if it's not in the diff
+ diff["model_type"] = value["model_type"]
+ if len(diff) > 0:
+ serializable_config_dict[key] = diff
+ elif (
key not in default_config_dict
or key == "transformers_version"
or value != default_config_dict[key]
@@ -784,6 +846,13 @@ def to_diff_dict(self) -> Dict[str, Any]:
):
serializable_config_dict[key] = value
+ if hasattr(self, "quantization_config"):
+ serializable_config_dict["quantization_config"] = (
+ self.quantization_config.to_dict()
+ if not isinstance(self.quantization_config, dict)
+ else self.quantization_config
+ )
+
self.dict_torch_dtype_to_str(serializable_config_dict)
return serializable_config_dict
@@ -806,6 +875,14 @@ def to_dict(self) -> Dict[str, Any]:
# Transformers version when serializing the model
output["transformers_version"] = __version__
+ for key, value in output.items():
+ # Deal with nested configs like CLIP
+ if isinstance(value, PretrainedConfig):
+ value = value.to_dict()
+ del value["transformers_version"]
+
+ output[key] = value
+
if hasattr(self, "quantization_config"):
output["quantization_config"] = (
self.quantization_config.to_dict()
@@ -967,6 +1044,24 @@ def get_configuration_file(configuration_files: List[str]) -> str:
return configuration_file
+def recursive_diff_dict(dict_a, dict_b, config_obj=None):
+ """
+ Helper function to recursively take the diff between two nested dictionaries. The resulting diff only contains the
+ values from `dict_a` that are different from values in `dict_b`.
+ """
+ diff = {}
+ default = config_obj.__class__().to_dict() if config_obj is not None else {}
+ for key, value in dict_a.items():
+ obj_value = getattr(config_obj, str(key), None)
+ if isinstance(obj_value, PretrainedConfig) and key in dict_b and isinstance(dict_b[key], dict):
+ diff_value = recursive_diff_dict(value, dict_b[key], config_obj=obj_value)
+ if len(diff_value) > 0:
+ diff[key] = diff_value
+ elif key not in dict_b or value != dict_b[key] or key not in default or value != default[key]:
+ diff[key] = value
+ return diff
+
+
PretrainedConfig.push_to_hub = copy_func(PretrainedConfig.push_to_hub)
if PretrainedConfig.push_to_hub.__doc__ is not None:
PretrainedConfig.push_to_hub.__doc__ = PretrainedConfig.push_to_hub.__doc__.format(
diff --git a/src/transformers/convert_slow_tokenizer.py b/src/transformers/convert_slow_tokenizer.py
index 195d09ecd891..f4074664f693 100644
--- a/src/transformers/convert_slow_tokenizer.py
+++ b/src/transformers/convert_slow_tokenizer.py
@@ -22,10 +22,22 @@
import warnings
from typing import Dict, List, Tuple
+from packaging import version
from tokenizers import AddedToken, Regex, Tokenizer, decoders, normalizers, pre_tokenizers, processors
from tokenizers.models import BPE, Unigram, WordPiece
-from .utils import requires_backends
+from .utils import is_protobuf_available, requires_backends
+
+
+def import_protobuf():
+ if is_protobuf_available():
+ import google.protobuf
+
+ if version.parse(google.protobuf.__version__) < version.parse("4.0.0"):
+ from transformers.utils import sentencepiece_model_pb2
+ else:
+ from transformers.utils import sentencepiece_model_pb2_new as sentencepiece_model_pb2
+ return sentencepiece_model_pb2
class SentencePieceExtractor:
@@ -54,12 +66,15 @@ def extract(self, vocab_scores=None) -> Tuple[Dict[str, int], List[Tuple]]:
# Merges
merges = []
- for piece_l in vocab.keys():
- for piece_r in vocab.keys():
- merge = f"{piece_l}{piece_r}"
- piece_score = vocab_scores.get(merge, None)
- if piece_score:
- merges += [(piece_l, piece_r, piece_score)]
+ for merge, piece_score in vocab_scores.items():
+ local = []
+ for index in range(1, len(merge)):
+ piece_l, piece_r = merge[:index], merge[index:]
+ if piece_l in vocab and piece_r in vocab:
+ local.append((piece_l, piece_r, piece_score))
+ local = sorted(local, key=lambda x: (vocab[x[0]], vocab[x[1]]))
+ merges.extend(local)
+
merges = sorted(merges, key=lambda val: val[2], reverse=reverse)
merges = [(val[0], val[1]) for val in merges]
return vocab, merges
@@ -442,7 +457,8 @@ def __init__(self, *args):
super().__init__(*args)
- from .utils import sentencepiece_model_pb2 as model_pb2
+ # from .utils import sentencepiece_model_pb2 as model_pb2
+ model_pb2 = import_protobuf()
m = model_pb2.ModelProto()
with open(self.original_tokenizer.vocab_file, "rb") as f:
@@ -548,7 +564,10 @@ def normalizer(self, proto):
list_normalizers.append(normalizers.Lowercase())
precompiled_charsmap = proto.normalizer_spec.precompiled_charsmap
- list_normalizers.append(normalizers.Precompiled(precompiled_charsmap))
+
+ if precompiled_charsmap:
+ list_normalizers.append(normalizers.Precompiled(precompiled_charsmap))
+
list_normalizers.append(normalizers.Replace(Regex(" {2,}"), " "))
return normalizers.Sequence(list_normalizers)
@@ -799,7 +818,10 @@ def normalizer(self, proto):
list_normalizers.append(normalizers.Lowercase())
precompiled_charsmap = proto.normalizer_spec.precompiled_charsmap
- list_normalizers.append(normalizers.Precompiled(precompiled_charsmap))
+
+ if precompiled_charsmap:
+ list_normalizers.append(normalizers.Precompiled(precompiled_charsmap))
+
list_normalizers.append(normalizers.Replace(Regex(" {2,}"), " "))
return normalizers.Sequence(list_normalizers)
@@ -833,7 +855,10 @@ def normalizer(self, proto):
list_normalizers.append(normalizers.Lowercase())
precompiled_charsmap = proto.normalizer_spec.precompiled_charsmap
- list_normalizers.append(normalizers.Precompiled(precompiled_charsmap))
+
+ if precompiled_charsmap:
+ list_normalizers.append(normalizers.Precompiled(precompiled_charsmap))
+
return normalizers.Sequence(list_normalizers)
def post_processor(self):
@@ -1134,9 +1159,9 @@ def tokenizer(self, proto):
)
tokenizer.add_special_tokens(
[
- AddedToken("", normalized=True),
- AddedToken("", normalized=True),
- AddedToken(" ", normalized=True),
+ AddedToken(""),
+ AddedToken(""),
+ AddedToken(" "),
]
)
else:
@@ -1175,7 +1200,11 @@ def post_processor(self):
single = f"{(bos+':0 ') * add_bos}$A:0{(' '+eos+':0') * add_eos}"
pair = f"{single}{(' '+bos+':1') * add_bos} $B:1{(' '+eos+':1') * add_eos}"
- special_tokens = [(bos, bos_token_id), (eos, eos_token_id)]
+ special_tokens = []
+ if add_bos:
+ special_tokens.append((bos, bos_token_id))
+ if add_eos:
+ special_tokens.append((eos, eos_token_id))
return processors.TemplateProcessing(single=single, pair=pair, special_tokens=special_tokens)
else:
diff --git a/src/transformers/data/metrics/__init__.py b/src/transformers/data/metrics/__init__.py
index 6f51f44dfeb2..ebd0d17aa55b 100644
--- a/src/transformers/data/metrics/__init__.py
+++ b/src/transformers/data/metrics/__init__.py
@@ -90,7 +90,8 @@ def glue_compute_metrics(task_name, preds, labels):
def xnli_compute_metrics(task_name, preds, labels):
warnings.warn(DEPRECATION_WARNING, FutureWarning)
requires_backends(xnli_compute_metrics, "sklearn")
- assert len(preds) == len(labels), f"Predictions and labels have mismatched lengths {len(preds)} and {len(labels)}"
+ if len(preds) != len(labels):
+ raise ValueError(f"Predictions and labels have mismatched lengths {len(preds)} and {len(labels)}")
if task_name == "xnli":
return {"acc": simple_accuracy(preds, labels)}
else:
diff --git a/src/transformers/data/test_generation_utils.py b/src/transformers/data/test_generation_utils.py
deleted file mode 100644
index a69b5683de75..000000000000
--- a/src/transformers/data/test_generation_utils.py
+++ /dev/null
@@ -1,99 +0,0 @@
-# Copyright 2020 The HuggingFace Team. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-import random
-import unittest
-
-import timeout_decorator
-
-from ..testing_utils import require_torch
-from ..utils import cached_property, is_torch_available
-
-
-if is_torch_available():
- import torch
-
- from ..models.marian import MarianConfig, MarianMTModel
-
-
-@require_torch
-class GenerationUtilsTest(unittest.TestCase):
- @cached_property
- def config(self):
- config = MarianConfig.from_pretrained("sshleifer/tiny-marian-en-de")
- return config
-
- @cached_property
- def model(self):
- return MarianMTModel(self.config)
-
- def test_postprocess_next_token_scores(self):
- config = self.config
- model = self.model
- # Initialize an input id tensor with batch size 8 and sequence length 12
- input_ids = torch.arange(0, 96, 1).view((8, 12))
- eos = config.eos_token_id
- bad_words_ids_test_cases = [[[299]], [[23, 24], [54]], [[config.eos_token_id]], []]
- masked_scores = [
- [(0, 299), (1, 299), (2, 299), (3, 299), (4, 299), (5, 299), (6, 299), (7, 299)],
- [(1, 24), (0, 54), (1, 54), (2, 54), (3, 54), (4, 54), (5, 54), (6, 54), (7, 54)],
- [(0, eos), (1, eos), (2, eos), (3, eos), (4, eos), (5, eos), (6, eos), (7, eos)],
- [],
- ]
-
- for test_case_index, bad_words_ids in enumerate(bad_words_ids_test_cases):
- # Initialize a scores tensor with batch size 8 and vocabulary size 300
- scores = torch.rand((8, 300))
- output = model.postprocess_next_token_scores(
- scores,
- input_ids,
- 0,
- bad_words_ids,
- 13,
- 15,
- config.max_length,
- config.eos_token_id,
- config.repetition_penalty,
- 32,
- 5,
- )
- for masked_score in masked_scores[test_case_index]:
- self.assertTrue(output[masked_score[0], masked_score[1]] == -float("inf"))
-
- @timeout_decorator.timeout(10)
- def test_postprocess_next_token_scores_large_bad_words_list(self):
- config = self.config
- model = self.model
- # Initialize an input id tensor with batch size 8 and sequence length 12
- input_ids = torch.arange(0, 96, 1).view((8, 12))
-
- bad_words_ids = []
- for _ in range(100):
- length_bad_word = random.randint(1, 4)
- bad_words_ids.append(random.sample(range(1, 300), length_bad_word))
-
- scores = torch.rand((8, 300))
- _ = model.postprocess_next_token_scores(
- scores,
- input_ids,
- 0,
- bad_words_ids,
- 13,
- 15,
- config.max_length,
- config.eos_token_id,
- config.repetition_penalty,
- 32,
- 5,
- )
diff --git a/src/transformers/deepspeed.py b/src/transformers/deepspeed.py
index 3a36db5f3ea5..7af2bedece84 100644
--- a/src/transformers/deepspeed.py
+++ b/src/transformers/deepspeed.py
@@ -17,7 +17,6 @@
import importlib.util
import weakref
-from copy import deepcopy
from functools import partialmethod
from .dependency_versions_check import dep_version_check
@@ -256,10 +255,12 @@ def deepspeed_config():
return None
-def deepspeed_optim_sched(trainer, hf_deepspeed_config, args, num_training_steps):
+def deepspeed_optim_sched(trainer, hf_deepspeed_config, args, num_training_steps, model_parameters):
"""
A convenience wrapper that deals with optimizer and lr scheduler configuration.
"""
+ from accelerate.utils import DummyOptim, DummyScheduler
+
config = hf_deepspeed_config.config
# Optimizer + Scheduler
@@ -267,13 +268,13 @@ def deepspeed_optim_sched(trainer, hf_deepspeed_config, args, num_training_steps
# 1. DS scheduler + DS optimizer: Yes
# 2. HF scheduler + HF optimizer: Yes
# 3. DS scheduler + HF optimizer: Yes
- # 4. HF scheduler + DS optimizer: Yes
+ # 4. HF scheduler + DS optimizer: No
#
# Unless Offload is enabled in which case it's:
# 1. DS scheduler + DS optimizer: Yes
# 2. HF scheduler + HF optimizer: Mostly*
# 3. DS scheduler + HF optimizer: Mostly*
- # 4. HF scheduler + DS optimizer: Yes
+ # 4. HF scheduler + DS optimizer: No
#
# Mostly*: All non-native DeepSpeed optimizers that have both CPU and GPU implementation should work (except LAMB)
@@ -284,6 +285,7 @@ def deepspeed_optim_sched(trainer, hf_deepspeed_config, args, num_training_steps
"--adafactor was passed, but also found `optimizer` configured in the DeepSpeed config. "
"Only one optimizer can be configured."
)
+ optimizer = DummyOptim(params=model_parameters)
else:
if hf_deepspeed_config.is_offload():
logger.info(
@@ -297,21 +299,21 @@ def deepspeed_optim_sched(trainer, hf_deepspeed_config, args, num_training_steps
# To use other optimizers requires voiding warranty with: `zero_allow_untested_optimizer`
config["zero_allow_untested_optimizer"] = True
- def _lr_scheduler_callable(optimizer):
- return trainer.create_scheduler(num_training_steps=num_training_steps, optimizer=optimizer)
-
lr_scheduler = None
- if "scheduler" not in config:
- if optimizer is None:
- # Optimizer is not available, so use callable to defer lr_scheduler creation to DS init
- lr_scheduler = _lr_scheduler_callable
- else:
- lr_scheduler = trainer.create_scheduler(num_training_steps=num_training_steps, optimizer=optimizer)
+ if "scheduler" in config:
+ lr_scheduler = DummyScheduler(optimizer)
+ else:
+ if isinstance(optimizer, DummyOptim):
+ raise ValueError(
+ "Found `optimizer` configured in the DeepSpeed config, but no `scheduler`. "
+ "Please configure a scheduler in the DeepSpeed config."
+ )
+ lr_scheduler = trainer.create_scheduler(num_training_steps=num_training_steps, optimizer=optimizer)
return optimizer, lr_scheduler
-def deepspeed_init(trainer, num_training_steps, resume_from_checkpoint=None, inference=False):
+def deepspeed_init(trainer, num_training_steps, inference=False):
"""
Init DeepSpeed, after updating the DeepSpeed configuration with any relevant Trainer's args.
@@ -323,28 +325,22 @@ def deepspeed_init(trainer, num_training_steps, resume_from_checkpoint=None, inf
resume_from_checkpoint: path to a checkpoint if to resume from after normal DeepSpeedEngine load
inference: launch in inference mode (no optimizer and no lr scheduler)
- Returns: model, optimizer, lr_scheduler
+ Returns: optimizer, lr_scheduler
We may use `deepspeed_init` more than once during the life of Trainer, when we do - it's a temp hack based on:
https://github.com/microsoft/DeepSpeed/issues/1394#issuecomment-937405374 until Deepspeed fixes a bug where it
can't resume from a checkpoint after it did some stepping https://github.com/microsoft/DeepSpeed/issues/1612
"""
- import deepspeed
from deepspeed.utils import logger as ds_logger
model = trainer.model
args = trainer.args
- if hasattr(trainer, "hf_deepspeed_config_orig"):
- hf_deepspeed_config = deepcopy(trainer.hf_deepspeed_config_orig)
- else:
- hf_deepspeed_config = args.hf_deepspeed_config
- trainer.hf_deepspeed_config_orig = deepcopy(args.hf_deepspeed_config)
+ hf_deepspeed_config = trainer.accelerator.state.deepspeed_plugin.hf_ds_config
# resume config update - some bits like `model` and `num_training_steps` only become available during train
hf_deepspeed_config.trainer_config_finalize(args, model, num_training_steps)
- config = hf_deepspeed_config.config
# set the Deepspeed log level consistent with the Trainer
ds_logger.setLevel(args.get_process_log_level())
@@ -361,40 +357,33 @@ def deepspeed_init(trainer, num_training_steps, resume_from_checkpoint=None, inf
model_parameters = None
else:
trainer.optimizer = None # important for when deepspeed_init is used as re-init
- optimizer, lr_scheduler = deepspeed_optim_sched(trainer, hf_deepspeed_config, args, num_training_steps)
model_parameters = list(filter(lambda p: p.requires_grad, model.parameters()))
+ optimizer, lr_scheduler = deepspeed_optim_sched(
+ trainer, hf_deepspeed_config, args, num_training_steps, model_parameters
+ )
# keep for quick debug:
# from pprint import pprint; pprint(config)
- kwargs = {
- "model": model,
- "model_parameters": model_parameters,
- "config_params": config,
- "optimizer": optimizer,
- "lr_scheduler": lr_scheduler,
- }
-
- deepspeed_engine, optimizer, _, lr_scheduler = deepspeed.initialize(**kwargs)
-
- if resume_from_checkpoint is not None:
- # it's possible that the user is trying to resume from model_path, which doesn't necessarily
- # contain a deepspeed checkpoint. e.g. examples just check if the dir exists and assume it's
- # a resume from a checkpoint and not just a local pretrained weight. So we check here if the
- # path contains what looks like a deepspeed checkpoint
- import glob
-
- deepspeed_checkpoint_dirs = sorted(glob.glob(f"{resume_from_checkpoint}/global_step*"))
-
- if len(deepspeed_checkpoint_dirs) > 0:
- logger.info(f"Attempting to resume from {resume_from_checkpoint}")
- # this magically updates self.optimizer and self.lr_scheduler
- load_path, _ = deepspeed_engine.load_checkpoint(
- resume_from_checkpoint, load_optimizer_states=True, load_lr_scheduler_states=True
- )
- if load_path is None:
- raise ValueError(f"[deepspeed] failed to resume from checkpoint {resume_from_checkpoint}")
- else:
- raise ValueError(f"Can't find a valid checkpoint at {resume_from_checkpoint}")
+ return optimizer, lr_scheduler
+
- return deepspeed_engine, optimizer, lr_scheduler
+def deepspeed_load_checkpoint(deepspeed_engine, checkpoint_path):
+ # it's possible that the user is trying to resume from model_path, which doesn't necessarily
+ # contain a deepspeed checkpoint. e.g. examples just check if the dir exists and assume it's
+ # a resume from a checkpoint and not just a local pretrained weight. So we check here if the
+ # path contains what looks like a deepspeed checkpoint
+ import glob
+
+ deepspeed_checkpoint_dirs = sorted(glob.glob(f"{checkpoint_path}/global_step*"))
+
+ if len(deepspeed_checkpoint_dirs) > 0:
+ logger.info(f"Attempting to resume from {checkpoint_path}")
+ # this magically updates self.optimizer and self.lr_scheduler
+ load_path, _ = deepspeed_engine.load_checkpoint(
+ checkpoint_path, load_optimizer_states=True, load_lr_scheduler_states=True
+ )
+ if load_path is None:
+ raise ValueError(f"[deepspeed] failed to resume from checkpoint {checkpoint_path}")
+ else:
+ raise ValueError(f"Can't find a valid checkpoint at {checkpoint_path}")
diff --git a/src/transformers/dependency_versions_check.py b/src/transformers/dependency_versions_check.py
index bbf863222a52..82d07850847e 100644
--- a/src/transformers/dependency_versions_check.py
+++ b/src/transformers/dependency_versions_check.py
@@ -11,7 +11,6 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
-import sys
from .dependency_versions_table import deps
from .utils.versions import require_version, require_version_core
@@ -23,11 +22,20 @@
# order specific notes:
# - tqdm must be checked before tokenizers
-pkgs_to_check_at_runtime = "python tqdm regex requests packaging filelock numpy tokenizers".split()
-if sys.version_info < (3, 7):
- pkgs_to_check_at_runtime.append("dataclasses")
-if sys.version_info < (3, 8):
- pkgs_to_check_at_runtime.append("importlib_metadata")
+pkgs_to_check_at_runtime = [
+ "python",
+ "tqdm",
+ "regex",
+ "requests",
+ "packaging",
+ "filelock",
+ "numpy",
+ "tokenizers",
+ "huggingface-hub",
+ "safetensors",
+ "accelerate",
+ "pyyaml",
+]
for pkg in pkgs_to_check_at_runtime:
if pkg in deps:
@@ -37,6 +45,14 @@
if not is_tokenizers_available():
continue # not required, check version only if installed
+ elif pkg == "accelerate":
+ # must be loaded here, or else tqdm check may fail
+ from .utils import is_accelerate_available
+
+ # Maybe switch to is_torch_available in the future here so that Accelerate is hard dep of
+ # Transformers with PyTorch
+ if not is_accelerate_available():
+ continue # not required, check version only if installed
require_version_core(deps[pkg])
else:
diff --git a/src/transformers/dependency_versions_table.py b/src/transformers/dependency_versions_table.py
index 68ad7a1587f4..117180c2eebc 100644
--- a/src/transformers/dependency_versions_table.py
+++ b/src/transformers/dependency_versions_table.py
@@ -2,8 +2,8 @@
# 1. modify the `_deps` dict in setup.py
# 2. run `make deps_table_update``
deps = {
- "Pillow": "Pillow",
- "accelerate": "accelerate>=0.17.0",
+ "Pillow": "Pillow<10.0.0",
+ "accelerate": "accelerate>=0.20.3",
"av": "av==9.2.0",
"beautifulsoup4": "beautifulsoup4",
"black": "black~=23.1",
@@ -12,24 +12,25 @@
"dataclasses": "dataclasses",
"datasets": "datasets!=2.5.0",
"decord": "decord==0.6.0",
- "deepspeed": "deepspeed>=0.8.3",
+ "deepspeed": "deepspeed>=0.9.3",
+ "diffusers": "diffusers",
"dill": "dill<0.3.5",
"evaluate": "evaluate>=0.2.0",
"fairscale": "fairscale>0.3",
"faiss-cpu": "faiss-cpu",
"fastapi": "fastapi",
"filelock": "filelock",
- "flax": "flax>=0.4.1,<=0.6.9",
+ "flax": "flax>=0.4.1,<=0.7.0",
"ftfy": "ftfy",
"fugashi": "fugashi>=1.0",
"GitPython": "GitPython<3.1.19",
"hf-doc-builder": "hf-doc-builder>=0.3.0",
- "huggingface-hub": "huggingface-hub>=0.11.0,<1.0",
+ "huggingface-hub": "huggingface-hub>=0.15.1,<1.0",
"importlib_metadata": "importlib_metadata",
"ipadic": "ipadic>=1.0.0,<2.0",
"isort": "isort>=5.5.4",
- "jax": "jax>=0.2.8,!=0.3.2,<=0.3.6",
- "jaxlib": "jaxlib>=0.1.65,<=0.3.6",
+ "jax": "jax>=0.4.1,<=0.4.13",
+ "jaxlib": "jaxlib>=0.4.1,<=0.4.13",
"jieba": "jieba",
"kenlm": "kenlm",
"keras-nlp": "keras-nlp>=0.3.1",
@@ -40,29 +41,30 @@
"onnxconverter-common": "onnxconverter-common",
"onnxruntime-tools": "onnxruntime-tools>=1.4.2",
"onnxruntime": "onnxruntime>=1.4.0",
+ "opencv-python": "opencv-python",
"optuna": "optuna",
"optax": "optax>=0.0.8,<=0.1.4",
"packaging": "packaging>=20.0",
"parameterized": "parameterized",
"phonemizer": "phonemizer",
- "protobuf": "protobuf<=3.20.2",
+ "protobuf": "protobuf",
"psutil": "psutil",
"pyyaml": "pyyaml>=5.1",
- "pydantic": "pydantic",
- "pytest": "pytest",
+ "pydantic": "pydantic<2",
+ "pytest": "pytest>=7.2.0",
"pytest-timeout": "pytest-timeout",
"pytest-xdist": "pytest-xdist",
- "python": "python>=3.7.0",
+ "python": "python>=3.8.0",
"ray[tune]": "ray[tune]",
"regex": "regex!=2019.12.17",
"requests": "requests",
- "rhoknp": "rhoknp>=1.1.0",
+ "rhoknp": "rhoknp>=1.1.0,<1.3.1",
"rjieba": "rjieba",
"rouge-score": "rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1",
"ruff": "ruff>=0.0.241,<=0.0.259",
"sacrebleu": "sacrebleu>=1.4.12,<2.0.0",
"sacremoses": "sacremoses",
- "safetensors": "safetensors>=0.2.1",
+ "safetensors": "safetensors>=0.3.1",
"sagemaker": "sagemaker>=2.31.0",
"scikit-learn": "scikit-learn",
"sentencepiece": "sentencepiece>=0.1.91,!=0.1.92",
@@ -70,9 +72,9 @@
"starlette": "starlette",
"sudachipy": "sudachipy>=0.6.6",
"sudachidict_core": "sudachidict_core>=20220729",
- "tensorflow-cpu": "tensorflow-cpu>=2.4,<2.13",
- "tensorflow": "tensorflow>=2.4,<2.13",
- "tensorflow-text": "tensorflow-text<2.13",
+ "tensorflow-cpu": "tensorflow-cpu>=2.6,<2.14",
+ "tensorflow": "tensorflow>=2.6,<2.14",
+ "tensorflow-text": "tensorflow-text<2.14",
"tf2onnx": "tf2onnx",
"timeout-decorator": "timeout-decorator",
"timm": "timm",
@@ -84,5 +86,6 @@
"tqdm": "tqdm>=4.27",
"unidic": "unidic>=1.0.2",
"unidic_lite": "unidic_lite>=1.0.7",
+ "urllib3": "urllib3<2.0.0",
"uvicorn": "uvicorn",
}
diff --git a/src/transformers/dynamic_module_utils.py b/src/transformers/dynamic_module_utils.py
index 8d0ff2c34f2b..d59257b27335 100644
--- a/src/transformers/dynamic_module_utils.py
+++ b/src/transformers/dynamic_module_utils.py
@@ -18,7 +18,9 @@
import os
import re
import shutil
+import signal
import sys
+import warnings
from pathlib import Path
from typing import Dict, Optional, Union
@@ -57,7 +59,7 @@ def create_dynamic_module(name: Union[str, os.PathLike]):
Creates a dynamic module in the cache directory for modules.
"""
init_hf_modules()
- dynamic_module_path = Path(HF_MODULES_CACHE) / name
+ dynamic_module_path = (Path(HF_MODULES_CACHE) / name).resolve()
# If the parent module does not exist yet, recursively create it.
if not dynamic_module_path.parent.exists():
create_dynamic_module(dynamic_module_path.parent)
@@ -115,15 +117,15 @@ def get_relative_import_files(module_file):
return all_relative_imports
-def check_imports(filename):
+def get_imports(filename):
"""
- Check if the current Python environment contains all the libraries that are imported in a file.
+ Extracts all the libraries that are imported in a file.
"""
with open(filename, "r", encoding="utf-8") as f:
content = f.read()
# filter out try/except block so in custom code we can have try/except imports
- content = re.sub(r"\s*try\s*:\s*.*?\s*except\s*:", "", content, flags=re.MULTILINE)
+ content = re.sub(r"\s*try\s*:\s*.*?\s*except\s*.*?:", "", content, flags=re.MULTILINE | re.DOTALL)
# Imports of the form `import xxx`
imports = re.findall(r"^\s*import\s+(\S+)\s*$", content, flags=re.MULTILINE)
@@ -131,9 +133,14 @@ def check_imports(filename):
imports += re.findall(r"^\s*from\s+(\S+)\s+import", content, flags=re.MULTILINE)
# Only keep the top-level module
imports = [imp.split(".")[0] for imp in imports if not imp.startswith(".")]
+ return list(set(imports))
+
- # Unique-ify and test we got them all
- imports = list(set(imports))
+def check_imports(filename):
+ """
+ Check if the current Python environment contains all the libraries that are imported in a file.
+ """
+ imports = get_imports(filename)
missing_packages = []
for imp in imports:
try:
@@ -166,10 +173,12 @@ def get_cached_module_file(
force_download: bool = False,
resume_download: bool = False,
proxies: Optional[Dict[str, str]] = None,
- use_auth_token: Optional[Union[bool, str]] = None,
+ token: Optional[Union[bool, str]] = None,
revision: Optional[str] = None,
local_files_only: bool = False,
+ repo_type: Optional[str] = None,
_commit_hash: Optional[str] = None,
+ **deprecated_kwargs,
):
"""
Prepares Downloads a module from a local folder or a distant repo and returns its path inside the cached
@@ -198,7 +207,7 @@ def get_cached_module_file(
proxies (`Dict[str, str]`, *optional*):
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
- use_auth_token (`str` or *bool*, *optional*):
+ token (`str` or *bool*, *optional*):
The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
when running `huggingface-cli login` (stored in `~/.huggingface`).
revision (`str`, *optional*, defaults to `"main"`):
@@ -207,16 +216,27 @@ def get_cached_module_file(
identifier allowed by git.
local_files_only (`bool`, *optional*, defaults to `False`):
If `True`, will only try to load the tokenizer configuration from local files.
+ repo_type (`str`, *optional*):
+ Specify the repo type (useful when downloading from a space for instance).
- Passing `use_auth_token=True` is required when you want to use a private model.
+ Passing `token=True` is required when you want to use a private model.
Returns:
`str`: The path to the module inside the cache.
"""
+ use_auth_token = deprecated_kwargs.pop("use_auth_token", None)
+ if use_auth_token is not None:
+ warnings.warn(
+ "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers.", FutureWarning
+ )
+ if token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ token = use_auth_token
+
if is_offline_mode() and not local_files_only:
logger.info("Offline mode: forcing local_files_only=True")
local_files_only = True
@@ -225,11 +245,11 @@ def get_cached_module_file(
pretrained_model_name_or_path = str(pretrained_model_name_or_path)
is_local = os.path.isdir(pretrained_model_name_or_path)
if is_local:
- submodule = pretrained_model_name_or_path.split(os.path.sep)[-1]
+ submodule = os.path.basename(pretrained_model_name_or_path)
else:
submodule = pretrained_model_name_or_path.replace("/", os.path.sep)
cached_module = try_to_load_from_cache(
- pretrained_model_name_or_path, module_file, cache_dir=cache_dir, revision=_commit_hash
+ pretrained_model_name_or_path, module_file, cache_dir=cache_dir, revision=_commit_hash, repo_type=repo_type
)
new_files = []
@@ -243,8 +263,9 @@ def get_cached_module_file(
proxies=proxies,
resume_download=resume_download,
local_files_only=local_files_only,
- use_auth_token=use_auth_token,
+ token=token,
revision=revision,
+ repo_type=repo_type,
_commit_hash=_commit_hash,
)
if not is_local and cached_module != resolved_module_file:
@@ -261,7 +282,7 @@ def get_cached_module_file(
full_submodule = TRANSFORMERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule
create_dynamic_module(full_submodule)
submodule_path = Path(HF_MODULES_CACHE) / full_submodule
- if submodule == pretrained_model_name_or_path.split(os.path.sep)[-1]:
+ if submodule == os.path.basename(pretrained_model_name_or_path):
# We copy local files to avoid putting too many folders in sys.path. This copy is done when the file is new or
# has changed since last copy.
if not (submodule_path / module_file).exists() or not filecmp.cmp(
@@ -300,17 +321,19 @@ def get_cached_module_file(
force_download=force_download,
resume_download=resume_download,
proxies=proxies,
- use_auth_token=use_auth_token,
+ token=token,
revision=revision,
local_files_only=local_files_only,
_commit_hash=commit_hash,
)
new_files.append(f"{module_needed}.py")
- if len(new_files) > 0:
+ if len(new_files) > 0 and revision is None:
new_files = "\n".join([f"- {f}" for f in new_files])
+ repo_type_str = "" if repo_type is None else f"{repo_type}s/"
+ url = f"https://huggingface.co/{repo_type_str}{pretrained_model_name_or_path}"
logger.warning(
- f"A new version of the following files was downloaded from {pretrained_model_name_or_path}:\n{new_files}"
+ f"A new version of the following files was downloaded from {url}:\n{new_files}"
"\n. Make sure to double-check they do not contain any added malicious code. To avoid downloading new "
"versions of the code file, you can pin a revision."
)
@@ -325,9 +348,11 @@ def get_class_from_dynamic_module(
force_download: bool = False,
resume_download: bool = False,
proxies: Optional[Dict[str, str]] = None,
- use_auth_token: Optional[Union[bool, str]] = None,
+ token: Optional[Union[bool, str]] = None,
revision: Optional[str] = None,
local_files_only: bool = False,
+ repo_type: Optional[str] = None,
+ code_revision: Optional[str] = None,
**kwargs,
):
"""
@@ -368,7 +393,7 @@ def get_class_from_dynamic_module(
proxies (`Dict[str, str]`, *optional*):
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
- use_auth_token (`str` or `bool`, *optional*):
+ token (`str` or `bool`, *optional*):
The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
when running `huggingface-cli login` (stored in `~/.huggingface`).
revision (`str`, *optional*, defaults to `"main"`):
@@ -377,10 +402,16 @@ def get_class_from_dynamic_module(
identifier allowed by git.
local_files_only (`bool`, *optional*, defaults to `False`):
If `True`, will only try to load the tokenizer configuration from local files.
+ repo_type (`str`, *optional*):
+ Specify the repo type (useful when downloading from a space for instance).
+ code_revision (`str`, *optional*, defaults to `"main"`):
+ The specific revision to use for the code on the Hub, if the code leaves in a different repository than the
+ rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for
+ storing models and other artifacts on huggingface.co, so `revision` can be any identifier allowed by git.
- Passing `use_auth_token=True` is required when you want to use a private model.
+ Passing `token=True` is required when you want to use a private model.
@@ -398,15 +429,24 @@ def get_class_from_dynamic_module(
# module.
cls = get_class_from_dynamic_module("sgugger/my-bert-model--modeling.MyBertModel", "sgugger/another-bert-model")
```"""
+ use_auth_token = kwargs.pop("use_auth_token", None)
+ if use_auth_token is not None:
+ warnings.warn(
+ "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers.", FutureWarning
+ )
+ if token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ token = use_auth_token
+
# Catch the name of the repo if it's specified in `class_reference`
if "--" in class_reference:
repo_id, class_reference = class_reference.split("--")
- # Invalidate revision since it's not relevant for this repo
- revision = "main"
else:
repo_id = pretrained_model_name_or_path
module_file, class_name = class_reference.split(".")
+ if code_revision is None and pretrained_model_name_or_path == repo_id:
+ code_revision = revision
# And lastly we get the class inside our newly created module
final_module = get_cached_module_file(
repo_id,
@@ -415,9 +455,10 @@ def get_class_from_dynamic_module(
force_download=force_download,
resume_download=resume_download,
proxies=proxies,
- use_auth_token=use_auth_token,
- revision=revision,
+ token=token,
+ revision=code_revision,
local_files_only=local_files_only,
+ repo_type=repo_type,
)
return get_class_in_module(class_name, final_module.replace(".py", ""))
@@ -439,6 +480,7 @@ def custom_object_save(obj, folder, config=None):
"this code in a separate module so we can include it in the saved folder and make it easier to share via "
"the Hub."
)
+ return
def _set_auto_map_in_config(_config):
module_name = obj.__class__.__module__
@@ -478,12 +520,68 @@ def _set_auto_map_in_config(_config):
elif config is not None:
_set_auto_map_in_config(config)
+ result = []
# Copy module file to the output folder.
object_file = sys.modules[obj.__module__].__file__
dest_file = Path(folder) / (Path(object_file).name)
shutil.copy(object_file, dest_file)
+ result.append(dest_file)
# Gather all relative imports recursively and make sure they are copied as well.
for needed_file in get_relative_import_files(object_file):
dest_file = Path(folder) / (Path(needed_file).name)
shutil.copy(needed_file, dest_file)
+ result.append(dest_file)
+
+ return result
+
+
+def _raise_timeout_error(signum, frame):
+ raise ValueError(
+ "Loading this model requires you to execute the configuration file in that repo on your local machine. We "
+ "asked if it was okay but did not get an answer. Make sure you have read the code there to avoid malicious "
+ "use, then set the option `trust_remote_code=True` to remove this error."
+ )
+
+
+TIME_OUT_REMOTE_CODE = 15
+
+
+def resolve_trust_remote_code(trust_remote_code, model_name, has_local_code, has_remote_code):
+ if trust_remote_code is None:
+ if has_local_code:
+ trust_remote_code = False
+ elif has_remote_code and TIME_OUT_REMOTE_CODE > 0:
+ try:
+ signal.signal(signal.SIGALRM, _raise_timeout_error)
+ signal.alarm(TIME_OUT_REMOTE_CODE)
+ while trust_remote_code is None:
+ answer = input(
+ f"Loading {model_name} requires to execute some code in that repo, you can inspect the content of "
+ f"the repository at https://hf.co/{model_name}. You can dismiss this prompt by passing "
+ "`trust_remote_code=True`.\nDo you accept? [y/N] "
+ )
+ if answer.lower() in ["yes", "y", "1"]:
+ trust_remote_code = True
+ elif answer.lower() in ["no", "n", "0", ""]:
+ trust_remote_code = False
+ signal.alarm(0)
+ except AttributeError:
+ # OS which does not support signal.SIGALRM
+ raise ValueError(
+ "Loading this model requires you to execute execute some code in that repo on your local machine. "
+ f"Make sure you have read the code at https://hf.co/{model_name} to avoid malicious use, then set "
+ "the option `trust_remote_code=True` to remove this error."
+ )
+ elif has_remote_code:
+ # For the CI which puts the timeout at 0
+ _raise_timeout_error(None, None)
+
+ if has_remote_code and not has_local_code and not trust_remote_code:
+ raise ValueError(
+ f"Loading {model_name} requires you to execute the configuration file in that"
+ " repo on your local machine. Make sure you have read the code there to avoid malicious use, then"
+ " set the option `trust_remote_code=True` to remove this error."
+ )
+
+ return trust_remote_code
diff --git a/src/transformers/feature_extraction_sequence_utils.py b/src/transformers/feature_extraction_sequence_utils.py
index 2121261be056..40717d993185 100644
--- a/src/transformers/feature_extraction_sequence_utils.py
+++ b/src/transformers/feature_extraction_sequence_utils.py
@@ -140,7 +140,7 @@ def pad(
return_attention_mask if return_attention_mask is not None else self.return_attention_mask
)
- if not required_input:
+ if len(required_input) == 0:
if return_attention_mask:
processed_features["attention_mask"] = []
return processed_features
diff --git a/src/transformers/feature_extraction_utils.py b/src/transformers/feature_extraction_utils.py
index 7823c4cf9e61..838827f8c5c2 100644
--- a/src/transformers/feature_extraction_utils.py
+++ b/src/transformers/feature_extraction_utils.py
@@ -19,6 +19,7 @@
import copy
import json
import os
+import warnings
from collections import UserDict
from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple, Union
@@ -156,7 +157,15 @@ def as_tensor(value):
as_tensor = jnp.array
is_tensor = is_jax_tensor
else:
- as_tensor = np.asarray
+
+ def as_tensor(value, dtype=None):
+ if isinstance(value, (list, tuple)) and isinstance(value[0], (list, tuple, np.ndarray)):
+ value_lens = [len(val) for val in value]
+ if len(set(value_lens)) > 1 and dtype is None:
+ # we have a ragged list so handle explicitly
+ value = as_tensor([np.asarray(val) for val in value], dtype=object)
+ return np.asarray(value, dtype=dtype)
+
is_tensor = is_numpy_array
# Do the tensor conversion in batch
@@ -247,8 +256,15 @@ def _set_processor_class(self, processor_class: str):
@classmethod
def from_pretrained(
- cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs
- ) -> PreTrainedFeatureExtractor:
+ cls,
+ pretrained_model_name_or_path: Union[str, os.PathLike],
+ cache_dir: Optional[Union[str, os.PathLike]] = None,
+ force_download: bool = False,
+ local_files_only: bool = False,
+ token: Optional[Union[str, bool]] = None,
+ revision: str = "main",
+ **kwargs,
+ ):
r"""
Instantiate a type of [`~feature_extraction_utils.FeatureExtractionMixin`] from a feature extractor, *e.g.* a
derived class of [`SequenceFeatureExtractor`].
@@ -277,7 +293,7 @@ def from_pretrained(
proxies (`Dict[str, str]`, *optional*):
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
- use_auth_token (`str` or `bool`, *optional*):
+ token (`str` or `bool`, *optional*):
The token to use as HTTP bearer authorization for remote files. If `True`, or not specified, will use
the token generated when running `huggingface-cli login` (stored in `~/.huggingface`).
revision (`str`, *optional*, defaults to `"main"`):
@@ -327,6 +343,25 @@ def from_pretrained(
assert feature_extractor.return_attention_mask is False
assert unused_kwargs == {"foo": False}
```"""
+ kwargs["cache_dir"] = cache_dir
+ kwargs["force_download"] = force_download
+ kwargs["local_files_only"] = local_files_only
+ kwargs["revision"] = revision
+
+ use_auth_token = kwargs.pop("use_auth_token", None)
+ if use_auth_token is not None:
+ warnings.warn(
+ "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers.", FutureWarning
+ )
+ if token is not None:
+ raise ValueError(
+ "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
+ )
+ token = use_auth_token
+
+ if token is not None:
+ kwargs["token"] = token
+
feature_extractor_dict, kwargs = cls.get_feature_extractor_dict(pretrained_model_name_or_path, **kwargs)
return cls.from_dict(feature_extractor_dict, **kwargs)
@@ -343,9 +378,21 @@ def save_pretrained(self, save_directory: Union[str, os.PathLike], push_to_hub:
Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the
repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
namespace).
- kwargs:
+ kwargs (`Dict[str, Any]`, *optional*):
Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
"""
+ use_auth_token = kwargs.pop("use_auth_token", None)
+
+ if use_auth_token is not None:
+ warnings.warn(
+ "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers.", FutureWarning
+ )
+ if kwargs.get("token", None) is not None:
+ raise ValueError(
+ "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
+ )
+ kwargs["token"] = use_auth_token
+
if os.path.isfile(save_directory):
raise AssertionError(f"Provided path ({save_directory}) should be a directory, not a file")
@@ -374,7 +421,7 @@ def save_pretrained(self, save_directory: Union[str, os.PathLike], push_to_hub:
repo_id,
files_timestamps,
commit_message=commit_message,
- token=kwargs.get("use_auth_token"),
+ token=kwargs.get("token"),
)
return [output_feature_extractor_file]
@@ -398,10 +445,21 @@ def get_feature_extractor_dict(
force_download = kwargs.pop("force_download", False)
resume_download = kwargs.pop("resume_download", False)
proxies = kwargs.pop("proxies", None)
+ token = kwargs.pop("token", None)
use_auth_token = kwargs.pop("use_auth_token", None)
local_files_only = kwargs.pop("local_files_only", False)
revision = kwargs.pop("revision", None)
+ if use_auth_token is not None:
+ warnings.warn(
+ "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers.", FutureWarning
+ )
+ if token is not None:
+ raise ValueError(
+ "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
+ )
+ token = use_auth_token
+
from_pipeline = kwargs.pop("_from_pipeline", None)
from_auto_class = kwargs.pop("_from_auto", False)
@@ -435,7 +493,7 @@ def get_feature_extractor_dict(
proxies=proxies,
resume_download=resume_download,
local_files_only=local_files_only,
- use_auth_token=use_auth_token,
+ token=token,
user_agent=user_agent,
revision=revision,
)
diff --git a/src/transformers/file_utils.py b/src/transformers/file_utils.py
index da24760118c6..d710296fc0f5 100644
--- a/src/transformers/file_utils.py
+++ b/src/transformers/file_utils.py
@@ -17,6 +17,8 @@
This module should not be update anymore and is only left for backward compatibility.
"""
+from huggingface_hub import get_full_repo_name # for backward compatibility
+
from . import __version__
# Backward compatibility imports, to make sure all those objects can be found in file_utils
@@ -71,7 +73,7 @@
define_sagemaker_information,
get_cached_models,
get_file_from_repo,
- get_full_repo_name,
+ get_torch_version,
has_file,
http_user_agent,
is_apex_available,
@@ -100,6 +102,7 @@
is_sagemaker_mp_enabled,
is_scipy_available,
is_sentencepiece_available,
+ is_seqio_available,
is_sklearn_available,
is_soundfile_availble,
is_spacy_available,
@@ -115,6 +118,7 @@
is_torch_cuda_available,
is_torch_fx_available,
is_torch_fx_proxy,
+ is_torch_mps_available,
is_torch_tf32_available,
is_torch_tpu_available,
is_torchaudio_available,
@@ -125,5 +129,4 @@
to_numpy,
to_py_obj,
torch_only_method,
- torch_version,
)
diff --git a/src/transformers/generation/__init__.py b/src/transformers/generation/__init__.py
index bf87b6e5ff5f..f0da9f514e7a 100644
--- a/src/transformers/generation/__init__.py
+++ b/src/transformers/generation/__init__.py
@@ -56,6 +56,7 @@
"NoRepeatNGramLogitsProcessor",
"PrefixConstrainedLogitsProcessor",
"RepetitionPenaltyLogitsProcessor",
+ "SequenceBiasLogitsProcessor",
"EncoderRepetitionPenaltyLogitsProcessor",
"TemperatureLogitsWarper",
"TopKLogitsWarper",
@@ -64,6 +65,7 @@
"EncoderNoRepeatNGramLogitsProcessor",
"ExponentialDecayLengthPenalty",
"LogitNormalization",
+ "UnbatchedClassifierFreeGuidanceLogitsProcessor",
]
_import_structure["stopping_criteria"] = [
"MaxNewTokensCriteria",
@@ -182,10 +184,12 @@
NoRepeatNGramLogitsProcessor,
PrefixConstrainedLogitsProcessor,
RepetitionPenaltyLogitsProcessor,
+ SequenceBiasLogitsProcessor,
TemperatureLogitsWarper,
TopKLogitsWarper,
TopPLogitsWarper,
TypicalLogitsWarper,
+ UnbatchedClassifierFreeGuidanceLogitsProcessor,
)
from .stopping_criteria import (
MaxLengthCriteria,
diff --git a/src/transformers/generation/beam_search.py b/src/transformers/generation/beam_search.py
index 5c423a6a1807..cf729bb45afb 100644
--- a/src/transformers/generation/beam_search.py
+++ b/src/transformers/generation/beam_search.py
@@ -15,7 +15,7 @@
from abc import ABC, abstractmethod
from collections import UserDict
-from typing import List, Optional, Tuple, Union
+from typing import Dict, List, Optional, Tuple, Union
import numpy as np
import torch
@@ -43,6 +43,10 @@
The id of the *padding* token.
eos_token_id (`Union[int, List[int]]`, *optional*):
The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
+ beam_indices (`torch.LongTensor`, *optional*):
+ Beam indices indicating to which beam hypothesis each token correspond.
+ group_index (`int`, *optional*):
+ The index of the group of beams. Used with [`~PreTrainedModel.group_beam_search`].
Return:
`UserDict`: A dictionary composed of the fields as defined above:
@@ -175,16 +179,22 @@ def __init__(
self.group_size = self.num_beams // self.num_beam_groups
self._is_init = False
+ # self._beam_hyps[i*self.num_beam_groups+j] is the beam_hyps of the j-th group in the i-th mini-batch.
+ # If group_beam_search is not used, the list consists of `batch_size` beam_hyps.
self._beam_hyps = [
BeamHypotheses(
- num_beams=self.num_beams,
+ num_beams=self.group_size,
length_penalty=self.length_penalty,
early_stopping=self.do_early_stopping,
max_length=max_length,
)
- for _ in range(batch_size)
+ for _ in range(batch_size * self.num_beam_groups)
]
- self._done = torch.tensor([False for _ in range(batch_size)], dtype=torch.bool, device=self.device)
+ # self._done[i*self.num_beam_groups+j] indicates whether the generation of the beam_hyps of the j-th group
+ # in the i-th mini-batch is complete.
+ self._done = torch.tensor(
+ [False for _ in range(batch_size * self.num_beam_groups)], dtype=torch.bool, device=self.device
+ )
if not isinstance(num_beams, int) or num_beams <= 1:
raise ValueError(
@@ -211,9 +221,11 @@ def process(
pad_token_id: Optional[int] = None,
eos_token_id: Optional[Union[int, List[int]]] = None,
beam_indices: Optional[torch.LongTensor] = None,
- ) -> Tuple[torch.Tensor]:
- cur_len = input_ids.shape[-1]
- batch_size = len(self._beam_hyps)
+ group_index: Optional[int] = 0,
+ ) -> Dict[str, torch.Tensor]:
+ cur_len = input_ids.shape[-1] + 1 # add up to the length which the next_scores is calculated on
+ batch_size = len(self._beam_hyps) // self.num_beam_groups
+
if not (batch_size == (input_ids.shape[0] // self.group_size)):
if self.num_beam_groups > 1:
raise ValueError(
@@ -234,9 +246,10 @@ def process(
if isinstance(eos_token_id, int):
eos_token_id = [eos_token_id]
- for batch_idx, beam_hyp in enumerate(self._beam_hyps):
- if self._done[batch_idx]:
- if self.num_beams < len(beam_hyp):
+ for batch_idx in range(batch_size):
+ batch_group_idx = batch_idx * self.num_beam_groups + group_index
+ if self._done[batch_group_idx]:
+ if self.num_beams < len(self._beam_hyps[batch_group_idx]):
raise ValueError(f"Batch can only be done if at least {self.num_beams} beams have been generated")
if eos_token_id is None or pad_token_id is None:
raise ValueError("Generated beams >= num_beams -> eos_token_id and pad_token have to be defined")
@@ -264,7 +277,7 @@ def process(
else:
beam_index = None
- beam_hyp.add(
+ self._beam_hyps[batch_group_idx].add(
input_ids[batch_beam_idx].clone(),
next_score.item(),
beam_indices=beam_index,
@@ -287,8 +300,7 @@ def process(
)
# Check if we are done so that we can save a pad step if all(done)
- cur_len += 1 # add up to the length which the next_scores is calculated on
- self._done[batch_idx] = self._done[batch_idx] or beam_hyp.is_done(
+ self._done[batch_group_idx] = self._done[batch_group_idx] or self._beam_hyps[batch_group_idx].is_done(
next_scores[batch_idx].max().item(), cur_len
)
@@ -311,20 +323,20 @@ def finalize(
eos_token_id: Optional[Union[int, List[int]]] = None,
beam_indices: Optional[torch.LongTensor] = None,
) -> Tuple[torch.LongTensor]:
- batch_size = len(self._beam_hyps)
+ batch_size = len(self._beam_hyps) // self.num_beam_groups
if isinstance(eos_token_id, int):
eos_token_id = [eos_token_id]
# finalize all open beam hypotheses and add to generated hypotheses
- for batch_idx, beam_hyp in enumerate(self._beam_hyps):
- if self._done[batch_idx]:
+ for batch_group_idx, beam_hyp in enumerate(self._beam_hyps):
+ if self._done[batch_group_idx]:
continue
# all open beam hypotheses are added to the beam hypothesis
# beam hypothesis class automatically keeps the best beams
- for beam_id in range(self.num_beams):
- batch_beam_idx = batch_idx * self.num_beams + beam_id
+ for index_per_group in range(self.group_size):
+ batch_beam_idx = batch_group_idx * self.group_size + index_per_group
final_score = final_beam_scores[batch_beam_idx].item()
final_tokens = input_ids[batch_beam_idx]
beam_index = beam_indices[batch_beam_idx] if beam_indices is not None else None
@@ -337,8 +349,10 @@ def finalize(
best_scores = torch.zeros(batch_size * self.num_beam_hyps_to_keep, device=self.device, dtype=torch.float32)
# retrieve best hypotheses
- for i, beam_hyp in enumerate(self._beam_hyps):
- sorted_hyps = sorted(beam_hyp.beams, key=lambda x: x[0])
+ for i in range(batch_size):
+ beam_hyps_in_batch = self._beam_hyps[i * self.num_beam_groups : (i + 1) * self.num_beam_groups]
+ candidate_beams = [beam for beam_hyp in beam_hyps_in_batch for beam in beam_hyp.beams]
+ sorted_hyps = sorted(candidate_beams, key=lambda x: x[0])
for j in range(self.num_beam_hyps_to_keep):
best_hyp_tuple = sorted_hyps.pop()
best_score = best_hyp_tuple[0]
@@ -366,7 +380,8 @@ def finalize(
# shorter batches are padded if needed
if sent_lengths.min().item() != sent_lengths.max().item():
- assert pad_token_id is not None, "`pad_token_id` has to be defined"
+ if pad_token_id is None:
+ raise ValueError("`pad_token_id` has to be defined")
decoded.fill_(pad_token_id)
if indices is not None:
@@ -495,6 +510,7 @@ def process(
scores_for_all_vocab: torch.FloatTensor,
pad_token_id: Optional[int] = None,
eos_token_id: Optional[Union[int, List[int]]] = None,
+ beam_indices: Optional[torch.LongTensor] = None,
) -> Tuple[torch.Tensor]:
r"""
Args:
@@ -517,6 +533,8 @@ def process(
The id of the *padding* token.
eos_token_id (`Union[int, List[int]]`, *optional*):
The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
+ beam_indices (`torch.LongTensor`, *optional*):
+ Beam indices indicating to which beam hypothesis each token correspond.
Return:
`UserDict`: A dictionary composed of the fields as defined above:
@@ -532,7 +550,7 @@ def process(
indicating to which beam the next tokens shall be added.
"""
- cur_len = input_ids.shape[-1]
+ cur_len = input_ids.shape[-1] + 1 # add up to the length which the next_scores is calculated on
batch_size = len(self._beam_hyps)
if not (batch_size == (input_ids.shape[0] // self.group_size)):
if self.num_beam_groups > 1:
@@ -582,9 +600,16 @@ def process(
completes_constraint = self.check_completes_constraints(input_ids[batch_beam_idx].cpu().tolist())
if completes_constraint:
+ if beam_indices is not None:
+ beam_index = beam_indices[batch_beam_idx]
+ beam_index = beam_index + (batch_beam_idx,)
+ else:
+ beam_index = None
+
beam_hyp.add(
input_ids[batch_beam_idx].clone(),
next_score.item(),
+ beam_indices=beam_index,
)
else:
# add next predicted token since it is not eos_token
@@ -617,7 +642,6 @@ def process(
)
# Check if we are done so that we can save a pad step if all(done)
- cur_len += 1 # add up to the length which the next_scores is calculated on
self._done[batch_idx] = self._done[batch_idx] or beam_hyp.is_done(
next_scores[batch_idx].max().item(), cur_len
)
@@ -780,6 +804,7 @@ def finalize(
max_length: int,
pad_token_id: Optional[int] = None,
eos_token_id: Optional[Union[int, List[int]]] = None,
+ beam_indices: Optional[torch.LongTensor] = None,
) -> Tuple[torch.LongTensor]:
batch_size = len(self._beam_hyps)
@@ -802,7 +827,8 @@ def finalize(
completes_constraint = self.check_completes_constraints(final_tokens.cpu().tolist())
if completes_constraint:
- beam_hyp.add(final_tokens, final_score)
+ beam_index = beam_indices[batch_beam_idx] if beam_indices is not None else None
+ beam_hyp.add(final_tokens, final_score, beam_indices=beam_index)
ids_collect.append(beam_id)
# due to overly complex constraints or other factors, sometimes we can't gaurantee a successful
@@ -820,6 +846,7 @@ def finalize(
# select the best hypotheses
sent_lengths = input_ids.new(batch_size * self.num_beam_hyps_to_keep)
best = []
+ best_indices = []
best_scores = torch.zeros(batch_size * self.num_beam_hyps_to_keep, device=self.device, dtype=torch.float32)
# retrieve best hypotheses
@@ -829,10 +856,15 @@ def finalize(
best_hyp_tuple = sorted_hyps.pop()
best_score = best_hyp_tuple[0]
best_hyp = best_hyp_tuple[1]
+ best_index = best_hyp_tuple[2]
sent_lengths[self.num_beam_hyps_to_keep * i + j] = len(best_hyp)
# append to lists
best.append(best_hyp)
+
+ # append indices to list
+ best_indices.append(best_index)
+
best_scores[i * self.num_beam_hyps_to_keep + j] = best_score
# prepare for adding eos
@@ -840,14 +872,28 @@ def finalize(
sent_max_len = min(sent_lengths_max, max_length) if max_length is not None else sent_lengths_max
decoded: torch.LongTensor = input_ids.new(batch_size * self.num_beam_hyps_to_keep, sent_max_len)
+
+ if len(best_indices) > 0 and best_indices[0] is not None:
+ indices: torch.LongTensor = input_ids.new(batch_size * self.num_beam_hyps_to_keep, sent_max_len)
+ else:
+ indices = None
+
# shorter batches are padded if needed
if sent_lengths.min().item() != sent_lengths.max().item():
- assert pad_token_id is not None, "`pad_token_id` has to be defined"
+ if pad_token_id is None:
+ raise ValueError("`pad_token_id` has to be defined")
decoded.fill_(pad_token_id)
+ if indices is not None:
+ indices.fill_(-1)
+
# fill with hypotheses and eos_token_id if the latter fits in
- for i, hypo in enumerate(best):
+ for i, (hypo, best_idx) in enumerate(zip(best, best_indices)):
decoded[i, : sent_lengths[i]] = hypo
+
+ if indices is not None:
+ indices[i, : len(best_idx)] = torch.tensor(best_idx)
+
if sent_lengths[i] < sent_max_len:
# inserting only the first eos_token_id
decoded[i, sent_lengths[i]] = eos_token_id[0]
@@ -856,6 +902,7 @@ def finalize(
{
"sequences": decoded,
"sequence_scores": best_scores,
+ "beam_indices": indices,
}
)
diff --git a/src/transformers/generation/configuration_utils.py b/src/transformers/generation/configuration_utils.py
index 9f3bedcdebd8..ef0963f675d0 100644
--- a/src/transformers/generation/configuration_utils.py
+++ b/src/transformers/generation/configuration_utils.py
@@ -17,6 +17,7 @@
import copy
import json
import os
+import warnings
from typing import Any, Dict, Optional, Union
from .. import __version__
@@ -142,9 +143,8 @@ class GenerationConfig(PushToHubMixin):
no_repeat_ngram_size (`int`, *optional*, defaults to 0):
If set to int > 0, all ngrams of that size can only occur once.
bad_words_ids(`List[List[int]]`, *optional*):
- List of token ids that are not allowed to be generated. In order to get the token ids of the words that
- should not appear in the generated text, use `tokenizer(bad_words, add_prefix_space=True,
- add_special_tokens=False).input_ids`.
+ List of list of token ids that are not allowed to be generated. Check
+ [`~generation.NoBadWordsLogitsProcessor`] for further documentation and examples.
force_words_ids(`List[List[int]]` or `List[List[List[int]]]`, *optional*):
List of token ids that must be generated. If given a `List[List[int]]`, this is treated as a simple list of
words that must be included, the opposite to `bad_words_ids`. If given `List[List[List[int]]]`, this
@@ -181,6 +181,17 @@ class GenerationConfig(PushToHubMixin):
A list of pairs of integers which indicates a mapping from generation indices to token indices that will be
forced before sampling. For example, `[[1, 123]]` means the second generated token will always be a token
of index 123.
+ sequence_bias (`Dict[Tuple[int], float]`, *optional*)):
+ Dictionary that maps a sequence of tokens to its bias term. Positive biases increase the odds of the
+ sequence being selected, while negative biases do the opposite. Check
+ [`~generation.SequenceBiasLogitsProcessor`] for further documentation and examples.
+ guidance_scale (`float`, *optional*):
+ The guidance scale for classifier free guidance (CFG). CFG is enabled by setting `guidance_scale > 1`.
+ Higher guidance scale encourages the model to generate samples that are more closely linked to the input
+ prompt, usually at the expense of poorer quality.
+ low_memory (`bool`, *optional*):
+ Switch to sequential topk for contrastive search to reduce peak memory. Used with contrastive search.
+
> Parameters that define the output variables of `generate`
@@ -223,6 +234,7 @@ class GenerationConfig(PushToHubMixin):
def __init__(self, **kwargs):
# Parameters that control the length of the output
+ # if the default `max_length` is updated here, make sure to update the `generate` tests following https://github.com/huggingface/transformers/pull/25030
self.max_length = kwargs.pop("max_length", 20)
self.max_new_tokens = kwargs.pop("max_new_tokens", None)
self.min_length = kwargs.pop("min_length", 0)
@@ -260,6 +272,9 @@ def __init__(self, **kwargs):
self.suppress_tokens = kwargs.pop("suppress_tokens", None)
self.begin_suppress_tokens = kwargs.pop("begin_suppress_tokens", None)
self.forced_decoder_ids = kwargs.pop("forced_decoder_ids", None)
+ self.sequence_bias = kwargs.pop("sequence_bias", None)
+ self.guidance_scale = kwargs.pop("guidance_scale", None)
+ self.low_memory = kwargs.pop("low_memory", None)
# Parameters that define the output variables of `generate`
self.num_return_sequences = kwargs.pop("num_return_sequences", 1)
@@ -288,7 +303,8 @@ def __init__(self, **kwargs):
# Additional attributes without default values
if not self._from_model_config:
- # we don't want to copy values from the model config if we're initializing a `GenerationConfig` from a model's default configuration file
+ # we don't want to copy values from the model config if we're initializing a `GenerationConfig` from a
+ # model's default configuration file
for key, value in kwargs.items():
try:
setattr(self, key, value)
@@ -297,7 +313,7 @@ def __init__(self, **kwargs):
raise err
# Validate the values of the attributes
- self.validate()
+ self.validate(is_init=True)
def __eq__(self, other):
if not isinstance(other, GenerationConfig):
@@ -314,14 +330,150 @@ def __eq__(self, other):
def __repr__(self):
return f"{self.__class__.__name__} {self.to_json_string()}"
- def validate(self):
+ def validate(self, is_init=False):
"""
- Validates the values of the attributes of the GenerationConfig instance, and raises a `ValueError` if any of
- the values are invalid.
+ Validates the values of the attributes of the [`GenerationConfig`] instance. Raises exceptions in the presence
+ of parameterization that can be detected as incorrect from the configuration instance alone.
+
+ Note that some parameters are best validated at generate runtime, as they may depend on other inputs and/or the
+ model, such as parameters related to the generation length.
"""
+
+ # Validation of individual attributes
if self.early_stopping not in {True, False, "never"}:
raise ValueError(f"`early_stopping` must be a boolean or 'never', but is {self.early_stopping}.")
+ # Validation of attribute relations:
+ fix_location = ""
+ if is_init:
+ fix_location = (
+ " This was detected when initializing the generation config instance, which means the corresponding "
+ "file may hold incorrect parameterization and should be fixed."
+ )
+
+ # 1. detect sampling-only parameterization when not in sampling mode
+ if self.do_sample is False:
+ greedy_wrong_parameter_msg = (
+ "`do_sample` is set to `False`. However, `{flag_name}` is set to `{flag_value}` -- this flag is only "
+ "used in sample-based generation modes. You should set `do_sample=True` or unset `{flag_name}`."
+ + fix_location
+ )
+ if self.temperature != 1.0:
+ warnings.warn(
+ greedy_wrong_parameter_msg.format(flag_name="temperature", flag_value=self.temperature),
+ UserWarning,
+ )
+ if self.top_p != 1.0:
+ warnings.warn(
+ greedy_wrong_parameter_msg.format(flag_name="top_p", flag_value=self.top_p),
+ UserWarning,
+ )
+ if self.typical_p != 1.0:
+ warnings.warn(
+ greedy_wrong_parameter_msg.format(flag_name="typical_p", flag_value=self.typical_p),
+ UserWarning,
+ )
+ if self.top_k != 50 and self.penalty_alpha is None: # contrastive search uses top_k
+ warnings.warn(
+ greedy_wrong_parameter_msg.format(flag_name="top_k", flag_value=self.top_k),
+ UserWarning,
+ )
+ if self.epsilon_cutoff != 0.0:
+ warnings.warn(
+ greedy_wrong_parameter_msg.format(flag_name="epsilon_cutoff", flag_value=self.epsilon_cutoff),
+ UserWarning,
+ )
+ if self.eta_cutoff != 0.0:
+ warnings.warn(
+ greedy_wrong_parameter_msg.format(flag_name="eta_cutoff", flag_value=self.eta_cutoff),
+ UserWarning,
+ )
+
+ # 2. detect beam-only parameterization when not in beam mode
+ if self.num_beams == 1:
+ single_beam_wrong_parameter_msg = (
+ "`num_beams` is set to 1. However, `{flag_name}` is set to `{flag_value}` -- this flag is only used "
+ "in beam-based generation modes. You should set `num_beams>1` or unset `{flag_name}`." + fix_location
+ )
+ if self.early_stopping is not False:
+ warnings.warn(
+ single_beam_wrong_parameter_msg.format(flag_name="early_stopping", flag_value=self.early_stopping),
+ UserWarning,
+ )
+ if self.num_beam_groups != 1:
+ warnings.warn(
+ single_beam_wrong_parameter_msg.format(
+ flag_name="num_beam_groups", flag_value=self.num_beam_groups
+ ),
+ UserWarning,
+ )
+ if self.diversity_penalty != 0.0:
+ warnings.warn(
+ single_beam_wrong_parameter_msg.format(
+ flag_name="diversity_penalty", flag_value=self.diversity_penalty
+ ),
+ UserWarning,
+ )
+ if self.length_penalty != 1.0:
+ warnings.warn(
+ single_beam_wrong_parameter_msg.format(flag_name="length_penalty", flag_value=self.length_penalty),
+ UserWarning,
+ )
+ if self.constraints is not None:
+ warnings.warn(
+ single_beam_wrong_parameter_msg.format(flag_name="constraints", flag_value=self.constraints),
+ UserWarning,
+ )
+
+ # 3. detect incorrect paramaterization specific to advanced beam modes
+ else:
+ # constrained beam search
+ if self.constraints is not None:
+ constrained_wrong_parameter_msg = (
+ "`constraints` is not `None`, triggering constrained beam search. However, `{flag_name}` is set "
+ "to `{flag_value}`, which is incompatible with this generation mode. Set `constraints=None` or "
+ "unset `{flag_name}` to continue." + fix_location
+ )
+ if self.do_sample is True:
+ raise ValueError(
+ constrained_wrong_parameter_msg.format(flag_name="do_sample", flag_value=self.do_sample)
+ )
+ if self.num_beam_groups != 1:
+ raise ValueError(
+ constrained_wrong_parameter_msg.format(
+ flag_name="num_beam_groups", flag_value=self.num_beam_groups
+ )
+ )
+ # group beam search
+ if self.diversity_penalty != 0.0 or self.num_beam_groups != 1:
+ group_error_prefix = (
+ "`diversity_penalty` is not 0.0 or `num_beam_groups` is not 1, triggering group beam search. In "
+ "this generation mode, "
+ )
+ if self.do_sample is True:
+ raise ValueError(group_error_prefix + "`do_sample` must be set to `False`")
+ if self.num_beams % self.num_beam_groups != 0:
+ raise ValueError(group_error_prefix + "`num_beams` should be divisible by `num_beam_groups`")
+ if self.diversity_penalty == 0.0:
+ raise ValueError(
+ group_error_prefix
+ + "`diversity_penalty` should be greater than `0.0`, otherwise your groups will be identical."
+ )
+
+ # 4. check `num_return_sequences`
+ if self.num_return_sequences != 1:
+ if self.num_beams == 1:
+ if self.do_sample is False:
+ raise ValueError(
+ "Greedy methods without beam search do not support `num_return_sequences` different than 1 "
+ f"(got {self.num_return_sequences})."
+ )
+ elif self.num_return_sequences > self.num_beams:
+ raise ValueError(
+ f"`num_return_sequences` ({self.num_return_sequences}) has to be smaller or equal to `num_beams` "
+ f"({self.num_beams})."
+ )
+
def save_pretrained(
self,
save_directory: Union[str, os.PathLike],
@@ -342,9 +494,37 @@ def save_pretrained(
Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the
repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
namespace).
- kwargs:
+ kwargs (`Dict[str, Any]`, *optional*):
Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
"""
+
+ # At save time, validate the instance -- if any warning/exception is thrown, we refuse to save the instance
+ try:
+ with warnings.catch_warnings(record=True) as caught_warnings:
+ self.validate()
+ for w in caught_warnings:
+ raise ValueError(w.message)
+ except ValueError as exc:
+ warnings.warn(
+ "The generation config instance is invalid -- `.validate()` throws warnings and/or exceptions. "
+ "Fix these issues to save the configuration. This warning will be raised to an exception in v4.34."
+ "\n\nThrown during validation:\n" + str(exc),
+ UserWarning,
+ )
+ return
+
+ use_auth_token = kwargs.pop("use_auth_token", None)
+
+ if use_auth_token is not None:
+ warnings.warn(
+ "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers.", FutureWarning
+ )
+ if kwargs.get("token", None) is not None:
+ raise ValueError(
+ "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
+ )
+ kwargs["token"] = use_auth_token
+
config_file_name = config_file_name if config_file_name is not None else GENERATION_CONFIG_NAME
if os.path.isfile(save_directory):
@@ -369,7 +549,7 @@ def save_pretrained(
repo_id,
files_timestamps,
commit_message=commit_message,
- token=kwargs.get("use_auth_token"),
+ token=kwargs.get("token"),
)
@classmethod
@@ -377,6 +557,11 @@ def from_pretrained(
cls,
pretrained_model_name: Union[str, os.PathLike],
config_file_name: Optional[Union[str, os.PathLike]] = None,
+ cache_dir: Optional[Union[str, os.PathLike]] = None,
+ force_download: bool = False,
+ local_files_only: bool = False,
+ token: Optional[Union[str, bool]] = None,
+ revision: str = "main",
**kwargs,
) -> "GenerationConfig":
r"""
@@ -405,7 +590,7 @@ def from_pretrained(
proxies (`Dict[str, str]`, *optional*):
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
- use_auth_token (`str` or `bool`, *optional*):
+ token (`str` or `bool`, *optional*):
The token to use as HTTP bearer authorization for remote files. If `True`, or not specified, will use
the token generated when running `huggingface-cli login` (stored in `~/.huggingface`).
revision (`str`, *optional*, defaults to `"main"`):
@@ -455,7 +640,7 @@ def from_pretrained(
>>> # If you'd like to try a minor variation to an existing configuration, you can also pass generation
>>> # arguments to `.from_pretrained()`. Be mindful that typos and unused arguments will be ignored
>>> generation_config, unused_kwargs = GenerationConfig.from_pretrained(
- ... "gpt2", top_k=1, foo=False, return_unused_kwargs=True
+ ... "gpt2", top_k=1, foo=False, do_sample=True, return_unused_kwargs=True
... )
>>> generation_config.top_k
1
@@ -465,18 +650,24 @@ def from_pretrained(
```"""
config_file_name = config_file_name if config_file_name is not None else GENERATION_CONFIG_NAME
- cache_dir = kwargs.pop("cache_dir", None)
- force_download = kwargs.pop("force_download", False)
resume_download = kwargs.pop("resume_download", False)
proxies = kwargs.pop("proxies", None)
use_auth_token = kwargs.pop("use_auth_token", None)
- local_files_only = kwargs.pop("local_files_only", False)
- revision = kwargs.pop("revision", None)
subfolder = kwargs.pop("subfolder", "")
from_pipeline = kwargs.pop("_from_pipeline", None)
from_auto_class = kwargs.pop("_from_auto", False)
commit_hash = kwargs.pop("_commit_hash", None)
+ if use_auth_token is not None:
+ warnings.warn(
+ "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers.", FutureWarning
+ )
+ if token is not None:
+ raise ValueError(
+ "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
+ )
+ token = use_auth_token
+
user_agent = {"file_type": "config", "from_auto_class": from_auto_class}
if from_pipeline is not None:
user_agent["using_pipeline"] = from_pipeline
@@ -504,7 +695,7 @@ def from_pretrained(
proxies=proxies,
resume_download=resume_download,
local_files_only=local_files_only,
- use_auth_token=use_auth_token,
+ use_auth_token=token,
user_agent=user_agent,
revision=revision,
subfolder=subfolder,
@@ -569,9 +760,9 @@ def from_dict(cls, config_dict: Dict[str, Any], **kwargs) -> "GenerationConfig":
if "_commit_hash" in kwargs and "_commit_hash" in config_dict:
kwargs["_commit_hash"] = config_dict["_commit_hash"]
- # remove all the arguments that are in the config_dict
-
- config = cls(**config_dict, **kwargs)
+ # The line below allows model-specific config to be loaded as well through kwargs, with safety checks.
+ # See https://github.com/huggingface/transformers/pull/21269
+ config = cls(**{**config_dict, **kwargs})
unused_kwargs = config.update(**kwargs)
logger.info(f"Generate config {config}")
diff --git a/src/transformers/generation/flax_logits_process.py b/src/transformers/generation/flax_logits_process.py
index 9e5b6897ce4b..e6b45ded8043 100644
--- a/src/transformers/generation/flax_logits_process.py
+++ b/src/transformers/generation/flax_logits_process.py
@@ -38,7 +38,7 @@
scores (`jnp.ndarray` of shape `(batch_size, config.vocab_size)`):
Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam
search or log softmax for each vocabulary token when using beam search
- kwargs:
+ kwargs (`Dict[str, Any]`, *optional*):
Additional logits processor specific kwargs.
Return:
@@ -129,6 +129,8 @@ class FlaxTopPLogitsWarper(FlaxLogitsWarper):
def __init__(self, top_p: float, filter_value: float = -float("Inf"), min_tokens_to_keep: int = 1):
if not isinstance(top_p, float) or (top_p < 0 or top_p > 1.0):
raise ValueError(f"`top_p` has to be a float > 0 and < 1, but is {top_p}")
+ if not isinstance(min_tokens_to_keep, int) or (min_tokens_to_keep < 1):
+ raise ValueError(f"`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}")
self.top_p = top_p
self.filter_value = filter_value
diff --git a/src/transformers/generation/flax_utils.py b/src/transformers/generation/flax_utils.py
index c28e0afbb998..228bfb4a2e81 100644
--- a/src/transformers/generation/flax_utils.py
+++ b/src/transformers/generation/flax_utils.py
@@ -296,7 +296,7 @@ def generate(
Custom logits processors that complement the default logits processors built from arguments and
generation config. If a logit processor is passed that is already created with the arguments or a
generation config an error is thrown. This feature is intended for advanced users.
- kwargs:
+ kwargs (`Dict[str, Any]`, *optional*):
Ad hoc parametrization of `generate_config` and/or additional model-specific kwargs that will be
forwarded to the `forward` function of the model. If the model is an encoder-decoder model, encoder
specific kwargs should not be prefixed and decoder specific kwargs should be prefixed with *decoder_*.
@@ -319,7 +319,7 @@ def generate(
"You have modified the pretrained model configuration to control generation. This is a"
" deprecated strategy to control generation and will be removed soon, in a future version."
" Please use a generation configuration file (see"
- " https://huggingface.co/docs/transformers/main_classes/text_generation)"
+ " https://huggingface.co/docs/transformers/main_classes/text_generation )"
)
self.generation_config = new_generation_config
generation_config = self.generation_config
@@ -377,15 +377,14 @@ def generate(
# Prepare `max_length` depending on other stopping criteria.
input_ids_seq_length = input_ids.shape[-1]
has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None
- if has_default_max_length and generation_config.max_new_tokens is None:
+ if has_default_max_length and generation_config.max_new_tokens is None and generation_config.max_length != 20:
+ # 20 is the default max_length of the generation config
warnings.warn(
- f"Using `max_length`'s default ({generation_config.max_length}) to control the generation length. "
- "This behaviour is deprecated and will be removed from the config in v5 of Transformers -- we"
- " recommend using `max_new_tokens` to control the maximum length of the generation.",
+ f"Using the model-agnostic default `max_length` (={generation_config.max_length}) "
+ "to control the generation length. recommend setting `max_new_tokens` to control the maximum length of the generation.",
UserWarning,
)
elif generation_config.max_new_tokens is not None:
- generation_config.max_length = generation_config.max_new_tokens + input_ids_seq_length
if not has_default_max_length:
logger.warning(
f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="
@@ -393,6 +392,7 @@ def generate(
"Please refer to the documentation for more information. "
"(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)"
)
+ generation_config.max_length = generation_config.max_new_tokens + input_ids_seq_length
if generation_config.min_length is not None and generation_config.min_length > generation_config.max_length:
raise ValueError(
@@ -463,6 +463,7 @@ def generate(
logits_processor=logits_processor,
trace=trace,
params=params,
+ num_return_sequences=generation_config.num_return_sequences,
model_kwargs=model_kwargs,
)
else:
@@ -749,6 +750,7 @@ def _beam_search(
logits_processor: Optional[FlaxLogitsProcessorList] = None,
trace: bool = True,
params: Optional[Dict[str, jnp.ndarray]] = None,
+ num_return_sequences: Optional[int] = None,
model_kwargs: Optional[Dict[str, jnp.ndarray]] = None,
):
"""
@@ -793,6 +795,9 @@ def gather_fn(tensor):
eos_token_id = eos_token_id if eos_token_id is not None else self.generation_config.eos_token_id
length_penalty = length_penalty if length_penalty is not None else self.generation_config.length_penalty
early_stopping = early_stopping if early_stopping is not None else self.generation_config.early_stopping
+ num_return_sequences = (
+ num_return_sequences if num_return_sequences is not None else self.generation_config.num_return_sequences
+ )
batch_size, num_beams, cur_len = input_ids.shape
@@ -996,8 +1001,8 @@ def beam_search_body_fn(state, input_ids_length=1):
sequences = jnp.where(none_finished[:, None, None], state.sequences, state.running_sequences)
scores = jnp.where(none_finished[:, None], state.scores, state.running_scores)
- # take best beam for each batch
- sequences = sequences[:, 0]
- scores = scores[:, 0]
+ # Take best beams for each batch (the score is sorted in descending order)
+ sequences = flatten_beam_dim(sequences[:, :num_return_sequences, :])
+ scores = flatten_beam_dim(scores[:, :num_return_sequences])
return FlaxBeamSearchOutput(sequences=sequences, scores=scores)
diff --git a/src/transformers/generation/logits_process.py b/src/transformers/generation/logits_process.py
index 95c8064ee404..289d0f955faa 100644
--- a/src/transformers/generation/logits_process.py
+++ b/src/transformers/generation/logits_process.py
@@ -15,7 +15,7 @@
import inspect
import math
-from typing import Callable, Iterable, List, Optional, Tuple, Union
+from typing import Callable, Dict, Iterable, List, Optional, Tuple, Union
import numpy as np
import torch
@@ -30,17 +30,10 @@
LOGITS_PROCESSOR_INPUTS_DOCSTRING = r"""
Args:
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
- Indices of input sequence tokens in the vocabulary.
-
- Indices can be obtained using [`BertTokenizer`]. See [`PreTrainedTokenizer.encode`] and
- [`PreTrainedTokenizer.__call__`] for details.
-
- [What are input IDs?](../glossary#input-ids)
+ Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`):
Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam
search or log softmax for each vocabulary token when using beam search
- kwargs:
- Additional logits processor specific kwargs.
Return:
`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`: The processed prediction scores.
@@ -53,7 +46,6 @@ class LogitsProcessor:
@add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
- """Torch method for processing logits."""
raise NotImplementedError(
f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."
)
@@ -64,7 +56,6 @@ class LogitsWarper:
@add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
- """Torch method for warping logits."""
raise NotImplementedError(
f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."
)
@@ -77,8 +68,22 @@ class LogitsProcessorList(list):
[`LogitsProcessor`] or [`LogitsWarper`] to the inputs.
"""
- @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> torch.FloatTensor:
+ r"""
+ Args:
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
+ scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`):
+ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using
+ beam search or log softmax for each vocabulary token when using beam search
+ kwargs (`Dict[str, Any]`, *optional*):
+ Additional kwargs that are specific to a logits processor.
+
+ Return:
+ `torch.FloatTensor` of shape `(batch_size, config.vocab_size)`:
+ The processed prediction scores.
+
+ """
for processor in self:
function_args = inspect.signature(processor.__call__).parameters
if len(function_args) > 2:
@@ -110,12 +115,13 @@ def __init__(self, min_length: int, eos_token_id: Union[int, List[int]]):
if isinstance(eos_token_id, int):
eos_token_id = [eos_token_id]
- if not all([isinstance(i, int) for i in eos_token_id]) or any([i < 0 for i in eos_token_id]):
+ if not all(isinstance(i, int) for i in eos_token_id) or any(i < 0 for i in eos_token_id):
logger.warning(f"`eos_token_id` has to be a list of positive integers, but is {eos_token_id}")
self.min_length = min_length
self.eos_token_id = eos_token_id
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
cur_len = input_ids.shape[-1]
if cur_len < self.min_length:
@@ -127,14 +133,53 @@ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> to
class MinNewTokensLengthLogitsProcessor(LogitsProcessor):
r"""
[`LogitsProcessor`] enforcing a min-length of new tokens by setting EOS (End-Of-Sequence) token probability to 0.
+ Note that for decoder-only models, such as Llama2, `min_length` will compute the length of `prompt + newly
+ generated tokens` whereas for other models it will behave as `min_new_tokens`, that is, taking only into account
+ the newly generated ones.
Args:
prompt_length_to_skip (`int`):
- The input tokens length.
+ The input tokens length. Not a valid argument when used with `generate` as it will automatically assign the
+ input length.
min_new_tokens (`int`):
The minimum *new* tokens length below which the score of `eos_token_id` is set to `-float("Inf")`.
eos_token_id (`Union[int, List[int]]`):
The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("distilgpt2")
+ >>> model = AutoModelForCausalLM.from_pretrained("distilgpt2")
+ >>> model.config.pad_token_id = model.config.eos_token_id
+ >>> model.generation_config.pad_token_id = model.config.eos_token_id
+ >>> input_context = "Hugging Face Company is"
+ >>> input_ids = tokenizer.encode(input_context, return_tensors="pt")
+
+ >>> # Without `eos_token_id`, it will generate the default length, 20, ignoring `min_new_tokens`
+ >>> outputs = model.generate(input_ids=input_ids, min_new_tokens=30)
+ >>> print(tokenizer.decode(outputs[0], skip_special_tokens=True))
+ Hugging Face Company is a company that has been working on a new product for the past year.
+
+ >>> # If `eos_token_id` is set to ` company` it will take into account how many `min_new_tokens` have been generated
+ >>> # before stopping. Note that ` Company` (5834) and ` company` (1664) are not actually the same token, and even
+ >>> # if they were ` Company` would be ignored by `min_new_tokens` as it excludes the prompt.
+ >>> outputs = model.generate(input_ids=input_ids, min_new_tokens=1, eos_token_id=1664)
+ >>> print(tokenizer.decode(outputs[0], skip_special_tokens=True))
+ Hugging Face Company is a company
+
+ >>> # Increasing `min_new_tokens` will bury the first occurrence of ` company` generating a different sequence.
+ >>> outputs = model.generate(input_ids=input_ids, min_new_tokens=2, eos_token_id=1664)
+ >>> print(tokenizer.decode(outputs[0], skip_special_tokens=True))
+ Hugging Face Company is a new company
+
+ >>> # If no more occurrences of the `eos_token` happen after `min_new_tokens` it returns to the 20 default tokens.
+ >>> outputs = model.generate(input_ids=input_ids, min_new_tokens=10, eos_token_id=1664)
+ >>> print(tokenizer.decode(outputs[0], skip_special_tokens=True))
+ Hugging Face Company is a new and innovative brand of facial recognition technology that is designed to help you
+ ```
"""
def __init__(self, prompt_length_to_skip: int, min_new_tokens: int, eos_token_id: Union[int, List[int]]):
@@ -147,13 +192,14 @@ def __init__(self, prompt_length_to_skip: int, min_new_tokens: int, eos_token_id
if isinstance(eos_token_id, int):
eos_token_id = [eos_token_id]
- if not all([isinstance(i, int) for i in eos_token_id]) or any([i < 0 for i in eos_token_id]):
+ if not all(isinstance(i, int) for i in eos_token_id) or any(i < 0 for i in eos_token_id):
logger.warning(f"`eos_token_id` has to be a list of positive integers, but is {eos_token_id}")
self.prompt_length_to_skip = prompt_length_to_skip
self.min_new_tokens = min_new_tokens
self.eos_token_id = eos_token_id
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
new_tokens_length = input_ids.shape[-1] - self.prompt_length_to_skip
if new_tokens_length < self.min_new_tokens:
@@ -165,11 +211,57 @@ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> to
class TemperatureLogitsWarper(LogitsWarper):
r"""
- [`LogitsWarper`] for temperature (exponential scaling output probability distribution).
+ [`LogitsWarper`] for temperature (exponential scaling output probability distribution), which effectively means
+ that it can control the randomness of the predicted tokens.
+
+
+
+ Make sure that `do_sample=True` is included in the `generate` arguments otherwise the temperature value won't have
+ any effect.
+
+
Args:
temperature (`float`):
- The value used to module the logits distribution.
+ Strictly positive float value used to modulate the logits distribution. A value smaller than `1` decreases
+ randomness (and vice versa), with `0` being equivalent to shifting all probability mass to the most likely
+ token.
+
+ Examples:
+
+ ```python
+ >>> import torch
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("gpt2")
+ >>> model = AutoModelForCausalLM.from_pretrained("gpt2")
+ >>> model.config.pad_token_id = model.config.eos_token_id
+ >>> model.generation_config.pad_token_id = model.config.eos_token_id
+ >>> input_context = "Hugging Face Company is"
+ >>> input_ids = tokenizer.encode(input_context, return_tensors="pt")
+
+ >>> torch.manual_seed(0)
+
+ >>> # With temperature=1, the default, we consistently get random outputs due to random sampling.
+ >>> outputs = model.generate(input_ids=input_ids, max_new_tokens=10, temperature=1, do_sample=True)
+ >>> print(tokenizer.decode(outputs[0], skip_special_tokens=True))
+ Hugging Face Company is one of these companies that is going to take a
+
+ >>> outputs = model.generate(input_ids=input_ids, max_new_tokens=10, temperature=1, do_sample=True)
+ >>> print(tokenizer.decode(outputs[0], skip_special_tokens=True))
+ Hugging Face Company is one of these companies, you can make a very
+
+ >>> # However, with temperature close to 0 , the output remains invariant.
+ >>> outputs = model.generate(input_ids=input_ids, max_new_tokens=10, temperature=0.0001, do_sample=True)
+ >>> print(tokenizer.decode(outputs[0], skip_special_tokens=True))
+ Hugging Face Company is a company that has been around for over 20 years
+
+ >>> # even if we set a different seed.
+ >>> torch.manual_seed(42)
+ >>> outputs = model.generate(input_ids=input_ids, max_new_tokens=10, temperature=0.0001, do_sample=True)
+ >>> print(tokenizer.decode(outputs[0], skip_special_tokens=True))
+ Hugging Face Company is a company that has been around for over 20 years
+ ```
"""
def __init__(self, temperature: float):
@@ -178,19 +270,46 @@ def __init__(self, temperature: float):
self.temperature = temperature
- def __call__(self, input_ids: torch.Tensor, scores: torch.Tensor) -> torch.FloatTensor:
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
scores = scores / self.temperature
return scores
class RepetitionPenaltyLogitsProcessor(LogitsProcessor):
r"""
- [`LogitsProcessor`] enforcing an exponential penalty on repeated sequences.
+ [`LogitsProcessor`] that prevents the repetition of previous tokens through an exponential penalty. This technique
+ shares some similarities with coverage mechanisms and other aimed at reducing repetition. During the text
+ generation process, the probability distribution for the next token is determined using a formula that incorporates
+ token scores based on their occurrence in the generated sequence. Tokens with higher scores are less likely to be
+ selected. The formula can be seen in the original [paper](https://arxiv.org/pdf/1909.05858.pdf). According to the
+ paper a penalty of around 1.2 yields a good balance between truthful generation and lack of repetition.
Args:
repetition_penalty (`float`):
The parameter for repetition penalty. 1.0 means no penalty. See [this
paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.
+
+ Examples:
+
+ ```py
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM
+
+ >>> # Initializing the model and tokenizer for it
+ >>> model = AutoModelForCausalLM.from_pretrained("gpt2")
+ >>> tokenizer = AutoTokenizer.from_pretrained("gpt2")
+ >>> inputs = tokenizer(["I'm not going to"], return_tensors="pt")
+
+ >>> # This shows a normal generate without any specific parameters
+ >>> summary_ids = model.generate(inputs["input_ids"], max_length=20)
+ >>> print(tokenizer.batch_decode(summary_ids, skip_special_tokens=True)[0])
+ I'm not going to lie, I'm not going to lie. I'm not going to lie
+
+ >>> # This generates a penalty for repeated tokens
+ >>> penalized_ids = model.generate(inputs["input_ids"], max_length=20, repetition_penalty=1.2)
+ >>> print(tokenizer.batch_decode(biased_ids, skip_special_tokens=True)[0])
+ I'm not going to lie, I was really excited about this. It's a great game
+ ```
"""
def __init__(self, penalty: float):
@@ -199,6 +318,7 @@ def __init__(self, penalty: float):
self.penalty = penalty
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
score = torch.gather(scores, 1, input_ids)
@@ -227,6 +347,7 @@ def __init__(self, penalty: float, encoder_input_ids: torch.LongTensor):
self.penalty = 1 / penalty
self.encoder_input_ids = encoder_input_ids
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
score = torch.gather(scores, 1, self.encoder_input_ids)
@@ -249,26 +370,59 @@ class TopPLogitsWarper(LogitsWarper):
All filtered values will be set to this float value.
min_tokens_to_keep (`int`, *optional*, defaults to 1):
Minimum number of tokens that cannot be filtered.
+
+ Examples:
+ ```python
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed
+
+ >>> set_seed(0)
+ >>> model = AutoModelForCausalLM.from_pretrained("gpt2")
+ >>> tokenizer = AutoTokenizer.from_pretrained("gpt2")
+
+ >>> text = "It is probably one of the most important things for parents to teach children about patience and acceptance. In this way, we as a society can ensure"
+ >>> inputs = tokenizer(text, return_tensors="pt")
+
+ >>> # Generate sequences without top_p sampling
+ >>> # We see that the answer tends to have a lot of repeated tokens and phrases
+ >>> outputs = model.generate(**inputs, max_length=55)
+ >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
+ 'It is probably one of the most important things for parents to teach children about patience and acceptance. In this way, we as a society can ensure that our children are not taught to be impatient or to be afraid of the future.\n\nThe first step is to teach them'
+
+ >>> # Generate sequences with top_p sampling: set `do_sample=True` to use top_p sampling with `top_p` arugment
+ >>> # We already see that the answer has less repetitive tokens and is more diverse
+ >>> outputs = model.generate(**inputs, max_length=55, do_sample=True, top_p=0.25)
+ >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
+ 'It is probably one of the most important things for parents to teach children about patience and acceptance. In this way, we as a society can ensure that children learn to be more accepting of others and to be more tolerant of others.\n\nWe can also teach children to be'
+
+ >>> # Generate sequences with top_p sampling with a larger top_p value
+ >>> # We see that as we increase the top_p value, less probable tokens also get selected during text generation, making the answer more diverse
+ >>> # Pro Tip: In practice, we tend to use top_p values between 0.9 and 1.0!
+ >>> outputs = model.generate(**inputs, max_length=55, do_sample=True, top_p=0.95)
+ >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
+ 'It is probably one of the most important things for parents to teach children about patience and acceptance. In this way, we as a society can ensure we have the best learning environment, so that we can teach to learn and not just take advantage of the environment.\n\nThe'
+ ```
"""
def __init__(self, top_p: float, filter_value: float = -float("Inf"), min_tokens_to_keep: int = 1):
top_p = float(top_p)
if top_p < 0 or top_p > 1.0:
raise ValueError(f"`top_p` has to be a float > 0 and < 1, but is {top_p}")
+ if not isinstance(min_tokens_to_keep, int) or (min_tokens_to_keep < 1):
+ raise ValueError(f"`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}")
self.top_p = top_p
self.filter_value = filter_value
self.min_tokens_to_keep = min_tokens_to_keep
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
sorted_logits, sorted_indices = torch.sort(scores, descending=False)
cumulative_probs = sorted_logits.softmax(dim=-1).cumsum(dim=-1)
# Remove tokens with cumulative top_p above the threshold (token with 0 are kept)
sorted_indices_to_remove = cumulative_probs <= (1 - self.top_p)
- if self.min_tokens_to_keep > 1:
- # Keep at least min_tokens_to_keep
- sorted_indices_to_remove[..., -self.min_tokens_to_keep :] = 0
+ # Keep at least min_tokens_to_keep
+ sorted_indices_to_remove[..., -self.min_tokens_to_keep :] = 0
# scatter sorted tensors to original indexing
indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove)
@@ -296,6 +450,7 @@ def __init__(self, top_k: int, filter_value: float = -float("Inf"), min_tokens_t
self.top_k = max(top_k, min_tokens_to_keep)
self.filter_value = filter_value
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
top_k = min(self.top_k, scores.size(-1)) # Safety check
# Remove all tokens with a probability less than the last token of the top-k
@@ -322,11 +477,14 @@ def __init__(self, mass: float = 0.9, filter_value: float = -float("Inf"), min_t
mass = float(mass)
if not (mass > 0 and mass < 1):
raise ValueError(f"`typical_p` has to be a float > 0 and < 1, but is {mass}")
+ if not isinstance(min_tokens_to_keep, int) or (min_tokens_to_keep < 1):
+ raise ValueError(f"`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}")
self.filter_value = filter_value
self.mass = mass
self.min_tokens_to_keep = min_tokens_to_keep
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
# calculate entropy
normalized = torch.nn.functional.log_softmax(scores, dim=-1)
@@ -343,9 +501,7 @@ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> to
last_ind = (cumulative_probs < self.mass).sum(dim=1)
last_ind[last_ind < 0] = 0
sorted_indices_to_remove = sorted_scores > sorted_scores.gather(1, last_ind.view(-1, 1))
- if self.min_tokens_to_keep > 1:
- # Keep at least min_tokens_to_keep (set to min_tokens_to_keep-1 because we add the first one below)
- sorted_indices_to_remove[..., : self.min_tokens_to_keep] = 0
+ sorted_indices_to_remove[..., : self.min_tokens_to_keep] = 0
indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove)
scores = scores.masked_fill(indices_to_remove, self.filter_value)
@@ -382,6 +538,7 @@ def __init__(self, epsilon: float, filter_value: float = -float("Inf"), min_toke
self.filter_value = filter_value
self.min_tokens_to_keep = min_tokens_to_keep
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
# Determine which indices to remove
probabilities = scores.softmax(dim=-1)
@@ -397,14 +554,65 @@ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> to
class EtaLogitsWarper(LogitsWarper):
r"""
- [`LogitsWarper`] that performs eta-sampling, i.e. calculates a dynamic cutoff `eta := min(epsilon, sqrt(epsilon,
- e^-entropy(probabilities)))` and restricts to tokens with `prob >= eta`. Takes the largest min_tokens_to_keep
- tokens if no tokens satisfy this constraint. See [Truncation Sampling as Language Model
- Desmoothing](https://arxiv.org/abs/2210.15191) for more information.
+ [`LogitsWarper`] that performs eta-sampling, a technique to filter out tokens with probabilities below a dynamic
+ cutoff value, `eta`, which is calculated based on a combination of the hyperparameter `epsilon` and the entropy of
+ the token probabilities, i.e. `eta := min(epsilon, sqrt(epsilon, e^-entropy(probabilities)))`. Takes the largest
+ min_tokens_to_keep tokens if no tokens satisfy this constraint. It addresses the issue of poor quality in long
+ samples of text generated by neural language models leading to more coherent and fluent text. See [Truncation
+ Sampling as Language Model Desmoothing](https://arxiv.org/abs/2210.15191) for more information. Note: `do_sample`
+ must be set to `True` for this `LogitsWarper` to work.
+
Args:
+ epsilon (`float`):
+ A float value in the range (0, 1). Hyperparameter used to calculate the dynamic cutoff value, `eta`. The
+ suggested values from the paper ranges from 3e-4 to 4e-3 depending on the size of the model.
+ filter_value (`float`, *optional*, defaults to `-float("Inf")`):
+ All values that are found to be below the dynamic cutoff value, `eta`, are set to this float value. This
+ parameter is useful when logits need to be modified for very low probability tokens that should be excluded
+ from generation entirely.
min_tokens_to_keep (`int`, *optional*, defaults to 1):
- Minimum number of tokens that cannot be filtered."""
+ Specifies the minimum number of tokens that must be kept for generation, regardless of their probabilities.
+ For example, if `min_tokens_to_keep` is set to 1, at least one token will always be kept for generation,
+ even if all tokens have probabilities below the cutoff `eta`.
+
+ Examples:
+ ```python
+ >>> # Import required libraries
+ >>> from transformers import AutoModelForCausalLM, AutoTokenizer, set_seed
+
+ >>> # Set the model name
+ >>> model_name = "gpt2"
+
+ >>> # Initialize the model and tokenizer
+ >>> model = AutoModelForCausalLM.from_pretrained(model_name)
+ >>> tokenizer = AutoTokenizer.from_pretrained(model_name)
+
+ >>> # Set the pad token to eos token
+ >>> model.config.pad_token_id = model.config.eos_token_id
+ >>> model.generation_config.pad_token_id = model.config.eos_token_id
+
+ >>> # The below sequence intentionally contains two subjects to show the difference between the two approaches
+ >>> sequence = "a quadcopter flight controller (RTFQ Flip MWC) that supports I2C sensors for adding things like a barometer, magnetometer, and GPS system. The officially supported sensor block (BMP180, HMC5883L on one board) is discontinued, as far as I know, everyone involved lived to sing another day. . . disorder and an extreme state of dysmetabolism characterized by extensive erythema and a significant reduction in uncovered"
+
+ >>> # Tokenize the sequence
+ >>> inputs = tokenizer(sequence, return_tensors="pt")
+
+ >>> set_seed(0)
+
+ >>> # We can see that the model is generating repeating text and also is not able to continue the sequence properly
+ >>> outputs = model.generate(inputs["input_ids"], max_length=128)
+ >>> print(tokenizer.decode(outputs[0], skip_special_tokens=True))
+ a quadcopter flight controller (RTFQ Flip MWC) that supports I2C sensors for adding things like a barometer, magnetometer, and GPS system. The officially supported sensor block (BMP180, HMC5883L on one board) is discontinued, as far as I know, everyone involved lived to sing another day... disorder and an extreme state of dysmetabolism characterized by extensive erythema and a significant reduction in uncovered muscle mass. The patient was diagnosed with a severe erythema and a severe erythema-like condition. The patient was treated with a combination
+
+ >>> # The result is much better and coherent when we use the `eta_cutoff` parameter
+ >>> outputs = model.generate(
+ ... inputs["input_ids"], max_length=128, do_sample=True, eta_cutoff=2e-2
+ ... ) # need to set do_sample=True for eta_cutoff to work
+ >>> print(tokenizer.decode(outputs[0], skip_special_tokens=True))
+ a quadcopter flight controller (RTFQ Flip MWC) that supports I2C sensors for adding things like a barometer, magnetometer, and GPS system. The officially supported sensor block (BMP180, HMC5883L on one board) is discontinued, as far as I know, everyone involved lived to sing another day... disorder and an extreme state of dysmetabolism characterized by extensive erythema and a significant reduction in uncovered fatty acids. A significant loss of brain development. The individual also experienced high levels of a common psychiatric condition called schizophrenia, with an important and life threatening consequence.
+ ```
+ """
def __init__(self, epsilon: float, filter_value: float = -float("Inf"), min_tokens_to_keep: int = 1):
epsilon = float(epsilon)
@@ -421,6 +629,7 @@ def __init__(self, epsilon: float, filter_value: float = -float("Inf"), min_toke
self.filter_value = filter_value
self.min_tokens_to_keep = min_tokens_to_keep
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
# Calculate the adaptive cutoff
probabilities = scores.softmax(dim=-1)
@@ -437,10 +646,28 @@ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> to
def _get_ngrams(ngram_size: int, prev_input_ids: torch.Tensor, num_hypos: int):
+ """
+ Assume ngram_size=2 and prev_input_ids=tensor([[40, 2883, 2712, 4346]]). The output of generated ngrams look like
+ this {(40,): [2883], (2883,): [2712], (2712,): [4346]}.
+
+ Args:
+ ngram_size (`int`):
+ The number sequential tokens taken as a group which may only occur once before being banned.
+ prev_input_ids (`torch.Tensor`):
+ Generated token ids for the current hypothesis.
+ num_hypos (`int`):
+ The number of hypotheses for which n-grams need to be generated.
+
+ Returns:
+ generated_ngrams (`dict`):
+ Dictionary of generated ngrams.
+ """
+ # Initialize an empty list of dictionaries, one for each hypothesis (index) in the range of num_hypos
generated_ngrams = [{} for _ in range(num_hypos)]
for idx in range(num_hypos):
gen_tokens = prev_input_ids[idx].tolist()
generated_ngram = generated_ngrams[idx]
+ # Loop through each n-gram of size ngram_size in the list of tokens (gen_tokens)
for ngram in zip(*[gen_tokens[i:] for i in range(ngram_size)]):
prev_ngram_tuple = tuple(ngram[:-1])
generated_ngram[prev_ngram_tuple] = generated_ngram.get(prev_ngram_tuple, []) + [ngram[-1]]
@@ -448,6 +675,22 @@ def _get_ngrams(ngram_size: int, prev_input_ids: torch.Tensor, num_hypos: int):
def _get_generated_ngrams(banned_ngrams, prev_input_ids, ngram_size, cur_len):
+ """
+ Determines the banned tokens for the current hypothesis based on previously generated n-grams.
+
+ Args:
+ banned_ngrams (`dict`):
+ A dictionary containing previously generated n-grams for each hypothesis.
+ prev_input_ids (`torch.Tensor`):
+ Generated token ids for the current hypothesis.
+ ngram_size (`int`):
+ The number sequential tokens taken as a group which may only occur once before being banned.
+ cur_len (`int`):
+ The current length of the token sequences for which the n-grams are being checked.
+
+ Returns:
+ List of tokens that are banned.
+ """
# Before decoding the next token, prevent decoding of ngrams that have already appeared
start_idx = cur_len + 1 - ngram_size
ngram_idx = tuple(prev_input_ids[start_idx:cur_len].tolist())
@@ -461,9 +704,7 @@ def _calc_banned_ngram_tokens(
if cur_len + 1 < ngram_size:
# return no banned tokens if we haven't generated no_repeat_ngram_size tokens yet
return [[] for _ in range(num_hypos)]
-
generated_ngrams = _get_ngrams(ngram_size, prev_input_ids, num_hypos)
-
banned_tokens = [
_get_generated_ngrams(generated_ngrams[hypo_idx], prev_input_ids[hypo_idx], ngram_size, cur_len)
for hypo_idx in range(num_hypos)
@@ -473,12 +714,43 @@ def _calc_banned_ngram_tokens(
class NoRepeatNGramLogitsProcessor(LogitsProcessor):
r"""
- [`LogitsProcessor`] that enforces no repetition of n-grams. See
+ N-grams are groups of "n" consecutive words, characters, or tokens taken from a sequence of text. Given the
+ sentence: "She runs fast", the bi-grams (n=2) would be ("she", "runs") and ("runs", "fast"). In text generation,
+ avoiding repetitions of word sequences provides a more diverse output. This [`LogitsProcessor`] enforces no
+ repetition of n-grams by setting the scores of banned tokens to negative infinity which eliminates those tokens
+ from consideration when further processing the scores.
[Fairseq](https://github.com/pytorch/fairseq/blob/a07cb6f40480928c9e0548b737aadd36ee66ac76/fairseq/sequence_generator.py#L345).
+
+
+ Use n-gram penalties with care. For instance, penalizing 2-grams (bigrams) in an article about the city of New York
+ might lead to undesirable outcomes where the city's name appears only once in the entire text.
+ [Reference](https://huggingface.co/blog/how-to-generate)
+
+
+
Args:
ngram_size (`int`):
All ngrams of size `ngram_size` can only occur once.
+
+ Examples:
+
+ ```py
+ >>> from transformers import GPT2Tokenizer, AutoModelForCausalLM
+
+ >>> model = AutoModelForCausalLM.from_pretrained("gpt2")
+ >>> tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
+ >>> inputs = tokenizer(["I enjoy watching football"], return_tensors="pt")
+
+ >>> output = model.generate(**inputs, max_length=50)
+ >>> print(tokenizer.decode(output[0], skip_special_tokens=True))
+ "I enjoy playing football on the weekends, but I'm not a big fan of the idea of playing in the middle of the night. I'm not a big fan of the idea of playing in the middle of the night. I'm not a big"
+
+ >>> # Now let's add ngram size using in model.generate. This should stop the repetitions in the output.
+ >>> output = model.generate(**inputs, max_length=50, no_repeat_ngram_size=2)
+ >>> print(tokenizer.decode(output[0], skip_special_tokens=True))
+ I enjoy playing football on the weekends, but I'm not a big fan of the idea of playing in the middle of a game. I think it's a bit of an overreaction to the fact that we're playing a team that's playing"
+ ```
"""
def __init__(self, ngram_size: int):
@@ -486,11 +758,11 @@ def __init__(self, ngram_size: int):
raise ValueError(f"`ngram_size` has to be a strictly positive integer, but is {ngram_size}")
self.ngram_size = ngram_size
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
num_batch_hypotheses = scores.shape[0]
cur_len = input_ids.shape[-1]
banned_batch_tokens = _calc_banned_ngram_tokens(self.ngram_size, input_ids, num_batch_hypotheses, cur_len)
-
for i, banned_tokens in enumerate(banned_batch_tokens):
scores[i, banned_tokens] = -float("inf")
@@ -520,6 +792,7 @@ def __init__(self, encoder_ngram_size: int, encoder_input_ids: torch.LongTensor)
self.batch_size = encoder_input_ids.shape[0]
self.generated_ngrams = _get_ngrams(encoder_ngram_size, encoder_input_ids, self.batch_size)
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
# B x num_beams
num_hypos = scores.shape[0]
@@ -538,138 +811,249 @@ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> to
return scores
-class NoBadWordsLogitsProcessor(LogitsProcessor):
+class SequenceBiasLogitsProcessor(LogitsProcessor):
"""
- [`LogitsProcessor`] that enforces that specified sequences will never be sampled.
+ [`LogitsProcessor`] that applies an additive bias on sequences. The bias is applied to the last token of a sequence
+ when the next generated token can complete it. Consequently, to take the most of biasing sequences with more than
+ one token, consider using beam methods (to gracefully work around partially completed sequences that have a
+ negative bias) and applying the bias to their prefixes (to ensure the bias is applied earlier).
+
+
+
+ In order to get the token ids of the sequences that you want to bias, make sure to set `add_prefix_space=True` when
+ initializing the tokenizer, and use `tokenizer(bad_words, add_special_tokens=False).input_ids`. The
+ `add_prefix_space` argument is only supported for some slow tokenizers, as fast tokenizers' prefixing behaviours
+ come from `pre tokenizers`. Read more [here](https://huggingface.co/docs/tokenizers/api/pre-tokenizers).
+
+
Args:
- bad_words_ids (`List[List[int]]`):
- List of list of token ids that are not allowed to be generated. In order to get the token ids of the words
- that should not appear in the generated text, use `tokenizer(bad_words, add_prefix_space=True,
- add_special_tokens=False).input_ids`.
- eos_token_id (`Union[int, List[int]]`):
- The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
+ sequence_bias (`Dict[Tuple[int], float]`):
+ Dictionary that maps a sequence of tokens to its bias term. Positive biases increase the odds of the
+ sequence being selected, while negative biases do the opposite. If a sequence has a length of 1, its bias
+ will always be applied. Otherwise, the bias will only be applied if the sequence in question is about to be
+ completed (in the token selection step after this processor is applied).
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM
+
+ >>> model = AutoModelForCausalLM.from_pretrained("gpt2")
+ >>> tokenizer = AutoTokenizer.from_pretrained("gpt2")
+ >>> inputs = tokenizer(["The full name of Donald is Donald"], return_tensors="pt")
+
+ >>> summary_ids = model.generate(inputs["input_ids"], max_new_tokens=4)
+ >>> print(tokenizer.batch_decode(summary_ids, skip_special_tokens=True)[0])
+ The full name of Donald is Donald J. Trump Jr
+
+ >>> # Now let's control generation through a bias. Please note that the tokenizer is initialized differently!
+ >>> tokenizer_with_prefix_space = AutoTokenizer.from_pretrained("gpt2", add_prefix_space=True)
+
+
+ >>> def get_tokens_as_tuple(word):
+ ... return tuple(tokenizer_with_prefix_space([word], add_special_tokens=False).input_ids[0])
+
+
+ >>> # If we add a negative bias without beam search, it may become "stuck" in a prefix without good continuations
+ >>> sequence_bias = {get_tokens_as_tuple("Trump"): -10.0}
+ >>> biased_ids = model.generate(inputs["input_ids"], max_new_tokens=4, sequence_bias=sequence_bias)
+ >>> print(tokenizer.batch_decode(biased_ids, skip_special_tokens=True)[0])
+ The full name of Donald is Donald J. Donald,
+
+ >>> biased_ids = model.generate(inputs["input_ids"], max_new_tokens=4, num_beams=4, sequence_bias=sequence_bias)
+ >>> print(tokenizer.batch_decode(biased_ids, skip_special_tokens=True)[0])
+ The full name of Donald is Donald Rumsfeld,
+
+ >>> # We can also add a positive bias to nudge the model towards specific tokens or continuations
+ >>> sequence_bias = {get_tokens_as_tuple("Donald Duck"): 10.0}
+ >>> biased_ids = model.generate(inputs["input_ids"], max_new_tokens=4, num_beams=4, sequence_bias=sequence_bias)
+ >>> print(tokenizer.batch_decode(biased_ids, skip_special_tokens=True)[0])
+ The full name of Donald is Donald Duck.
+ ```
"""
- def __init__(self, bad_words_ids: List[List[int]], eos_token_id: Union[int, List[int]]):
- if not isinstance(bad_words_ids, List) or len(bad_words_ids) == 0:
- raise ValueError(f"`bad_words_ids` has to be a non-empty list, but is {bad_words_ids}.")
- if any(not isinstance(bad_word_ids, list) for bad_word_ids in bad_words_ids):
- raise ValueError(f"`bad_words_ids` has to be a list of lists, but is {bad_words_ids}.")
+ def __init__(self, sequence_bias: Dict[Tuple[int], float]):
+ self.sequence_bias = sequence_bias
+ self._validate_arguments()
+
+ # Bias variables that will be populated on the first call (for retrocompatibility purposes, the vocabulary size
+ # is infered in the first usage, which inhibits initializing here)
+ self.length_1_bias = None
+ self.prepared_bias_variables = False
+
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
+ # 1 - Prepares the bias tensors. This is only needed the first time the logit processor is called.
+ if not self.prepared_bias_variables:
+ self._prepare_bias_variables(scores)
+
+ # 2 - prepares an empty bias to add
+ bias = torch.zeros_like(scores)
+
+ # 3 - include the bias from length = 1
+ bias += self.length_1_bias
+
+ # 4 - include the bias from length > 1, after determining which biased sequences may be completed.
+ for sequence_ids, sequence_bias in self.sequence_bias.items():
+ if len(sequence_ids) == 1: # the sequence is of length 1, already applied
+ continue
+ if len(sequence_ids) > input_ids.shape[1]: # the sequence is longer than the context, ignore
+ continue
+ prefix_length = len(sequence_ids) - 1
+ last_token = sequence_ids[-1]
+ matching_rows = torch.eq(
+ input_ids[:, -prefix_length:],
+ torch.tensor(sequence_ids[:-1], dtype=input_ids.dtype, device=input_ids.device),
+ ).prod(dim=1)
+ bias[:, last_token] += torch.where(
+ matching_rows.bool(),
+ torch.tensor(sequence_bias, device=input_ids.device),
+ torch.tensor(0.0, device=input_ids.device),
+ )
+
+ # 5 - apply the bias to the scores
+ scores = scores + bias
+ return scores
+
+ def _prepare_bias_variables(self, scores: torch.FloatTensor):
+ vocabulary_size = scores.shape[-1]
+
+ # Check biased tokens out of bounds
+ invalid_biases = []
+ for sequence_ids in self.sequence_bias:
+ for token_id in sequence_ids:
+ if token_id >= vocabulary_size:
+ invalid_biases.append(token_id)
+ if len(invalid_biases) > 0:
+ raise ValueError(
+ f"The model vocabulary size is {vocabulary_size}, but the following tokens were being biased: "
+ f"{invalid_biases}"
+ )
+
+ # Precompute the bias tensors to be applied. Sequences of length 1 are kept separately, as they can be applied
+ # with simpler logic.
+ self.length_1_bias = torch.zeros((vocabulary_size,), dtype=torch.float).to(scores.device)
+ for sequence_ids, bias in self.sequence_bias.items():
+ if len(sequence_ids) == 1:
+ self.length_1_bias[sequence_ids[-1]] = bias
+
+ self.prepared_bias_variables = True
+
+ def _validate_arguments(self):
+ sequence_bias = self.sequence_bias
+ if not isinstance(sequence_bias, dict) or len(sequence_bias) == 0:
+ raise ValueError(f"`sequence_bias` has to be a non-empty dictionary, but is {sequence_bias}.")
+ if any(not isinstance(sequence_ids, tuple) for sequence_ids in sequence_bias.keys()):
+ raise ValueError(f"`sequence_bias` has to be a dict with tuples as keys, but is {sequence_bias}.")
if any(
- any((not isinstance(token_id, (int, np.integer)) or token_id < 0) for token_id in bad_word_ids)
- for bad_word_ids in bad_words_ids
+ any((not isinstance(token_id, (int, np.integer)) or token_id < 0) for token_id in sequence_ids)
+ or len(sequence_ids) == 0
+ for sequence_ids in sequence_bias.keys()
):
raise ValueError(
- f"Each list in `bad_words_ids` has to be a list of positive integers, but is {bad_words_ids}."
+ f"Each key in `sequence_bias` has to be a non-empty tuple of positive integers, but is "
+ f"{sequence_bias}."
)
+ if any(not isinstance(bias, float) for bias in sequence_bias.values()):
+ raise ValueError(f"`sequence_bias` has to be a dict with floats as values, but is {sequence_bias}.")
- if eos_token_id is None:
- eos_token_id = []
- if isinstance(eos_token_id, int):
- eos_token_id = [eos_token_id]
- bad_words_ids = list(
- filter(lambda bad_token_seq: all([bad_token_seq != [i] for i in eos_token_id]), bad_words_ids)
- )
- self.bad_words_id_length_1 = []
- self.bad_words_id_length_greater_than_1 = []
- for word in bad_words_ids:
- if len(word) == 1:
- self.bad_words_id_length_1.append(word[0])
- else:
- self.bad_words_id_length_greater_than_1.append(word)
+class NoBadWordsLogitsProcessor(SequenceBiasLogitsProcessor):
+ """
+ [`LogitsProcessor`] that enforces that specified sequences will never be selected.
- self.static_bad_words_mask: Optional[torch.LongTensor] = None
+
- for banned_token_seq in self.bad_words_id_length_greater_than_1:
- if len(banned_token_seq) == 0:
- raise ValueError(f"Banned words token sequences {bad_words_ids} cannot have an empty list")
+ In order to get the token ids of the words that should not appear in the generated text, make sure to set
+ `add_prefix_space=True` when initializing the tokenizer, and use `tokenizer(bad_words,
+ add_special_tokens=False).input_ids`. The `add_prefix_space` argument is only supported for some slow tokenizers,
+ as fast tokenizers' prefixing behaviours come from `pre tokenizers`. Read more
+ [here](https://huggingface.co/docs/tokenizers/api/pre-tokenizers).
- def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
- if self.static_bad_words_mask is None and len(self.bad_words_id_length_1) > 0:
- self.static_bad_words_mask = self._calc_static_bad_word_mask(scores)
+
- dynamic_banned_tokens = self._calc_banned_bad_words_ids(input_ids.tolist())
- scores = self._set_scores_to_inf_for_banned_tokens(scores, dynamic_banned_tokens)
+ Args:
+ bad_words_ids (`List[List[int]]`):
+ List of list of token ids that are not allowed to be generated.
+ eos_token_id (`Union[int, List[int]]`):
+ The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
- return scores
+ Examples:
- def _calc_static_bad_word_mask(self, scores: torch.FloatTensor) -> torch.BoolTensor:
- static_bad_words_mask = torch.zeros(scores.shape[1])
- static_bad_words_mask[self.bad_words_id_length_1] = 1
- return static_bad_words_mask.unsqueeze(0).to(scores.device).bool()
-
- def _tokens_match(self, prev_tokens: List[int], tokens: List[int]) -> bool:
- if len(tokens) == 0:
- # if bad word tokens is just one token always ban it
- return True
- elif len(tokens) > len(prev_tokens):
- # if bad word tokens are longer then prev input_ids they can't be equal
- return False
- else:
- return prev_tokens[-len(tokens) :] == tokens
+ ```python
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM
- def _calc_banned_bad_words_ids(self, prev_input_ids: List[List[int]]) -> Iterable[int]:
- banned_tokens = []
- for prev_input_ids_slice in prev_input_ids:
- banned_tokens_slice = []
- for banned_token_seq in self.bad_words_id_length_greater_than_1:
- if self._tokens_match(prev_input_ids_slice, banned_token_seq[:-1]):
- banned_tokens_slice.append(banned_token_seq[-1])
+ >>> model = AutoModelForCausalLM.from_pretrained("gpt2")
+ >>> tokenizer = AutoTokenizer.from_pretrained("gpt2")
+ >>> inputs = tokenizer(["In a word, the cake is a"], return_tensors="pt")
- banned_tokens.append(banned_tokens_slice)
+ >>> summary_ids = model.generate(inputs["input_ids"], max_new_tokens=5, pad_token_id=tokenizer.eos_token_id)
+ >>> print(tokenizer.batch_decode(summary_ids, skip_special_tokens=True)[0])
+ In a word, the cake is a bit of a mess.
- return banned_tokens
+ >>> # Now let's control generation taking the bad words out. Please note that the tokenizer is initialized differently
- def _set_scores_to_inf_for_banned_tokens(
- self, scores: torch.Tensor, banned_tokens: List[List[int]]
- ) -> torch.Tensor:
- """
- Modifies the scores in place by setting the banned token positions to `-inf`. Banned token is expected to be a
- list of list of banned tokens to ban in the format [[batch index, vocabulary position],...
+ >>> tokenizer_with_prefix_space = AutoTokenizer.from_pretrained("gpt2", add_prefix_space=True)
- Args:
- scores: logits distribution of shape (batch size, vocabulary size)
- banned_tokens: list of list of tokens to ban of length (batch_size)
- """
- banned_mask_list = []
- for idx, batch_banned_tokens in enumerate(banned_tokens):
- for token in batch_banned_tokens:
- # Eliminates invalid bad word IDs that are over the vocabulary size.
- if token <= scores.shape[1]:
- banned_mask_list.append([idx, token])
- else:
- logger.error(
- f"An invalid bad word ID is defined: {token}. This ID is not contained in the "
- "vocabulary, and is therefore ignored."
- )
- if not banned_mask_list and self.static_bad_words_mask is None:
- return scores
- else:
- if banned_mask_list:
- banned_mask = torch.LongTensor(banned_mask_list)
- indices = torch.ones(len(banned_mask))
- # A sparse tensor is generated from a list of coordinates: [[0, 1], [0, 2], [2, 0]]. A conversion to dense tensor generates:
- # [ 0 1 1 ]
- # [ 0 0 0 ]
- # [ 1 0 0 ]
-
- banned_mask = (
- torch.sparse.LongTensor(banned_mask.t(), indices, scores.size())
- .to(scores.device)
- .to_dense()
- .bool()
- )
+ >>> def get_tokens_as_list(word_list):
+ ... "Converts a sequence of words into a list of tokens"
+ ... tokens_list = []
+ ... for word in word_list.split(" "):
+ ... tokenized_word = tokenizer_with_prefix_space([word], add_special_tokens=False).input_ids[0]
+ ... tokens_list.append(tokenized_word)
+ ... return tokens_list
- if self.static_bad_words_mask is not None:
- banned_mask = torch.bitwise_or(banned_mask, self.static_bad_words_mask)
- else:
- banned_mask = self.static_bad_words_mask
- scores = scores.masked_fill(banned_mask, -float("inf"))
- return scores
+ >>> word_list = "mess"
+ >>> bad_words_ids = get_tokens_as_list(word_list=word_list)
+
+ >>> badwords_ids = model.generate(
+ ... inputs["input_ids"],
+ ... max_new_tokens=5,
+ ... bad_words_ids=bad_words_ids,
+ ... eos_token_id=tokenizer_with_prefix_space.eos_token_id,
+ ... )
+ >>> print(tokenizer.batch_decode(badwords_ids, skip_special_tokens=True)[0])
+ In a word, the cake is a bit of a surprise.
+
+ >>> badwords_ids = model.generate(inputs["input_ids"], max_new_tokens=4, num_beams=5, bad_words_ids=bad_words_ids)
+ >>> print(tokenizer.batch_decode(biased_ids, skip_special_tokens=True)[0])
+ In a word, the cake is a great way to start
+ ```
+ """
+
+ def __init__(self, bad_words_ids: List[List[int]], eos_token_id: Union[int, List[int]]):
+ self.bad_word_ids = bad_words_ids
+ self._validate_arguments()
+
+ # Filter EOS token from bad_words_ids
+ if eos_token_id is None:
+ eos_token_id = []
+ if isinstance(eos_token_id, int):
+ eos_token_id = [eos_token_id]
+ bad_words_ids = list(
+ filter(lambda bad_token_seq: all(bad_token_seq != [i] for i in eos_token_id), bad_words_ids)
+ )
+
+ # Forbidding a sequence is equivalent to setting its bias to -inf
+ sequence_bias = {tuple(sequence): float("-inf") for sequence in bad_words_ids}
+ super().__init__(sequence_bias=sequence_bias)
+
+ def _validate_arguments(self):
+ bad_words_ids = self.bad_word_ids
+ if not isinstance(bad_words_ids, list) or len(bad_words_ids) == 0:
+ raise ValueError(f"`bad_words_ids` has to be a non-empty list, but is {bad_words_ids}.")
+ if any(not isinstance(bad_word_ids, list) for bad_word_ids in bad_words_ids):
+ raise ValueError(f"`bad_words_ids` has to be a list of lists, but is {bad_words_ids}.")
+ if any(
+ any((not isinstance(token_id, (int, np.integer)) or token_id < 0) for token_id in bad_word_ids)
+ for bad_word_ids in bad_words_ids
+ ):
+ raise ValueError(
+ f"Each list in `bad_words_ids` has to be a list of positive integers, but is {bad_words_ids}."
+ )
class PrefixConstrainedLogitsProcessor(LogitsProcessor):
@@ -678,7 +1062,7 @@ class PrefixConstrainedLogitsProcessor(LogitsProcessor):
generation. See [Autoregressive Entity Retrieval](https://arxiv.org/abs/2010.00904) for more information.
Args:
- prefix_allowed_tokens_fn: (`Callable[[int, torch.Tensor], List[int]]`):
+ prefix_allowed_tokens_fn (`Callable[[int, torch.Tensor], List[int]]`):
This function constraints the beam search to allowed tokens only at each step. This function takes 2
arguments `inputs_ids` and the batch ID `batch_id`. It has to return a list with the allowed tokens for the
next generation step conditioned on the previously generated tokens `inputs_ids` and the batch ID
@@ -689,6 +1073,7 @@ def __init__(self, prefix_allowed_tokens_fn: Callable[[int, torch.Tensor], List[
self._prefix_allowed_tokens_fn = prefix_allowed_tokens_fn
self._num_beams = num_beams
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
mask = torch.full_like(scores, -math.inf)
for batch_id, beam_sent in enumerate(input_ids.view(-1, self._num_beams, input_ids.shape[-1])):
@@ -736,6 +1121,23 @@ def __call__(
current_tokens: torch.LongTensor,
beam_group_idx: int,
) -> torch.FloatTensor:
+ r"""
+ Args:
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
+ scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`):
+ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using
+ beam search or log softmax for each vocabulary token when using beam search
+ current_tokens (`torch.LongTensor` of shape `(batch_size)`):
+ Indices of input sequence tokens in the vocabulary, corresponding to the tokens selected by the other
+ beam groups in the current generation step.
+ beam_group_idx (`int`):
+ The index of the beam group currently being processed.
+
+ Return:
+ `torch.FloatTensor` of shape `(batch_size, config.vocab_size)`:
+ The processed prediction scores.
+ """
# hamming diversity: penalise using same token in current group which was used in previous groups at
# the same time step
batch_size = current_tokens.shape[0] // self._num_beams
@@ -770,6 +1172,7 @@ class ForcedBOSTokenLogitsProcessor(LogitsProcessor):
def __init__(self, bos_token_id: int):
self.bos_token_id = bos_token_id
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
cur_len = input_ids.shape[-1]
if cur_len == 1:
@@ -797,6 +1200,7 @@ def __init__(self, max_length: int, eos_token_id: Union[int, List[int]]):
eos_token_id = [eos_token_id]
self.eos_token_id = eos_token_id
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
cur_len = input_ids.shape[-1]
if cur_len == self.max_length - 1:
@@ -813,6 +1217,7 @@ class InfNanRemoveLogitsProcessor(LogitsProcessor):
the logits processor should only be used if necessary since it can slow down the generation method.
"""
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
# set all nan values to 0.0
scores[scores != scores] = 0.0
@@ -850,7 +1255,8 @@ def __init__(
eos_token_id = [eos_token_id]
self.eos_token_id = eos_token_id
- def __call__(self, input_ids: torch.Tensor, scores: torch.Tensor) -> torch.FloatTensor:
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
cur_len = input_ids.shape[-1]
if cur_len > self.regulation_start:
for i in self.eos_token_id:
@@ -866,7 +1272,8 @@ class LogitNormalization(LogitsProcessor, LogitsWarper):
the scores are normalized when comparing the hypotheses.
"""
- def __call__(self, input_ids: torch.Tensor, scores: torch.Tensor) -> torch.Tensor:
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
scores = scores.log_softmax(dim=-1)
return scores
@@ -882,7 +1289,8 @@ def __init__(self, begin_suppress_tokens, begin_index):
self.begin_suppress_tokens = list(begin_suppress_tokens)
self.begin_index = begin_index
- def __call__(self, input_ids, scores):
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
if input_ids.shape[1] == self.begin_index:
scores[:, self.begin_suppress_tokens] = -float("inf")
@@ -896,7 +1304,8 @@ class SuppressTokensLogitsProcessor(LogitsProcessor):
def __init__(self, suppress_tokens):
self.suppress_tokens = list(suppress_tokens)
- def __call__(self, input_ids, scores):
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
scores[:, self.suppress_tokens] = -float("inf")
return scores
@@ -909,7 +1318,8 @@ class ForceTokensLogitsProcessor(LogitsProcessor):
def __init__(self, force_token_map: List[List[int]]):
self.force_token_map = dict(force_token_map)
- def __call__(self, input_ids, scores):
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
generation_idx = input_ids.shape[-1]
current_token = self.force_token_map.get(generation_idx, None)
if current_token is not None:
@@ -945,7 +1355,8 @@ def __init__(self, generate_config): # support for the kwargs
self.begin_index -= 1
self.max_initial_timestamp_index = generate_config.max_initial_timestamp_index
- def __call__(self, input_ids, scores):
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
# suppress <|notimestamps|> which is handled by without_timestamps
scores[:, self.no_timestamps_token_id] = -float("inf")
@@ -980,3 +1391,200 @@ def __call__(self, input_ids, scores):
scores[k, : self.timestamp_begin] = -float("inf")
return scores
+
+
+class ClassifierFreeGuidanceLogitsProcessor(LogitsProcessor):
+ r"""Logits processor for classifier free guidance (CFG). The scores are split over the batch dimension,
+ where the first half correspond to the conditional logits (predicted from the input prompt) and the second half
+ correspond to the unconditional logits (predicted from an empty or 'null' prompt). The processor computes a
+ weighted average across the conditional and unconditional logits, parameterised by the `guidance_scale`.
+
+ Args:
+ guidance_scale (float):
+ The guidance scale for classifier free guidance (CFG). CFG is enabled by setting `guidance_scale > 1`.
+ Higher guidance scale encourages the model to generate samples that are more closely linked to the input
+ prompt, usually at the expense of poorer quality.
+ """
+
+ def __init__(self, guidance_scale):
+ if guidance_scale > 1:
+ self.guidance_scale = guidance_scale
+ else:
+ raise ValueError(
+ "Require guidance scale >1 to use the classifier free guidance processor, got guidance scale "
+ f"{guidance_scale}."
+ )
+
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
+ # simple check to make sure we have compatible batch sizes between our
+ # logits scores (cond + uncond) and input ids (cond only)
+ if scores.shape[0] != 2 * input_ids.shape[0]:
+ raise ValueError(
+ f"Logits should have twice the batch size of the input ids, the first half of batches corresponding to "
+ f"the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got "
+ f"batch size {scores.shape[0]} for the logits and {input_ids.shape[0]} for the input ids."
+ )
+ unguided_bsz = scores.shape[0] // 2
+ cond_logits, uncond_logits = scores.split(unguided_bsz, dim=0)
+ scores = uncond_logits + (cond_logits - uncond_logits) * self.guidance_scale
+ return scores
+
+
+class AlternatingCodebooksLogitsProcessor(LogitsProcessor):
+ r"""
+ [`LogitsProcessor`] enforcing alternated generation between the two codebooks of [`Bark`]'s fine submodel.
+
+ Args:
+ input_start_len (`int`):
+ The length of the initial input sequence.
+ semantic_vocab_size (`int`):
+ Vocabulary size of the semantic part, i.e number of tokens associated to the semantic vocabulary.
+ codebook_size (`int`):
+ Number of tokens associated to the codebook.
+ """
+
+ def __init__(self, input_start_len: int, semantic_vocab_size: int, codebook_size: int):
+ if not isinstance(input_start_len, int) or input_start_len < 0:
+ raise ValueError(f"`input_starting_length` has to be a non-negative integer, but is {input_start_len}")
+
+ self.input_start_len = input_start_len
+ self.semantic_vocab_size = semantic_vocab_size
+ self.codebook_size = codebook_size
+
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
+ curr_len = input_ids.shape[-1]
+
+ # even -> first codebook, odd -> second codebook
+ is_first_codebook = ((curr_len - self.input_start_len) % 2) == 0
+
+ if is_first_codebook:
+ scores[:, : self.semantic_vocab_size] = -float("inf")
+ scores[:, self.semantic_vocab_size + self.codebook_size :] = -float("inf")
+ else:
+ scores[:, : self.semantic_vocab_size + self.codebook_size] = -float("inf")
+
+ return scores
+
+
+class UnbatchedClassifierFreeGuidanceLogitsProcessor(LogitsProcessor):
+ r"""Logits processor for Classifier-Free Guidance (CFG). The processors
+ computes a weighted average across scores from prompt conditional and prompt unconditional (or negative) logits,
+ parameterized by the `guidance_scale`. The unconditional scores are computed internally by prompting `model` with
+ the `unconditional_ids` branch.
+
+ See [the paper](https://arxiv.org/abs/2306.17806) for more information.
+
+ Args:
+ guidance_scale (`float`):
+ The guidance scale for classifier free guidance (CFG). CFG is enabled by setting `guidance_scale != 1`.
+ Higher guidance scale encourages the model to generate samples that are more closely linked to the input
+ prompt, usually at the expense of poorer quality. A value smaller than 1 has the opposite effect, while
+ making the negative prompt provided with negative_prompt_ids (if any) act as a positive prompt.
+ unconditional_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Indices of input sequence tokens in the vocabulary for the unconditional branch. If unset, will default to
+ the last token of the prompt.
+ unconditional_attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, **optional**):
+ Attention mask for unconditional_ids.
+ model (`PreTrainedModel`):
+ The model computing the unconditional scores. Supposedly the same as the one computing the conditional
+ scores. Both models must use the same tokenizer.
+ smooth_factor (`float`, **optional**):
+ The interpolation weight for CFG Rescale. 1 means no rescaling, 0 reduces to the conditional scores without
+ CFG. Turn it lower if the output degenerates.
+ use_cache (`bool`, **optional**):
+ Whether to cache key/values during the negative prompt forward pass.
+
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM
+
+ >>> model = AutoModelForCausalLM.from_pretrained("gpt2")
+ >>> tokenizer = AutoTokenizer.from_pretrained("gpt2")
+ >>> inputs = tokenizer(["Today, a dragon flew over Paris, France,"], return_tensors="pt")
+ >>> out = model.generate(inputs["input_ids"], guidance_scale=1.5)
+ >>> tokenizer.batch_decode(out, skip_special_tokens=True)[0]
+ The dragon flew over Paris, France, landing in Lyon, a city of a few million. Dragon-flying was a new form of
+ transport, and the dragon was the first in Europe.
+
+ >>> # with a negative prompt
+ >>> neg_inputs = tokenizer(["A very happy event happened,"], return_tensors="pt")
+ >>> out = model.generate(inputs["input_ids"], guidance_scale=2, negative_prompt_ids=neg_inputs["input_ids"])
+ >>> tokenizer.batch_decode(out, skip_special_tokens=True)[0]
+ The dragon flew over Paris, France, crashing into Notre Dame Cathedral in the French capital killing at least 127
+ people and injuring more than 350.
+
+ >>> # with a positive prompt
+ >>> neg_inputs = tokenizer(["A very happy event happened,"], return_tensors="pt")
+ >>> out = model.generate(inputs["input_ids"], guidance_scale=0, negative_prompt_ids=neg_inputs["input_ids"])
+ >>> tokenizer.batch_decode(out, skip_special_tokens=True)[0]
+ Today, a dragon flew over Paris, France, and I'm very happy to be here.
+ ```
+ """
+
+ def __init__(
+ self,
+ guidance_scale: float,
+ model,
+ unconditional_ids: Optional[torch.LongTensor] = None,
+ unconditional_attention_mask: Optional[torch.LongTensor] = None,
+ use_cache: Optional[bool] = True,
+ ):
+ self.guidance_scale = guidance_scale
+ self.model = model
+ self.unconditional_context = {
+ "input_ids": unconditional_ids,
+ "attention_mask": unconditional_attention_mask,
+ "use_cache": use_cache,
+ "past_key_values": None,
+ "first_pass": True,
+ }
+
+ def get_unconditional_logits(self, input_ids):
+ if self.unconditional_context["first_pass"]:
+ if self.unconditional_context["input_ids"] is None:
+ self.unconditional_context["input_ids"] = input_ids[:, -1:]
+ if self.unconditional_context["attention_mask"] is None:
+ self.unconditional_context["attention_mask"] = torch.ones_like(
+ self.unconditional_context["input_ids"], dtype=torch.long
+ )
+ input_ids = self.unconditional_context["input_ids"]
+ attention_mask = self.unconditional_context["attention_mask"]
+ self.unconditional_context["first_pass"] = False
+ else:
+ attention_mask = torch.cat(
+ [
+ self.unconditional_context["attention_mask"],
+ torch.ones_like(input_ids[:, -1:], dtype=torch.long),
+ ],
+ dim=1,
+ )
+ if not self.unconditional_context["use_cache"]:
+ input_ids = torch.cat([self.unconditional_context["input_ids"], input_ids[:, -1:]], dim=1)
+ else:
+ input_ids = input_ids[:, -1:]
+ self.unconditional_context["input_ids"] = input_ids
+ self.unconditional_context["attention_mask"] = attention_mask
+
+ out = self.model(
+ input_ids,
+ attention_mask=attention_mask,
+ use_cache=self.unconditional_context["use_cache"],
+ past_key_values=self.unconditional_context["past_key_values"],
+ )
+ self.unconditional_context["past_key_values"] = out.get("past_key_values", None)
+
+ return out.logits
+
+ def __call__(self, input_ids, scores):
+ scores = torch.nn.functional.log_softmax(scores, dim=-1)
+ if self.guidance_scale == 1:
+ return scores
+
+ logits = self.get_unconditional_logits(input_ids)
+
+ unconditional_logits = torch.nn.functional.log_softmax(logits[:, -1], dim=-1)
+ out = self.guidance_scale * (scores - unconditional_logits) + unconditional_logits
+ return out
diff --git a/src/transformers/generation/stopping_criteria.py b/src/transformers/generation/stopping_criteria.py
index 7023fa9998c9..4e0a294e7c34 100644
--- a/src/transformers/generation/stopping_criteria.py
+++ b/src/transformers/generation/stopping_criteria.py
@@ -6,7 +6,10 @@
import torch
-from ..utils import add_start_docstrings
+from ..utils import add_start_docstrings, logging
+
+
+logger = logging.get_logger(__name__)
STOPPING_CRITERIA_INPUTS_DOCSTRING = r"""
@@ -14,14 +17,14 @@
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary.
- Indices can be obtained using [`BertTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
[`PreTrainedTokenizer.__call__`] for details.
[What are input IDs?](../glossary#input-ids)
scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`):
Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax
or scores for each vocabulary token after SoftMax.
- kwargs:
+ kwargs (`Dict[str, Any]`, *optional*):
Additional stopping criteria specific kwargs.
Return:
@@ -46,14 +49,25 @@ class MaxLengthCriteria(StoppingCriteria):
Args:
max_length (`int`):
The maximum length that the output sequence can have in number of tokens.
+ max_position_embeddings (`int`, `optional`):
+ The maximum model length, as defined by the model's `config.max_position_embeddings` attribute.
"""
- def __init__(self, max_length: int):
+ def __init__(self, max_length: int, max_position_embeddings: Optional[int] = None):
self.max_length = max_length
+ self.max_position_embeddings = max_position_embeddings
@add_start_docstrings(STOPPING_CRITERIA_INPUTS_DOCSTRING)
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
- return input_ids.shape[-1] >= self.max_length
+ cur_len = input_ids.shape[-1]
+ is_done = cur_len >= self.max_length
+ if self.max_position_embeddings is not None and not is_done and cur_len >= self.max_position_embeddings:
+ logger.warning_once(
+ "This is a friendly reminder - the current text generation call will exceed the model's predefined "
+ f"maximum length ({self.max_position_embeddings}). Depending on the model, you may observe "
+ "exceptions, performance degradation, or nothing at all."
+ )
+ return is_done
class MaxNewTokensCriteria(StoppingCriteria):
diff --git a/src/transformers/generation/streamers.py b/src/transformers/generation/streamers.py
index 4a6226c0b7b5..4b299db5da69 100644
--- a/src/transformers/generation/streamers.py
+++ b/src/transformers/generation/streamers.py
@@ -81,7 +81,7 @@ def __init__(self, tokenizer: "AutoTokenizer", skip_prompt: bool = False, **deco
def put(self, value):
"""
- Recives tokens, decodes them, and prints them to stdout as soon as they form entire words.
+ Receives tokens, decodes them, and prints them to stdout as soon as they form entire words.
"""
if len(value.shape) > 1 and value.shape[0] > 1:
raise ValueError("TextStreamer only supports batch size 1")
diff --git a/src/transformers/generation/tf_logits_process.py b/src/transformers/generation/tf_logits_process.py
index 369c969526a4..02e33caf79ac 100644
--- a/src/transformers/generation/tf_logits_process.py
+++ b/src/transformers/generation/tf_logits_process.py
@@ -42,7 +42,7 @@
cur_len (`int`):
The current length of valid input sequence tokens. In the TF implementation, the input_ids' sequence length
is the maximum length generate can produce, and we need to know which of its tokens are valid.
- kwargs:
+ kwargs (`Dict[str, Any]`, *optional*):
Additional logits processor specific kwargs.
Return:
@@ -160,6 +160,8 @@ class TFTopPLogitsWarper(TFLogitsWarper):
def __init__(self, top_p: float, filter_value: float = -float("Inf"), min_tokens_to_keep: int = 1):
if not isinstance(top_p, float) or (top_p < 0 or top_p > 1.0):
raise ValueError(f"`top_p` has to be a float > 0 and < 1, but is {top_p}")
+ if not isinstance(min_tokens_to_keep, int) or (min_tokens_to_keep < 1):
+ raise ValueError(f"`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}")
self.top_p = top_p
self.filter_value = filter_value
@@ -290,7 +292,10 @@ class TFNoBadWordsLogitsProcessor(TFLogitsProcessor):
Args:
bad_words_ids (`List[List[int]]`):
List of list of token ids that are not allowed to be generated. In order to get the tokens of the words
- that should not appear in the generated text, use `tokenizer(bad_word, add_prefix_space=True).input_ids`.
+ that should not appear in the generated text, make sure to set `add_prefix_space=True` when initializing
+ the tokenizer, and use `tokenizer(bad_words, add_special_tokens=False).input_ids`. The `add_prefix_space`
+ argument is only supported for some slow tokenizers, as fast tokenizers' prefixing behaviours come from
+ `pre tokenizers`. Read more [here](https://huggingface.co/docs/tokenizers/api/pre-tokenizers).
eos_token_id (`int`):
The id of the *end-of-sequence* token.
"""
@@ -313,7 +318,7 @@ def __init__(self, bad_words_ids: List[List[int]], eos_token_id: int):
self.bad_word_seqs_ids = tf.ragged.constant(bad_words_ids).to_tensor(default_value=-1)
# 2. a tensor with the unpadded length of each forbidden sequence, for quick length comparisons
bad_word_seqs_len = [len(bad_words) for bad_words in bad_words_ids]
- if any([word_len == 0 for word_len in bad_word_seqs_len]):
+ if any(word_len == 0 for word_len in bad_word_seqs_len):
raise ValueError(f"Banned words token sequences {bad_words_ids} cannot have an empty list")
self.bad_word_seqs_len = tf.convert_to_tensor(bad_word_seqs_len, dtype=tf.int32)
# 3. a tensor containing the last token for each sequence, for easy access to the tokens that may be banned
diff --git a/src/transformers/generation/tf_utils.py b/src/transformers/generation/tf_utils.py
index 5cd8153c2bf1..648ec710cfe5 100644
--- a/src/transformers/generation/tf_utils.py
+++ b/src/transformers/generation/tf_utils.py
@@ -474,27 +474,6 @@ def prepare_inputs_for_generation(self, *args, **kwargs):
"A model class needs to define a `prepare_inputs_for_generation` method in order to use `generate`."
)
- def adjust_logits_during_generation(
- self, logits, cur_len, max_length, forced_bos_token_id, forced_eos_token_id, **kwargs
- ):
- """
- Implement in subclasses of [`PreTrainedModel`] for custom behavior to adjust the logits in the generate method.
- """
- vocab_size = getattr(self.config, "vocab_size", None)
- if vocab_size is None and self.config.is_encoder_decoder:
- decoder_config = getattr(self.config, "decoder", None)
- if decoder_config is not None:
- vocab_size = getattr(self.config.decoder, "vocab_size", None)
-
- if cur_len == 1 and forced_bos_token_id is not None:
- vocab_range = tf.constant(range(vocab_size))
- return tf.where(vocab_range != forced_bos_token_id, -1e8, logits)
- elif cur_len == max_length - 1 and forced_eos_token_id is not None:
- vocab_range = tf.constant(range(vocab_size))
- return tf.where(vocab_range != forced_eos_token_id, -1e8, logits)
- else:
- return logits
-
def compute_transition_scores(
self,
sequences: tf.Tensor,
@@ -705,7 +684,7 @@ def generate(
seed (`List[int]`, *optional*):
Random seed to control sampling, containing two integers, used when `do_sample` is `True`. See the
`seed` argument from stateless functions in `tf.random`.
- kwargs:
+ kwargs (`Dict[str, Any]`, *optional*):
Ad hoc parametrization of `generate_config` and/or additional model-specific kwargs that will be
forwarded to the `forward` function of the model. If the model is an encoder-decoder model, encoder
specific kwargs should not be prefixed and decoder specific kwargs should be prefixed with *decoder_*.
@@ -746,7 +725,7 @@ def generate(
"You have modified the pretrained model configuration to control generation. This is a"
" deprecated strategy to control generation and will be removed soon, in a future version."
" Please use a generation configuration file (see"
- " https://huggingface.co/docs/transformers/main_classes/text_generation)"
+ " https://huggingface.co/docs/transformers/main_classes/text_generation )"
)
self.generation_config = new_generation_config
generation_config = self.generation_config
@@ -850,15 +829,14 @@ def generate(
# 7. Prepare `max_length` depending on other stopping criteria.
input_ids_seq_length = shape_list(input_ids)[-1]
has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None
- if has_default_max_length and generation_config.max_new_tokens is None:
+ if has_default_max_length and generation_config.max_new_tokens is None and generation_config.max_length != 20:
+ # 20 is the default max_length of the generation config
warnings.warn(
- f"Using `max_length`'s default ({generation_config.max_length}) to control the generation length. "
- "This behaviour is deprecated and will be removed from the config in v5 of Transformers -- we"
- " recommend using `max_new_tokens` to control the maximum length of the generation.",
+ f"Using the model-agnostic default `max_length` (={generation_config.max_length}) "
+ "to control the generation length. recommend setting `max_new_tokens` to control the maximum length of the generation.",
UserWarning,
)
elif generation_config.max_new_tokens is not None:
- generation_config.max_length = generation_config.max_new_tokens + input_ids_seq_length
if not has_default_max_length:
logger.warning(
f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="
@@ -866,6 +844,7 @@ def generate(
"Please refer to the documentation for more information. "
"(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)"
)
+ generation_config.max_length = generation_config.max_new_tokens + input_ids_seq_length
# If the input length is a tensor (i.e. dynamic length), skip length checks
if not isinstance(input_ids_seq_length, tf.Tensor):
@@ -1638,7 +1617,7 @@ def greedy_search(
# TODO (Joao): fix cache format or find programatic way to detect cache index
# GPT2 and other models has a slightly different cache structure, with a different batch axis
model_name = str(self.decoder) if "EncoderDecoder" in str(self) else str(self)
- cache_batch_axis = 1 if any([model_prefix in model_name for model_prefix in ("TFGPT2", "TFCTRL")]) else 0
+ cache_batch_axis = 1 if any(model_prefix in model_name for model_prefix in ("TFGPT2", "TFCTRL")) else 0
# some models, like XLNet, need more than the last token in the presence of past_key_values
needs_full_input = "use_mems" in set(inspect.signature(self.prepare_inputs_for_generation).parameters.keys())
@@ -1922,7 +1901,7 @@ def sample(
# TODO (Joao): fix cache format or find programatic way to detect cache index
# GPT2 and other models has a slightly different cache structure, with a different batch axis
model_name = str(self.decoder) if "EncoderDecoder" in str(self) else str(self)
- cache_batch_axis = 1 if any([model_prefix in model_name for model_prefix in ("TFGPT2", "TFCTRL")]) else 0
+ cache_batch_axis = 1 if any(model_prefix in model_name for model_prefix in ("TFGPT2", "TFCTRL")) else 0
# some models, like XLNet, need more than the last token in the presence of past_key_values
needs_full_input = "use_mems" in set(inspect.signature(self.prepare_inputs_for_generation).parameters.keys())
@@ -2265,7 +2244,7 @@ def unflatten_beam_dim(tensor, num_beams, batch_axis=0):
# TODO (Joao): fix cache format or find programatic way to detect cache index
# GPT2 and other models has a slightly different cache structure, with a different batch axis
model_name = str(self.decoder) if "EncoderDecoder" in str(self) else str(self)
- cache_batch_axis = 1 if any([model_prefix in model_name for model_prefix in ("TFGPT2", "TFCTRL")]) else 0
+ cache_batch_axis = 1 if any(model_prefix in model_name for model_prefix in ("TFGPT2", "TFCTRL")) else 0
# some models, like XLNet, need more than the last token in the presence of past_key_values
needs_full_input = "use_mems" in set(inspect.signature(self.prepare_inputs_for_generation).parameters.keys())
@@ -2779,7 +2758,7 @@ def gather_fn(tensor):
# TODO (Joao): fix cache format or find programatic way to detect cache index
# GPT2 and other models has a slightly different cache structure, with a different batch axis
model_name = str(self.decoder) if "EncoderDecoder" in str(self) else str(self)
- cache_batch_axis = 1 if any([model_prefix in model_name for model_prefix in ("TFGPT2", "TFCTRL")]) else 0
+ cache_batch_axis = 1 if any(model_prefix in model_name for model_prefix in ("TFGPT2", "TFCTRL")) else 0
# 2. init `attentions`, `hidden_states`, and `scores` tuples
scores = [] if (return_dict_in_generate and output_scores) else None
diff --git a/src/transformers/generation/utils.py b/src/transformers/generation/utils.py
index 06836d4d4ae2..0a32785ef66e 100644
--- a/src/transformers/generation/utils.py
+++ b/src/transformers/generation/utils.py
@@ -33,7 +33,7 @@
MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING,
MODEL_FOR_VISION_2_SEQ_MAPPING,
)
-from ..utils import ModelOutput, logging
+from ..utils import ExplicitEnum, ModelOutput, logging
from .beam_constraints import DisjunctiveConstraint, PhrasalConstraint
from .beam_search import BeamScorer, BeamSearchScorer, ConstrainedBeamSearchScorer
from .configuration_utils import GenerationConfig
@@ -56,12 +56,14 @@
NoRepeatNGramLogitsProcessor,
PrefixConstrainedLogitsProcessor,
RepetitionPenaltyLogitsProcessor,
+ SequenceBiasLogitsProcessor,
SuppressTokensAtBeginLogitsProcessor,
SuppressTokensLogitsProcessor,
TemperatureLogitsWarper,
TopKLogitsWarper,
TopPLogitsWarper,
TypicalLogitsWarper,
+ UnbatchedClassifierFreeGuidanceLogitsProcessor,
)
from .stopping_criteria import (
MaxLengthCriteria,
@@ -466,6 +468,23 @@ class BeamSampleEncoderDecoderOutput(ModelOutput):
GenerateOutput = Union[GreedySearchOutput, SampleOutput, BeamSearchOutput, BeamSampleOutput, ContrastiveSearchOutput]
+class GenerationMode(ExplicitEnum):
+ """
+ Possible generation modes, downstream of the [`~generation.GenerationMixin.generate`] method.
+ """
+
+ # Non-beam methods
+ CONTRASTIVE_SEARCH = "contrastive_search"
+ GREEDY_SEARCH = "greedy_search"
+ SAMPLE = "sample"
+ ASSISTED_GENERATION = "assisted_generation"
+ # Beam methods
+ BEAM_SEARCH = "beam_search"
+ BEAM_SAMPLE = "beam_sample"
+ CONSTRAINED_BEAM_SEARCH = "constrained_beam_search"
+ GROUP_BEAM_SEARCH = "group_beam_search"
+
+
class GenerationMixin:
"""
A class containing all functions for auto-regressive text generation, to be used as a mixin in [`PreTrainedModel`].
@@ -559,12 +578,6 @@ def _prepare_model_inputs(
inputs = self._maybe_initialize_input_ids_for_generation(inputs, bos_token_id, model_kwargs)
return inputs, input_name, model_kwargs
- def adjust_logits_during_generation(self, logits: torch.FloatTensor, **kwargs) -> torch.FloatTensor:
- """
- Implement in subclasses of [`PreTrainedModel`] for custom behavior to adjust the logits in the generate method.
- """
- return logits
-
def _maybe_initialize_input_ids_for_generation(
self,
inputs: Optional[torch.Tensor] = None,
@@ -616,6 +629,10 @@ def _prepare_encoder_decoder_kwargs_for_generation(
) -> Dict[str, Any]:
# 1. get encoder
encoder = self.get_encoder()
+ # Compatibility with Accelerate big model inference: we need the encoder to outputs stuff on the same device
+ # as the inputs.
+ if hasattr(encoder, "_hf_hook"):
+ encoder._hf_hook.io_same_device = True
# 2. Prepare encoder args and encoder kwargs from model kwargs.
irrelevant_prefix = ["decoder_", "cross_attn", "use_cache"]
@@ -753,6 +770,8 @@ def _update_model_kwargs_for_generation(
model_kwargs["past_key_values"] = self._extract_past_from_model_output(
outputs, standardize_cache_format=standardize_cache_format
)
+ if getattr(outputs, "state", None) is not None:
+ model_kwargs["state"] = outputs.state
# update token_type_ids with last value
if "token_type_ids" in model_kwargs:
@@ -821,6 +840,46 @@ def _get_logits_warper(
warpers.append(LogitNormalization())
return warpers
+ def _get_generation_mode(
+ self, generation_config: GenerationConfig, assistant_model: Optional["PreTrainedModel"]
+ ) -> GenerationMode:
+ """
+ Returns the generation mode triggered by a [`GenerationConfig`] instance.
+ """
+ if generation_config.constraints is not None or generation_config.force_words_ids is not None:
+ generation_mode = GenerationMode.CONSTRAINED_BEAM_SEARCH
+ elif generation_config.num_beams == 1:
+ if generation_config.do_sample is False:
+ if (
+ generation_config.top_k is not None
+ and generation_config.top_k > 1
+ and generation_config.penalty_alpha is not None
+ and generation_config.penalty_alpha > 0
+ ):
+ generation_mode = GenerationMode.CONTRASTIVE_SEARCH
+ else:
+ generation_mode = GenerationMode.GREEDY_SEARCH
+ else:
+ generation_mode = GenerationMode.SAMPLE
+ else:
+ if generation_config.num_beam_groups > 1:
+ generation_mode = GenerationMode.GROUP_BEAM_SEARCH
+ elif generation_config.do_sample is True:
+ generation_mode = GenerationMode.BEAM_SAMPLE
+ else:
+ generation_mode = GenerationMode.BEAM_SEARCH
+
+ # Assisted generation may extend some generation modes
+ if assistant_model is not None:
+ if generation_mode in ("greedy_search", "sample"):
+ generation_mode = GenerationMode.ASSISTED_GENERATION
+ else:
+ raise ValueError(
+ "You've set `assistant_model`, which triggers assisted generate. Currently, assisted generate "
+ "is only supported with Greedy Search and Sample."
+ )
+ return generation_mode
+
def _get_logits_processor(
self,
generation_config: GenerationConfig,
@@ -828,6 +887,9 @@ def _get_logits_processor(
encoder_input_ids: torch.LongTensor,
prefix_allowed_tokens_fn: Callable[[int, torch.Tensor], List[int]],
logits_processor: Optional[LogitsProcessorList],
+ model_kwargs: Optional[Dict[str, Any]] = None,
+ negative_prompt_ids: Optional[torch.Tensor] = None,
+ negative_prompt_attention_mask: Optional[torch.Tensor] = None,
) -> LogitsProcessorList:
"""
This class returns a [`LogitsProcessorList`] list object that contains all relevant [`LogitsProcessor`]
@@ -836,8 +898,19 @@ def _get_logits_processor(
# instantiate processors list
processors = LogitsProcessorList()
- # the following idea is largely copied from this PR: https://github.com/huggingface/transformers/pull/5420/files
- # all samplers can be found in `generation_utils_samplers.py`
+ if generation_config.guidance_scale is not None and generation_config.guidance_scale != 1:
+ processors.append(
+ UnbatchedClassifierFreeGuidanceLogitsProcessor(
+ generation_config.guidance_scale,
+ self,
+ unconditional_ids=negative_prompt_ids,
+ unconditional_attention_mask=negative_prompt_attention_mask,
+ use_cache=model_kwargs["use_cache"],
+ )
+ )
+ if generation_config.sequence_bias is not None:
+ processors.append(SequenceBiasLogitsProcessor(sequence_bias=generation_config.sequence_bias))
+
if generation_config.diversity_penalty is not None and generation_config.diversity_penalty > 0.0:
processors.append(
HammingDiversityLogitsProcessor(
@@ -943,7 +1016,13 @@ def _get_stopping_criteria(
) -> StoppingCriteriaList:
criteria = StoppingCriteriaList()
if generation_config.max_length is not None:
- criteria.append(MaxLengthCriteria(max_length=generation_config.max_length))
+ max_position_embeddings = getattr(self.config, "max_position_embeddings", None)
+ criteria.append(
+ MaxLengthCriteria(
+ max_length=generation_config.max_length,
+ max_position_embeddings=max_position_embeddings,
+ )
+ )
if generation_config.max_time is not None:
criteria.append(MaxTimeCriteria(max_time=generation_config.max_time))
criteria = self._merge_criteria_processor_list(criteria, stopping_criteria)
@@ -1130,6 +1209,32 @@ def _validate_model_kwargs(self, model_kwargs: Dict[str, Any]):
# `prepare_inputs_for_generation` doesn't accept them, then a stricter check can be made ;)
if "kwargs" in model_args or "model_kwargs" in model_args:
model_args |= set(inspect.signature(self.forward).parameters)
+
+ # Encoder-Decoder models may also need Encoder arguments from `model_kwargs`
+ if self.config.is_encoder_decoder:
+ base_model = getattr(self, self.base_model_prefix, None)
+
+ # allow encoder kwargs
+ encoder = getattr(self, "encoder", None)
+ # `MusicgenForConditionalGeneration` has `text_encoder` and `audio_encoder`.
+ # Also, it has `base_model_prefix = "encoder_decoder"` but there is no `self.encoder_decoder`
+ # TODO: A better way to handle this.
+ if encoder is None and base_model is not None:
+ encoder = getattr(base_model, "encoder", None)
+
+ if encoder is not None:
+ encoder_model_args = set(inspect.signature(encoder.forward).parameters)
+ model_args |= encoder_model_args
+
+ # allow decoder kwargs
+ decoder = getattr(self, "decoder", None)
+ if decoder is None and base_model is not None:
+ decoder = getattr(base_model, "decoder", None)
+
+ if decoder is not None:
+ decoder_model_args = set(inspect.signature(decoder.forward).parameters)
+ model_args |= {f"decoder_{x}" for x in decoder_model_args}
+
for key, value in model_kwargs.items():
if value is not None and key not in model_args:
unused_model_args.append(key)
@@ -1140,6 +1245,52 @@ def _validate_model_kwargs(self, model_kwargs: Dict[str, Any]):
" generate arguments will also show up in this list)"
)
+ def _validate_generated_length(self, generation_config, input_ids_length, has_default_max_length):
+ """Performs validation related to the resulting generated length"""
+
+ # 1. Max length warnings related to poor parameterization
+ if has_default_max_length and generation_config.max_new_tokens is None and generation_config.max_length != 20:
+ # 20 is the default max_length of the generation config
+ warnings.warn(
+ f"Using the model-agnostic default `max_length` (={generation_config.max_length}) to control the"
+ "generation length. We recommend setting `max_new_tokens` to control the maximum length of the "
+ "generation.",
+ UserWarning,
+ )
+ if input_ids_length >= generation_config.max_length:
+ input_ids_string = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"
+ warnings.warn(
+ f"Input length of {input_ids_string} is {input_ids_length}, but `max_length` is set to"
+ f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider"
+ " increasing `max_new_tokens`.",
+ UserWarning,
+ )
+
+ # 2. Min length warnings due to unfeasible parameter combinations
+ min_length_error_suffix = (
+ " Generation will stop at the defined maximum length. You should decrease the minimum length and/or "
+ "increase the maximum length."
+ )
+ if has_default_max_length:
+ min_length_error_suffix += (
+ f" Note that `max_length` is set to {generation_config.max_length}, its default value."
+ )
+ if generation_config.min_length is not None and generation_config.min_length > generation_config.max_length:
+ warnings.warn(
+ f"Unfeasible length constraints: `min_length` ({generation_config.min_length}) is larger than"
+ f" the maximum possible length ({generation_config.max_length})." + min_length_error_suffix,
+ UserWarning,
+ )
+ if generation_config.min_new_tokens is not None:
+ min_length = generation_config.min_new_tokens + input_ids_length
+ if min_length > generation_config.max_length:
+ warnings.warn(
+ f"Unfeasible length constraints: `min_new_tokens` ({generation_config.min_new_tokens}), when "
+ f"added to the prompt length ({input_ids_length}), is larger than"
+ f" the maximum possible length ({generation_config.max_length})." + min_length_error_suffix,
+ UserWarning,
+ )
+
@torch.no_grad()
def generate(
self,
@@ -1151,6 +1302,8 @@ def generate(
synced_gpus: Optional[bool] = None,
assistant_model: Optional["PreTrainedModel"] = None,
streamer: Optional["BaseStreamer"] = None,
+ negative_prompt_ids: Optional[torch.Tensor] = None,
+ negative_prompt_attention_mask: Optional[torch.Tensor] = None,
**kwargs,
) -> Union[GenerateOutput, torch.LongTensor]:
r"""
@@ -1208,7 +1361,12 @@ def generate(
streamer (`BaseStreamer`, *optional*):
Streamer object that will be used to stream the generated sequences. Generated tokens are passed
through `streamer.put(token_ids)` and the streamer is responsible for any further processing.
- kwargs:
+ negative_prompt_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ The negative prompt needed for some processors such as CFG. The batch size must match the input batch
+ size. This is an experimental feature, subject to breaking API changes in future versions.
+ negative_prompt_attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Attention_mask for `negative_prompt_ids`.
+ kwargs (`Dict[str, Any]`, *optional*):
Ad hoc parametrization of `generate_config` and/or additional model-specific kwargs that will be
forwarded to the `forward` function of the model. If the model is an encoder-decoder model, encoder
specific kwargs should not be prefixed and decoder specific kwargs should be prefixed with *decoder_*.
@@ -1254,7 +1412,7 @@ def generate(
"You have modified the pretrained model configuration to control generation. This is a"
" deprecated strategy to control generation and will be removed soon, in a future version."
" Please use a generation configuration file (see"
- " https://huggingface.co/docs/transformers/main_classes/text_generation)"
+ " https://huggingface.co/docs/transformers/main_classes/text_generation )"
)
self.generation_config = new_generation_config
generation_config = self.generation_config
@@ -1293,7 +1451,12 @@ def generate(
# 4. Define other model kwargs
model_kwargs["output_attentions"] = generation_config.output_attentions
model_kwargs["output_hidden_states"] = generation_config.output_hidden_states
- model_kwargs["use_cache"] = generation_config.use_cache
+ # decoder-only models with inputs_embeds forwarding must use caching (otherwise we can't detect whether we are
+ # generating the first new token or not, and we only want to use the embeddings for the first new token)
+ if not self.config.is_encoder_decoder and model_input_name == "inputs_embeds":
+ model_kwargs["use_cache"] = True
+ else:
+ model_kwargs["use_cache"] = generation_config.use_cache
accepts_attention_mask = "attention_mask" in set(inspect.signature(self.forward).parameters.keys())
requires_attention_mask = "encoder_outputs" not in model_kwargs
@@ -1305,8 +1468,11 @@ def generate(
# decoder-only models should use left-padding for generation
if not self.config.is_encoder_decoder:
+ # If `input_ids` was given, check if the last id in any sequence is `pad_token_id`
+ # Note: If using, `inputs_embeds` this check does not work, because we want to be more hands-off.
if (
generation_config.pad_token_id is not None
+ and len(inputs_tensor.shape) == 2
and torch.sum(inputs_tensor[:, -1] == generation_config.pad_token_id) > 0
):
logger.warning(
@@ -1338,17 +1504,9 @@ def generate(
streamer.put(input_ids.cpu())
# 6. Prepare `max_length` depending on other stopping criteria.
- input_ids_seq_length = input_ids.shape[-1]
+ input_ids_length = input_ids.shape[-1]
has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None
- if has_default_max_length and generation_config.max_new_tokens is None:
- warnings.warn(
- f"Using `max_length`'s default ({generation_config.max_length}) to control the generation length. "
- "This behaviour is deprecated and will be removed from the config in v5 of Transformers -- we"
- " recommend using `max_new_tokens` to control the maximum length of the generation.",
- UserWarning,
- )
- elif generation_config.max_new_tokens is not None:
- generation_config.max_length = generation_config.max_new_tokens + input_ids_seq_length
+ if generation_config.max_new_tokens is not None:
if not has_default_max_length:
logger.warning(
f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="
@@ -1356,83 +1514,11 @@ def generate(
"Please refer to the documentation for more information. "
"(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)"
)
-
- if generation_config.min_length is not None and generation_config.min_length > generation_config.max_length:
- raise ValueError(
- f"Unfeasible length constraints: the minimum length ({generation_config.min_length}) is larger than"
- f" the maximum length ({generation_config.max_length})"
- )
- if input_ids_seq_length >= generation_config.max_length:
- input_ids_string = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"
- logger.warning(
- f"Input length of {input_ids_string} is {input_ids_seq_length}, but `max_length` is set to"
- f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider"
- " increasing `max_new_tokens`."
- )
+ generation_config.max_length = generation_config.max_new_tokens + input_ids_length
+ self._validate_generated_length(generation_config, input_ids_length, has_default_max_length)
# 7. determine generation mode
- is_constraint_gen_mode = (
- generation_config.constraints is not None or generation_config.force_words_ids is not None
- )
-
- is_contrastive_search_gen_mode = (
- (generation_config.num_beams == 1)
- and generation_config.top_k is not None
- and generation_config.top_k > 1
- and generation_config.do_sample is False
- and generation_config.penalty_alpha is not None
- and generation_config.penalty_alpha > 0
- )
-
- is_greedy_gen_mode = (
- (generation_config.num_beams == 1)
- and (generation_config.num_beam_groups == 1)
- and generation_config.do_sample is False
- and not is_constraint_gen_mode
- and not is_contrastive_search_gen_mode
- )
- is_sample_gen_mode = (
- (generation_config.num_beams == 1)
- and (generation_config.num_beam_groups == 1)
- and generation_config.do_sample is True
- and not is_constraint_gen_mode
- and not is_contrastive_search_gen_mode
- )
- is_beam_gen_mode = (
- (generation_config.num_beams > 1)
- and (generation_config.num_beam_groups == 1)
- and generation_config.do_sample is False
- and not is_constraint_gen_mode
- and not is_contrastive_search_gen_mode
- )
- is_beam_sample_gen_mode = (
- (generation_config.num_beams > 1)
- and (generation_config.num_beam_groups == 1)
- and generation_config.do_sample is True
- and not is_constraint_gen_mode
- and not is_contrastive_search_gen_mode
- )
- is_group_beam_gen_mode = (
- (generation_config.num_beams > 1)
- and (generation_config.num_beam_groups > 1)
- and not is_constraint_gen_mode
- and not is_contrastive_search_gen_mode
- )
- is_assisted_gen_mode = False
- if assistant_model is not None:
- if not (is_greedy_gen_mode or is_sample_gen_mode):
- raise ValueError(
- "You've set `assistant_model`, which triggers assisted generate. Currently, assisted generate "
- "is only supported with Greedy Search and Sample."
- )
- is_assisted_gen_mode = True
-
- if generation_config.num_beam_groups > generation_config.num_beams:
- raise ValueError("`num_beam_groups` has to be smaller or equal to `num_beams`")
- if is_group_beam_gen_mode and generation_config.do_sample is True:
- raise ValueError(
- "Diverse beam search cannot be used in sampling mode. Make sure that `do_sample` is set to `False`."
- )
+ generation_mode = self._get_generation_mode(generation_config, assistant_model)
if streamer is not None and (generation_config.num_beams > 1):
raise ValueError(
@@ -1453,10 +1539,13 @@ def generate(
# 8. prepare distribution pre_processing samplers
logits_processor = self._get_logits_processor(
generation_config=generation_config,
- input_ids_seq_length=input_ids_seq_length,
+ input_ids_seq_length=input_ids_length,
encoder_input_ids=inputs_tensor,
prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
logits_processor=logits_processor,
+ model_kwargs=model_kwargs,
+ negative_prompt_ids=negative_prompt_ids,
+ negative_prompt_attention_mask=negative_prompt_attention_mask,
)
# 9. prepare stopping criteria
@@ -1464,7 +1553,7 @@ def generate(
generation_config=generation_config, stopping_criteria=stopping_criteria
)
# 10. go into different generation modes
- if is_assisted_gen_mode:
+ if generation_mode == GenerationMode.ASSISTED_GENERATION:
if generation_config.num_return_sequences > 1:
raise ValueError(
"num_return_sequences has to be 1 when doing assisted generate, "
@@ -1502,13 +1591,7 @@ def generate(
streamer=streamer,
**model_kwargs,
)
- if is_greedy_gen_mode:
- if generation_config.num_return_sequences > 1:
- raise ValueError(
- "num_return_sequences has to be 1 when doing greedy search, "
- f"but is {generation_config.num_return_sequences}."
- )
-
+ if generation_mode == GenerationMode.GREEDY_SEARCH:
# 11. run greedy search
return self.greedy_search(
input_ids,
@@ -1523,12 +1606,7 @@ def generate(
**model_kwargs,
)
- elif is_contrastive_search_gen_mode:
- if generation_config.num_return_sequences > 1:
- raise ValueError(
- "num_return_sequences has to be 1 when doing contrastive search, "
- f"but is {generation_config.num_return_sequences}."
- )
+ elif generation_mode == GenerationMode.CONTRASTIVE_SEARCH:
if not model_kwargs["use_cache"]:
raise ValueError("Contrastive search requires `use_cache=True`")
@@ -1544,10 +1622,11 @@ def generate(
return_dict_in_generate=generation_config.return_dict_in_generate,
synced_gpus=synced_gpus,
streamer=streamer,
+ sequential=generation_config.low_memory,
**model_kwargs,
)
- elif is_sample_gen_mode:
+ elif generation_mode == GenerationMode.SAMPLE:
# 11. prepare logits warper
logits_warper = self._get_logits_warper(generation_config)
@@ -1574,13 +1653,7 @@ def generate(
**model_kwargs,
)
- elif is_beam_gen_mode:
- if generation_config.num_return_sequences > generation_config.num_beams:
- raise ValueError("`num_return_sequences` has to be smaller or equal to `num_beams`.")
-
- if stopping_criteria.max_length is None:
- raise ValueError("`max_length` needs to be a stopping_criteria for now.")
-
+ elif generation_mode == GenerationMode.BEAM_SEARCH:
# 11. prepare beam search scorer
beam_scorer = BeamSearchScorer(
batch_size=batch_size,
@@ -1612,26 +1685,25 @@ def generate(
**model_kwargs,
)
- elif is_beam_sample_gen_mode:
+ elif generation_mode == GenerationMode.BEAM_SAMPLE:
# 11. prepare logits warper
logits_warper = self._get_logits_warper(generation_config)
- if stopping_criteria.max_length is None:
- raise ValueError("`max_length` needs to be a stopping_criteria for now.")
# 12. prepare beam search scorer
beam_scorer = BeamSearchScorer(
- batch_size=batch_size * generation_config.num_return_sequences,
+ batch_size=batch_size,
num_beams=generation_config.num_beams,
device=inputs_tensor.device,
length_penalty=generation_config.length_penalty,
do_early_stopping=generation_config.early_stopping,
+ num_beam_hyps_to_keep=generation_config.num_return_sequences,
max_length=generation_config.max_length,
)
# 13. interleave input_ids with `num_beams` additional sequences per batch
input_ids, model_kwargs = self._expand_inputs_for_generation(
input_ids=input_ids,
- expand_size=generation_config.num_beams * generation_config.num_return_sequences,
+ expand_size=generation_config.num_beams,
is_encoder_decoder=self.config.is_encoder_decoder,
**model_kwargs,
)
@@ -1651,20 +1723,7 @@ def generate(
**model_kwargs,
)
- elif is_group_beam_gen_mode:
- if generation_config.num_return_sequences > generation_config.num_beams:
- raise ValueError("`num_return_sequences` has to be smaller or equal to `num_beams`.")
-
- if generation_config.num_beams % generation_config.num_beam_groups != 0:
- raise ValueError("`num_beams` should be divisible by `num_beam_groups` for group beam search.")
-
- if stopping_criteria.max_length is None:
- raise ValueError("`max_length` needs to be a stopping_criteria for now.")
-
- has_default_typical_p = kwargs.get("typical_p") is None and generation_config.typical_p == 1.0
- if not has_default_typical_p:
- raise ValueError("Decoder argument `typical_p` is not supported with beam groups.")
-
+ elif generation_mode == GenerationMode.GROUP_BEAM_SEARCH:
# 11. prepare beam search scorer
beam_scorer = BeamSearchScorer(
batch_size=batch_size,
@@ -1697,22 +1756,7 @@ def generate(
**model_kwargs,
)
- elif is_constraint_gen_mode:
- if generation_config.num_return_sequences > generation_config.num_beams:
- raise ValueError("`num_return_sequences` has to be smaller or equal to `num_beams`.")
-
- if stopping_criteria.max_length is None:
- raise ValueError("`max_length` needs to be a stopping_criteria for now.")
-
- if generation_config.num_beams <= 1:
- raise ValueError("`num_beams` needs to be greater than 1 for constrained generation.")
-
- if generation_config.do_sample:
- raise ValueError("`do_sample` needs to be false for constrained generation.")
-
- if generation_config.num_beam_groups is not None and generation_config.num_beam_groups > 1:
- raise ValueError("`num_beam_groups` not supported yet for constrained generation.")
-
+ elif generation_mode == GenerationMode.CONSTRAINED_BEAM_SEARCH:
final_constraints = []
if generation_config.constraints is not None:
final_constraints = generation_config.constraints
@@ -1802,6 +1846,7 @@ def contrastive_search(
return_dict_in_generate: Optional[bool] = None,
synced_gpus: bool = False,
streamer: Optional["BaseStreamer"] = None,
+ sequential: Optional[bool] = None,
**model_kwargs,
) -> Union[ContrastiveSearchOutput, torch.LongTensor]:
r"""
@@ -1852,6 +1897,8 @@ def contrastive_search(
streamer (`BaseStreamer`, *optional*):
Streamer object that will be used to stream the generated sequences. Generated tokens are passed
through `streamer.put(token_ids)` and the streamer is responsible for any further processing.
+ sequential (`bool`, *optional*):
+ Switches topk hidden state computation from parallel to sequential to reduce memory if True.
model_kwargs:
Additional model specific keyword arguments will be forwarded to the `forward` function of the model.
If model is an encoder-decoder model the kwargs should include `encoder_outputs`.
@@ -1891,6 +1938,7 @@ def contrastive_search(
stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()
pad_token_id = pad_token_id if pad_token_id is not None else self.generation_config.pad_token_id
eos_token_id = eos_token_id if eos_token_id is not None else self.generation_config.eos_token_id
+ sequential = sequential if sequential is not None else self.generation_config.low_memory
if isinstance(eos_token_id, int):
eos_token_id = [eos_token_id]
eos_token_id_tensor = torch.tensor(eos_token_id).to(input_ids.device) if eos_token_id is not None else None
@@ -1956,6 +2004,7 @@ def contrastive_search(
last_hidden_states = outputs.decoder_hidden_states[-1]
else:
last_hidden_states = outputs.hidden_states[-1]
+
# next logit for contrastive search to select top-k candidate tokens
logit_for_next_step = outputs.logits[:, -1, :]
@@ -1965,11 +2014,11 @@ def contrastive_search(
is_encoder_decoder=self.config.is_encoder_decoder,
standardize_cache_format=True,
)
-
- # Expands model inputs top_k times, for batched forward passes (akin to beam search).
- _, model_kwargs = self._expand_inputs_for_generation(
- expand_size=top_k, is_encoder_decoder=self.config.is_encoder_decoder, **model_kwargs
- )
+ if not sequential:
+ # Expands model inputs top_k times, for batched forward passes (akin to beam search).
+ _, model_kwargs = self._expand_inputs_for_generation(
+ expand_size=top_k, is_encoder_decoder=self.config.is_encoder_decoder, **model_kwargs
+ )
past_key_values = model_kwargs.get("past_key_values")
if past_key_values is None:
@@ -1989,7 +2038,6 @@ def contrastive_search(
# contrastive_search main logic start:
# contrastive search decoding consists of two steps: (1) candidate tokens recall; (2) candidate re-rank by
# degeneration penalty
-
logit_for_next_step = logits_processor(input_ids, logit_for_next_step)
logit_for_next_step = logits_warper(input_ids, logit_for_next_step)
next_probs = nn.functional.softmax(logit_for_next_step, dim=-1)
@@ -2019,30 +2067,81 @@ def contrastive_search(
items = []
# item is either the key or the value matrix
for item in layer:
- items.append(item.repeat_interleave(top_k, dim=0))
+ if sequential:
+ items.append(item.repeat_interleave(1, dim=0))
+ else:
+ items.append(item.repeat_interleave(top_k, dim=0))
new_key_values.append(items)
model_kwargs["past_key_values"] = new_key_values
- # compute the candidate tokens by the language model and collects their hidden_states
- next_model_inputs = self.prepare_inputs_for_generation(top_k_ids.view(-1, 1), **model_kwargs)
- outputs = self(
- **next_model_inputs, return_dict=True, output_hidden_states=True, output_attentions=output_attentions
- )
- next_past_key_values = self._extract_past_from_model_output(outputs, standardize_cache_format=True)
+ if sequential:
+ all_outputs = {key: [] for key in outputs} # defined in first loop iteration
+ all_last_hstates, all_hstates, all_logits = [], [], []
+ for i in range(top_k):
+ # compute the candidate tokens by the language model and collect their hidden_states
+ next_model_inputs = self.prepare_inputs_for_generation(top_k_ids[:, i].view(-1, 1), **model_kwargs)
+
+ outputs = self(
+ **next_model_inputs,
+ return_dict=True,
+ output_hidden_states=True,
+ output_attentions=output_attentions,
+ )
+ for key in all_outputs:
+ all_outputs[key].append(outputs[key])
+
+ if self.config.is_encoder_decoder:
+ next_hidden = outputs.decoder_hidden_states[-1]
+ full_hidden_states = outputs.decoder_hidden_states
+
+ else:
+ next_hidden = outputs.hidden_states[-1]
+ full_hidden_states = outputs.hidden_states
+
+ all_last_hstates.append(torch.squeeze(next_hidden, 0))
+ all_hstates.append(full_hidden_states)
+ all_logits.append(outputs.logits[:, -1, :])
+
+ # stack hidden states
+ next_hidden = torch.stack([all_last_hstates[i] for i in range(top_k)], dim=0)
+ final_full_hstates = [0 for i in range(len(full_hidden_states))]
+ for layer in range(len(full_hidden_states)):
+ final_full_hstates[layer] = torch.stack(
+ [torch.squeeze(all_hstates[i][layer], 0) for i in range(top_k)], dim=0
+ )
+ full_hidden_states = tuple(final_full_hstates)
+
+ # stack logits
+ logits = torch.cat(all_logits, dim=0)
- logits = outputs.logits[:, -1, :]
- # name is different for encoder-decoder and decoder-only models
- if self.config.is_encoder_decoder:
- next_hidden = outputs.decoder_hidden_states[-1]
- full_hidden_states = outputs.decoder_hidden_states
else:
- next_hidden = outputs.hidden_states[-1]
- full_hidden_states = outputs.hidden_states
+ # compute the candidate tokens by the language model and collect their hidden_states
+ # assembles top_k_ids into batch of size k
+ next_model_inputs = self.prepare_inputs_for_generation(top_k_ids.view(-1, 1), **model_kwargs)
+
+ outputs = self(
+ **next_model_inputs,
+ return_dict=True,
+ output_hidden_states=True,
+ output_attentions=output_attentions,
+ )
+ # name is different for encoder-decoder and decoder-only models
+ if self.config.is_encoder_decoder:
+ next_hidden = outputs.decoder_hidden_states[-1]
+ full_hidden_states = outputs.decoder_hidden_states
+ else:
+ next_hidden = outputs.hidden_states[-1]
+ full_hidden_states = outputs.hidden_states
+
+ logits = outputs.logits[:, -1, :]
+
context_hidden = last_hidden_states.repeat_interleave(top_k, dim=0)
# compute the degeneration penalty and re-rank the candidates based on the degeneration penalty and the
- # model confidence
+ # model confidence. Keeping `selected_idx` on CPU enables multi-device contrastive search and doesn't
+ # introduce (noticeable) slowdowns on single-device runs.
selected_idx = _ranking_fast(context_hidden, next_hidden, top_k_probs, penalty_alpha, top_k)
+ selected_idx = selected_idx.to("cpu")
# prepare for the next step: (1) next token_id; (2) past_key_values; (3) last_hidden_states for computing
# the degeneration penalty; (4) logits for selecting next top-k candidates; (5) selected tokens scores
@@ -2057,17 +2156,32 @@ def contrastive_search(
layer = torch.stack(torch.split(layer, top_k))[range(batch_size), selected_idx, :]
next_decoder_hidden_states += (layer,)
- # select the past_key_value
- new_key_values = ()
- for layer in next_past_key_values:
- items = ()
- # item is either the key or the value matrix
- for item in layer:
- item = torch.stack(torch.split(item, top_k, dim=0)) # [B, K, num_head, seq_len, esz]
- item = item[range(batch_size), selected_idx, ...] # [B, num_head, seq_len, esz]
- items += (item,)
- new_key_values += (items,)
- next_past_key_values = new_key_values
+ # generate past_key_values cache of only the selected token
+ if sequential:
+ next_model_input = self.prepare_inputs_for_generation(
+ top_k_ids[:, selected_idx].view(-1, 1), **model_kwargs
+ )
+
+ selected_outputs = self(
+ **next_model_input,
+ return_dict=True,
+ output_hidden_states=False,
+ output_attentions=False,
+ )
+ next_past_key_values = selected_outputs["past_key_values"]
+
+ else:
+ next_past_key_values = self._extract_past_from_model_output(outputs, standardize_cache_format=True)
+ new_key_values = ()
+ for layer in next_past_key_values:
+ items = ()
+ # item is either the key or the value matrix
+ for item in layer:
+ item = torch.stack(torch.split(item, top_k, dim=0)) # [B, K, num_head, seq_len, esz]
+ item = item[range(batch_size), selected_idx, ...] # [B, num_head, seq_len, esz]
+ items += (item,)
+ new_key_values += (items,)
+ next_past_key_values = new_key_values
logit_for_next_step = torch.stack(torch.split(logits, top_k))[range(batch_size), selected_idx, :]
@@ -2909,9 +3023,6 @@ def beam_search(
continue # don't waste resources running the code we don't need
next_token_logits = outputs.logits[:, -1, :]
- # hack: adjust tokens for Marian. For Marian we have to make sure that the `pad_token_id`
- # cannot be generated both before and after the `nn.functional.log_softmax` operation.
- next_token_logits = self.adjust_logits_during_generation(next_token_logits, cur_len=cur_len)
next_token_scores = nn.functional.log_softmax(
next_token_logits, dim=-1
) # (batch_size * num_beams, vocab_size)
@@ -2941,9 +3052,10 @@ def beam_search(
vocab_size = next_token_scores.shape[-1]
next_token_scores = next_token_scores.view(batch_size, num_beams * vocab_size)
- # Sample 2 next tokens for each beam (so we have some spare tokens and match output of beam search)
+ # Sample 1 + len(eos_token_id) next tokens for each beam so we have at least 1 non eos token per beam.
+ n_eos_tokens = len(eos_token_id) if eos_token_id else 0
next_token_scores, next_tokens = torch.topk(
- next_token_scores, 2 * num_beams, dim=1, largest=True, sorted=True
+ next_token_scores, max(2, 1 + n_eos_tokens) * num_beams, dim=1, largest=True, sorted=True
)
next_indices = torch.div(next_tokens, vocab_size, rounding_mode="floor")
@@ -3236,9 +3348,6 @@ def beam_sample(
next_token_logits = outputs.logits[:, -1, :]
- # hack: adjust tokens for Marian. For Marian we have to make sure that the `pad_token_id`
- # cannot be generated both before and after the `nn.functional.log_softmax` operation.
- next_token_logits = self.adjust_logits_during_generation(next_token_logits, cur_len=cur_len)
next_token_scores = nn.functional.log_softmax(
next_token_logits, dim=-1
) # (batch_size * num_beams, vocab_size)
@@ -3511,10 +3620,10 @@ def group_beam_search(
else self.generation_config.return_dict_in_generate
)
- batch_size = len(beam_scorer._beam_hyps)
num_beams = beam_scorer.num_beams
num_beam_groups = beam_scorer.num_beam_groups
num_sub_beams = num_beams // num_beam_groups
+ batch_size = len(beam_scorer._beam_hyps) // num_beam_groups
device = input_ids.device
batch_beam_size, cur_len = input_ids.shape
@@ -3599,9 +3708,6 @@ def group_beam_search(
# select outputs of beams of current group only
next_token_logits = outputs.logits[batch_group_indices, -1, :]
- # hack: adjust tokens for Marian. For Marian we have to make sure that the `pad_token_id`
- # cannot be generated both before and after the `nn.functional.log_softmax` operation.
- next_token_logits = self.adjust_logits_during_generation(next_token_logits, cur_len=cur_len)
next_token_scores = nn.functional.log_softmax(
next_token_logits, dim=-1
) # (batch_size * group_size, vocab_size)
@@ -3619,9 +3725,10 @@ def group_beam_search(
# reshape for beam search
next_token_scores = next_token_scores.view(batch_size, group_size * vocab_size)
- # Sample 2 next tokens for each beam (so we have some spare tokens and match output of beam search)
+ # Sample 1 + len(eos_token_id) next tokens for each beam so we have at least 1 non eos token per beam.
+ n_eos_tokens = len(eos_token_id) if eos_token_id else 0
next_token_scores, next_tokens = torch.topk(
- next_token_scores, 2 * group_size, dim=1, largest=True, sorted=True
+ next_token_scores, max(2, 1 + n_eos_tokens) * group_size, dim=1, largest=True, sorted=True
)
next_indices = torch.div(next_tokens, vocab_size, rounding_mode="floor")
@@ -3637,6 +3744,7 @@ def group_beam_search(
pad_token_id=pad_token_id,
eos_token_id=eos_token_id,
beam_indices=process_beam_indices,
+ group_index=beam_group_idx,
)
beam_scores[batch_group_indices] = beam_outputs["next_beam_scores"]
beam_next_tokens = beam_outputs["next_beam_tokens"]
@@ -3898,8 +4006,21 @@ def constrained_beam_search(
else self.generation_config.return_dict_in_generate
)
+ batch_size = len(constrained_beam_scorer._beam_hyps)
+ num_beams = constrained_beam_scorer.num_beams
+
+ batch_beam_size, cur_len = input_ids.shape
+
+ if num_beams * batch_size != batch_beam_size:
+ raise ValueError(
+ f"Batch dimension of `input_ids` should be {num_beams * batch_size}, but is {batch_beam_size}."
+ )
+
# init attention / hidden states / scores tuples
scores = () if (return_dict_in_generate and output_scores) else None
+ beam_indices = (
+ tuple(() for _ in range(batch_beam_size)) if (return_dict_in_generate and output_scores) else None
+ )
decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
cross_attentions = () if (return_dict_in_generate and output_attentions) else None
decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None
@@ -3911,16 +4032,6 @@ def constrained_beam_search(
model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
)
- batch_size = len(constrained_beam_scorer._beam_hyps)
- num_beams = constrained_beam_scorer.num_beams
-
- batch_beam_size, cur_len = input_ids.shape
-
- if num_beams * batch_size != batch_beam_size:
- raise ValueError(
- f"Batch dimension of `input_ids` should be {num_beams * batch_size}, but is {batch_beam_size}."
- )
-
# initialise score of first beam with 0 and the rest with -1e9. This makes sure that only tokens
# of the first beam are considered to avoid sampling the exact same tokens across all beams.
beam_scores = torch.zeros((batch_size, num_beams), dtype=torch.float, device=input_ids.device)
@@ -3953,9 +4064,6 @@ def constrained_beam_search(
continue # don't waste resources running the code we don't need
next_token_logits = outputs.logits[:, -1, :]
- # hack: adjust tokens for Marian. For Marian we have to make sure that the `pad_token_id`
- # cannot be generated both before and after the `nn.functional.log_softmax` operation.
- next_token_logits = self.adjust_logits_during_generation(next_token_logits, cur_len=cur_len)
next_token_scores = nn.functional.log_softmax(
next_token_logits, dim=-1
) # (batch_size * num_beams, vocab_size)
@@ -3988,9 +4096,10 @@ def constrained_beam_search(
vocab_size = next_token_scores.shape[-1]
next_token_scores = next_token_scores.view(batch_size, num_beams * vocab_size)
- # Sample 2 next tokens for each beam (so we have some spare tokens and match output of beam search)
+ # Sample 1 + len(eos_token_id) next tokens for each beam so we have at least 1 non eos token per beam.
+ n_eos_tokens = len(eos_token_id) if eos_token_id else 0
next_token_scores, next_tokens = torch.topk(
- next_token_scores, 2 * num_beams, dim=1, largest=True, sorted=True
+ next_token_scores, max(2, 1 + n_eos_tokens) * num_beams, dim=1, largest=True, sorted=True
)
next_indices = (next_tokens / vocab_size).long()
@@ -4005,6 +4114,7 @@ def constrained_beam_search(
scores_for_all_vocab,
pad_token_id=pad_token_id,
eos_token_id=eos_token_id,
+ beam_indices=beam_indices,
)
beam_scores = beam_outputs["next_beam_scores"]
beam_next_tokens = beam_outputs["next_beam_tokens"]
@@ -4017,6 +4127,9 @@ def constrained_beam_search(
if model_kwargs["past_key_values"] is not None:
model_kwargs["past_key_values"] = self._reorder_cache(model_kwargs["past_key_values"], beam_idx)
+ if return_dict_in_generate and output_scores:
+ beam_indices = tuple((beam_indices[beam_idx[i]] + (beam_idx[i],) for i in range(len(beam_indices))))
+
# increase cur_len
cur_len = cur_len + 1
@@ -4034,6 +4147,7 @@ def constrained_beam_search(
pad_token_id=pad_token_id,
eos_token_id=eos_token_id,
max_length=stopping_criteria.max_length,
+ beam_indices=beam_indices,
)
if return_dict_in_generate:
@@ -4044,6 +4158,7 @@ def constrained_beam_search(
sequences=sequence_outputs["sequences"],
sequences_scores=sequence_outputs["sequence_scores"],
scores=scores,
+ beam_indices=sequence_outputs["beam_indices"],
encoder_attentions=encoder_attentions,
encoder_hidden_states=encoder_hidden_states,
decoder_attentions=decoder_attentions,
@@ -4055,6 +4170,7 @@ def constrained_beam_search(
sequences=sequence_outputs["sequences"],
sequences_scores=sequence_outputs["sequence_scores"],
scores=scores,
+ beam_indices=sequence_outputs["beam_indices"],
attentions=decoder_attentions,
hidden_states=decoder_hidden_states,
)
@@ -4221,6 +4337,18 @@ def assisted_decoding(
# keep track of which sequences are already finished
unfinished_sequences = input_ids.new(input_ids.shape[0]).fill_(1)
+ # other auxiliary variables
+ max_len = stopping_criteria[0].max_length
+ assistant_kv_indexing = (
+ 1
+ if "bloom" in assistant_model.__class__.__name__.lower()
+ or (
+ assistant_model.config.architectures is not None
+ and "bloom" in assistant_model.config.architectures[0].lower()
+ )
+ else 0
+ )
+
this_peer_finished = False # used by synced_gpus only
while True:
if synced_gpus:
@@ -4235,7 +4363,6 @@ def assisted_decoding(
# Assistant: main logic start
cur_len = input_ids.shape[-1]
- max_len = stopping_criteria[0].max_length
# 1. Forecast next N tokens using the assistant model. This `for` block can be replaced with a
# `.generate()` call if we decide to add `past_key_values` as a possible output of generate, as we
@@ -4244,7 +4371,7 @@ def assisted_decoding(
for _ in range(int(assistant_model.max_assistant_tokens)):
# 1.1. use the assistant model to obtain the next candidate logits
if "assistant_past_key_values" in model_kwargs:
- prev_seq_len = model_kwargs["assistant_past_key_values"][0][0].shape[2]
+ prev_seq_len = model_kwargs["assistant_past_key_values"][0][assistant_kv_indexing].shape[-2]
# `new_token_len` can be 1 or 2 (next token in assistant + last token picked by the larger model)
new_token_len = candidate_input_ids.shape[1] - prev_seq_len
assist_inputs = candidate_input_ids[:, -new_token_len:]
@@ -4310,6 +4437,7 @@ def assisted_decoding(
encoder_outputs=model_kwargs["encoder_outputs"],
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
+ use_cache=True,
)
else:
outputs = self(
@@ -4318,6 +4446,7 @@ def assisted_decoding(
past_key_values=model_kwargs["past_key_values"],
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
+ use_cache=True,
)
else:
if self.config.is_encoder_decoder:
@@ -4326,12 +4455,14 @@ def assisted_decoding(
encoder_outputs=model_kwargs["encoder_outputs"],
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
+ use_cache=True,
)
else:
outputs = self(
candidate_input_ids,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
+ use_cache=True,
)
# 2.2. Process the new logits
@@ -4496,7 +4627,10 @@ def _crop_past_key_values(model, past_key_values, maximum_length):
)
)
past_key_values = tuple(new_past)
- elif "bloom" in model.__class__.__name__.lower(): # bloom is special
+ # bloom is special
+ elif "bloom" in model.__class__.__name__.lower() or (
+ model.config.architectures is not None and "bloom" in model.config.architectures[0].lower()
+ ):
for idx in range(len(past_key_values)):
new_past.append(
(
@@ -4505,6 +4639,16 @@ def _crop_past_key_values(model, past_key_values, maximum_length):
)
)
past_key_values = tuple(new_past)
+ # gptbigcode is too
+ elif "gptbigcode" in model.__class__.__name__.lower() or (
+ model.config.architectures is not None and "gptbigcode" in model.config.architectures[0].lower()
+ ):
+ if model.config.multi_query:
+ for idx in range(len(past_key_values)):
+ past_key_values[idx] = past_key_values[idx][:, :maximum_length, :]
+ else:
+ for idx in range(len(past_key_values)):
+ past_key_values[idx] = past_key_values[idx][:, :, :maximum_length, :]
else:
for idx in range(len(past_key_values)):
new_past.append(
diff --git a/src/transformers/hf_argparser.py b/src/transformers/hf_argparser.py
index b1fa67f45823..34570588744a 100644
--- a/src/transformers/hf_argparser.py
+++ b/src/transformers/hf_argparser.py
@@ -15,24 +15,17 @@
import dataclasses
import json
import sys
+import types
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError
from copy import copy
from enum import Enum
from inspect import isclass
from pathlib import Path
-from typing import Any, Callable, Dict, Iterable, List, NewType, Optional, Tuple, Union, get_type_hints
+from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, Optional, Tuple, Union, get_type_hints
import yaml
-try:
- # For Python versions <3.8, Literal is not in typing: https://peps.python.org/pep-0586/
- from typing import Literal
-except ImportError:
- # For Python 3.7
- from typing_extensions import Literal
-
-
DataClass = NewType("DataClass", Any)
DataClassType = NewType("DataClassType", Any)
@@ -129,8 +122,8 @@ def __init__(self, dataclass_types: Union[DataClassType, Iterable[DataClassType]
Args:
dataclass_types:
Dataclass type, or list of dataclass types for which we will "fill" instances with the parsed args.
- kwargs:
- (Optional) Passed to `argparse.ArgumentParser()` in the regular way.
+ kwargs (`Dict[str, Any]`, *optional*):
+ Passed to `argparse.ArgumentParser()` in the regular way.
"""
# To make the default appear when using --help
if "formatter_class" not in kwargs:
@@ -159,7 +152,7 @@ def _parse_dataclass_field(parser: ArgumentParser, field: dataclasses.Field):
aliases = [aliases]
origin_type = getattr(field.type, "__origin__", field.type)
- if origin_type is Union:
+ if origin_type is Union or (hasattr(types, "UnionType") and isinstance(origin_type, types.UnionType)):
if str not in field.type.__args__ and (
len(field.type.__args__) != 2 or type(None) not in field.type.__args__
):
@@ -245,10 +238,23 @@ def _add_dataclass_arguments(self, dtype: DataClassType):
type_hints: Dict[str, type] = get_type_hints(dtype)
except NameError:
raise RuntimeError(
- f"Type resolution failed for f{dtype}. Try declaring the class in global scope or "
+ f"Type resolution failed for {dtype}. Try declaring the class in global scope or "
"removing line of `from __future__ import annotations` which opts in Postponed "
"Evaluation of Annotations (PEP 563)"
)
+ except TypeError as ex:
+ # Remove this block when we drop Python 3.9 support
+ if sys.version_info[:2] < (3, 10) and "unsupported operand type(s) for |" in str(ex):
+ python_version = ".".join(map(str, sys.version_info[:3]))
+ raise RuntimeError(
+ f"Type resolution failed for {dtype} on Python {python_version}. Try removing "
+ "line of `from __future__ import annotations` which opts in union types as "
+ "`X | Y` (PEP 604) via Postponed Evaluation of Annotations (PEP 563). To "
+ "support Python versions that lower than 3.10, you need to use "
+ "`typing.Union[X, Y]` instead of `X | Y` and `typing.Optional[X]` instead of "
+ "`X | None`."
+ ) from ex
+ raise
for field in dataclasses.fields(dtype):
if not field.init:
@@ -387,8 +393,8 @@ def parse_json_file(self, json_file: str, allow_extra_keys: bool = False) -> Tup
- the dataclass instances in the same order as they were passed to the initializer.
"""
- open_json_file = open(Path(json_file))
- data = json.loads(open_json_file.read())
+ with open(Path(json_file), encoding="utf-8") as open_json_file:
+ data = json.loads(open_json_file.read())
outputs = self.parse_dict(data, allow_extra_keys=allow_extra_keys)
return tuple(outputs)
diff --git a/src/transformers/hyperparameter_search.py b/src/transformers/hyperparameter_search.py
new file mode 100644
index 000000000000..8dfd60cc39cd
--- /dev/null
+++ b/src/transformers/hyperparameter_search.py
@@ -0,0 +1,141 @@
+# coding=utf-8
+# Copyright 2023-present the HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from .integrations import (
+ is_optuna_available,
+ is_ray_available,
+ is_sigopt_available,
+ is_wandb_available,
+ run_hp_search_optuna,
+ run_hp_search_ray,
+ run_hp_search_sigopt,
+ run_hp_search_wandb,
+)
+from .trainer_utils import (
+ HPSearchBackend,
+ default_hp_space_optuna,
+ default_hp_space_ray,
+ default_hp_space_sigopt,
+ default_hp_space_wandb,
+)
+from .utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+
+class HyperParamSearchBackendBase:
+ name: str
+ pip_package: str = None
+
+ @staticmethod
+ def is_available():
+ raise NotImplementedError
+
+ def run(self, trainer, n_trials: int, direction: str, **kwargs):
+ raise NotImplementedError
+
+ def default_hp_space(self, trial):
+ raise NotImplementedError
+
+ def ensure_available(self):
+ if not self.is_available():
+ raise RuntimeError(
+ f"You picked the {self.name} backend, but it is not installed. Run {self.pip_install()}."
+ )
+
+ @classmethod
+ def pip_install(cls):
+ return f"`pip install {cls.pip_package or cls.name}`"
+
+
+class OptunaBackend(HyperParamSearchBackendBase):
+ name = "optuna"
+
+ @staticmethod
+ def is_available():
+ return is_optuna_available()
+
+ def run(self, trainer, n_trials: int, direction: str, **kwargs):
+ return run_hp_search_optuna(trainer, n_trials, direction, **kwargs)
+
+ def default_hp_space(self, trial):
+ return default_hp_space_optuna(trial)
+
+
+class RayTuneBackend(HyperParamSearchBackendBase):
+ name = "ray"
+ pip_package = "'ray[tune]'"
+
+ @staticmethod
+ def is_available():
+ return is_ray_available()
+
+ def run(self, trainer, n_trials: int, direction: str, **kwargs):
+ return run_hp_search_ray(trainer, n_trials, direction, **kwargs)
+
+ def default_hp_space(self, trial):
+ return default_hp_space_ray(trial)
+
+
+class SigOptBackend(HyperParamSearchBackendBase):
+ name = "sigopt"
+
+ @staticmethod
+ def is_available():
+ return is_sigopt_available()
+
+ def run(self, trainer, n_trials: int, direction: str, **kwargs):
+ return run_hp_search_sigopt(trainer, n_trials, direction, **kwargs)
+
+ def default_hp_space(self, trial):
+ return default_hp_space_sigopt(trial)
+
+
+class WandbBackend(HyperParamSearchBackendBase):
+ name = "wandb"
+
+ @staticmethod
+ def is_available():
+ return is_wandb_available()
+
+ def run(self, trainer, n_trials: int, direction: str, **kwargs):
+ return run_hp_search_wandb(trainer, n_trials, direction, **kwargs)
+
+ def default_hp_space(self, trial):
+ return default_hp_space_wandb(trial)
+
+
+ALL_HYPERPARAMETER_SEARCH_BACKENDS = {
+ HPSearchBackend(backend.name): backend for backend in [OptunaBackend, RayTuneBackend, SigOptBackend, WandbBackend]
+}
+
+
+def default_hp_search_backend() -> str:
+ available_backends = [backend for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() if backend.is_available()]
+ if len(available_backends) > 0:
+ name = available_backends[0].name
+ if len(available_backends) > 1:
+ logger.info(
+ f"{len(available_backends)} hyperparameter search backends available. Using {name} as the default."
+ )
+ return name
+ raise RuntimeError(
+ "No hyperparameter search backend available.\n"
+ + "\n".join(
+ f" - To install {backend.name} run {backend.pip_install()}"
+ for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values()
+ )
+ )
diff --git a/src/transformers/image_processing_utils.py b/src/transformers/image_processing_utils.py
index d51c9eebd227..078858909183 100644
--- a/src/transformers/image_processing_utils.py
+++ b/src/transformers/image_processing_utils.py
@@ -16,12 +16,15 @@
import copy
import json
import os
+import warnings
from typing import Any, Dict, Iterable, Optional, Tuple, Union
import numpy as np
from .dynamic_module_utils import custom_object_save
from .feature_extraction_utils import BatchFeature as BaseBatchFeature
+from .image_transforms import center_crop, normalize, rescale
+from .image_utils import ChannelDimension
from .utils import (
IMAGE_PROCESSOR_NAME,
PushToHubMixin,
@@ -81,7 +84,16 @@ def _set_processor_class(self, processor_class: str):
self._processor_class = processor_class
@classmethod
- def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs):
+ def from_pretrained(
+ cls,
+ pretrained_model_name_or_path: Union[str, os.PathLike],
+ cache_dir: Optional[Union[str, os.PathLike]] = None,
+ force_download: bool = False,
+ local_files_only: bool = False,
+ token: Optional[Union[str, bool]] = None,
+ revision: str = "main",
+ **kwargs,
+ ):
r"""
Instantiate a type of [`~image_processing_utils.ImageProcessingMixin`] from an image processor.
@@ -109,7 +121,7 @@ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike],
proxies (`Dict[str, str]`, *optional*):
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
- use_auth_token (`str` or `bool`, *optional*):
+ token (`str` or `bool`, *optional*):
The token to use as HTTP bearer authorization for remote files. If `True`, or not specified, will use
the token generated when running `huggingface-cli login` (stored in `~/.huggingface`).
revision (`str`, *optional*, defaults to `"main"`):
@@ -162,6 +174,25 @@ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike],
assert image_processor.do_normalize is False
assert unused_kwargs == {"foo": False}
```"""
+ kwargs["cache_dir"] = cache_dir
+ kwargs["force_download"] = force_download
+ kwargs["local_files_only"] = local_files_only
+ kwargs["revision"] = revision
+
+ use_auth_token = kwargs.pop("use_auth_token", None)
+ if use_auth_token is not None:
+ warnings.warn(
+ "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers.", FutureWarning
+ )
+ if token is not None:
+ raise ValueError(
+ "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
+ )
+ token = use_auth_token
+
+ if token is not None:
+ kwargs["token"] = token
+
image_processor_dict, kwargs = cls.get_image_processor_dict(pretrained_model_name_or_path, **kwargs)
return cls.from_dict(image_processor_dict, **kwargs)
@@ -178,9 +209,21 @@ def save_pretrained(self, save_directory: Union[str, os.PathLike], push_to_hub:
Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the
repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
namespace).
- kwargs:
+ kwargs (`Dict[str, Any]`, *optional*):
Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
"""
+ use_auth_token = kwargs.pop("use_auth_token", None)
+
+ if use_auth_token is not None:
+ warnings.warn(
+ "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers.", FutureWarning
+ )
+ if kwargs.get("token", None) is not None:
+ raise ValueError(
+ "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
+ )
+ kwargs["token"] = use_auth_token
+
if os.path.isfile(save_directory):
raise AssertionError(f"Provided path ({save_directory}) should be a directory, not a file")
@@ -209,7 +252,7 @@ def save_pretrained(self, save_directory: Union[str, os.PathLike], push_to_hub:
repo_id,
files_timestamps,
commit_message=commit_message,
- token=kwargs.get("use_auth_token"),
+ token=kwargs.get("token"),
)
return [output_image_processor_file]
@@ -236,6 +279,7 @@ def get_image_processor_dict(
force_download = kwargs.pop("force_download", False)
resume_download = kwargs.pop("resume_download", False)
proxies = kwargs.pop("proxies", None)
+ token = kwargs.pop("token", None)
use_auth_token = kwargs.pop("use_auth_token", None)
local_files_only = kwargs.pop("local_files_only", False)
revision = kwargs.pop("revision", None)
@@ -244,6 +288,16 @@ def get_image_processor_dict(
from_pipeline = kwargs.pop("_from_pipeline", None)
from_auto_class = kwargs.pop("_from_auto", False)
+ if use_auth_token is not None:
+ warnings.warn(
+ "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers.", FutureWarning
+ )
+ if token is not None:
+ raise ValueError(
+ "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
+ )
+ token = use_auth_token
+
user_agent = {"file_type": "image processor", "from_auto_class": from_auto_class}
if from_pipeline is not None:
user_agent["using_pipeline"] = from_pipeline
@@ -274,7 +328,7 @@ def get_image_processor_dict(
proxies=proxies,
resume_download=resume_download,
local_files_only=local_files_only,
- use_auth_token=use_auth_token,
+ token=token,
user_agent=user_agent,
revision=revision,
subfolder=subfolder,
@@ -466,6 +520,81 @@ def __call__(self, images, **kwargs) -> BatchFeature:
def preprocess(self, images, **kwargs) -> BatchFeature:
raise NotImplementedError("Each image processor must implement its own preprocess method")
+ def rescale(
+ self, image: np.ndarray, scale: float, data_format: Optional[Union[str, ChannelDimension]] = None, **kwargs
+ ) -> np.ndarray:
+ """
+ Rescale an image by a scale factor. image = image * scale.
+
+ Args:
+ image (`np.ndarray`):
+ Image to rescale.
+ scale (`float`):
+ The scaling factor to rescale pixel values by.
+ data_format (`str` or `ChannelDimension`, *optional*):
+ The channel dimension format for the output image. If unset, the channel dimension format of the input
+ image is used. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+
+ Returns:
+ `np.ndarray`: The rescaled image.
+ """
+ return rescale(image, scale=scale, data_format=data_format, **kwargs)
+
+ def normalize(
+ self,
+ image: np.ndarray,
+ mean: Union[float, Iterable[float]],
+ std: Union[float, Iterable[float]],
+ data_format: Optional[Union[str, ChannelDimension]] = None,
+ **kwargs,
+ ) -> np.ndarray:
+ """
+ Normalize an image. image = (image - image_mean) / image_std.
+
+ Args:
+ image (`np.ndarray`):
+ Image to normalize.
+ mean (`float` or `Iterable[float]`):
+ Image mean to use for normalization.
+ std (`float` or `Iterable[float]`):
+ Image standard deviation to use for normalization.
+ data_format (`str` or `ChannelDimension`, *optional*):
+ The channel dimension format for the output image. If unset, the channel dimension format of the input
+ image is used. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+
+ Returns:
+ `np.ndarray`: The normalized image.
+ """
+ return normalize(image, mean=mean, std=std, data_format=data_format, **kwargs)
+
+ def center_crop(
+ self,
+ image: np.ndarray,
+ size: Dict[str, int],
+ data_format: Optional[Union[str, ChannelDimension]] = None,
+ **kwargs,
+ ) -> np.ndarray:
+ """
+ Center crop an image to `(size["height"], size["width"])`. If the input size is smaller than `crop_size` along
+ any edge, the image is padded with 0's and then center cropped.
+
+ Args:
+ image (`np.ndarray`):
+ Image to center crop.
+ size (`Dict[str, int]`):
+ Size of the output image.
+ data_format (`str` or `ChannelDimension`, *optional*):
+ The channel dimension format of the image. If not provided, it will be the same as the input image.
+ """
+ size = get_size_dict(size)
+ if "height" not in size or "width" not in size:
+ raise ValueError(f"The size dictionary must have keys 'height' and 'width'. Got {size.keys()}")
+ return center_crop(image, size=(size["height"], size["width"]), data_format=data_format, **kwargs)
+
VALID_SIZE_DICT_KEYS = ({"height", "width"}, {"shortest_edge"}, {"shortest_edge", "longest_edge"}, {"longest_edge"})
diff --git a/src/transformers/image_transforms.py b/src/transformers/image_transforms.py
index 369ddc8d4c00..d1621492d667 100644
--- a/src/transformers/image_transforms.py
+++ b/src/transformers/image_transforms.py
@@ -24,7 +24,6 @@
get_channel_dimension_axis,
get_image_size,
infer_channel_dimension_format,
- to_numpy_array,
)
from .utils import ExplicitEnum, TensorType, is_jax_tensor, is_tf_tensor, is_torch_tensor
from .utils.import_utils import (
@@ -114,7 +113,9 @@ def rescale(
rescaled_image = image * scale
if data_format is not None:
rescaled_image = to_channel_dimension_format(rescaled_image, data_format)
+
rescaled_image = rescaled_image.astype(dtype)
+
return rescaled_image
@@ -345,18 +346,6 @@ def normalize(
data_format (`ChannelDimension`, *optional*):
The channel dimension format of the output image. If unset, will use the inferred format from the input.
"""
- requires_backends(normalize, ["vision"])
-
- if isinstance(image, PIL.Image.Image):
- warnings.warn(
- "PIL.Image.Image inputs are deprecated and will be removed in v4.26.0. Please use numpy arrays instead.",
- FutureWarning,
- )
- # Convert PIL image to numpy array with the same logic as in the previous feature extractor normalize -
- # casting to numpy array and dividing by 255.
- image = to_numpy_array(image)
- image = rescale(image, scale=1 / 255)
-
if not isinstance(image, np.ndarray):
raise ValueError("image must be a numpy array")
@@ -418,15 +407,10 @@ def center_crop(
"""
requires_backends(center_crop, ["vision"])
- if isinstance(image, PIL.Image.Image):
- warnings.warn(
- "PIL.Image.Image inputs are deprecated and will be removed in v4.26.0. Please use numpy arrays instead.",
- FutureWarning,
- )
- image = to_numpy_array(image)
- return_numpy = False if return_numpy is None else return_numpy
- else:
- return_numpy = True if return_numpy is None else return_numpy
+ if return_numpy is not None:
+ warnings.warn("return_numpy is deprecated and will be removed in v.4.33", FutureWarning)
+
+ return_numpy = True if return_numpy is None else return_numpy
if not isinstance(image, np.ndarray):
raise ValueError(f"Input image must be of type np.ndarray, got {type(image)}")
@@ -742,3 +726,32 @@ def convert_to_rgb(image: ImageInput) -> ImageInput:
image = image.convert("RGB")
return image
+
+
+def flip_channel_order(image: np.ndarray, data_format: Optional[ChannelDimension] = None) -> np.ndarray:
+ """
+ Flips the channel order of the image.
+
+ If the image is in RGB format, it will be converted to BGR and vice versa.
+
+ Args:
+ image (`np.ndarray`):
+ The image to flip.
+ data_format (`ChannelDimension`, *optional*):
+ The channel dimension format for the output image. Can be one of:
+ - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ If unset, will use same as the input image.
+ """
+
+ input_data_format = infer_channel_dimension_format(image)
+ if input_data_format == ChannelDimension.LAST:
+ image = image[..., ::-1]
+ elif input_data_format == ChannelDimension.FIRST:
+ image = image[::-1, ...]
+ else:
+ raise ValueError(f"Unsupported channel dimension: {input_data_format}")
+
+ if data_format is not None:
+ image = to_channel_dimension_format(image, data_format)
+ return image
diff --git a/src/transformers/image_utils.py b/src/transformers/image_utils.py
index 08ec05fa09c3..72ed45492baf 100644
--- a/src/transformers/image_utils.py
+++ b/src/transformers/image_utils.py
@@ -14,7 +14,7 @@
# limitations under the License.
import os
-from typing import TYPE_CHECKING, Dict, Iterable, List, Tuple, Union
+from typing import TYPE_CHECKING, Dict, Iterable, List, Optional, Tuple, Union
import numpy as np
import requests
@@ -64,6 +64,10 @@ class ChannelDimension(ExplicitEnum):
LAST = "channels_last"
+def is_pil_image(img):
+ return is_vision_available() and isinstance(img, PIL.Image.Image)
+
+
def is_valid_image(img):
return (
(is_vision_available() and isinstance(img, PIL.Image.Image))
@@ -140,17 +144,24 @@ def to_numpy_array(img) -> np.ndarray:
return to_numpy(img)
-def infer_channel_dimension_format(image: np.ndarray) -> ChannelDimension:
+def infer_channel_dimension_format(
+ image: np.ndarray, num_channels: Optional[Union[int, Tuple[int, ...]]] = None
+) -> ChannelDimension:
"""
Infers the channel dimension format of `image`.
Args:
image (`np.ndarray`):
The image to infer the channel dimension of.
+ num_channels (`int` or `Tuple[int, ...]`, *optional*, defaults to `(1, 3)`):
+ The number of channels of the image.
Returns:
The channel dimension of the image.
"""
+ num_channels = num_channels if num_channels is not None else (1, 3)
+ num_channels = (num_channels,) if isinstance(num_channels, int) else num_channels
+
if image.ndim == 3:
first_dim, last_dim = 0, 2
elif image.ndim == 4:
@@ -158,9 +169,9 @@ def infer_channel_dimension_format(image: np.ndarray) -> ChannelDimension:
else:
raise ValueError(f"Unsupported number of image dimensions: {image.ndim}")
- if image.shape[first_dim] in (1, 3):
+ if image.shape[first_dim] in num_channels:
return ChannelDimension.FIRST
- elif image.shape[last_dim] in (1, 3):
+ elif image.shape[last_dim] in num_channels:
return ChannelDimension.LAST
raise ValueError("Unable to infer channel dimension format")
@@ -249,13 +260,15 @@ def valid_coco_panoptic_annotations(annotations: Iterable[Dict[str, Union[List,
return all(is_valid_annotation_coco_panoptic(ann) for ann in annotations)
-def load_image(image: Union[str, "PIL.Image.Image"]) -> "PIL.Image.Image":
+def load_image(image: Union[str, "PIL.Image.Image"], timeout: Optional[float] = None) -> "PIL.Image.Image":
"""
Loads `image` to a PIL Image.
Args:
image (`str` or `PIL.Image.Image`):
The image to convert to the PIL Image format.
+ timeout (`float`, *optional*):
+ The timeout value in seconds for the URL request.
Returns:
`PIL.Image.Image`: A PIL Image.
@@ -265,7 +278,7 @@ def load_image(image: Union[str, "PIL.Image.Image"]) -> "PIL.Image.Image":
if image.startswith("http://") or image.startswith("https://"):
# We need to actually check for a real protocol, otherwise it's impossible to use a local file
# like http_huggingface_co.png
- image = PIL.Image.open(requests.get(image, stream=True).raw)
+ image = PIL.Image.open(requests.get(image, stream=True, timeout=timeout).raw)
elif os.path.isfile(image):
image = PIL.Image.open(image)
else:
diff --git a/src/transformers/integrations.py b/src/transformers/integrations.py
index 4b0e1c590d82..112c1a7a5525 100644
--- a/src/transformers/integrations.py
+++ b/src/transformers/integrations.py
@@ -15,6 +15,7 @@
Integrations with other Python libraries.
"""
import functools
+import importlib.metadata
import importlib.util
import json
import numbers
@@ -30,8 +31,7 @@
import numpy as np
from . import __version__ as version
-from .utils import flatten_dict, is_datasets_available, is_torch_available, logging
-from .utils.versions import importlib_metadata
+from .utils import flatten_dict, is_datasets_available, is_pandas_available, is_torch_available, logging
logger = logging.get_logger(__name__)
@@ -59,13 +59,13 @@
)
if TYPE_CHECKING and _has_neptune:
try:
- _neptune_version = importlib_metadata.version("neptune")
+ _neptune_version = importlib.metadata.version("neptune")
logger.info(f"Neptune version {_neptune_version} available.")
- except importlib_metadata.PackageNotFoundError:
+ except importlib.metadata.PackageNotFoundError:
try:
- _neptune_version = importlib_metadata.version("neptune-client")
+ _neptune_version = importlib.metadata.version("neptune-client")
logger.info(f"Neptune-client version {_neptune_version} available.")
- except importlib_metadata.PackageNotFoundError:
+ except importlib.metadata.PackageNotFoundError:
_has_neptune = False
from .trainer_callback import ProgressCallback, TrainerCallback # noqa: E402
@@ -146,6 +146,16 @@ def is_codecarbon_available():
return importlib.util.find_spec("codecarbon") is not None
+def is_flytekit_available():
+ return importlib.util.find_spec("flytekit") is not None
+
+
+def is_flyte_deck_standard_available():
+ if not is_flytekit_available():
+ return False
+ return importlib.util.find_spec("flytekitplugins.deck") is not None
+
+
def hp_params(trial):
if is_optuna_available():
import optuna
@@ -167,15 +177,6 @@ def hp_params(trial):
raise RuntimeError(f"Unknown type for trial {trial.__class__}")
-def default_hp_search_backend():
- if is_optuna_available():
- return "optuna"
- elif is_ray_tune_available():
- return "ray"
- elif is_sigopt_available():
- return "sigopt"
-
-
def run_hp_search_optuna(trainer, n_trials: int, direction: str, **kwargs) -> BestRun:
import optuna
@@ -366,10 +367,8 @@ def dynamic_modules_import_trainable(*args, **kwargs):
def run_hp_search_sigopt(trainer, n_trials: int, direction: str, **kwargs) -> BestRun:
import sigopt
- from transformers.utils.versions import importlib_metadata
-
if trainer.args.process_index == 0:
- if importlib_metadata.version("sigopt") >= "8.0.0":
+ if importlib.metadata.version("sigopt") >= "8.0.0":
sigopt.set_project("huggingface")
experiment = sigopt.create_experiment(
@@ -629,9 +628,6 @@ def on_train_begin(self, args, state, control, **kwargs):
if hasattr(model, "config") and model.config is not None:
model_config_json = model.config.to_json_string()
self.tb_writer.add_text("model_config", model_config_json)
- # Version of TensorBoard coming from tensorboardX does not have this method.
- if hasattr(self.tb_writer, "add_hparams"):
- self.tb_writer.add_hparams(args.to_sanitized_dict(), metric_dict={})
def on_log(self, args, state, control, logs=None, **kwargs):
if not state.is_world_process_zero:
@@ -720,7 +716,7 @@ def setup(self, args, state, model, **kwargs):
logger.info(
'Automatic Weights & Biases logging enabled, to disable set os.environ["WANDB_DISABLED"] = "true"'
)
- combined_dict = {**args.to_sanitized_dict()}
+ combined_dict = {**args.to_dict()}
if hasattr(model, "config") and model.config is not None:
model_config = model.config.to_dict()
@@ -750,7 +746,7 @@ def setup(self, args, state, model, **kwargs):
# keep track of model topology and gradients, unsupported on TPU
_watch_model = os.getenv("WANDB_WATCH", "false")
if not is_torch_tpu_available() and _watch_model in ("all", "parameters", "gradients"):
- self._wandb.watch(model, log=_watch_model, log_freq=max(100, args.logging_steps))
+ self._wandb.watch(model, log=_watch_model, log_freq=max(100, state.logging_steps))
def on_train_begin(self, args, state, control, model=None, **kwargs):
if self._wandb is None:
@@ -1537,6 +1533,69 @@ def on_save(self, args, state, control, **kwargs):
self._clearml_task.update_output_model(artifact_path, iteration=state.global_step, auto_delete_file=False)
+class FlyteCallback(TrainerCallback):
+ """A [`TrainerCallback`] that sends the logs to [Flyte](https://flyte.org/).
+ NOTE: This callback only works within a Flyte task.
+
+ Args:
+ save_log_history (`bool`, *optional*, defaults to `True`):
+ When set to True, the training logs are saved as a Flyte Deck.
+
+ sync_checkpoints (`bool`, *optional*, defaults to `True`):
+ When set to True, checkpoints are synced with Flyte and can be used to resume training in the case of an
+ interruption.
+
+ Example:
+
+ ```python
+ # Note: This example skips over some setup steps for brevity.
+ from flytekit import current_context, task
+
+
+ @task
+ def train_hf_transformer():
+ cp = current_context().checkpoint
+ trainer = Trainer(..., callbacks=[FlyteCallback()])
+ output = trainer.train(resume_from_checkpoint=cp.restore())
+ ```
+ """
+
+ def __init__(self, save_log_history: bool = True, sync_checkpoints: bool = True):
+ super().__init__()
+ if not is_flytekit_available():
+ raise ImportError("FlyteCallback requires flytekit to be installed. Run `pip install flytekit`.")
+
+ if not is_flyte_deck_standard_available() or not is_pandas_available():
+ logger.warning(
+ "Syncing log history requires both flytekitplugins-deck-standard and pandas to be installed. "
+ "Run `pip install flytekitplugins-deck-standard pandas` to enable this feature."
+ )
+ save_log_history = False
+
+ from flytekit import current_context
+
+ self.cp = current_context().checkpoint
+ self.save_log_history = save_log_history
+ self.sync_checkpoints = sync_checkpoints
+
+ def on_save(self, args, state, control, **kwargs):
+ if self.sync_checkpoints and state.is_world_process_zero:
+ ckpt_dir = f"checkpoint-{state.global_step}"
+ artifact_path = os.path.join(args.output_dir, ckpt_dir)
+
+ logger.info(f"Syncing checkpoint in {ckpt_dir} to Flyte. This may take time.")
+ self.cp.save(artifact_path)
+
+ def on_train_end(self, args, state, control, **kwargs):
+ if self.save_log_history:
+ import pandas as pd
+ from flytekit import Deck
+ from flytekitplugins.deck.renderer import TableRenderer
+
+ log_history_df = pd.DataFrame(state.log_history)
+ Deck("Log History", TableRenderer().to_html(log_history_df))
+
+
INTEGRATION_TO_CALLBACK = {
"azure_ml": AzureMLCallback,
"comet_ml": CometCallback,
@@ -1547,6 +1606,7 @@ def on_save(self, args, state, control, **kwargs):
"codecarbon": CodeCarbonCallback,
"clearml": ClearMLCallback,
"dagshub": DagsHubCallback,
+ "flyte": FlyteCallback,
}
diff --git a/src/transformers/keras_callbacks.py b/src/transformers/keras_callbacks.py
index a9d75c9aeeaa..3bb4e859b1c6 100644
--- a/src/transformers/keras_callbacks.py
+++ b/src/transformers/keras_callbacks.py
@@ -12,7 +12,6 @@
from . import IntervalStrategy, PreTrainedTokenizerBase
from .modelcard import TrainingSummary
-from .utils import get_full_repo_name
logger = logging.getLogger(__name__)
@@ -144,7 +143,7 @@ def __init__(
@staticmethod
def _concatenate_batches(batches, padding_index=-100):
# If all batches are unidimensional or same length, do a simple concatenation
- if batches[0].ndim == 1 or all([batch.shape[1] == batches[0].shape[1] for batch in batches]):
+ if batches[0].ndim == 1 or all(batch.shape[1] == batches[0].shape[1] for batch in batches):
return np.concatenate(batches, axis=0)
# Welp, they're not the same length. Let's do some padding
@@ -193,8 +192,7 @@ def on_epoch_end(self, epoch, logs=None):
# This dense conditional recognizes the case where we have an encoder-decoder model, but
# avoids getting tangled up when we just have a model with a layer called 'encoder'
if hasattr(self.model, "encoder") and hasattr(self.model.encoder, "main_input_name"):
- if self.model.encoder.main_input_name != self.model.main_input_name:
- main_input_name = self.model.encoder.main_input_name
+ main_input_name = self.model.encoder.main_input_name
else:
main_input_name = getattr(self.model, "main_input_name", "input_ids")
@@ -224,7 +222,9 @@ def generation_function(inputs, attention_mask):
if self.use_xla_generation:
predictions = self.generation_function(generation_inputs, attention_mask=attention_mask)
else:
- predictions = self.model.generate(generation_inputs, attention_mask=attention_mask)
+ predictions = self.model.generate(
+ generation_inputs, attention_mask=attention_mask, **self.generate_kwargs
+ )
else:
predictions = self.model.predict_on_batch(batch)
if isinstance(predictions, dict):
@@ -333,14 +333,13 @@ def __init__(
raise ValueError("Please supply a positive integer argument for save_steps when save_strategy == 'steps'!")
self.save_steps = save_steps
output_dir = Path(output_dir)
+
+ # Create repo and retrieve repo_id
if hub_model_id is None:
hub_model_id = output_dir.absolute().name
- if "/" not in hub_model_id:
- hub_model_id = get_full_repo_name(hub_model_id, token=hub_token)
+ self.hub_model_id = create_repo(repo_id=hub_model_id, exist_ok=True, token=hub_token).repo_id
self.output_dir = output_dir
- self.hub_model_id = hub_model_id
- create_repo(self.hub_model_id, exist_ok=True)
self.repo = Repository(str(self.output_dir), clone_from=self.hub_model_id, token=hub_token)
self.tokenizer = tokenizer
diff --git a/src/transformers/models/deformable_detr/custom_kernel/cpu/ms_deform_attn_cpu.cpp b/src/transformers/kernels/deformable_detr/cpu/ms_deform_attn_cpu.cpp
similarity index 100%
rename from src/transformers/models/deformable_detr/custom_kernel/cpu/ms_deform_attn_cpu.cpp
rename to src/transformers/kernels/deformable_detr/cpu/ms_deform_attn_cpu.cpp
diff --git a/src/transformers/models/deformable_detr/custom_kernel/cpu/ms_deform_attn_cpu.h b/src/transformers/kernels/deformable_detr/cpu/ms_deform_attn_cpu.h
similarity index 100%
rename from src/transformers/models/deformable_detr/custom_kernel/cpu/ms_deform_attn_cpu.h
rename to src/transformers/kernels/deformable_detr/cpu/ms_deform_attn_cpu.h
diff --git a/src/transformers/models/deformable_detr/custom_kernel/cuda/ms_deform_attn_cuda.cu b/src/transformers/kernels/deformable_detr/cuda/ms_deform_attn_cuda.cu
similarity index 100%
rename from src/transformers/models/deformable_detr/custom_kernel/cuda/ms_deform_attn_cuda.cu
rename to src/transformers/kernels/deformable_detr/cuda/ms_deform_attn_cuda.cu
diff --git a/src/transformers/models/deformable_detr/custom_kernel/cuda/ms_deform_attn_cuda.cuh b/src/transformers/kernels/deformable_detr/cuda/ms_deform_attn_cuda.cuh
similarity index 100%
rename from src/transformers/models/deformable_detr/custom_kernel/cuda/ms_deform_attn_cuda.cuh
rename to src/transformers/kernels/deformable_detr/cuda/ms_deform_attn_cuda.cuh
diff --git a/src/transformers/models/deformable_detr/custom_kernel/cuda/ms_deform_attn_cuda.h b/src/transformers/kernels/deformable_detr/cuda/ms_deform_attn_cuda.h
similarity index 100%
rename from src/transformers/models/deformable_detr/custom_kernel/cuda/ms_deform_attn_cuda.h
rename to src/transformers/kernels/deformable_detr/cuda/ms_deform_attn_cuda.h
diff --git a/src/transformers/models/deformable_detr/custom_kernel/cuda/ms_deform_im2col_cuda.cuh b/src/transformers/kernels/deformable_detr/cuda/ms_deform_im2col_cuda.cuh
similarity index 100%
rename from src/transformers/models/deformable_detr/custom_kernel/cuda/ms_deform_im2col_cuda.cuh
rename to src/transformers/kernels/deformable_detr/cuda/ms_deform_im2col_cuda.cuh
diff --git a/src/transformers/models/deformable_detr/custom_kernel/ms_deform_attn.h b/src/transformers/kernels/deformable_detr/ms_deform_attn.h
similarity index 100%
rename from src/transformers/models/deformable_detr/custom_kernel/ms_deform_attn.h
rename to src/transformers/kernels/deformable_detr/ms_deform_attn.h
diff --git a/src/transformers/models/deformable_detr/custom_kernel/vision.cpp b/src/transformers/kernels/deformable_detr/vision.cpp
similarity index 100%
rename from src/transformers/models/deformable_detr/custom_kernel/vision.cpp
rename to src/transformers/kernels/deformable_detr/vision.cpp
diff --git a/src/transformers/kernels/mra/cuda_kernel.cu b/src/transformers/kernels/mra/cuda_kernel.cu
new file mode 100644
index 000000000000..87ed89052873
--- /dev/null
+++ b/src/transformers/kernels/mra/cuda_kernel.cu
@@ -0,0 +1,383 @@
+#include "cuda_kernel.h"
+
+//////////////////////////////////////////////////////////////////////////////////////////////////
+//////////////////////////////////////////////////////////////////////////////////////////////////
+
+__global__ void index_max_cuda_kernel(
+ float *index_vals, // [batch_size, 32, num_block]
+ int *indices, // [batch_size, num_block]
+ float *max_vals, // [batch_size, A_num_block * 32]
+ float *max_vals_scatter, // [batch_size, 32, num_block]
+ long batch_size,
+ long A_num_block,
+ long B_num_block,
+ long num_block
+) {
+
+ long batch_idx = blockIdx.x;
+
+ long thread_idx = threadIdx.x;
+ long num_thread = blockDim.x;
+
+ extern __shared__ float buffer[];
+ int *max_buffer = (int*)buffer;
+
+ for (int i = 0; i < A_num_block * 32; i = i + num_thread) {
+ int idx = i + thread_idx;
+ if (idx < A_num_block * 32) {
+ max_buffer[idx] = -1e8;
+ }
+ }
+ __syncthreads();
+
+ int *indices_pt = &indices[batch_idx * num_block];
+ float *index_vals_pt = &index_vals[batch_idx * num_block * 32];
+
+ for (int idx_start = 0; idx_start < 32 * num_block; idx_start = idx_start + num_thread) {
+ int idx = idx_start + thread_idx;
+ int A_block_idx = indices_pt[idx % num_block] / B_num_block;
+ atomicMax(&max_buffer[A_block_idx * 32 + idx / num_block], (int)(index_vals_pt[idx] * 1000));
+ }
+ __syncthreads();
+
+ float *max_vals_pt = &max_vals[batch_idx * A_num_block * 32];
+ for (int i = 0; i < A_num_block * 32; i = i + num_thread) {
+ int idx = i + thread_idx;
+ if (idx < A_num_block * 32) {
+ max_vals_pt[idx] = (float)max_buffer[idx] / 1000.;
+ }
+ }
+
+ float *max_vals_scatter_pt = &max_vals_scatter[batch_idx * num_block * 32];
+ for (int idx_start = 0; idx_start < 32 * num_block; idx_start = idx_start + num_thread) {
+ int idx = idx_start + thread_idx;
+ int A_block_idx = indices_pt[idx % num_block] / B_num_block;
+ max_vals_scatter_pt[idx] = (float)max_buffer[A_block_idx * 32 + idx / num_block] / 1000.;
+ }
+
+}
+
+__global__ void mm_to_sparse_cuda_kernel(
+ float *dense_A, // [batch_size, A_num_block, dim, 32]
+ float *dense_B, // [batch_size, B_num_block, dim, 32]
+ int *indices, // [batch_size, num_block]
+ float *sparse_C, // [batch_size, num_block, 32, 32]
+ long batch_size,
+ long A_num_block,
+ long B_num_block,
+ long dim,
+ long num_block
+) {
+
+ long batch_idx = blockIdx.y;
+ long block_idx = blockIdx.x * blockDim.y + threadIdx.y;
+
+ long thread_idx = threadIdx.x;
+
+ __shared__ float buffer[4096];
+ float *A_buffer = &buffer[threadIdx.y * 1024]; // [2, 8, 32]
+ float *B_buffer = &buffer[threadIdx.y * 1024 + 512]; // [2, 8, 32]
+
+ long batch_idx__block_idx = batch_idx * num_block + block_idx;
+
+ long AB_block_idx = indices[batch_idx__block_idx];
+ float *dense_A_pt = &dense_A[(batch_idx * A_num_block + AB_block_idx / B_num_block) * dim * 32];
+ float *dense_B_pt = &dense_B[(batch_idx * B_num_block + AB_block_idx % B_num_block) * dim * 32];
+
+ int reg_1_idx = thread_idx / 8; // [0000000011111111222222223333333344444444555555556666666677777777]
+ int reg_2_idx = thread_idx % 8; // [0123456701234567012345670123456701234567012345670123456701234567]
+
+ float reg_1[8];
+ float reg_2[8];
+
+ float reg_array[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
+
+ #pragma unroll
+ for (int i = 0; i < 4; i++) {
+ A_buffer[i * 64 + thread_idx] = dense_A_pt[i * 64 + thread_idx];
+ B_buffer[i * 64 + thread_idx] = dense_B_pt[i * 64 + thread_idx];
+ }
+
+ __syncthreads();
+
+ #pragma unroll
+ for (int i = 0; i < 4; i++) {
+ reg_1[i] = A_buffer[reg_1_idx * 4 + i];
+ reg_2[i] = B_buffer[reg_2_idx * 4 + i];
+ }
+
+ for (int dim_stride = 1; dim_stride < (dim / 8); dim_stride++) {
+
+ #pragma unroll
+ for (int i = 0; i < 4; i++) {
+ A_buffer[(dim_stride % 2) * 256 + i * 64 + thread_idx] = dense_A_pt[dim_stride * 256 + i * 64 + thread_idx];
+ B_buffer[(dim_stride % 2) * 256 + i * 64 + thread_idx] = dense_B_pt[dim_stride * 256 + i * 64 + thread_idx];
+ }
+
+ #pragma unroll
+ for (int mini_dim_idx = 1; mini_dim_idx < 8; mini_dim_idx++) {
+ #pragma unroll
+ for (int i = 0; i < 4; i++) {
+ reg_1[(mini_dim_idx % 2) * 4 + i] = A_buffer[((dim_stride - 1) % 2) * 256 + mini_dim_idx * 32 + reg_1_idx * 4 + i];
+ reg_2[(mini_dim_idx % 2) * 4 + i] = B_buffer[((dim_stride - 1) % 2) * 256 + mini_dim_idx * 32 + reg_2_idx * 4 + i];
+ }
+ #pragma unroll
+ for (int i = 0; i < 4; i++) {
+ #pragma unroll
+ for (int j = 0; j < 4; j++) {
+ reg_array[i * 4 + j] += reg_1[((mini_dim_idx - 1) % 2) * 4 + i] * reg_2[((mini_dim_idx - 1) % 2) * 4 + j];
+ }
+ }
+ }
+
+ __syncthreads();
+
+ #pragma unroll
+ for (int i = 0; i < 4; i++) {
+ reg_1[i] = A_buffer[(dim_stride % 2) * 256 + reg_1_idx * 4 + i];
+ reg_2[i] = B_buffer[(dim_stride % 2) * 256 + reg_2_idx * 4 + i];
+ }
+
+ #pragma unroll
+ for (int i = 0; i < 4; i++) {
+ #pragma unroll
+ for (int j = 0; j < 4; j++) {
+ reg_array[i * 4 + j] += reg_1[4 + i] * reg_2[4 + j];
+ }
+ }
+
+ }
+
+ #pragma unroll
+ for (int mini_dim_idx = 1; mini_dim_idx < 8; mini_dim_idx++) {
+ #pragma unroll
+ for (int i = 0; i < 4; i++) {
+ reg_1[(mini_dim_idx % 2) * 4 + i] = A_buffer[256 + mini_dim_idx * 32 + reg_1_idx * 4 + i];
+ reg_2[(mini_dim_idx % 2) * 4 + i] = B_buffer[256 + mini_dim_idx * 32 + reg_2_idx * 4 + i];
+ }
+ #pragma unroll
+ for (int i = 0; i < 4; i++) {
+ #pragma unroll
+ for (int j = 0; j < 4; j++) {
+ reg_array[i * 4 + j] += reg_1[((mini_dim_idx - 1) % 2) * 4 + i] * reg_2[((mini_dim_idx - 1) % 2) * 4 + j];
+ }
+ }
+ }
+ #pragma unroll
+ for (int i = 0; i < 4; i++) {
+ #pragma unroll
+ for (int j = 0; j < 4; j++) {
+ reg_array[i * 4 + j] += reg_1[4 + i] * reg_2[4 + j];
+ }
+ }
+ __syncthreads();
+
+ float *C_buffer = &buffer[threadIdx.y * 1024]; // [32, 32]
+
+ #pragma unroll
+ for (int i = 0; i < 4; i++) {
+ #pragma unroll
+ for (int j = 0; j < 4; j++) {
+ C_buffer[(reg_2_idx * 4 + j) * 32 + reg_1_idx * 4 + i] = reg_array[i * 4 + j];
+ }
+ }
+ __syncthreads();
+
+ float *sparse_C_pt = &sparse_C[batch_idx__block_idx * 1024];
+
+ #pragma unroll
+ for (int i = 0; i < 16; i++) {
+ sparse_C_pt[i * 64 + thread_idx] = C_buffer[i * 64 + thread_idx];
+ }
+
+}
+
+__global__ void sparse_dense_mm_cuda_kernel(
+ float *sparse_A, // [batch_size, num_block, 32, 32]
+ int *indices, // [batch_size, num_block]
+ float *dense_B, // [batch_size, B_num_block, dim, 32]
+ float *dense_C, // [batch_size, A_num_block, dim, 32]
+ long batch_size,
+ long A_num_block,
+ long B_num_block,
+ long dim,
+ long num_block
+) {
+
+ long batch_idx = blockIdx.y;
+ long block_idx = blockIdx.x * blockDim.y + threadIdx.y;
+
+ long thread_idx = threadIdx.x;
+
+ __shared__ float buffer[6144];
+ float *A_buffer = &buffer[threadIdx.y * 3072]; // [32, 32]
+ float *B_buffer = &buffer[threadIdx.y * 3072 + 1024]; // [32, 64]
+
+ long batch_idx__block_idx = batch_idx * num_block + block_idx;
+
+ float *sparse_A_pt = &sparse_A[batch_idx__block_idx * 1024];
+ #pragma unroll
+ for (int i = 0; i < 8; i++) {
+ A_buffer[i * 128 + thread_idx] = sparse_A_pt[i * 128 + thread_idx];
+ }
+
+ long AB_block_idx = indices[batch_idx__block_idx];
+ float *dense_B_pt = &dense_B[(batch_idx * B_num_block + AB_block_idx % B_num_block) * 32 * dim];
+ float *dense_C_pt = &dense_C[(batch_idx * A_num_block + AB_block_idx / B_num_block) * 32 * dim];
+
+ // [0000000011111111222222223333333344444444555555556666666677777777]
+ // [0123456701234567012345670123456701234567012345670123456701234567]
+ int reg_1_idx = thread_idx / 8;
+ int reg_2_idx = thread_idx % 8;
+
+ float reg_1[8];
+ float reg_2[8];
+
+ float reg_array[16];
+
+ for (int dim_stride = 0; dim_stride < dim; dim_stride = dim_stride + 64) {
+
+ #pragma unroll
+ for (int i = 0; i < 16; i++) {
+ B_buffer[i * 128 + thread_idx] = dense_B_pt[dim_stride * 32 + i * 128 + thread_idx];
+ }
+
+ #pragma unroll
+ for (int i = 0; i < 16; i++) {
+ reg_array[i] = 0;
+ }
+
+ __syncthreads();
+
+ #pragma unroll
+ for (int i = 0; i < 4; i++) {
+ reg_1[i] = B_buffer[(reg_1_idx * 4 + i) * 32];
+ reg_2[i] = A_buffer[reg_2_idx * 4 + i];
+ }
+
+ #pragma unroll
+ for (int mini_dim_idx = 1; mini_dim_idx < 32; mini_dim_idx++) {
+ #pragma unroll
+ for (int i = 0; i < 4; i++) {
+ reg_1[(mini_dim_idx % 2) * 4 + i] = B_buffer[(reg_1_idx * 4 + i) * 32 + mini_dim_idx];
+ reg_2[(mini_dim_idx % 2) * 4 + i] = A_buffer[mini_dim_idx * 32 + reg_2_idx * 4 + i];
+ }
+ #pragma unroll
+ for (int i = 0; i < 4; i++) {
+ #pragma unroll
+ for (int j = 0; j < 4; j++) {
+ reg_array[i * 4 + j] += reg_1[((mini_dim_idx - 1) % 2) * 4 + i] * reg_2[((mini_dim_idx - 1) % 2) * 4 + j];
+ }
+ }
+ }
+
+ #pragma unroll
+ for (int i = 0; i < 4; i++) {
+ #pragma unroll
+ for (int j = 0; j < 4; j++) {
+ reg_array[i * 4 + j] += reg_1[4 + i] * reg_2[4 + j];
+ }
+ }
+
+ __syncthreads();
+
+ float *C_buffer = &buffer[threadIdx.y * 3072 + 1024]; // [64, 32]
+
+ #pragma unroll
+ for (int i = 0; i < 4; i++) {
+ #pragma unroll
+ for (int j = 0; j < 4; j++) {
+ C_buffer[(reg_1_idx * 4 + i) * 32 + reg_2_idx * 4 + j] = reg_array[i * 4 + j];
+ }
+ }
+ __syncthreads();
+
+ #pragma unroll
+ for (int i = 0; i < 16; i++) {
+ atomicAdd(&dense_C_pt[dim_stride * 32 + i * 128 + thread_idx], C_buffer[i * 128 + thread_idx]);
+ }
+ __syncthreads();
+
+ }
+
+}
+
+
+__global__ void reduce_sum_cuda_kernel(
+ float *sparse_A, // [batch_size, num_block, 32, 32]
+ int *indices, // [batch_size, num_block]
+ float *dense_C, // [batch_size, A_num_block, 32]
+ long batch_size,
+ long A_num_block,
+ long B_num_block,
+ long num_block
+) {
+
+ long batch_idx = blockIdx.y;
+ long block_idx = blockIdx.x * blockDim.y + threadIdx.y;
+
+ long thread_idx = threadIdx.x;
+
+ long batch_idx__block_idx = batch_idx * num_block + block_idx;
+
+ long AB_block_idx = indices[batch_idx__block_idx];
+ float *sparse_A_pt = &sparse_A[batch_idx__block_idx * 1024];
+
+ float reg_array[16];
+ float value = 0;
+
+ #pragma unroll
+ for (int i = 0; i < 8; i++) {
+ reg_array[i] = sparse_A_pt[i * 32 + thread_idx];
+ }
+ #pragma unroll
+ for (int stride = 8; stride < 32; stride = stride + 8) {
+ #pragma unroll
+ for (int i = 0; i < 8; i++) {
+ reg_array[(stride + i) % 16] = sparse_A_pt[(stride + i) * 32 + thread_idx];
+ }
+ #pragma unroll
+ for (int i = 0; i < 8; i++) {
+ value = value + reg_array[(stride - 8 + i) % 16];
+ }
+ }
+ #pragma unroll
+ for (int i = 0; i < 8; i++) {
+ value = value + reg_array[8 + i];
+ }
+
+ float *dense_C_pt = &dense_C[(batch_idx * A_num_block + AB_block_idx / B_num_block) * 32];
+
+ atomicAdd(&dense_C_pt[thread_idx], value);
+
+}
+
+__global__ void scatter_cuda_kernel(
+ float *dense_A, // [batch_size, A_num_block, 32]
+ int *indices, // [batch_size, num_block]
+ float *sparse_C, // [batch_size, num_block, 32, 32]
+ long batch_size,
+ long A_num_block,
+ long B_num_block,
+ long num_block
+) {
+
+ long batch_idx = blockIdx.y;
+ long block_idx = blockIdx.x * blockDim.y + threadIdx.y;
+
+ long thread_idx = threadIdx.x;
+
+ long batch_idx__block_idx = batch_idx * num_block + block_idx;
+
+ long AB_block_idx = indices[batch_idx__block_idx];
+ float *dense_A_pt = &dense_A[(batch_idx * A_num_block + AB_block_idx / B_num_block) * 32];
+ float *sparse_C_pt = &sparse_C[(batch_idx * num_block + block_idx) * 1024];
+
+ float value = dense_A_pt[thread_idx];
+
+ #pragma unroll
+ for (int i = 0; i < 32; i++) {
+ sparse_C_pt[i * 32 + thread_idx] = value;
+ }
+
+}
diff --git a/src/transformers/kernels/mra/cuda_kernel.h b/src/transformers/kernels/mra/cuda_kernel.h
new file mode 100644
index 000000000000..a95b46f7d159
--- /dev/null
+++ b/src/transformers/kernels/mra/cuda_kernel.h
@@ -0,0 +1,59 @@
+
+#define WARP_SIZE 32
+#define FULL_MASK 0xffffffff
+#define OPTIMAL_THREADS 256
+
+__global__ void index_max_cuda_kernel(
+ float *index_vals, // [batch_size, 32, num_block]
+ int *indices, // [batch_size, num_block]
+ float *max_vals, // [batch_size, A_num_block * 32]
+ float *max_vals_scatter, // [batch_size, 32, num_block]
+ long batch_size,
+ long A_num_block,
+ long B_num_block,
+ long num_block
+);
+
+__global__ void mm_to_sparse_cuda_kernel(
+ float *dense_A, // [batch_size, A_num_block, dim, 32]
+ float *dense_B, // [batch_size, B_num_block, dim, 32]
+ int *indices, // [batch_size, num_block]
+ float *sparse_C, // [batch_size, num_block, 32, 32]
+ long batch_size,
+ long A_num_block,
+ long B_num_block,
+ long dim,
+ long num_block
+);
+
+__global__ void sparse_dense_mm_cuda_kernel(
+ float *sparse_A, // [batch_size, num_block, 32, 32]
+ int *indices, // [batch_size, num_block]
+ float *dense_B, // [batch_size, B_num_block, dim, 32]
+ float *dense_C, // [batch_size, A_num_block, dim, 32]
+ long batch_size,
+ long A_num_block,
+ long B_num_block,
+ long dim,
+ long num_block
+);
+
+__global__ void reduce_sum_cuda_kernel(
+ float *sparse_A, // [batch_size, num_block, 32, 32]
+ int *indices, // [batch_size, num_block]
+ float *dense_C, // [batch_size, A_num_block, 32]
+ long batch_size,
+ long A_num_block,
+ long B_num_block,
+ long num_block
+);
+
+__global__ void scatter_cuda_kernel(
+ float *dense_A, // [batch_size, A_num_block, 32]
+ int *indices, // [batch_size, num_block]
+ float *sparse_C, // [batch_size, num_block, 32, 32]
+ long batch_size,
+ long A_num_block,
+ long B_num_block,
+ long num_block
+);
diff --git a/src/transformers/kernels/mra/cuda_launch.cu b/src/transformers/kernels/mra/cuda_launch.cu
new file mode 100644
index 000000000000..ba2a0cacfe61
--- /dev/null
+++ b/src/transformers/kernels/mra/cuda_launch.cu
@@ -0,0 +1,154 @@
+#include
+#include
+#include "cuda_launch.h"
+#include "cuda_kernel.h"
+#include
+
+//////////////////////////////////////////////////////////////////////////////////////////////////
+//////////////////////////////////////////////////////////////////////////////////////////////////
+
+std::vector index_max_kernel(
+ at::Tensor index_vals, // [batch_size, 32, num_block]
+ at::Tensor indices, // [batch_size, num_block],
+ int A_num_block,
+ int B_num_block
+) {
+ int batch_size = indices.size(0);
+ int num_block = indices.size(1);
+
+ at::Tensor max_vals = at::zeros({batch_size, A_num_block * 32}, index_vals.options());
+ at::Tensor max_vals_scatter = at::zeros({batch_size, 32, num_block}, index_vals.options());
+
+ dim3 threads(256);
+ dim3 blocks(batch_size);
+ int shared_mem = A_num_block * 32 * sizeof(float);
+
+ index_max_cuda_kernel<<>>(
+ index_vals.data_ptr(),
+ indices.data_ptr(),
+ max_vals.data_ptr(),
+ max_vals_scatter.data_ptr(),
+ batch_size,
+ A_num_block,
+ B_num_block,
+ num_block
+ );
+
+ return {max_vals, max_vals_scatter};
+}
+
+at::Tensor mm_to_sparse_kernel(
+ at::Tensor dense_A, // [batch_size, A_num_block, dim, 32]
+ at::Tensor dense_B, // [batch_size, B_num_block, dim, 32]
+ at::Tensor indices // [batch_size, num_block]
+) {
+ int batch_size = dense_A.size(0);
+ int A_num_block = dense_A.size(1);
+ int B_num_block = dense_B.size(1);
+ int dim = dense_A.size(2);
+ int num_block = indices.size(1);
+
+ at::Tensor sparse_C = at::zeros({batch_size, num_block, 32, 32}, dense_A.options());
+
+ dim3 threads(64, 4);
+ dim3 blocks(num_block / 4, batch_size);
+
+ mm_to_sparse_cuda_kernel<<>>(
+ dense_A.data_ptr(),
+ dense_B.data_ptr(),
+ indices.data_ptr(),
+ sparse_C.data_ptr(),
+ batch_size,
+ A_num_block,
+ B_num_block,
+ dim,
+ num_block
+ );
+
+ return sparse_C;
+}
+
+at::Tensor sparse_dense_mm_kernel(
+ at::Tensor sparse_A, // [batch_size, num_block, 32, 32]
+ at::Tensor indices, // [batch_size, num_block]
+ at::Tensor dense_B, // [batch_size, B_num_block, dim, 32]
+ int A_num_block
+) {
+ int batch_size = sparse_A.size(0);
+ int num_block = sparse_A.size(1);
+ int B_num_block = dense_B.size(1);
+ int dim = dense_B.size(2);
+
+ at::Tensor dense_C = at::zeros({batch_size, A_num_block, dim, 32}, dense_B.options());
+
+ dim3 threads(128, 2);
+ dim3 blocks(num_block / 2, batch_size);
+
+ sparse_dense_mm_cuda_kernel<<>>(
+ sparse_A.data_ptr(),
+ indices.data_ptr(),
+ dense_B.data_ptr(),
+ dense_C.data_ptr(),
+ batch_size,
+ A_num_block,
+ B_num_block,
+ dim,
+ num_block
+ );
+
+ return dense_C;
+}
+
+at::Tensor reduce_sum_kernel(
+ at::Tensor sparse_A, // [batch_size, num_block, 32, 32]
+ at::Tensor indices, // [batch_size, num_block]
+ int A_num_block,
+ int B_num_block
+) {
+ int batch_size = sparse_A.size(0);
+ int num_block = sparse_A.size(1);
+
+ at::Tensor dense_C = at::zeros({batch_size, A_num_block, 32}, sparse_A.options());
+
+ dim3 threads(32, 4);
+ dim3 blocks(num_block / 4, batch_size);
+
+ reduce_sum_cuda_kernel<<>>(
+ sparse_A.data_ptr(),
+ indices.data_ptr(),
+ dense_C.data_ptr(),
+ batch_size,
+ A_num_block,
+ B_num_block,
+ num_block
+ );
+
+ return dense_C;
+}
+
+at::Tensor scatter_kernel(
+ at::Tensor dense_A, // [batch_size, A_num_block, 32]
+ at::Tensor indices, // [batch_size, num_block]
+ int B_num_block
+) {
+ int batch_size = dense_A.size(0);
+ int A_num_block = dense_A.size(1);
+ int num_block = indices.size(1);
+
+ at::Tensor sparse_C = at::zeros({batch_size, num_block, 32, 32}, dense_A.options());
+
+ dim3 threads(32, 4);
+ dim3 blocks(num_block / 4, batch_size);
+
+ scatter_cuda_kernel<<>>(
+ dense_A.data_ptr(),
+ indices.data_ptr(),
+ sparse_C.data_ptr(),
+ batch_size,
+ A_num_block,
+ B_num_block,
+ num_block
+ );
+
+ return sparse_C;
+}
diff --git a/src/transformers/kernels/mra/cuda_launch.h b/src/transformers/kernels/mra/cuda_launch.h
new file mode 100644
index 000000000000..0200140ee337
--- /dev/null
+++ b/src/transformers/kernels/mra/cuda_launch.h
@@ -0,0 +1,39 @@
+#include
+#include
+#include
+
+#define min(a, b) ((a)<(b)?(a):(b))
+#define max(a, b) ((a)>(b)?(a):(b))
+
+std::vector index_max_kernel(
+ at::Tensor index_vals,
+ at::Tensor indices,
+ int A_num_block,
+ int B_num_block
+);
+
+at::Tensor mm_to_sparse_kernel(
+ at::Tensor dense_A,
+ at::Tensor dense_B,
+ at::Tensor indices
+);
+
+at::Tensor sparse_dense_mm_kernel(
+ at::Tensor sparse_A,
+ at::Tensor indices,
+ at::Tensor dense_B,
+ int A_num_block
+);
+
+at::Tensor reduce_sum_kernel(
+ at::Tensor sparse_A,
+ at::Tensor indices,
+ int A_num_block,
+ int B_num_block
+);
+
+at::Tensor scatter_kernel(
+ at::Tensor dense_A,
+ at::Tensor indices,
+ int B_num_block
+);
diff --git a/src/transformers/kernels/mra/torch_extension.cpp b/src/transformers/kernels/mra/torch_extension.cpp
new file mode 100644
index 000000000000..60c9262b7792
--- /dev/null
+++ b/src/transformers/kernels/mra/torch_extension.cpp
@@ -0,0 +1,78 @@
+#include
+#include
+#include "cuda_launch.h"
+#include
+
+std::vector index_max(
+ at::Tensor index_vals,
+ at::Tensor indices,
+ int A_num_block,
+ int B_num_block
+) {
+ return index_max_kernel(
+ index_vals,
+ indices,
+ A_num_block,
+ B_num_block
+ );
+}
+
+at::Tensor mm_to_sparse(
+ at::Tensor dense_A,
+ at::Tensor dense_B,
+ at::Tensor indices
+) {
+ return mm_to_sparse_kernel(
+ dense_A,
+ dense_B,
+ indices
+ );
+}
+
+at::Tensor sparse_dense_mm(
+ at::Tensor sparse_A,
+ at::Tensor indices,
+ at::Tensor dense_B,
+ int A_num_block
+) {
+ return sparse_dense_mm_kernel(
+ sparse_A,
+ indices,
+ dense_B,
+ A_num_block
+ );
+}
+
+at::Tensor reduce_sum(
+ at::Tensor sparse_A,
+ at::Tensor indices,
+ int A_num_block,
+ int B_num_block
+) {
+ return reduce_sum_kernel(
+ sparse_A,
+ indices,
+ A_num_block,
+ B_num_block
+ );
+}
+
+at::Tensor scatter(
+ at::Tensor dense_A,
+ at::Tensor indices,
+ int B_num_block
+) {
+ return scatter_kernel(
+ dense_A,
+ indices,
+ B_num_block
+ );
+}
+
+PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
+ m.def("index_max", &index_max, "index_max (CUDA)");
+ m.def("mm_to_sparse", &mm_to_sparse, "mm_to_sparse (CUDA)");
+ m.def("sparse_dense_mm", &sparse_dense_mm, "sparse_dense_mm (CUDA)");
+ m.def("reduce_sum", &reduce_sum, "reduce_sum (CUDA)");
+ m.def("scatter", &scatter, "scatter (CUDA)");
+}
diff --git a/src/transformers/kernels/rwkv/wkv_cuda.cu b/src/transformers/kernels/rwkv/wkv_cuda.cu
new file mode 100644
index 000000000000..571d5a8a8307
--- /dev/null
+++ b/src/transformers/kernels/rwkv/wkv_cuda.cu
@@ -0,0 +1,187 @@
+#include
+#include
+
+#define MIN_VALUE (-1e38)
+
+template
+__global__ void kernel_forward(
+ const int B, const int T, const int C, const F *__restrict__ const _w, const F *__restrict__ const _u,
+ const F *__restrict__ const _k, const F *__restrict__ const _v, F *__restrict__ const _y
+) {
+ const int idx = blockIdx.x * blockDim.x + threadIdx.x;
+ const int _b = idx / C;
+ const int _c = idx % C;
+ const int _offset = _b * T * C + _c;
+
+ F u = _u[_c];
+ F w = _w[_c];
+ const F *__restrict__ const k = _k + _offset;
+ const F *__restrict__ const v = _v + _offset;
+ F *__restrict__ const y = _y + _offset;
+
+ // aa and bb are running sums divided by exp(pp) (to avoid overflow)
+ F aa = 0, bb = 0, pp = MIN_VALUE;
+ for (int i = 0; i < T; i++) {
+ const int ii = i * C;
+ const F kk = k[ii];
+ const F vv = v[ii];
+
+ F ww = u + kk;
+ F p = max(pp, ww);
+ F e1 = exp(pp - p);
+ F e2 = exp(ww - p);
+ y[ii] = (e1 * aa + e2 * vv) / (e1 * bb + e2);
+
+ ww = w + pp;
+ p = max(ww, kk);
+ e1 = exp(ww - p);
+ e2 = exp(kk - p);
+ aa = e1 * aa + e2 * vv;
+ bb = e1 * bb + e2;
+ pp = p;
+ }
+}
+
+template
+__global__ void kernel_forward_with_state(
+ const int B, const int T, const int C, const F *__restrict__ const _w, const F *__restrict__ const _u,
+ const F *__restrict__ const _k, const F *__restrict__ const _v, F *__restrict__ const _y, F *__restrict__ const _s
+) {
+ const int idx = blockIdx.x * blockDim.x + threadIdx.x;
+ const int _b = idx / C;
+ const int _c = idx % C;
+ const int _offset_s = _b * C * 3 + _c * 3;
+ const int _offset = _b * T * C + _c;
+
+ F u = _u[_c];
+ F w = _w[_c];
+ const F *__restrict__ const k = _k + _offset;
+ const F *__restrict__ const v = _v + _offset;
+ F *__restrict__ const y = _y + _offset;
+ F *__restrict__ const s = _s + _offset_s;
+
+ // aa and bb are running sums divided by exp(pp) (to avoid overflow)
+ F aa = s[0], bb = s[1], pp = s[2];
+ for (int i = 0; i < T; i++) {
+ const int ii = i * C;
+ const F kk = k[ii];
+ const F vv = v[ii];
+
+ F ww = u + kk;
+ F p = max(pp, ww);
+ F e1 = exp(pp - p);
+ F e2 = exp(ww - p);
+ y[ii] = (e1 * aa + e2 * vv) / (e1 * bb + e2);
+
+ ww = w + pp;
+ p = max(ww, kk);
+ e1 = exp(ww - p);
+ e2 = exp(kk - p);
+ aa = e1 * aa + e2 * vv;
+ bb = e1 * bb + e2;
+ pp = p;
+ }
+ s[0] = aa;
+ s[1] = bb;
+ s[2] = pp;
+}
+
+template
+__global__ void kernel_backward(
+ const int B, const int T, const int C, const F *__restrict__ const _w, const F *__restrict__ const _u,
+ const F *__restrict__ const _k, const F *__restrict__ const _v, const F *__restrict__ const _y,
+ const F *__restrict__ const _gy, F *__restrict__ const _gw, F *__restrict__ const _gu, F *__restrict__ const _gk,
+ F *__restrict__ const _gv
+) {
+ const int idx = blockIdx.x * blockDim.x + threadIdx.x;
+ const int _b = idx / C;
+ const int _c = idx % C;
+ const int _offset = _b * T * C + _c;
+
+ F u = _u[_c];
+ F w = _w[_c];
+ const F *__restrict__ const k = _k + _offset;
+ const F *__restrict__ const v = _v + _offset;
+ const F *__restrict__ const y = _y + _offset;
+ const F *__restrict__ const gy = _gy + _offset;
+ F *__restrict__ const gk = _gk + _offset;
+ F *__restrict__ const gv = _gv + _offset;
+
+ F q[Tmax], r[Tmax];
+
+ F gw = 0, gu = 0, aa = 0, bb = 0, ga = 0, gb = 0, pp = MIN_VALUE;
+ for (int i = 0; i < T; i++) {
+ const int ii = i * C;
+ const F kk = k[ii];
+ const F vv = v[ii];
+ const F yy = y[ii];
+
+ F ww = u + kk;
+ F p = max(pp, ww);
+ F e1 = exp(pp - p);
+ F e2 = exp(ww - p);
+ const F qq = gy[ii] / (e1 * bb + e2);
+ gw += (ga - gb * yy) * e1 * qq;
+ gu += (vv - yy) * e2 * qq;
+ q[i] = qq;
+ r[i] = ww - p;
+
+ ww = w + pp;
+ p = max(ww, kk);
+ e1 = exp(ww - p);
+ e2 = exp(kk - p);
+ ga = e1 * (aa + ga);
+ gb = e1 * (bb + gb);
+ aa = e1 * aa + e2 * vv;
+ bb = e1 * bb + e2;
+ pp = p;
+ }
+ const int _offsetBC = _b * C + _c;
+ _gw[_offsetBC] = gw * _w[_c]; // multiply by w because of w -> -exp(w) in python forward()
+ _gu[_offsetBC] = gu;
+
+ aa = 0, bb = 0, pp = MIN_VALUE;
+ for (int i = T - 1; i >= 0; i--) {
+ const int ii = i * C;
+ const F kk = k[ii];
+ const F vv = v[ii];
+ const F yy = y[ii];
+ const F qq = q[i];
+ const F rr = r[i];
+
+ F e1 = qq * exp(rr);
+ F e2 = exp(kk + pp);
+ gk[ii] = e1 * (vv - yy) + e2 * (aa * vv + bb);
+ gv[ii] = e1 + e2 * aa;
+
+ const F ww = w + pp;
+ const F www = rr - u - kk;
+ const F p = max(ww, www);
+ e1 = exp(ww - p);
+ e2 = qq * exp(www - p);
+ aa = e1 * aa + e2;
+ bb = e1 * bb - e2 * yy;
+ pp = p;
+ }
+}
+
+void cuda_forward(int B, int T, int C, float *w, float *u, float *k, float *v, float *y) {
+ dim3 threadsPerBlock( min(C, 32) ); // requires --maxrregcount 60 for optimal performance
+ assert(B * C % threadsPerBlock.x == 0);
+ dim3 numBlocks(B * C / threadsPerBlock.x);
+ kernel_forward<<>>(B, T, C, w, u, k, v, y);
+}
+
+void cuda_forward_with_state(int B, int T, int C, float *w, float *u, float *k, float *v, float *y, float *s) {
+ dim3 threadsPerBlock( min(C, 32) ); // requires --maxrregcount 60 for optimal performance
+ assert(B * C % threadsPerBlock.x == 0);
+ dim3 numBlocks(B * C / threadsPerBlock.x);
+ kernel_forward_with_state<<>>(B, T, C, w, u, k, v, y, s);
+}
+
+void cuda_backward(int B, int T, int C, float *w, float *u, float *k, float *v, float *y, float *gy, float *gw, float *gu, float *gk, float *gv) {
+ dim3 threadsPerBlock( min(C, 32) ); // requires --maxrregcount 60 for optimal performance
+ assert(B * C % threadsPerBlock.x == 0);
+ dim3 numBlocks(B * C / threadsPerBlock.x);
+ kernel_backward<<>>(B, T, C, w, u, k, v, y, gy, gw, gu, gk, gv);
+}
diff --git a/src/transformers/kernels/rwkv/wkv_cuda_bf16.cu b/src/transformers/kernels/rwkv/wkv_cuda_bf16.cu
new file mode 100644
index 000000000000..042cb4aba1db
--- /dev/null
+++ b/src/transformers/kernels/rwkv/wkv_cuda_bf16.cu
@@ -0,0 +1,186 @@
+#include
+#include
+#include "ATen/ATen.h"
+#define MIN_VALUE (-1e38)
+typedef at::BFloat16 bf16;
+
+__global__ void kernel_forward_bf16(
+ const int B, const int T, const int C, const float *__restrict__ const _w, const bf16 *__restrict__ const _u,
+ const bf16 *__restrict__ const _k, const bf16 *__restrict__ const _v, bf16 *__restrict__ const _y
+) {
+ const int idx = blockIdx.x * blockDim.x + threadIdx.x;
+ const int _b = idx / C;
+ const int _c = idx % C;
+ const int _offset = _b * T * C + _c;
+
+ float u = float(_u[_c]);
+ float w = _w[_c];
+ const bf16 *__restrict__ const k = _k + _offset;
+ const bf16 *__restrict__ const v = _v + _offset;
+ bf16 *__restrict__ const y = _y + _offset;
+
+ // aa and bb are running sums divided by exp(pp) (to avoid overflow)
+ float aa = 0, bb = 0, pp = MIN_VALUE;
+ for (int i = 0; i < T; i++) {
+ const int ii = i * C;
+ const float kk = float(k[ii]);
+ const float vv = float(v[ii]);
+
+ float ww = u + kk;
+ float p = max(pp, ww);
+ float e1 = exp(pp - p);
+ float e2 = exp(ww - p);
+ y[ii] = bf16((e1 * aa + e2 * vv) / (e1 * bb + e2));
+
+ ww = w + pp;
+ p = max(ww, kk);
+ e1 = exp(ww - p);
+ e2 = exp(kk - p);
+ aa = e1 * aa + e2 * vv;
+ bb = e1 * bb + e2;
+ pp = p;
+ }
+}
+
+__global__ void kernel_forward_with_state_bf16(
+ const int B, const int T, const int C, const float *__restrict__ const _w, const bf16 *__restrict__ const _u,
+ const bf16 *__restrict__ const _k, const bf16 *__restrict__ const _v, bf16 *__restrict__ const _y,
+ float *__restrict__ const _s
+) {
+ const int idx = blockIdx.x * blockDim.x + threadIdx.x;
+ const int _b = idx / C;
+ const int _c = idx % C;
+ const int _offset_s = _b * C * 3 + _c * 3;
+ const int _offset = _b * T * C + _c;
+
+ float u = float(_u[_c]);
+ float w = _w[_c];
+ const bf16 *__restrict__ const k = _k + _offset;
+ const bf16 *__restrict__ const v = _v + _offset;
+ bf16 *__restrict__ const y = _y + _offset;
+ float *__restrict__ const s = _s + _offset_s;
+
+ // aa and bb are running sums divided by exp(pp) (to avoid overflow)
+ float aa = s[0], bb = s[1], pp = s[2];
+ for (int i = 0; i < T; i++) {
+ const int ii = i * C;
+ const float kk = float(k[ii]);
+ const float vv = float(v[ii]);
+
+ float ww = u + kk;
+ float p = max(pp, ww);
+ float e1 = exp(pp - p);
+ float e2 = exp(ww - p);
+ y[ii] = bf16(e1 * aa + e2 * vv) / (e1 * bb + e2);
+
+ ww = w + pp;
+ p = max(ww, kk);
+ e1 = exp(ww - p);
+ e2 = exp(kk - p);
+ aa = e1 * aa + e2 * vv;
+ bb = e1 * bb + e2;
+ pp = p;
+ }
+ s[0] = aa;
+ s[1] = bb;
+ s[2] = pp;
+}
+
+__global__ void kernel_backward_bf16(
+ const int B, const int T, const int C, const float *__restrict__ const _w, const bf16 *__restrict__ const _u,
+ const bf16 *__restrict__ const _k, const bf16 *__restrict__ const _v, const bf16 *__restrict__ const _y,
+ const bf16 *__restrict__ const _gy, bf16 *__restrict__ const _gw, bf16 *__restrict__ const _gu,
+ bf16 *__restrict__ const _gk, bf16 *__restrict__ const _gv
+) {
+ const int idx = blockIdx.x * blockDim.x + threadIdx.x;
+ const int _b = idx / C;
+ const int _c = idx % C;
+ const int _offset = _b * T * C + _c;
+
+ float u = float(_u[_c]);
+ float w = _w[_c];
+ const bf16 *__restrict__ const k = _k + _offset;
+ const bf16 *__restrict__ const v = _v + _offset;
+ const bf16 *__restrict__ const y = _y + _offset;
+ const bf16 *__restrict__ const gy = _gy + _offset;
+ bf16 *__restrict__ const gk = _gk + _offset;
+ bf16 *__restrict__ const gv = _gv + _offset;
+
+ float q[Tmax], r[Tmax];
+
+ float gw = 0, gu = 0, aa = 0, bb = 0, ga = 0, gb = 0, pp = MIN_VALUE;
+ for (int i = 0; i < T; i++) {
+ const int ii = i * C;
+ const float kk = float(k[ii]);
+ const float vv = float(v[ii]);
+ const float yy = float(y[ii]);
+
+ float ww = u + kk;
+ float p = max(pp, ww);
+ float e1 = exp(pp - p);
+ float e2 = exp(ww - p);
+ const float qq = float(gy[ii]) / (e1 * bb + e2);
+ gw += (ga - gb * yy) * e1 * qq;
+ gu += (vv - yy) * e2 * qq;
+ q[i] = qq;
+ r[i] = ww - p;
+
+ ww = w + pp;
+ p = max(ww, kk);
+ e1 = exp(ww - p);
+ e2 = exp(kk - p);
+ ga = e1 * (aa + ga);
+ gb = e1 * (bb + gb);
+ aa = e1 * aa + e2 * vv;
+ bb = e1 * bb + e2;
+ pp = p;
+ }
+ const int _offsetBC = _b * C + _c;
+ _gw[_offsetBC] = bf16(gw * _w[_c]); // multiply by w because of w -> -exp(w) in python forward()
+ _gu[_offsetBC] = bf16(gu);
+
+ aa = 0, bb = 0, pp = MIN_VALUE;
+ for (int i = T - 1; i >= 0; i--) {
+ const int ii = i * C;
+ const float kk = float(k[ii]);
+ const float vv = float(v[ii]);
+ const float yy = float(y[ii]);
+ const float qq = q[i];
+ const float rr = r[i];
+
+ float e1 = qq * exp(rr);
+ float e2 = exp(kk + pp);
+ gk[ii] = bf16(e1 * (vv - yy) + e2 * (aa * vv + bb));
+ gv[ii] = bf16(e1 + e2 * aa);
+
+ const float ww = w + pp;
+ const float www = rr - u - kk;
+ const float p = max(ww, www);
+ e1 = exp(ww - p);
+ e2 = qq * exp(www - p);
+ aa = e1 * aa + e2;
+ bb = e1 * bb - e2 * yy;
+ pp = p;
+ }
+}
+
+void cuda_forward_bf16(int B, int T, int C, float *w, bf16 *u, bf16 *k, bf16 *v, bf16 *y) {
+ dim3 threadsPerBlock( min(C, 32) ); // requires --maxrregcount 60 for optimal performance
+ assert(B * C % threadsPerBlock.x == 0);
+ dim3 numBlocks(B * C / threadsPerBlock.x);
+ kernel_forward_bf16<<>>(B, T, C, w, u, k, v, y);
+}
+
+void cuda_forward_with_state_bf16(int B, int T, int C, float *w, bf16 *u, bf16 *k, bf16 *v, bf16 *y, float *s) {
+ dim3 threadsPerBlock( min(C, 32) ); // requires --maxrregcount 60 for optimal performance
+ assert(B * C % threadsPerBlock.x == 0);
+ dim3 numBlocks(B * C / threadsPerBlock.x);
+ kernel_forward_with_state_bf16<<>>(B, T, C, w, u, k, v, y, s);
+}
+
+void cuda_backward_bf16(int B, int T, int C, float *w, bf16 *u, bf16 *k, bf16 *v, bf16 *y, bf16 *gy, bf16 *gw, bf16 *gu, bf16 *gk, bf16 *gv) {
+ dim3 threadsPerBlock( min(C, 32) ); // requires --maxrregcount 60 for optimal performance
+ assert(B * C % threadsPerBlock.x == 0);
+ dim3 numBlocks(B * C / threadsPerBlock.x);
+ kernel_backward_bf16<<>>(B, T, C, w, u, k, v, y, gy, gw, gu, gk, gv);
+}
diff --git a/src/transformers/kernels/rwkv/wkv_op.cpp b/src/transformers/kernels/rwkv/wkv_op.cpp
new file mode 100644
index 000000000000..55e728066592
--- /dev/null
+++ b/src/transformers/kernels/rwkv/wkv_op.cpp
@@ -0,0 +1,66 @@
+#include
+#include "ATen/ATen.h"
+typedef at::BFloat16 bf16;
+
+void cuda_forward(int B, int T, int C, float *w, float *u, float *k, float *v, float *y);
+void cuda_forward_bf16(int B, int T, int C, float *w, bf16 *u, bf16 *k, bf16 *v, bf16 *y);
+void cuda_forward_with_state(int B, int T, int C, float *w, float *u, float *k, float *v, float *y, float *s);
+void cuda_forward_with_state_bf16(int B, int T, int C, float *w, bf16 *u, bf16 *k, bf16 *v, bf16 *y, float *s);
+void cuda_backward(int B, int T, int C, float *w, float *u, float *k, float *v, float *y, float *gy, float *gw, float *gu, float *gk, float *gv);
+void cuda_backward_bf16(int B, int T, int C, float *w, bf16 *u, bf16 *k, bf16 *v, bf16 *y, bf16 *gy, bf16 *gw, bf16 *gu, bf16 *gk, bf16 *gv);
+
+void forward(torch::Tensor &w, torch::Tensor &u, torch::Tensor &k, torch::Tensor &v, torch::Tensor &y) {
+ const int B = k.size(0);
+ const int T = k.size(1);
+ const int C = k.size(2);
+ cuda_forward(B, T, C, w.data_ptr(), u.data_ptr(), k.data_ptr(), v.data_ptr(), y.data_ptr());
+}
+void forward_bf16(torch::Tensor &w, torch::Tensor &u, torch::Tensor &k, torch::Tensor &v, torch::Tensor &y) {
+ const int B = k.size(0);
+ const int T = k.size(1);
+ const int C = k.size(2);
+ cuda_forward_bf16(B, T, C, w.data_ptr