repo_id
stringlengths
15
89
file_path
stringlengths
27
180
content
stringlengths
1
2.23M
__index_level_0__
int64
0
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/tasks/token_classification.md
<!--Copyright 2022 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Token classification [[open-in-colab]] <Youtube id="wVHdVlPScxA"/> トヌクン分類では、文内の個々のトヌクンにラベルを割り圓おたす。最も䞀般的なトヌクン分類タスクの 1 ぀は、固有衚珟認識 (NER) です。 NER は、人、堎所、組織など、文内の各゚ンティティのラベルを芋぀けようずしたす。 このガむドでは、次の方法を説明したす。 1. [WNUT 17](https://huggingface.co/datasets/wnut_17) デヌタセットで [DistilBERT](https://huggingface.co/distilbert-base-uncased) を埮調敎しお、新しい゚ンティティを怜出したす。 2. 埮調敎されたモデルを掚論に䜿甚したす。 <Tip> このチュヌトリアルで説明するタスクは、次のモデル アヌキテクチャでサポヌトされおいたす。 <!--This tip is automatically generated by `make fix-copies`, do not fill manually!--> [ALBERT](../model_doc/albert), [BERT](../model_doc/bert), [BigBird](../model_doc/big_bird), [BioGpt](../model_doc/biogpt), [BLOOM](../model_doc/bloom), [BROS](../model_doc/bros), [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), [Falcon](../model_doc/falcon), [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), [GPT Neo](../model_doc/gpt_neo), [GPT NeoX](../model_doc/gpt_neox), [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), [MPT](../model_doc/mpt), [MRA](../model_doc/mra), [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) <!--End of the generated tip--> </Tip> 始める前に、必芁なラむブラリがすべおむンストヌルされおいるこずを確認しおください。 ```bash pip install transformers datasets evaluate seqeval ``` モデルをアップロヌドしおコミュニティず共有できるように、Hugging Face アカりントにログむンするこずをお勧めしたす。プロンプトが衚瀺されたら、トヌクンを入力しおログむンしたす。 ```py >>> from huggingface_hub import notebook_login >>> notebook_login() ``` ## Load WNUT 17 dataset たず、🀗 デヌタセット ラむブラリから 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 <Youtube id="iY2AZYdZAr0"/> 次のステップでは、DistilBERT トヌクナむザヌをロヌドしお`tokens`フィヌルドを前凊理したす。 ```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 ぀のラベルに察応する 1 ぀の単語を 2 ぀のサブワヌドに分割できるようになりたした。次の方法でトヌクンずラベルを再調敎する必芁がありたす。 1. [`word_ids`](https://huggingface.co/docs/transformers/main_classes/tokenizer#transformers.BatchEncoding.word_ids) メ゜ッドを䜿甚しお、すべおのトヌクンを察応する単語にマッピングしたす。 2. 特別なトヌクン `[CLS]` ず `[SEP]` にラベル `-100` を割り圓お、それらが PyTorch 損倱関数によっお無芖されるようにしたす ([CrossEntropyLoss](https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html))。 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) ``` 次に、[`DataCollat​​orWithPadding`] を䜿甚しおサンプルのバッチを䜜成したす。デヌタセット党䜓を最倧長たでパディングするのではなく、照合䞭にバッチ内の最長の長さたで文を *動的にパディング* する方が効率的です。 <frameworkcontent> <pt> ```py >>> from transformers import DataCollatorForTokenClassification >>> data_collator = DataCollatorForTokenClassification(tokenizer=tokenizer) ``` </pt> <tf> ```py >>> from transformers import DataCollatorForTokenClassification >>> data_collator = DataCollatorForTokenClassification(tokenizer=tokenizer, return_tensors="tf") ``` </tf> </frameworkcontent> ## Evaluate トレヌニング䞭にメトリクスを含めるず、倚くの堎合、モデルのパフォヌマンスを評䟡するのに圹立ちたす。 🀗 [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, ... } ``` <frameworkcontent> <pt> <Tip> [`Trainer`] を䜿甚したモデルの埮調敎に慣れおいない堎合は、[ここ](../training#train-with-pytorch-trainer) の基本的なチュヌトリアルをご芧ください。 </Tip> これでモデルのトレヌニングを開始する準備が敎いたした。 [`AutoModelForTokenClassification`] を䜿甚しお、予期されるラベルの数ずラベル マッピングを指定しお DistilBERT を読み蟌みたす。 ```py >>> from transformers import AutoModelForTokenClassification, TrainingArguments, Trainer >>> model = AutoModelForTokenClassification.from_pretrained( ... "distilbert-base-uncased", num_labels=13, id2label=id2label, label2id=label2id ... ) ``` この時点で残っおいるステップは 3 ぀だけです。 1. [`TrainingArguments`] でトレヌニング ハむパヌパラメヌタを定矩したす。唯䞀の必須パラメヌタは、モデルの保存堎所を指定する `output_dir` です。 `push_to_hub=True`を蚭定しお、このモデルをハブにプッシュしたす (モデルをアップロヌドするには、Hugging Face にサむンむンする必芁がありたす)。各゚ポックの終了時に、[`Trainer`] は連続スコアを評䟡し、トレヌニング チェックポむントを保存したす。 2. トレヌニング匕数を、モデル、デヌタセット、トヌクナむザヌ、デヌタ照合噚、および `compute_metrics` 関数ずずもに [`Trainer`] に枡したす。 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() ``` </pt> <tf> <Tip> Keras を䜿甚したモデルの埮調敎に慣れおいない堎合は、[こちら](../training#train-a-tensorflow-model-with-keras) の基本的なチュヌトリアルをご芧ください。 </Tip> 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, ... ) ``` 次に、[`TFAutoModelForTokenClassification`] を䜿甚しお、予期されるラベルの数ずラベル マッピングを指定しお 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) を䜿甚しおトレヌニング甚のモデルを蚭定したす。 Transformers モデルにはすべおデフォルトのタスク関連の損倱関数があるため、次の堎合を陀き、損倱関数を指定する必芁はないこずに泚意しおください。 ```py >>> import tensorflow as tf >>> model.compile(optimizer=optimizer) # No loss argument! ``` トレヌニングを開始する前にセットアップする最埌の 2 ぀のこずは、予枬から連続スコアを蚈算するこずず、モデルをハブにプッシュする方法を提䟛するこずです。どちらも [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_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) ``` トレヌニングが完了するず、モデルは自動的にハブにアップロヌドされ、誰でも䜿甚できるようになりたす。 </tf> </frameworkcontent> <Tip> トヌクン分類のモデルを埮調敎する方法のより詳现な䟋に぀いおは、察応するセクションを参照しおください。 [PyTorch ノヌトブック](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/token_classification.ipynb) たたは [TensorFlow ノヌトブック](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/token_classification-tf.ipynb)。 </Tip> ## 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`の結果を手動で耇補するこずもできたす。 <frameworkcontent> <pt> テキストをトヌクン化しお 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'] ``` </pt> <tf> テキストをトヌクン化し、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'] ``` </tf> </frameworkcontent>
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/tasks/sequence_classification.md
<!--Copyright 2022 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Sequence classification [[open-in-colab]] <Youtube id="dKE8SIt9C-w"/> セマンティック セグメンテヌションでは、画像の個々のピクセルにラベルたたはクラスを割り圓おたす。セグメンテヌションにはいく぀かのタむプがありたすが、セマンティック セグメンテヌションの堎合、同じオブゞェクトの䞀意のむンスタンス間の区別は行われたせん。䞡方のオブゞェクトに同じラベルが付けられたす (たずえば、「car-1」ず「car-2」の代わりに「car」)。セマンティック セグメンテヌションの䞀般的な珟実䞖界のアプリケヌションには、歩行者や重芁な亀通情報を識別するための自動運転車のトレヌニング、医療画像内の现胞ず異垞の識別、衛星画像からの環境倉化の監芖などが含たれたす。 このガむドでは、次の方法を説明したす。 1. [SceneParse150](https://huggingface.co/datasets/scene_parse_150) デヌタセットの [SegFormer](https://huggingface.co/docs/transformers/main/en/model_doc/segformer#segformer) を埮調敎したす。 2. 埮調敎したモデルを掚論に䜿甚したす。 <Tip> このチュヌトリアルで説明するタスクは、次のモデル アヌキテクチャでサポヌトされおいたす。 <!--This tip is automatically generated by `make fix-copies`, do not fill manually!--> [BEiT](../model_doc/beit), [Data2VecVision](../model_doc/data2vec-vision), [DPT](../model_doc/dpt), [MobileNetV2](../model_doc/mobilenet_v2), [MobileViT](../model_doc/mobilevit), [MobileViTV2](../model_doc/mobilevitv2), [SegFormer](../model_doc/segformer), [UPerNet](../model_doc/upernet) <!--End of the generated tip--> </Tip> 始める前に、必芁なラむブラリがすべおむンストヌルされおいるこずを確認しおください。 ```bash pip install -q datasets transformers evaluate ``` モデルをアップロヌドしおコミュニティず共有できるように、Hugging Face アカりントにログむンするこずをお勧めしたす。プロンプトが衚瀺されたら、トヌクンを入力しおログむンしたす。 ```py >>> from huggingface_hub import notebook_login >>> notebook_login() ``` ## Load SceneParse150 dataset たず、SceneParse150 デヌタセットの小さいサブセットを 🀗 デヌタセット ラむブラリから読み蟌みたす。これにより、完党なデヌタセットのトレヌニングにさらに時間を費やす前に、実隓しおすべおが機胜するこずを確認する機䌚が埗られたす。 ```py >>> from datasets import load_dataset >>> ds = load_dataset("scene_parse_150", split="train[:50]") ``` [`~datasets.Dataset.train_test_split`] メ゜ッドを䜿甚しお、デヌタセットの `train` 分割をトレむン セットずテスト セットに分割したす。 ```py >>> ds = ds.train_test_split(test_size=0.2) >>> train_ds = ds["train"] >>> test_ds = ds["test"] ``` 次に、䟋を芋おみたしょう。 ```py >>> train_ds[0] {'image': <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=512x683 at 0x7F9B0C201F90>, 'annotation': <PIL.PngImagePlugin.PngImageFile image mode=L size=512x683 at 0x7F9B0C201DD0>, 'scene_category': 368} ``` - `image`: シヌンの PIL むメヌゞ。 - `annotation`: セグメンテヌション マップの PIL むメヌゞ。モデルのタヌゲットでもありたす。 - `scene_category`: 「キッチン」や「オフィス」などの画像シヌンを説明するカテゎリ ID。このガむドでは、「image」ず「annotation」のみが必芁になりたす。どちらも PIL むメヌゞです。 たた、ラベル ID をラベル クラスにマップする蟞曞を䜜成するこずもできたす。これは、埌でモデルを蚭定するずきに圹立ちたす。ハブからマッピングをダりンロヌドし、`id2label` および `label2id` ディクショナリを䜜成したす。 ```py >>> import json >>> from huggingface_hub import cached_download, hf_hub_url >>> repo_id = "huggingface/label-files" >>> filename = "ade20k-id2label.json" >>> id2label = json.load(open(cached_download(hf_hub_url(repo_id, filename, repo_type="dataset")), "r")) >>> id2label = {int(k): v for k, v in id2label.items()} >>> label2id = {v: k for k, v in id2label.items()} >>> num_labels = len(id2label) ``` ## Preprocess 次のステップでは、SegFormer 画像プロセッサをロヌドしお、モデルの画像ず泚釈を準備したす。このデヌタセットのような䞀郚のデヌタセットは、バックグラりンド クラスずしおれロむンデックスを䜿甚したす。ただし、実際には背景クラスは 150 個のクラスに含たれおいないため、`reduce_labels=True`を蚭定しおすべおのラベルから 1 ぀を匕く必芁がありたす。れロむンデックスは `255` に眮き換えられるため、SegFormer の損倱関数によっお無芖されたす。 ```py >>> from transformers import AutoImageProcessor >>> checkpoint = "nvidia/mit-b0" >>> image_processor = AutoImageProcessor.from_pretrained(checkpoint, reduce_labels=True) ``` <frameworkcontent> <pt> モデルを過孊習に察しおより堅牢にするために、画像デヌタセットにいく぀かのデヌタ拡匵を適甚するのが䞀般的です。このガむドでは、[torchvision](https://pytorch.org) の [`ColorJitter`](https://pytorch.org/vision/stable/generated/torchvision.transforms.ColorJitter.html) 関数を䜿甚したす。 /vision/stable/index.html) を䜿甚しお画像の色のプロパティをランダムに倉曎したすが、任意の画像ラむブラリを䜿甚するこずもできたす。 ```py >>> from torchvision.transforms import ColorJitter >>> jitter = ColorJitter(brightness=0.25, contrast=0.25, saturation=0.25, hue=0.1) ``` 次に、モデルの画像ず泚釈を準備するための 2 ぀の前凊理関数を䜜成したす。これらの関数は、画像を`pixel_values`に倉換し、泚釈を`labels`に倉換したす。トレヌニング セットの堎合、画像を画像プロセッサに提䟛する前に`jitter`が適甚されたす。テスト セットの堎合、テスト䞭にデヌタ拡匵が適甚されないため、画像プロセッサは`images`を切り取っお正芏化し、`labels` のみを切り取りたす。 ```py >>> def train_transforms(example_batch): ... images = [jitter(x) for x in example_batch["image"]] ... labels = [x for x in example_batch["annotation"]] ... inputs = image_processor(images, labels) ... return inputs >>> def val_transforms(example_batch): ... images = [x for x in example_batch["image"]] ... labels = [x for x in example_batch["annotation"]] ... inputs = image_processor(images, labels) ... return inputs ``` デヌタセット党䜓に`jitter`を適甚するには、🀗 Datasets [`~datasets.Dataset.set_transform`] 関数を䜿甚したす。倉換はオンザフラむで適甚されるため、高速で消費するディスク容量が少なくなりたす。 ```py >>> train_ds.set_transform(train_transforms) >>> test_ds.set_transform(val_transforms) ``` </pt> </frameworkcontent> <frameworkcontent> <tf> モデルを過孊習に察しおより堅牢にするために、画像デヌタセットにいく぀かのデヌタ拡匵を適甚するのが䞀般的です。 このガむドでは、[`tf.image`](https://www.tensorflow.org/api_docs/python/tf/image) を䜿甚しお画像の色のプロパティをランダムに倉曎したすが、任意のプロパティを䜿甚するこずもできたす。画像 奜きな図曞通。 2 ぀の別々の倉換関数を定矩したす。 - 画像拡匵を含むトレヌニング デヌタ倉換 - 🀗 Transformers のコンピュヌタヌ ビゞョン モデルはチャネル優先のレむアりトを想定しおいるため、画像を転眮するだけの怜蚌デヌタ倉換 ```py >>> import tensorflow as tf >>> def aug_transforms(image): ... image = tf.keras.utils.img_to_array(image) ... image = tf.image.random_brightness(image, 0.25) ... image = tf.image.random_contrast(image, 0.5, 2.0) ... image = tf.image.random_saturation(image, 0.75, 1.25) ... image = tf.image.random_hue(image, 0.1) ... image = tf.transpose(image, (2, 0, 1)) ... return image >>> def transforms(image): ... image = tf.keras.utils.img_to_array(image) ... image = tf.transpose(image, (2, 0, 1)) ... return image ``` 次に、モデルの画像ず泚釈のバッチを準備する 2 ぀の前凊理関数を䜜成したす。これらの機胜が適甚されたす 画像倉換を行い、以前にロヌドされた `image_processor` を䜿甚しお画像を `pixel_values` に倉換し、 `labels`ぞの泚釈。 `ImageProcessor` は、画像のサむズ倉曎ず正芏化も凊理したす。 ```py >>> def train_transforms(example_batch): ... images = [aug_transforms(x.convert("RGB")) for x in example_batch["image"]] ... labels = [x for x in example_batch["annotation"]] ... inputs = image_processor(images, labels) ... return inputs >>> def val_transforms(example_batch): ... images = [transforms(x.convert("RGB")) for x in example_batch["image"]] ... labels = [x for x in example_batch["annotation"]] ... inputs = image_processor(images, labels) ... return inputs ``` デヌタセット党䜓に前凊理倉換を適甚するには、🀗 Datasets [`~datasets.Dataset.set_transform`] 関数を䜿甚したす。 倉換はオンザフラむで適甚されるため、高速で消費するディスク容量が少なくなりたす。 ```py >>> train_ds.set_transform(train_transforms) >>> test_ds.set_transform(val_transforms) ``` </tf> </frameworkcontent> ## Evaluate トレヌニング䞭にメトリクスを含めるず、倚くの堎合、モデルのパフォヌマンスを評䟡するのに圹立ちたす。 🀗 [Evaluate](https://huggingface.co/docs/evaluate/index) ラむブラリを䜿甚しお、評䟡メ゜ッドをすばやくロヌドできたす。このタスクでは、[Mean Intersection over Union](https://huggingface.co/spaces/evaluate-metric/accuracy) (IoU) メトリックをロヌドしたす (🀗 Evaluate [クむック ツアヌ](https://huggingface.co) を参照しおください) /docs/evaluate/a_quick_tour) を参照しお、メトリクスをロヌドしお蚈算する方法の詳现を確認しおください)。 ```py >>> import evaluate >>> metric = evaluate.load("mean_iou") ``` 次に、メトリクスを [`~evaluate.EvaluationModule.compute`] する関数を䜜成したす。予枬を次のように倉換する必芁がありたす 最初にロゞットを䜜成し、次に [`~evaluate.EvaluationModule.compute`] を呌び出す前にラベルのサむズに䞀臎するように再圢成したす。 <frameworkcontent> <pt> ```py >>> import numpy as np >>> import torch >>> from torch import nn >>> def compute_metrics(eval_pred): ... with torch.no_grad(): ... logits, labels = eval_pred ... logits_tensor = torch.from_numpy(logits) ... logits_tensor = nn.functional.interpolate( ... logits_tensor, ... size=labels.shape[-2:], ... mode="bilinear", ... align_corners=False, ... ).argmax(dim=1) ... pred_labels = logits_tensor.detach().cpu().numpy() ... metrics = metric.compute( ... predictions=pred_labels, ... references=labels, ... num_labels=num_labels, ... ignore_index=255, ... reduce_labels=False, ... ) ... for key, value in metrics.items(): ... if type(value) is np.ndarray: ... metrics[key] = value.tolist() ... return metrics ``` </pt> </frameworkcontent> <frameworkcontent> <tf> ```py >>> def compute_metrics(eval_pred): ... logits, labels = eval_pred ... logits = tf.transpose(logits, perm=[0, 2, 3, 1]) ... logits_resized = tf.image.resize( ... logits, ... size=tf.shape(labels)[1:], ... method="bilinear", ... ) ... pred_labels = tf.argmax(logits_resized, axis=-1) ... metrics = metric.compute( ... predictions=pred_labels, ... references=labels, ... num_labels=num_labels, ... ignore_index=-1, ... reduce_labels=image_processor.do_reduce_labels, ... ) ... per_category_accuracy = metrics.pop("per_category_accuracy").tolist() ... per_category_iou = metrics.pop("per_category_iou").tolist() ... metrics.update({f"accuracy_{id2label[i]}": v for i, v in enumerate(per_category_accuracy)}) ... metrics.update({f"iou_{id2label[i]}": v for i, v in enumerate(per_category_iou)}) ... return {"val_" + k: v for k, v in metrics.items()} ``` </tf> </frameworkcontent> これで`compute_metrics`関数の準備が敎いたした。トレヌニングをセットアップするずきにこの関数に戻りたす。 ## Train <frameworkcontent> <pt> <Tip> [`Trainer`] を䜿甚したモデルの埮調敎に慣れおいない堎合は、[こちら](../training#finetune-with-trainer) の基本的なチュヌトリアルをご芧ください。 </Tip> これでモデルのトレヌニングを開始する準備が敎いたした。 [`AutoModelForSemanticSegmentation`] を䜿甚しお SegFormer をロヌドし、ラベル ID ずラベル クラス間のマッピングをモデルに枡したす。 ```py >>> from transformers import AutoModelForSemanticSegmentation, TrainingArguments, Trainer >>> model = AutoModelForSemanticSegmentation.from_pretrained(checkpoint, id2label=id2label, label2id=label2id) ``` この時点で残っおいる手順は次の 3 ぀だけです。 1. [`TrainingArguments`] でトレヌニング ハむパヌパラメヌタを定矩したす。 `image` 列が削陀されるため、未䜿甚の列を削陀しないこずが重芁です。 `image` 列がないず、`pixel_values` を䜜成できたせん。この動䜜を防ぐには、`remove_unused_columns=False`を蚭定しおください。他に必芁なパラメヌタは、モデルの保存堎所を指定する `output_dir` だけです。 `push_to_hub=True`を蚭定しお、このモデルをハブにプッシュしたす (モデルをアップロヌドするには、Hugging Face にサむンむンする必芁がありたす)。各゚ポックの終了時に、[`Trainer`] は IoU メトリックを評䟡し、トレヌニング チェックポむントを保存したす。 2. トレヌニング匕数を、モデル、デヌタセット、トヌクナむザヌ、デヌタ照合噚、および `compute_metrics` 関数ずずもに [`Trainer`] に枡したす。 3. [`~Trainer.train`] を呌び出しおモデルを埮調敎したす。 ```py >>> training_args = TrainingArguments( ... output_dir="segformer-b0-scene-parse-150", ... learning_rate=6e-5, ... num_train_epochs=50, ... per_device_train_batch_size=2, ... per_device_eval_batch_size=2, ... save_total_limit=3, ... evaluation_strategy="steps", ... save_strategy="steps", ... save_steps=20, ... eval_steps=20, ... logging_steps=1, ... eval_accumulation_steps=5, ... remove_unused_columns=False, ... push_to_hub=True, ... ) >>> trainer = Trainer( ... model=model, ... args=training_args, ... train_dataset=train_ds, ... eval_dataset=test_ds, ... compute_metrics=compute_metrics, ... ) >>> trainer.train() ``` トレヌニングが完了したら、 [`~transformers.Trainer.push_to_hub`] メ゜ッドを䜿甚しおモデルをハブに共有し、誰もがモデルを䜿甚できるようにしたす。 ```py >>> trainer.push_to_hub() ``` </pt> </frameworkcontent> <frameworkcontent> <tf> <Tip> Keras を䜿甚したモデルの埮調敎に慣れおいない堎合は、たず [基本チュヌトリアル](./training#train-a-tensorflow-model-with-keras) を確認しおください。 </Tip> TensorFlow でモデルを埮調敎するには、次の手順に埓いたす。 1. トレヌニングのハむパヌパラメヌタを定矩し、オプティマむザヌず孊習率スケゞュヌルを蚭定したす。 2. 事前トレヌニングされたモデルをむンスタンス化したす。 3. 🀗 デヌタセットを `tf.data.Dataset` に倉換したす。 4. モデルをコンパむルしたす。 5. コヌルバックを远加しおメトリクスを蚈算し、モデルを 🀗 Hub にアップロヌドしたす 6. `fit()` メ゜ッドを䜿甚しおトレヌニングを実行したす。 たず、ハむパヌパラメヌタヌ、オプティマむザヌ、孊習率スケゞュヌルを定矩したす。 ```py >>> from transformers import create_optimizer >>> batch_size = 2 >>> num_epochs = 50 >>> num_train_steps = len(train_ds) * num_epochs >>> learning_rate = 6e-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, ... ) ``` 次に、ラベル マッピングずずもに [`TFAutoModelForSemanticSegmentation`] を䜿甚しお SegFormer をロヌドし、それをコンパむルしたす。 オプティマむザ。 Transformers モデルにはすべおデフォルトのタスク関連の損倱関数があるため、次の堎合を陀き、損倱関数を指定する必芁はないこずに泚意しおください。 ```py >>> from transformers import TFAutoModelForSemanticSegmentation >>> model = TFAutoModelForSemanticSegmentation.from_pretrained( ... checkpoint, ... id2label=id2label, ... label2id=label2id, ... ) >>> model.compile(optimizer=optimizer) # No loss argument! ``` [`~datasets.Dataset.to_tf_dataset`] ず [`DefaultDataCollat​​or`] を䜿甚しお、デヌタセットを `tf.data.Dataset` 圢匏に倉換したす。 ```py >>> from transformers import DefaultDataCollator >>> data_collator = DefaultDataCollator(return_tensors="tf") >>> tf_train_dataset = train_ds.to_tf_dataset( ... columns=["pixel_values", "label"], ... shuffle=True, ... batch_size=batch_size, ... collate_fn=data_collator, ... ) >>> tf_eval_dataset = test_ds.to_tf_dataset( ... columns=["pixel_values", "label"], ... shuffle=True, ... batch_size=batch_size, ... collate_fn=data_collator, ... ) ``` 予枬から粟床を蚈算し、モデルを 🀗 ハブにプッシュするには、[Keras callbacks](../main_classes/keras_callbacks) を䜿甚したす。 `compute_metrics` 関数を [`KerasMetricCallback`] に枡したす。 そしお [`PushToHubCallback`] を䜿甚しおモデルをアップロヌドしたす。 ```py >>> from transformers.keras_callbacks import KerasMetricCallback, PushToHubCallback >>> metric_callback = KerasMetricCallback( ... metric_fn=compute_metrics, eval_dataset=tf_eval_dataset, batch_size=batch_size, label_cols=["labels"] ... ) >>> push_to_hub_callback = PushToHubCallback(output_dir="scene_segmentation", tokenizer=image_processor) >>> callbacks = [metric_callback, push_to_hub_callback] ``` ぀いに、モデルをトレヌニングする準備が敎いたした。`fit()`トレヌニングおよび怜蚌デヌタセット、゚ポック数、 モデルを埮調敎するためのコヌルバック: ```py >>> model.fit( ... tf_train_dataset, ... validation_data=tf_eval_dataset, ... callbacks=callbacks, ... epochs=num_epochs, ... ) ``` おめでずうモデルを埮調敎し、🀗 Hub で共有したした。これで掚論に䜿甚できるようになりたした。 </tf> </frameworkcontent> ## Inference モデルを埮調敎したので、それを掚論に䜿甚できるようになりたした。 掚論のために画像をロヌドしたす。 ```py >>> image = ds[0]["image"] >>> image ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/semantic-seg-image.png" alt="Image of bedroom"/> </div> <frameworkcontent> <pt> 掚論甚に埮調敎されたモデルを詊す最も簡単な方法は、それを [`pipeline`] で䜿甚するこずです。モデルを䜿甚しお画像セグメンテヌション甚の `pipeline` をむンスタンス化し、それに画像を枡したす。 ```py >>> from transformers import pipeline >>> segmenter = pipeline("image-segmentation", model="my_awesome_seg_model") >>> segmenter(image) [{'score': None, 'label': 'wall', 'mask': <PIL.Image.Image image mode=L size=640x427 at 0x7FD5B2062690>}, {'score': None, 'label': 'sky', 'mask': <PIL.Image.Image image mode=L size=640x427 at 0x7FD5B2062A50>}, {'score': None, 'label': 'floor', 'mask': <PIL.Image.Image image mode=L size=640x427 at 0x7FD5B2062B50>}, {'score': None, 'label': 'ceiling', 'mask': <PIL.Image.Image image mode=L size=640x427 at 0x7FD5B2062A10>}, {'score': None, 'label': 'bed ', 'mask': <PIL.Image.Image image mode=L size=640x427 at 0x7FD5B2062E90>}, {'score': None, 'label': 'windowpane', 'mask': <PIL.Image.Image image mode=L size=640x427 at 0x7FD5B2062390>}, {'score': None, 'label': 'cabinet', 'mask': <PIL.Image.Image image mode=L size=640x427 at 0x7FD5B2062550>}, {'score': None, 'label': 'chair', 'mask': <PIL.Image.Image image mode=L size=640x427 at 0x7FD5B2062D90>}, {'score': None, 'label': 'armchair', 'mask': <PIL.Image.Image image mode=L size=640x427 at 0x7FD5B2062E10>}] ``` 必芁に応じお、`pipeline` の結果を手動で耇補するこずもできたす。画像プロセッサで画像を凊理し、`pixel_values`を GPU に配眮したす。 ```py >>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # use GPU if available, otherwise use a CPU >>> encoding = image_processor(image, return_tensors="pt") >>> pixel_values = encoding.pixel_values.to(device) ``` 入力をモデルに枡し、「logits」を返したす。 ```py >>> outputs = model(pixel_values=pixel_values) >>> logits = outputs.logits.cpu() ``` 次に、ロゞットを元の画像サむズに再スケヌルしたす。 ```py >>> upsampled_logits = nn.functional.interpolate( ... logits, ... size=image.size[::-1], ... mode="bilinear", ... align_corners=False, ... ) >>> pred_seg = upsampled_logits.argmax(dim=1)[0] ``` ``` </pt> </frameworkcontent> <frameworkcontent> <tf> 画像プロセッサをロヌドしお画像を前凊理し、入力を TensorFlow テン゜ルずしお返したす。 ```py >>> from transformers import AutoImageProcessor >>> image_processor = AutoImageProcessor.from_pretrained("MariaK/scene_segmentation") >>> inputs = image_processor(image, return_tensors="tf") ``` 入力をモデルに枡し、`logits`を返したす。 ```py >>> from transformers import TFAutoModelForSemanticSegmentation >>> model = TFAutoModelForSemanticSegmentation.from_pretrained("MariaK/scene_segmentation") >>> logits = model(**inputs).logits ``` 次に、ロゞットを元の画像サむズに再スケヌルし、クラス次元に argmax を適甚したす。 ```py >>> logits = tf.transpose(logits, [0, 2, 3, 1]) >>> upsampled_logits = tf.image.resize( ... logits, ... # We reverse the shape of `image` because `image.size` returns width and height. ... image.size[::-1], ... ) >>> pred_seg = tf.math.argmax(upsampled_logits, axis=-1)[0] ``` </tf> </frameworkcontent> 結果を芖芚化するには、[デヌタセット カラヌ パレット](https://github.com/tensorflow/models/blob/3f1ca33afe3c1631b733ea7e40c294273b9e406d/research/deeplab/utils/get_dataset_colormap.py#L51) を、それぞれをマップする `ade_palette()` ずしおロヌドしたす。クラスを RGB 倀に倉換したす。次に、画像ず予枬されたセグメンテヌション マップを組み合わせおプロットできたす。 ```py >>> import matplotlib.pyplot as plt >>> import numpy as np >>> color_seg = np.zeros((pred_seg.shape[0], pred_seg.shape[1], 3), dtype=np.uint8) >>> palette = np.array(ade_palette()) >>> for label, color in enumerate(palette): ... color_seg[pred_seg == label, :] = color >>> color_seg = color_seg[..., ::-1] # convert to BGR >>> img = np.array(image) * 0.5 + color_seg * 0.5 # plot the image with the segmentation map >>> img = img.astype(np.uint8) >>> plt.figure(figsize=(15, 10)) >>> plt.imshow(img) >>> plt.show() ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/semantic-seg-preds.png" alt="Image of bedroom overlaid with segmentation map"/> </div>
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/tasks/knowledge_distillation_for_image_classification.md
<!--Copyright 2023 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Knowledge Distillation for Computer Vision [[open-in-colab]] 知識の蒞留は、より倧芏暡で耇雑なモデル (教垫) からより小芏暡で単玔なモデル (生埒) に知識を䌝達するために䜿甚される手法です。あるモデルから別のモデルに知識を抜出するには、特定のタスク (この堎合は画像分類) でトレヌニングされた事前トレヌニング枈み教垫モデルを取埗し、画像分類でトレヌニングされる生埒モデルをランダムに初期化したす。次に、孊生モデルをトレヌニングしお、その出力ず教垫の出力の差を最小限に抑え、動䜜を暡倣したす。これは [Distilling the Knowledge in a Neural Network by Hinton et al](https://arxiv.org/abs/1503.02531) で最初に導入されたした。このガむドでは、タスク固有の知識の蒞留を行いたす。これには [Beans デヌタセット](https://huggingface.co/datasets/beans) を䜿甚したす。 このガむドでは、[埮調敎された ViT モデル](https://huggingface.co/merve/vit-mobilenet-beans-224) (教垫モデル) を抜出しお [MobileNet](https://huggingface. co/google/mobilenet_v2_1.4_224) (孊生モデル) 🀗 Transformers の [Trainer API](https://huggingface.co/docs/transformers/en/main_classes/trainer#trainer) を䜿甚したす。 蒞留ずプロセスの評䟡に必芁なラむブラリをむンストヌルしたしょう。 ```bash pip install transformers datasets accelerate tensorboard evaluate --upgrade ``` この䟋では、教垫モデルずしお`merve/beans-vit-224`モデルを䜿甚しおいたす。これは、Bean デヌタセットに基づいお埮調敎された`google/vit-base-patch16-224-in21k`に基づく画像分類モデルです。このモデルをランダムに初期化された MobileNetV2 に抜出したす。 次に、デヌタセットをロヌドしたす。 ```python from datasets import load_dataset dataset = load_dataset("beans") ``` この堎合、同じ解像床で同じ出力が返されるため、どちらのモデルの画像プロセッサも䜿甚できたす。 `dataset`の`map()`メ゜ッドを䜿甚しお、デヌタセットのすべおの分割に前凊理を適甚したす。 ```python from transformers import AutoImageProcessor teacher_processor = AutoImageProcessor.from_pretrained("merve/beans-vit-224") def process(examples): processed_inputs = teacher_processor(examples["image"]) return processed_inputs processed_datasets = dataset.map(process, batched=True) ``` 基本的に、我々は生埒モデルランダムに初期化されたMobileNetが教垫モデル埮調敎されたビゞョン倉換噚を暡倣するこずを望む。これを実珟するために、たず教垫ず生埒からロゞット出力を埗る。次に、それぞれの゜フトタヌゲットの重芁床を制埡するパラメヌタ`temperature`で分割する。`lambda`ず呌ばれるパラメヌタは蒞留ロスの重芁床を量る。この䟋では、`temperature=5`、`lambda=0.5`ずする。生埒ず教垫の間の発散を蚈算するために、Kullback-Leibler発散損倱を䜿甚したす。2぀のデヌタPずQが䞎えられたずき、KLダむバヌゞェンスはQを䜿っおPを衚珟するためにどれだけの䜙分な情報が必芁かを説明したす。もし2぀が同じであれば、QからPを説明するために必芁な他の情報はないので、それらのKLダむバヌゞェンスはれロになりたす。 ```python from transformers import TrainingArguments, Trainer import torch import torch.nn as nn import torch.nn.functional as F class ImageDistilTrainer(Trainer): def __init__(self, *args, teacher_model=None, **kwargs): super().__init__(*args, **kwargs) self.teacher = teacher_model self.student = student_model self.loss_function = nn.KLDivLoss(reduction="batchmean") device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') self.teacher.to(device) self.teacher.eval() self.temperature = temperature self.lambda_param = lambda_param def compute_loss(self, student, inputs, return_outputs=False): student_output = self.student(**inputs) with torch.no_grad(): teacher_output = self.teacher(**inputs) # Compute soft targets for teacher and student soft_teacher = F.softmax(teacher_output.logits / self.temperature, dim=-1) soft_student = F.log_softmax(student_output.logits / self.temperature, dim=-1) # Compute the loss distillation_loss = self.loss_function(soft_student, soft_teacher) * (self.temperature ** 2) # Compute the true label loss student_target_loss = student_output.loss # Calculate final loss loss = (1. - self.lambda_param) * student_target_loss + self.lambda_param * distillation_loss return (loss, student_output) if return_outputs else loss ``` 次に、Hugging Face Hub にログむンしお、`trainer`を通じおモデルを Hugging Face Hub にプッシュできるようにしたす。 ```python from huggingface_hub import notebook_login notebook_login() ``` 教垫モデルず生埒モデルである`TrainingArguments`を蚭定したしょう。 ```python from transformers import AutoModelForImageClassification, MobileNetV2Config, MobileNetV2ForImageClassification training_args = TrainingArguments( output_dir="my-awesome-model", num_train_epochs=30, fp16=True, logging_dir=f"{repo_name}/logs", logging_strategy="epoch", evaluation_strategy="epoch", save_strategy="epoch", load_best_model_at_end=True, metric_for_best_model="accuracy", report_to="tensorboard", push_to_hub=True, hub_strategy="every_save", hub_model_id=repo_name, ) num_labels = len(processed_datasets["train"].features["labels"].names) # initialize models teacher_model = AutoModelForImageClassification.from_pretrained( "merve/beans-vit-224", num_labels=num_labels, ignore_mismatched_sizes=True ) # training MobileNetV2 from scratch student_config = MobileNetV2Config() student_config.num_labels = num_labels student_model = MobileNetV2ForImageClassification(student_config) ``` `compute_metrics` 関数を䜿甚しお、テスト セットでモデルを評䟡できたす。この関数は、トレヌニング プロセス䞭にモデルの`accuracy`ず`f1`を蚈算するために䜿甚されたす。 ```python import evaluate import numpy as np accuracy = evaluate.load("accuracy") def compute_metrics(eval_pred): predictions, labels = eval_pred acc = accuracy.compute(references=labels, predictions=np.argmax(predictions, axis=1)) return {"accuracy": acc["accuracy"]} ``` 定矩したトレヌニング匕数を䜿甚しお`Trainer`を初期化したしょう。デヌタ照合装眮も初期化したす。 ```python from transformers import DefaultDataCollator data_collator = DefaultDataCollator() trainer = ImageDistilTrainer( student_model=student_model, teacher_model=teacher_model, training_args=training_args, train_dataset=processed_datasets["train"], eval_dataset=processed_datasets["validation"], data_collator=data_collator, tokenizer=teacher_extractor, compute_metrics=compute_metrics, temperature=5, lambda_param=0.5 ) ``` これでモデルをトレヌニングできるようになりたした。 ```python trainer.train() ``` テスト セットでモデルを評䟡できたす。 ```python trainer.evaluate(processed_datasets["test"]) ``` テスト セットでは、モデルの粟床は 72% に達したす。蒞留効率の健党性チェックを行うために、同じハむパヌパラメヌタを䜿甚しお Bean デヌタセットで MobileNet を最初からトレヌニングし、テスト セットで 63% の粟床を芳察したした。読者の皆様には、さたざたな事前トレヌニング枈み教垫モデル、孊生アヌキテクチャ、蒞留パラメヌタを詊しおいただき、その結果を報告しおいただくようお勧めしたす。抜出されたモデルのトレヌニング ログずチェックポむントは [このリポゞトリ](https://huggingface.co/merve/vit-mobilenet-beans-224) にあり、最初からトレヌニングされた MobileNetV2 はこの [リポゞトリ]( https://huggingface.co/merve/resnet-mobilenet-beans-5)。
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/tasks/zero_shot_image_classification.md
<!--Copyright 2023 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Zero-shot image classification [[open-in-colab]] れロショット画像分類は、次のモデルを䜿甚しお画像をさたざたなカテゎリに分類するタスクです。 これらの特定のカテゎリのラベル付きの䟋を含むデヌタに察しお明瀺的にトレヌニングされおいない。 埓来、画像分類には、ラベル付き画像の特定のセットでモデルをトレヌニングする必芁があり、このモデルは次のこずを孊習したす。 特定の画像の特城をラベルに「マッピング」したす。分類タスクにそのようなモデルを䜿甚する必芁がある堎合、 新しいラベルのセットでは、モデルを "再調敎" するために埮調敎が必​​芁です。 察照的に、れロショットたたはオヌプン語圙画像分類モデルは、通垞、倧芏暡なシステムでトレヌニングされたマルチモヌダル モデルです。 画像ず関連する説明のデヌタセット。これらのモデルは、れロショット画像分類を含む倚くの䞋流タスクに䜿甚できる、調敎された芖芚蚀語衚珟を孊習したす。 これは、画像分類に察するより柔軟なアプロヌチであり、モデルを新しいただ芋たこずのないカテゎリに䞀般化できるようになりたす。 远加のトレヌニング デヌタを必芁ずせず、ナヌザヌはタヌゲット オブゞェクトの自由圢匏のテキスト説明を含む画像をク゚リできるようになりたす。 このガむドでは、次の方法を孊びたす。 * れロショット画像分類パむプラむンを䜜成する * 手動でれロショット画像分類掚論を実行したす 始める前に、必芁なラむブラリがすべおむンストヌルされおいるこずを確認しおください。 ```bash pip install -q transformers ``` ## Zero-shot image classification 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 ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/owl.jpg" alt="Photo of an owl"/> </div> 画像ず候補オブゞェクトのラベルをパむプラむンに枡したす。ここでは画像を盎接枡したす。他の適切なオプション 画像ぞのロヌカル パスたたは画像 URL を含めたす。 候補ラベルは、この䟋のように単玔な単語にするこずも、より説明的な単語にするこずもできたす。 ```py >>> predictions = detector(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 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 ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/car.jpg" alt="Photo of a car"/> </div> プロセッサを䜿甚しおモデルの入力を準備したす。プロセッサヌは、 サむズ倉曎ず正芏化によるモデルの画像、およびテキスト入力を凊理するトヌクナむザヌ。 ```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'}] ```
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/tasks/visual_question_answering.md
<!--Copyright 2023 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Visual Question Answering [[open-in-colab]] Visual Question Answering (VQA) は、画像に基づいお自由圢匏の質問に答えるタスクです。 このタスクをサポヌトするモデルぞの入力は通垞、画像ず質問の組み合わせであり、出力は 自然蚀語で衚珟された答え。 VQA の泚目すべき䜿甚䟋には次のようなものがありたす。 * 芖芚障害者向けのアクセシビリティ アプリケヌション。 * 教育: 講矩や教科曞で瀺されおいる芖芚的な資料に぀いお質問を投げかけるこず。 VQA は、むンタラクティブな博物通の展瀺物や史跡でも利甚できたす。 * カスタマヌ サヌビスず電子商取匕: VQA は、ナヌザヌが補品に぀いお質問できるようにするこずでナヌザヌ ゚クスペリ゚ンスを向䞊させたす。 * 画像怜玢: VQA モデルを䜿甚しお、特定の特城を持぀画像を怜玢できたす。たずえば、ナヌザヌは「犬はいたすか?」ず尋ねるこずができたす。䞀連の画像から犬が写っおいるすべおの画像を怜玢したす。 このガむドでは、次の方法を孊びたす。 - [`Graphcore/vqa` デヌタセット](https://huggingface.co/datasets/Graphcore/vqa) 䞊で分類 VQA モデル、特に [ViLT](../model_doc/vilt) を埮調敎したす。 - 埮調敎された ViLT を掚論に䜿甚したす。 - BLIP-2 などの生成モデルを䜿甚しおれロショット VQA 掚論を実行したす。 ## Fine-tuning ViLT ViLT モデルは、Vision Transformer (ViT) にテキスト埋め蟌みを組み蟌んでおり、最小限の蚭蚈を可胜にしたす。 芖芚ず蚀語の事前トレヌニング (VLP)。このモデルは、いく぀かの䞋流タスクに䜿甚できたす。 VQA タスクの堎合、分類子 head は最䞊郚 (`[CLS]` トヌクンの最終的な非衚瀺状態の最䞊郚にある線圢局) に配眮され、ランダムに初期化されたす。 したがっお、芖芚的質問応答は **分類問題** ずしお扱われたす。 BLIP、BLIP-2、InstructBLIP などの最近のモデルは、VQA を生成タスクずしお扱いたす。このガむドの埌半では、 れロショット VQA 掚論にそれらを䜿甚する方法を瀺したす。 始める前に、必芁なラむブラリがすべおむンストヌルされおいるこずを確認しおください。 ```bash pip install -q transformers datasets ``` モデルをコミュニティず共有するこずをお勧めしたす。 Hugging Face アカりントにログむンしお、🀗 ハブにアップロヌドしたす。 プロンプトが衚瀺されたら、トヌクンを入力しおログむンしたす。 ```py >>> from huggingface_hub import notebook_login >>> notebook_login() ``` モデルのチェックポむントをグロヌバル倉数ずしお定矩したしょう。 ```py >>> model_checkpoint = "dandelin/vilt-b32-mlm" ``` ## Load the data 説明の目的で、このガむドでは、泚釈付きの芖芚的な質問に答える「Graphcore/vqa」デヌタセットの非垞に小さなサンプルを䜿甚したす。 完党なデヌタセットは [🀗 Hub](https://huggingface.co/datasets/Graphcore/vqa) で芋぀けるこずができたす。 [`Graphcore/vqa` デヌタセット](https://huggingface.co/datasets/Graphcore/vqa) の代わりに、 公匏 [VQA デヌタセット ペヌゞ](https://visualqa.org/download.html) から同じデヌタを手動で取埗したす。フォロヌしたい堎合は、 カスタム デヌタを䜿甚したチュヌトリアルでは、[画像デヌタセットを䜜成する](https://huggingface.co/docs/datasets/image_dataset#loading-script) 方法を確認しおください。 🀗 デヌタセットのドキュメントのガむド。 怜蚌分割から最初の 200 個の䟋をロヌドし、デヌタセットの機胜を調べおみたしょう。 ```python >>> from datasets import load_dataset >>> dataset = load_dataset("Graphcore/vqa", split="validation[:200]") >>> dataset Dataset({ features: ['question', 'question_type', 'question_id', 'image_id', 'answer_type', 'label'], num_rows: 200 }) ``` デヌタセットの特城を理解するために䟋を芋おみたしょう。 ```py >>> dataset[0] {'question': 'Where is he looking?', 'question_type': 'none of the above', 'question_id': 262148000, 'image_id': '/root/.cache/huggingface/datasets/downloads/extracted/ca733e0e000fb2d7a09fbcc94dbfe7b5a30750681d0e965f8e0a23b1c2f98c75/val2014/COCO_val2014_000000262148.jpg', 'answer_type': 'other', 'label': {'ids': ['at table', 'down', 'skateboard', 'table'], 'weights': [0.30000001192092896, 1.0, 0.30000001192092896, 0.30000001192092896]}} ``` このタスクに関連する機胜には次のものがありたす。 * `question`: 画像から回答する質問 * `image_id`: 質問が参照する画像ぞのパス * `label`: 泚釈 残りの機胜は必芁ないので削陀できたす。 ```py >>> dataset = dataset.remove_columns(['question_type', 'question_id', 'answer_type']) ``` ご芧のずおり、`label`機胜には、さたざたなヒュヌマン・アノテヌタヌによっお収集された、同じ質問に察する耇数の回答 (ここでは`id`ず呌びたす) が含たれおいたす。 質問に察する答えは䞻芳的なものになる可胜性があるためです。この堎合、問題は "圌はどこを芋おいるのか"ずいうこずです。䞀郚の人々 これには "ダりン" ずいう泚釈が付けられ、他のものには "テヌブルで" ずいう泚釈が付けられ、別の泚釈には "スケヌトボヌド" ずいう泚釈が付けられたした。 画像を芋お、どの答えを出すかを考えおください。 ```python >>> from PIL import Image >>> image = Image.open(dataset[0]['image_id']) >>> image ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/vqa-example.png" alt="VQA Image Example"/> </div> 質問ず回答のあいたいさのため、このようなデヌタセットはマルチラベル分類問題ずしお扱われたす ( 耇数の回答が有効である可胜性がありたす)。さらに、ワンホット ゚ンコヌドされたベクトルを䜜成するだけではなく、 泚釈内に特定の回答が出珟した回数に基づく゜フト ゚ンコヌディング。 たずえば、䞊の䟋では、"down"ずいう回答が他の回答よりも頻繁に遞択されるため、 スコア (デヌタセットでは`weight`ず呌ばれたす) は 1.0 で、残りの回答のスコアは 1.0 未満です。 埌で適切な分類ヘッドを䜿甚しおモデルをむンスタンス化するために、2 ぀の蟞曞を䜜成したしょう。 ラベル名を敎数に倉換する、たたはその逆: ```py >>> import itertools >>> labels = [item['ids'] for item in dataset['label']] >>> flattened_labels = list(itertools.chain(*labels)) >>> unique_labels = list(set(flattened_labels)) >>> label2id = {label: idx for idx, label in enumerate(unique_labels)} >>> id2label = {idx: label for label, idx in label2id.items()} ``` マッピングができたので、文字列の回答をその ID に眮き換え、さらに前凊理をより䟿利にするためにデヌタセットをフラット化するこずができたす。 ```python >>> def replace_ids(inputs): ... inputs["label"]["ids"] = [label2id[x] for x in inputs["label"]["ids"]] ... return inputs >>> dataset = dataset.map(replace_ids) >>> flat_dataset = dataset.flatten() >>> flat_dataset.features {'question': Value(dtype='string', id=None), 'image_id': Value(dtype='string', id=None), 'label.ids': Sequence(feature=Value(dtype='int64', id=None), length=-1, id=None), 'label.weights': Sequence(feature=Value(dtype='float64', id=None), length=-1, id=None)} ``` ## Preprocessing data 次のステップでは、ViLT プロセッサをロヌドしお、モデルの画像デヌタずテキスト デヌタを準備したす。 [`ViltProcessor`] は、BERT トヌクナむザヌず ViLT 画像プロセッサを䟿利な単䞀プロセッサにラップしたす。 ```py >>> from transformers import ViltProcessor >>> processor = ViltProcessor.from_pretrained(model_checkpoint) ``` デヌタを前凊理するには、[`ViltProcessor`] を䜿甚しお画像ず質問を゚ンコヌドする必芁がありたす。プロセッサヌは䜿甚したす [`BertTokenizerFast`] を䜿甚しおテキストをトヌクン化し、テキスト デヌタの `input_ids`、`attention_mask`、および `token_type_ids` を䜜成したす。 画像に関しおは、プロセッサは [`ViltImageProcessor`] を利甚しお画像のサむズ倉曎ず正芏化を行い、`pixel_values` ず `pixel_mask` を䜜成したす。 これらの前凊理ステップはすべお内郚で行われ、`processor`を呌び出すだけで枈みたす。ただし、それでも必芁なのは、 察象のラベルを準備したす。この衚珟では、各芁玠は考えられる答え (ラベル) に察応したす。正解の堎合、芁玠は保持されたす。 それぞれのスコア (重み) が蚭定され、残りの芁玠は 0 に蚭定されたす。 次の関数は、画像ず質問に `processor` を適甚し、䞊で説明したようにラベルをフォヌマットしたす。 ```py >>> import torch >>> def preprocess_data(examples): ... image_paths = examples['image_id'] ... images = [Image.open(image_path) for image_path in image_paths] ... texts = examples['question'] ... encoding = processor(images, texts, padding="max_length", truncation=True, return_tensors="pt") ... for k, v in encoding.items(): ... encoding[k] = v.squeeze() ... targets = [] ... for labels, scores in zip(examples['label.ids'], examples['label.weights']): ... target = torch.zeros(len(id2label)) ... for label, score in zip(labels, scores): ... target[label] = score ... targets.append(target) ... encoding["labels"] = targets ... return encoding ``` デヌタセット党䜓に前凊理関数を適甚するには、🀗 Datasets [`~datasets.map`] 関数を䜿甚したす。 `map` を高速化するには、次のようにしたす。 デヌタセットの耇数の芁玠を䞀床に凊理するには、`batched=True` を蚭定したす。この時点で、䞍芁な列は自由に削陀しおください。 ```py >>> processed_dataset = flat_dataset.map(preprocess_data, batched=True, remove_columns=['question','question_type', 'question_id', 'image_id', 'answer_type', 'label.ids', 'label.weights']) >>> processed_dataset Dataset({ features: ['input_ids', 'token_type_ids', 'attention_mask', 'pixel_values', 'pixel_mask', 'labels'], num_rows: 200 }) ``` 最埌のステップずしお、[`DefaultDataCollat​​or`] を䜿甚しおサンプルのバッチを䜜成したす。 ```py >>> from transformers import DefaultDataCollator >>> data_collator = DefaultDataCollator() ``` ## Train the model これでモデルのトレヌニングを開始する準備が敎いたした。 [`ViltForQuestionAnswering`] で ViLT をロヌドしたす。ラベルの数を指定したす ラベルマッピングずずもに: ```py >>> from transformers import ViltForQuestionAnswering >>> model = ViltForQuestionAnswering.from_pretrained(model_checkpoint, num_labels=len(id2label), id2label=id2label, label2id=label2id) ``` この時点で残っおいるステップは 3 ぀だけです。 1. [`TrainingArguments`] でトレヌニング ハむパヌパラメヌタを定矩したす。 ```py >>> from transformers import TrainingArguments >>> repo_id = "MariaK/vilt_finetuned_200" >>> training_args = TrainingArguments( ... output_dir=repo_id, ... per_device_train_batch_size=4, ... num_train_epochs=20, ... save_steps=200, ... logging_steps=50, ... learning_rate=5e-5, ... save_total_limit=2, ... remove_unused_columns=False, ... push_to_hub=True, ... ) ``` 2. トレヌニング匕数をモデル、デヌタセット、プロセッサヌ、デヌタ照合噚ずずもに [`Trainer`] に枡したす。 ```py >>> from transformers import Trainer >>> trainer = Trainer( ... model=model, ... args=training_args, ... data_collator=data_collator, ... train_dataset=processed_dataset, ... tokenizer=processor, ... ) ``` 3. [`~Trainer.train`] を呌び出しおモデルを埮調敎したす。 ```py >>> trainer.train() ``` トレヌニングが完了したら、 [`~Trainer.push_to_hub`] メ゜ッドを䜿甚しおモデルをハブに共有し、🀗 ハブで最終モデルを共有したす。 ```py >>> trainer.push_to_hub() ``` ## Inference ViLT モデルを埮調敎し、🀗 Hub にアップロヌドしたので、それを掚論に䜿甚できたす。もっずも単玔な 掚論甚に埮調敎されたモデルを詊す方法は、それを [`pipeline`] で䜿甚するこずです。 ```py >>> from transformers import pipeline >>> pipe = pipeline("visual-question-answering", model="MariaK/vilt_finetuned_200") ``` このガむドのモデルは 200 の䟋でのみトレヌニングされおいるため、倚くを期埅しないでください。少なくずもそれがあるかどうか芋おみたしょう デヌタから䜕かを孊習し、掚論を説明するためにデヌタセットから最初の䟋を取り出したす。 ```py >>> example = dataset[0] >>> image = Image.open(example['image_id']) >>> question = example['question'] >>> print(question) >>> pipe(image, question, top_k=1) "Where is he looking?" [{'score': 0.5498199462890625, 'answer': 'down'}] ``` あたり自信がありたせんが、モデルは確かに䜕かを孊習したした。より倚くの䟋ずより長いトレヌニングを行うず、はるかに良い結果が埗られたす。 必芁に応じお、パむプラむンの結果を手動で耇補するこずもできたす。 1. 画像ず質問を取埗し、モデルのプロセッサを䜿甚しおモデル甚に準備したす。 2. モデルを通じお結果たたは前凊理を転送したす。 3. ロゞットから、最も可胜性の高い回答の ID を取埗し、`id2label` で実際の回答を芋぀けたす。 ```py >>> processor = ViltProcessor.from_pretrained("MariaK/vilt_finetuned_200") >>> image = Image.open(example['image_id']) >>> question = example['question'] >>> # prepare inputs >>> inputs = processor(image, question, return_tensors="pt") >>> model = ViltForQuestionAnswering.from_pretrained("MariaK/vilt_finetuned_200") >>> # forward pass >>> with torch.no_grad(): ... outputs = model(**inputs) >>> logits = outputs.logits >>> idx = logits.argmax(-1).item() >>> print("Predicted answer:", model.config.id2label[idx]) Predicted answer: down ``` ## Zero-shot VQA 以前のモデルでは、VQA を分類タスクずしお扱いたした。 BLIP、BLIP-2、InstructBLIP アプロヌチなどの䞀郚の最近のモデル 生成タスクずしおの VQA。 [BLIP-2](../model_doc/blip-2) を䟋ずしお考えおみたしょう。新しいビゞュアル蚀語の事前トレヌニングを導入したした 事前にトレヌニングされたビゞョン ゚ンコヌダヌず LLM を任意に組み合わせお䜿甚​​できるパラダむム (詳现に぀いおは、[BLIP-2 ブログ投皿](https://huggingface.co/blog/blip-2) を参照)。 これにより、芖芚的な質問応答を含む耇数の芖芚蚀語タスクで最先端の結果を達成するこずができたす。 このモデルを VQA に䜿甚する方法を説明したしょう。たず、モデルをロヌドしたしょう。ここではモデルを明瀺的に送信したす。 GPU (利甚可胜な堎合)。これは [`Trainer`] が自動的に凊理するため、トレヌニング時に事前に行う必芁はありたせんでした。 ```py >>> from transformers import AutoProcessor, Blip2ForConditionalGeneration >>> import torch >>> processor = AutoProcessor.from_pretrained("Salesforce/blip2-opt-2.7b") >>> model = Blip2ForConditionalGeneration.from_pretrained("Salesforce/blip2-opt-2.7b", torch_dtype=torch.float16) >>> device = "cuda" if torch.cuda.is_available() else "cpu" >>> model.to(device) ``` モデルは画像ずテキストを入力ずしお受け取るため、VQA デヌタセットの最初の䟋ずたったく同じ画像ず質問のペアを䜿甚しおみたしょう。 ```py >>> example = dataset[0] >>> image = Image.open(example['image_id']) >>> question = example['question'] ``` 芖芚的な質問応答タスクに BLIP-2 を䜿甚するには、テキスト プロンプトが特定の圢匏 (`Question: {} Answer:`) に埓う必芁がありたす。 ```py >>> prompt = f"Question: {question} Answer:" ``` 次に、モデルのプロセッサで画像/プロンプトを前凊理し、凊理された入力をモデルに枡し、出力をデコヌドする必芁がありたす。 ```py >>> inputs = processor(image, text=prompt, return_tensors="pt").to(device, torch.float16) >>> generated_ids = model.generate(**inputs, max_new_tokens=10) >>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip() >>> print(generated_text) "He is looking at the crowd" ``` ご芧のずおり、モデルは矀衆ず顔の向き (䞋を向いおいる) を認識したしたが、芋逃しおいるようです。 芳客がスケヌタヌの埌ろにいるずいう事実。それでも、人間が泚釈を付けたデヌタセットを取埗するこずが䞍可胜な堎合には、これは このアプロヌチにより、有甚な結果がすぐに埗られたす。
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/tasks/image_classification.md
<!--Copyright 2022 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Image classification [[open-in-colab]] <Youtube id="tjAIM7BOYhw"/> 画像分類では、画像にラベルたたはクラスを割り圓おたす。テキストや音声の分類ずは異なり、入力は 画像を構成するピクセル倀。損傷の怜出など、画像分類には倚くの甚途がありたす 自然灜害の埌、䜜物の健康状態を監芖したり、病気の兆候がないか医療画像をスクリヌニングしたりするのに圹立ちたす。 このガむドでは、次の方法を説明したす。 1. [Food-101](https://huggingface.co/datasets/food101) デヌタセットの [ViT](model_doc/vit) を埮調敎しお、画像内の食品を分類したす。 2. 埮調敎したモデルを掚論に䜿甚したす。 <Tip> このチュヌトリアルで説明するタスクは、次のモデル アヌキテクチャでサポヌトされおいたす。 <!--This tip is automatically generated by `make fix-copies`, do not fill manually!--> [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), [DINOv2](../model_doc/dinov2), [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), [MobileViTV2](../model_doc/mobilevitv2), [NAT](../model_doc/nat), [Perceiver](../model_doc/perceiver), [PoolFormer](../model_doc/poolformer), [PVT](../model_doc/pvt), [RegNet](../model_doc/regnet), [ResNet](../model_doc/resnet), [SegFormer](../model_doc/segformer), [SwiftFormer](../model_doc/swiftformer), [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) <!--End of the generated tip--> </Tip> 始める前に、必芁なラむブラリがすべおむンストヌルされおいるこずを確認しおください。 ```bash pip install transformers datasets evaluate ``` Hugging Face アカりントにログむンしお、モデルをアップロヌドしおコミュニティず共有するこずをお勧めしたす。プロンプトが衚瀺されたら、トヌクンを入力しおログむンしたす。 ```py >>> from huggingface_hub import notebook_login >>> notebook_login() ``` ## Load Food-101 dataset Datasets、🀗 デヌタセット ラむブラリから Food-101 デヌタセットの小さいサブセットを読み蟌みたす。これにより、次の機䌚が埗られたす 完党なデヌタセットのトレヌニングにさらに時間を費やす前に、実隓しおすべおが機胜するこずを確認しおください。 ```py >>> from datasets import load_dataset >>> food = load_dataset("food101", split="train[:5000]") ``` [`~datasets.Dataset.train_test_split`] メ゜ッドを䜿甚しお、デヌタセットの `train` 分割をトレむン セットずテスト セットに分割したす。 ```py >>> food = food.train_test_split(test_size=0.2) ``` 次に、䟋を芋おみたしょう。 ```py >>> food["train"][0] {'image': <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=512x512 at 0x7F52AFC8AC50>, 'label': 79} ``` デヌタセット内の各䟋には 2 ぀のフィヌルドがありたす。 - `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) ``` <frameworkcontent> <pt> いく぀かの画像倉換を画像に適甚しお、モデルの過孊習に察する堅牢性を高めたす。ここでは 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) ``` 次に、[`DefaultDataCollat​​or`] を䜿甚しおサンプルのバッチを䜜成したす。 🀗 Transformers の他のデヌタ照合噚ずは異なり、`DefaultDataCollat​​or` はパディングなどの远加の前凊理を適甚したせん。 ```py >>> from transformers import DefaultDataCollator >>> data_collator = DefaultDataCollator() ``` </pt> </frameworkcontent> <frameworkcontent> <tf> 過剰適合を回避し、モデルをより堅牢にするために、デヌタセットのトレヌニング郚分にデヌタ拡匵を远加したす。 ここでは、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", ... ) ``` 次に、䞀床に 1 ぀の画像ではなく、画像のバッチに適切な倉換を適甚する関数を䜜成したす。 ```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.Dataset.set_transform`] を䜿甚しお、その堎で倉換を適甚したす。 ```py food["train"].set_transform(preprocess_train) food["test"].set_transform(preprocess_val) ``` 最埌の前凊理ステップずしお、`DefaultDataCollat​​or`を䜿甚しおサンプルのバッチを䜜成したす。 🀗 Transformers の他のデヌタ照合機胜ずは異なり、 `DefaultDataCollat​​or` は、パディングなどの远加の前凊理を適甚したせん。 ```py >>> from transformers import DefaultDataCollator >>> data_collator = DefaultDataCollator(return_tensors="tf") ``` </tf> </frameworkcontent> ## Evaluate トレヌニング䞭にメトリクスを含めるず、倚くの堎合、モデルのパフォヌマンスを評䟡するのに圹立ちたす。すぐにロヌドできたす 🀗 [Evaluate](https://huggingface.co/docs/evaluate/index) ラむブラリを䜿甚した評䟡方法。このタスクでは、ロヌドしたす [accuracy](https://huggingface.co/spaces/evaluate-metric/accuracy) 指暙 (詳现に぀いおは、🀗 評䟡 [クむック ツアヌ](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 <frameworkcontent> <pt> <Tip> [`Trainer`] を䜿甚したモデルの埮調敎に慣れおいない堎合は、[こちら](../training#train-with-pytorch-trainer) の基本的なチュヌトリアルをご芧ください。 </Tip> これでモデルのトレヌニングを開始する準備が敎いたした。 [`AutoModelForImageClassification`] を䜿甚しお ViT をロヌドしたす。ラベルの数ず予想されるラベルの数、およびラベル マッピングを指定したす。 ```py >>> from transformers import AutoModelForImageClassification, TrainingArguments, Trainer >>> model = AutoModelForImageClassification.from_pretrained( ... checkpoint, ... num_labels=len(labels), ... id2label=id2label, ... label2id=label2id, ... ) ``` この時点で残っおいるステップは 3 ぀だけです。 1. [`TrainingArguments`] でトレヌニング ハむパヌパラメヌタを定矩したす。 `image` 列が削陀されるため、未䜿甚の列を削陀しないこずが重芁です。 `image` 列がないず、`pixel_values` を䜜成できたせん。この動䜜を防ぐには、`remove_unused_columns=False`を蚭定しおください。他に必芁なパラメヌタは、モデルの保存堎所を指定する `output_dir` だけです。 `push_to_hub=True`を蚭定しお、このモデルをハブにプッシュしたす (モデルをアップロヌドするには、Hugging Face にサむンむンする必芁がありたす)。各゚ポックの終了時に、[`Trainer`] は粟床を評䟡し、トレヌニング チェックポむントを保存したす。 2. トレヌニング匕数を、モデル、デヌタセット、トヌクナむザヌ、デヌタ照合噚、および `compute_metrics` 関数ずずもに [`Trainer`] に枡したす。 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() ``` </pt> </frameworkcontent> <frameworkcontent> <tf> <Tip> Keras を䜿甚したモデルの埮調敎に慣れおいない堎合は、たず [基本チュヌトリアル](./training#train-a-tensorflow-model-with-keras) を確認しおください。 </Tip> TensorFlow でモデルを埮調敎するには、次の手順に埓いたす。 1. トレヌニングのハむパヌパラメヌタを定矩し、オプティマむザヌず孊習率スケゞュヌルを蚭定したす。 2. 事前トレヌニングされたモデルをむンスタンス化したす。 3. 🀗 デヌタセットを `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, ... ) ``` 次に、ラベル マッピングずずもに [`TFAutoModelForImageClassification`] を䜿甚しお ViT を読み蟌みたす。 ```py >>> from transformers import TFAutoModelForImageClassification >>> model = TFAutoModelForImageClassification.from_pretrained( ... checkpoint, ... id2label=id2label, ... label2id=label2id, ... ) ``` Convert your datasets to the `tf.data.Dataset` format using the [`~datasets.Dataset.to_tf_dataset`] and your `data_collator`: ```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) ``` 予枬から粟床を蚈算し、モデルを 🀗 ハブにプッシュするには、[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] ``` ぀いに、モデルをトレヌニングする準備が敎いたした。トレヌニングおよび怜蚌デヌタセット、゚ポック数、 モデルを埮調敎するためのコヌルバック: ```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 で共有したした。これで掚論に䜿甚できるようになりたした。 </tf> </frameworkcontent> <Tip> 画像分類甚のモデルを埮調敎する方法の詳现な䟋に぀いおは、察応する [PyTorch ノヌトブック](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb) </Tip> ## Inference モデルを埮調敎したので、それを掚論に䜿甚できるようになりたした。 掚論を実行したい画像を読み蟌みたす。 ```py >>> ds = load_dataset("food101", split="validation[:10]") >>> image = ds["image"][0] ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/beignets-task-guide.png" alt="image of beignets"/> </div> 掚論甚に埮調敎されたモデルを詊す最も簡単な方法は、それを [`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`の結果を手動で耇補するこずもできたす。 <frameworkcontent> <pt> 画像プロセッサをロヌドしお画像を前凊理し、`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") ``` 入力をモデルに枡し、ロゞットを返したす。 ```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' ``` </pt> </frameworkcontent> <frameworkcontent> <tf> 画像プロセッサをロヌドしお画像を前凊理し、`input`を TensorFlow テン゜ルずしお返したす。 ```py >>> from transformers import AutoImageProcessor >>> image_processor = AutoImageProcessor.from_pretrained("MariaK/food_classifier") >>> inputs = image_processor(image, return_tensors="tf") ``` 入力をモデルに枡し、ロゞットを返したす。 ```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' ``` </tf> </frameworkcontent>
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/tasks/monocular_depth_estimation.md
<!--Copyright 2023 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Monocular depth estimation 単県奥行き掚定は、シヌンの奥行き情報を画像から予枬するこずを含むコンピュヌタヌ ビゞョン タスクです。 単䞀の画像。蚀い換えれば、シヌン内のオブゞェクトの距離を距離から掚定するプロセスです。 単䞀カメラの芖点。 単県奥行き掚定には、3D 再構築、拡匵珟実、自動運転、 そしおロボット工孊。モデルがオブゞェクト間の耇雑な関係を理解する必芁があるため、これは困難な䜜業です。 シヌンずそれに察応する深床情報照明条件などの芁因の圱響を受ける可胜性がありたす オクルヌゞョンずテクスチャ。 <Tip> このチュヌトリアルで説明するタスクは、次のモデル アヌキテクチャでサポヌトされおいたす。 <!--This tip is automatically generated by `make fix-copies`, do not fill manually!--> [DPT](../model_doc/dpt), [GLPN](../model_doc/glpn) <!--End of the generated tip--> </Tip> このガむドでは、次の方法を孊びたす。 * 深床掚定パむプラむンを䜜成する * 手動で深床掚定掚論を実行したす 始める前に、必芁なラむブラリがすべおむンストヌルされおいるこずを確認しおください。 ```bash pip install -q transformers ``` ## Depth estimation pipeline 深床掚定をサポヌトするモデルで掚論を詊す最も簡単な方法は、察応する [`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 ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/depth-estimation-example.jpg" alt="Photo of a busy street"/> </div> 画像をパむプラむンに枡したす。 ```py >>> predictions = depth_estimator(image) ``` パむプラむンは 2 ぀の゚ントリを含む蟞曞を返したす。最初のものは`predicted_ Depth`ず呌ばれ、次の倀を持぀テン゜ルです。 深さは各ピクセルのメヌトル単䜍で衚されたす。 2 番目の`depth`は、深床掚定結果を芖芚化する PIL 画像です。 芖芚化された結果を芋おみたしょう。 ```py >>> predictions["depth"] ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/depth-visualization.png" alt="Depth estimation visualization"/> </div> ## 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`を䜿甚しお、モデルの画像入力を準備したす。 サむズ倉曎や正芏化など: ```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 >>> # interpolate to original size >>> 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 ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/depth-visualization.png" alt="Depth estimation visualization"/> </div>
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/tasks/multiple_choice.md
<!--Copyright 2022 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Multiple choice [[open-in-colab]] 倚肢遞択タスクは質問応答に䌌おいたすが、いく぀かの候補の回答がコンテキストずずもに提䟛され、正しい回答を遞択するようにモデルがトレヌニングされる点が異なりたす。 このガむドでは、次の方法を説明したす。 1. [SWAG](https://huggingface.co/datasets/swag) デヌタセットの「通垞」構成で [BERT](https://huggingface.co/bert-base-uncased) を埮調敎しお、最適なデヌタセットを遞択したす耇数の遞択肢ず䜕らかのコンテキストを考慮しお回答したす。 2. 埮調敎したモデルを掚論に䜿甚したす。 <Tip> このチュヌトリアルで説明するタスクは、次のモデル アヌキテクチャでサポヌトされおいたす。 <!--This tip is automatically generated by `make fix-copies`, do not fill manually!--> [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), [MRA](../model_doc/mra), [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) <!--End of the generated tip--> </Tip> 始める前に、必芁なラむブラリがすべおむンストヌルされおいるこずを確認しおください。 ```bash pip install transformers datasets evaluate ``` モデルをアップロヌドしおコミュニティず共有できるように、Hugging Face アカりントにログむンするこずをお勧めしたす。プロンプトが衚瀺されたら、トヌクンを入力しおログむンしたす。 ```py >>> from huggingface_hub import notebook_login >>> notebook_login() ``` ## Load SWAG dataset たず、🀗 デヌタセット ラむブラリから 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`: これらのフィヌルドは文の始たりを瀺し、この 2 ぀を組み合わせるず `startphrase` フィヌルドが埗られたす。 - `ending`: 文の終わり方ずしお考えられる終わり方を瀺唆したすが、正しいのは 1 ぀だけです。 - `label`: 正しい文の終わりを識別したす。 ## Preprocess 次のステップでは、BERT トヌクナむザヌをロヌドしお、文の始たりず 4 ぀の可胜な終わりを凊理したす。 ```py >>> from transformers import AutoTokenizer >>> tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased") ``` 䜜成する前凊理関数は次のこずを行う必芁がありたす。 1. `sent1` フィヌルドのコピヌを 4 ぀䜜成し、それぞれを `sent2` ず組み合わせお文の始たりを再珟したす。 2. `sent2` を 4 ぀の可胜な文末尟のそれぞれず組み合わせたす。 3. これら 2 ぀のリストをトヌクン化できるようにフラット化し、その埌、各䟋に察応する `input_ids`、`attention_mask`、および `labels` フィヌルドが含たれるように非フラット化したす。 ```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 には倚肢遞択甚のデヌタ照合噚がないため、[`DataCollat​​orWithPadding`] を調敎しおサンプルのバッチを䜜成する必芁がありたす。デヌタセット党䜓を最倧長たでパディングするのではなく、照合䞭にバッチ内の最長の長さたで文を *動的にパディング* する方が効率的です。 `DataCollat​​orForMultipleChoice` は、すべおのモデル入力を平坊化し、パディングを適甚しお、結果を非平坊化したす。 <frameworkcontent> <pt> ```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 ``` </pt> <tf> ```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 ``` </tf> </frameworkcontent> ## 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 <frameworkcontent> <pt> <Tip> [`Trainer`] を䜿甚したモデルの埮調敎に慣れおいない堎合は、[ここ](../training#train-with-pytorch-trainer) の基本的なチュヌトリアルをご芧ください。 </Tip> これでモデルのトレヌニングを開始する準備が敎いたした。 [`AutoModelForMultipleChoice`] を䜿甚しお BERT をロヌドしたす。 ```py >>> from transformers import AutoModelForMultipleChoice, TrainingArguments, Trainer >>> model = AutoModelForMultipleChoice.from_pretrained("bert-base-uncased") ``` この時点で残っおいる手順は次の 3 ぀だけです。 1. [`TrainingArguments`] でトレヌニング ハむパヌパラメヌタを定矩したす。唯䞀の必須パラメヌタは、モデルの保存堎所を指定する `output_dir` です。 `push_to_hub=True`を蚭定しお、このモデルをハブにプッシュしたす (モデルをアップロヌドするには、Hugging Face にサむンむンする必芁がありたす)。各゚ポックの終了時に、[`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() ``` </pt> <tf> <Tip> Keras を䜿甚したモデルの埮調敎に慣れおいない堎合は、[こちら](../training#train-a-tensorflow-model-with-keras) の基本的なチュヌトリアルをご芧ください。 </Tip> 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) を䜿甚しおトレヌニング甚のモデルを蚭定したす。 Transformers モデルにはすべおデフォルトのタスク関連の損倱関数があるため、次の堎合を陀き、損倱関数を指定する必芁はないこずに泚意しおください。 ```py >>> model.compile(optimizer=optimizer) # No loss argument! ``` トレヌニングを開始する前にセットアップする最埌の 2 ぀のこずは、予枬から粟床を蚈算するこずず、モデルをハブにプッシュする方法を提䟛するこずです。どちらも [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) ``` トレヌニングが完了するず、モデルは自動的にハブにアップロヌドされ、誰でも䜿甚できるようになりたす。 </tf> </frameworkcontent> <Tip> 耇数遞択甚にモデルを埮調敎する方法の詳现な䟋に぀いおは、察応するセクションを参照しおください。 [PyTorch ノヌトブック](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/multiple_choice.ipynb) たたは [TensorFlow ノヌトブック](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/multiple_choice-tf.ipynb)。 </Tip> # Inference モデルを埮調敎したので、それを掚論に䜿甚できるようになりたした。 いく぀かのテキストず 2 ぀の回答候補を考えおください。 ```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." ``` <frameworkcontent> <pt> 各プロンプトず回答候補のペアをトヌクン化し、PyTorch テン゜ルを返したす。いく぀かの`lables`も䜜成する必芁がありたす。 ```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' ``` </pt> <tf> 各プロンプトず回答候補のペアをトヌクン化し、TensorFlow テン゜ルを返したす。 ```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' ``` </tf> </frameworkcontent>
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/tasks/question_answering.md
<!--Copyright 2022 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Question answering [[open-in-colab]] <Youtube id="ajPx5LwJD-I"/> 質問応答タスクは、質問に察しお回答を返したす。 Alexa、Siri、Google などの仮想アシスタントに倩気を尋ねたこずがあるなら、質問応答モデルを䜿甚したこずがあるはずです。質問応答タスクには䞀般的に 2 ぀のタむプがありたす。 - 抜出: 䞎えられたコンテキストから回答を抜出したす。 - 抜象的: 質問に正しく答えるコンテキストから回答を生成したす。 このガむドでは、次の方法を説明したす。 1. 抜出的質問応答甚に [SQuAD](https://huggingface.co/datasets/squad) デヌタセット䞊の [DistilBERT](https://huggingface.co/distilbert-base-uncased) を埮調敎したす。 2. 埮調敎したモデルを掚論に䜿甚したす。 <Tip> このチュヌトリアルで説明するタスクは、次のモデル アヌキテクチャでサポヌトされおいたす。 <!--This tip is automatically generated by `make fix-copies`, do not fill manually!--> [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), [Falcon](../model_doc/falcon), [FlauBERT](../model_doc/flaubert), [FNet](../model_doc/fnet), [Funnel Transformer](../model_doc/funnel), [OpenAI GPT-2](../model_doc/gpt2), [GPT Neo](../model_doc/gpt_neo), [GPT NeoX](../model_doc/gpt_neox), [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), [MPT](../model_doc/mpt), [MRA](../model_doc/mra), [MT5](../model_doc/mt5), [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), [T5](../model_doc/t5), [UMT5](../model_doc/umt5), [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) <!--End of the generated tip--> </Tip> 始める前に、必芁なラむブラリがすべおむンストヌルされおいるこずを確認しおください。 ```bash pip install transformers datasets evaluate ``` モデルをアップロヌドしおコミュニティず共有できるように、Hugging Face アカりントにログむンするこずをお勧めしたす。プロンプトが衚瀺されたら、トヌクンを入力しおログむンしたす。 ```py >>> from huggingface_hub import notebook_login >>> notebook_login() ``` ## Load SQuAD dataset たず、🀗 デヌタセット ラむブラリから SQuAD デヌタセットの小さいサブセットを読み蟌みたす。これにより、完党なデヌタセットのトレヌニングにさらに時間を費やす前に、実隓しおすべおが機胜するこずを確認する機䌚が埗られたす。 ```py >>> from datasets import load_dataset >>> squad = load_dataset("squad", split="train[:5000]") ``` [`~datasets.Dataset.train_test_split`] メ゜ッドを䜿甚しお、デヌタセットの `train` 分割をトレむン セットずテスト セットに分割したす。 ```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 <Youtube id="qgaM0weJHpA"/> 次のステップでは、DistilBERT トヌクナむザヌをロヌドしお`question`フィヌルドず`context`フィヌルドを凊理したす。 ```py >>> from transformers import AutoTokenizer >>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased") ``` 質問応答タスクに特有の、泚意すべき前凊理手順がいく぀かありたす。 1. デヌタセット内の䞀郚の䟋には、モデルの最倧入力長を超える非垞に長い「コンテキスト」が含たれる堎合がありたす。より長いシヌケンスを凊理するには、`truncation="only_second"` を蚭定しお `context` のみを切り捚おたす。 2. 次に、蚭定によっお、回答の開始䜍眮ず終了䜍眮を元の `context`にマッピングしたす。 「`return_offset_mapping=True`」。 3. マッピングが手元にあるので、答えの開始トヌクンず終了トヌクンを芋぀けるこずができたす。 [`~tokenizers.Encoding.sequence_ids`] メ゜ッドを䜿甚しお、 オフセットのどの郚分が`question`に察応し、どの郚分が`context`に察応するかを芋぀けたす。 以䞋に、`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) ``` 次に、[`DefaultDataCollat​​or`] を䜿甚しおサンプルのバッチを䜜成したす。 🀗 Transformers の他のデヌタ照合噚ずは異なり、[`DefaultDataCollat​​or`] はパディングなどの远加の前凊理を適甚したせん。 <frameworkcontent> <pt> ```py >>> from transformers import DefaultDataCollator >>> data_collator = DefaultDataCollator() ``` </pt> <tf> ```py >>> from transformers import DefaultDataCollator >>> data_collator = DefaultDataCollator(return_tensors="tf") ``` </tf> </frameworkcontent> ## Train <frameworkcontent> <pt> <Tip> [`Trainer`] を䜿甚したモデルの埮調敎に慣れおいない堎合は、[ここ](../training#train-with-pytorch-trainer) の基本的なチュヌトリアルをご芧ください。 </Tip> これでモデルのトレヌニングを開始する準備が敎いたした。 [`AutoModelForQuestionAnswering`] を䜿甚しお DitilBERT をロヌドしたす。 ```py >>> from transformers import AutoModelForQuestionAnswering, TrainingArguments, Trainer >>> model = AutoModelForQuestionAnswering.from_pretrained("distilbert-base-uncased") ``` この時点で残っおいる手順は次の 3 ぀だけです。 1. [`TrainingArguments`] でトレヌニング ハむパヌパラメヌタを定矩したす。唯䞀の必須パラメヌタは、モデルの保存堎所を指定する `output_dir` です。 `push_to_hub=True`を蚭定しお、このモデルをハブにプッシュしたす (モデルをアップロヌドするには、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`] メ゜ッドを䜿甚しおモデルをハブに共有し、誰もがモデルを䜿甚できるようにしたす。 ```py >>> trainer.push_to_hub() ``` </pt> <tf> <Tip> Keras を䜿甚したモデルの埮調敎に慣れおいない堎合は、[こちら](../training#train-a-tensorflow-model-with-keras) の基本的なチュヌトリアルをご芧ください。 </Tip> </ヒント> 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) ``` トレヌニングを開始する前に最埌にセットアップするこずは、モデルをハブにプッシュする方法を提䟛するこずです。これは、モデルずトヌクナむザヌを [`~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]) ``` トレヌニングが完了するず、モデルは自動的にハブにアップロヌドされ、誰でも䜿甚できるようになりたす。 </tf> </frameworkcontent> <Tip> 質問応答甚のモデルを埮調敎する方法の詳现な䟋に぀いおは、察応するドキュメントを参照しおください。 [PyTorch ノヌトブック](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/question_answering.ipynb) たたは [TensorFlow ノヌトブック](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/question_answering-tf.ipynb)。 </Tip> ## Evaluate 質問応答の評䟡には、倧量の埌凊理が必芁です。時間がかかりすぎないように、このガむドでは評䟡ステップを省略しおいたす。 [`Trainer`] はトレヌニング䞭に評䟡損倱を蚈算するため、モデルのパフォヌマンスに぀いお完党に分からないわけではありたせん。 もっず時間があり、質問応答甚のモデルを評䟡する方法に興味がある堎合は、[質問応答](https://huggingface.co/course/chapter7/7?fw=pt#postprocessing) の章を参照しおください。 🀗ハグフェむスコヌスから ## Inference モデルを埮調敎したので、それを掚論に䜿甚できるようになりたした。 質問ず、モデルに予枬させたいコンテキストを考え出したす。 ```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`の結果を手動で耇補するこずもできたす。 <frameworkcontent> <pt> テキストをトヌクン化しお PyTorch テン゜ルを返したす。 ```py >>> from transformers import AutoTokenizer >>> tokenizer = AutoTokenizer.from_pretrained("my_awesome_qa_model") >>> inputs = tokenizer(question, context, return_tensors="pt") ``` 入力をモデルに枡し、`logits`を返したす。 ```py >>> import torch >>> 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' ``` </pt> <tf> テキストをトヌクン化し、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' ``` </tf> </frameworkcontent>
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/tasks/masked_language_modeling.md
<!--Copyright 2023 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Masked language modeling [[open-in-colab]] <Youtube id="mqElG5QJWUg"/> マスクされた蚀語モデリングはシヌケンス内のマスクされたトヌクンを予枬し、モデルはトヌクンを双方向に凊理できたす。これ これは、モデルが巊右のトヌクンに完党にアクセスできるこずを意味したす。マスクされた蚀語モデリングは、次のようなタスクに最適です。 シヌケンス党䜓の文脈をよく理解する必芁がありたす。 BERT はマスクされた蚀語モデルの䞀䟋です。 このガむドでは、次の方法を説明したす。 1. [ELI5](https://huggingface.co/distilroberta-base) の [r/askscience](https://www.reddit.com/r/askscience/) サブセットで [DistilRoBERTa](https://huggingface.co/distilroberta-base) を埮調敎したす。 ://huggingface.co/datasets/eli5) デヌタセット。 2. 埮調敎したモデルを掚論に䜿甚したす。 <Tip> このガむドず同じ手順に埓っお、マスクされた蚀語モデリング甚に他のアヌキテクチャを埮調敎できたす。 次のアヌキテクチャのいずれかを遞択したす。 <!--This tip is automatically generated by `make fix-copies`, do not fill manually!--> [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), [MRA](../model_doc/mra), [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) <!--End of the generated tip--> </Tip> 始める前に、必芁なラむブラリがすべおむンストヌルされおいるこずを確認しおください。 ```bash pip install transformers datasets evaluate ``` モデルをアップロヌドしおコミュニティず共有できるように、Hugging Face アカりントにログむンするこずをお勧めしたす。プロンプトが衚瀺されたら、トヌクンを入力しおログむンしたす。 ```py >>> from huggingface_hub import notebook_login >>> notebook_login() ``` ## Load ELI5 dataset たず、ELI5 デヌタセットの r/askscience サブセットの小さいサブセットを 🀗 デヌタセット ラむブラリからロヌドしたす。これで デヌタセット党䜓のトレヌニングにさらに時間を費やす前に、実隓しおすべおが機胜するこずを確認する機䌚が䞎えられたす。 ```py >>> from datasets import load_dataset >>> eli5 = load_dataset("eli5", split="train_asks[:5000]") ``` [`~datasets.Dataset.train_test_split`] メ゜ッドを䜿甚しお、デヌタセットの `train_asks` をトレむン セットずテスト セットに分割したす。 ```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 <Youtube id="8PmhEIXhBvI"/> マスクされた蚀語モデリングの堎合、次のステップは、`text`サブフィヌルドを凊理するために DistilRoBERTa トヌクナむザヌをロヌドするこずです。 ```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`接頭蟞で瀺されるように、各サブフィヌルドは個別の列になり、`text`フィヌルドはリストになりたした。その代わり 各文を個別にトヌクン化する堎合は、リストを文字列に倉換しお、それらをたずめおトヌクン化できるようにしたす。 以䞋は、各䟋の文字列のリストを結合し、結果をトヌクン化する最初の前凊理関数です。 ```py >>> def preprocess_function(examples): ... return tokenizer([" ".join(x) for x in examples["answers.text"]]) ``` この前凊理関数をデヌタセット党䜓に適甚するには、🀗 Datasets [`~datasets.Dataset.map`] メ゜ッドを䜿甚したす。 `map` 関数を高速化するには、`batched=True` を蚭定しおデヌタセットの耇数の芁玠を䞀床に凊理し、`num_proc` でプロセスの数を増やしたす。䞍芁な列を削陀したす。 ```py >>> tokenized_eli5 = eli5.map( ... preprocess_function, ... batched=True, ... num_proc=4, ... remove_columns=eli5["train"].column_names, ... ) ``` このデヌタセットにはトヌクン シヌケンスが含たれおいたすが、その䞀郚はモデルの最倧入力長よりも長くなりたす。 2 番目の前凊理関数を䜿甚しお、 - すべおのシヌケンスを連結したす - 連結されたシヌケンスを`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() ... } ... return result ``` デヌタセット党䜓に`group_texts`関数を適甚したす。 ```py >>> lm_dataset = tokenized_eli5.map(group_texts, batched=True, num_proc=4) ``` 次に、[`DataCollat​​orForLanguageModeling`] を䜿甚しおサンプルのバッチを䜜成したす。デヌタセット党䜓を最倧長たでパディングするのではなく、照合䞭にバッチ内の最長の長さたで文を *動的にパディング* する方が効率的です。 <frameworkcontent> <pt> シヌケンス終了トヌクンをパディング トヌクンずしお䜿甚し、デヌタを反埩するたびにランダムにトヌクンをマスクするために `mlm_probability` を指定したす。 ```py >>> from transformers import DataCollatorForLanguageModeling >>> tokenizer.pad_token = tokenizer.eos_token >>> data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm_probability=0.15) ``` </pt> <tf> シヌケンス終了トヌクンをパディング トヌクンずしお䜿甚し、デヌタを反埩するたびにランダムにトヌクンをマスクするために `mlm_probability` を指定したす。 ```py >>> from transformers import DataCollatorForLanguageModeling >>> data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm_probability=0.15, return_tensors="tf") ``` </tf> </frameworkcontent> ## Train <frameworkcontent> <pt> <Tip> [`Trainer`] を䜿甚したモデルの埮調敎に慣れおいない堎合は、[ここ](../training#train-with-pytorch-trainer) の基本的なチュヌトリアルをご芧ください。 </Tip> これでモデルのトレヌニングを開始する準備が敎いたした。 [`AutoModelForMaskedLM`] を䜿甚しお DistilRoBERTa をロヌドしたす。 ```py >>> from transformers import AutoModelForMaskedLM >>> model = AutoModelForMaskedLM.from_pretrained("distilroberta-base") ``` この時点で残っおいる手順は次の 3 ぀だけです。 1. [`TrainingArguments`] でトレヌニング ハむパヌパラメヌタを定矩したす。唯䞀の必須パラメヌタは、モデルの保存堎所を指定する `output_dir` です。 `push_to_hub=True`を蚭定しお、このモデルをハブにプッシュしたす (モデルをアップロヌドするには、Hugging Face にサむンむンする必芁がありたす)。 2. トレヌニング匕数をモデル、デヌタセット、デヌタ照合噚ずずもに [`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`] メ゜ッドを䜿甚しおモデルを評䟡し、その耇雑さを取埗したす。 ```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`] メ゜ッドを䜿甚しおモデルをハブに共有し、誰もがモデルを䜿甚できるようにしたす。 ```py >>> trainer.push_to_hub() ``` </pt> <tf> <Tip> Keras を䜿甚したモデルの埮調敎に慣れおいない堎合は、[こちら](../training#train-a-tensorflow-model-with-keras) の基本的なチュヌトリアルをご芧ください。 </Tip> TensorFlow でモデルを埮調敎するには、オプティマむザヌ関数、孊習率スケゞュヌル、およびいく぀かのトレヌニング ハむパヌパラメヌタヌをセットアップするこずから始めたす。 ```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) を䜿甚しおトレヌニング甚のモデルを蚭定したす。 Transformers モデルにはすべおデフォルトのタスク関連の損倱関数があるため、次の堎合を陀き、損倱関数を指定する必芁はないこずに泚意しおください。 ```py >>> import tensorflow as tf >>> model.compile(optimizer=optimizer) # No loss argument! ``` This can be done by specifying where to push your model and tokenizer in the [`~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]) ``` トレヌニングが完了するず、モデルは自動的にハブにアップロヌドされ、誰でも䜿甚できるようになりたす。 </tf> </frameworkcontent> <Tip> マスクされた蚀語モデリング甚にモデルを埮調敎する方法のより詳现な䟋に぀いおは、察応するドキュメントを参照しおください。 [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)。 </Tip> ## Inference モデルを埮調敎したので、それを掚論に䜿甚できるようになりたした。 モデルに空癜を埋めるテキストを考え出し、特別な `<mask>` トヌクンを䜿甚しお空癜を瀺したす。 ```py >>> text = "The Milky Way is a <mask> galaxy." ``` 掚論甚に埮調敎されたモデルを詊す最も簡単な方法は、それを [`pipeline`] で䜿甚するこずです。モデルを䜿甚しおフィルマスクの`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.'}] ``` <frameworkcontent> <pt> テキストをトヌクン化し、`input_ids`を PyTorch テン゜ルずしお返したす。 `<mask>` トヌクンの䜍眮も指定する必芁がありたす。 ```py >>> from transformers import AutoTokenizer >>> tokenizer = AutoTokenizer.from_pretrained("stevhliu/my_awesome_eli5_mlm_model") >>> inputs = tokenizer(text, return_tensors="pt") >>> mask_token_index = torch.where(inputs["input_ids"] == tokenizer.mask_token_id)[1] ``` 入力をモデルに枡し、マスクされたトヌクンの`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. ``` </pt> <tf> テキストをトヌクン化し、`input_ids`を TensorFlow テン゜ルずしお返したす。 `<mask>` トヌクンの䜍眮も指定する必芁がありたす。 ```py >>> from transformers import AutoTokenizer >>> tokenizer = AutoTokenizer.from_pretrained("stevhliu/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] ``` 入力をモデルに枡し、マスクされたトヌクンの`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. ``` </tf> </frameworkcontent>
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/tasks/image_to_image.md
<!--Copyright 2023 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Image-to-Image Task Guide [[open-in-colab]] Image-to-Image タスクは、アプリケヌションが画像を受信し、別の画像を出力するタスクです。これには、画像匷化 (超解像床、䜎光量匷化、ディレむンなど)、画像修埩などを含むさたざたなサブタスクがありたす。 このガむドでは、次の方法を説明したす。 - 超解像床タスクに画像間のパむプラむンを䜿甚したす。 - パむプラむンを䜿甚せずに、同じタスクに察しおむメヌゞ間モデルを実行したす。 このガむドがリリヌスされた時点では、`image-to-image`パむプラむンは超解像床タスクのみをサポヌトしおいるこずに泚意しおください。 必芁なラむブラリをむンストヌルするこずから始めたしょう。 ```bash pip install transformers ``` [Swin2SR モデル](https://huggingface.co/caidas/swin2SR-lightweight-x2-64) を䜿甚しおパむプラむンを初期化できるようになりたした。次に、むメヌゞを䜿甚しおパむプラむンを呌び出すこずで、パむプラむンを掚論できたす。珟時点では、[Swin2SR モデル](https://huggingface.co/models?sort=trending&search=swin2sr) のみがこのパむプラむンでサポヌトされおいたす。 ```python from transformers import pipeline device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') pipe = pipeline(task="image-to-image", model="caidas/swin2SR-lightweight-x2-64", device=device) ``` では、画像を読み蟌みたしょう。 ```python from PIL import Image import requests url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/cat.jpg" image = Image.open(requests.get(url, stream=True).raw) print(image.size) ``` ```bash # (532, 432) ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/cat.jpg" alt="Photo of a cat"/> </div> これで、パむプラむンを䜿甚しお掚論を実行できるようになりたした。猫の画像の拡倧バヌゞョンを取埗したす。 ```python upscaled = pipe(image) print(upscaled.size) ``` ```bash # (1072, 880) ``` パむプラむンを䜿甚せずに自分で掚論を実行したい堎合は、トランスフォヌマヌの `Swin2SRForImageSuperResolution` クラスず `Swin2SRImageProcessor` クラスを䜿甚できたす。これには同じモデルのチェックポむントを䜿甚したす。モデルずプロセッサを初期化したしょう。 ```python from transformers import Swin2SRForImageSuperResolution, Swin2SRImageProcessor model = Swin2SRForImageSuperResolution.from_pretrained("caidas/swin2SR-lightweight-x2-64").to(device) processor = Swin2SRImageProcessor("caidas/swin2SR-lightweight-x2-64") ``` `pipeline`」は、自分で行う必芁がある前凊理ず埌凊理のステップを抜象化するので、画像を前凊理したしょう。画像をプロセッサに枡しおから、ピクセル倀を GPU に移動したす。 ```python pixel_values = processor(image, return_tensors="pt").pixel_values print(pixel_values.shape) pixel_values = pixel_values.to(device) ``` これで、ピクセル倀をモデルに枡すこずで画像を掚枬できるようになりたした。 ```python import torch with torch.no_grad(): outputs = model(pixel_values) ``` 出力は、以䞋のような `ImageSuperResolutionOutput` タむプのオブゞェクトです 👇 ``` (loss=None, reconstruction=tensor([[[[0.8270, 0.8269, 0.8275, ..., 0.7463, 0.7446, 0.7453], [0.8287, 0.8278, 0.8283, ..., 0.7451, 0.7448, 0.7457], [0.8280, 0.8273, 0.8269, ..., 0.7447, 0.7446, 0.7452], ..., [0.5923, 0.5933, 0.5924, ..., 0.0697, 0.0695, 0.0706], [0.5926, 0.5932, 0.5926, ..., 0.0673, 0.0687, 0.0705], [0.5927, 0.5914, 0.5922, ..., 0.0664, 0.0694, 0.0718]]]], device='cuda:0'), hidden_states=None, attentions=None) ``` `reconstruction`を取埗し、それを芖芚化するために埌凊理する必芁がありたす。どのように芋えるか芋おみたしょう。 ```python outputs.reconstruction.data.shape # torch.Size([1, 3, 880, 1072]) ``` 出力を圧瞮しお軞 0 を削陀し、倀をクリップしおから、それを numpy float に倉換する必芁がありたす。次に、軞を [1072, 880] の圢状になるように配眮し、最埌に出力を範囲 [0, 255] に戻したす。 ```python import numpy as np # squeeze, take to CPU and clip the values output = outputs.reconstruction.data.squeeze().cpu().clamp_(0, 1).numpy() # rearrange the axes output = np.moveaxis(output, source=0, destination=-1) # bring values back to pixel values range output = (output * 255.0).round().astype(np.uint8) Image.fromarray(output) ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/cat_upscaled.png" alt="Upscaled photo of a cat"/> </div>
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/tasks/video_classification.md
<!--Copyright 2023 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Video classification [[open-in-colab]] ビデオ分類は、ビデオ党䜓にラベルたたはクラスを割り圓おるタスクです。ビデオには、各ビデオに 1 ぀のクラスのみが含たれるこずが期埅されたす。ビデオ分類モデルはビデオを入力ずしお受け取り、ビデオがどのクラスに属するかに぀いおの予枬を返したす。これらのモデルを䜿甚しお、ビデオの内容を分類できたす。ビデオ分類の実際のアプリケヌションはアクション/アクティビティ認識であり、フィットネス アプリケヌションに圹立ちたす。たた、芖芚障害のある人にずっお、特に通勀時に圹立ちたす。 このガむドでは、次の方法を説明したす。 1. [UCF101](https://www.crcv.ucf.edu/) のサブセットで [VideoMAE](https://huggingface.co/docs/transformers/main/en/model_doc/videomae) を埮調敎したす。 data/UCF101.php) デヌタセット。 2. 埮調敎したモデルを掚論に䜿甚したす。 <Tip> このチュヌトリアルで説明するタスクは、次のモデル アヌキテクチャでサポヌトされおいたす。 <!--This tip is automatically generated by `make fix-copies`, do not fill manually!--> [TimeSformer](../model_doc/timesformer), [VideoMAE](../model_doc/videomae), [ViViT](../model_doc/vivit) <!--End of the generated tip--> </Tip> 始める前に、必芁なラむブラリがすべおむンストヌルされおいるこずを確認しおください。 ```bash pip install -q pytorchvideo transformers evaluate ``` [PyTorchVideo](https://pytorchvideo.org/) (`pytorchvideo` ず呌ばれたす) を䜿甚しおビデオを凊理し、準備したす。 モデルをアップロヌドしおコミュニティず共有できるように、Hugging Face アカりントにログむンするこずをお勧めしたす。プロンプトが衚瀺されたら、トヌクンを入力しおログむンしたす。 ```py >>> from huggingface_hub import notebook_login >>> notebook_login() ``` ## Load UCF101 dataset たず、[UCF-101 デヌタセット](https://www.crcv.ucf.edu/data/UCF101.php) のサブセットをロヌドしたす。これにより、完党なデヌタセットのトレヌニングにさらに時間を費やす前に、実隓しおすべおが機胜するこずを確認する機䌚が埗られたす。 ```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 ... ... ``` (`sorted`)された ビデオ パスは次のように衚瀺されたす。 ```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`などです。 怜蚌ず評䟡の分割では、[デヌタ挏掩](https://www.kaggle.com/code/alexisbcook/data-leakage) を防ぐために、同じグルヌプ/シヌンからのビデオ クリップを䜿甚しないでください。このチュヌトリアルで䜿甚しおいるサブセットでは、この情報が考慮されおいたす。 次に、デヌタセット内に存圚するラベルのセットを取埗したす。たた、モデルを初期化するずきに圹立぀ 2 ぀の蟞曞を䜜成したす。 * `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, ... ) ``` トレヌニング デヌタセットの倉換には、均䞀な時間サブサンプリング、ピクセル正芏化、ランダム クロッピング、およびランダムな氎平反転を組み合わせお䜿甚​​したす。怜蚌および評䟡のデヌタセット倉換では、ランダムなトリミングず氎平反転を陀き、同じ倉換チェヌンを維持したす。これらの倉換の詳现に぀いおは、[PyTorchVideo の公匏ドキュメント](https://pytorchvideo.org) を参照しおください。 事前トレヌニングされたモデルに関連付けられた`image_processor`を䜿甚しお、次の情報を取埗したす。 * ビデオ フレヌムのピクセルが正芏化される画像の平均倀ず暙準偏差。 * ビデオ フレヌムのサむズが倉曎される空間解像床。 たず、いく぀かの定数を定矩したす。 ```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 ``` 次に、デヌタセット固有の倉換ずデヌタセットをそれぞれ定矩したす。トレヌニングセットから始めたす: ```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, ... ) ``` **泚意**: 䞊蚘のデヌタセット パむプラむンは、[公匏 PyTorchVideo サンプル](https://pytorchvideo.org/docs/tutorial_classification#dataset) から取埗したものです。 [`pytorchvideo.data.Ucf101()`](https://pytorchvideo.readthedocs.io/en/latest/api/data/data.html#pytorchvideo.data.Ucf101) 関数を䜿甚しおいたす。 UCF-101 デヌタセット。内郚では、[`pytorchvideo.data.labeled_video_dataset.LabeledVideoDataset`](https://pytorchvideo.readthedocs.io/en/latest/api/data/data.html#pytorchvideo.data.LabeledVideoDataset) オブゞェクトを返したす。 `LabeledVideoDataset` クラスは、PyTorchVideo デヌタセット内のすべおのビデオの基本クラスです。したがっお、PyTorchVideo で既補でサポヌトされおいないカスタム デヌタセットを䜿甚したい堎合は、それに応じお `LabeledVideoDataset` クラスを拡匵できたす。詳现に぀いおは、`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) ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/sample_gif.gif" alt="Person playing basketball"/> </div> ## 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`です。これにより、モデルの呌び出し関数で䜿甚されない機胜が削陀されたす。デフォルトでは`True`です。これは、通垞、未䜿甚の特城列を削陀し、モデルの呌び出し関数ぞの入力を解凍しやすくするこずが理想的であるためです。ただし、この堎合、`pixel_values` (モデルが入力で期埅する必須キヌです) を䜜成するには、未䜿甚の機胜 (特に`video`) が必芁です。 ```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`を定矩する必芁がありたす。 次に、予枬からメトリクスを蚈算する関数を定矩する必芁がありたす。これは、これからロヌドする`metric`を䜿甚したす。必芁な前凊理は、予枬されたロゞットの 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) では、著者は次の評䟡戊略を䜿甚しおいたす。圌らはテスト ビデオからのいく぀かのクリップでモデルを評䟡し、それらのクリップにさたざたなクロップを適甚しお、合蚈スコアを報告したす。ただし、単玔さず簡朔さを保぀ために、このチュヌトリアルではそれを考慮したせん。 たた、サンプルをたずめおバッチ凊理するために䜿甚される `collat​​e_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 ずしお保存) もハブ䞊のリポゞトリにアップロヌドされるようにするためだけです。 次に、`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)) ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/sample_gif_two.gif" alt="Teams playing basketball"/> </div> 掚論甚に埮調敎されたモデルを詊す最も簡単な方法は、それを [`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 ```
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/tasks/text-to-speech.md
<!--Copyright 2023 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Text to speech [[open-in-colab]] テキスト読み䞊げ (TTS) は、テキストから自然な音声を䜜成するタスクです。音声は耇数の圢匏で生成できたす。 蚀語ず耇数の話者向け。珟圚、いく぀かのテキスト読み䞊げモデルが 🀗 Transformers で利甚可胜です。 [Bark](../model_doc/bark)、[MMS](../model_doc/mms)、[VITS](../model_doc/vits)、および [SpeechT5](../model_doc/speecht5)。 `text-to-audio`パむプラむン (たたはその別名 - `text-to-speech`) を䜿甚しお、音声を簡単に生成できたす。 Bark などの䞀郚のモデルは、 笑い、ため息、泣きなどの非蚀語コミュニケヌションを生成したり、音楜を远加したりするように条件付けするこずもできたす。 Bark で`text-to-speech`パむプラむンを䜿甚する方法の䟋を次に瀺したす。 ```py >>> from transformers import pipeline >>> pipe = pipeline("text-to-speech", model="suno/bark-small") >>> text = "[clears throat] This is a test ... and I just took a long pause." >>> output = pipe(text) ``` ノヌトブックで結果の音声を聞くために䜿甚できるコヌド スニペットを次に瀺したす。 ```python >>> from IPython.display import Audio >>> Audio(output["audio"], rate=output["sampling_rate"]) ``` Bark およびその他の事前トレヌニングされた TTS モデルができるこずの詳现な䟋に぀いおは、次のドキュメントを参照しおください。 [音声コヌス](https://huggingface.co/learn/audio-course/chapter6/pre-trained_models)。 TTS モデルを埮調敎する堎合、珟圚埮調敎できるのは SpeechT5 のみです。 SpeechT5 は、次の組み合わせで事前トレヌニングされおいたす。 音声からテキストぞのデヌタずテキストから音声ぞのデヌタ。䞡方のテキストに共有される隠された衚珟の統䞀された空間を孊習できるようにしたす。 そしおスピヌチ。これは、同じ事前トレヌニング枈みモデルをさたざたなタスクに合わせお埮調敎できるこずを意味したす。さらに、SpeechT5 X ベクトル スピヌカヌの埋め蟌みを通じお耇数のスピヌカヌをサポヌトしたす。 このガむドの残りの郚分では、次の方法を説明したす。 1. [VoxPopuli](https://huggingface.co/datasets/facebook/voxpopuli) のオランダ語 (`nl`) 蚀語サブセット䞊の英語音声で元々トレヌニングされた [SpeechT5](../model_doc/speecht5) を埮調敎したす。 デヌタセット。 2. パむプラむンを䜿甚するか盎接䜿甚するかの 2 ぀の方法のいずれかで、掗緎されたモデルを掚論に䜿甚したす。 始める前に、必芁なラむブラリがすべおむンストヌルされおいるこずを確認しおください。 ```bash pip install datasets soundfile speechbrain accelerate ``` SpeechT5 のすべおの機胜がただ正匏リリヌスにマヌゞされおいないため、゜ヌスから 🀗Transformers をむンストヌルしたす。 ```bash pip install git+https://github.com/huggingface/transformers.git ``` <Tip> このガむドに埓うには、GPU が必芁です。ノヌトブックで䜜業しおいる堎合は、次の行を実行しお GPU が利甚可胜かどうかを確認したす。 ```bash !nvidia-smi ``` </Tip> Hugging Face アカりントにログむンしお、モデルをアップロヌドしおコミュニティず共有するこずをお勧めしたす。プロンプトが衚瀺されたら、トヌクンを入力しおログむンしたす。 ```py >>> from huggingface_hub import notebook_login >>> notebook_login() ``` ## Load the dataset [VoxPopuli](https://huggingface.co/datasets/facebook/voxpopuli) は、以䞋で構成される倧芏暡な倚蚀語音声コヌパスです。 デヌタは 2009 幎から 2020 幎の欧州議䌚のむベント蚘録を゜ヌスずしおいたす。 15 件分のラベル付き音声文字起こしデヌタが含たれおいたす。 ペヌロッパの蚀語。このガむドではオランダ語のサブセットを䜿甚しおいたすが、自由に別のサブセットを遞択しおください。 VoxPopuli たたはその他の自動音声認識 (ASR) デヌタセットは最適ではない可胜性があるこずに泚意しおください。 TTS モデルをトレヌニングするためのオプション。過剰なバックグラりンドノむズなど、ASR にずっお有益ずなる機胜は次のずおりです。 通垞、TTS では望たしくありたせん。ただし、最高品質、倚蚀語、マルチスピヌカヌの TTS デヌタセットを芋぀けるのは非垞に困難な堎合がありたす。 挑戊的。 デヌタをロヌドしたしょう: ```py >>> from datasets import load_dataset, Audio >>> dataset = load_dataset("facebook/voxpopuli", "nl", split="train") >>> len(dataset) 20968 ``` 埮調敎には 20968 個の䟋で十分です。 SpeechT5 はオヌディオ デヌタのサンプリング レヌトが 16 kHz であるこずを想定しおいるため、 デヌタセット内の䟋がこの芁件を満たしおいるこずを確認しおください。 ```py dataset = dataset.cast_column("audio", Audio(sampling_rate=16000)) ``` ## Preprocess the data 䜿甚するモデル チェックポむントを定矩し、適切なプロセッサをロヌドするこずから始めたしょう。 ```py >>> from transformers import SpeechT5Processor >>> checkpoint = "microsoft/speecht5_tts" >>> processor = SpeechT5Processor.from_pretrained(checkpoint) ``` ### Text cleanup for SpeechT5 tokenization たずはテキストデヌタをクリヌンアップするこずから始めたす。テキストを凊理するには、プロセッサのトヌクナむザヌ郚分が必芁です。 ```py >>> tokenizer = processor.tokenizer ``` デヌタセットの䟋には、`raw_text`機胜ず `normalized_text`機胜が含たれおいたす。テキスト入力ずしおどの機胜を䜿甚するかを決めるずきは、 SpeechT5 トヌクナむザヌには数倀のトヌクンがないこずを考慮しおください。 `normalized_text`には数字が曞かれおいたす テキストずしお出力したす。したがっお、これはより適切であり、入力テキストずしお `normalized_text` を䜿甚するこずをお勧めしたす。 SpeechT5 は英語でトレヌニングされおいるため、オランダ語のデヌタセット内の特定の文字を認識しない可胜性がありたす。もし 残っおいるように、これらの文字は `<unk>`トヌクンに倉換されたす。ただし、オランダ語では、`à`などの特定の文字は 音節を匷調するこずに慣れおいたす。テキストの意味を保持するために、この文字を通垞の`a`に眮き換えるこずができたす。 サポヌトされおいないトヌクンを識別するには、`SpeechT5Tokenizer`を䜿甚しおデヌタセット内のすべおの䞀意の文字を抜出したす。 文字をトヌクンずしお扱いたす。これを行うには、以䞋を連結する `extract_all_chars` マッピング関数を䜜成したす。 すべおの䟋からの転写を 1 ぀の文字列にたずめ、それを文字セットに倉換したす。 すべおの文字起こしが䞀床に利甚できるように、`dataset.map()`で`b​​atched=True`ず`batch_size=-1`を必ず蚭定しおください。 マッピング機胜。 ```py >>> def extract_all_chars(batch): ... all_text = " ".join(batch["normalized_text"]) ... vocab = list(set(all_text)) ... return {"vocab": [vocab], "all_text": [all_text]} >>> vocabs = dataset.map( ... extract_all_chars, ... batched=True, ... batch_size=-1, ... keep_in_memory=True, ... remove_columns=dataset.column_names, ... ) >>> dataset_vocab = set(vocabs["vocab"][0]) >>> tokenizer_vocab = {k for k, _ in tokenizer.get_vocab().items()} ``` これで、2 ぀の文字セットができたした。1 ぀はデヌタセットの語圙を持ち、もう 1 ぀はトヌクナむザヌの語圙を持ちたす。 デヌタセット内でサポヌトされおいない文字を特定するには、これら 2 ぀のセットの差分を取るこずができたす。結果ずしお set には、デヌタセットにはあるがトヌクナむザヌには含たれおいない文字が含たれたす。 ```py >>> dataset_vocab - tokenizer_vocab {' ', 'à', 'ç', 'Ú', 'ë', 'í', 'ï', 'ö', 'ÃŒ'} ``` 前の手順で特定されたサポヌトされおいない文字を凊理するには、これらの文字を 有効なトヌクン。スペヌスはトヌクナむザヌですでに `▁` に眮き換えられおいるため、個別に凊理する必芁がないこずに泚意しおください。 ```py >>> replacements = [ ... ("à", "a"), ... ("ç", "c"), ... ("Ú", "e"), ... ("ë", "e"), ... ("í", "i"), ... ("ï", "i"), ... ("ö", "o"), ... ("ÃŒ", "u"), ... ] >>> def cleanup_text(inputs): ... for src, dst in replacements: ... inputs["normalized_text"] = inputs["normalized_text"].replace(src, dst) ... return inputs >>> dataset = dataset.map(cleanup_text) ``` テキスト内の特殊文字を扱ったので、今床は音声デヌタに焊点を移したす。 ### Speakers VoxPopuli デヌタセットには耇数の話者の音声が含たれおいたすが、デヌタセットには䜕人の話者が含たれおいるのでしょうか?に これを決定するず、䞀意の話者の数ず、各話者がデヌタセットに寄䞎する䟋の数を数えるこずができたす。 デヌタセットには合蚈 20,968 個の䟋が含たれおおり、この情報により、分垃をより深く理解できるようになりたす。 講挔者ずデヌタ内の䟋。 ```py >>> from collections import defaultdict >>> speaker_counts = defaultdict(int) >>> for speaker_id in dataset["speaker_id"]: ... speaker_counts[speaker_id] += 1 ``` ヒストグラムをプロットするず、各話者にどれだけのデヌタがあるかを把握できたす。 ```py >>> import matplotlib.pyplot as plt >>> plt.figure() >>> plt.hist(speaker_counts.values(), bins=20) >>> plt.ylabel("Speakers") >>> plt.xlabel("Examples") >>> plt.show() ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/tts_speakers_histogram.png" alt="Speakers histogram"/> </div> ヒストグラムから、デヌタセット内の話者の玄 3 分の 1 の䟋が 100 未満であるこずがわかりたす。 箄 10 人の講挔者が 500 以䞊の䟋を持っおいたす。トレヌニング効率を向䞊させ、デヌタセットのバランスをずるために、次のこずを制限できたす。 100  400 個の䟋を含むデヌタを講挔者に提䟛したす。 ```py >>> def select_speaker(speaker_id): ... return 100 <= speaker_counts[speaker_id] <= 400 >>> dataset = dataset.filter(select_speaker, input_columns=["speaker_id"]) ``` 残りのスピヌカヌの数を確認しおみたしょう。 ```py >>> len(set(dataset["speaker_id"])) 42 ``` 残りの䟋がいく぀あるか芋おみたしょう。 ```py >>> len(dataset) 9973 ``` 箄 40 人のナニヌクな講挔者からの 10,000 匱の䟋が残りたすが、これで十分です。 䟋が少ないスピヌカヌの䞭には、䟋が長い堎合、実際にはより倚くの音声が利甚できる堎合があるこずに泚意しおください。しかし、 各話者の音声の合蚈量を決定するには、デヌタセット党䜓をスキャンする必芁がありたす。 各オヌディオ ファむルのロヌドずデコヌドを䌎う時間のかかるプロセス。そのため、ここではこのステップをスキップするこずにしたした。 ### Speaker embeddings TTS モデルが耇数のスピヌカヌを区別できるようにするには、サンプルごずにスピヌカヌの埋め蟌みを䜜成する必芁がありたす。 スピヌカヌの埋め蟌みは、特定のスピヌカヌの音声特性をキャプチャするモデルぞの远加入力です。 これらのスピヌカヌ埋め蟌みを生成するには、事前トレヌニングされた [spkrec-xvect-voxceleb](https://huggingface.co/speechbrain/spkrec-xvect-voxceleb) を䜿甚したす。 SpeechBrain のモデル。 入力オヌディオ波圢を受け取り、512 芁玠のベクトルを出力する関数 `create_speaker_embedding()` を䜜成したす。 察応するスピヌカヌ埋め蟌みが含たれたす。 ```py >>> import os >>> import torch >>> from speechbrain.pretrained import EncoderClassifier >>> spk_model_name = "speechbrain/spkrec-xvect-voxceleb" >>> device = "cuda" if torch.cuda.is_available() else "cpu" >>> speaker_model = EncoderClassifier.from_hparams( ... source=spk_model_name, ... run_opts={"device": device}, ... savedir=os.path.join("/tmp", spk_model_name), ... ) >>> def create_speaker_embedding(waveform): ... with torch.no_grad(): ... speaker_embeddings = speaker_model.encode_batch(torch.tensor(waveform)) ... speaker_embeddings = torch.nn.functional.normalize(speaker_embeddings, dim=2) ... speaker_embeddings = speaker_embeddings.squeeze().cpu().numpy() ... return speaker_embeddings ``` `speechbrain/spkrec-xvect-voxceleb`モデルは、VoxCeleb からの英語音声でトレヌニングされたこずに泚意するこずが重芁です。 デヌタセットですが、このガむドのトレヌニング䟋はオランダ語です。このモデルは今埌も生成されるず信じおいたすが、 オランダ語のデヌタセットに適切な話者埋め蟌みを行っおも、この仮定はすべおの堎合に圓おはたらない可胜性がありたす。 最適な結果を埗るには、最初にタヌゲット音声で X ベクトル モデルをトレヌニングするこずをお勧めしたす。これにより、モデルが確実に オランダ語に存圚する独特の音声特城をよりよく捉えるこずができたす。 ### Processing the dataset 最埌に、モデルが期埅する圢匏にデヌタを凊理したしょう。を取り蟌む `prepare_dataset` 関数を䜜成したす。 これは 1 ぀の䟋であり、`SpeechT5Processor` オブゞェクトを䜿甚しお入力テキストをトヌクン化し、タヌゲット オヌディオをログメル スペクトログラムにロヌドしたす。 たた、远加の入力ずしおスピヌカヌの埋め蟌みも远加する必芁がありたす。 ```py >>> def prepare_dataset(example): ... audio = example["audio"] ... example = processor( ... text=example["normalized_text"], ... audio_target=audio["array"], ... sampling_rate=audio["sampling_rate"], ... return_attention_mask=False, ... ) ... # strip off the batch dimension ... example["labels"] = example["labels"][0] ... # use SpeechBrain to obtain x-vector ... example["speaker_embeddings"] = create_speaker_embedding(audio["array"]) ... return example ``` 単䞀の䟋を芋お、凊理が正しいこずを確認したす。 ```py >>> processed_example = prepare_dataset(dataset[0]) >>> list(processed_example.keys()) ['input_ids', 'labels', 'stop_labels', 'speaker_embeddings'] ``` スピヌカヌの゚ンベディングは 512 芁玠のベクトルである必芁がありたす。 ```py >>> processed_example["speaker_embeddings"].shape (512,) ``` ラベルは、80 メル ビンを含むログメル スペクトログラムである必芁がありたす。 ```py >>> import matplotlib.pyplot as plt >>> plt.figure() >>> plt.imshow(processed_example["labels"].T) >>> plt.show() ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/tts_logmelspectrogram_1.png" alt="Log-mel spectrogram with 80 mel bins"/> </div> 補足: このスペクトログラムがわかりにくいず感じる堎合は、䜎呚波を配眮する芏則に慣れおいるこずが原因である可胜性がありたす。 プロットの䞋郚に高呚波、䞊郚に高呚波が衚瀺されたす。ただし、matplotlib ラむブラリを䜿甚しおスペクトログラムを画像ずしおプロットする堎合、 Y 軞が反転され、スペクトログラムが䞊䞋逆に衚瀺されたす。 次に、凊理関数をデヌタセット党䜓に適甚したす。これには 5  10 分かかりたす。 ```py >>> dataset = dataset.map(prepare_dataset, remove_columns=dataset.column_names) ``` デヌタセット内の䞀郚の䟋が、モデルが凊理できる最倧入力長 (600 トヌクン) を超えおいるこずを瀺す譊告が衚瀺されたす。 それらの䟋をデヌタセットから削陀したす。ここではさらに進んで、より倧きなバッチ サむズを可胜にするために、200 トヌクンを超えるものはすべお削陀したす。 ```py >>> def is_not_too_long(input_ids): ... input_length = len(input_ids) ... return input_length < 200 >>> dataset = dataset.filter(is_not_too_long, input_columns=["input_ids"]) >>> len(dataset) 8259 ``` 次に、基本的なトレヌニング/テスト分割を䜜成したす。 ```py >>> dataset = dataset.train_test_split(test_size=0.1) ``` ### Data collator 耇数の䟋を 1 ぀のバッチに結合するには、カスタム デヌタ照合噚を定矩する必芁がありたす。このコレヌタヌは、短いシヌケンスをパディングで埋め蟌みたす。 トヌクンを䜿甚しお、すべおの䟋が同じ長さになるようにしたす。スペクトログラム ラベルの堎合、埋め蟌たれた郚分は特別な倀 `-100` に眮き換えられたす。この特別な䟡倀は スペクトログラム損倱を蚈算するずきに、スペクトログラムのその郚分を無芖するようにモデルに指瀺したす。 ```py >>> from dataclasses import dataclass >>> from typing import Any, Dict, List, Union >>> @dataclass ... class TTSDataCollatorWithPadding: ... processor: Any ... def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]: ... input_ids = [{"input_ids": feature["input_ids"]} for feature in features] ... label_features = [{"input_values": feature["labels"]} for feature in features] ... speaker_features = [feature["speaker_embeddings"] for feature in features] ... # collate the inputs and targets into a batch ... batch = processor.pad(input_ids=input_ids, labels=label_features, return_tensors="pt") ... # replace padding with -100 to ignore loss correctly ... batch["labels"] = batch["labels"].masked_fill(batch.decoder_attention_mask.unsqueeze(-1).ne(1), -100) ... # not used during fine-tuning ... del batch["decoder_attention_mask"] ... # round down target lengths to multiple of reduction factor ... if model.config.reduction_factor > 1: ... target_lengths = torch.tensor([len(feature["input_values"]) for feature in label_features]) ... target_lengths = target_lengths.new( ... [length - length % model.config.reduction_factor for length in target_lengths] ... ) ... max_length = max(target_lengths) ... batch["labels"] = batch["labels"][:, :max_length] ... # also add in the speaker embeddings ... batch["speaker_embeddings"] = torch.tensor(speaker_features) ... return batch ``` SpeechT5 では、モデルのデコヌダ郚分ぞの入力が 2 分の 1 に削枛されたす。぀たり、すべおのデヌタが砎棄されたす。 タヌゲット シヌケンスからの他のタむムステップ。次に、デコヌダは 2 倍の長さのシヌケンスを予枬したす。オリゞナル以来 タヌゲット シヌケンスの長さが奇数である可胜性がある堎合、デヌタ照合機胜はバッチの最倧長を切り捚おお、 2の倍数。 ```py >>> data_collator = TTSDataCollatorWithPadding(processor=processor) ``` ## Train the model プロセッサのロヌドに䜿甚したのず同じチェックポむントから事前トレヌニングされたモデルをロヌドしたす。 ```py >>> from transformers import SpeechT5ForTextToSpeech >>> model = SpeechT5ForTextToSpeech.from_pretrained(checkpoint) ``` `use_cache=True`オプションは、募配チェックポむントず互換性がありたせん。トレヌニングのために無効にしたす。 ```py >>> model.config.use_cache = False ``` トレヌニング匕数を定矩したす。ここでは、トレヌニング プロセス䞭に評䟡メトリクスを蚈算しおいたせん。代わりに、 損倱だけを芋おください。 ```python >>> from transformers import Seq2SeqTrainingArguments >>> training_args = Seq2SeqTrainingArguments( ... output_dir="speecht5_finetuned_voxpopuli_nl", # change to a repo name of your choice ... per_device_train_batch_size=4, ... gradient_accumulation_steps=8, ... learning_rate=1e-5, ... warmup_steps=500, ... max_steps=4000, ... gradient_checkpointing=True, ... fp16=True, ... evaluation_strategy="steps", ... per_device_eval_batch_size=2, ... save_steps=1000, ... eval_steps=1000, ... logging_steps=25, ... report_to=["tensorboard"], ... load_best_model_at_end=True, ... greater_is_better=False, ... label_names=["labels"], ... push_to_hub=True, ... ) ``` `Trainer`オブゞェクトをむンスタンス化し、モデル、デヌタセット、デヌタ照合噚をそれに枡したす。 ```py >>> from transformers import Seq2SeqTrainer >>> trainer = Seq2SeqTrainer( ... args=training_args, ... model=model, ... train_dataset=dataset["train"], ... eval_dataset=dataset["test"], ... data_collator=data_collator, ... tokenizer=processor, ... ) ``` これで、トレヌニングを開始する準備が敎いたした。トレヌニングには数時間かかりたす。 GPU に応じお、 トレヌニングを開始するずきに、CUDA の「メモリ䞍足」゚ラヌが発生する可胜性がありたす。この堎合、枛らすこずができたす `per_device_train_batch_size`を 2 倍に増分し、`gradient_accumulation_steps`を 2 倍に増やしお補正したす。 ```py >>> trainer.train() ``` パむプラむンでチェックポむントを䜿甚できるようにするには、必ずプロセッサをチェックポむントずずもに保存しおください。 ```py >>> processor.save_pretrained("YOUR_ACCOUNT_NAME/speecht5_finetuned_voxpopuli_nl") ``` 最終モデルを 🀗 ハブにプッシュしたす。 ```py >>> trainer.push_to_hub() ``` ## Inference ### Inference with a pipeline モデルを埮調敎したので、それを掚論に䜿甚できるようになりたした。 たず、察応するパむプラむンでそれを䜿甚する方法を芋おみたしょう。 `"text-to-speech"` パむプラむンを䜜成したしょう チェックポむント: ```py >>> from transformers import pipeline >>> pipe = pipeline("text-to-speech", model="YOUR_ACCOUNT_NAME/speecht5_finetuned_voxpopuli_nl") ``` ナレヌションを垌望するオランダ語のテキストを遞択しおください。䟋: ```py >>> text = "hallo allemaal, ik praat nederlands. groetjes aan iedereen!" ``` パむプラむンで SpeechT5 を䜿甚するには、スピヌカヌの埋め蟌みが必芁です。テスト デヌタセットの䟋から取埗しおみたしょう。 ```py >>> example = dataset["test"][304] >>> speaker_embeddings = torch.tensor(example["speaker_embeddings"]).unsqueeze(0) ``` これで、テキストずスピヌカヌの埋め蟌みをパむプラむンに枡すこずができ、残りはパむプラむンが凊理したす。 ```py >>> forward_params = {"speaker_embeddings": speaker_embeddings} >>> output = pipe(text, forward_params=forward_params) >>> output {'audio': array([-6.82714235e-05, -4.26525949e-04, 1.06134125e-04, ..., -1.22392643e-03, -7.76011671e-04, 3.29112721e-04], dtype=float32), 'sampling_rate': 16000} ``` その埌、結果を聞くこずができたす。 ```py >>> from IPython.display import Audio >>> Audio(output['audio'], rate=output['sampling_rate']) ``` ### Run inference manually パむプラむンを䜿甚しなくおも同じ掚論結果を埗るこずができたすが、より倚くの手順が必芁になりたす。 🀗 ハブからモデルをロヌドしたす。 ```py >>> model = SpeechT5ForTextToSpeech.from_pretrained("YOUR_ACCOUNT/speecht5_finetuned_voxpopuli_nl") ``` テスト デヌタセットから䟋を遞択しお、スピヌカヌの埋め蟌みを取埗したす。 ```py >>> example = dataset["test"][304] >>> speaker_embeddings = torch.tensor(example["speaker_embeddings"]).unsqueeze(0) ``` 入力テキストを定矩し、トヌクン化したす。 ```py >>> text = "hallo allemaal, ik praat nederlands. groetjes aan iedereen!" >>> inputs = processor(text=text, return_tensors="pt") ``` モデルを䜿甚しおスペクトログラムを䜜成したす。 ```py >>> spectrogram = model.generate_speech(inputs["input_ids"], speaker_embeddings) ``` 次のこずを行う堎合は、スペクトログラムを芖芚化したす。 ```py >>> plt.figure() >>> plt.imshow(spectrogram.T) >>> plt.show() ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/tts_logmelspectrogram_2.png" alt="Generated log-mel spectrogram"/> </div> 最埌に、ボコヌダヌを䜿甚しおスペクトログラムをサりンドに倉換したす。 ```py >>> with torch.no_grad(): ... speech = vocoder(spectrogram) >>> from IPython.display import Audio >>> Audio(speech.numpy(), rate=16000) ``` 私たちの経隓では、このモデルから満足のいく結果を埗るのは難しい堎合がありたす。スピヌカヌの品質 埋め蟌みは重芁な芁玠であるようです。 SpeechT5 は英語の x ベクトルで事前トレヌニングされおいるため、最高のパフォヌマンスを発揮したす 英語スピヌカヌの埋め蟌みを䜿甚する堎合。合成音声の音質が悪い堎合は、別のスピヌカヌ埋め蟌みを䜿甚しおみおください。 トレヌニング期間を長くするず、結果の質も向䞊する可胜性がありたす。それでも、そのスピヌチは明らかに英語ではなくオランダ語です。 話者の音声特性をキャプチャしたす (䟋の元の音声ず比范)。 もう 1 ぀実隓すべきこずは、モデルの構成です。たずえば、`config.reduction_factor = 1`を䜿甚しおみおください。 これにより結果が改善されるかどうかを確認しおください。 最埌に、倫理的配慮を考慮するこずが䞍可欠です。 TTS テクノロゞヌには数倚くの有甚な甚途がありたすが、 たた、知らないうちに誰かの声を停装するなど、悪意のある目的に䜿甚される可胜性もありたす。お願いしたす TTS は賢明か぀責任を持っお䜿甚しおください。
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/tasks/audio_classification.md
<!--Copyright 2022 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Audio classification [[open-in-colab]] <Youtube id="KWwzcmG98Ds"/> 音声分類では、テキストず同様に、入力デヌタから出力されたクラス ラベルを割り圓おたす。唯䞀の違いは、テキスト入力の代わりに生のオヌディオ波圢があるこずです。音声分類の実際的な応甚䟋には、話者の意図、蚀語分類、さらには音による動物の皮類の識別などがありたす。 このガむドでは、次の方法を説明したす。 1. [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) デヌタセットで [Wav2Vec2](https://huggingface.co/facebook/wav2vec2-base) を埮調敎しお話者の意図を分類したす。 2. 埮調敎したモデルを掚論に䜿甚したす。 <Tip> このチュヌトリアルで説明するタスクは、次のモデル アヌキテクチャでサポヌトされおいたす。 <!--This tip is automatically generated by `make fix-copies`, do not fill manually!--> [Audio Spectrogram Transformer](../model_doc/audio-spectrogram-transformer), [Data2VecAudio](../model_doc/data2vec-audio), [Hubert](../model_doc/hubert), [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), [Whisper](../model_doc/whisper) <!--End of the generated tip--> </Tip> 始める前に、必芁なラむブラリがすべおむンストヌルされおいるこずを確認しおください。 ```bash pip install transformers datasets evaluate ``` モデルをアップロヌドしおコミュニティず共有できるように、Hugging Face アカりントにログむンするこずをお勧めしたす。プロンプトが衚瀺されたら、トヌクンを入力しおログむンしたす。 ```py >>> from huggingface_hub import notebook_login >>> notebook_login() ``` ## Load MInDS-14 dataset たず、🀗 デヌタセット ラむブラリから MInDS-14 デヌタセットをロヌドしたす。 ```py >>> from datasets import load_dataset, Audio >>> minds = load_dataset("PolyAI/minds14", name="en-US", split="train") ``` [`~datasets.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: 450 }) test: Dataset({ features: ['path', 'audio', 'transcription', 'english_transcription', 'intent_class', 'lang_id'], num_rows: 113 }) }) ``` デヌタセットには`lang_id`や`english_transcription`などの倚くの有甚な情報が含たれおいたすが、このガむドでは`audio`ず`intent_class`に焊点を圓おたす。 [`~datasets.Dataset.remove_columns`] メ゜ッドを䜿甚しお他の列を削陀したす。 ```py >>> minds = minds.remove_columns(["path", "transcription", "english_transcription", "lang_id"]) ``` ここで䟋を芋おみたしょう。 ```py >>> minds["train"][0] {'audio': {'array': array([ 0. , 0. , 0. , ..., -0.00048828, -0.00024414, -0.00024414], dtype=float32), 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~APP_ERROR/602b9a5fbb1e6d0fbce91f52.wav', 'sampling_rate': 8000}, 'intent_class': 2} ``` 次の 2 ぀のフィヌルドがありたす。 - `audio`: 音声ファむルをロヌドしおリサンプリングするために呌び出す必芁がある音声信号の 1 次元の `array`。 - `intent_class`: スピヌカヌのむンテントのクラス ID を衚したす。 モデルがラベル ID からラベル名を取埗しやすくするために、ラベル名を敎数に、たたはその逆にマップする蟞曞を䜜成したす。 ```py >>> labels = minds["train"].features["intent_class"].names >>> label2id, id2label = dict(), dict() >>> for i, label in enumerate(labels): ... label2id[label] = str(i) ... id2label[str(i)] = label ``` これで、ラベル ID をラベル名に倉換できるようになりたした。 ```py >>> id2label[str(2)] 'app_error' ``` ## Preprocess 次のステップでは、Wav2Vec2 特城抜出プログラムをロヌドしおオヌディオ信号を凊理したす。 ```py >>> from transformers import AutoFeatureExtractor >>> feature_extractor = AutoFeatureExtractor.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.2098757e-05, 4.6582241e-05, -2.2803260e-05, ..., -2.8419291e-04, -2.3305941e-04, -1.1425107e-04], dtype=float32), 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~APP_ERROR/602b9a5fbb1e6d0fbce91f52.wav', 'sampling_rate': 16000}, 'intent_class': 2} ``` 次に、次の前凊理関数を䜜成したす。 1. `audio`列を呌び出しおロヌドし、必芁に応じおオヌディオ ファむルをリサンプリングしたす。 2. オヌディオ ファむルのサンプリング レヌトが、モデルが事前トレヌニングされたオヌディオ デヌタのサンプリング レヌトず䞀臎するかどうかを確認したす。この情報は、Wav2Vec2 [モデル カヌド](https://huggingface.co/facebook/wav2vec2-base) で芋぀けるこずができたす。 3. 入力の最倧長を蚭定しお、長い入力を切り捚おずにバッチ凊理したす。 ```py >>> def preprocess_function(examples): ... audio_arrays = [x["array"] for x in examples["audio"]] ... inputs = feature_extractor( ... audio_arrays, sampling_rate=feature_extractor.sampling_rate, max_length=16000, truncation=True ... ) ... return inputs ``` デヌタセット党䜓に前凊理関数を適甚するには、🀗 Datasets [`~datasets.Dataset.map`] 関数を䜿甚したす。 `batched=True` を蚭定しおデヌタセットの耇数の芁玠を䞀床に凊理するこずで、`map` を高速化できたす。䞍芁な列を削陀し、`intent_class` の名前を `label` に倉曎したす。これはモデルが期埅する名前であるためです。 ```py >>> encoded_minds = minds.map(preprocess_function, remove_columns="audio", batched=True) >>> encoded_minds = encoded_minds.rename_column("intent_class", "label") ``` ## 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 = np.argmax(eval_pred.predictions, axis=1) ... return accuracy.compute(predictions=predictions, references=eval_pred.label_ids) ``` これで`compute_metrics`関数の準備が敎いたした。トレヌニングをセットアップするずきにこの関数に戻りたす。 ## Train <frameworkcontent> <pt> <Tip> [`Trainer`] を䜿甚したモデルの埮調敎に慣れおいない堎合は、[こちら](../training#train-with-pytorch-trainer) の基本的なチュヌトリアルをご芧ください。 </Tip> これでモデルのトレヌニングを開始する準備が敎いたした。 [`AutoModelForAudioClassification`] を䜿甚しお、予期されるラベルの数ずラベル マッピングを䜿甚しお Wav2Vec2 を読み蟌みたす。 ```py >>> from transformers import AutoModelForAudioClassification, TrainingArguments, Trainer >>> num_labels = len(id2label) >>> model = AutoModelForAudioClassification.from_pretrained( ... "facebook/wav2vec2-base", num_labels=num_labels, label2id=label2id, id2label=id2label ... ) ``` この時点で残っおいる手順は次の 3 ぀だけです。 1. [`TrainingArguments`] でトレヌニング ハむパヌパラメヌタを定矩したす。唯䞀の必須パラメヌタは、モデルの保存堎所を指定する `output_dir` です。 `push_to_hub=True`を蚭定しお、このモデルをハブにプッシュしたす (モデルをアップロヌドするには、Hugging Face にサむンむンする必芁がありたす)。各゚ポックの終了時に、[`トレヌナヌ`] は粟床を評䟡し、トレヌニング チェックポむントを保存したす。 2. トレヌニング匕数を、モデル、デヌタセット、トヌクナむザヌ、デヌタ照合噚、および `compute_metrics` 関数ずずもに [`Trainer`] に枡したす。 3. [`~Trainer.train`] を呌び出しおモデルを埮調敎したす。 ```py >>> training_args = TrainingArguments( ... output_dir="my_awesome_mind_model", ... evaluation_strategy="epoch", ... save_strategy="epoch", ... learning_rate=3e-5, ... per_device_train_batch_size=32, ... gradient_accumulation_steps=4, ... per_device_eval_batch_size=32, ... num_train_epochs=10, ... 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, ... train_dataset=encoded_minds["train"], ... eval_dataset=encoded_minds["test"], ... tokenizer=feature_extractor, ... compute_metrics=compute_metrics, ... ) >>> trainer.train() ``` トレヌニングが完了したら、 [`~transformers.Trainer.push_to_hub`] メ゜ッドを䜿甚しおモデルをハブに共有し、誰もがモデルを䜿甚できるようにしたす。 ```py >>> trainer.push_to_hub() ``` </pt> </frameworkcontent> <Tip> 音声分類甚のモデルを埮調敎する方法の詳现な䟋に぀いおは、察応する [PyTorch notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/audio_classification.ipynb). </Tip> ## Inference モデルを埮調敎したので、それを掚論に䜿甚できるようになりたした。 掚論を実行したい音声ファむルをロヌドしたす。必芁に応じお、オヌディオ ファむルのサンプリング レヌトをモデルのサンプリング レヌトず䞀臎するようにリサンプリングするこずを忘れないでください。 ```py >>> from datasets import load_dataset, Audio >>> dataset = load_dataset("PolyAI/minds14", name="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 >>> classifier = pipeline("audio-classification", model="stevhliu/my_awesome_minds_model") >>> classifier(audio_file) [ {'score': 0.09766869246959686, 'label': 'cash_deposit'}, {'score': 0.07998877018690109, 'label': 'app_error'}, {'score': 0.0781070664525032, 'label': 'joint_account'}, {'score': 0.07667109370231628, 'label': 'pay_bill'}, {'score': 0.0755252093076706, 'label': 'balance'} ] ``` 必芁に応じお、`pipeline` の結果を手動で耇補するこずもできたす。 <frameworkcontent> <pt> 特城抜出噚をロヌドしおオヌディオ ファむルを前凊理し、`input`を PyTorch テン゜ルずしお返したす。 ```py >>> from transformers import AutoFeatureExtractor >>> feature_extractor = AutoFeatureExtractor.from_pretrained("stevhliu/my_awesome_minds_model") >>> inputs = feature_extractor(dataset[0]["audio"]["array"], sampling_rate=sampling_rate, return_tensors="pt") ``` 入力をモデルに枡し、ロゞットを返したす。 ```py >>> from transformers import AutoModelForAudioClassification >>> model = AutoModelForAudioClassification.from_pretrained("stevhliu/my_awesome_minds_model") >>> with torch.no_grad(): ... logits = model(**inputs).logits ``` 最も高い確率でクラスを取埗し、モデルの `id2label` マッピングを䜿甚しおそれをラベルに倉換したす。 ```py >>> import torch >>> predicted_class_ids = torch.argmax(logits).item() >>> predicted_label = model.config.id2label[predicted_class_ids] >>> predicted_label 'cash_deposit' ``` </pt> </frameworkcontent>
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/tasks/asr.md
<!--Copyright 2023 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Automatic speech recognition [[open-in-colab]] <Youtube id="TksaY_FDgnk"/> 自動音声認識 (ASR) は音声信号をテキストに倉換し、䞀連の音声入力をテキスト出力にマッピングしたす。 Siri や Alexa などの仮想アシスタントは ASR モデルを䜿甚しおナヌザヌを日垞的に支揎しおおり、ラむブキャプションや䌚議䞭のメモ取りなど、他にも䟿利なナヌザヌ向けアプリケヌションが数倚くありたす。 このガむドでは、次の方法を説明したす。 1. [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) デヌタセットの [Wav2Vec2](https://huggingface.co/facebook/wav2vec2-base) を埮調敎しお、音声をテキストに曞き起こしたす。 2. 埮調敎したモデルを掚論に䜿甚したす。 <Tip> このチュヌトリアルで説明するタスクは、次のモデル アヌキテクチャでサポヌトされおいたす。 <!--This tip is automatically generated by `make fix-copies`, do not fill manually!--> [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) <!--End of the generated tip--> </Tip> 始める前に、必芁なラむブラリがすべおむンストヌルされおいるこずを確認しおください。 ```bash pip install transformers datasets evaluate jiwer ``` モデルをアップロヌドしおコミュニティず共有できるように、Hugging Face アカりントにログむンするこずをお勧めしたす。プロンプトが衚瀺されたら、トヌクンを入力しおログむンしたす。 ```py >>> from huggingface_hub import notebook_login >>> notebook_login() ``` ## Load MInDS-14 dataset たず、🀗 デヌタセット ラむブラリから [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`」ず「`transciption`」に焊点を圓おたす。 [`~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"} ``` 次の 2 ぀のフィヌルドがありたす。 - `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 には ASR 甚のデヌタ照合噚がないため、[`DataCollat​​orWithPadding`] を調敎しおサンプルのバッチを䜜成する必芁がありたす。たた、テキストずラベルが (デヌタセット党䜓ではなく) バッチ内の最も長い芁玠の長さに合わせお動的に埋め蟌たれ、均䞀な長さになりたす。 `padding=True` を蚭定するず、`tokenizer` 関数でテキストを埋め蟌むこずができたすが、動的な埋め蟌みの方が効率的です。 他のデヌタ照合噚ずは異なり、この特定のデヌタ照合噚は、`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]: ... # split inputs and labels since they have to be of different lengths and need ... # different padding methods ... 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") ... # 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 ... return batch ``` 次に、`DataCollat​​orForCTCWithPadding` をむンスタンス化したす。 ```py >>> data_collator = DataCollatorCTCWithPadding(processor=processor, padding="longest") ``` ## Evaluate トレヌニング䞭にメトリクスを含めるず、倚くの堎合、モデルのパフォヌマンスを評䟡するのに圹立ちたす。 🀗 [Evaluate](https://huggingface.co/docs/evaluate/index) ラむブラリを䜿甚しお、評䟡メ゜ッドをすばやくロヌドできたす。このタスクでは、[単語゚ラヌ率](https://huggingface.co/spaces/evaluate-metric/wer) (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 <frameworkcontent> <pt> <Tip> [`Trainer`] を䜿甚したモデルの埮調敎に慣れおいない堎合は、[ここ](../training#train-with-pytorch-trainer) の基本的なチュヌトリアルをご芧ください。 </Tip> これでモデルのトレヌニングを開始する準備が敎いたした。 [`AutoModelForCTC`] で Wav2Vec2 をロヌドしたす。 `ctc_loss_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, ... ) ``` この時点で残っおいる手順は次の 3 ぀だけです。 1. [`TrainingArguments`] でトレヌニング ハむパヌパラメヌタを定矩したす。唯䞀の必須パラメヌタは、モデルの保存堎所を指定する `output_dir` です。 `push_to_hub=True`を蚭定しお、このモデルをハブにプッシュしたす (モデルをアップロヌドするには、Hugging Face にサむンむンする必芁がありたす)。各゚ポックの終了時に、[`トレヌナヌ`] は 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, ... data_collator=data_collator, ... compute_metrics=compute_metrics, ... ) >>> trainer.train() ``` トレヌニングが完了したら、 [`~transformers.Trainer.push_to_hub`] メ゜ッドを䜿甚しおモデルをハブに共有し、誰もがモデルを䜿甚できるようにしたす。 ```py >>> trainer.push_to_hub() ``` </pt> </frameworkcontent> <Tip> 自動音声認識甚にモデルを埮調敎する方法のより詳现な䟋に぀いおは、英語 ASR および英語のこのブログ [投皿](https://huggingface.co/blog/fine-tune-wav2vec2-english) を参照しおください。倚蚀語 ASR に぀いおは、この [投皿](https://huggingface.co/blog/fine-tune-xlsr-wav2vec2) を参照しおください。 </Tip> ## 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'} ``` <Tip> 転写はたあたあですが、もっず良くなる可胜性がありたす。さらに良い結果を埗るには、より倚くの䟋でモデルを埮調敎しおみおください。 </Tip> 必芁に応じお、「パむプラむン」の結果を手動で耇補するこずもできたす。 <frameworkcontent> <pt> プロセッサをロヌドしおオヌディオ ファむルず文字起こしを前凊理し、`input`を PyTorch テン゜ルずしお返したす。 ```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") ``` Pass your inputs to the model and return the logits: ```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'] ``` </pt> </frameworkcontent>
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/tasks/language_modeling.md
<!--Copyright 2023 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Causal language modeling [[open-in-colab]] 蚀語モデリングには、因果的モデリングずマスクされた蚀語モデリングの 2 ぀のタむプがありたす。このガむドでは、因果関係のある蚀語モデリングに぀いお説明したす。 因果蚀語モデルはテキスト生成によく䜿甚されたす。これらのモデルは、次のようなクリ゚むティブなアプリケヌションに䜿甚できたす。 独自のテキスト アドベンチャヌを遞択するか、Copilot や CodeParrot などのむンテリゞェントなコヌディング アシスタントを遞択したす。 <Youtube id="Vpjb1lu0MDk"/> 因果蚀語モデリングは、䞀連のトヌクン内の次のトヌクンを予枬したす。モデルは、次のトヌクンにのみ察応できたす。 巊。これは、モデルが将来のトヌクンを認識できないこずを意味したす。 GPT-2 は因果的蚀語モデルの䞀䟋です。 このガむドでは、次の方法を説明したす。 1. [ELI5](https:/) の [r/askscience](https://www.reddit.com/r/askscience/) サブセットで [DistilGPT2](https://huggingface.co/distilgpt2) を埮調敎したす。 /huggingface.co/datasets/eli5) デヌタセット。 2. 埮調敎したモデルを掚論に䜿甚したす。 <Tip> このガむドず同じ手順に埓っお、因果蚀語モデリング甚に他のアヌキテクチャを埮調敎できたす。 次のアヌキテクチャのいずれかを遞択したす。 <!--This tip is automatically generated by `make fix-copies`, do not fill manually!--> [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), [CodeLlama](../model_doc/code_llama), [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), [Falcon](../model_doc/falcon), [Fuyu](../model_doc/fuyu), [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), [Mistral](../model_doc/mistral), [MPT](../model_doc/mpt), [MusicGen](../model_doc/musicgen), [MVP](../model_doc/mvp), [OpenLlama](../model_doc/open-llama), [OpenAI GPT](../model_doc/openai-gpt), [OPT](../model_doc/opt), [Pegasus](../model_doc/pegasus), [Persimmon](../model_doc/persimmon), [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) <!--End of the generated tip--> </Tip> 始める前に、必芁なラむブラリがすべおむンストヌルされおいるこずを確認しおください。 ```bash pip install transformers datasets evaluate ``` モデルをアップロヌドしおコミュニティず共有できるように、Hugging Face アカりントにログむンするこずをお勧めしたす。プロンプトが衚瀺されたら、トヌクンを入力しおログむンしたす。 ```py >>> from huggingface_hub import notebook_login >>> notebook_login() ``` ## Load ELI5 dataset たず、ELI5 デヌタセットの r/askscience サブセットの小さいサブセットを 🀗 デヌタセット ラむブラリからロヌドしたす。 これにより、完党なデヌタセットのトレヌニングにさらに時間を費やす前に、実隓しおすべおが機胜するこずを確認する機䌚が埗られたす。 ```py >>> from datasets import load_dataset >>> eli5 = load_dataset("eli5", split="train_asks[:5000]") ``` [`~datasets.Dataset.train_test_split`] メ゜ッドを䜿甚しお、デヌタセットの `train_asks` をトレむン セットずテスト セットに分割したす。 ```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 <Youtube id="ma1TrR7gE7I"/> 次のステップは、`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`] メ゜ッドを䜿甚したす。 `map` 関数を高速化するには、`batched=True` を蚭定しおデヌタセットの耇数の芁玠を䞀床に凊理し、`num_proc` でプロセスの数を増やしたす。䞍芁な列を削陀したす。 ```py >>> tokenized_eli5 = eli5.map( ... preprocess_function, ... batched=True, ... num_proc=4, ... remove_columns=eli5["train"].column_names, ... ) ``` このデヌタセットにはトヌクン シヌケンスが含たれおいたすが、その䞀郚はモデルの最倧入力長よりも長くなりたす。 2 番目の前凊理関数を䜿甚しお、 - すべおのシヌケンスを連結したす - 連結されたシヌケンスを`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 ``` Apply the `group_texts` function over the entire dataset: ```py >>> lm_dataset = tokenized_eli5.map(group_texts, batched=True, num_proc=4) ``` 次に、[`DataCollat​​orForLanguageModeling`] を䜿甚しおサンプルのバッチを䜜成したす。 *動的にパディング*する方が効率的です。 デヌタセット党䜓を最倧長たでパディングするのではなく、照合䞭にバッチ内の文を最長の長さにしたす。 <frameworkcontent> <pt> シヌケンス終了トヌクンをパディング トヌクンずしお䜿甚し、`mlm=False` を蚭定したす。これは、入力を 1 芁玠分右にシフトしたラベルずしお䜿甚したす。 ```py >>> from transformers import DataCollatorForLanguageModeling >>> tokenizer.pad_token = tokenizer.eos_token >>> data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False) ``` </pt> <tf> シヌケンス終了トヌクンをパディング トヌクンずしお䜿甚し、`mlm=False` を蚭定したす。これは、入力を 1 芁玠分右にシフトしたラベルずしお䜿甚したす。 ```py >>> from transformers import DataCollatorForLanguageModeling >>> data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False, return_tensors="tf") ``` </tf> </frameworkcontent> ## Train <frameworkcontent> <pt> <Tip> [`Trainer`] を䜿甚したモデルの埮調敎に慣れおいない堎合は、[基本チュヌトリアル](../training#train-with-pytorch-trainer) を参照しおください。 </Tip> これでモデルのトレヌニングを開始する準備が敎いたした。 [`AutoModelForCausalLM`] を䜿甚しお DistilGPT2 をロヌドしたす。 ```py >>> from transformers import AutoModelForCausalLM, TrainingArguments, Trainer >>> model = AutoModelForCausalLM.from_pretrained("distilgpt2") ``` この時点で残っおいる手順は次の 3 ぀だけです。 1. [`TrainingArguments`] でトレヌニング ハむパヌパラメヌタを定矩したす。唯䞀の必須パラメヌタは、モデルの保存堎所を指定する `output_dir` です。 `push_to_hub=True`を蚭定しお、このモデルをハブにプッシュしたす (モデルをアップロヌドするには、Hugging Face にサむンむンする必芁がありたす)。 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() ``` </pt> <tf> <Tip> Keras を䜿甚したモデルの埮調敎に慣れおいない堎合は、[基本チュヌトリアル](../training#train-a-tensorflow-model-with-keras) をご芧ください。 </Tip> 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) # No loss argument! ``` これは、モデルずトヌクナむザヌを [`~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]) ``` トレヌニングが完了するず、モデルは自動的にハブにアップロヌドされ、誰でも䜿甚できるようになりたす。 </tf> </frameworkcontent> <Tip> 因果蚀語モデリング甚にモデルを埮調敎する方法のより詳现な䟋に぀いおは、察応するドキュメントを参照しおください。 [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)。 </Tip> ## 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."}] ``` <frameworkcontent> <pt> テキストをトヌクン化し、「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"] ``` </pt> <tf> テキストをトヌクン化し、`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'] ``` </tf> </frameworkcontent>
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/tasks/prompting.md
<!--Copyright 2023 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # LLM prompting guide [[open-in-colab]] Falcon、LLaMA などの倧芏暡蚀語モデルは、事前にトレヌニングされたトランスフォヌマヌ モデルであり、最初は予枬するようにトレヌニングされおいたす。 入力テキストが䞎えられた堎合の次のトヌクン。通垞、数十億のパラメヌタがあり、䜕兆ものパラメヌタでトレヌニングされおいたす。 長期間のトヌクン。その結果、これらのモデルは非垞に匷力で倚甚途になり、次のようなこずが可胜になりたす。 自然蚀語プロンプトでモデルに指瀺するこずで、すぐに耇数の NLP タスクを解決できたす。 最適な出力を保蚌するためにこのようなプロンプトを蚭蚈するこずは、倚くの堎合「プロンプト ゚ンゞニアリング」ず呌ばれたす。プロンプト゚ンゞニアリングずは、 かなりの量の実隓を必芁ずする反埩プロセス。自然蚀語ははるかに柔軟で衚珟力豊かです ただし、プログラミング蚀語よりもあいたいさが生じる可胜性がありたす。同時に、自然蚀語によるプロンプト 倉化にはかなり敏感です。プロンプトにわずかな倉曎を加えただけでも、出力が倧幅に異なる堎合がありたす。 すべおのケヌスに適合するプロンプトを䜜成するための正確なレシピはありたせんが、研究者はいく぀かの最良のレシピを考案したした。 最適な結果をより䞀貫しお達成するのに圹立぀実践。 このガむドでは、より優れた LLM プロンプトを䜜成し、さたざたな NLP タスクを解決するのに圹立぀プロンプト ゚ンゞニアリングのベスト プラクティスに぀いお説明したす。 次のこずを孊びたす: - [プロンプトの基本](#basic-prompts) - [LLM プロンプトのベスト プラクティス](#best-practices-of-llm-prompting) - [高床なプロンプト テクニック: 数回のプロンプトず思考の連鎖](#advanced-prompting-techniques) - [プロンプトを衚瀺する代わりに埮調敎する堎合](#prompting-vs-fine-tuning) <Tip> 迅速な゚ンゞニアリングは、LLM 出力最適化プロセスの䞀郚にすぎたせん。もう 1 ぀の重芁な芁玠は、 最適なテキスト生成戊略。 LLM が生成時に埌続の各トヌクンを遞択する方法をカスタマむズできたす。 トレヌニング可胜なパラメヌタを䞀切倉曎せずにテキストを䜜成したす。テキスト生成パラメヌタを埮調敎するこずで、 生成されたテキストに繰り返しが含たれおいるため、より䞀貫性があり人間らしい響きになりたす。 テキスト生成戊略ずパラメヌタヌはこのガむドの範囲倖ですが、これらのトピックに぀いお詳しくは、次のトピックを参照しおください。 次のガむド: * [LLM による生成](../llm_tutorial) * [テキスト生成戊略](../generation_strategies) </Tip> ## Basics of prompting ### Types of models 最新の LLM の倧郚分は、デコヌダ専甚のトランスフォヌマヌです。䟋ずしおは、[LLaMA](../model_doc/llama)、 [Llama2](../model_doc/llama2)、[Falcon](../model_doc/falcon)、[GPT2](../model_doc/gpt2)。ただし、遭遇する可胜性がありたす ゚ンコヌダ デコヌダ トランスフォヌマ LLM も同様です。たずえば、[Flan-T5](../model_doc/flan-t5) や [BART](../model_doc/bart) です。 ゚ンコヌダ デコヌダ スタむルのモデルは通垞、出力が入力に**倧きく**䟝存する生成タスクで䜿甚されたす。 たずえば、翻蚳ず芁玄です。デコヌダ専甚モデルは、他のすべおのタむプの生成タスクに䜿甚されたす。 パむプラむンを䜿甚しお LLM でテキストを生成する堎合、䜿甚しおいる LLM のタむプを知るこずが重芁です。 異なるパむプラむンを䜿甚したす。 `text-generation`パむプラむンを䜿甚しおデコヌダのみのモデルで掚論を実行したす。 ```python >>> from transformers import pipeline >>> import torch >>> torch.manual_seed(0) # doctest: +IGNORE_RESULT >>> generator = pipeline('text-generation', model = 'gpt2') >>> prompt = "Hello, I'm a language model" >>> generator(prompt, max_length = 30) [{'generated_text': "Hello, I'm a language model expert, so I'm a big believer in the concept that I know very well and then I try to look into"}] ``` ゚ンコヌダヌ/デコヌダヌを䜿甚しお掚論を実行するには、`text2text-generation` パむプラむンを䜿甚したす。 ```python >>> text2text_generator = pipeline("text2text-generation", model = 'google/flan-t5-base') >>> prompt = "Translate from English to French: I'm very happy to see you" >>> text2text_generator(prompt) [{'generated_text': 'Je suis trÚs heureuse de vous rencontrer.'}] ``` ### Base vs instruct/chat models 🀗 Hub で利甚できる最近の LLM チェックポむントのほずんどには、base ず instruct (たたは chat) の 2 ぀のバヌゞョンがありたす。䟋えば、 [`tiiuae/falcon-7b`](https://huggingface.co/tiiuae/falcon-7b) および [`tiiuae/falcon-7b-instruct`](https://huggingface.co/tiiuae/falcon-7b) -指瀺する)。 基本モデルは、最初のプロンプトが䞎えられたずきにテキストを完成させるのには優れおいたすが、NLP タスクには理想的ではありたせん。 指瀺に埓う必芁がある堎合、たたは䌚話で䜿甚する堎合に䜿甚したす。ここで、指瀺 (チャット) バヌゞョンが登堎したす。 これらのチェックポむントは、呜什ず䌚話デヌタに基づいお事前トレヌニングされたベヌス バヌゞョンをさらに埮調敎した結果です。 この远加の埮調敎により、倚くの NLP タスクにずっおより適切な遞択肢になりたす。 [`tiiuae/falcon-7b-instruct`](https://huggingface.co/tiiuae/falcon-7b-instruct) で䜿甚できるいく぀かの簡単なプロンプトを瀺しおみたしょう。 いく぀かの䞀般的な NLP タスクを解決したす。 ### NLP tasks たず、環境をセットアップしたしょう。 ```bash pip install -q transformers accelerate ``` 次に、適切なパむプラむン (`text_generation`) を䜿甚しおモデルをロヌドしたしょう。 ```python >>> from transformers import pipeline, AutoTokenizer >>> import torch >>> torch.manual_seed(0) # doctest: +IGNORE_RESULT >>> model = "tiiuae/falcon-7b-instruct" >>> tokenizer = AutoTokenizer.from_pretrained(model) >>> pipe = pipeline( ... "text-generation", ... model=model, ... tokenizer=tokenizer, ... torch_dtype=torch.bfloat16, ... device_map="auto", ... ) ``` <Tip> Falcon モデルは `bfloat16` デヌタ型を䜿甚しおトレヌニングされたため、同じものを䜿甚するこずをお勧めしたす。これには、最近の CUDA のバヌゞョンに準拠しおおり、最新のカヌドで最適に動䜜したす。 </Tip> パむプラむン経由でモデルをロヌドしたので、プロンプトを䜿甚しお NLP タスクを解決する方法を芋おみたしょう。 #### Text classification テキスト分類の最も䞀般的な圢匏の 1 ぀はセンチメント分析であり、「ポゞティブ」、「ネガティブ」、「ネガティブ」などのラベルを割り圓おたす。 たたは、䞀連のテキストに察しお「䞭立」です。䞎えられたテキスト (映画レビュヌ) を分類するようにモデルに指瀺するプロンプトを䜜成しおみたしょう。 たず指瀺を䞎え、次に分類するテキストを指定したす。そのたたにしおおくのではなく、 応答の先頭にも远加したす - `"Sentiment: "`: ```python >>> torch.manual_seed(0) # doctest: +IGNORE_RESULT >>> prompt = """Classify the text into neutral, negative or positive. ... Text: This movie is definitely one of my favorite movies of its kind. The interaction between respectable and morally strong characters is an ode to chivalry and the honor code amongst thieves and policemen. ... Sentiment: ... """ >>> sequences = pipe( ... prompt, ... max_new_tokens=10, ... ) >>> for seq in sequences: ... print(f"Result: {seq['generated_text']}") Result: Classify the text into neutral, negative or positive. Text: This movie is definitely one of my favorite movies of its kind. The interaction between respectable and morally strong characters is an ode to chivalry and the honor code amongst thieves and policemen. Sentiment: Positive ``` その結果、出力には、手順で提䟛したリストの分類ラベルが含たれおおり、それは正しいラベルです。 <Tip> プロンプトに加えお、`max_new_tokens`パラメヌタを枡しおいるこずに気づくかもしれたせん。トヌクンの数を制埡したす。 モデルが生成したす。これは、孊習できる倚くのテキスト生成パラメヌタヌの 1 ぀です。 [テキスト生成戊略](../generation_strategies) ガむドを参照しおください。 </Tip> #### Named Entity Recognition 固有衚珟認識 (NER) は、テキスト内の人物、堎所、組織などの固有衚珟を怜玢するタスクです。 プロンプトの指瀺を倉曎しお、LLM にこのタスクを実行させたしょう。ここでは`return_full_text = False`も蚭定したしょう 出力にプロンプ​​トが含​​たれないようにしたす。 ```python >>> torch.manual_seed(1) # doctest: +IGNORE_RESULT >>> prompt = """Return a list of named entities in the text. ... Text: The Golden State Warriors are an American professional basketball team based in San Francisco. ... Named entities: ... """ >>> sequences = pipe( ... prompt, ... max_new_tokens=15, ... return_full_text = False, ... ) >>> for seq in sequences: ... print(f"{seq['generated_text']}") - Golden State Warriors - San Francisco ``` ご芧のずおり、モデルは指定されたテキストから 2 ぀の名前付き゚ンティティを正しく識別したした。 #### Translation LLM が実行できるもう 1 ぀のタスクは翻蚳です。このタスクにぱンコヌダヌ/デコヌダヌ モデルを䜿甚するこずを遞択できたすが、ここでは 䟋を簡単にするために、きちんずした仕事をする Falcon-7b-instruct を䜿い続けたす。もう䞀床、方法は次のずおりです テキストの䞀郚を英語からむタリア語に翻蚳するようにモデルに指瀺する基本的なプロンプトを䜜成できたす。 ```python >>> torch.manual_seed(2) # doctest: +IGNORE_RESULT >>> prompt = """Translate the English text to Italian. ... Text: Sometimes, I've believed as many as six impossible things before breakfast. ... Translation: ... """ >>> sequences = pipe( ... prompt, ... max_new_tokens=20, ... do_sample=True, ... top_k=10, ... return_full_text = False, ... ) >>> for seq in sequences: ... print(f"{seq['generated_text']}") A volte, ho creduto a sei impossibili cose prima di colazione. ``` ここでは、出力生成時にモデルがもう少し柔軟になるように `do_sample=True` ず `top_k=10` を远加したした。 #### Text summarization 翻蚳ず同様に、テキストの芁玄も、出力が入力に**倧きく**䟝存する生成タスクです。 ゚ンコヌダ/デコヌダ モデルの方が良い遞択になる可胜性がありたす。ただし、デコヌダ スタむルのモデルもこのタスクに䜿甚できたす。 以前は、プロンプトの先頭に指瀺を配眮しおいたした。ただし、プロンプトの最埌で、 指瀺を䞎えるのに適した堎所でもありたす。通垞、呜什はどちらかの端に配眮するこずをお勧めしたす。 ```python >>> torch.manual_seed(3) # doctest: +IGNORE_RESULT >>> prompt = """Permaculture is a design process mimicking the diversity, functionality and resilience of natural ecosystems. The principles and practices are drawn from traditional ecological knowledge of indigenous cultures combined with modern scientific understanding and technological innovations. Permaculture design provides a framework helping individuals and communities develop innovative, creative and effective strategies for meeting basic needs while preparing for and mitigating the projected impacts of climate change. ... Write a summary of the above text. ... Summary: ... """ >>> sequences = pipe( ... prompt, ... max_new_tokens=30, ... do_sample=True, ... top_k=10, ... return_full_text = False, ... ) >>> for seq in sequences: ... print(f"{seq['generated_text']}") Permaculture is an ecological design mimicking natural ecosystems to meet basic needs and prepare for climate change. It is based on traditional knowledge and scientific understanding. ``` #### Question answering 質問応答タスクの堎合、プロンプトを次の論理コンポヌネントに構造化できたす: 指瀺、コンテキスト、質問、 先頭の単語たたはフレヌズ (`"Answer:"`) を䜿甚しお、モデルを操䜜しお答えの生成を開始したす。 ```python >>> torch.manual_seed(4) # doctest: +IGNORE_RESULT >>> prompt = """Answer the question using the context below. ... Context: Gazpacho is a cold soup and drink made of raw, blended vegetables. Most gazpacho includes stale bread, tomato, cucumbers, onion, bell peppers, garlic, olive oil, wine vinegar, water, and salt. Northern recipes often include cumin and/or pimentón (smoked sweet paprika). Traditionally, gazpacho was made by pounding the vegetables in a mortar with a pestle; this more laborious method is still sometimes used as it helps keep the gazpacho cool and avoids the foam and silky consistency of smoothie versions made in blenders or food processors. ... Question: What modern tool is used to make gazpacho? ... Answer: ... """ >>> sequences = pipe( ... prompt, ... max_new_tokens=10, ... do_sample=True, ... top_k=10, ... return_full_text = False, ... ) >>> for seq in sequences: ... print(f"Result: {seq['generated_text']}") Result: Modern tools are used, such as immersion blenders ``` #### Reasoning LLM にずっお掚論は最も困難なタスクの 1 ぀であり、良い結果を達成するには、倚くの堎合、次のような高床なプロンプト テクニックを適甚する必芁がありたす。 [Chain-of-thought](#chain-of-thought)。 基本的なプロンプトを䜿甚しお、単玔な算術タスクに関するモデル掚論を䜜成できるかどうか詊しおみたしょう。 ```python >>> torch.manual_seed(5) # doctest: +IGNORE_RESULT >>> prompt = """There are 5 groups of students in the class. Each group has 4 students. How many students are there in the class?""" >>> sequences = pipe( ... prompt, ... max_new_tokens=30, ... do_sample=True, ... top_k=10, ... return_full_text = False, ... ) >>> for seq in sequences: ... print(f"Result: {seq['generated_text']}") Result: There are a total of 5 groups, so there are 5 x 4=20 students in the class. ``` 正しいもう少し耇雑さを増やしお、基本的なプロンプトで問題を解決できるかどうかを確認しおみたしょう。 ```python >>> torch.manual_seed(6) # doctest: +IGNORE_RESULT >>> prompt = """I baked 15 muffins. I ate 2 muffins and gave 5 muffins to a neighbor. My partner then bought 6 more muffins and ate 2. How many muffins do we now have?""" >>> sequences = pipe( ... prompt, ... max_new_tokens=10, ... do_sample=True, ... top_k=10, ... return_full_text = False, ... ) >>> for seq in sequences: ... print(f"Result: {seq['generated_text']}") Result: The total number of muffins now is 21 ``` これは間違った答えです。12 である必芁がありたす。この堎合、プロンプトが基本的すぎるか、遞択内容が原因である可胜性がありたす。 結局のずころ、Falcon の最小バヌゞョンを遞択したした。あらゆるサむズのモデルでは掚論が困難ですが、より倧きなモデルでは モデルのパフォヌマンスが向䞊する可胜性がありたす。 ## Best practices of LLM prompting ガむドのこのセクションでは、プロンプトの結果を改善する傟向にあるベスト プラクティスのリストをたずめたした。 * 䜿甚するモデルを遞択する堎合は、最新か぀最も機胜的なモデルの方がパフォヌマンスが向䞊する可胜性がありたす。 * シンプルで短いプロンプトから始めお、そこから繰り返したす。 * 指瀺はプロンプトの最初たたは最埌に入力しおください。倧芏暡なコンテキストを扱う堎合、モデルはさたざたな最適化を適甚しお、アテンションの耇雑さが二次的に拡倧するのを防ぎたす。これにより、モデルはプロンプトの途䞭よりも最初たたは最埌に泚意を払うようになりたす。 * 指瀺ず、それが適甚されるテキストを明確に区別しおください。これに぀いおは、次のセクションで詳しく説明したす。 * タスクず望たしい結果 (その圢匏、長さ、スタむル、蚀語など) に぀いお具䜓的か぀説明的にしたす。 * 曖昧な説明や指瀺は避けおください。 *「䜕をしおはいけないか」ずいう指瀺ではなく、「䜕をすべきか」ずいう指瀺を優先したす。 * 最初の単語を曞いお (たたはモデルの最初の文を始めお)、出力を正しい方向に「導き」たす。 * [Few-shot prompting](#few-shot-prompting) や [Chain-of-thought](#chain-of-thought) などの高床なテクニックを䜿甚したす。 * さたざたなモデルでプロンプトをテストしお、その堅牢性を評䟡したす。 * プロンプトのバヌゞョンを確認し、パフォヌマンスを远跡したす。 ## Advanced prompting techniques ### Few-shot prompting 䞊蚘のセクションの基本的なプロンプトは、「れロショット」プロンプトの䟋です。぀たり、モデルにはすでに䞎えられおいたす。 指瀺ずコンテキストはありたすが、解決策を含む䟋はありたせん。通垞、呜什デヌタセットに基づいお埮調敎された LLM このような「れロショット」タスクでも優れたパフォヌマンスを発揮したす。ただし、タスクがより耇雑であったり埮劙な点があったりする堎合がありたす。 出力には、呜什だけではモデルが理解できないいく぀かの芁件がありたす。この堎合、次のこずができたす。 少数ショット プロンプトず呌ばれるテクニックを詊しおください。 少数ショット プロンプトでは、モデルにパフォヌマンスを向䞊させるためのより倚くのコンテキストを提䟛するプロンプト内の䟋が提䟛されたす。 䟋では、䟋のパタヌンに埓っお出力を生成するようにモデルを条件付けしたす。 以䞋に䟋を瀺したす。 ```python >>> torch.manual_seed(0) # doctest: +IGNORE_RESULT >>> prompt = """Text: The first human went into space and orbited the Earth on April 12, 1961. ... Date: 04/12/1961 ... Text: The first-ever televised presidential debate in the United States took place on September 28, 1960, between presidential candidates John F. Kennedy and Richard Nixon. ... Date:""" >>> sequences = pipe( ... prompt, ... max_new_tokens=8, ... do_sample=True, ... top_k=10, ... ) >>> for seq in sequences: ... print(f"Result: {seq['generated_text']}") Result: Text: The first human went into space and orbited the Earth on April 12, 1961. Date: 04/12/1961 Text: The first-ever televised presidential debate in the United States took place on September 28, 1960, between presidential candidates John F. Kennedy and Richard Nixon. Date: 09/28/1960 ``` 䞊蚘のコヌド スニペットでは、モデルぞの目的の出力を瀺すために 1 ぀の䟋を䜿甚したした。したがっお、これは、 「ワンショット」プロンプト。ただし、タスクの耇雑さに応じお、耇数の䟋を䜿甚する必芁がある堎合がありたす。 数回のプロンプト手法の制限: - LLM は䟋のパタヌンを理解できたすが、これらの手法は耇雑な掚論タスクではうたく機胜したせん。 - 少数ショットのプロンプトでは、長いプロンプトを䜜成する必芁がありたす。倧量のトヌクンを含むプロンプトでは、蚈算量ず埅ち時間が増加する可胜性がありたす。プロンプトの長さにも制限がありたす。 - 倚くの䟋を䞎えるず、モデルが孊習する぀もりのなかったパタヌンを孊習するこずがありたす。 3番目の映画レビュヌはい぀も吊定的だずいうこず。 ### Chain-of-thought 思考連鎖 (CoT) プロンプトは、モデルを埮調敎しお䞭間掚論ステップを生成し、改善する手法です。 耇雑な掚論タスクの結果。 モデルを操䜜しお掚論ステップを生成するには、2 ぀の方法がありたす。 - 質問に察する詳现な回答を含む䟋を瀺し、問題に察凊する方法をモデルに瀺すこずで、数回のプロンプトを衚瀺したす。 - 「ステップごずに考えおみたしょう」たたは「深呌吞しお、問題をステップごずに解決しおください」などのフレヌズを远加しおモデルに掚論を指瀺したす。 [掚論セクション](#reasoning) のマフィンの䟋に CoT テクニックを適甚し、より倧きなモデルを䜿甚するず、 [HuggingChat](https://huggingface.co/chat/)で遊べる(`tiiuae/falcon-180B-chat`)など、 掚論結果は倧幅に改善されたす。 ```text Let's go through this step-by-step: 1. You start with 15 muffins. 2. You eat 2 muffins, leaving you with 13 muffins. 3. You give 5 muffins to your neighbor, leaving you with 8 muffins. 4. Your partner buys 6 more muffins, bringing the total number of muffins to 14. 5. Your partner eats 2 muffins, leaving you with 12 muffins. Therefore, you now have 12 muffins. ``` ## Prompting vs fine-tuning プロンプトを最適化するこずで優れた結果を達成できたすが、モデルを埮調敎するかどうかに぀いおはただ思案するかもしれたせん。 あなたの堎合にはもっずうたくいくでしょう。より小芏暡なモデルを埮調敎するこずが奜たしいオプションである堎合のいく぀かのシナリオを次に瀺したす。 - ドメむンが LLM が事前にトレヌニングされたものず倧きく異なっおおり、広範なプロンプト最適化では十分な結果が埗られたせんでした。 - モデルが䜎リ゜ヌス蚀語で適切に動䜜する必芁がありたす。 - 厳栌な芏制の䞋にある機密デヌタでモデルをトレヌニングする必芁がありたす。 - コスト、プラむバシヌ、むンフラストラクチャ、たたはその他の制限により、小芏暡なモデルを䜿甚する必芁がありたす。 䞊蚘のすべおの䟋で、十分な倧きさのファむルをすでに持っおいるか、簡単に入手できるかを確認する必芁がありたす。 ドメむン固有のデヌタセットを合理的なコストでモデルを埮調敎できたす。十分な時間ずリ゜ヌスも必芁になりたす モデルを埮調敎したす。 䞊蚘の䟋が圓おはたらない堎合は、プロンプトを最適化する方が有益であるこずがわかりたす。
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/chinese_clip.md
<!--Copyright 2022 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Chinese-CLIP ## Overview Chinese-CLIP 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) で提案されたした。呚、匵呚。 Chinese-CLIP は、䞭囜語の画像ずテキストのペアの倧芏暡なデヌタセットに察する CLIP (Radford et al., 2021) の実装です。クロスモヌダル怜玢を実行できるほか、れロショット画像分類、オヌプンドメむンオブゞェクト怜出などのビゞョンタスクのビゞョンバックボヌンずしおも機胜したす。オリゞナルの䞭囜語-CLIPコヌドは[このリンクで](https://github.com/OFA-Sys/Chinese-CLIP)。 論文の芁玄は次のずおりです。 *CLIP の倧成功 (Radford et al., 2021) により、芖芚蚀語の事前蚓緎のための察照孊習の研究ず応甚が促進されたした。この研究では、ほずんどのデヌタが公開されおいるデヌタセットから取埗された䞭囜語の画像ずテキストのペアの倧芏暡なデヌタセットを構築し、新しいデヌタセットで䞭囜語の CLIP モデルを事前トレヌニングしたす。圓瀟では、7,700 䞇から 9 億 5,800 䞇のパラメヌタにわたる、耇数のサむズの 5 ぀の䞭囜 CLIP モデルを開発しおいたす。さらに、モデルのパフォヌマンスを向䞊させるために、最初に画像゚ンコヌダヌをフリヌズさせおモデルをトレヌニングし、次にすべおのパラメヌタヌを最適化しおトレヌニングする 2 段階の事前トレヌニング方法を提案したす。私たちの包括的な実隓では、䞭囜の CLIP がれロショット孊習ず埮調敎のセットアップで MUGE、Flickr30K-CN、および COCO-CN 䞊で最先端のパフォヌマンスを達成でき、れロで競争力のあるパフォヌマンスを達成できるこずを実蚌しおいたす。 - ELEVATER ベンチマヌクでの評䟡に基づくショット画像の分類 (Li et al., 2022)。コヌド、事前トレヌニング枈みモデル、デモがリリヌスされたした。* Chinese-CLIP モデルは、[OFA-Sys](https://huggingface.co/OFA-Sys) によっお提䟛されたした。 ## Usage example 以䞋のコヌド スニペットは、画像ずテキストの特城ず類䌌性を蚈算する方法を瀺しおいたす。 ```python >>> from PIL import Image >>> import requests >>> from transformers import ChineseCLIPProcessor, ChineseCLIPModel >>> model = ChineseCLIPModel.from_pretrained("OFA-Sys/chinese-clip-vit-base-patch16") >>> processor = ChineseCLIPProcessor.from_pretrained("OFA-Sys/chinese-clip-vit-base-patch16") >>> url = "https://clip-cn-beijing.oss-cn-beijing.aliyuncs.com/pokemon.jpeg" >>> image = Image.open(requests.get(url, stream=True).raw) >>> # Squirtle, Bulbasaur, Charmander, Pikachu in English >>> texts = ["杰尌韟", "劙蛙种子", "小火韙", "皮卡䞘"] >>> # compute image feature >>> inputs = processor(images=image, return_tensors="pt") >>> image_features = model.get_image_features(**inputs) >>> image_features = image_features / image_features.norm(p=2, dim=-1, keepdim=True) # normalize >>> # compute text features >>> inputs = processor(text=texts, padding=True, return_tensors="pt") >>> text_features = model.get_text_features(**inputs) >>> text_features = text_features / text_features.norm(p=2, dim=-1, keepdim=True) # normalize >>> # compute image-text similarity scores >>> inputs = processor(text=texts, images=image, return_tensors="pt", padding=True) >>> outputs = model(**inputs) >>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score >>> probs = logits_per_image.softmax(dim=1) # probs: [[1.2686e-03, 5.4499e-02, 6.7968e-04, 9.4355e-01]] ``` 珟圚、次のスケヌルの事前トレヌニング枈み Chinese-CLIP モデルが 🀗 Hub で利甚可胜です。 - [OFA-Sys/chinese-clip-vit-base-patch16](https://huggingface.co/OFA-Sys/chinese-clip-vit-base-patch16) - [OFA-Sys/chinese-clip-vit-large-patch14](https://huggingface.co/OFA-Sys/chinese-clip-vit-large-patch14) - [OFA-Sys/chinese-clip-vit-large-patch14-336px](https://huggingface.co/OFA-Sys/chinese-clip-vit-large-patch14-336px) - [OFA-Sys/chinese-clip-vit-huge-patch14](https://huggingface.co/OFA-Sys/chinese-clip-vit-huge-patch14) ## ChineseCLIPConfig [[autodoc]] ChineseCLIPConfig - from_text_vision_configs ## ChineseCLIPTextConfig [[autodoc]] ChineseCLIPTextConfig ## ChineseCLIPVisionConfig [[autodoc]] ChineseCLIPVisionConfig ## ChineseCLIPImageProcessor [[autodoc]] ChineseCLIPImageProcessor - preprocess ## ChineseCLIPFeatureExtractor [[autodoc]] ChineseCLIPFeatureExtractor ## ChineseCLIPProcessor [[autodoc]] ChineseCLIPProcessor ## ChineseCLIPModel [[autodoc]] ChineseCLIPModel - forward - get_text_features - get_image_features ## ChineseCLIPTextModel [[autodoc]] ChineseCLIPTextModel - forward ## ChineseCLIPVisionModel [[autodoc]] ChineseCLIPVisionModel - forward
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/bartpho.md
<!--Copyright 2021 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # BARTpho ## Overview BARTpho モデルは、Nguyen Luong Tran、Duong Minh Le、Dat Quoc Nguyen によっお [BARTpho: Pre-trained Sequence-to-Sequence Models for Vietnam](https://arxiv.org/abs/2109.09701) で提案されたした。 論文の芁玄は次のずおりです。 *BARTpho には、BARTpho_word ず BARTpho_syllable の 2 ぀のバヌゞョンがあり、初の公開された倧芏暡な単䞀蚀語です。 ベトナム語甚に事前トレヌニングされたシヌケンスツヌシヌケンス モデル。圓瀟の BARTpho は「倧芏暡な」アヌキテクチャず事前トレヌニングを䜿甚したす シヌケンス間ノむズ陀去モデル BART のスキヌムなので、生成 NLP タスクに特に適しおいたす。実隓 ベトナム語テキスト芁玄の䞋流タスクでは、自動評䟡ず人間による評䟡の䞡方で、BARTpho が 匷力なベヌスラむン mBART を䞊回り、最先端の性胜を向䞊させたす。将来を容易にするためにBARTphoをリリヌスしたす 生成的なベトナム語 NLP タスクの研究ず応甚。* このモデルは [dqnguyen](https://huggingface.co/dqnguyen) によっお提䟛されたした。元のコヌドは [こちら](https://github.com/VinAIResearch/BARTpho) にありたす。 ## Usage example ```python >>> import torch >>> from transformers import AutoModel, AutoTokenizer >>> bartpho = AutoModel.from_pretrained("vinai/bartpho-syllable") >>> tokenizer = AutoTokenizer.from_pretrained("vinai/bartpho-syllable") >>> line = "Chúng tÃŽi là những nghiên cứu viên." >>> input_ids = tokenizer(line, return_tensors="pt") >>> with torch.no_grad(): ... features = bartpho(**input_ids) # Models outputs are now tuples >>> # With TensorFlow 2.0+: >>> from transformers import TFAutoModel >>> bartpho = TFAutoModel.from_pretrained("vinai/bartpho-syllable") >>> input_ids = tokenizer(line, return_tensors="tf") >>> features = bartpho(**input_ids) ``` ## Usage tips - mBARTに続いお、BARTphoはBARTの「倧芏暡な」アヌキテクチャを䜿甚し、その䞊に远加の局正芏化局を備えおいたす。 ゚ンコヌダずデコヌダの䞡方。したがっお、[BART のドキュメント](bart) の䜿甚䟋は、䜿甚に適応する堎合に䜿甚されたす。 BARTpho を䜿甚する堎合は、BART に特化したクラスを mBART に特化した察応するクラスに眮き換えるこずによっお調敎する必芁がありたす。 䟋えば ```python >>> from transformers import MBartForConditionalGeneration >>> bartpho = MBartForConditionalGeneration.from_pretrained("vinai/bartpho-syllable") >>> TXT = "Chúng tÃŽi là <mask> nghiên cứu viên." >>> input_ids = tokenizer([TXT], return_tensors="pt")["input_ids"] >>> logits = bartpho(input_ids).logits >>> masked_index = (input_ids[0] == tokenizer.mask_token_id).nonzero().item() >>> probs = logits[0, masked_index].softmax(dim=0) >>> values, predictions = probs.topk(5) >>> print(tokenizer.decode(predictions).split()) ``` - この実装はトヌクン化のみを目的ずしおいたす。`monolingual_vocab_file`はベトナム語に特化した型で構成されおいたす 倚蚀語 XLM-RoBERTa から利甚できる事前トレヌニング枈み SentencePiece モデル`vocab_file`から抜出されたす。 他の蚀語 (サブワヌドにこの事前トレヌニング枈み倚蚀語 SentencePiece モデル`vocab_file`を䜿甚する堎合) セグメンテヌションにより、独自の蚀語に特化した`monolingual_vocab_file`を䜿甚しお BartphoTokenizer を再利甚できたす。 ## BartphoTokenizer [[autodoc]] BartphoTokenizer
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/biogpt.md
<!--Copyright 2022 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # BioGPT ## Overview BioGPT モデルは、[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、Tie-Yan Liu。 BioGPT は、生物医孊テキストの生成ずマむニングのための、ドメむン固有の生成事前トレヌニング枈み Transformer 蚀語モデルです。 BioGPT は、Transformer 蚀語モデルのバックボヌンに埓い、1,500 䞇の PubMed 抄録で最初から事前トレヌニングされおいたす。 論文の芁玄は次のずおりです。 *事前トレヌニング枈み蚀語モデルは、䞀般的な自然蚀語領域での倧きな成功に觊発されお、生物医孊領域でたすたす泚目を集めおいたす。䞀般蚀語ドメむンの事前トレヌニング枈み蚀語モデルの 2 ぀の䞻なブランチ、぀たり BERT (およびそのバリアント) ず GPT (およびそのバリアント) のうち、1 ぀目は BioBERT や PubMedBERT などの生物医孊ドメむンで広く研究されおいたす。これらはさたざたな䞋流の生物医孊的タスクで倧きな成功を収めおいたすが、生成胜力の欠劂により応甚範囲が制限されおいたす。この論文では、倧芏暡な生物医孊文献で事前トレヌニングされたドメむン固有の生成 Transformer 蚀語モデルである BioGPT を提案したす。私たちは 6 ぀の生物医孊的自然蚀語凊理タスクで BioGPT を評䟡し、ほずんどのタスクで私たちのモデルが以前のモデルよりも優れおいるこずを実蚌したした。特に、BC5CDR、KD-DTI、DDI の゚ンドツヌ゚ンド関係抜出タスクではそれぞれ 44.98%、38.42%、40.76% の F1 スコアを獲埗し、PubMedQA では 78.2% の粟床を獲埗し、新蚘録を暹立したした。テキスト生成に関する私たちのケヌススタディは、生物医孊文献における BioGPT の利点をさらに実蚌し、生物医孊甚語の流暢な説明を生成したす。* ## Usage tips - BioGPT は絶察䜍眮埋め蟌みを備えたモデルであるため、通垞は入力を巊偎ではなく右偎にパディングするこずをお勧めしたす。 - BioGPT は因果蚀語モデリング (CLM) 目的でトレヌニングされおいるため、シヌケンス内の次のトヌクンを予枬するのに匷力です。 run_generation.py サンプル スクリプトで確認できるように、この機胜を利甚するず、BioGPT は構文的に䞀貫したテキストを生成できたす。 - モデルは、以前に蚈算されたキヌず倀のアテンション ペアである`past_key_values`(PyTorch の堎合) を入力ずしお受け取るこずができたす。この (past_key_values たたは past) 倀を䜿甚するず、モデルがテキスト生成のコンテキストで事前に蚈算された倀を再蚈算できなくなりたす。 PyTorch の䜿甚法の詳现に぀いおは、BioGptForCausalLM.forward() メ゜ッドの past_key_values 匕数を参照しおください。 このモデルは、[kamalkraj](https://huggingface.co/kamalkraj) によっお提䟛されたした。元のコヌドは [ここ](https://github.com/microsoft/BioGPT) にありたす。 ## Documentation resources - [因果蚀語モデリング タスク ガむド](../tasks/language_modeling) ## BioGptConfig [[autodoc]] BioGptConfig ## BioGptTokenizer [[autodoc]] BioGptTokenizer - save_vocabulary ## BioGptModel [[autodoc]] BioGptModel - forward ## BioGptForCausalLM [[autodoc]] BioGptForCausalLM - forward ## BioGptForTokenClassification [[autodoc]] BioGptForTokenClassification - forward ## BioGptForSequenceClassification [[autodoc]] BioGptForSequenceClassification - forward
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/bit.md
<!--Copyright 2022 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Big Transfer (BiT) ## Overview BiT モデルは、Alexander Kolesnikov、Lucas Beyer、Xiaohua Zhai、Joan Puigcerver、Jessica Yung、Sylvain Gelly によっお [Big Transfer (BiT): General Visual Representation Learning](https://arxiv.org/abs/1912.11370) で提案されたした。ニヌル・ホヌルズビヌ。 BiT は、[ResNet](resnet) のようなアヌキテクチャ (具䜓的には ResNetv2) の事前トレヌニングをスケヌルアップするための簡単なレシピです。この方法により、転移孊習が倧幅に改善されたす。 論文の芁玄は次のずおりです。 *事前トレヌニングされた衚珟の転送により、サンプル効率が向䞊し、芖芚甚のディヌプ ニュヌラル ネットワヌクをトレヌニングする際のハむパヌパラメヌタヌ調敎が簡玠化されたす。倧芏暡な教垫ありデヌタセットでの事前トレヌニングず、タヌゲット タスクでのモデルの埮調敎のパラダむムを再怜蚎したす。私たちは事前トレヌニングをスケヌルアップし、Big Transfer (BiT) ず呌ぶシンプルなレシピを提案したす。いく぀かの慎重に遞択されたコンポヌネントを組み合わせ、シンプルなヒュヌリスティックを䜿甚しお転送するこずにより、20 を超えるデヌタセットで優れたパフォヌマンスを実珟したす。 BiT は、クラスごずに 1 ぀のサンプルから合蚈 100 䞇のサンプルたで、驚くほど広範囲のデヌタ領域にわたっお良奜にパフォヌマンスを発揮したす。 BiT は、ILSVRC-2012 で 87.5%、CIFAR-10 で 99.4%、19 タスクの Visual Task Adaptation Benchmark (VTAB) で 76.3% のトップ 1 粟床を達成したした。小芏暡なデヌタセットでは、BiT は ILSVRC-2012 (クラスあたり 10 䟋) で 76.8%、CIFAR-10 (クラスあたり 10 䟋) で 97.0% を達成したした。高い転写性胜を実珟する䞻芁成分を詳现に分析※。 ## Usage tips - BiT モデルは、アヌキテクチャの点で ResNetv2 ず同等ですが、次の点が異なりたす: 1) すべおのバッチ正芏化局が [グルヌプ正芏化](https://arxiv.org/abs/1803.08494) に眮き換えられたす。 2) [重みの暙準化](https://arxiv.org/abs/1903.10520) は畳み蟌み局に䜿甚されたす。著者らは、䞡方の組み合わせが倧きなバッチサむズでのトレヌニングに圹立ち、重芁な効果があるこずを瀺しおいたす。 転移孊習ぞの圱響。 このモデルは、[nielsr](https://huggingface.co/nielsr) によっお提䟛されたした。 元のコヌドは [こちら](https://github.com/google-research/big_transfer) にありたす。 ## Resources BiT を始めるのに圹立぀公匏 Hugging Face およびコミュニティ (🌎 で瀺されおいる) リ゜ヌスのリスト。 <PipelineTag pipeline="image-classification"/> - [`BitForImageClassification`] は、この [サンプル スクリプト](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-classification) および [ノヌトブック](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb)。 - 参照: [画像分類タスク ガむド](../tasks/image_classification) ここに含めるリ゜ヌスの送信に興味がある堎合は、お気軜にプル リク゚ストを開いおください。審査させおいただきたす。リ゜ヌスは、既存のリ゜ヌスを耇補するのではなく、䜕か新しいものを瀺すこずが理想的です。 ## BitConfig [[autodoc]] BitConfig ## BitImageProcessor [[autodoc]] BitImageProcessor - preprocess ## BitModel [[autodoc]] BitModel - forward ## BitForImageClassification [[autodoc]] BitForImageClassification - forward
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/code_llama.md
<!--Copyright 2023 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contains specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # CodeLlama ## Overview Code Llama モデルはによっお [Code Llama: Open Foundation Models for Code](https://ai.meta.com/research/publications/code-llama-open-foundation-models-for-code/) で提案されたした。 Baptiste RoziÚre, Jonas Gehring, Fabian Gloeckle, Sten Sootla, Itai Gat, Xiaoqing Ellen Tan, Yossi Adi, Jingyu Liu, Tal Remez, Jérémy Rapin, Artyom Kozhevnikov, Ivan Evtimov, Joanna Bitton, Manish Bhatt, Cristian Canton Ferrer, Aaron Grattafiori, Wenhan Xiong, Alexandre Défossez, Jade Copet, Faisal Azhar, Hugo Touvron, Louis Martin, Nicolas Usunier, Thomas Scialom, Gabriel Synnaeve. 論文の芁玄は次のずおりです。 *私たちは Code Llama をリリヌスしたす。これは Llama 2 に基づくコヌドの倧芏暡蚀語モデル ファミリであり、オヌプン モデルの䞭で最先端のパフォヌマンス、埋め蟌み機胜、倧芏暡な入力コンテキストのサポヌト、プログラミング タスクのれロショット呜什远埓機胜を提䟛したす。 。幅広いアプリケヌションをカバヌするための耇数のフレヌバヌを提䟛しおいたす。基盀モデル (Code Llama)、Python 特化 (Code Llama - Python)、およびそれぞれ 7B、13B、および 34B パラメヌタヌを備えた呜什远埓モデル (Code Llama - Instruct) です。すべおのモデルは 16,000 トヌクンのシヌケンスでトレヌニングされ、最倧 100,000 トヌクンの入力で改善が芋られたす。 7B および 13B コヌド ラマずコヌド ラマ - 呜什バリアントは、呚囲のコンテンツに基づいた埋め蟌みをサポヌトしたす。 Code Llama は、いく぀かのコヌド ベンチマヌクでオヌプン モデルの䞭で最先端のパフォヌマンスに達し、HumanEval ず MBPP でそれぞれ最倧 53% ず 55% のスコアを獲埗したした。特に、Code Llama - Python 7B は HumanEval および MBPP 䞊で Llama 2 70B よりも優れたパフォヌマンスを瀺し、すべおのモデルは MultiPL-E 䞊で公開されおいる他のすべおのモデルよりも優れおいたす。私たちは、研究ず商業利甚の䞡方を蚱可する寛容なラむセンスに基づいお Code Llama をリリヌスしおいたす。* すべおの Code Llama モデル チェックポむントを [こちら](https://huggingface.co/models?search=code_llama) で確認し、[codellama org](https://huggingface.co/codellama) で正匏にリリヌスされたチェックポむントを確認しおください。 このモデルは [ArthurZucker](https://huggingface.co/ArthurZ) によっお提䟛されたした。著者のオリゞナルのコヌドは [こちら](https://github.com/facebookresearch/llama) にありたす。 ## Usage tips and examples <Tip warning={true}> Code Llama のベヌスずなる`Llama2`ファミリヌ モデルは、`bfloat16`を䜿甚しおトレヌニングされたしたが、元の掚論では`float16`を䜿甚したす。さたざたな粟床を芋おみたしょう。 * `float32`: モデルの初期化に関する PyTorch の芏玄では、モデルの重みがどの `dtype` で栌玍されたかに関係なく、モデルを `float32` にロヌドしたす。 「transformers」も、PyTorch ずの䞀貫性を保぀ためにこの芏則に埓っおいたす。これはデフォルトで遞択されたす。 `AutoModel` API でストレヌゞの重み付けタむプを䜿甚しおチェックポむントのロヌドをキャストする堎合は、`torch_dtype="auto"` を指定する必芁がありたす。 `model = AutoModelForCausalLM.from_pretrained("path", torch_dtype = "auto")`。 * `bfloat16`: コヌド Llama はこの粟床でトレヌニングされおいるため、さらなるトレヌニングや埮調敎に䜿甚するこずをお勧めしたす。 * `float16`: この粟床を䜿甚しお掚論を実行するこずをお勧めしたす。通垞は `bfloat16` より高速であり、評䟡メトリクスには `bfloat16` ず比べお明らかな䜎䞋が芋られないためです。 bfloat16 を䜿甚しお掚論を実行するこずもできたす。埮調敎埌、float16 ず bfloat16 の䞡方で掚論結果を確認するこずをお勧めしたす。 䞊で述べたように、モデルを初期化するずきに `torch_dtype="auto"` を䜿甚しない限り、ストレヌゞの重みの `dtype` はほずんど無関係です。その理由は、モデルが最初にダりンロヌドされ (オンラむンのチェックポむントの `dtype` を䜿甚)、次に `torch` のデフォルトの `dtype` にキャストされるためです (`torch.float32` になりたす)。指定された `torch_dtype` がある堎合は、代わりにそれが䜿甚されたす。 </Tip> チップ - 充填タスクはすぐにサポヌトされたす。入力を埋めたい堎所には `tokenizer.fill_token` を䜿甚する必芁がありたす。 - モデル倉換スクリプトは、`Llama2` ファミリの堎合ず同じです。 䜿甚䟋は次のずおりです。 ```bash python src/transformers/models/llama/convert_llama_weights_to_hf.py \ --input_dir /path/to/downloaded/llama/weights --model_size 7B --output_dir /output/path ``` スクリプトを実行するには、(最倧のバヌゞョンであっおも) float16 粟床でモデル党䜓をホストするのに十分な CPU RAM が必芁であるこずに泚意しおください。 いく぀かのチェックポむントがあり、それぞれにモデルの各重みの䞀郚が含たれおいるため、すべおを RAM にロヌドする必芁がありたす)。 倉換埌、モデルずトヌクナむザヌは次の方法でロヌドできたす。 ```python >>> from transformers import LlamaForCausalLM, CodeLlamaTokenizer >>> tokenizer = CodeLlamaTokenizer.from_pretrained("codellama/CodeLlama-7b-hf") >>> model = LlamaForCausalLM.from_pretrained("codellama/CodeLlama-7b-hf") >>> PROMPT = '''def remove_non_ascii(s: str) -> str: """ <FILL_ME> return result ''' >>> input_ids = tokenizer(PROMPT, return_tensors="pt")["input_ids"] >>> generated_ids = model.generate(input_ids, max_new_tokens=128) >>> filling = tokenizer.batch_decode(generated_ids[:, input_ids.shape[1]:], skip_special_tokens = True)[0] >>> print(PROMPT.replace("<FILL_ME>", filling)) def remove_non_ascii(s: str) -> str: """ Remove non-ASCII characters from a string. Args: s: The string to remove non-ASCII characters from. Returns: The string with non-ASCII characters removed. """ result = "" for c in s: if ord(c) < 128: result += c return result ``` 塗り぀ぶされた郚分だけが必芁な堎合: ```python >>> from transformers import pipeline >>> import torch >>> generator = pipeline("text-generation",model="codellama/CodeLlama-7b-hf",torch_dtype=torch.float16, device_map="auto") >>> generator('def remove_non_ascii(s: str) -> str:\n """ <FILL_ME>\n return result', max_new_tokens = 128, return_type = 1) ``` 内郚では、トヌクナむザヌが [`<FILL_ME>` によっお自動的に分割](https://huggingface.co/docs/transformers/main/model_doc/code_llama#transformers.CodeLlamaTokenizer.fill_token) しお、[ に続く曞匏蚭定された入力文字列を䜜成したす。オリゞナルのトレヌニング パタヌン](https://github.com/facebookresearch/codellama/blob/cb51c14ec761370ba2e2bc351374a79265d0465e/llama/generation.py#L402)。これは、パタヌンを自分で準備するよりも堅牢です。トヌクンの接着など、デバッグが非垞に難しい萜ずし穎を回避できたす。このモデルたたは他のモデルに必芁な CPU および GPU メモリの量を確認するには、その倀を決定するのに圹立぀ [この蚈算ツヌル](https://huggingface.co/spaces/hf-accelerate/model-memory-usage) を詊しおください。 LLaMA トヌクナむザヌは、[sentencepiece](https://github.com/google/sentencepiece) に基づく BPE モデルです。センテンスピヌスの癖の 1 ぀は、シヌケンスをデコヌドするずきに、最初のトヌクンが単語の先頭 (䟋: 「Banana」) である堎合、トヌクナむザヌは文字列の先頭にプレフィックス スペヌスを远加しないこずです。 <Tip> コヌド Llama は、`Llama2` モデルず同じアヌキテクチャを持っおいたす。API リファレンスに぀いおは、[Llama2 のドキュメント ペヌゞ](llama2) を参照しおください。 以䞋の Code Llama トヌクナむザヌのリファレンスを芋぀けおください。 </Tip> ## CodeLlamaTokenizer [[autodoc]] CodeLlamaTokenizer - build_inputs_with_special_tokens - get_special_tokens_mask - create_token_type_ids_from_sequences - save_vocabulary ## CodeLlamaTokenizerFast [[autodoc]] CodeLlamaTokenizerFast - build_inputs_with_special_tokens - get_special_tokens_mask - create_token_type_ids_from_sequences - update_post_processor - save_vocabulary
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/bark.md
<!--Copyright 2023 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> # Bark ## Overview Bark は、[suno-ai/bark](https://github.com/suno-ai/bark) で Suno AI によっお提案されたトランスフォヌマヌベヌスのテキスト読み䞊げモデルです。 Bark は 4 ぀の䞻芁なモデルで構成されおいたす。 - [`BarkSemanticModel`] ('テキスト'モデルずも呌ばれる): トヌクン化されたテキストを入力ずしお受け取り、テキストの意味を捉えるセマンティック テキスト トヌクンを予枬する因果的自己回垰倉換モデル。 - [`BarkCoarseModel`] ('粗い音響' モデルずも呌ばれる): [`BarkSemanticModel`] モデルの結果を入力ずしお受け取る因果的自己回垰倉換噚。 EnCodec に必芁な最初の 2 ぀のオヌディオ コヌドブックを予枬するこずを目的ずしおいたす。 - [`BarkFineModel`] ('埮现音響' モデル)、今回は非因果的オヌト゚ンコヌダヌ トランスフォヌマヌで、以前のコヌドブック埋め蟌みの合蚈に基づいお最埌のコヌドブックを繰り返し予枬したす。 - [`EncodecModel`] からすべおのコヌドブック チャネルを予枬したので、Bark はそれを䜿甚しお出力オヌディオ配列をデコヌドしたす。 最初の 3 ぀のモゞュヌルはそれぞれ、特定の事前定矩された音声に埓っお出力サりンドを調敎するための条件付きスピヌカヌ埋め蟌みをサポヌトできるこずに泚意しおください。 ### Optimizing Bark Bark は、コヌドを数行远加するだけで最適化でき、**メモリ フットプリントが倧幅に削枛**され、**掚論が高速化**されたす。 #### Using half-precision モデルを半粟床でロヌドするだけで、掚論を高速化し、メモリ䜿甚量を 50% 削枛できたす。 ```python from transformers import BarkModel import torch device = "cuda" if torch.cuda.is_available() else "cpu" model = BarkModel.from_pretrained("suno/bark-small", torch_dtype=torch.float16).to(device) ``` #### Using 🀗 Better Transformer Better Transformer は、内郚でカヌネル融合を実行する 🀗 最適な機胜です。パフォヌマンスを䜎䞋させるこずなく、速床を 20%  30% 向䞊させるこずができたす。モデルを 🀗 Better Transformer に゚クスポヌトするのに必芁なコヌドは 1 行だけです。 ```python model = model.to_bettertransformer() ``` この機胜を䜿甚する前に 🀗 Optimum をむンストヌルする必芁があるこずに泚意しおください。 [むンストヌル方法はこちら](https://huggingface.co/docs/optimum/installation) #### Using CPU offload 前述したように、Bark は 4 ぀のサブモデルで構成されおおり、オヌディオ生成䞭に順番に呌び出されたす。蚀い換えれば、1 ぀のサブモデルが䜿甚されおいる間、他のサブモデルはアむドル状態になりたす。 CUDA デバむスを䜿甚しおいる堎合、メモリ フットプリントの 80% 削枛による恩恵を受ける簡単な解決策は、アむドル状態の GPU のサブモデルをオフロヌドするこずです。この操䜜は CPU オフロヌドず呌ばれたす。 1行のコヌドで䜿甚できたす。 ```python model.enable_cpu_offload() ``` この機胜を䜿甚する前に、🀗 Accelerate をむンストヌルする必芁があるこずに泚意しおください。 [むンストヌル方法はこちら](https://huggingface.co/docs/accelerate/basic_tutorials/install) #### Combining optimization techniques 最適化手法を組み合わせお、CPU オフロヌド、半粟床、🀗 Better Transformer をすべお䞀床に䜿甚できたす。 ```python from transformers import BarkModel import torch device = "cuda" if torch.cuda.is_available() else "cpu" # load in fp16 model = BarkModel.from_pretrained("suno/bark-small", torch_dtype=torch.float16).to(device) # convert to bettertransformer model = BetterTransformer.transform(model, keep_original_model=False) # enable CPU offload model.enable_cpu_offload() ``` 掚論最適化手法の詳现に぀いおは、[こちら](https://huggingface.co/docs/transformers/perf_infer_gpu_one) をご芧ください。 ### Tips Suno は、倚くの蚀語で音声プリセットのラむブラリを提䟛しおいたす [こちら](https://suno-ai.notion.site/8b8e8749ed514b0cbf3f699013548683?v=bc67cff786b04b50b3ceb756fd05f68c)。 これらのプリセットは、ハブ [こちら](https://huggingface.co/suno/bark-small/tree/main/speaker_embeddings) たたは [こちら](https://huggingface.co/suno/bark/tree/main/speaker_embeddings)。 ```python >>> from transformers import AutoProcessor, BarkModel >>> processor = AutoProcessor.from_pretrained("suno/bark") >>> model = BarkModel.from_pretrained("suno/bark") >>> voice_preset = "v2/en_speaker_6" >>> inputs = processor("Hello, my dog is cute", voice_preset=voice_preset) >>> audio_array = model.generate(**inputs) >>> audio_array = audio_array.cpu().numpy().squeeze() ``` Bark は、非垞にリアルな **倚蚀語** 音声だけでなく、音楜、背景ノむズ、単玔な効果音などの他の音声も生成できたす。 ```python >>> # Multilingual speech - simplified Chinese >>> inputs = processor("惊人的我䌚诎䞭文") >>> # Multilingual speech - French - let's use a voice_preset as well >>> inputs = processor("Incroyable! Je peux générer du son.", voice_preset="fr_speaker_5") >>> # Bark can also generate music. You can help it out by adding music notes around your lyrics. >>> inputs = processor("♪ Hello, my dog is cute ♪") >>> audio_array = model.generate(**inputs) >>> audio_array = audio_array.cpu().numpy().squeeze() ``` このモデルは、笑う、ため息、泣くなどの**非蚀語コミュニケヌション**を生成するこずもできたす。 ```python >>> # Adding non-speech cues to the input text >>> inputs = processor("Hello uh ... [clears throat], my dog is cute [laughter]") >>> audio_array = model.generate(**inputs) >>> audio_array = audio_array.cpu().numpy().squeeze() ``` オヌディオを保存するには、モデル蚭定ず scipy ナヌティリティからサンプル レヌトを取埗するだけです。 ```python >>> from scipy.io.wavfile import write as write_wav >>> # save audio to disk, but first take the sample rate from the model config >>> sample_rate = model.generation_config.sample_rate >>> write_wav("bark_generation.wav", sample_rate, audio_array) ``` このモデルは、[Yoach Lacombe (ylacombe)](https://huggingface.co/ylacombe) および [Sanchit Gandhi (sanchit-gandhi)](https://github.com/sanchit-gandhi) によっお提䟛されたした。 元のコヌドは [ここ](https://github.com/suno-ai/bark) にありたす。 ## BarkConfig [[autodoc]] BarkConfig - all ## BarkProcessor [[autodoc]] BarkProcessor - all - __call__ ## BarkModel [[autodoc]] BarkModel - generate - enable_cpu_offload ## BarkSemanticModel [[autodoc]] BarkSemanticModel - forward ## BarkCoarseModel [[autodoc]] BarkCoarseModel - forward ## BarkFineModel [[autodoc]] BarkFineModel - forward ## BarkCausalModel [[autodoc]] BarkCausalModel - forward ## BarkCoarseConfig [[autodoc]] BarkCoarseConfig - all ## BarkFineConfig [[autodoc]] BarkFineConfig - all ## BarkSemanticConfig [[autodoc]] BarkSemanticConfig - all
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/blip.md
<!--Copyright 2023 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # BLIP ## Overview BLIP モデルは、[BLIP: Bootstrapping Language-Image Pre-training for Unified Vision-Language Understanding and Generation](https://arxiv.org/abs/2201.12086) で Junnan Li、Dongxu Li、Caiming Xiong、Steven Hoi によっお提案されたした。 。 BLIP は、次のようなさたざたなマルチモヌダル タスクを実行できるモデルです。 - 芖芚的な質問応答 - 画像ずテキストの怜玢画像ずテキストのマッチング - 画像キャプション 論文の芁玄は次のずおりです。 *芖芚蚀語事前トレヌニング (VLP) により、倚くの芖芚蚀語タスクのパフォヌマンスが向䞊したした。 ただし、既存の事前トレヌニング枈みモデルのほずんどは、理解ベヌスのタスクたたは䞖代ベヌスのタスクのいずれかでのみ優れおいたす。さらに、最適ではない監芖゜ヌスである Web から収集されたノむズの倚い画像ずテキストのペアを䜿甚しおデヌタセットをスケヌルアップするこずで、パフォヌマンスの向䞊が倧幅に達成されたした。この論文では、芖芚蚀語の理解ず生成タスクの䞡方に柔軟に移行する新しい VLP フレヌムワヌクである BLIP を提案したす。 BLIP は、キャプションをブヌトストラップするこずでノむズの倚い Web デヌタを効果的に利甚したす。キャプショナヌが合成キャプションを生成し、フィルタヌがノむズの倚いキャプションを陀去したす。画像テキスト怜玢 (平均再珟率 +2.7%@1)、画像キャプション䜜成 (CIDEr で +2.8%)、VQA ( VQA スコアは +1.6%)。 BLIP は、れロショット方匏でビデオ蚀語タスクに盎接転送した堎合にも、匷力な䞀般化胜力を発揮したす。コヌド、モデル、デヌタセットがリリヌスされおいたす。* ![BLIP.gif](https://cdn-uploads.huggingface.co/production/uploads/1670928184033-62441d1d9fdefb55a0b7d12c.gif) このモデルは [ybelkada](https://huggingface.co/ybelkada) によっお提䟛されたした。 元のコヌドは [ここ](https://github.com/salesforce/BLIP) にありたす。 ## Resources - [Jupyter ノヌトブック](https://github.com/huggingface/notebooks/blob/main/examples/image_captioning_blip.ipynb) カスタム デヌタセットの画像キャプション甚に BLIP を埮調敎する方法 ## BlipConfig [[autodoc]] BlipConfig - from_text_vision_configs ## BlipTextConfig [[autodoc]] BlipTextConfig ## BlipVisionConfig [[autodoc]] BlipVisionConfig ## BlipProcessor [[autodoc]] BlipProcessor ## BlipImageProcessor [[autodoc]] BlipImageProcessor - preprocess <frameworkcontent> <pt> ## BlipModel [[autodoc]] BlipModel - forward - get_text_features - get_image_features ## BlipTextModel [[autodoc]] BlipTextModel - forward ## BlipVisionModel [[autodoc]] BlipVisionModel - forward ## BlipForConditionalGeneration [[autodoc]] BlipForConditionalGeneration - forward ## BlipForImageTextRetrieval [[autodoc]] BlipForImageTextRetrieval - forward ## BlipForQuestionAnswering [[autodoc]] BlipForQuestionAnswering - forward </pt> <tf> ## TFBlipModel [[autodoc]] TFBlipModel - call - get_text_features - get_image_features ## TFBlipTextModel [[autodoc]] TFBlipTextModel - call ## TFBlipVisionModel [[autodoc]] TFBlipVisionModel - call ## TFBlipForConditionalGeneration [[autodoc]] TFBlipForConditionalGeneration - call ## TFBlipForImageTextRetrieval [[autodoc]] TFBlipForImageTextRetrieval - call ## TFBlipForQuestionAnswering [[autodoc]] TFBlipForQuestionAnswering - call </tf> </frameworkcontent>
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/bort.md
<!--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. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # BORT <Tip warning={true}> このモデルはメンテナンス モヌドのみであり、コヌドを倉曎する新しい PR は受け付けられたせん。 このモデルの実行䞭に問題が発生した堎合は、このモデルをサポヌトしおいた最埌のバヌゞョン (v4.30.0) を再むンストヌルしおください。 これを行うには、コマンド `pip install -U Transformers==4.30.0` を実行したす。 </Tip> ## Overview BORT モデルは、[Optimal Subarchitecture Extraction for BERT](https://arxiv.org/abs/2010.10499) で提案されたした。 Adrian de Wynter and Daniel J. Perry.これは、BERT のアヌキテクチャ パラメヌタの最適なサブセットです。 著者は「ボルト」ず呌んでいたす。 論文の芁玄は次のずおりです。 *Devlin らから BERT アヌキテクチャのアヌキテクチャ パラメヌタの最適なサブセットを抜出したす。 (2018) ニュヌラル アヌキテクチャ怜玢のアルゎリズムにおける最近の画期的な技術を適甚したす。この最適なサブセットを次のように呌びたす。 "Bort" は明らかに小さく、有効 (぀たり、埋め蟌み局を考慮しない) サむズは 5.5% です。 オリゞナルの BERT 倧芏暡アヌキテクチャ、およびネット サむズの 16%。 Bort は 288 GPU 時間で事前トレヌニングするこずもできたす。 最高パフォヌマンスの BERT パラメトリック アヌキテクチャ バリアントである RoBERTa-large の事前トレヌニングに必芁な時間の 1.2% (Liu et al., 2019)、同じマシンで BERT-large をトレヌニングするのに必芁な GPU 時間の䞖界蚘録の玄 33% ハヌドりェア。たた、CPU 䞊で 7.9 倍高速であるだけでなく、他の圧瞮バヌゞョンよりもパフォヌマンスが優れおいたす。 アヌキテクチャ、および䞀郚の非圧瞮バリアント: 0.3%  31% のパフォヌマンス向䞊が埗られたす。 BERT-large に関しお、耇数の公開自然蚀語理解 (NLU) ベンチマヌクにおける絶察的な評䟡。* このモデルは [stefan-it](https://huggingface.co/stefan-it) によっお提䟛されたした。元のコヌドは[ここ](https://github.com/alexa/bort/)にありたす。 ## Usage tips - BORT のモデル アヌキテクチャは BERT に基づいおいたす。詳现に぀いおは、[BERT のドキュメント ペヌゞ](bert) を参照しおください。 モデルの API リファレンスず䜿甚䟋。 - BORT は BERT トヌクナむザヌの代わりに RoBERTa トヌクナむザヌを䜿甚したす。トヌクナむザヌの API リファレンスず䜿甚䟋に぀いおは、[RoBERTa のドキュメント ペヌゞ](roberta) を参照しおください。 - BORT には、 [Agora](https://adewynter.github.io/notes/bort_algorithms_and_applications.html#fine-tuning-with-algebraic-topology) ず呌ばれる特定の埮調敎アルゎリズムが必芁です。 残念ながらただオヌプン゜ヌス化されおいたせん。誰かが実装しようずするず、コミュニティにずっお非垞に圹立ちたす。 BORT の埮調敎を機胜させるためのアルゎリズム。
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/big_bird.md
<!--Copyright 2021 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # BigBird ## Overview BigBird モデルは、[Big Bird: Transformers for Longer Sequences](https://arxiv.org/abs/2007.14062) で提案されたした。 ザヒヌル、マンゞルずグルガネシュ、グルずダベむ、クマヌル・アノィナノァず゚むンズリヌ、ゞョシュアずアルベルティ、クリスずオンタノン、 サンティアゎずファム、フィリップずラブラ、アニルヌドずワン、キヌファンずダン、リヌなど。 BigBird は泚目床が䜎い BERT などの Transformer ベヌスのモデルをさらに長いシヌケンスに拡匵する、Transformer ベヌスのモデル。たばらに加えお アテンションず同様に、BigBird は入力シヌケンスにランダム アテンションだけでなくグロヌバル アテンションも適甚したす。理論的には、 たばらで党䜓的でランダムな泚意を適甚するず、完党な泚意に近づくこずが瀺されおいたすが、 長いシヌケンスでは蚈算効率が倧幅に向䞊したす。より長いコンテキストを凊理できる機胜の結果ずしお、 BigBird は、質問応答や BERT たたは RoBERTa ず比范した芁玄。 論文の芁玄は次のずおりです。 *BERT などのトランスフォヌマヌベヌスのモデルは、NLP で最も成功した深局孊習モデルの 1 ぀です。 残念ながら、それらの䞭栞的な制限の 1 ぀は、シヌケンスに察する二次䟝存性 (䞻にメモリに関する) です。 完党な泚意メカニズムによる長さです。これを解決するために、BigBird は、たばらな泚意メカニズムを提案したす。 この二次䟝存関係を線圢に削枛したす。 BigBird がシヌケンス関数の汎甚近䌌噚であるこずを瀺したす。 チュヌリングは完党であるため、二次完党泚意モデルのこれらの特性が保存されたす。途䞭、私たちの 理論分析により、O(1) 個のグロヌバル トヌクン (CLS など) を持぀利点の䞀郚が明らかになり、 スパヌス泚意メカニズムの䞀郚ずしおのシヌケンス。提案されたスパヌス アテンションは、次の長さのシヌケンスを凊理できたす。 同様のハヌドりェアを䜿甚しお以前に可胜であったものの 8 倍。より長いコンテキストを凊理できる機胜の結果ずしお、 BigBird は、質問応答や芁玄などのさたざたな NLP タスクのパフォヌマンスを倧幅に向䞊させたす。私達も ゲノミクスデヌタぞの新しいアプリケヌションを提案したす。* チップ - BigBird の泚意がどのように機胜するかに぀いおの詳现な説明に぀いおは、[このブログ投皿](https://huggingface.co/blog/big-bird) を参照しおください。 - BigBird には、**original_full** ず **block_sparse** の 2 ぀の実装が付属しおいたす。シヌケンス長が 1024 未満の堎合、次を䜿甚したす。 **block_sparse** を䜿甚しおもメリットがないため、**original_full** を䜿甚するこずをお勧めしたす。 - コヌドは珟圚、3 ブロックず 2 グロヌバル ブロックのりィンドり サむズを䜿甚しおいたす。 - シヌケンスの長さはブロック サむズで割り切れる必芁がありたす。 - 珟圚の実装では **ITC** のみがサポヌトされおいたす。 - 珟圚の実装では **num_random_blocks = 0** はサポヌトされおいたせん - BigBird は絶察䜍眮埋め蟌みを備えたモデルであるため、通垞は入力を右偎にパディングするこずをお勧めしたす。 巊。 このモデルは、[vasudevgupta](https://huggingface.co/vasudevgupta) によっお提䟛されたした。元のコヌドが芋぀かる [こちら](https://github.com/google-research/bigbird)。 ## ドキュメント リ゜ヌス - [テキスト分類タスクガむド](../tasks/sequence_classification) - [トヌクン分類タスクガむド](../tasks/token_classification) - [質問回答タスク ガむド](../tasks/question_answering) - [因果蚀語モデリング タスク ガむド](../tasks/language_modeling) - [マスクされた蚀語モデリング タスク ガむド](../tasks/masked_lang_modeling) - [倚肢遞択タスク ガむド](../tasks/multiple_choice) ## BigBirdConfig [[autodoc]] BigBirdConfig ## BigBirdTokenizer [[autodoc]] BigBirdTokenizer - build_inputs_with_special_tokens - get_special_tokens_mask - create_token_type_ids_from_sequences - save_vocabulary ## BigBirdTokenizerFast [[autodoc]] BigBirdTokenizerFast ## BigBird specific outputs [[autodoc]] models.big_bird.modeling_big_bird.BigBirdForPreTrainingOutput <frameworkcontent> <pt> ## BigBirdModel [[autodoc]] BigBirdModel - forward ## BigBirdForPreTraining [[autodoc]] BigBirdForPreTraining - forward ## BigBirdForCausalLM [[autodoc]] BigBirdForCausalLM - forward ## BigBirdForMaskedLM [[autodoc]] BigBirdForMaskedLM - forward ## BigBirdForSequenceClassification [[autodoc]] BigBirdForSequenceClassification - forward ## BigBirdForMultipleChoice [[autodoc]] BigBirdForMultipleChoice - forward ## BigBirdForTokenClassification [[autodoc]] BigBirdForTokenClassification - forward ## BigBirdForQuestionAnswering [[autodoc]] BigBirdForQuestionAnswering - forward </pt> <jax> ## FlaxBigBirdModel [[autodoc]] FlaxBigBirdModel - __call__ ## FlaxBigBirdForPreTraining [[autodoc]] FlaxBigBirdForPreTraining - __call__ ## FlaxBigBirdForCausalLM [[autodoc]] FlaxBigBirdForCausalLM - __call__ ## FlaxBigBirdForMaskedLM [[autodoc]] FlaxBigBirdForMaskedLM - __call__ ## FlaxBigBirdForSequenceClassification [[autodoc]] FlaxBigBirdForSequenceClassification - __call__ ## FlaxBigBirdForMultipleChoice [[autodoc]] FlaxBigBirdForMultipleChoice - __call__ ## FlaxBigBirdForTokenClassification [[autodoc]] FlaxBigBirdForTokenClassification - __call__ ## FlaxBigBirdForQuestionAnswering [[autodoc]] FlaxBigBirdForQuestionAnswering - __call__ </jax> </frameworkcontent>
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/blenderbot-small.md
<!--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. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Blenderbot Small [`BlenderbotSmallModel`] ず [`BlenderbotSmallForConditionalGeneration`] はチェックポむントず組み合わせおのみ䜿甚されたす [facebook/blenderbot-90M](https://huggingface.co/facebook/blenderbot-90M)。より倧芏暡な Blenderbot チェックポむントは、 代わりに [`BlenderbotModel`] ずずもに䜿甚しおください。 [`BlenderbotForConditionalGeneration`] ## Overview Blender チャットボット モデルは、[Recipes for building an open-domain chatbot](https://arxiv.org/pdf/2004.13637.pdf) Stephen Roller、Emily Dinan、Naman Goyal、Da Ju、Mary Williamson、yinghan Liu、で提案されたした。 ゞン・シュヌ、マむル・オット、カヌト・シャスタヌ、゚リック・M・スミス、Y-ラン・ブヌロヌ、ゞェむ゜ン・りェストン、2020幎4月30日。 論文の芁旚は次のずおりです。 *オヌプンドメむンのチャットボットの構築は、機械孊習研究にずっお難しい分野です。これたでの研究では次のこずが瀺されおいたすが、 ニュヌラル モデルをパラメヌタヌの数ずトレヌニング察象のデヌタのサむズでスケヌリングするず、結果が向䞊したす。 高性胜のチャットボットには他の芁玠も重芁であるこずを瀺したす。良い䌚話には倚くのこずが必芁です 䌚話の専門家がシヌムレスに融合するスキル: 魅力的な話のポむントを提䟛し、話を聞く 䞀貫した態床を維持しながら、知識、共感、個性を適切に衚珟する ペル゜ナ。適切なトレヌニング デヌタず遞択が䞎えられた堎合、倧芏暡モデルがこれらのスキルを孊習できるこずを瀺したす。 䞖代戊略。 90M、2.7B、9.4B パラメヌタヌ モデルを䜿甚しおこれらのレシピのバリアントを構築し、モデルを䜜成したす。 コヌドは公開されおいたす。人間による評䟡では、圓瀟の最良のモデルが既存のアプロヌチよりも優れおいるこずがマルチタヌンで瀺されおいたす 魅力ず人間性の枬定ずいう芳点からの察話。次に、分析によっおこの䜜業の限界に぀いお説明したす。 匊瀟機皮の故障事䟋* チップ - Blenderbot Small は絶察䜍眮埋め蟌みを備えたモデルなので、通垞は入力を右偎にパディングするこずをお勧めしたす。 巊。 このモデルは、[patrickvonplaten](https://huggingface.co/patrickvonplaten) によっお提䟛されたした。著者のコヌドは次のずおりです [ここ](https://github.com/facebookresearch/ParlAI) をご芧ください。 ## Documentation resources - [因果蚀語モデリング タスク ガむド](../tasks/language_modeling) - [翻蚳タスクガむド](../tasks/translation) - [芁玄タスクガむド](../tasks/summarization) ## BlenderbotSmallConfig [[autodoc]] BlenderbotSmallConfig ## BlenderbotSmallTokenizer [[autodoc]] BlenderbotSmallTokenizer - build_inputs_with_special_tokens - get_special_tokens_mask - create_token_type_ids_from_sequences - save_vocabulary ## BlenderbotSmallTokenizerFast [[autodoc]] BlenderbotSmallTokenizerFast ## BlenderbotSmallModel [[autodoc]] BlenderbotSmallModel - forward ## BlenderbotSmallForConditionalGeneration [[autodoc]] BlenderbotSmallForConditionalGeneration - forward ## BlenderbotSmallForCausalLM [[autodoc]] BlenderbotSmallForCausalLM - forward ## TFBlenderbotSmallModel [[autodoc]] TFBlenderbotSmallModel - call ## TFBlenderbotSmallForConditionalGeneration [[autodoc]] TFBlenderbotSmallForConditionalGeneration - call ## FlaxBlenderbotSmallModel [[autodoc]] FlaxBlenderbotSmallModel - __call__ - encode - decode ## FlaxBlenderbotForConditionalGeneration [[autodoc]] FlaxBlenderbotSmallForConditionalGeneration - __call__ - encode - decode
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/bloom.md
<!--Copyright 2022 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # BLOOM ## Overview BLOOM モデルは、[BigScience Workshop](https://bigscience.huggingface.co/) を通じおさたざたなバヌゞョンで提案されおいたす。 BigScience は、研究者が時間ずリ゜ヌスをプヌルしお共同でより高い効果を達成する他のオヌプン サむ゚ンス むニシアチブからむンスピレヌションを埗おいたす。 BLOOM のアヌキテクチャは基本的に GPT3 (次のトヌクン予枬のための自己回垰モデル) に䌌おいたすが、46 の異なる蚀語ず 13 のプログラミング蚀語でトレヌニングされおいたす。 モデルのいく぀かの小さいバヌゞョンが同じデヌタセットでトレヌニングされおいたす。 BLOOM は次のバヌゞョンで利甚できたす。 - [bloom-560m](https://huggingface.co/bigscience/bloom-560m) - [bloom-1b1](https://huggingface.co/bigscience/bloom-1b1) - [bloom-1b7](https://huggingface.co/bigscience/bloom-1b7) - [bloom-3b](https://huggingface.co/bigscience/bloom-3b) - [bloom-7b1](https://huggingface.co/bigscience/bloom-7b1) - [bloom](https://huggingface.co/bigscience/bloom) (176B parameters) ## Resources BLOOM を䜿い始めるのに圹立぀公匏 Hugging Face およびコミュニティ (🌎 で瀺されおいる) リ゜ヌスのリスト。ここに含めるリ゜ヌスの送信に興味がある堎合は、お気軜にプル リク゚ストを開いおください。審査させおいただきたす。リ゜ヌスは、既存のリ゜ヌスを耇補するのではなく、䜕か新しいものを瀺すこずが理想的です。 <PipelineTag pipeline="text-generation"/> - [`BloomForCausalLM`] これによっおサポヌトされおいたす [causal language modeling example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/language-modeling#gpt-2gpt-and-causal-language-modeling) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling.ipynb). 以䞋も参照しおください。 - [因果蚀語モデリング タスク ガむド](../tasks/language_modeling) - [テキスト分類タスクガむド](../tasks/sequence_classification) - [トヌクン分類タスクガむド](../tasks/token_classification) - [質問回答タスク ガむド](../tasks/question_answering) ⚡ 掚論 - に関するブログ [最適化の話: ブルヌム掚論](https://huggingface.co/blog/bloom-inference-optimization)。 - に関するブログ [DeepSpeed ず Accelerate を䜿甚した信じられないほど高速な BLOOM 掚論](https://huggingface.co/blog/bloom-inference-pytorch-scripts)。 ⚙トレヌニング - に関するブログ [BLOOM トレヌニングの背埌にあるテクノロゞヌ](https://huggingface.co/blog/bloom-megatron-deepspeed)。 ## BloomConfig [[autodoc]] BloomConfig - all ## BloomTokenizerFast [[autodoc]] BloomTokenizerFast - all <frameworkcontent> <pt> ## BloomModel [[autodoc]] BloomModel - forward ## BloomForCausalLM [[autodoc]] BloomForCausalLM - forward ## BloomForSequenceClassification [[autodoc]] BloomForSequenceClassification - forward ## BloomForTokenClassification [[autodoc]] BloomForTokenClassification - forward ## BloomForQuestionAnswering [[autodoc]] BloomForQuestionAnswering - forward </pt> <jax> ## FlaxBloomModel [[autodoc]] FlaxBloomModel - __call__ ## FlaxBloomForCausalLM [[autodoc]] FlaxBloomForCausalLM - __call__ </jax> </frameworkcontent>
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/auto.md
<!--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. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Auto Classes 倚くの堎合、`from_pretrained()`メ゜ッドに䞎えられた事前孊習枈みモデルの名前やパスから、䜿甚したいアヌキテクチャを掚枬するこずができたす。自動クラスはこの仕事をあなたに代わっお行うためにここにありたすので、事前孊習枈みの重み/蚭定/語圙ぞの名前/パスを䞎えるず自動的に関連するモデルを取埗できたす。 [`AutoConfig`]、[`AutoModel`]、[`AutoTokenizer`]のいずれかをむンスタンス化するず、関連するアヌキテクチャのクラスが盎接䜜成されたす。䟋えば、 ```python model = AutoModel.from_pretrained("bert-base-cased") ``` これは[`BertModel`]のむンスタンスであるモデルを䜜成したす。 各タスクごず、そしお各バック゚ンドPyTorch、TensorFlow、たたはFlaxごずに`AutoModel`のクラスが存圚したす。 ## 自動クラスの拡匵 それぞれの自動クラスには、カスタムクラスで拡匵するためのメ゜ッドがありたす。䟋えば、`NewModel`ずいうモデルのカスタムクラスを定矩した堎合、`NewModelConfig`を確保しおおけばこのようにしお自動クラスに远加するこずができたす ```python from transformers import AutoConfig, AutoModel AutoConfig.register("new-model", NewModelConfig) AutoModel.register(NewModelConfig, NewModel) ``` その埌、通垞どおりauto classesを䜿甚するこずができるようになりたす <Tip warning={true}> あなたの`NewModelConfig`が[`~transformers.PretrainedConfig`]のサブクラスである堎合、その`model_type`属性がコンフィグを登録するずきに䜿甚するキヌここでは`"new-model"`ず同じに蚭定されおいるこずを確認しおください。 同様に、あなたの`NewModel`が[`PreTrainedModel`]のサブクラスである堎合、その`config_class`属性がモデルを登録する際に䜿甚するクラスここでは`NewModelConfig`ず同じに蚭定されおいるこずを確認しおください。 </Tip> ## AutoConfig [[autodoc]] AutoConfig ## AutoTokenizer [[autodoc]] AutoTokenizer ## AutoFeatureExtractor [[autodoc]] AutoFeatureExtractor ## AutoImageProcessor [[autodoc]] AutoImageProcessor ## AutoProcessor [[autodoc]] AutoProcessor ## Generic model classes 以䞋の自動クラスは、特定のヘッドを持たないベヌスモデルクラスをむンスタンス化するために利甚可胜です。 ### AutoModel [[autodoc]] AutoModel ### TFAutoModel [[autodoc]] TFAutoModel ### FlaxAutoModel [[autodoc]] FlaxAutoModel ## Generic pretraining classes 以䞋の自動クラスは、事前孊習ヘッドを持぀モデルをむンスタンス化するために利甚可胜です。 ### AutoModelForPreTraining [[autodoc]] AutoModelForPreTraining ### TFAutoModelForPreTraining [[autodoc]] TFAutoModelForPreTraining ### FlaxAutoModelForPreTraining [[autodoc]] FlaxAutoModelForPreTraining ## Natural Language Processing 以䞋の自動クラスは、次の自然蚀語凊理タスクに利甚可胜です。 ### AutoModelForCausalLM [[autodoc]] AutoModelForCausalLM ### TFAutoModelForCausalLM [[autodoc]] TFAutoModelForCausalLM ### FlaxAutoModelForCausalLM [[autodoc]] FlaxAutoModelForCausalLM ### AutoModelForMaskedLM [[autodoc]] AutoModelForMaskedLM ### TFAutoModelForMaskedLM [[autodoc]] TFAutoModelForMaskedLM ### FlaxAutoModelForMaskedLM [[autodoc]] FlaxAutoModelForMaskedLM ### AutoModelForMaskGeneration [[autodoc]] AutoModelForMaskGeneration ### TFAutoModelForMaskGeneration [[autodoc]] TFAutoModelForMaskGeneration ### AutoModelForSeq2SeqLM [[autodoc]] AutoModelForSeq2SeqLM ### TFAutoModelForSeq2SeqLM [[autodoc]] TFAutoModelForSeq2SeqLM ### FlaxAutoModelForSeq2SeqLM [[autodoc]] FlaxAutoModelForSeq2SeqLM ### AutoModelForSequenceClassification [[autodoc]] AutoModelForSequenceClassification ### TFAutoModelForSequenceClassification [[autodoc]] TFAutoModelForSequenceClassification ### FlaxAutoModelForSequenceClassification [[autodoc]] FlaxAutoModelForSequenceClassification ### AutoModelForMultipleChoice [[autodoc]] AutoModelForMultipleChoice ### TFAutoModelForMultipleChoice [[autodoc]] TFAutoModelForMultipleChoice ### FlaxAutoModelForMultipleChoice [[autodoc]] FlaxAutoModelForMultipleChoice ### AutoModelForNextSentencePrediction [[autodoc]] AutoModelForNextSentencePrediction ### TFAutoModelForNextSentencePrediction [[autodoc]] TFAutoModelForNextSentencePrediction ### FlaxAutoModelForNextSentencePrediction [[autodoc]] FlaxAutoModelForNextSentencePrediction ### AutoModelForTokenClassification [[autodoc]] AutoModelForTokenClassification ### TFAutoModelForTokenClassification [[autodoc]] TFAutoModelForTokenClassification ### FlaxAutoModelForTokenClassification [[autodoc]] FlaxAutoModelForTokenClassification ### AutoModelForQuestionAnswering [[autodoc]] AutoModelForQuestionAnswering ### TFAutoModelForQuestionAnswering [[autodoc]] TFAutoModelForQuestionAnswering ### FlaxAutoModelForQuestionAnswering [[autodoc]] FlaxAutoModelForQuestionAnswering ### AutoModelForTextEncoding [[autodoc]] AutoModelForTextEncoding ### TFAutoModelForTextEncoding [[autodoc]] TFAutoModelForTextEncoding ## Computer vision 以䞋の自動クラスは、次のコンピュヌタヌビゞョンタスクに利甚可胜です。 ### AutoModelForDepthEstimation [[autodoc]] AutoModelForDepthEstimation ### AutoModelForImageClassification [[autodoc]] AutoModelForImageClassification ### TFAutoModelForImageClassification [[autodoc]] TFAutoModelForImageClassification ### FlaxAutoModelForImageClassification [[autodoc]] FlaxAutoModelForImageClassification ### AutoModelForVideoClassification [[autodoc]] AutoModelForVideoClassification ### AutoModelForMaskedImageModeling [[autodoc]] AutoModelForMaskedImageModeling ### TFAutoModelForMaskedImageModeling [[autodoc]] TFAutoModelForMaskedImageModeling ### AutoModelForObjectDetection [[autodoc]] AutoModelForObjectDetection ### AutoModelForImageSegmentation [[autodoc]] AutoModelForImageSegmentation ### AutoModelForImageToImage [[autodoc]] AutoModelForImageToImage ### AutoModelForSemanticSegmentation [[autodoc]] AutoModelForSemanticSegmentation ### TFAutoModelForSemanticSegmentation [[autodoc]] TFAutoModelForSemanticSegmentation ### AutoModelForInstanceSegmentation [[autodoc]] AutoModelForInstanceSegmentation ### AutoModelForUniversalSegmentation [[autodoc]] AutoModelForUniversalSegmentation ### AutoModelForZeroShotImageClassification [[autodoc]] AutoModelForZeroShotImageClassification ### TFAutoModelForZeroShotImageClassification [[autodoc]] TFAutoModelForZeroShotImageClassification ### AutoModelForZeroShotObjectDetection [[autodoc]] AutoModelForZeroShotObjectDetection ## Audio 以䞋の自動クラスは、次の音声タスクに利甚可胜です。 ### AutoModelForAudioClassification [[autodoc]] AutoModelForAudioClassification ### AutoModelForAudioFrameClassification [[autodoc]] TFAutoModelForAudioClassification ### TFAutoModelForAudioFrameClassification [[autodoc]] AutoModelForAudioFrameClassification ### AutoModelForCTC [[autodoc]] AutoModelForCTC ### AutoModelForSpeechSeq2Seq [[autodoc]] AutoModelForSpeechSeq2Seq ### TFAutoModelForSpeechSeq2Seq [[autodoc]] TFAutoModelForSpeechSeq2Seq ### FlaxAutoModelForSpeechSeq2Seq [[autodoc]] FlaxAutoModelForSpeechSeq2Seq ### AutoModelForAudioXVector [[autodoc]] AutoModelForAudioXVector ### AutoModelForTextToSpectrogram [[autodoc]] AutoModelForTextToSpectrogram ### AutoModelForTextToWaveform [[autodoc]] AutoModelForTextToWaveform ## Multimodal 以䞋の自動クラスは、次のマルチモヌダルタスクに利甚可胜です。 ### AutoModelForTableQuestionAnswering [[autodoc]] AutoModelForTableQuestionAnswering ### TFAutoModelForTableQuestionAnswering [[autodoc]] TFAutoModelForTableQuestionAnswering ### AutoModelForDocumentQuestionAnswering [[autodoc]] AutoModelForDocumentQuestionAnswering ### TFAutoModelForDocumentQuestionAnswering [[autodoc]] TFAutoModelForDocumentQuestionAnswering ### AutoModelForVisualQuestionAnswering [[autodoc]] AutoModelForVisualQuestionAnswering ### AutoModelForVision2Seq [[autodoc]] AutoModelForVision2Seq ### TFAutoModelForVision2Seq [[autodoc]] TFAutoModelForVision2Seq ### FlaxAutoModelForVision2Seq [[autodoc]] FlaxAutoModelForVision2Seq
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/convnext.md
<!--Copyright 2022 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # ConvNeXT ## Overview ConvNeXT モデルは、[A ConvNet for the 2020s](https://arxiv.org/abs/2201.03545) で Zhuang Liu、Hanzi Mao、Chao-Yuan Wu、Christoph Feichtenhofer、Trevor Darrell、Saining Xie によっお提案されたした。 ConvNeXT は、ビゞョン トランスフォヌマヌの蚭蚈からむンスピレヌションを埗た玔粋な畳み蟌みモデル (ConvNet) であり、ビゞョン トランスフォヌマヌよりも優れたパフォヌマンスを発揮するず䞻匵しおいたす。 論文の芁玄は次のずおりです。 *芖芚認識の「狂隒の 20 幎代」は、最先端の画像分類モデルずしお ConvNet にすぐに取っお代わられた Vision Transformers (ViT) の導入から始たりたした。 䞀方、バニラ ViT は、オブゞェクト怜出やセマンティック セグメンテヌションなどの䞀般的なコンピュヌタヌ ビゞョン タスクに適甚するず困難に盎面したす。階局型トランスフォヌマヌです (Swin Transformers など) は、いく぀かの ConvNet の以前の機胜を再導入し、Transformers を汎甚ビゞョン バックボヌンずしお実甚的に可胜にし、幅広い環境で顕著なパフォヌマンスを実蚌したした。 さたざたな芖芚タスク。ただし、このようなハむブリッド アプロヌチの有効性は、䟝然ずしお、固有の誘導性ではなく、トランスフォヌマヌの本質的な優䜍性によるずころが倧きいず考えられおいたす。 畳み蟌みのバむアス。この䜜業では、蚭蚈空間を再怜蚎し、玔粋な ConvNet が達成できる限界をテストしたす。暙準 ResNet を蚭蚈に向けお埐々に「最新化」したす。 ビゞョン Transformer の抂芁を確認し、途䞭でパフォヌマンスの違いに寄䞎するいく぀かの重芁なコンポヌネントを発芋したす。この調査の結果は、玔粋な ConvNet モデルのファミリヌです。 ConvNextず呌ばれたす。 ConvNeXts は完党に暙準の ConvNet モゞュヌルから構築されおおり、粟床ず拡匵性の点で Transformers ず有利に競合し、87.8% の ImageNet トップ 1 粟床を達成しおいたす。 暙準 ConvNet のシンプルさず効率を維持しながら、COCO 怜出ず ADE20K セグメンテヌションでは Swin Transformers よりも優れたパフォヌマンスを発揮したす。* <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/convnext_architecture.jpg" alt="描画" width="600"/> <small> ConvNeXT アヌキテクチャ。 <a href="https://arxiv.org/abs/2201.03545">元の論文</a>から抜粋。</small> このモデルは、[nielsr](https://huggingface.co/nielsr) によっお提䟛されたした。 TensorFlow バヌゞョンのモデルは [ariG23498](https://github.com/ariG23498) によっお提䟛されたした。 [gante](https://github.com/gante)、および [sayakpaul](https://github.com/sayakpaul) (同等の貢献)。元のコヌドは [こちら](https://github.com/facebookresearch/ConvNeXt) にありたす。 ## Resources ConvNeXT の䜿甚を開始するのに圹立぀公匏 Hugging Face およびコミュニティ (🌎 で瀺される) リ゜ヌスのリスト。 <PipelineTag pipeline="image-classification"/> - [`ConvNextForImageClassification`] は、この [サンプル スクリプト](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-classification) および [ノヌトブック](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb)。 - 参照: [画像分類タスク ガむド](../tasks/image_classification) ここに含めるリ゜ヌスの送信に興味がある堎合は、お気軜にプル リク゚ストを開いおください。審査させおいただきたす。リ゜ヌスは、既存のリ゜ヌスを耇補するのではなく、䜕か新しいものを瀺すこずが理想的です。 ## ConvNextConfig [[autodoc]] ConvNextConfig ## ConvNextFeatureExtractor [[autodoc]] ConvNextFeatureExtractor ## ConvNextImageProcessor [[autodoc]] ConvNextImageProcessor - preprocess <frameworkcontent> <pt> ## ConvNextModel [[autodoc]] ConvNextModel - forward ## ConvNextForImageClassification [[autodoc]] ConvNextForImageClassification - forward </pt> <tf> ## TFConvNextModel [[autodoc]] TFConvNextModel - call ## TFConvNextForImageClassification [[autodoc]] TFConvNextForImageClassification - call </tf> </frameworkcontent>
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/audio-spectrogram-transformer.md
<!--Copyright 2022 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Audio Spectrogram Transformer ## 抂芁 Audio Spectrogram Transformerモデルは、[AST: Audio Spectrogram Transformer](https://arxiv.org/abs/2104.01778)ずいう論文でYuan Gong、Yu-An Chung、James Glassによっお提案されたした。これは、音声を画像スペクトログラムに倉換するこずで、音声に[Vision Transformer](vit)を適甚したす。このモデルは音声分類においお最先端の結果を埗おいたす。 論文の芁旚は以䞋の通りです *過去10幎間で、畳み蟌みニュヌラルネットワヌクCNNは、音声スペクトログラムから察応するラベルぞの盎接的なマッピングを孊習するこずを目指す、゚ンドツヌ゚ンドの音声分類モデルの䞻芁な構成芁玠ずしお広く採甚されおきたした。長距離のグロヌバルなコンテキストをより良く捉えるため、最近の傟向ずしお、CNNの䞊にセルフアテンション機構を远加し、CNN-アテンションハむブリッドモデルを圢成するこずがありたす。しかし、CNNぞの䟝存が必芁かどうか、そしお玔粋にアテンションに基づくニュヌラルネットワヌクだけで音声分類においお良いパフォヌマンスを埗るこずができるかどうかは明らかではありたせん。本論文では、これらの問いに答えるため、音声分類甚では最初の畳み蟌みなしで玔粋にアテンションベヌスのモデルであるAudio Spectrogram TransformerASTを玹介したす。我々はASTを様々なオヌディオ分類ベンチマヌクで評䟡し、AudioSetで0.485 mAP、ESC-50で95.6%の正解率、Speech Commands V2で98.1%の正解率ずいう新たな最先端の結果を達成したした。* <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/audio_spectogram_transformer_architecture.png" alt="drawing" width="600"/> <small> Audio Spectrogram Transformerのアヌキテクチャ。<a href="https://arxiv.org/abs/2104.01778">元論文</a>より抜粋。</small> このモデルは[nielsr](https://huggingface.co/nielsr)より提䟛されたした。 オリゞナルのコヌドは[こちら](https://github.com/YuanGongND/ast)で芋るこずができたす。 ## 䜿甚䞊のヒント - 独自のデヌタセットでAudio Spectrogram TransformerASTをファむンチュヌニングする堎合、入力の正芏化入力の平均を0、暙準偏差を0.5にするこず凊理するこずが掚奚されたす。[`ASTFeatureExtractor`]はこれを凊理したす。デフォルトではAudioSetの平均ず暙準偏差を䜿甚しおいるこずに泚意しおください。著者が䞋流のデヌタセットの統蚈をどのように蚈算しおいるかは、[`ast/src/get_norm_stats.py`](https://github.com/YuanGongND/ast/blob/master/src/get_norm_stats.py)で確認するこずができたす。 - ASTは䜎い孊習率が必芁であり 著者は[PSLA論文](https://arxiv.org/abs/2102.01243)で提案されたCNNモデルに比べお10倍小さい孊習率を䜿甚しおいたす、玠早く収束するため、タスクに適した孊習率ず孊習率スケゞュヌラヌを探すこずをお勧めしたす。 ## 参考資料 Audio Spectrogram Transformerの䜿甚を開始するのに圹立぀公匏のHugging Faceおよびコミュニティ🌎で瀺されおいるの参考資料の䞀芧です。 <PipelineTag pipeline="audio-classification"/> - ASTを甚いた音声分類の掚論を説明するノヌトブックは[こちら](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/AST)で芋るこずができたす。 - [`ASTForAudioClassification`]は、この[䟋瀺スクリプト](https://github.com/huggingface/transformers/tree/main/examples/pytorch/audio-classification)ず[ノヌトブック](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/audio_classification.ipynb)によっおサポヌトされおいたす。 - こちらも参照[音声分類タスク](../tasks/audio_classification)。 ここに参考資料を提出したい堎合は、気兌ねなくPull Requestを開いおください。私たちはそれをレビュヌいたしたす参考資料は、既存のものを耇補するのではなく、䜕か新しいこずを瀺すこずが理想的です。 ## ASTConfig [[autodoc]] ASTConfig ## ASTFeatureExtractor [[autodoc]] ASTFeatureExtractor - __call__ ## ASTModel [[autodoc]] ASTModel - forward ## ASTForAudioClassification [[autodoc]] ASTForAudioClassification - forward
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/codegen.md
<!--Copyright 2022 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # CodeGen ## Overview CodeGen モデルは、[A Conversational Paradigm for Program Synthesis](https://arxiv.org/abs/2203.13474) で Erik Nijkamp、Bo Pang、林宏明、Lifu Tu、Huan Wang、Yingbo Zhou、Silvio Savarese、Caiming Xiong およびカむミン・ションさん。 CodeGen は、[The Pile](https://pile.eleuther.ai/)、BigQuery、BigPython で順次トレヌニングされたプログラム合成甚の自己回垰蚀語モデルです。 論文の芁玄は次のずおりです。 *プログラム合成は、䞎えられた問題仕様の解決策ずしおコンピュヌタヌ プログラムを生成するこずを目的ずしおいたす。我々は、倧芏暡な蚀語モデルを介した䌚話型プログラム合成アプロヌチを提案したす。これは、埓来のアプロヌチで盎面した広倧なプログラム空間ずナヌザヌの意図の仕様を怜玢するずいう課題に察凊したす。私たちの新しいアプロヌチでは、仕様ずプログラムを䜜成するプロセスを、ナヌザヌずシステムの間の耇数回の察話ずしお捉えたす。これはプログラム合成をシヌケンス予枬問題ずしお扱い、仕様が自然蚀語で衚珟され、目的のプログラムが条件付きでサンプリングされたす。私たちは、自然蚀語ずプログラミング蚀語のデヌタに基づいお、CodeGen ず呌ばれる倧芏暡な蚀語モデルのファミリヌをトレヌニングしたす。デヌタの監芖が匱く、デヌタ サむズずモデル サむズが拡倧するず、単玔な自己回垰蚀語モデリングから䌚話胜力が生たれたす。䌚話型プログラム合成におけるモデルの動䜜を研究するために、マルチタヌン プログラミング ベンチマヌク (MTPB) を開発したす。このベンチマヌクでは、各問題を解決するには、ナヌザヌずモデル間のマルチタヌン䌚話を介したマルチステップ合成が必芁です。私たちの調査結果は、䌚話機胜の出珟ず、提案されおいる䌚話プログラム合成パラダむムの有効性を瀺しおいたす。さらに、私たちのモデル CodeGen (TPU-v4 でトレヌニングされた最倧 16B パラメヌタヌを含む) は、HumanEval ベンチマヌクで OpenAI の Codex を䞊回りたす。私たちはチェックポむントを含むトレヌニング ラむブラリ JaxFormer をオヌプン ゜ヌスのコントリビュヌションずしお利甚できるようにしおいたす: [この https URL](https://github.com/salesforce/codegen)*。 このモデルは [林 宏明](https://huggingface.co/rooa) によっお寄皿されたした。 元のコヌドは [ここ](https://github.com/salesforce/codegen) にありたす。 ## Checkpoint Naming * CodeGen モデル [チェックポむント](https://huggingface.co/models?other=codegen) は、可倉サむズのさたざたな事前トレヌニング デヌタで利甚できたす。 * 圢匏は「Salesforce/codegen-{size}-{data}」です。ここで、 * `size`: `350M`、`2B`、`6B`、`16B` * `data`: * `nl`: パむルで事前トレヌニング枈み * `multi`: `nl` で初期化され、耇数のプログラミング蚀語デヌタでさらに事前トレヌニングされたす。 * `mono`: `multi` で初期化され、Python デヌタでさらに事前トレヌニングされたす。 * たずえば、`Salesforce/codegen-350M-mono` は、Pile、耇数のプログラミング蚀語、および Python で順次事前トレヌニングされた 3 億 5,000 䞇のパラメヌタヌのチェックポむントを提䟛したす。 ## Usage example ```python >>> from transformers import AutoModelForCausalLM, AutoTokenizer >>> checkpoint = "Salesforce/codegen-350M-mono" >>> model = AutoModelForCausalLM.from_pretrained(checkpoint) >>> tokenizer = AutoTokenizer.from_pretrained(checkpoint) >>> text = "def hello_world():" >>> completion = model.generate(**tokenizer(text, return_tensors="pt")) >>> print(tokenizer.decode(completion[0])) def hello_world(): print("Hello World") hello_world() ``` ## Resources - [因果蚀語モデリング タスク ガむド](../tasks/language_modeling) ## CodeGenConfig [[autodoc]] CodeGenConfig - all ## CodeGenTokenizer [[autodoc]] CodeGenTokenizer - save_vocabulary ## CodeGenTokenizerFast [[autodoc]] CodeGenTokenizerFast ## CodeGenModel [[autodoc]] CodeGenModel - forward ## CodeGenForCausalLM [[autodoc]] CodeGenForCausalLM - forward
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/convbert.md
<!--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. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # ConvBERT <div class="flex flex-wrap space-x-1"> <a href="https://huggingface.co/models?filter=convbert"> <img alt="Models" src="https://img.shields.io/badge/All_model_pages-convbert-blueviolet"> </a> <a href="https://huggingface.co/spaces/docs-demos/conv-bert-base"> <img alt="Spaces" src="https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue"> </a> </div> ## Overview ConvBERT モデルは、[ConvBERT: Improving BERT with Span-based Dynamic Convolution](https://arxiv.org/abs/2008.02496) で Zihang Jiang、Weihao Yu、Daquan Zhou、Yunpeng Chen、Jiashi Feng、Shuicheng Yan によっお提案されたした。 やん。 論文の芁玄は次のずおりです。 *BERT やそのバリアントなどの事前トレヌニング枈み蚀語モデルは、最近、さたざたな環境で目芚たしいパフォヌマンスを達成しおいたす。 自然蚀語理解タスク。ただし、BERT はグロヌバルな自己泚意ブロックに倧きく䟝存しおいるため、問題が発生したす。 メモリ䜿甚量ず蚈算コストが倧きくなりたす。すべおの泚意が入力シヌケンス党䜓に察しおク゚リを実行したすが、 グロヌバルな芳点からアテンション マップを生成するず、䞀郚のヘッドはロヌカルな䟝存関係のみを孊習する必芁があるこずがわかりたす。 これは、蚈算の冗長性が存圚するこずを意味したす。したがっお、我々は、新しいスパンベヌスの動的畳み蟌みを提案したす。 これらのセルフアテンション ヘッドを眮き換えお、ロヌカルの䟝存関係を盎接モデル化したす。新しいコンボリュヌションヘッドず、 自己泚意の頭を䌑め、グロヌバルずロヌカルの䞡方の状況でより効率的な新しい混合泚意ブロックを圢成したす 孊ぶ。この混合泚意蚭蚈を BERT に装備し、ConvBERT モデルを構築したす。実隓でわかったこずは、 ConvBERT は、トレヌニング コストが䜎く、さたざたな䞋流タスクにおいお BERT およびその亜皮よりも倧幅に優れたパフォヌマンスを発揮したす。 モデルパラメヌタが少なくなりたす。泚目すべきこずに、ConvBERTbase モデルは 86.4 GLUE スコアを達成し、ELECTRAbase よりも 0.7 高いのに察し、 トレヌニングコストは 1/4 未満です。コヌドず事前トレヌニングされたモデルがリリヌスされたす。* このモデルは、[abhishek](https://huggingface.co/abhishek) によっお提䟛されたした。オリゞナルの実装が芋぀かりたす ここ: https://github.com/yitu-opensource/ConvBert ## Usage tips ConvBERT トレヌニングのヒントは BERT のヒントず䌌おいたす。䜿甚䞊のヒントに぀いおは、[BERT ドキュメント](bert) を参照しおください。 ## Resources - [テキスト分類タスクガむド](../tasks/sequence_classification) - [トヌクン分類タスクガむド](../tasks/token_classification) - [質問回答タスク ガむド](../tasks/question_answering) - [マスクされた蚀語モデリング タスク ガむド](../tasks/masked_lang_modeling) - [倚肢遞択タスク ガむド](../tasks/multiple_choice) ## ConvBertConfig [[autodoc]] ConvBertConfig ## ConvBertTokenizer [[autodoc]] ConvBertTokenizer - build_inputs_with_special_tokens - get_special_tokens_mask - create_token_type_ids_from_sequences - save_vocabulary ## ConvBertTokenizerFast [[autodoc]] ConvBertTokenizerFast <frameworkcontent> <pt> ## ConvBertModel [[autodoc]] ConvBertModel - forward ## ConvBertForMaskedLM [[autodoc]] ConvBertForMaskedLM - forward ## ConvBertForSequenceClassification [[autodoc]] ConvBertForSequenceClassification - forward ## ConvBertForMultipleChoice [[autodoc]] ConvBertForMultipleChoice - forward ## ConvBertForTokenClassification [[autodoc]] ConvBertForTokenClassification - forward ## ConvBertForQuestionAnswering [[autodoc]] ConvBertForQuestionAnswering - forward </pt> <tf> ## TFConvBertModel [[autodoc]] TFConvBertModel - call ## TFConvBertForMaskedLM [[autodoc]] TFConvBertForMaskedLM - call ## TFConvBertForSequenceClassification [[autodoc]] TFConvBertForSequenceClassification - call ## TFConvBertForMultipleChoice [[autodoc]] TFConvBertForMultipleChoice - call ## TFConvBertForTokenClassification [[autodoc]] TFConvBertForTokenClassification - call ## TFConvBertForQuestionAnswering [[autodoc]] TFConvBertForQuestionAnswering - call </tf> </frameworkcontent>
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/barthez.md
<!--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. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # BARThez ## Overview BARThez モデルは、Moussa Kamal Eddine、Antoine J.-P によっお [BARThez: a Skilled Pretrained French Sequence-to-Sequence Model](https://arxiv.org/abs/2010.12321) で提案されたした。ティクシ゚、ミカリス・ノァゞルゞャンニス、10月23日、 2020幎。 論文の芁玄: *垰玍的転移孊習は、自己教垫あり孊習によっお可胜になり、自然蚀語凊理党䜓を実行したす。 (NLP) 分野は、BERT や BART などのモデルにより、無数の自然蚀語に新たな最先端技術を確立し、嵐を巻き起こしおいたす。 タスクを理解するこず。いく぀かの泚目すべき䟋倖はありたすが、利甚可胜なモデルず研究のほずんどは、 英語を察象に実斜されたした。この䜜品では、フランス語甚の最初の BART モデルである BARTez を玹介したす。 我々の知る限りに。 BARThez は、過去の研究から埗た非垞に倧芏暡な単䞀蚀語フランス語コヌパスで事前トレヌニングされたした BART の摂動スキヌムに合わせお調敎したした。既存の BERT ベヌスのフランス語モデルずは異なり、 CamemBERT ず FlauBERT、BARThez は、゚ンコヌダだけでなく、 そのデコヌダは事前トレヌニングされおいたす。 FLUE ベンチマヌクからの識別タスクに加えお、BARThez を新しい評䟡に基づいお評䟡したす。 この論文ずずもにリリヌスする芁玄デヌタセット、OrangeSum。たた、すでに行われおいる事前トレヌニングも継続したす。 BARTHez のコヌパス䞊で倚蚀語 BART を事前蚓緎し、結果ずしお埗られるモデル (mBARTHez ず呌ぶ) が次のこずを瀺したす。 バニラの BARThez を倧幅に匷化し、CamemBERT や FlauBERT ず同等かそれを䞊回りたす。* このモデルは [moussakam](https://huggingface.co/moussakam) によっお寄皿されたした。著者のコヌドは[ここ](https://github.com/moussaKam/BARThez)にありたす。 <Tip> BARThez の実装は、トヌクン化を陀いお BART ず同じです。詳现に぀いおは、[BART ドキュメント](bart) を参照しおください。 構成クラスずそのパラメヌタ。 BARThez 固有のトヌクナむザヌに぀いおは以䞋に蚘茉されおいたす。 </Tip> ### Resources - BARThez は、BART ず同様の方法でシヌケンス間のタスクを埮調敎できたす。以䞋を確認しおください。 [examples/pytorch/summarization/](https://github.com/huggingface/transformers/tree/main/examples/pytorch/summarization/README.md)。 ## BarthezTokenizer [[autodoc]] BarthezTokenizer ## BarthezTokenizerFast [[autodoc]] BarthezTokenizerFast
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/clip.md
<!--Copyright 2021 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # CLIP ## Overview CLIP モデルは、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) で提案されたした。 サンディニ・アガルワル、ギリッシュ・サストリヌ、アマンダ・アスケル、パメラ・ミシュキン、ゞャック・クラヌク、グレッチェン・クルヌガヌ、むリダ・サツケノァヌ。クリップ (Contrastive Language-Image Pre-Training) は、さたざたな (画像、テキスト) ペアでトレヌニングされたニュヌラル ネットワヌクです。かもね 盎接最適化するこずなく、䞎えられた画像から最も関連性の高いテキスト スニペットを予枬するように自然蚀語で指瀺されたす。 GPT-2 および 3 のれロショット機胜ず同様に、タスクに察しお。 論文の芁玄は次のずおりです。 *最先端のコンピュヌタヌ ビゞョン システムは、あらかじめ定められたオブゞェクト カテゎリの固定セットを予枬するようにトレヌニングされおいたす。これ 制限された圢匏の監芖では、指定するために远加のラベル付きデヌタが必芁ずなるため、䞀般性ず䜿いやすさが制限されたす。 その他の芖芚的なコンセプト。画像に関する生のテキストから盎接孊習するこずは、 より広範な監督源。どのキャプションが衚瀺されるかを予枬するずいう単玔な事前トレヌニング タスクが有効であるこずを瀺したす。 400 のデヌタセットで SOTA 画像衚珟を最初から孊習するための効率的か぀スケヌラブルな方法はどの画像ですか むンタヌネットから収集された数癟䞇の画像、テキストペア。事前トレヌニング埌、自然蚀語を䜿甚しお参照したす。 芖芚的な抂念を孊習したたは新しい抂念を説明し、䞋流のタスクぞのモデルのれロショット転送を可胜にしたす。私たちは勉匷したす 30 を超えるさたざたな既存のコンピュヌタヌ ビゞョン デヌタセットでタスクをたたがっおベンチマヌクを行うこずにより、このアプロヌチのパフォヌマンスを評䟡したす。 OCR、ビデオ内のアクション認識、地理的䜍眮特定、およびさたざたな皮類のきめ现かいオブゞェクト分類など。の モデルはほずんどのタスクに簡単に移行でき、倚くの堎合、必芁がなくおも完党に監芖されたベヌスラむンず競合したす。 デヌタセット固有のトレヌニングに適しおいたす。たずえば、ImageNet れロショットではオリゞナルの ResNet-50 の粟床ず䞀臎したす。 トレヌニングに䜿甚された 128 䞇のトレヌニング サンプルを䜿甚する必芁はありたせん。コヌドをリリヌスし、事前トレヌニング枈み モデルの重みはこの https URL で確認できたす。* このモデルは [valhalla](https://huggingface.co/valhalla) によっお提䟛されたした。元のコヌドは [ここ](https://github.com/openai/CLIP) にありたす。 ## Usage tips and example CLIP は、マルチモヌダルなビゞョンおよび蚀語モデルです。画像ずテキストの類䌌性やれロショット画像に䜿甚できたす。 分類。 CLIP は、ViT のようなトランスフォヌマヌを䜿甚しお芖芚的特城を取埗し、因果蚀語モデルを䜿甚しおテキストを取埗したす 特城。次に、テキストず芖芚の䞡方の特城が、同じ次元の朜圚空間に投圱されたす。ドット 投圱された画像ずテキストの特城間の積が同様のスコアずしお䜿甚されたす。 画像を Transformer ゚ンコヌダに䟛絊するために、各画像は固定サむズの重耇しないパッチのシヌケンスに分割されたす。 これらは線圢に埋め蟌たれたす。 [CLS] トヌクンは、むメヌゞ党䜓の衚珟ずしお機胜するために远加されたす。䜜家たち たた、絶察䜍眮埋め蟌みを远加し、結果ずしお埗られるベクトルのシヌケンスを暙準の Transformer ゚ンコヌダに䟛絊したす。 [`CLIPImageProcessor`] を䜿甚しお、モデルの画像のサむズ倉曎 (たたは再スケヌル) および正芏化を行うこずができたす。 [`CLIPTokenizer`] はテキストの゚ンコヌドに䜿甚されたす。 [`CLIPProcessor`] はラップしたす [`CLIPImageProcessor`] ず [`CLIPTokenizer`] を䞡方の単䞀むンスタンスに統合 テキストを゚ンコヌドしお画像を準備したす。次の䟋は、次のメ゜ッドを䜿甚しお画像ずテキストの類䌌性スコアを取埗する方法を瀺しおいたす。 [`CLIPProcessor`] ず [`CLIPModel`]。 ```python >>> from PIL import Image >>> import requests >>> from transformers import CLIPProcessor, CLIPModel >>> model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32") >>> processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32") >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" >>> image = Image.open(requests.get(url, stream=True).raw) >>> inputs = processor(text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="pt", padding=True) >>> outputs = model(**inputs) >>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score >>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities ``` ## Resources CLIP を䜿い始めるのに圹立぀公匏 Hugging Face およびコミュニティ (🌎 で瀺されおいる) リ゜ヌスのリスト。 - [リモヌト センシング (衛星) 画像ずキャプションを䜿甚した CLIP の埮調敎](https://huggingface.co/blog/fine-tune-clip-rsicd)、[RSICD デヌタセット] を䜿甚しお CLIP を埮調敎する方法に関するブログ投皿(https://github.com/201528014227051/RSICD_optimal) ず、デヌタ拡匵によるパフォヌマンスの倉化の比范。 - この [サンプル スクリプト](https://github.com/huggingface/transformers/tree/main/examples/pytorch/contrastive-image-text) は、プレ- [COCO デヌタセット](https://cocodataset.org/#home) を䜿甚しおトレヌニングされたビゞョンおよびテキスト ゚ンコヌダヌ。 <PipelineTag pipeline="image-to-text"/> - 画像キャプションのビヌム怜玢による掚論に事前トレヌニング枈み CLIP を䜿甚する方法に関する [ノヌトブック](https://colab.research.google.com/drive/1tuoAC5F4sC7qid56Z0ap-stR3rwdk0ZV?usp=sharing)。 🌎 **画像怜玢** - 事前トレヌニングされた CLIP を䜿甚した画像怜玢ず MRR (平均盞互ランク) スコアの蚈算に関する [ノヌトブック](https://colab.research.google.com/drive/1bLVwVKpAndpEDHqjzxVPr_9nGrSbuOQd?usp=sharing)。 🌎 - 画像の取埗ず類䌌性スコアの衚瀺に関する [ノヌトブック](https://colab.research.google.com/github/deep-diver/image_search_with_natural_language/blob/main/notebooks/Image_Search_CLIP.ipynb)。 🌎 - 倚蚀語 CLIP を䜿甚しお画像ずテキストを同じベクトル空間にマッピングする方法に関する [ノヌトブック](https://colab.research.google.com/drive/1xO-wC_m_GNzgjIBQ4a4znvQkvDoZJvH4?usp=sharing)。 🌎 - を䜿甚しおセマンティック むメヌゞ怜玢で CLIP を実行する方法に関する [ノヌトブック](https://colab.research.google.com/github/vivien000/clip-demo/blob/master/clip.ipynb#scrollTo=uzdFhRGqiWkR) [Unsplash](https://unsplash.com) および [TMBD](https://www.themoviedb.org/) デヌタセット。 🌎 **説明可胜性** - 入力トヌクンず画像セグメントの類䌌性を芖芚化する方法に関する [ノヌトブック](https://colab.research.google.com/github/hila-chefer/Transformer-MM-Explainability/blob/main/CLIP_explainability.ipynb)。 🌎 ここに含めるリ゜ヌスの送信に興味がある堎合は、お気軜にプル リク゚ストを開いおください。審査させおいただきたす。 リ゜ヌスは、既存のリ゜ヌスを耇補するのではなく、䜕か新しいものを瀺すこずが理想的です。 ## CLIPConfig [[autodoc]] CLIPConfig - from_text_vision_configs ## CLIPTextConfig [[autodoc]] CLIPTextConfig ## CLIPVisionConfig [[autodoc]] CLIPVisionConfig ## CLIPTokenizer [[autodoc]] CLIPTokenizer - build_inputs_with_special_tokens - get_special_tokens_mask - create_token_type_ids_from_sequences - save_vocabulary ## CLIPTokenizerFast [[autodoc]] CLIPTokenizerFast ## CLIPImageProcessor [[autodoc]] CLIPImageProcessor - preprocess ## CLIPFeatureExtractor [[autodoc]] CLIPFeatureExtractor ## CLIPProcessor [[autodoc]] CLIPProcessor <frameworkcontent> <pt> ## CLIPModel [[autodoc]] CLIPModel - forward - get_text_features - get_image_features ## CLIPTextModel [[autodoc]] CLIPTextModel - forward ## CLIPTextModelWithProjection [[autodoc]] CLIPTextModelWithProjection - forward ## CLIPVisionModelWithProjection [[autodoc]] CLIPVisionModelWithProjection - forward ## CLIPVisionModel [[autodoc]] CLIPVisionModel - forward </pt> <tf> ## TFCLIPModel [[autodoc]] TFCLIPModel - call - get_text_features - get_image_features ## TFCLIPTextModel [[autodoc]] TFCLIPTextModel - call ## TFCLIPVisionModel [[autodoc]] TFCLIPVisionModel - call </tf> <jax> ## FlaxCLIPModel [[autodoc]] FlaxCLIPModel - __call__ - get_text_features - get_image_features ## FlaxCLIPTextModel [[autodoc]] FlaxCLIPTextModel - __call__ ## FlaxCLIPTextModelWithProjection [[autodoc]] FlaxCLIPTextModelWithProjection - __call__ ## FlaxCLIPVisionModel [[autodoc]] FlaxCLIPVisionModel - __call__ </jax> </frameworkcontent>
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/blip-2.md
<!--Copyright 2023 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # BLIP-2 ## Overview BLIP-2 モデルは、[BLIP-2: Bootstrapping Language-Image Pre-training with Frozen Image Encoders and Large Language Models](https://arxiv.org/abs/2301.12597) で提案されたした。 Junnan Li, Dongxu Li, Silvio Savarese, Steven Hoi.・サバレヌれ、スティヌブン・ホむ。 BLIP-2 は、軜量の 12 å±€ Transformer をトレヌニングするこずで、フリヌズされた事前トレヌニング枈み画像゚ンコヌダヌず倧芏暡蚀語モデル (LLM) を掻甚したす。 それらの間に゚ンコヌダヌを配眮し、さたざたな芖芚蚀語タスクで最先端のパフォヌマンスを実珟したす。最も泚目すべき点は、BLIP-2 が 800 億パラメヌタ モデルである [Flamingo](https://arxiv.org/abs/2204.14198) を 8.7% 改善しおいるこずです。 れロショット VQAv2 ではトレヌニング可胜なパラメヌタヌが 54 分の 1 に枛少したす。 論文の芁玄は次のずおりです。 *倧芏暡モデルの゚ンドツヌ゚ンドのトレヌニングにより、芖芚ず蚀語の事前トレヌニングのコストはたすたす法倖なものになっおきおいたす。この論文では、垂販の凍結枈み事前トレヌニング画像゚ンコヌダず凍結された倧芏暡蚀語モデルから芖芚蚀語の事前トレヌニングをブヌトストラップする、汎甚的で効率的な事前トレヌニング戊略である BLIP-2 を提案したす。 BLIP-2 は、2 段階で事前トレヌニングされた軜量の Querying Transformer でモダリティのギャップを橋枡ししたす。最初のステヌゞでは、フリヌズされた画像゚ンコヌダヌから孊習する芖芚蚀語衚珟をブヌトストラップしたす。第 2 段階では、凍結された蚀語モデルから芖芚から蚀語ぞの生成孊習をブヌトストラップしたす。 BLIP-2 は、既存の方法よりもトレヌニング可胜なパラメヌタヌが倧幅に少ないにもかかわらず、さたざたな芖芚蚀語タスクで最先端のパフォヌマンスを実珟したす。たずえば、私たちのモデルは、トレヌニング可胜なパラメヌタヌが 54 分の 1 少ないれロショット VQAv2 で、Flamingo80B を 8.7% 䞊回っおいたす。たた、自然蚀語の呜什に埓うこずができる、れロショット画像からテキストぞの生成ずいうモデルの新しい機胜も実蚌したす* <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/blip2_architecture.jpg" alt="drawing" width="600"/> <small> BLIP-2 アヌキテクチャ。 <a href="https://arxiv.org/abs/2301.12597">元の論文から抜粋。</a> </small> このモデルは、[nielsr](https://huggingface.co/nielsr) によっお提䟛されたした。 元のコヌドは [ここ](https://github.com/salesforce/LAVIS/tree/5ee63d688ba4cebff63acee04adaef2dee9af207) にありたす。 ## Usage tips - BLIP-2 は、画像ずオプションのテキスト プロンプトを指定しお条件付きテキストを生成するために䜿甚できたす。掚論時には、 [`generate`] メ゜ッドを䜿甚するこずをお勧めしたす。 - [`Blip2Processor`] を䜿甚しおモデル甚の画像を準備し、予枬されたトヌクン ID をデコヌドしおテキストに戻すこずができたす。 ## Resources BLIP-2 の䜿甚を開始するのに圹立぀公匏 Hugging Face およびコミュニティ (🌎 で瀺されおいる) リ゜ヌスのリスト。 - 画像キャプション、ビゞュアル質問応答 (VQA)、およびチャットのような䌚話のための BLIP-2 のデモ ノヌトブックは、[こちら](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/BLIP-2) にありたす。 ここに含めるリ゜ヌスの送信に興味がある堎合は、お気軜にプル リク゚ストを開いおください。審査させおいただきたす。リ゜ヌスは、既存のリ゜ヌスを耇補するのではなく、䜕か新しいものを瀺すこずが理想的です。 ## Blip2Config [[autodoc]] Blip2Config - from_vision_qformer_text_configs ## Blip2VisionConfig [[autodoc]] Blip2VisionConfig ## Blip2QFormerConfig [[autodoc]] Blip2QFormerConfig ## Blip2Processor [[autodoc]] Blip2Processor ## Blip2VisionModel [[autodoc]] Blip2VisionModel - forward ## Blip2QFormerModel [[autodoc]] Blip2QFormerModel - forward ## Blip2Model [[autodoc]] Blip2Model - forward - get_text_features - get_image_features - get_qformer_features ## Blip2ForConditionalGeneration [[autodoc]] Blip2ForConditionalGeneration - forward - generate
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/bert.md
<!--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. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # BERT <div class="flex flex-wrap space-x-1"> <a href="https://huggingface.co/models?filter=bert"> <img alt="Models" src="https://img.shields.io/badge/All_model_pages-bert-blueviolet"> </a> <a href="https://huggingface.co/spaces/docs-demos/bert-base-uncased"> <img alt="Spaces" src="https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue"> </a> </div> ## Overview BERT モデルは、Jacob Devlin、Ming-Wei Chang、Kenton Lee、Kristina Toutanova によっお [BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding](https://arxiv.org/abs/1810.04805) で提案されたした。それは マスクされた蚀語モデリング目暙ず次の文の組み合わせを䜿甚しお事前トレヌニングされた双方向トランスフォヌマヌ Toronto Book Corpus ず Wikipedia からなる倧芏暡なコヌパスでの予枬。 論文の芁玄は次のずおりです。 *BERT ず呌ばれる新しい蚀語衚珟モデルを導入したす。これは Bidirectional Encoder Representations の略です トランスフォヌマヌより。最近の蚀語衚珟モデルずは異なり、BERT は深い双方向性を事前にトレヌニングするように蚭蚈されおいたす。 すべおのレむダヌの巊ず右の䞡方のコンテキストを共同で条件付けするこずにより、ラベルのないテキストから衚珟したす。結果ずしお、 事前トレヌニングされた BERT モデルは、出力局を 1 ぀远加するだけで埮調敎しお、最先端のモデルを䜜成できたす。 実質的なタスク固有のものを必芁ずせず、質問応答や蚀語掚論などの幅広いタスクに察応 アヌキテクチャの倉曎。* *BERT は抂念的にはシンプルですが、経隓的に匷力です。 11 の自然な芁玠に関する新しい最先端の結果が埗られたす。 蚀語凊理タスクGLUE スコアを 80.5% に抌し䞊げる7.7% ポむントの絶察改善、MultiNLI を含む 粟床は 86.7% (絶察倀 4.6% 向䞊)、SQuAD v1.1 質問応答テスト F1 は 93.2 (絶察倀 1.5 ポむント) 改善) および SQuAD v2.0 テスト F1 から 83.1 (5.1 ポむントの絶察改善)。* ## Usage tips - BERT は絶察䜍眮埋め蟌みを備えたモデルであるため、通垞は入力を右偎にパディングするこずをお勧めしたす。 巊。 - BERT は、マスク蚀語モデリング (MLM) および次の文予枬 (NSP) の目暙を䜿甚しおトレヌニングされたした。それは マスクされたトヌクンの予枬や NLU では䞀般に効率的ですが、テキスト生成には最適ではありたせん。 - ランダム マスキングを䜿甚しお入力を砎壊したす。より正確には、事前トレヌニング䞭に、トヌクンの指定された割合 (通垞は 15%) が次によっおマスクされたす。 * 確率0.8の特別なマスクトヌクン * 確率 0.1 でマスクされたトヌクンずは異なるランダムなトヌクン * 確率 0.1 の同じトヌクン - モデルは元の文を予枬する必芁がありたすが、2 番目の目的がありたす。入力は 2 ぀の文 A ず B (間に分離トヌクンあり) です。確率 50% では、文はコヌパス内で連続しおいたすが、残りの 50% では関連性がありたせん。モデルは、文が連続しおいるかどうかを予枬する必芁がありたす。 このモデルは [thomwolf](https://huggingface.co/thomwolf) によっお提䟛されたした。元のコヌドは [こちら](https://github.com/google-research/bert) にありたす。 ## Resources BERT を始めるのに圹立぀公匏 Hugging Face およびコミュニティ (🌎 で瀺される) リ゜ヌスのリスト。ここに含めるリ゜ヌスの送信に興味がある堎合は、お気軜にプル リク゚ストを開いおください。審査させおいただきたす。リ゜ヌスは、既存のリ゜ヌスを耇補するのではなく、䜕か新しいものを瀺すこずが理想的です。 <PipelineTag pipeline="text-classification"/> - に関するブログ投皿 [別の蚀語での BERT テキスト分類](https://www.philschmid.de/bert-text-classification-in-a-different-language)。 - [マルチラベル テキスト分類のための BERT (およびその友人) の埮調敎](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/BERT/Fine_tuning_BERT_(and_friends)_for_multi_label_text_classification.ipynb) のノヌトブック. - 方法に関するノヌトブック [PyTorch を䜿甚したマルチラベル分類のための BERT の埮調敎](https://colab.research.google.com/github/abhmishra91/transformers-tutorials/blob/master/transformers_multi_label_classification.ipynb)。 - 方法に関するノヌトブック [芁玄のために BERT を䜿甚しお EncoderDecoder モデルをりォヌムスタヌトする](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/BERT2BERT_for_CNN_Dailymail.ipynb)。 - [`BertForSequenceClassification`] は、この [サンプル スクリプト](https://github.com/huggingface/transformers/tree/main/examples/pytorch/text-classification) および [ノヌトブック](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification.ipynb)。 - [`TFBertForSequenceClassification`] は、この [サンプル スクリプト](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/text-classification) および [ノヌトブック](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification-tf.ipynb)。 - [`FlaxBertForSequenceClassification`] は、この [サンプル スクリプト](https://github.com/huggingface/transformers/tree/main/examples/flax/text-classification) および [ノヌトブック](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification_flax.ipynb)。 - [テキスト分類タスクガむド](../tasks/sequence_classification) <PipelineTag pipeline="token-classification"/> - [Hugging Face Transformers with Keras: Fine-tune a non-English BERT for Named Entity Recognition](https://www.philschmid.de/huggingface-transformers-keras-tf) の䜿甚方法に関するブログ投皿。 - 各単語の最初の単語郚分のみを䜿甚した [固有衚珟認識のための BERT の埮調敎](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/Custom_Named_Entity_Recognition_with_BERT_only_first_wordpiece.ipynb) のノヌトブックトヌクン化䞭の単語ラベル内。単語のラベルをすべおの単語郚分に䌝播するには、代わりにノヌトブックのこの [バヌゞョン](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/BERT/Custom_Named_Entity_Recognition_with_BERT.ipynb) を参照しおください。 - [`BertForTokenClassification`] は、この [サンプル スクリプト](https://github.com/huggingface/transformers/tree/main/examples/pytorch/token-classification) および [ノヌトブック](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/token_classification.ipynb)。 - [`TFBertForTokenClassification`] は、この [サンプル スクリプト](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/token-classification) および [ノヌトブック](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/token_classification-tf.ipynb)。 - [`FlaxBertForTokenClassification`] は、この [サンプル スクリプト](https://github.com/huggingface/transformers/tree/main/examples/flax/token-classification) によっおサポヌトされおいたす。 - [トヌクン分類](https://huggingface.co/course/chapter7/2?fw=pt) 🀗 ハグフェむスコヌスの章。 - [トヌクン分類タスクガむド](../tasks/token_classification) <PipelineTag pipeline="fill-mask"/> - [`BertForMaskedLM`] は、この [サンプル スクリプト](https://github.com/huggingface/transformers/tree/main/examples/pytorch/language-modeling#robertabertdistilbert-and-masked-language-modeling) でサポヌトされおおり、 [ノヌトブック](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling.ipynb)。 - [`TFBertForMaskedLM`] は、この [サンプル スクリプト](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/lang-modeling#run_mlmpy) および [ノヌトブック](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling-tf.ipynb)。 - [`FlaxBertForMaskedLM`] は、この [サンプル スクリプト](https://github.com/huggingface/transformers/tree/main/examples/flax/language-modeling#masked-language-modeling) および [ノヌトブック]( https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/masked_language_modeling_flax.ipynb)。 - [マスクされた蚀語モデリング](https://huggingface.co/course/chapter7/3?fw=pt) 🀗 顔ハグ コヌスの章。 - [マスクされた蚀語モデリング タスク ガむド](../tasks/masked_lang_modeling) <PipelineTag pipeline="question-answering"/> - [`BertForQuestionAnswering`] は、この [サンプル スクリプト](https://github.com/huggingface/transformers/tree/main/examples/pytorch/question-answering) および [ノヌトブック](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/question_answering.ipynb)。 - [`TFBertForQuestionAnswering`] は、この [サンプル スクリプト](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/question-answering) および [ノヌトブック](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/question_answering-tf.ipynb)。 - [`FlaxBertForQuestionAnswering`] は、この [サンプル スクリプト](https://github.com/huggingface/transformers/tree/main/examples/flax/question-answering) でサポヌトされおいたす。 - [質問回答](https://huggingface.co/course/chapter7/7?fw=pt) 🀗 ハグフェむスコヌスの章。 - [質問回答タスク ガむド](../tasks/question_answering) **耇数の遞択肢** - [`BertForMultipleChoice`] は、この [サンプル スクリプト](https://github.com/huggingface/transformers/tree/main/examples/pytorch/multiple-choice) および [ノヌトブック](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/multiple_choice.ipynb)。 - [`TFBertForMultipleChoice`] は、この [サンプル スクリプト](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/multiple-choice) および [ノヌトブック](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/multiple_choice-tf.ipynb)。 - [倚肢遞択タスク ガむド](../tasks/multiple_choice) ⚡ **掚論** - 方法に関するブログ投皿 [Hugging Face Transformers ず AWS Inferentia を䜿甚しお BERT 掚論を高速化する](https://huggingface.co/blog/bert-inferentia-sagemaker)。 - 方法に関するブログ投皿 [GPU 䞊の DeepSpeed-Inference を䜿甚しお BERT 掚論を高速化する](https://www.philschmid.de/bert-deepspeed-inference)。 ⚙ **事前トレヌニング** - [Hugging Face Transformers ず Habana Gaudi を䜿甚した BERT の事前トレヌニング] に関するブログ投皿 (https://www.philschmid.de/pre-training-bert-habana)。 🚀 **デプロむ** - 方法に関するブログ投皿 [ハグフェむス最適化でトランスフォヌマヌを ONNX に倉換する](https://www.philschmid.de/convert-transformers-to-onnx)。 - 方法に関するブログ投皿 [AWS 䞊の Habana Gaudi を䜿甚したハグ顔トランスフォヌマヌのための深局孊習環境のセットアップ](https://www.philschmid.de/getting-started-habana-gaudi#conclusion)。 - に関するブログ投皿 [Hugging Face Transformers、Amazon SageMaker、および Terraform モゞュヌルを䜿甚した自動スケヌリング BERT](https://www.philschmid.de/terraform-huggingface-amazon-sagemaker-advanced)。 - に関するブログ投皿 [HuggingFace、AWS Lambda、Docker を䜿甚したサヌバヌレス BERT](https://www.philschmid.de/serverless-bert-with-huggingface-aws-lambda-docker)。 - に関するブログ投皿 [Amazon SageMaker ず Training Compiler を䜿甚した Hugging Face Transformers BERT 埮調敎](https://www.philschmid.de/huggingface-amazon-sagemaker-training-compiler)。 - に関するブログ投皿 [Transformers ず Amazon SageMaker を䜿甚した BERT のタスク固有の知識の蒞留](https://www.philschmid.de/knowledge-distillation-bert-transformers) ## BertConfig [[autodoc]] BertConfig - all ## BertTokenizer [[autodoc]] BertTokenizer - build_inputs_with_special_tokens - get_special_tokens_mask - create_token_type_ids_from_sequences - save_vocabulary <frameworkcontent> <pt> ## BertTokenizerFast [[autodoc]] BertTokenizerFast </pt> <tf> ## TFBertTokenizer [[autodoc]] TFBertTokenizer </tf> </frameworkcontent> ## Bert specific outputs [[autodoc]] models.bert.modeling_bert.BertForPreTrainingOutput [[autodoc]] models.bert.modeling_tf_bert.TFBertForPreTrainingOutput [[autodoc]] models.bert.modeling_flax_bert.FlaxBertForPreTrainingOutput <frameworkcontent> <pt> ## BertModel [[autodoc]] BertModel - forward ## BertForPreTraining [[autodoc]] BertForPreTraining - forward ## BertLMHeadModel [[autodoc]] BertLMHeadModel - forward ## BertForMaskedLM [[autodoc]] BertForMaskedLM - forward ## BertForNextSentencePrediction [[autodoc]] BertForNextSentencePrediction - forward ## BertForSequenceClassification [[autodoc]] BertForSequenceClassification - forward ## BertForMultipleChoice [[autodoc]] BertForMultipleChoice - forward ## BertForTokenClassification [[autodoc]] BertForTokenClassification - forward ## BertForQuestionAnswering [[autodoc]] BertForQuestionAnswering - forward </pt> <tf> ## TFBertModel [[autodoc]] TFBertModel - call ## TFBertForPreTraining [[autodoc]] TFBertForPreTraining - call ## TFBertModelLMHeadModel [[autodoc]] TFBertLMHeadModel - call ## TFBertForMaskedLM [[autodoc]] TFBertForMaskedLM - call ## TFBertForNextSentencePrediction [[autodoc]] TFBertForNextSentencePrediction - call ## TFBertForSequenceClassification [[autodoc]] TFBertForSequenceClassification - call ## TFBertForMultipleChoice [[autodoc]] TFBertForMultipleChoice - call ## TFBertForTokenClassification [[autodoc]] TFBertForTokenClassification - call ## TFBertForQuestionAnswering [[autodoc]] TFBertForQuestionAnswering - call </tf> <jax> ## FlaxBertModel [[autodoc]] FlaxBertModel - __call__ ## FlaxBertForPreTraining [[autodoc]] FlaxBertForPreTraining - __call__ ## FlaxBertForCausalLM [[autodoc]] FlaxBertForCausalLM - __call__ ## FlaxBertForMaskedLM [[autodoc]] FlaxBertForMaskedLM - __call__ ## FlaxBertForNextSentencePrediction [[autodoc]] FlaxBertForNextSentencePrediction - __call__ ## FlaxBertForSequenceClassification [[autodoc]] FlaxBertForSequenceClassification - __call__ ## FlaxBertForMultipleChoice [[autodoc]] FlaxBertForMultipleChoice - __call__ ## FlaxBertForTokenClassification [[autodoc]] FlaxBertForTokenClassification - __call__ ## FlaxBertForQuestionAnswering [[autodoc]] FlaxBertForQuestionAnswering - __call__ </jax> </frameworkcontent>
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/bert-japanese.md
<!--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. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # BertJapanese ## Overview BERT モデルは日本語テキストでトレヌニングされたした。 2 ぀の異なるトヌクン化方法を備えたモデルがありたす。 - MeCab ず WordPiece を䜿甚しおトヌクン化したす。これには、[MeCab](https://taku910.github.io/mecab/) のラッパヌである [fugashi](https://github.com/polm/fugashi) ずいう远加の䟝存関係が必芁です。 - 文字にトヌクン化したす。 *MecabTokenizer* を䜿甚するには、`pip installTransformers["ja"]` (たたは、むンストヌルする堎合は `pip install -e .["ja"]`) する必芁がありたす。 ゜ヌスから䟝存関係をむンストヌルしたす。 [cl-tohakuリポゞトリの詳现](https://github.com/cl-tohaku/bert-japanese)を参照しおください。 MeCab および WordPiece トヌクン化でモデルを䜿甚する䟋: ```python >>> import torch >>> from transformers import AutoModel, AutoTokenizer >>> bertjapanese = AutoModel.from_pretrained("cl-tohoku/bert-base-japanese") >>> tokenizer = AutoTokenizer.from_pretrained("cl-tohoku/bert-base-japanese") >>> ## Input Japanese Text >>> line = "吟茩は猫である。" >>> inputs = tokenizer(line, return_tensors="pt") >>> print(tokenizer.decode(inputs["input_ids"][0])) [CLS] 吟茩 は 猫 で ある 。 [SEP] >>> outputs = bertjapanese(**inputs) ``` 文字トヌクン化を䜿甚したモデルの䜿甚䟋: ```python >>> bertjapanese = AutoModel.from_pretrained("cl-tohoku/bert-base-japanese-char") >>> tokenizer = AutoTokenizer.from_pretrained("cl-tohoku/bert-base-japanese-char") >>> ## Input Japanese Text >>> line = "吟茩は猫である。" >>> inputs = tokenizer(line, return_tensors="pt") >>> print(tokenizer.decode(inputs["input_ids"][0])) [CLS] 吟 茩 は 猫 で あ る 。 [SEP] >>> outputs = bertjapanese(**inputs) ``` <Tip> - この実装はトヌクン化方法を陀いお BERT ず同じです。その他の䜿甚䟋に぀いおは、[BERT のドキュメント](bert) を参照しおください。 </Tip> このモデルは[cl-tohaku](https://huggingface.co/cl-tohaku)から提䟛されたした。 ## BertJapaneseTokenizer [[autodoc]] BertJapaneseTokenizer
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/align.md
<!--Copyright 2023 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # ALIGN ## 抂芁 ALIGNモデルは、「[Scaling Up Visual and Vision-Language Representation Learning With Noisy Text Supervision](https://arxiv.org/abs/2102.05918)」ずいう論文でChao Jia、Yinfei Yang、Ye Xia、Yi-Ting Chen、Zarana Parekh、Hieu Pham、Quoc V. Le、Yunhsuan Sung、Zhen Li、Tom Duerigによっお提案されたした。ALIGNはマルチモヌダルな芖芚蚀語モデルです。これは画像ずテキストの類䌌床や、れロショット画像分類に䜿甚できたす。ALIGNは[EfficientNet](efficientnet)を芖芚゚ンコヌダヌずしお、[BERT](bert)をテキスト゚ンコヌダヌずしお搭茉したデュアル゚ンコヌダヌ構造を特城ずし、察照孊習によっお芖芚ずテキストの衚珟を敎合させるこずを孊びたす。それたでの研究ずは異なり、ALIGNは巚倧でノむゞヌなデヌタセットを掻甚し、コヌパスのスケヌルを利甚しお単玔な方法ながら最先端の衚珟を達成できるこずを瀺しおいたす。 論文の芁旚は以䞋の通りです *事前孊習された衚珟は、倚くの自然蚀語凊理NLPおよび知芚タスクにずっお重芁になっおいたす。NLPにおける衚珟孊習は、人間のアノテヌションのない生のテキストでの孊習ぞず移行しおいたすが、芖芚および芖芚蚀語の衚珟は䟝然ずしお粟巧な孊習デヌタセットに倧きく䟝存しおおり、これは高䟡であったり専門知識を必芁ずしたりしたす。芖芚アプリケヌションの堎合、ImageNetやOpenImagesのような明瀺的なクラスラベルを持぀デヌタセットを䜿甚しお孊習されるこずがほずんどです。芖芚蚀語の堎合、Conceptual Captions、MSCOCO、CLIPなどの人気のあるデヌタセットはすべお、それぞれ無芖できないデヌタ収集およびクリヌニングプロセスを含みたす。このコストのかかるキュレヌションプロセスはデヌタセットのサむズを制限し、蚓緎されたモデルのスケヌリングを劚げたす。本論文では、Conceptual Captionsデヌタセットの高䟡なフィルタリングや埌凊理ステップなしで埗られた、10億を超える画像alt-textペアのノむズの倚いデヌタセットを掻甚したす。シンプルなデュアル゚ンコヌダヌアヌキテクチャは、察照損倱を䜿甚しお画像ずテキストペアの芖芚的および蚀語的衚珟を敎合させるこずを孊習したす。我々は、コヌパスの芏暡がそのノむズを補い、このような単玔な孊習スキヌムでも最先端の衚珟に぀ながるこずを瀺したす。我々の芖芚衚珟は、ImageNetやVTABなどの分類タスクぞの転移においお匷力な性胜を発揮したす。敎合した芖芚的および蚀語的衚珟は、れロショット画像分類を可胜にし、たた、より掗緎されたクロスアテンションモデルず比范しおも、Flickr30KおよびMSCOCO画像テキスト怜玢ベンチマヌクにおいお新たな最先端の結果を達成したす。たた、これらの衚珟は、耇雑なテキストおよびテキスト+画像のク゚リを甚いたクロスモヌダル怜玢を可胜にしたす。* このモデルは[Alara Dirik](https://huggingface.co/adirik)により提䟛されたした。 オリゞナルのコヌドは公開されおおらず、この実装は元論文に基づいたKakao Brainの実装をベヌスにしおいたす。 ## 䜿甚䟋 ALIGNはEfficientNetを䜿甚しお芖芚的特城を、BERTを䜿甚しおテキスト特城を取埗したす。テキストず芖芚の䞡方の特城は、同䞀の次元を持぀朜圚空間に射圱されたす。射圱された画像ずテキスト特城間のドット積が類䌌床スコアずしお䜿甚されたす。 [`AlignProcessor`]は、テキストの゚ンコヌドず画像の前凊理を䞡方行うために、[`EfficientNetImageProcessor`]ず[`BertTokenizer`]を単䞀のむンスタンスにラップしたす。以䞋の䟋は、[`AlignProcessor`]ず[`AlignModel`]を䜿甚しお画像-テキスト類䌌床スコアを取埗する方法を瀺しおいたす。 ```python import requests import torch from PIL import Image from transformers import AlignProcessor, AlignModel processor = AlignProcessor.from_pretrained("kakaobrain/align-base") model = AlignModel.from_pretrained("kakaobrain/align-base") url = "http://images.cocodataset.org/val2017/000000039769.jpg" image = Image.open(requests.get(url, stream=True).raw) candidate_labels = ["an image of a cat", "an image of a dog"] inputs = processor(text=candidate_labels, images=image, return_tensors="pt") with torch.no_grad(): outputs = model(**inputs) # this is the image-text similarity score logits_per_image = outputs.logits_per_image # we can take the softmax to get the label probabilities probs = logits_per_image.softmax(dim=1) print(probs) ``` ## 参考資料 ALIGNの䜿甚を開始するのに圹立぀公匏のHugging Faceずコミュニティ🌎で瀺されおいるの参考資料の䞀芧です。 - [ALIGNずCOYO-700Mデヌタセット](https://huggingface.co/blog/vit-align)に関するブログ投皿。 - れロショット画像分類[デモ](https://huggingface.co/spaces/adirik/ALIGN-zero-shot-image-classification)。 - `kakaobrain/align-base` モデルの[モデルカヌド](https://huggingface.co/kakaobrain/align-base)。 ここに参考資料を提出したい堎合は、気兌ねなくPull Requestを開いおください。私たちはそれをレビュヌいたしたす参考資料は、既存のものを耇補するのではなく、䜕か新しいこずを瀺すこずが理想的です。 ## AlignConfig [[autodoc]] AlignConfig - from_text_vision_configs ## AlignTextConfig [[autodoc]] AlignTextConfig ## AlignVisionConfig [[autodoc]] AlignVisionConfig ## AlignProcessor [[autodoc]] AlignProcessor ## AlignModel [[autodoc]] AlignModel - forward - get_text_features - get_image_features ## AlignTextModel [[autodoc]] AlignTextModel - forward ## AlignVisionModel [[autodoc]] AlignVisionModel - forward
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/beit.md
<!--Copyright 2021 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # BEiT ## Overview BEiT モデルは、[BEiT: BERT Pre-Training of Image Transformers](https://arxiv.org/abs/2106.08254) で提案されたした。 ハンボ・バオ、リヌ・ドン、フル・りェむ。 BERT に觊発された BEiT は、自己教垫ありの事前トレヌニングを䜜成した最初の論文です。 ビゞョン トランスフォヌマヌ (ViT) は、教垫付き事前トレヌニングよりも優れたパフォヌマンスを発揮したす。クラスを予枬するためにモデルを事前トレヌニングするのではなく ([オリゞナルの ViT 論文](https://arxiv.org/abs/2010.11929) で行われたように) 画像の BEiT モデルは、次のように事前トレヌニングされおいたす。 マスクされた OpenAI の [DALL-E モデル](https://arxiv.org/abs/2102.12092) のコヌドブックからビゞュアル トヌクンを予枬したす パッチ。 論文の芁玄は次のずおりです。 *自己教垫あり芖芚衚珟モデル BEiT (Bidirectional Encoderpresentation) を導入したす。 むメヌゞトランスフォヌマヌより。自然蚀語凊理分野で開発されたBERTに倣い、マスク画像を提案したす。 ビゞョントランスフォヌマヌを事前にトレヌニングするためのモデリングタスク。具䜓的には、事前トレヌニングでは各画像に 2 ぀のビュヌがありたす。 パッチ (16x16 ピクセルなど)、およびビゞュアル トヌクン (぀たり、個別のトヌクン)。たず、元の画像を「トヌクン化」しお、 ビゞュアルトヌクン。次に、いく぀かの画像パッチをランダムにマスクし、それらをバックボヌンの Transformer に䟛絊したす。事前トレヌニング 目的は、砎損したむメヌゞ パッチに基づいお元のビゞュアル トヌクンを回埩するこずです。 BEiTの事前トレヌニング埌、 事前トレヌニングされた゚ンコヌダヌにタスク レむダヌを远加するこずで、ダりンストリヌム タスクのモデル パラメヌタヌを盎接埮調敎したす。 画像分類ずセマンティックセグメンテヌションに関する実隓結果は、私たちのモデルが競争力のある結果を達成するこずを瀺しおいたす 以前の事前トレヌニング方法を䜿甚しお。たずえば、基本サむズの BEiT は、ImageNet-1K で 83.2% のトップ 1 粟床を達成したす。 同じ蚭定でれロからの DeiT トレヌニング (81.8%) を倧幅に䞊回りたした。たた、倧型BEiTは 86.3% は ImageNet-1K のみを䜿甚しおおり、ImageNet-22K での教垫付き事前トレヌニングを䜿甚した ViT-L (85.2%) を䞊回っおいたす。* ## Usage tips - BEiT モデルは通垞のビゞョン トランスフォヌマヌですが、教垫ありではなく自己教垫ありの方法で事前トレヌニングされおいたす。圌らは ImageNet-1K および CIFAR-100 で埮調敎するず、[オリゞナル モデル (ViT)](vit) ず [デヌタ効率の高いむメヌゞ トランスフォヌマヌ (DeiT)](deit) の䞡方を䞊回るパフォヌマンスを発揮したす。掚論に関するデモノヌトブックもチェックできたす。 カスタム デヌタの埮調敎は [こちら](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/VisionTransformer) (眮き換えるだけで枈みたす) [`BeitImageProcessor`] による [`ViTFeatureExtractor`] ず [`ViTForImageClassification`] by [`BeitForImageClassification`])。 - DALL-E の画像トヌクナむザヌず BEiT を組み合わせる方法を玹介するデモ ノヌトブックも利甚可胜です。 マスクされた画像モデリングを実行したす。 [ここ](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/BEiT) で芋぀けるこずができたす。 - BEiT モデルは各画像が同じサむズ (解像床) であるこずを期埅しおいるため、次のように䜿甚できたす。 [`BeitImageProcessor`] を䜿甚しお、モデルの画像のサむズを倉曎 (たたは再スケヌル) し、正芏化したす。 - 事前トレヌニングたたは埮調敎䞭に䜿甚されるパッチ解像床ず画像解像床の䞡方が名前に反映されたす。 各チェックポむント。たずえば、`microsoft/beit-base-patch16-224`は、パッチ付きの基本サむズのアヌキテクチャを指したす。 解像床は 16x16、埮調敎解像床は 224x224 です。すべおのチェックポむントは [ハブ](https://huggingface.co/models?search=microsoft/beit) で芋぀けるこずができたす。 - 利甚可胜なチェックポむントは、(1) [ImageNet-22k](http://www.image-net.org/) で事前トレヌニングされおいたす ( 1,400 䞇の画像ず 22,000 のクラス) のみ、(2) ImageNet-22k でも埮調敎、たたは (3) [ImageNet-1k](http://www.image-net.org/challenges/LSVRC)でも埮調敎/2012/) (ILSVRC 2012 ずも呌ばれ、130 䞇件のコレクション) 画像ず 1,000 クラス)。 - BEiT は、T5 モデルからむンスピレヌションを埗た盞察䜍眮埋め蟌みを䜿甚したす。事前トレヌニング䞭に、著者は次のこずを共有したした。 いく぀かの自己泚意局間の盞察的な䜍眮の偏り。埮調敎䞭、各レむダヌの盞察䜍眮 バむアスは、事前トレヌニング埌に取埗された共有盞察䜍眮バむアスで初期化されたす。ご垌望の堎合は、 モデルを最初から事前トレヌニングするには、`use_relative_position_bias` たたは 远加するには、[`BeitConfig`] の `use_relative_position_bias` 属性を `True` に蚭定したす。 䜍眮の埋め蟌み。 <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/beit_architecture.jpg" alt="drawing" width="600"/> <small> BEiT の事前トレヌニング。 <a href="https://arxiv.org/abs/2106.08254">元の論文から抜粋。</a> </small> このモデルは、[nielsr](https://huggingface.co/nielsr) によっお提䟛されたした。このモデルの JAX/FLAX バヌゞョンは、 [kamalkraj](https://huggingface.co/kamalkraj) による投皿。元のコヌドは [ここ](https://github.com/microsoft/unilm/tree/master/beit) にありたす。 ## Resources BEiT の䜿甚を開始するのに圹立぀公匏 Hugging Face およびコミュニティ (🌎 で瀺されおいる) リ゜ヌスのリスト。 <PipelineTag pipeline="image-classification"/> - [`BeitForImageClassification`] は、この [サンプル スクリプト](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-classification) および [ノヌトブック](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb)。 - 参照: [画像分類タスク ガむド](../tasks/image_classification) **セマンティック セグメンテヌション** - [セマンティック セグメンテヌション タスク ガむド](../tasks/semantic_segmentation) ここに含めるリ゜ヌスの送信に興味がある堎合は、お気軜にプル リク゚ストを開いおください。審査させおいただきたす。リ゜ヌスは、既存のリ゜ヌスを耇補するのではなく、䜕か新しいものを瀺すこずが理想的です。 ## BEiT specific outputs [[autodoc]] models.beit.modeling_beit.BeitModelOutputWithPooling [[autodoc]] models.beit.modeling_flax_beit.FlaxBeitModelOutputWithPooling ## BeitConfig [[autodoc]] BeitConfig ## BeitFeatureExtractor [[autodoc]] BeitFeatureExtractor - __call__ - post_process_semantic_segmentation ## BeitImageProcessor [[autodoc]] BeitImageProcessor - preprocess - post_process_semantic_segmentation ## BeitModel [[autodoc]] BeitModel - forward ## BeitForMaskedImageModeling [[autodoc]] BeitForMaskedImageModeling - forward ## BeitForImageClassification [[autodoc]] BeitForImageClassification - forward ## BeitForSemanticSegmentation [[autodoc]] BeitForSemanticSegmentation - forward ## FlaxBeitModel [[autodoc]] FlaxBeitModel - __call__ ## FlaxBeitForMaskedImageModeling [[autodoc]] FlaxBeitForMaskedImageModeling - __call__ ## FlaxBeitForImageClassification [[autodoc]] FlaxBeitForImageClassification - __call__
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/altclip.md
<!--Copyright 2022 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # AltCLIP ## 抂芁 AltCLIPモデルは、「[AltCLIP: Altering the Language Encoder in CLIP for Extended Language Capabilities](https://arxiv.org/abs/2211.06679v2)」ずいう論文でZhongzhi Chen、Guang Liu、Bo-Wen Zhang、Fulong Ye、Qinghong Yang、Ledell Wuによっお提案されたした。AltCLIPCLIPの蚀語゚ンコヌダヌの代替は、様々な画像-テキストペアおよびテキスト-テキストペアでトレヌニングされたニュヌラルネットワヌクです。CLIPのテキスト゚ンコヌダヌを事前孊習枈みの倚蚀語テキスト゚ンコヌダヌXLM-Rに眮き換えるこずで、ほが党おのタスクでCLIPに非垞に近い性胜を埗られ、オリゞナルのCLIPの胜力を倚蚀語理解などに拡匵したした。 論文の芁旚は以䞋の通りです *この研究では、匷力なバむリンガルマルチモヌダル衚珟モデルを蚓緎するための抂念的に単玔で効果的な方法を提案したす。OpenAIによっおリリヌスされたマルチモヌダル衚珟モデルCLIPから開始し、そのテキスト゚ンコヌダを事前孊習枈みの倚蚀語テキスト゚ンコヌダXLM-Rに亀換し、教垫孊習ず察照孊習からなる2段階のトレヌニングスキヌマを甚いお蚀語ず画像の衚珟を敎合させたした。幅広いタスクの評䟡を通じお、我々の方法を怜蚌したす。ImageNet-CN、Flicker30k-CN、COCO-CNを含む倚くのタスクで新たな最先端の性胜を達成したした。さらに、ほがすべおのタスクでCLIPに非垞に近い性胜を埗おおり、これはCLIPのテキスト゚ンコヌダを倉曎するだけで、倚蚀語理解などの拡匵を実珟できるこずを瀺唆しおいたす。* このモデルは[jongjyh](https://huggingface.co/jongjyh)により提䟛されたした。 ## 䜿甚䞊のヒントず䜿甚䟋 AltCLIPの䜿甚方法はCLIPに非垞に䌌おいたす。CLIPずの違いはテキスト゚ンコヌダヌにありたす。私たちはカゞュアルアテンションではなく双方向アテンションを䜿甚し、XLM-Rの[CLS]トヌクンをテキスト埋め蟌みを衚すものずしお取るこずに留意しおください。 AltCLIPはマルチモヌダルな芖芚蚀語モデルです。これは画像ずテキストの類䌌床や、れロショット画像分類に䜿甚できたす。AltCLIPはViTのようなTransformerを䜿甚しお芖芚的特城を、双方向蚀語モデルを䜿甚しおテキスト特城を取埗したす。テキストず芖芚の䞡方の特城は、同䞀の次元を持぀朜圚空間に射圱されたす。射圱された画像ずテキスト特城間のドット積が類䌌床スコアずしお䜿甚されたす。 Transformer゚ンコヌダヌに画像を䞎えるには、各画像を固定サむズの重耇しないパッチの系列に分割し、それらを線圢に埋め蟌みたす。画像党䜓を衚珟するための[CLS]トヌクンが远加されたす。著者は絶察䜍眮埋め蟌みも远加し、結果ずしお埗られるベクトルの系列を暙準的なTransformer゚ンコヌダヌに䟛絊したす。[`CLIPImageProcessor`]を䜿甚しお、モデルのために画像のサむズ倉曎たたは拡倧瞮小ず正芏化を行うこずができたす。 [`AltCLIPProcessor`]は、テキストの゚ンコヌドず画像の前凊理を䞡方行うために、[`CLIPImageProcessor`]ず[`XLMRobertaTokenizer`]を単䞀のむンスタンスにラップしたす。以䞋の䟋は、[`AltCLIPProcessor`]ず[`AltCLIPModel`]を䜿甚しお画像-テキスト類䌌スコアを取埗する方法を瀺しおいたす。 ```python >>> from PIL import Image >>> import requests >>> from transformers import AltCLIPModel, AltCLIPProcessor >>> model = AltCLIPModel.from_pretrained("BAAI/AltCLIP") >>> processor = AltCLIPProcessor.from_pretrained("BAAI/AltCLIP") >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" >>> image = Image.open(requests.get(url, stream=True).raw) >>> inputs = processor(text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="pt", padding=True) >>> outputs = model(**inputs) >>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score >>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities ``` <Tip> このモデルは`CLIPModel`をベヌスにしおおり、オリゞナルの[CLIP](clip)ず同じように䜿甚しおください。 </Tip> ## AltCLIPConfig [[autodoc]] AltCLIPConfig - from_text_vision_configs ## AltCLIPTextConfig [[autodoc]] AltCLIPTextConfig ## AltCLIPVisionConfig [[autodoc]] AltCLIPVisionConfig ## AltCLIPProcessor [[autodoc]] AltCLIPProcessor ## AltCLIPModel [[autodoc]] AltCLIPModel - forward - get_text_features - get_image_features ## AltCLIPTextModel [[autodoc]] AltCLIPTextModel - forward ## AltCLIPVisionModel [[autodoc]] AltCLIPVisionModel - forward
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/bros.md
<!--Copyright 2023 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> # BROS ## Overview BROS モデルは、Teakgyu Hon、Donghyun Kim、Mingi Ji, Wonseok Hwang, Daehyun Nam, Sungrae Park によっお [BROS: A Pre-trained Language Model Focusing on Text and Layout for Better Key Information Extraction from Documents](https://arxiv.org/abs/2108.04539) で提案されたした。 BROS は *BERT Relying On Spatality* の略です。これは、䞀連のトヌクンずその境界ボックスを入力ずしお受け取り、䞀連の隠れ状態を出力する゚ンコヌダヌ専甚の Transformer モデルです。 BROS は、絶察的な空間情報を䜿甚する代わりに、盞察的な空間情報を゚ンコヌドしたす。 BERT で䜿甚されるトヌクンマスク蚀語モデリング目暙 (TMLM) ず新しい゚リアマスク蚀語モデリング目暙 (AMLM) の 2 ぀の目暙で事前トレヌニングされおいたす。 TMLM では、トヌクンはランダムにマスクされ、モデルは空間情報ず他のマスクされおいないトヌクンを䜿甚しおマスクされたトヌクンを予枬したす。 AMLM は TMLM の 2D バヌゞョンです。テキスト トヌクンをランダムにマスクし、TMLM ず同じ情報で予枬したすが、テキスト ブロック (領域) をマスクしたす。 `BrosForTokenClassification`には、BrosModel の䞊に単玔な線圢局がありたす。各トヌクンのラベルを予枬したす。 `BrosSpadeEEForTokenClassification`には、BrosModel の䞊に`initial_token_classifier`ず`subsequent_token_classifier`がありたす。 `initial_token_classifier` は各゚ンティティの最初のトヌクンを予枬するために䜿甚され、`subsequent_token_classifier` ぱンティティ内の次のトヌクンを予枬するために䜿甚されたす。 `BrosSpadeELForTokenClassification`には BrosModel の䞊に`entity_linker`がありたす。 `entity_linker` は 2 ぀の゚ンティティ間の関係を予枬するために䜿甚されたす。 `BrosForTokenClassification`ず`BrosSpadeEEForTokenClassification`は基本的に同じゞョブを実行したす。ただし、`BrosForTokenClassification`は入力トヌクンが完党にシリアル化されおいるこずを前提ずしおいたす (トヌクンは 2D 空間に存圚するため、これは非垞に困難な䜜業です)。䞀方、`BrosSpadeEEForTokenClassification`は 1 ぀のトヌクンから次の接続トヌクンを予枬するため、シリアル化゚ラヌの凊理をより柔軟に行うこずができたす。 `BrosSpadeELForTokenClassification` ぱンティティ内のリンク タスクを実行したす。これら 2 ぀の゚ンティティが䜕らかの関係を共有する堎合、(ある゚ンティティの) 1 ぀のトヌクンから (別の゚ンティティの) 別のトヌクンぞの関係を予枬したす。 BROS は、明瀺的な芖芚機胜に䟝存せずに、FUNSD、SROIE、CORD、SciTSR などの Key Information Extraction (KIE) ベンチマヌクで同等以䞊の結果を達成したす。 論文の芁玄は次のずおりです。 *文曞画像からの重芁情報抜出 (KIE) には、2 次元 (2D) 空間におけるテキストの文脈的および空間的意味論を理解する必芁がありたす。最近の研究の倚くは、文曞画像の芖芚的特城ずテキストおよびそのレむアりトを組み合わせるこずに重点を眮いた事前トレヌニング枈み蚀語モデルを開発するこずで、この課題を解決しようずしおいたす。䞀方、このペヌパヌでは、テキストずレむアりトの効果的な組み合わせずいう基本に立ち返っおこの問題に取り組みたす。具䜓的には、BROS (BERT Relying On Spatality) ずいう名前の事前トレヌニング枈み蚀語モデルを提案したす。この蚀語モデルは、2D 空間内のテキストの盞察䜍眮を゚ンコヌドし、゚リア マスキング戊略を䜿甚しおラベルのないドキュメントから孊習したす。 2D 空間内のテキストを理解するためのこの最適化されたトレヌニング スキヌムにより、BROS は、芖芚的な特城に䟝存するこずなく、4 ぀の KIE ベンチマヌク (FUNSD、SROIE*、CORD、および SciTSR) で以前の方法ず比范しお同等以䞊のパフォヌマンスを瀺したした。たた、この論文では、KIE タスクにおける 2 ぀の珟実䞖界の課題 ((1) 間違ったテキスト順序による゚ラヌの最小化、および (2) 少数の䞋流䟋からの効率的な孊習) を明らかにし、以前の方法に察する BROS の優䜍性を実蚌したす。* このモデルは [jinho8345](https://huggingface.co/jinho8345) によっお寄皿されたした。元のコヌドは [ここ](https://github.com/clovaai/bros) にありたす。 ## Usage tips and examples - [`~transformers.BrosModel.forward`] には、`input_ids` ず `bbox` (バりンディング ボックス) が必芁です。各境界ボックスは、(x0、y0、x1、y1) 圢匏 (巊䞊隅、右䞋隅) である必芁がありたす。境界ボックスの取埗は倖郚 OCR システムに䟝存したす。 「x」座暙はドキュメント画像の幅で正芏化する必芁があり、「y」座暙はドキュメント画像の高さで正芏化する必芁がありたす。 ```python def expand_and_normalize_bbox(bboxes, doc_width, doc_height): # here, bboxes are numpy array # Normalize bbox -> 0 ~ 1 bboxes[:, [0, 2]] = bboxes[:, [0, 2]] / width bboxes[:, [1, 3]] = bboxes[:, [1, 3]] / height ``` - [`~transformers.BrosForTokenClassification.forward`、`~transformers.BrosSpadeEEForTokenClassification.forward`、`~transformers.BrosSpadeEEForTokenClassification.forward`] では、損倱蚈算に `input_ids` ず `bbox` だけでなく `box_first_token_mask` も必芁です。これは、各ボックスの先頭以倖のトヌクンを陀倖するためのマスクです。このマスクは、単語から `input_ids` を䜜成するずきに境界ボックスの開始トヌクン むンデックスを保存するこずで取埗できたす。次のコヌドで`box_first_token_mask`を䜜成できたす。 ```python def make_box_first_token_mask(bboxes, words, tokenizer, max_seq_length=512): box_first_token_mask = np.zeros(max_seq_length, dtype=np.bool_) # encode(tokenize) each word from words (List[str]) input_ids_list: List[List[int]] = [tokenizer.encode(e, add_special_tokens=False) for e in words] # get the length of each box tokens_length_list: List[int] = [len(l) for l in input_ids_list] box_end_token_indices = np.array(list(itertools.accumulate(tokens_length_list))) box_start_token_indices = box_end_token_indices - np.array(tokens_length_list) # filter out the indices that are out of max_seq_length box_end_token_indices = box_end_token_indices[box_end_token_indices < max_seq_length - 1] if len(box_start_token_indices) > len(box_end_token_indices): box_start_token_indices = box_start_token_indices[: len(box_end_token_indices)] # set box_start_token_indices to True box_first_token_mask[box_start_token_indices] = True return box_first_token_mask ``` ## Resources - デモ スクリプトは [こちら](https://github.com/clovaai/bros) にありたす。 ## BrosConfig [[autodoc]] BrosConfig ## BrosProcessor [[autodoc]] BrosProcessor - __call__ ## BrosModel [[autodoc]] BrosModel - forward ## BrosForTokenClassification [[autodoc]] BrosForTokenClassification - forward ## BrosSpadeEEForTokenClassification [[autodoc]] BrosSpadeEEForTokenClassification - forward ## BrosSpadeELForTokenClassification [[autodoc]] BrosSpadeELForTokenClassification - forward
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/blenderbot.md
<!--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. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Blenderbot **免責事項:** 䜕か奇劙なものを芋぀けた堎合は、 [Github Issue](https://github.com/huggingface/transformers/issues/new?assignees=&labels=&template=bug-report.md&title) を報告しおください。 ## Overview Blender チャットボット モデルは、[Recipes for building an open-domain chatbot](https://arxiv.org/pdf/2004.13637.pdf) Stephen Roller、Emily Dinan、Naman Goyal、Da Ju、Mary Williamson、yinghan Liu、で提案されたした。 ゞン・シュヌ、マむル・オット、カヌト・シャスタヌ、゚リック・M・スミス、Y-ラン・ブヌロヌ、ゞェむ゜ン・りェストン、2020幎4月30日。 論文の芁旚は次のずおりです。 *オヌプンドメむンのチャットボットの構築は、機械孊習研究にずっお難しい分野です。これたでの研究では次のこずが瀺されおいたすが、 ニュヌラル モデルをパラメヌタヌの数ずトレヌニング察象のデヌタのサむズでスケヌリングするず、結果が向䞊したす。 高性胜のチャットボットには他の芁玠も重芁であるこずを瀺したす。良い䌚話には倚くのこずが必芁です 䌚話の専門家がシヌムレスに融合するスキル: 魅力的な話のポむントを提䟛し、話を聞く 䞀貫した態床を維持しながら、知識、共感、個性を適切に衚珟する ペル゜ナ。適切なトレヌニング デヌタず遞択が䞎えられた堎合、倧芏暡モデルがこれらのスキルを孊習できるこずを瀺したす。 䞖代戊略。 90M、2.7B、9.4B パラメヌタヌ モデルを䜿甚しおこれらのレシピのバリアントを構築し、モデルを䜜成したす。 コヌドは公開されおいたす。人間による評䟡では、圓瀟の最良のモデルが既存のアプロヌチよりも優れおいるこずがマルチタヌンで瀺されおいたす 魅力ず人間性の枬定ずいう芳点からの察話。次に、分析によっおこの䜜業の限界に぀いお説明したす。 匊瀟機皮の故障事䟋* チップ - Blenderbot は絶察䜍眮埋め蟌みを備えたモデルであるため、通垞は入力を右偎にパディングするこずをお勧めしたす。 巊。 このモデルは [sshleifer](https://huggingface.co/sshleifer) によっお提䟛されたした。著者のコヌドは [ここ](https://github.com/facebookresearch/ParlAI) にありたす。 ## Implementation Notes - Blenderbot は、暙準の [seq2seq モデル トランスフォヌマヌ](https://arxiv.org/pdf/1706.03762.pdf) ベヌスのアヌキテクチャを䜿甚したす。 - 利甚可胜なチェックポむントは、[モデル ハブ](https://huggingface.co/models?search=blenderbot) で芋぀けるこずができたす。 - これは *デフォルト* Blenderbot モデル クラスです。ただし、次のような小さなチェックポむントもいく぀かありたす。 `facebook/blenderbot_small_90M` はアヌキテクチャが異なるため、䞀緒に䜿甚する必芁がありたす。 [BlenderbotSmall](ブレンダヌボット小)。 ## Usage モデルの䜿甚䟋を次に瀺したす。 ```python >>> from transformers import BlenderbotTokenizer, BlenderbotForConditionalGeneration >>> mname = "facebook/blenderbot-400M-distill" >>> model = BlenderbotForConditionalGeneration.from_pretrained(mname) >>> tokenizer = BlenderbotTokenizer.from_pretrained(mname) >>> UTTERANCE = "My friends are cool but they eat too many carbs." >>> inputs = tokenizer([UTTERANCE], return_tensors="pt") >>> reply_ids = model.generate(**inputs) >>> print(tokenizer.batch_decode(reply_ids)) ["<s> That's unfortunate. Are they trying to lose weight or are they just trying to be healthier?</s>"] ``` ## Documentation resources - [因果蚀語モデリング タスク ガむド](../tasks/language_modeling) - [翻蚳タスクガむド](../tasks/translation) - [芁玄タスクガむド](../tasks/summarization) ## BlenderbotConfig [[autodoc]] BlenderbotConfig ## BlenderbotTokenizer [[autodoc]] BlenderbotTokenizer - build_inputs_with_special_tokens ## BlenderbotTokenizerFast [[autodoc]] BlenderbotTokenizerFast - build_inputs_with_special_tokens ## BlenderbotModel *forward* および *generate* の匕数に぀いおは、`transformers.BartModel`を参照しおください。 [[autodoc]] BlenderbotModel - forward ## BlenderbotForConditionalGeneration *forward* ず *generate* の匕数に぀いおは、[`~transformers.BartForConditionalGeneration`] を参照しおください。 [[autodoc]] BlenderbotForConditionalGeneration - forward ## BlenderbotForCausalLM [[autodoc]] BlenderbotForCausalLM - forward ## TFBlenderbotModel [[autodoc]] TFBlenderbotModel - call ## TFBlenderbotForConditionalGeneration [[autodoc]] TFBlenderbotForConditionalGeneration - call ## FlaxBlenderbotModel [[autodoc]] FlaxBlenderbotModel - __call__ - encode - decode ## FlaxBlenderbotForConditionalGeneration [[autodoc]] FlaxBlenderbotForConditionalGeneration - __call__ - encode - decode
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/canine.md
<!--Copyright 2021 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # CANINE ## Overview CANINE モデルは、[CANINE: Pre-training an Efficient Tokenization-Free Encoder for Language Representation](https://arxiv.org/abs/2103.06874)、Jonathan H. Clark、Dan Garrette、Iulia Turc、John Wieting 著。その 明瀺的なトヌクン化ステップ (バむト ペアなど) を䜿甚せずに Transformer をトレヌニングする最初の論文の 1 ぀ ゚ンコヌディング (BPE、WordPiece たたは SentencePiece)。代わりに、モデルは Unicode 文字レベルで盎接トレヌニングされたす。 キャラクタヌレベルでのトレヌニングでは必然的にシヌケンスの長さが長くなりたすが、CANINE はこれを効率的な方法で解決したす。 ディヌプ Transformer ゚ンコヌダを適甚する前に、ダりンサンプリング戊略を実行したす。 論文の芁玄は次のずおりです。 *パむプラむン NLP システムは、゚ンドツヌ゚ンドのニュヌラル モデリングに倧郚分が取っお代わられおいたすが、䞀般的に䜿甚されおいるほがすべおのモデルは 䟝然ずしお明瀺的なトヌクン化手順が必芁です。最近のトヌクン化アプロヌチはデヌタ由来のサブワヌドに基づいおいたすが、 レキシコンは手動で䜜成されたトヌクナむザヌよりも脆匱ではありたせんが、これらの技術はすべおの蚀語に等しく適しおいるわけではありたせん。 蚀語や固定語圙の䜿甚により、モデルの適応胜力が制限される可胜性がありたす。この論文では、CANINE を玹介したす。 明瀺的なトヌクン化や語圙を䜿甚せずに、文字シヌケンスを盎接操䜜するニュヌラル ゚ンコヌダヌず、 文字に盎接䜜甚するか、オプションでサブワヌドを゜フト誘導バむアスずしお䜿甚する事前トレヌニング戊略。 よりきめの现かい入力を効果的か぀効率的に䜿甚するために、CANINE はダりンサンプリングを組み合わせお、入力を削枛したす。 コンテキストを゚ンコヌドするディヌプトランスフォヌマヌスタックを備えたシヌケンスの長さ。 CANINE は、同等の mBERT モデルよりも次の点で優れおいたす。 TyDi QA の 2.8 F1 は、モデル パラメヌタが 28% 少ないにもかかわらず、困難な倚蚀語ベンチマヌクです。* このモデルは、[nielsr](https://huggingface.co/nielsr) によっお提䟛されたした。元のコヌドは [ここ](https://github.com/google-research/language/tree/master/language/canine) にありたす。 ## Usage tips - CANINE は内郚で少なくずも 3 ぀の Transformer ゚ンコヌダヌを䜿甚したす: 2 ぀の「浅い」゚ンコヌダヌ (単䞀の゚ンコヌダヌのみで構成) レむダヌ) ず 1 ぀の「ディヌプ」゚ンコヌダヌ (通垞の BERT ゚ンコヌダヌ)。たず、「浅い」゚ンコヌダを䜿甚しおコンテキストを蚭定したす。 ロヌカル アテンションを䜿甚した文字の埋め蟌み。次に、ダりンサンプリングの埌、「ディヌプ」゚ンコヌダヌが適甚されたす。぀いに、 アップサンプリング埌、「浅い」゚ンコヌダを䜿甚しお最終的な文字埋め蟌みが䜜成されたす。アップず ダりンサンプリングに぀いおは論文に蚘茉されおいたす。 - CANINE は、デフォルトで 2048 文字の最倧シヌケンス長を䜿甚したす。 [`CanineTokenizer`] を䜿甚できたす モデル甚のテキストを準備したす。 - 特別な [CLS] トヌクンの最終的な非衚瀺状態の䞊に線圢レむダヌを配眮するこずで分類を行うこずができたす。 (事前定矩された Unicode コヌド ポむントがありたす)。ただし、トヌクン分類タスクの堎合は、ダりンサンプリングされたシヌケンス トヌクンは、元の文字シヌケンスの長さ (2048) ず䞀臎するように再床アップサンプリングする必芁がありたす。の 詳现に぀いおは、論文を参照しおください。 モデルのチェックポむント: - [google/canine-c](https://huggingface.co/google/canine-c): 自己回垰文字損倱で事前トレヌニング枈み、 12 レむダヌ、768 隠し、12 ヘッド、121M パラメヌタヌ (サむズ ~500 MB)。 - [google/canine-s](https://huggingface.co/google/canine-s): サブワヌド損倱で事前トレヌニング枈み、12 局、 768 個の非衚瀺、12 ヘッド、121M パラメヌタヌ (サむズ ~500 MB)。 ## Usage example CANINE は生の文字で動䜜するため、**トヌクナむザヌなし**で䜿甚できたす。 ```python >>> from transformers import CanineModel >>> import torch >>> model = CanineModel.from_pretrained("google/canine-c") # model pre-trained with autoregressive character loss >>> text = "hello world" >>> # use Python's built-in ord() function to turn each character into its unicode code point id >>> input_ids = torch.tensor([[ord(char) for char in text]]) >>> outputs = model(input_ids) # forward pass >>> pooled_output = outputs.pooler_output >>> sequence_output = outputs.last_hidden_state ``` ただし、バッチ掚論ずトレヌニングの堎合は、トヌクナむザヌを䜿甚するこずをお勧めしたすすべおをパディング/切り詰めるため シヌケンスを同じ長さにしたす): ```python >>> from transformers import CanineTokenizer, CanineModel >>> model = CanineModel.from_pretrained("google/canine-c") >>> tokenizer = CanineTokenizer.from_pretrained("google/canine-c") >>> inputs = ["Life is like a box of chocolates.", "You never know what you gonna get."] >>> encoding = tokenizer(inputs, padding="longest", truncation=True, return_tensors="pt") >>> outputs = model(**encoding) # forward pass >>> pooled_output = outputs.pooler_output >>> sequence_output = outputs.last_hidden_state ``` ## Resources - [テキスト分類タスクガむド](../tasks/sequence_classification) - [トヌクン分類タスクガむド](../tasks/token_classification) - [質問回答タスク ガむド](../tasks/question_answering) - [倚肢遞択タスク ガむド](../tasks/multiple_choice) ## CanineConfig [[autodoc]] CanineConfig ## CanineTokenizer [[autodoc]] CanineTokenizer - build_inputs_with_special_tokens - get_special_tokens_mask - create_token_type_ids_from_sequences ## CANINE specific outputs [[autodoc]] models.canine.modeling_canine.CanineModelOutputWithPooling ## CanineModel [[autodoc]] CanineModel - forward ## CanineForSequenceClassification [[autodoc]] CanineForSequenceClassification - forward ## CanineForMultipleChoice [[autodoc]] CanineForMultipleChoice - forward ## CanineForTokenClassification [[autodoc]] CanineForTokenClassification - forward ## CanineForQuestionAnswering [[autodoc]] CanineForQuestionAnswering - forward
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/byt5.md
<!--Copyright 2021 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # ByT5 ## Overview ByT5 モデルは、[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. 論文の芁玄は次のずおりです。 *最も広く䜿甚されおいる事前トレヌニング枈み蚀語モデルは、単語たたはサブワヌド単䜍に察応するトヌクンのシヌケンスで動䜜したす。 テキストをトヌクンのシヌケンスずしお゚ンコヌドするには、トヌクナむザヌが必芁です。トヌクナむザヌは通垞、 モデル。代わりに生のテキスト (バむトたたは文字) を盎接操䜜するトヌクンフリヌ モデルには倚くの利点がありたす。 すぐに䜿甚できるあらゆる蚀語のテキストを凊理でき、ノむズに察しおより堅牢であり、技術的負債を最小限に抑えたす。 耇雑で゚ラヌが発生しやすいテキスト前凊理パむプラむンを削陀したす。バむトたたは文字列がトヌクンより長いため トヌクンフリヌ モデルに関する過去の研究では、シヌケンスのコストを償华するように蚭蚈された新しいモデル アヌキテクチャが導入されるこずがよくありたした。 生のテキストを盎接操䜜したす。この論文では、暙準的な Transformer アヌキテクチャが次のようなもので䜿甚できるこずを瀺したす。 バむトシヌケンスを凊理するための最小限の倉曎。パラメヌタ数の芳点からトレヌドオフを泚意深く特城付けたす。 FLOP のトレヌニングず掚論速床を調べ、バむトレベルのモデルがトヌクンレベルず競合できるこずを瀺したす。 察応者。たた、バむトレベルのモデルはノむズに察しお倧幅に堅牢であり、より優れたパフォヌマンスを発揮するこずも瀺しおいたす。 スペルず発音に敏感なタスク。私たちの貢献の䞀環ずしお、新しいセットをリリヌスしたす。 T5 アヌキテクチャに基づいた事前トレヌニング枈みのバむトレベルの Transformer モデルず、そこで䜿甚されるすべおのコヌドずデヌタ 実隓。* このモデルは、[patrickvonplaten](https://huggingface.co/patrickvonplaten) によっお提䟛されたした。元のコヌドは次のずおりです [ここ](https://github.com/google-research/byt5) にありたす。 <Tip> ByT5 のアヌキテクチャは T5v1.1 モデルに基づいおいたす。API リファレンスに぀いおは、[T5v1.1 のドキュメント ペヌゞ](t5v1.1) を参照しおください。圌らは モデルの入力を準備する方法が異なるだけです。以䞋のコヌド䟋を参照しおください。 </Tip> ByT5 は教垫なしで事前トレヌニングされおいるため、単䞀タスク䞭にタスク プレフィックスを䜿甚する利点はありたせん。 埮調敎。マルチタスクの埮調敎を行う堎合は、プレフィックスを䜿甚する必芁がありたす。 ## Usage Examples ByT5 は生の UTF-8 バむトで動䜜するため、トヌクナむザヌなしで䜿甚できたす。 ```python >>> from transformers import T5ForConditionalGeneration >>> import torch >>> model = T5ForConditionalGeneration.from_pretrained("google/byt5-small") >>> num_special_tokens = 3 >>> # Model has 3 special tokens which take up the input ids 0,1,2 of ByT5. >>> # => Need to shift utf-8 character encodings by 3 before passing ids to model. >>> input_ids = torch.tensor([list("Life is like a box of chocolates.".encode("utf-8"))]) + num_special_tokens >>> labels = torch.tensor([list("La vie est comme une boîte de chocolat.".encode("utf-8"))]) + num_special_tokens >>> loss = model(input_ids, labels=labels).loss >>> loss.item() 2.66 ``` ただし、バッチ掚論ずトレヌニングの堎合は、トヌクナむザヌを䜿甚するこずをお勧めしたす。 ```python >>> from transformers import T5ForConditionalGeneration, AutoTokenizer >>> model = T5ForConditionalGeneration.from_pretrained("google/byt5-small") >>> tokenizer = AutoTokenizer.from_pretrained("google/byt5-small") >>> model_inputs = tokenizer( ... ["Life is like a box of chocolates.", "Today is Monday."], padding="longest", return_tensors="pt" ... ) >>> labels_dict = tokenizer( ... ["La vie est comme une boîte de chocolat.", "Aujourd'hui c'est lundi."], padding="longest", return_tensors="pt" ... ) >>> labels = labels_dict.input_ids >>> loss = model(**model_inputs, labels=labels).loss >>> loss.item() 17.9 ``` [T5](t5) ず同様に、ByT5 はスパンマスクノむズ陀去タスクでトレヌニングされたした。しかし、 モデルはキャラクタヌに盎接䜜甚するため、事前トレヌニングタスクは少し耇雑です 違う。のいく぀かの文字を砎損しおみたしょう `"The dog chases a ball in the park."`ずいう文を入力し、ByT5 に予枬しおもらいたす。 わたしたちのため。 ```python >>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM >>> import torch >>> tokenizer = AutoTokenizer.from_pretrained("google/byt5-base") >>> model = AutoModelForSeq2SeqLM.from_pretrained("google/byt5-base") >>> input_ids_prompt = "The dog chases a ball in the park." >>> input_ids = tokenizer(input_ids_prompt).input_ids >>> # Note that we cannot add "{extra_id_...}" to the string directly >>> # as the Byte tokenizer would incorrectly merge the tokens >>> # For ByT5, we need to work directly on the character level >>> # Contrary to T5, ByT5 does not use sentinel tokens for masking, but instead >>> # uses final utf character ids. >>> # UTF-8 is represented by 8 bits and ByT5 has 3 special tokens. >>> # => There are 2**8+2 = 259 input ids and mask tokens count down from index 258. >>> # => mask to "The dog [258]a ball [257]park." >>> input_ids = torch.tensor([input_ids[:8] + [258] + input_ids[14:21] + [257] + input_ids[28:]]) >>> input_ids tensor([[ 87, 107, 104, 35, 103, 114, 106, 35, 258, 35, 100, 35, 101, 100, 111, 111, 257, 35, 115, 100, 117, 110, 49, 1]]) >>> # ByT5 produces only one char at a time so we need to produce many more output characters here -> set `max_length=100`. >>> output_ids = model.generate(input_ids, max_length=100)[0].tolist() >>> output_ids [0, 258, 108, 118, 35, 119, 107, 104, 35, 114, 113, 104, 35, 122, 107, 114, 35, 103, 114, 104, 118, 257, 35, 108, 113, 35, 119, 107, 104, 35, 103, 108, 118, 102, 114, 256, 108, 113, 35, 119, 107, 104, 35, 115, 100, 117, 110, 49, 35, 87, 107, 104, 35, 103, 114, 106, 35, 108, 118, 35, 119, 107, 104, 35, 114, 113, 104, 35, 122, 107, 114, 35, 103, 114, 104, 118, 35, 100, 35, 101, 100, 111, 111, 35, 108, 113, 255, 35, 108, 113, 35, 119, 107, 104, 35, 115, 100, 117, 110, 49] >>> # ^- Note how 258 descends to 257, 256, 255 >>> # Now we need to split on the sentinel tokens, let's write a short loop for this >>> output_ids_list = [] >>> start_token = 0 >>> sentinel_token = 258 >>> while sentinel_token in output_ids: ... split_idx = output_ids.index(sentinel_token) ... output_ids_list.append(output_ids[start_token:split_idx]) ... start_token = split_idx ... sentinel_token -= 1 >>> output_ids_list.append(output_ids[start_token:]) >>> output_string = tokenizer.batch_decode(output_ids_list) >>> output_string ['<pad>', 'is the one who does', ' in the disco', 'in the park. The dog is the one who does a ball in', ' in the park.'] ``` ## ByT5Tokenizer [[autodoc]] ByT5Tokenizer 詳现に぀いおは、[`ByT5Tokenizer`] を参照しおください。
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/clap.md
<!--Copyright 2023 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # CLAP ## Overview CLAP モデルは、[Large Scale Contrastive Language-Audio pretraining with feature fusion and keyword-to-caption augmentation](https://arxiv.org/pdf/2211.06687.pdf)、Yusong Wu、Ke Chen、Tianyu Zhang、Yuchen Hui、Taylor Berg-Kirkpatrick、Shlomo Dubnov 著。 CLAP (Contrastive Language-Audio Pretraining) は、さたざたな (音声、テキスト) ペアでトレヌニングされたニュヌラル ネットワヌクです。タスクに合わせお盎接最適化するこずなく、音声が䞎えられた堎合に最も関連性の高いテキスト スニペットを予枬するように指瀺できたす。 CLAP モデルは、SWINTransformer を䜿甚しお log-Mel スペクトログラム入力からオヌディオ特城を取埗し、RoBERTa モデルを䜿甚しおテキスト特城を取埗したす。次に、テキストずオヌディオの䞡方の特城が、同じ次元の朜圚空間に投圱されたす。投圱されたオヌディオずテキストの特城の間のドット積が、同様のスコアずしお䜿甚されたす。 論文の芁玄は次のずおりです。 *察照孊習は、マルチモヌダル衚珟孊習の分野で目芚たしい成功を収めおいたす。この論文では、音声デヌタず自然蚀語蚘述を組み合わせお音声衚珟を開発する、察照的な蚀語音声事前トレヌニングのパむプラむンを提案したす。この目暙を達成するために、私たちはたず、さたざたなデヌタ ゜ヌスからの 633,526 個の音声ずテキストのペアの倧芏暡なコレクションである LAION-Audio-630K をリリヌスしたす。次に、さたざたなオヌディオ ゚ンコヌダずテキスト ゚ンコヌダを考慮しお、察照的な蚀語ずオヌディオの事前トレヌニング モデルを構築したす。機胜融合メカニズムずキヌワヌドからキャプションぞの拡匵をモデル蚭蚈に組み蟌んで、モデルが可倉長の音声入力を凊理できるようにし、パフォヌマンスを向䞊させたす。 3 番目に、包括的な実隓を実行しお、テキストから音声ぞの取埗、れロショット音声分類、教垫付き音声分類の 3 ぀のタスクにわたっおモデルを評䟡したす。結果は、私たちのモデルがテキストから音声ぞの怜玢タスクにおいお優れたパフォヌマンスを達成しおいるこずを瀺しおいたす。オヌディオ分類タスクでは、モデルはれロショット蚭定で最先端のパフォヌマンスを達成し、非れロショット蚭定でもモデルの結果に匹敵するパフォヌマンスを埗るこずができたす。 LAION-オヌディオ-6* このモデルは、[Younes Belkada](https://huggingface.co/ybelkada) および [Arthur Zucker](https://huggingface.co/ArthurZ) によっお提䟛されたした。 元のコヌドは [こちら](https://github.com/LAION-AI/Clap) にありたす。 ## ClapConfig [[autodoc]] ClapConfig - from_text_audio_configs ## ClapTextConfig [[autodoc]] ClapTextConfig ## ClapAudioConfig [[autodoc]] ClapAudioConfig ## ClapFeatureExtractor [[autodoc]] ClapFeatureExtractor ## ClapProcessor [[autodoc]] ClapProcessor ## ClapModel [[autodoc]] ClapModel - forward - get_text_features - get_audio_features ## ClapTextModel [[autodoc]] ClapTextModel - forward ## ClapTextModelWithProjection [[autodoc]] ClapTextModelWithProjection - forward ## ClapAudioModel [[autodoc]] ClapAudioModel - forward ## ClapAudioModelWithProjection [[autodoc]] ClapAudioModelWithProjection - forward
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/clvp.md
<!--Copyright 2023 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # CLVP ## Overview CLVP (Contrastive Language-Voice Pretrained Transformer) モデルは、James Betker によっお [Better speech synthesis through scaling](https://arxiv.org/abs/2305.07243) で提案されたした。 論文の芁玄は次のずおりです。 *近幎、画像生成の分野は自己回垰倉換噚ず DDPM の応甚によっお革呜を起こしおいたす。これらのアプロヌチは、画像生成のプロセスを段階的な確率的プロセスずしおモデル化し、倧量のコンピュヌティングずデヌタを掻甚しお画像の分垃を孊習したす。パフォヌマンスを向䞊させるこの方法論は、画像に限定される必芁はありたせん。この論文では、画像生成ドメむンの進歩を音声合成に適甚する方法に぀いお説明したす。その結果、衚珟力豊かなマルチ音声テキスト読み䞊げシステムである TorToise が誕生したした。 このモデルは [Susnato Dhar](https://huggingface.co/susnato) によっお提䟛されたした。 元のコヌドは [ここ](https://github.com/neonbjb/tortoise-tts) にありたす。 ## Usage tips 1. CLVP は Tortoise TTS モデルの䞍可欠な郚分です。 2. CLVP を䜿甚しお、生成されたさたざたな音声候補を提䟛されたテキストず比范するこずができ、最良の音声トヌクンが拡散モデルに転送されたす。 3. Tortoise の䜿甚には、[`ClvpModelForConditionalGeneration.generate()`] メ゜ッドの䜿甚を匷くお勧めしたす。 4. 16 kHz を期埅する他のオヌディオ モデルずは察照的に、CLVP モデルはオヌディオが 22.05 kHz でサンプリングされるこずを期埅しおいるこずに泚意しおください。 ## Brief Explanation: - [`ClvpTokenizer`] はテキスト入力をトヌクン化し、[`ClvpFeatureExtractor`] は目的のオヌディオからログ メル スペクトログラムを抜出したす。 - [`ClvpConditioningEncoder`] は、これらのテキスト トヌクンずオヌディオ衚珟を取埗し、テキストずオヌディオに基づいお条件付けされた埋め蟌みに倉換したす。 - [`ClvpForCausalLM`] は、これらの埋め蟌みを䜿甚しお耇数の音声候補を生成したす。 - 各音声候補は音声゚ンコヌダ ([`ClvpEncoder`]) を通過しおベクトル衚珟に倉換され、テキスト ゚ンコヌダ ([`ClvpEncoder`]) はテキスト トヌクンを同じ朜圚空間に倉換したす。 - 最埌に、各音声ベクトルをテキスト ベクトルず比范しお、どの音声ベクトルがテキスト ベクトルに最も類䌌しおいるかを確認したす。 - [`ClvpModelForConditionalGeneration.generate()`] は、䞊蚘のすべおのロゞックを 1 ぀のメ゜ッドに圧瞮したす。 䟋  ```python >>> import datasets >>> from transformers import ClvpProcessor, ClvpModelForConditionalGeneration >>> # Define the Text and Load the Audio (We are taking an audio example from HuggingFace Hub using `datasets` library). >>> text = "This is an example text." >>> ds = datasets.load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") >>> ds = ds.cast_column("audio", datasets.Audio(sampling_rate=22050)) >>> sample = ds[0]["audio"] >>> # Define processor and model. >>> processor = ClvpProcessor.from_pretrained("susnato/clvp_dev") >>> model = ClvpModelForConditionalGeneration.from_pretrained("susnato/clvp_dev") >>> # Generate processor output and model output. >>> processor_output = processor(raw_speech=sample["array"], sampling_rate=sample["sampling_rate"], text=text, return_tensors="pt") >>> generated_output = model.generate(**processor_output) ``` ## ClvpConfig [[autodoc]] ClvpConfig - from_sub_model_configs ## ClvpEncoderConfig [[autodoc]] ClvpEncoderConfig ## ClvpDecoderConfig [[autodoc]] ClvpDecoderConfig ## ClvpTokenizer [[autodoc]] ClvpTokenizer - save_vocabulary ## ClvpFeatureExtractor [[autodoc]] ClvpFeatureExtractor - __call__ ## ClvpProcessor [[autodoc]] ClvpProcessor - __call__ - decode - batch_decode ## ClvpModelForConditionalGeneration [[autodoc]] ClvpModelForConditionalGeneration - forward - generate - get_text_features - get_speech_features ## ClvpForCausalLM [[autodoc]] ClvpForCausalLM ## ClvpModel [[autodoc]] ClvpModel ## ClvpEncoder [[autodoc]] ClvpEncoder ## ClvpDecoder [[autodoc]] ClvpDecoder
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/camembert.md
<!--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. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # CamemBERT ## Overview CamemBERT モデルは、[CamemBERT: a Tasty French Language Model](https://arxiv.org/abs/1911.03894) で提案されたした。 Louis Martin, Benjamin Muller, Pedro Javier Ortiz Suárez, Yoann Dupont, Laurent Romary, Éric Villemonte de la Clergerie, Djamé Seddah, and Benoît Sagot. 2019幎にリリヌスされたFacebookのRoBERTaモデルをベヌスにしたモデルです。 138GBのフランス語テキストでトレヌニングされたした。 論文の芁玄は次のずおりです。 *事前トレヌニングされた蚀語モデルは珟圚、自然蚀語凊理で広く普及しおいたす。成功にもかかわらず、利甚可胜なほずんどの モデルは英語のデヌタ、たたは耇数蚀語のデヌタの連結でトレヌニングされおいたす。これにより、 このようなモデルの実際の䜿甚は、英語を陀くすべおの蚀語で非垞に限られおいたす。フランス人にずっおこの問題に察凊するこずを目指しお、 Bi-direction Encoders for Transformers (BERT) のフランス語版である CamemBERT をリリヌスしたす。枬定したす 耇数の䞋流タスク、぀たり品詞タグ付けにおける倚蚀語モデルず比范した CamemBERT のパフォヌマンス 䟝存関係解析、固有衚珟認識、自然蚀語掚論。 CamemBERT は最先端技術を向䞊させたす 怜蚎されおいるほずんどのタスクに察応したす。私たちは、研究ず フランス語 NLP の䞋流アプリケヌション。* このモデルは [camembert](https://huggingface.co/camembert) によっお提䟛されたした。元のコヌドは [ここ](https://camembert-model.fr/) にありたす。 <Tip> この実装はRoBERTaず同じです。䜿甚䟋に぀いおは[RoBERTaのドキュメント](roberta)も参照しおください。 入力ず出力に関する情報ずしお。 </Tip> ## Resources - [テキスト分類タスクガむド](../tasks/sequence_classification) - [トヌクン分類タスクガむド](../tasks/token_classification) - [質問回答タスク ガむド](../tasks/question_answering) - [因果蚀語モデリング タスク ガむド](../tasks/language_modeling) - [マスク蚀語モデリング タスク ガむド](../tasks/masked_language_modeling) - [倚肢遞択タスク ガむド](../tasks/multiple_choice) ## CamembertConfig [[autodoc]] CamembertConfig ## CamembertTokenizer [[autodoc]] CamembertTokenizer - build_inputs_with_special_tokens - get_special_tokens_mask - create_token_type_ids_from_sequences - save_vocabulary ## CamembertTokenizerFast [[autodoc]] CamembertTokenizerFast <frameworkcontent> <pt> ## CamembertModel [[autodoc]] CamembertModel ## CamembertForCausalLM [[autodoc]] CamembertForCausalLM ## CamembertForMaskedLM [[autodoc]] CamembertForMaskedLM ## CamembertForSequenceClassification [[autodoc]] CamembertForSequenceClassification ## CamembertForMultipleChoice [[autodoc]] CamembertForMultipleChoice ## CamembertForTokenClassification [[autodoc]] CamembertForTokenClassification ## CamembertForQuestionAnswering [[autodoc]] CamembertForQuestionAnswering </pt> <tf> ## TFCamembertModel [[autodoc]] TFCamembertModel ## TFCamembertForCasualLM [[autodoc]] TFCamembertForCausalLM ## TFCamembertForMaskedLM [[autodoc]] TFCamembertForMaskedLM ## TFCamembertForSequenceClassification [[autodoc]] TFCamembertForSequenceClassification ## TFCamembertForMultipleChoice [[autodoc]] TFCamembertForMultipleChoice ## TFCamembertForTokenClassification [[autodoc]] TFCamembertForTokenClassification ## TFCamembertForQuestionAnswering [[autodoc]] TFCamembertForQuestionAnswering </tf> </frameworkcontent>
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/convnextv2.md
<!--Copyright 2023 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # ConvNeXt V2 ## Overview ConvNeXt V2 モデルは、Sanghyun Woo、Shobhik Debnath、Ronghang Hu、Xinlei Chen、Zhuang Liu, In So Kweon, Saining Xie. によっお [ConvNeXt V2: Co-designing and Scaling ConvNets with Masked Autoencoders](https://arxiv.org/abs/2301.00808) で提案されたした。 ConvNeXt V2 は、Vision Transformers の蚭蚈からむンスピレヌションを埗た玔粋な畳み蟌みモデル (ConvNet) であり、[ConvNeXT](convnext) の埌継です。 論文の芁玄は次のずおりです。 *アヌキテクチャの改善ず衚珟孊習フレヌムワヌクの改善により、芖芚認識の分野は 2020 幎代初頭に急速な近代化ずパフォヌマンスの向䞊を実珟したした。たずえば、ConvNeXt に代衚される最新の ConvNet は、さたざたなシナリオで匷力なパフォヌマンスを実蚌しおいたす。これらのモデルはもずもず ImageNet ラベルを䜿甚した教垫あり孊習甚に蚭蚈されたしたが、マスク オヌト゚ンコヌダヌ (MAE) などの自己教垫あり孊習手法からも朜圚的に恩恵を受けるこずができたす。ただし、これら 2 ぀のアプロヌチを単玔に組み合わせるず、パフォヌマンスが暙準以䞋になるこずがわかりたした。この論文では、完党畳み蟌みマスク オヌト゚ンコヌダ フレヌムワヌクず、チャネル間の機胜競合を匷化するために ConvNeXt アヌキテクチャに远加できる新しい Global Response Normalization (GRN) 局を提案したす。この自己教垫あり孊習手法ずアヌキテクチャの改善の共同蚭蚈により、ConvNeXt V2 ず呌ばれる新しいモデル ファミリが誕生したした。これにより、ImageNet 分類、COCO 怜出、ADE20K セグメンテヌションなどのさたざたな認識ベンチマヌクにおける玔粋な ConvNet のパフォヌマンスが倧幅に向䞊したす。たた、ImageNet でトップ 1 の粟床 76.7% を誇る効率的な 370 䞇パラメヌタの Atto モデルから、最先端の 88.9% を達成する 650M Huge モデルたで、さたざたなサむズの事前トレヌニング枈み ConvNeXt V2 モデルも提䟛しおいたす。公開トレヌニング デヌタのみを䜿甚した粟床*。 <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/convnextv2_architecture.png" alt="描画" width="600"/> <small> ConvNeXt V2 アヌキテクチャ。 <a href="https://arxiv.org/abs/2301.00808">元の論文</a>から抜粋。</small> このモデルは [adirik](https://huggingface.co/adirik) によっお提䟛されたした。元のコヌドは [こちら](https://github.com/facebookresearch/ConvNeXt-V2) にありたす。 ## Resources ConvNeXt V2 の䜿甚を開始するのに圹立぀公匏 Hugging Face およびコミュニティ (🌎 で瀺される) リ゜ヌスのリスト。 <PipelineTag pipeline="image-classification"/> - [`ConvNextV2ForImageClassification`] は、この [サンプル スクリプト](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-classification) および [ノヌトブック](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb)。 ここに含めるリ゜ヌスの送信に興味がある堎合は、お気軜にプル リク゚ストを開いおください。審査させおいただきたす。リ゜ヌスは、既存のリ゜ヌスを耇補するのではなく、䜕か新しいものを瀺すこずが理想的です。 ## ConvNextV2Config [[autodoc]] ConvNextV2Config ## ConvNextV2Model [[autodoc]] ConvNextV2Model - forward ## ConvNextV2ForImageClassification [[autodoc]] ConvNextV2ForImageClassification - forward ## TFConvNextV2Model [[autodoc]] TFConvNextV2Model - call ## TFConvNextV2ForImageClassification [[autodoc]] TFConvNextV2ForImageClassification - call
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/bert-generation.md
<!--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. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # BertGeneration ## Overview BertGeneration モデルは、次を䜿甚しおシヌケンス間のタスクに利甚できる BERT モデルです。 [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://arxiv.org/abs/1907.12461) で提案されおいる [`EncoderDecoderModel`] タスク、Sascha Rothe、Sishi Nagayan、Aliaksei Severyn 著。 論文の芁玄は次のずおりです。 *倧芏暡なニュヌラル モデルの教垫なし事前トレヌニングは、最近、自然蚀語凊理に革呜をもたらしたした。による NLP 実践者は、公開されたチェックポむントからりォヌムスタヌトしお、耇数の項目で最先端の技術を掚進しおきたした。 コンピュヌティング時間を倧幅に節玄しながらベンチマヌクを実行したす。これたでのずころ、䞻に自然蚀語に焊点を圓おおきたした。 タスクを理解する。この論文では、シヌケンス生成のための事前トレヌニングされたチェックポむントの有効性を実蚌したす。私たちは 公開されおいる事前トレヌニング枈み BERT ず互換性のある Transformer ベヌスのシヌケンス間モデルを開発したした。 GPT-2 および RoBERTa チェックポむントを䜿甚し、モデルの初期化の有甚性に぀いお広範な実蚌研究を実斜したした。 ゚ンコヌダずデコヌダ、これらのチェックポむント。私たちのモデルは、機械翻蚳に関する新しい最先端の結果をもたらしたす。 テキストの芁玄、文の分割、および文の融合。* ## Usage examples and tips - モデルを [`EncoderDecoderModel`] ず組み合わせお䜿甚​​しお、2 ぀の事前トレヌニングされたモデルを掻甚できたす。 埌続の埮調敎のための BERT チェックポむント。 ```python >>> # leverage checkpoints for Bert2Bert model... >>> # use BERT's cls token as BOS token and sep token as EOS token >>> encoder = BertGenerationEncoder.from_pretrained("bert-large-uncased", bos_token_id=101, eos_token_id=102) >>> # add cross attention layers and use BERT's cls token as BOS token and sep token as EOS token >>> decoder = BertGenerationDecoder.from_pretrained( ... "bert-large-uncased", add_cross_attention=True, is_decoder=True, bos_token_id=101, eos_token_id=102 ... ) >>> bert2bert = EncoderDecoderModel(encoder=encoder, decoder=decoder) >>> # create tokenizer... >>> tokenizer = BertTokenizer.from_pretrained("bert-large-uncased") >>> input_ids = tokenizer( ... "This is a long article to summarize", add_special_tokens=False, return_tensors="pt" ... ).input_ids >>> labels = tokenizer("This is a short summary", return_tensors="pt").input_ids >>> # train... >>> loss = bert2bert(input_ids=input_ids, decoder_input_ids=labels, labels=labels).loss >>> loss.backward() ``` - 事前トレヌニングされた [`EncoderDecoderModel`] もモデル ハブで盎接利甚できたす。 ```python >>> # instantiate sentence fusion model >>> sentence_fuser = EncoderDecoderModel.from_pretrained("google/roberta2roberta_L-24_discofuse") >>> tokenizer = AutoTokenizer.from_pretrained("google/roberta2roberta_L-24_discofuse") >>> input_ids = tokenizer( ... "This is the first sentence. This is the second sentence.", add_special_tokens=False, return_tensors="pt" ... ).input_ids >>> outputs = sentence_fuser.generate(input_ids) >>> print(tokenizer.decode(outputs[0])) ``` チップ - [`BertGenerationEncoder`] ず [`BertGenerationDecoder`] は、 [`EncoderDecoder`] ず組み合わせたす。 - 芁玄、文の分割、文の融合、および翻蚳の堎合、入力に特別なトヌクンは必芁ありたせん。 したがっお、入力の末尟に EOS トヌクンを远加しないでください。 このモデルは、[patrickvonplaten](https://huggingface.co/patrickvonplaten) によっお提䟛されたした。元のコヌドは次のずおりです [ここ](https://tfhub.dev/s?module-type=text-generation&subtype=module,placeholder) がありたす。 ## BertGenerationConfig [[autodoc]] BertGenerationConfig ## BertGenerationTokenizer [[autodoc]] BertGenerationTokenizer - save_vocabulary ## BertGenerationEncoder [[autodoc]] BertGenerationEncoder - forward ## BertGenerationDecoder [[autodoc]] BertGenerationDecoder - forward
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/albert.md
<!--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. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # ALBERT <div class="flex flex-wrap space-x-1"> <a href="https://huggingface.co/models?filter=albert"> <img alt="Models" src="https://img.shields.io/badge/All_model_pages-albert-blueviolet"> </a> <a href="https://huggingface.co/spaces/docs-demos/albert-base-v2"> <img alt="Spaces" src="https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue"> </a> </div> ## 抂芁 ALBERTモデルは、「[ALBERT: A Lite BERT for Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942)」ずいう論文でZhenzhong Lan、Mingda Chen、Sebastian Goodman、Kevin Gimpel、Piyush Sharma、Radu Soricutによっお提案されたした。BERTのメモリ消費を枛らしトレヌニングを高速化するためのパラメヌタ削枛技術を2぀瀺しおいたす - 埋め蟌み行列を2぀の小さな行列に分割する。 - グルヌプ間で分割された繰り返し局を䜿甚する。 論文の芁旚は以䞋の通りです *自然蚀語衚珟の事前孊習時にモデルのサむズを増やすず、䞋流タスクのパフォヌマンスが向䞊するこずがしばしばありたす。しかし、ある時点でさらなるモデルの増倧は、GPU/TPUのメモリ制限、長い蚓緎時間、予期せぬモデルの劣化ずいった問題のために困難になりたす。これらの問題に察凊するために、我々はBERTのメモリ消費を䜎枛し、蚓緎速床を高めるための2぀のパラメヌタ削枛技術を提案したす。包括的な実蚌的蚌拠は、我々の提案方法が元のBERTに比べおはるかによくスケヌルするモデルを生み出すこずを瀺しおいたす。たた、文間の䞀貫性をモデリングに焊点を圓おた自己教垫あり損倱を䜿甚し、耇数の文が含たれる䞋流タスクに䞀貫しお助けずなるこずを瀺したす。その結果、我々の最良のモデルは、BERT-largeに比べおパラメヌタが少ないにもかかわらず、GLUE、RACE、SQuADベンチマヌクで新たな最先端の結果を確立したす。* このモデルは[lysandre](https://huggingface.co/lysandre)により提䟛されたした。このモデルのjaxバヌゞョンは[kamalkraj](https://huggingface.co/kamalkraj)により提䟛されたした。オリゞナルのコヌドは[こちら](https://github.com/google-research/ALBERT)で芋るこずができたす。 ## 䜿甚䞊のヒント - ALBERTは絶察䜍眮埋め蟌みを䜿甚するモデルなので、通垞、入力を巊偎ではなく右偎にパディングするこずが掚奚されたす。 - ALBERTは繰り返し局を䜿甚するためメモリ䜿甚量は小さくなりたすが、同じ数の繰り返し局を反埩しなければならないため、隠れ局の数が同じであればBERTのようなアヌキテクチャず同様の蚈算コストがかかりたす。 - 埋め蟌みサむズEは隠れサむズHず異なりたすが、これは埋め蟌みが文脈に䟝存しない䞀぀の埋め蟌みベクトルが䞀぀のトヌクンを衚すのに察し、隠れ状態は文脈に䟝存する1぀の隠れ状態がトヌクン系列を衚すため、H >> Eずするこずがより論理的です。たた、埋め蟌み行列のサむズはV x Eず倧きいですVは語圙サむズ。E < Hであれば、パラメヌタは少なくなりたす。 - 局はパラメヌタを共有するグルヌプに分割されおいたすメモリ節玄のため。次文予枬NSP: Next Sentence Predictionは文の順序予枬に眮き換えられたす入力では、2぀の文AずBそれらは連続しおいるがあり、Aに続いおBを䞎えるか、Bに続いおAを䞎えたす。モデルはそれらが入れ替わっおいるかどうかを予枬する必芁がありたす。 ## 参考資料 - [テキスト分類タスクガむド](../tasks/sequence_classification) - [トヌクン分類タスクガむド](../tasks/token_classification) - [質問応答タスクガむド](../tasks/question_answering) - [マスクされた蚀語モデルタスクガむド](../tasks/masked_language_modeling) - [倚肢遞択タスクガむド](../tasks/multiple_choice) ## AlbertConfig [[autodoc]] AlbertConfig ## AlbertTokenizer [[autodoc]] AlbertTokenizer - build_inputs_with_special_tokens - get_special_tokens_mask - create_token_type_ids_from_sequences - save_vocabulary ## AlbertTokenizerFast [[autodoc]] AlbertTokenizerFast ## Albert specific outputs [[autodoc]] models.albert.modeling_albert.AlbertForPreTrainingOutput [[autodoc]] models.albert.modeling_tf_albert.TFAlbertForPreTrainingOutput <frameworkcontent> <pt> ## AlbertModel [[autodoc]] AlbertModel - forward ## AlbertForPreTraining [[autodoc]] AlbertForPreTraining - forward ## AlbertForMaskedLM [[autodoc]] AlbertForMaskedLM - forward ## AlbertForSequenceClassification [[autodoc]] AlbertForSequenceClassification - forward ## AlbertForMultipleChoice [[autodoc]] AlbertForMultipleChoice ## AlbertForTokenClassification [[autodoc]] AlbertForTokenClassification - forward ## AlbertForQuestionAnswering [[autodoc]] AlbertForQuestionAnswering - forward </pt> <tf> ## TFAlbertModel [[autodoc]] TFAlbertModel - call ## TFAlbertForPreTraining [[autodoc]] TFAlbertForPreTraining - call ## TFAlbertForMaskedLM [[autodoc]] TFAlbertForMaskedLM - call ## TFAlbertForSequenceClassification [[autodoc]] TFAlbertForSequenceClassification - call ## TFAlbertForMultipleChoice [[autodoc]] TFAlbertForMultipleChoice - call ## TFAlbertForTokenClassification [[autodoc]] TFAlbertForTokenClassification - call ## TFAlbertForQuestionAnswering [[autodoc]] TFAlbertForQuestionAnswering - call </tf> <jax> ## FlaxAlbertModel [[autodoc]] FlaxAlbertModel - __call__ ## FlaxAlbertForPreTraining [[autodoc]] FlaxAlbertForPreTraining - __call__ ## FlaxAlbertForMaskedLM [[autodoc]] FlaxAlbertForMaskedLM - __call__ ## FlaxAlbertForSequenceClassification [[autodoc]] FlaxAlbertForSequenceClassification - __call__ ## FlaxAlbertForMultipleChoice [[autodoc]] FlaxAlbertForMultipleChoice - __call__ ## FlaxAlbertForTokenClassification [[autodoc]] FlaxAlbertForTokenClassification - __call__ ## FlaxAlbertForQuestionAnswering [[autodoc]] FlaxAlbertForQuestionAnswering - __call__ </jax> </frameworkcontent>
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/autoformer.md
<!--Copyright 2023 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Autoformer ## 抂芁 Autoformerモデルは、「[Autoformer: Decomposition Transformers with Auto-Correlation for Long-Term Series Forecasting](https://arxiv.org/abs/2106.13008)」ずいう論文でHaixu Wu、Jiehui Xu、Jianmin Wang、Mingsheng Longによっお提案されたした。 このモデルは、予枬プロセス䞭にトレンドず季節性成分を逐次的に分解できる深局分解アヌキテクチャずしおTransformerを増匷したす。 論文の芁旚は以䞋の通りです *䟋えば異垞気象の早期譊告や長期的な゚ネルギヌ消費蚈画ずいった実応甚においお、予枬時間を延長するこずは重芁な芁求です。本論文では、時系列の長期予枬問題を研究しおいたす。以前のTransformerベヌスのモデルは、長距離䟝存関係を発芋するために様々なセルフアテンション機構を採甚しおいたす。しかし、長期未来の耇雑な時間的パタヌンによっおモデルが信頌できる䟝存関係を芋぀けるこずを劚げられたす。たた、Transformerは、長い系列の効率化のためにポむントワむズなセルフアテンションのスパヌスバヌゞョンを採甚する必芁があり、情報利甚のボトルネックずなりたす。Transformerを超えお、我々は自己盞関機構を持぀新しい分解アヌキテクチャずしおAutoformerを蚭蚈したした。系列分解の事前凊理の慣行を砎り、それを深局モデルの基本的な内郚ブロックずしお革新したす。この蚭蚈は、耇雑な時系列に察するAutoformerの進行的な分解胜力を匷化したす。さらに、確率過皋理論に觊発されお、系列の呚期性に基づいた自己盞関機構を蚭蚈し、サブ系列レベルでの䟝存関係の発芋ず衚珟の集玄を行いたす。自己盞関は効率ず粟床の䞡方でセルフアテンションを䞊回りたす。長期予枬においお、Autoformerは、゚ネルギヌ、亀通、経枈、気象、疟病の5぀の実甚的な応甚をカバヌする6぀のベンチマヌクで38%の盞察的な改善をもたらし、最先端の粟床を達成したす。* このモデルは[elisim](https://huggingface.co/elisim)ず[kashif](https://huggingface.co/kashif)より提䟛されたした。 オリゞナルのコヌドは[こちら](https://github.com/thuml/Autoformer)で芋るこずができたす。 ## 参考資料 Autoformerの䜿甚を開始するのに圹立぀公匏のHugging Faceおよびコミュニティ🌎で瀺されおいるの参考資料の䞀芧です。ここに参考資料を提出したい堎合は、気兌ねなくPull Requestを開いおください。私たちはそれをレビュヌいたしたす参考資料は、既存のものを耇補するのではなく、䜕か新しいこずを瀺すこずが理想的です。 - HuggingFaceブログでAutoformerに関するブログ蚘事をチェックしおください[はい、Transformersは時系列予枬に効果的です+ Autoformer](https://huggingface.co/blog/autoformer) ## AutoformerConfig [[autodoc]] AutoformerConfig ## AutoformerModel [[autodoc]] AutoformerModel - forward ## AutoformerForPrediction [[autodoc]] AutoformerForPrediction - forward
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/clipseg.md
<!--Copyright 2022 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # CLIPSeg ## Overview CLIPSeg モデルは、Timo LÃŒddecke, Alexander Ecker によっお [Image Segmentation using Text and Image Prompts](https://arxiv.org/abs/2112.10003) で提案されたした。 そしおアレクサンダヌ・゚ッカヌ。 CLIPSeg は、れロショットおよびワンショット画像セグメンテヌションのために、凍結された [CLIP](clip) モデルの䞊に最小限のデコヌダを远加したす。 論文の芁玄は次のずおりです。 *画像のセグメンテヌションは通垞、トレヌニングによっお解決されたす。 オブゞェクト クラスの固定セットのモデル。埌で远加のクラスやより耇雑なク゚リを組み蟌むずコストがかかりたす これらの匏を含むデヌタセットでモデルを再トレヌニングする必芁があるためです。ここでシステムを提案したす 任意の情報に基づいお画像セグメンテヌションを生成できたす。 テスト時にプロンプ​​トが衚瀺されたす。プロンプトはテキストたたは 画像。このアプロヌチにより、統䞀されたモデルを䜜成できたす。 3 ぀の䞀般的なセグメンテヌション タスクに぀いお (1 回トレヌニング枈み) 参照匏のセグメンテヌション、れロショット セグメンテヌション、ワンショット セグメンテヌションずいう明確な課題が䌎いたす。 CLIP モデルをバックボヌンずしお構築し、これをトランスベヌスのデコヌダで拡匵しお、高密床なデヌタ通信を可胜にしたす。 予枬。の拡匵バヌゞョンでトレヌニングした埌、 PhraseCut デヌタセット、私たちのシステムは、フリヌテキスト プロンプトたたは ク゚リを衚す远加の画像。埌者の画像ベヌスのプロンプトのさたざたなバリ゚ヌションを詳现に分析したす。 この新しいハむブリッド入力により、動的適応が可胜になりたす。 前述の 3 ぀のセグメンテヌション タスクのみですが、 テキストたたは画像をク゚リするバむナリ セグメンテヌション タスクに 定匏化するこずができる。最埌に、システムがうたく適応しおいるこずがわかりたした アフォヌダンスたたはプロパティを含む䞀般化されたク゚リ* <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/clipseg_architecture.png" alt="描画" width="600"/> <small> CLIPSeg の抂芁。 <a href="https://arxiv.org/abs/2112.10003">元の論文から抜粋。</a> </small> このモデルは、[nielsr](https://huggingface.co/nielsr) によっお提䟛されたした。 元のコヌドは [ここ](https://github.com/timojl/clipseg) にありたす。 ## Usage tips - [`CLIPSegForImageSegmentation`] は、[`CLIPSegModel`] の䞊にデコヌダを远加したす。埌者は [`CLIPModel`] ず同じです。 - [`CLIPSegForImageSegmentation`] は、テスト時に任意のプロンプトに基づいお画像セグメンテヌションを生成できたす。プロンプトはテキストのいずれかです (`input_ids` ずしおモデルに提䟛される) たたは画像 (`conditional_pixel_values` ずしおモデルに提䟛される)。カスタムを提䟛するこずもできたす 条件付き埋め蟌み (`conditional_embeddings`ずしおモデルに提䟛されたす)。 ## Resources CLIPSeg の䜿甚を開始するのに圹立぀、公匏 Hugging Face およびコミュニティ (🌎 で瀺されおいる) リ゜ヌスのリスト。ここに含めるリ゜ヌスの送信に興味がある堎合は、お気軜にプル リク゚ストを開いおください。審査させおいただきたす。リ゜ヌスは、既存のリ゜ヌスを耇補するのではなく、䜕か新しいものを瀺すこずが理想的です。 <PipelineTag pipeline="image-segmentation"/> - [CLIPSeg を䜿甚したれロショット画像セグメンテヌション](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/CLIPSeg/Zero_shot_image_segmentation_with_CLIPSeg.ipynb) を説明するノヌトブック。 ## CLIPSegConfig [[autodoc]] CLIPSegConfig - from_text_vision_configs ## CLIPSegTextConfig [[autodoc]] CLIPSegTextConfig ## CLIPSegVisionConfig [[autodoc]] CLIPSegVisionConfig ## CLIPSegProcessor [[autodoc]] CLIPSegProcessor ## CLIPSegModel [[autodoc]] CLIPSegModel - forward - get_text_features - get_image_features ## CLIPSegTextModel [[autodoc]] CLIPSegTextModel - forward ## CLIPSegVisionModel [[autodoc]] CLIPSegVisionModel - forward ## CLIPSegForImageSegmentation [[autodoc]] CLIPSegForImageSegmentation - forward
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/conditional_detr.md
<!--Copyright 2022 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Conditional DETR ## Overview 条件付き DETR モデルは、[Conditional DETR for Fast Training Convergence](https://arxiv.org/abs/2108.06152) で Depu Meng、Xiaokang Chen、Zejia Fan、Gang Zeng、Houqiang Li、Yuhui Yuan、Lei Sun, Jingdong Wang によっお提案されたした。王京東。条件付き DETR は、高速 DETR トレヌニングのための条件付きクロスアテンション メカニズムを提䟛したす。条件付き DETR は DETR よりも 6.7 倍から 10 倍速く収束したす。 論文の芁玄は次のずおりです。 *最近開発された DETR アプロヌチは、トランスフォヌマヌ ゚ンコヌダヌおよびデコヌダヌ アヌキテクチャを物䜓怜出に適甚し、有望なパフォヌマンスを実珟したす。この論文では、トレヌニングの収束が遅いずいう重芁な問題を扱い、高速 DETR トレヌニングのための条件付きクロスアテンション メカニズムを玹介したす。私たちのアプロヌチは、DETR におけるクロスアテンションが 4 ぀の四肢の䜍眮特定ずボックスの予枬にコンテンツの埋め蟌みに倧きく䟝存しおいるため、高品質のコンテンツの埋め蟌みの必芁性が高たり、トレヌニングの難易床が高くなるずいう点に動機づけられおいたす。条件付き DETR ず呌ばれる私たちのアプロヌチは、デコヌダヌのマルチヘッド クロスアテンションのためにデコヌダヌの埋め蟌みから条件付きの空間ク゚リを孊習したす。利点は、条件付き空間ク゚リを通じお、各クロスアテンション ヘッドが、個別の領域 (たずえば、1 ぀のオブゞェクトの端たたはオブゞェクト ボックス内の領域) を含むバンドに泚目できるこずです。これにより、オブゞェクト分類ずボックス回垰のための個別の領域をロヌカラむズするための空間範囲が狭たり、コンテンツの埋め蟌みぞの䟝存が緩和され、トレヌニングが容易になりたす。実隓結果は、条件付き DETR がバックボヌン R50 および R101 で 6.7 倍速く収束し、より匷力なバックボヌン DC5-R50 および DC5-R101 で 10 倍速く収束するこずを瀺しおいたす。コヌドは https://github.com/Atten4Vis/ConditionalDETR で入手できたす。* <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/conditional_detr_curve.jpg" alt="描画" width="600"/> <small> 条件付き DETR は、元の DETR に比べおはるかに速い収束を瀺したす。 <a href="https://arxiv.org/abs/2108.06152">元の論文</a>から匕甚。</small> このモデルは [DepuMeng](https://huggingface.co/DepuMeng) によっお寄皿されたした。元のコヌドは [ここ](https://github.com/Atten4Vis/ConditionalDETR) にありたす。 ## Resources - [オブゞェクト怜出タスクガむド](../tasks/object_detection) ## ConditionalDetrConfig [[autodoc]] ConditionalDetrConfig ## ConditionalDetrImageProcessor [[autodoc]] ConditionalDetrImageProcessor - preprocess - post_process_object_detection - post_process_instance_segmentation - post_process_semantic_segmentation - post_process_panoptic_segmentation ## ConditionalDetrFeatureExtractor [[autodoc]] ConditionalDetrFeatureExtractor - __call__ - post_process_object_detection - post_process_instance_segmentation - post_process_semantic_segmentation - post_process_panoptic_segmentation ## ConditionalDetrModel [[autodoc]] ConditionalDetrModel - forward ## ConditionalDetrForObjectDetection [[autodoc]] ConditionalDetrForObjectDetection - forward ## ConditionalDetrForSegmentation [[autodoc]] ConditionalDetrForSegmentation - forward
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/bigbird_pegasus.md
<!--Copyright 2021 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # BigBirdPegasus ## Overview BigBird モデルは、[Big Bird: Transformers for Longer Sequences](https://arxiv.org/abs/2007.14062) で提案されたした。 ザヒヌル、マンゞルずグルガネシュ、グルずダベむ、クマヌル・アノィナノァず゚むンズリヌ、ゞョシュアずアルベルティ、クリスずオンタノン、 サンティアゎずファム、フィリップずラブラ、アニルヌドずワン、キヌファンずダン、リヌなど。 BigBird は泚目床が䜎い BERT などの Transformer ベヌスのモデルをさらに長いシヌケンスに拡匵する、Transformer ベヌスのモデル。たばらに加えお アテンションず同様に、BigBird は入力シヌケンスにランダム アテンションだけでなくグロヌバル アテンションも適甚したす。理論的には、 たばらで党䜓的でランダムな泚意を適甚するず、完党な泚意に近づくこずが瀺されおいたすが、 長いシヌケンスでは蚈算効率が倧幅に向䞊したす。より長いコンテキストを凊理できる機胜の結果ずしお、 BigBird は、質問応答や BERT たたは RoBERTa ず比范した芁玄。 論文の芁玄は次のずおりです。 *BERT などのトランスフォヌマヌベヌスのモデルは、NLP で最も成功した深局孊習モデルの 1 ぀です。 残念ながら、それらの䞭栞的な制限の 1 ぀は、シヌケンスに察する二次䟝存性 (䞻にメモリに関する) です。 完党な泚意メカニズムによる長さです。これを解決するために、BigBird は、たばらな泚意メカニズムを提案したす。 この二次䟝存関係を線圢に削枛したす。 BigBird がシヌケンス関数の汎甚近䌌噚であるこずを瀺したす。 チュヌリングは完党であるため、二次完党泚意モデルのこれらの特性が保存されたす。途䞭、私たちの 理論分析により、O(1) 個のグロヌバル トヌクン (CLS など) を持぀利点の䞀郚が明らかになり、 スパヌス泚意メカニズムの䞀郚ずしおのシヌケンス。提案されたスパヌス アテンションは、次の長さのシヌケンスを凊理できたす。 同様のハヌドりェアを䜿甚しお以前に可胜であったものの 8 倍。より長いコンテキストを凊理できる機胜の結果ずしお、 BigBird は、質問応答や芁玄などのさたざたな NLP タスクのパフォヌマンスを倧幅に向䞊させたす。私達も ゲノミクスデヌタぞの新しいアプリケヌションを提案したす。* ## Usage tips - BigBird の泚意がどのように機胜するかに぀いおの詳现な説明に぀いおは、[このブログ投皿](https://huggingface.co/blog/big-bird) を参照しおください。 - BigBird には、**original_full** ず **block_sparse** の 2 ぀の実装が付属しおいたす。シヌケンス長が 1024 未満の堎合、次を䜿甚したす。 **block_sparse** を䜿甚しおもメリットがないため、**original_full** を䜿甚するこずをお勧めしたす。 - コヌドは珟圚、3 ブロックず 2 グロヌバル ブロックのりィンドり サむズを䜿甚しおいたす。 - シヌケンスの長さはブロック サむズで割り切れる必芁がありたす。 - 珟圚の実装では **ITC** のみがサポヌトされおいたす。 - 珟圚の実装では **num_random_blocks = 0** はサポヌトされおいたせん。 - BigBirdPegasus は [PegasusTokenizer](https://github.com/huggingface/transformers/blob/main/src/transformers/models/pegasus/tokenization_pegasus.py) を䜿甚したす。 - BigBird は絶察䜍眮埋め蟌みを備えたモデルであるため、通垞は入力を右偎にパディングするこずをお勧めしたす。 巊。 元のコヌドは [こちら](https://github.com/google-research/bigbird) にありたす。 ## ドキュメント リ゜ヌス - [テキスト分類タスクガむド](../tasks/sequence_classification) - [質問回答タスク ガむド](../tasks/question_answering) - [因果蚀語モデリング タスク ガむド](../tasks/language_modeling) - [翻蚳タスクガむド](../tasks/translation) - [芁玄タスクガむド](../tasks/summarization) ## BigBirdPegasusConfig [[autodoc]] BigBirdPegasusConfig - all ## BigBirdPegasusModel [[autodoc]] BigBirdPegasusModel - forward ## BigBirdPegasusForConditionalGeneration [[autodoc]] BigBirdPegasusForConditionalGeneration - forward ## BigBirdPegasusForSequenceClassification [[autodoc]] BigBirdPegasusForSequenceClassification - forward ## BigBirdPegasusForQuestionAnswering [[autodoc]] BigBirdPegasusForQuestionAnswering - forward ## BigBirdPegasusForCausalLM [[autodoc]] BigBirdPegasusForCausalLM - forward
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/bertweet.md
<!--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. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # BERTweet ## Overview BERTweet モデルは、Dat Quoc Nguyen、Thanh Vu によっお [BERTweet: A pre-trained language model for English Tweets](https://www.aclweb.org/anthology/2020.emnlp-demos.2.pdf) で提案されたした。アン・トゥアン・グ゚ンさん。 論文の芁玄は次のずおりです。 *私たちは、英語ツむヌト甚に初めお公開された倧芏暡な事前トレヌニング枈み蚀語モデルである BERTweet を玹介したす。私たちのBERTweetは、 BERT ベヌスず同じアヌキテクチャ (Devlin et al., 2019) は、RoBERTa 事前トレヌニング手順 (Liu et al.) を䜿甚しおトレヌニングされたす。 al.、2019。実隓では、BERTweet が匷力なベヌスラむンである RoBERTa ベヌスおよび XLM-R ベヌスを䞊回るパフォヌマンスを瀺すこずが瀺されおいたす (Conneau et al., 2020)、3 ぀のツむヌト NLP タスクにおいお、以前の最先端モデルよりも優れたパフォヌマンス結果が埗られたした。 品詞タグ付け、固有衚珟認識およびテキスト分類。* ## Usage example ```python >>> import torch >>> from transformers import AutoModel, AutoTokenizer >>> bertweet = AutoModel.from_pretrained("vinai/bertweet-base") >>> # For transformers v4.x+: >>> tokenizer = AutoTokenizer.from_pretrained("vinai/bertweet-base", use_fast=False) >>> # For transformers v3.x: >>> # tokenizer = AutoTokenizer.from_pretrained("vinai/bertweet-base") >>> # INPUT TWEET IS ALREADY NORMALIZED! >>> line = "SC has first two presumptive cases of coronavirus , DHEC confirms HTTPURL via @USER :cry:" >>> input_ids = torch.tensor([tokenizer.encode(line)]) >>> with torch.no_grad(): ... features = bertweet(input_ids) # Models outputs are now tuples >>> # With TensorFlow 2.0+: >>> # from transformers import TFAutoModel >>> # bertweet = TFAutoModel.from_pretrained("vinai/bertweet-base") ``` <Tip> この実装は、トヌクン化方法を陀いお BERT ず同じです。詳现に぀いおは、[BERT ドキュメント](bert) を参照しおください。 API リファレンス情報。 </Tip> このモデルは [dqnguyen](https://huggingface.co/dqnguyen) によっお提䟛されたした。元のコヌドは [ここ](https://github.com/VinAIResearch/BERTweet) にありたす。 ## BertweetTokenizer [[autodoc]] BertweetTokenizer
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/bridgetower.md
<!--Copyright 2023 The Intel Labs Team Authors, The Microsoft Research Team Authors and 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. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # BridgeTower ## Overview BridgeTower モデルは、Xiao Xu、Chenfei Wu、Shachar Rosenman、Vasudev Lal、Wanxiang Che、Nan Duan [BridgeTower: Building Bridges Between Encoders in Vision-Language Representative Learning](https://arxiv.org/abs/2206.08657) で提案されたした。ドゥアン。このモデルの目暙は、 各ナニモヌダル ゚ンコヌダずクロスモヌダル ゚ンコヌダの間のブリッゞにより、クロスモヌダル ゚ンコヌダの各局での包括的か぀詳现な察話が可胜になり、远加のパフォヌマンスず蚈算コストがほずんど無芖できる皋床で、さたざたな䞋流タスクで優れたパフォヌマンスを実珟したす。 この論文は [AAAI'23](https://aaai.org/Conferences/AAAI-23/) 䌚議に採択されたした。 論文の芁玄は次のずおりです。 *TWO-TOWER アヌキテクチャを備えたビゞョン蚀語 (VL) モデルは、近幎の芖芚蚀語衚珟孊習の䞻流ずなっおいたす。 珟圚の VL モデルは、軜量のナニモヌダル ゚ンコヌダヌを䜿甚しお、ディヌプ クロスモヌダル ゚ンコヌダヌで䞡方のモダリティを同時に抜出、䜍眮合わせ、融合するこずを孊習するか、事前にトレヌニングされたディヌプ ナニモヌダル ゚ンコヌダヌから最終局のナニモヌダル衚珟を䞊郚のクロスモヌダル゚ンコヌダヌ。 どちらのアプロヌチも、芖芚蚀語衚珟の孊習を制限し、モデルのパフォヌマンスを制限する可胜性がありたす。この論文では、ナニモヌダル ゚ンコヌダの最䞊䜍局ずクロスモヌダル ゚ンコヌダの各局の間の接続を構築する耇数のブリッゞ局を導入する BRIDGETOWER を提案したす。 これにより、効果的なボトムアップのクロスモヌダル調敎ず、クロスモヌダル ゚ンコヌダヌ内の事前トレヌニング枈みナニモヌダル ゚ンコヌダヌのさたざたなセマンティック レベルの芖芚衚珟ずテキスト衚珟の間の融合が可胜になりたす。 BRIDGETOWER は 4M 画像のみで事前トレヌニングされおおり、さたざたな䞋流の芖芚蚀語タスクで最先端のパフォヌマンスを実珟したす。 特に、VQAv2 テスト暙準セットでは、BRIDGETOWER は 78.73% の粟床を達成し、同じ事前トレヌニング デヌタずほが無芖できる远加パラメヌタず蚈算コストで以前の最先端モデル METER を 1.09% 䞊回りたした。 特に、モデルをさらにスケヌリングするず、BRIDGETOWER は 81.15% の粟床を達成し、桁違いに倧きなデヌタセットで事前トレヌニングされたモデルを䞊回りたした。* <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/bridgetower_architecture%20.jpg" alt="drawing" width="600"/> <small> ブリッゞタワヌ アヌキテクチャ。 <a href="https://arxiv.org/abs/2206.08657">元の論文から抜粋。</a> </small> このモデルは、[Anahita Bhiwandiwalla](https://huggingface.co/anahita-b)、[Tiep Le](https://huggingface.co/Tile)、[Shaoyen Tseng](https://huggingface.co/shaoyent。元のコヌドは [ここ](https://github.com/microsoft/BridgeTower) にありたす。 ## Usage tips and examples BridgeTower は、ビゞュアル ゚ンコヌダヌ、テキスト ゚ンコヌダヌ、および耇数の軜量ブリッゞ レむダヌを備えたクロスモヌダル ゚ンコヌダヌで構成されたす。 このアプロヌチの目暙は、各ナニモヌダル ゚ンコヌダヌずクロスモヌダル ゚ンコヌダヌの間にブリッゞを構築し、クロスモヌダル ゚ンコヌダヌの各局で包括的か぀詳现な察話を可胜にするこずでした。 原則ずしお、提案されたアヌキテクチャでは、任意のビゞュアル、テキスト、たたはクロスモヌダル ゚ンコヌダを適甚できたす。 [`BridgeTowerProcessor`] は、[`RobertaTokenizer`] ず [`BridgeTowerImageProcessor`] を単䞀のむンスタンスにラップし、䞡方の機胜を実珟したす。 テキストを゚ンコヌドし、画像をそれぞれ甚意したす。 次の䟋は、[`BridgeTowerProcessor`] ず [`BridgeTowerForContrastiveLearning`] を䜿甚しお察照孊習を実行する方法を瀺しおいたす。 ```python >>> from transformers import BridgeTowerProcessor, BridgeTowerForContrastiveLearning >>> import requests >>> from PIL import Image >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" >>> image = Image.open(requests.get(url, stream=True).raw) >>> texts = ["An image of two cats chilling on a couch", "A football player scoring a goal"] >>> processor = BridgeTowerProcessor.from_pretrained("BridgeTower/bridgetower-large-itm-mlm-itc") >>> model = BridgeTowerForContrastiveLearning.from_pretrained("BridgeTower/bridgetower-large-itm-mlm-itc") >>> # forward pass >>> scores = dict() >>> for text in texts: ... # prepare inputs ... encoding = processor(image, text, return_tensors="pt") ... outputs = model(**encoding) ... scores[text] = outputs ``` 次の䟋は、[`BridgeTowerProcessor`] ず [`BridgeTowerForImageAndTextRetrieval`] を䜿甚しお画像テキストの取埗を実行する方法を瀺しおいたす。 ```python >>> from transformers import BridgeTowerProcessor, BridgeTowerForImageAndTextRetrieval >>> import requests >>> from PIL import Image >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" >>> image = Image.open(requests.get(url, stream=True).raw) >>> texts = ["An image of two cats chilling on a couch", "A football player scoring a goal"] >>> processor = BridgeTowerProcessor.from_pretrained("BridgeTower/bridgetower-base-itm-mlm") >>> model = BridgeTowerForImageAndTextRetrieval.from_pretrained("BridgeTower/bridgetower-base-itm-mlm") >>> # forward pass >>> scores = dict() >>> for text in texts: ... # prepare inputs ... encoding = processor(image, text, return_tensors="pt") ... outputs = model(**encoding) ... scores[text] = outputs.logits[0, 1].item() ``` 次の䟋は、[`BridgeTowerProcessor`] ず [`BridgeTowerForMaskedLM`] を䜿甚しおマスクされた蚀語モデリングを実行する方法を瀺しおいたす。 ```python >>> from transformers import BridgeTowerProcessor, BridgeTowerForMaskedLM >>> from PIL import Image >>> import requests >>> url = "http://images.cocodataset.org/val2017/000000360943.jpg" >>> image = Image.open(requests.get(url, stream=True).raw).convert("RGB") >>> text = "a <mask> looking out of the window" >>> processor = BridgeTowerProcessor.from_pretrained("BridgeTower/bridgetower-base-itm-mlm") >>> model = BridgeTowerForMaskedLM.from_pretrained("BridgeTower/bridgetower-base-itm-mlm") >>> # prepare inputs >>> encoding = processor(image, text, return_tensors="pt") >>> # forward pass >>> outputs = model(**encoding) >>> results = processor.decode(outputs.logits.argmax(dim=-1).squeeze(0).tolist()) >>> print(results) .a cat looking out of the window. ``` チップ - BridgeTower のこの実装では、[`RobertaTokenizer`] を䜿甚しおテキスト埋め蟌みを生成し、OpenAI の CLIP/ViT モデルを䜿甚しお芖芚的埋め蟌みを蚈算したす。 - 事前トレヌニングされた [bridgeTower-base](https://huggingface.co/BridgeTower/bridgetower-base) および [bridgetower マスクされた蚀語モデリングず画像テキスト マッチング](https://huggingface.co/BridgeTower/bridgetower--base-itm-mlm) のチェックポむント がリリヌスされたした。 - 画像怜玢およびその他の䞋流タスクにおける BridgeTower のパフォヌマンスに぀いおは、[衚 5](https://arxiv.org/pdf/2206.08657.pdf) を参照しおください。 - このモデルの PyTorch バヌゞョンは、torch 1.10 以降でのみ䜿甚できたす。 ## BridgeTowerConfig [[autodoc]] BridgeTowerConfig ## BridgeTowerTextConfig [[autodoc]] BridgeTowerTextConfig ## BridgeTowerVisionConfig [[autodoc]] BridgeTowerVisionConfig ## BridgeTowerImageProcessor [[autodoc]] BridgeTowerImageProcessor - preprocess ## BridgeTowerProcessor [[autodoc]] BridgeTowerProcessor - __call__ ## BridgeTowerModel [[autodoc]] BridgeTowerModel - forward ## BridgeTowerForContrastiveLearning [[autodoc]] BridgeTowerForContrastiveLearning - forward ## BridgeTowerForMaskedLM [[autodoc]] BridgeTowerForMaskedLM - forward ## BridgeTowerForImageAndTextRetrieval [[autodoc]] BridgeTowerForImageAndTextRetrieval - forward
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/bart.md
<!--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. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # BART <div class="flex flex-wrap space-x-1"> <a href="https://huggingface.co/models?filter=bart"> <img alt="Models" src="https://img.shields.io/badge/All_model_pages-bart-blueviolet"> </a> <a href="https://huggingface.co/spaces/docs-demos/bart-large-mnli"> <img alt="Spaces" src="https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue"> </a> </div> **免責事項:** 䜕か奇劙なものを芋぀けた堎合は、[Github 問題](https://github.com/huggingface/transformers/issues/new?assignees=&labels=&template=bug-report.md&title) を提出し、割り圓おおください。 @patrickvonplaten ## Overview Bart モデルは、[BART: Denoising Sequence-to-Sequence Pre-training for Natural Language Generation、 翻蚳ず理解](https://arxiv.org/abs/1910.13461) Mike Lewis、Yinhan Liu、Naman Goyal、Marjan 著 ガズビニネゞャド、アブデルラフマン・モハメド、オメル・レノィ、ベス・ストダノフ、ルヌク・れトルモむダヌ、2019幎10月29日。 芁玄によるず、 - Bart は、双方向゚ンコヌダ (BERT など) を備えた暙準の seq2seq/機械翻蚳アヌキテクチャを䜿甚したす。 巊から右ぞのデコヌダ (GPT など)。 - 事前トレヌニング タスクには、元の文の順序をランダムにシャッフルし、新しい埋め蟌みスキヌムが含たれたす。 ここで、テキストの範囲は単䞀のマスク トヌクンに眮き換えられたす。 - BART は、テキスト生成甚に埮調敎した堎合に特に効果的ですが、理解タスクにも適しおいたす。それ RoBERTa のパフォヌマンスを GLUE および SQuAD の同等のトレヌニング リ゜ヌスず同等にし、新たな成果を達成したす。 さたざたな抜象的な察話、質問応答、芁玄タスクに関する最先端の結果が埗られ、成果が埗られたす。 ルヌゞュは最倧6枚たで。 チップ - BART は絶察䜍眮埋め蟌みを備えたモデルであるため、通垞は入力を右偎にパディングするこずをお勧めしたす。 巊。 - ゚ンコヌダヌずデコヌダヌを備えたシヌケンスツヌシヌケンス モデル。゚ンコヌダには砎損したバヌゞョンのトヌクンが䟛絊され、デコヌダには元のトヌクンが䟛絊されたすただし、通垞のトランスフォヌマヌ デコヌダず同様に、将来のワヌドを隠すためのマスクがありたす。次の倉換の構成は、゚ンコヌダヌの事前トレヌニング タスクに適甚されたす。 * ランダムなトヌクンをマスクしたす (BERT ず同様) * ランダムなトヌクンを削陀したす * k 個のトヌクンのスパンを 1 ぀のマスク トヌクンでマスクしたす (0 トヌクンのスパンはマスク トヌクンの挿入です) * 文を䞊べ替えたす * ドキュメントを回転しお特定のトヌクンから開始するようにしたす このモデルは [sshleifer](https://huggingface.co/sshleifer) によっお提䟛されたした。著者のコヌドは [ここ](https://github.com/pytorch/fairseq/tree/master/examples/bart) にありたす。 ### Examples - シヌケンス間タスク甚の BART およびその他のモデルを埮調敎するための䟋ずスクリプトは、次の堎所にありたす。 [examples/pytorch/summarization/](https://github.com/huggingface/transformers/tree/main/examples/pytorch/summarization/README.md)。 - Hugging Face `datasets` を䜿甚しお [`BartForConditionalGeneration`] をトレヌニングする方法の䟋 オブゞェクトは、この [フォヌラム ディスカッション](https://discuss.huggingface.co/t/train-bart-for-conditional-generation-e-g-summarization/1904) で芋぀けるこずができたす。 - [抜出されたチェックポむント](https://huggingface.co/models?search=distilbart) は、この [論文](https://arxiv.org/abs/2010.13002) で説明されおいたす。 ## Implementation Notes - Bart はシヌケンスの分類に `token_type_ids` を䜿甚したせん。 [`BartTokenizer`] を䜿甚するか、 [`~BartTokenizer.encode`] を䜿甚しお適切に分割したす。 - [`BartModel`] のフォワヌドパスは、枡されなかった堎合、`decoder_input_ids` を䜜成したす。 これは、他のモデリング API ずは異なりたす。この機胜の䞀般的な䜿甚䟋は、マスクの塗り぀ぶしです。 - モデルの予枬は、次の堎合に元の実装ず同䞀になるように意図されおいたす。 `forced_bos_token_id=0`。ただし、これは、枡す文字列が次の堎合にのみ機胜したす。 [`fairseq.encode`] はスペヌスで始たりたす。 - [`~generation.GenerationMixin.generate`] は、次のような条件付き生成タスクに䜿甚する必芁がありたす。 芁玄に぀いおは、その docstring の䟋を参照しおください。 - *facebook/bart-large-cnn* 重みをロヌドするモデルには `mask_token_id` がないか、実行できたせん。 マスクを埋めるタスク。 ## Mask Filling `facebook/bart-base` および `facebook/bart-large` チェックポむントを䜿甚しお、マルチトヌクン マスクを埋めるこずができたす。 ```python from transformers import BartForConditionalGeneration, BartTokenizer model = BartForConditionalGeneration.from_pretrained("facebook/bart-large", forced_bos_token_id=0) tok = BartTokenizer.from_pretrained("facebook/bart-large") example_english_phrase = "UN Chief Says There Is No <mask> in Syria" batch = tok(example_english_phrase, return_tensors="pt") generated_ids = model.generate(batch["input_ids"]) assert tok.batch_decode(generated_ids, skip_special_tokens=True) == [ "UN Chief Says There Is No Plan to Stop Chemical Weapons in Syria" ] ``` ## Resources BART を始めるのに圹立぀公匏 Hugging Face およびコミュニティ (🌎 で瀺されおいる) リ゜ヌスのリスト。ここに含めるリ゜ヌスの送信に興味がある堎合は、お気軜にプル リク゚ストを開いおください。審査させおいただきたす。リ゜ヌスは、既存のリ゜ヌスを耇補するのではなく、䜕か新しいものを瀺すこずが理想的です。 <PipelineTag pipeline="summarization"/> - に関するブログ投皿 [分散トレヌニング: 🀗 Transformers ず Amazon SageMaker を䜿甚した芁玄のための BART/T5 のトレヌニング](https://huggingface.co/blog/sagemaker-distributed-training-seq2seq)。 - 方法に関するノヌトブック [blurr を䜿甚しお fastai で芁玄するために BART を埮調敎する](https://colab.research.google.com/github/ohmeow/ohmeow_website/blob/master/posts/2021-05-25-mbart-sequence-classification-with-blurr.ipynb). 🌎 🌎 - 方法に関するノヌトブック [トレヌナヌ クラスを䜿甚しお 2 ぀の蚀語で芁玄するために BART を埮調敎する](https://colab.research.google.com/github/elsanns/xai-nlp-notebooks/blob/master/fine_tune_bart_summarization_two_langs.ipynb)。 🌎 - [`BartForConditionalGeneration`] は、この [サンプル スクリプト](https://github.com/huggingface/transformers/tree/main/examples/pytorch/summarization) および [ノヌトブック](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/summarization.ipynb)。 - [`TFBartForConditionalGeneration`] は、この [サンプル スクリプト](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/summarization) および [ノヌトブック](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/summarization-tf.ipynb)。 - [`FlaxBartForConditionalGeneration`] は、この [サンプル スクリプト](https://github.com/huggingface/transformers/tree/main/examples/flax/summarization) でサポヌトされおいたす。 - [芁玄](https://huggingface.co/course/chapter7/5?fw=pt#summarization) 🀗 ハグフェむスコヌスの章。 - [芁玄タスクガむド](../tasks/summarization.md) <PipelineTag pipeline="fill-mask"/> - [`BartForConditionalGeneration`] は、この [サンプル スクリプト](https://github.com/huggingface/transformers/tree/main/examples/pytorch/language-modeling#robertabertdistilbert-and-masked-language-modeling) でサポヌトされおおり、 [ノヌトブック](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling.ipynb)。 - [`TFBartForConditionalGeneration`] は、この [サンプル スクリプト](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/language-modeling#run_mlmpy) および [ノヌトブック](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling-tf.ipynb)。 - [`FlaxBartForConditionalGeneration`] は、この [サンプル スクリプト](https://github.com/huggingface/transformers/tree/main/examples/flax/language-modeling#masked-language-modeling) および [ノヌトブック]( https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/masked_language_modeling_flax.ipynb)。 - [マスクされた蚀語モデリング](https://huggingface.co/course/chapter7/3?fw=pt) 🀗 顔ハグ コヌスの章。 - [マスクされた蚀語モデリング タスク ガむド](../tasks/masked_lang_modeling) <PipelineTag pipeline="translation"/> - [ヒンディヌ語から英語ぞの翻蚳に Seq2SeqTrainer を䜿甚しお mBART を埮調敎する]方法に関するノヌト (https://colab.research.google.com/github/vasudevgupta7/huggingface-tutorials/blob/main/translation_training.ipynb)。 🌎 - [`BartForConditionalGeneration`] は、この [サンプル スクリプト](https://github.com/huggingface/transformers/tree/main/examples/pytorch/translation) および [ノヌトブック](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/translation.ipynb)。 - [`TFBartForConditionalGeneration`] は、この [サンプル スクリプト](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/translation) および [ノヌトブック](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/translation-tf.ipynb)。 - [翻蚳タスクガむド](../tasks/translation) 以䞋も参照しおください。 - [テキスト分類タスクガむド](../tasks/sequence_classification) - [質問回答タスク ガむド](../tasks/question_answering) - [因果蚀語モデリング タスク ガむド](../tasks/language_modeling) - [抜出されたチェックポむント](https://huggingface.co/models?search=distilbart) は、この [論文](https://arxiv.org/abs/2010.13002) で説明されおいたす。 ## BartConfig [[autodoc]] BartConfig - all ## BartTokenizer [[autodoc]] BartTokenizer - all ## BartTokenizerFast [[autodoc]] BartTokenizerFast - all ## BartModel [[autodoc]] BartModel - forward ## BartForConditionalGeneration [[autodoc]] BartForConditionalGeneration - forward ## BartForSequenceClassification [[autodoc]] BartForSequenceClassification - forward ## BartForQuestionAnswering [[autodoc]] BartForQuestionAnswering - forward ## BartForCausalLM [[autodoc]] BartForCausalLM - forward ## TFBartModel [[autodoc]] TFBartModel - call ## TFBartForConditionalGeneration [[autodoc]] TFBartForConditionalGeneration - call ## TFBartForSequenceClassification [[autodoc]] TFBartForSequenceClassification - call ## FlaxBartModel [[autodoc]] FlaxBartModel - __call__ - encode - decode ## FlaxBartForConditionalGeneration [[autodoc]] FlaxBartForConditionalGeneration - __call__ - encode - decode ## FlaxBartForSequenceClassification [[autodoc]] FlaxBartForSequenceClassification - __call__ - encode - decode ## FlaxBartForQuestionAnswering [[autodoc]] FlaxBartForQuestionAnswering - __call__ - encode - decode ## FlaxBartForCausalLM [[autodoc]] FlaxBartForCausalLM - __call__
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/model_doc/cpm.md
<!--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. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # CPM ## Overview CPM モデルは、Zhengyan Zhang、Xu Han、Hao Zhou、Pei Ke、Yuxian Gu によっお [CPM: A Large-scale Generative Chinese Pre-trained Language Model](https://arxiv.org/abs/2012.00413) で提案されたした。葉埳明、秊裕䜳、 Yusheng Su、Haozhe Ji、Jian Guan、Fanchao Qi、Xiaozi 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。 論文の芁玄は次のずおりです。 *事前トレヌニングされた蚀語モデル (PLM) は、さたざたな䞋流の NLP タスクに有益であるこずが蚌明されおいたす。最近ではGPT-3、 1,750億個のパラメヌタず570GBの孊習デヌタを備え、数回の撮圱1枚でもの容量で倧きな泚目を集めたした れロショット孊習。ただし、GPT-3 を適甚しお䞭囜語の NLP タスクに察凊するこずは䟝然ずしお困難です。 GPT-3 の蚀語は䞻に英語であり、パラメヌタヌは公開されおいたせん。この技術レポヌトでは、 倧芏暡な䞭囜語トレヌニング デヌタに察する生成的事前トレヌニングを備えた䞭囜語事前トレヌニング枈み蚀語モデル (CPM)。最高に 私たちの知識の限りでは、26 億のパラメヌタず 100GB の䞭囜語トレヌニング デヌタを備えた CPM は、事前トレヌニングされた䞭囜語ずしおは最倧のものです。 蚀語モデルは、䌚話、゚ッセむの䜜成、 クロヌれテストず蚀語理解。広範な実隓により、CPM が倚くの環境で優れたパフォヌマンスを達成できるこずが実蚌されおいたす。 少数ショット (れロショットでも) 孊習の蚭定での NLP タスク。* このモデルは [canwenxu](https://huggingface.co/canwenxu) によっお提䟛されたした。オリゞナルの実装が芋぀かりたす ここ: https://github.com/TsinghuaAI/CPM-Generate <Tip> CPM のアヌキテクチャは、トヌクン化方法を陀いお GPT-2 ず同じです。詳现に぀いおは、[GPT-2 ドキュメント](gpt2) を参照しおください。 API リファレンス情報。 </Tip> ## CpmTokenizer [[autodoc]] CpmTokenizer ## CpmTokenizerFast [[autodoc]] CpmTokenizerFast
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/internal/modeling_utils.md
<!--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. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # カスタムレむダヌずナヌティリティ このペヌゞには、ラむブラリで䜿甚されるすべおのカスタム レむダヌず、モデリングに提䟛されるナヌティリティ関数がリストされたす。 これらのほずんどは、ラむブラリ内のモデルのコヌドを研究する堎合にのみ圹に立ちたす。 ## Pytorch custom modules [[autodoc]] pytorch_utils.Conv1D [[autodoc]] modeling_utils.PoolerStartLogits - forward [[autodoc]] modeling_utils.PoolerEndLogits - forward [[autodoc]] modeling_utils.PoolerAnswerClass - forward [[autodoc]] modeling_utils.SquadHeadOutput [[autodoc]] modeling_utils.SQuADHead - forward [[autodoc]] modeling_utils.SequenceSummary - forward ## PyTorch Helper Functions [[autodoc]] pytorch_utils.apply_chunking_to_forward [[autodoc]] pytorch_utils.find_pruneable_heads_and_indices [[autodoc]] pytorch_utils.prune_layer [[autodoc]] pytorch_utils.prune_conv1d_layer [[autodoc]] pytorch_utils.prune_linear_layer ## TensorFlow custom layers [[autodoc]] modeling_tf_utils.TFConv1D [[autodoc]] modeling_tf_utils.TFSequenceSummary ## TensorFlow loss functions [[autodoc]] modeling_tf_utils.TFCausalLanguageModelingLoss [[autodoc]] modeling_tf_utils.TFMaskedLanguageModelingLoss [[autodoc]] modeling_tf_utils.TFMultipleChoiceLoss [[autodoc]] modeling_tf_utils.TFQuestionAnsweringLoss [[autodoc]] modeling_tf_utils.TFSequenceClassificationLoss [[autodoc]] modeling_tf_utils.TFTokenClassificationLoss ## TensorFlow Helper Functions [[autodoc]] modeling_tf_utils.get_initializer [[autodoc]] modeling_tf_utils.keras_serializable [[autodoc]] modeling_tf_utils.shape_list
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/internal/file_utils.md
<!--Copyright 2021 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # 䞀般的なナヌティリティ このペヌゞには、ファむル `utils.py` にある Transformers の䞀般的なナヌティリティ関数がすべおリストされおいたす。 これらのほずんどは、ラむブラリで䞀般的なコヌドを孊習する堎合にのみ圹に立ちたす。 ## 列挙型ず名前付きタプル [[autodoc]] utils.ExplicitEnum [[autodoc]] utils.PaddingStrategy [[autodoc]] utils.TensorType ## 特別なデコレヌタヌ [[autodoc]] utils.add_start_docstrings [[autodoc]] utils.add_start_docstrings_to_model_forward [[autodoc]] utils.add_end_docstrings [[autodoc]] utils.add_code_sample_docstrings [[autodoc]] utils.replace_return_docstrings ## 特殊なプロパティ [[autodoc]] utils.cached_property ## その他のナヌティリティ [[autodoc]] utils._LazyModule
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/internal/audio_utils.md
<!--Copyright 2023 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # `FeatureExtractor` 甚のナヌティリティ このペヌゞには、*短時間フヌリ゚倉換* や *ログ メル スペクトログラム* などの䞀般的なアルゎリズムを䜿甚しお生のオヌディオから特別な特城を蚈算するために、オヌディオ [`FeatureExtractor`] で䜿甚できるすべおのナヌティリティ関数がリストされおいたす。 これらのほずんどは、ラむブラリ内のオヌディオ プロセッサのコヌドを孊習する堎合にのみ圹に立ちたす。 ## オヌディオ倉換 [[autodoc]] audio_utils.hertz_to_mel [[autodoc]] audio_utils.mel_to_hertz [[autodoc]] audio_utils.mel_filter_bank [[autodoc]] audio_utils.optimal_fft_length [[autodoc]] audio_utils.window_function [[autodoc]] audio_utils.spectrogram [[autodoc]] audio_utils.power_to_db [[autodoc]] audio_utils.amplitude_to_db
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/internal/generation_utils.md
<!--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. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # 発電甚ナヌティリティ このペヌゞには、[`~generation.GenerationMixin.generate`] で䜿甚されるすべおのナヌティリティ関数がリストされおいたす。 [`~generation.GenerationMixin.greedy_search`], [`~generation.GenerationMixin.contrastive_search`], [`~generation.GenerationMixin.sample`], [`~generation.GenerationMixin.beam_search`], [`~generation.GenerationMixin.beam_sample`], [`~generation.GenerationMixin.group_beam_search`]、および [`~generation.GenerationMixin.constrained_beam_search`]。 これらのほずんどは、ラむブラリ内の生成メ゜ッドのコヌドを孊習する堎合にのみ圹に立ちたす。 ## 出力を生成する [`~generation.GenerationMixin.generate`] の出力は、次のサブクラスのむンスタンスです。 [`~utils.ModelOutput`]。この出力は、返されたすべおの情報を含むデヌタ構造です。 [`~generation.GenerationMixin.generate`] によっお䜜成されたすが、タプルたたは蟞曞ずしおも䜿甚できたす。 以䞋に䟋を瀺したす。 ```python from transformers import GPT2Tokenizer, GPT2LMHeadModel tokenizer = GPT2Tokenizer.from_pretrained("gpt2") model = GPT2LMHeadModel.from_pretrained("gpt2") inputs = tokenizer("Hello, my dog is cute and ", return_tensors="pt") generation_output = model.generate(**inputs, return_dict_in_generate=True, output_scores=True) ``` `generation_output` オブゞェクトは、できる限り [`~generation.GreedySearchDecoderOnlyOutput`] です。 以䞋のそのクラスのドキュメントを参照しおください。これは、次の属性があるこずを意味したす。 - `sequences`: 生成されたトヌクンのシヌケンス - `scores` (オプション): 各生成ステップの蚀語モデリング ヘッドの予枬スコア - `hidden_​​states` (オプション): 生成ステップごずのモデルの隠れた状態 - `attentions` (オプション): 生成ステップごずのモデルのアテンションの重み ここでは、`output_scores=True`を枡したので `scores` がありたすが、`hidden_​​states` はありたせん。 `attentions` は、`output_hidden_​​states=True`たたは`output_attentions=True`を枡さなかったためです。 通垞ず同じように各属性にアクセスできたす。その属性がモデルから返されなかった堎合は、 は「なし」を取埗したす。ここで、たずえば`generation_output.scores`は、生成されたすべおの予枬スコアです。 蚀語モデリングのヘッドであり、`generation_output.attentions`は`None`です。 `generation_output` オブゞェクトをタプルずしお䜿甚する堎合、`None` 倀を持たない属性のみが保持されたす。 たずえば、ここには 2 ぀の芁玠、`loss`、次に`logits`がありたす。 ```python generation_output[:2] ``` たずえば、タプル `(generation_output.sequences,generation_output.scores)` を返したす。 `generation_output` オブゞェクトを蟞曞ずしお䜿甚する堎合、`None` を持たない属性のみが保持されたす。 ここでは、たずえば、`sequences`ず`scores`ずいう 2 ぀のキヌがありたす。 ここではすべおの出力タむプを文曞化したす。 ### PyTorch [[autodoc]] generation.GreedySearchEncoderDecoderOutput [[autodoc]] generation.GreedySearchDecoderOnlyOutput [[autodoc]] generation.SampleEncoderDecoderOutput [[autodoc]] generation.SampleDecoderOnlyOutput [[autodoc]] generation.BeamSearchEncoderDecoderOutput [[autodoc]] generation.BeamSearchDecoderOnlyOutput [[autodoc]] generation.BeamSampleEncoderDecoderOutput [[autodoc]] generation.BeamSampleDecoderOnlyOutput [[autodoc]] generation.ContrastiveSearchEncoderDecoderOutput [[autodoc]] generation.ContrastiveSearchDecoderOnlyOutput ### TensorFlow [[autodoc]] generation.TFGreedySearchEncoderDecoderOutput [[autodoc]] generation.TFGreedySearchDecoderOnlyOutput [[autodoc]] generation.TFSampleEncoderDecoderOutput [[autodoc]] generation.TFSampleDecoderOnlyOutput [[autodoc]] generation.TFBeamSearchEncoderDecoderOutput [[autodoc]] generation.TFBeamSearchDecoderOnlyOutput [[autodoc]] generation.TFBeamSampleEncoderDecoderOutput [[autodoc]] generation.TFBeamSampleDecoderOnlyOutput [[autodoc]] generation.TFContrastiveSearchEncoderDecoderOutput [[autodoc]] generation.TFContrastiveSearchDecoderOnlyOutput ### FLAX [[autodoc]] generation.FlaxSampleOutput [[autodoc]] generation.FlaxGreedySearchOutput [[autodoc]] generation.FlaxBeamSearchOutput ## LogitsProcessor [`LogitsProcessor`] を䜿甚しお、蚀語モデルのヘッドの予枬スコアを倉曎できたす。 䞖代。 ### PyTorch [[autodoc]] AlternatingCodebooksLogitsProcessor - __call__ [[autodoc]] ClassifierFreeGuidanceLogitsProcessor - __call__ [[autodoc]] EncoderNoRepeatNGramLogitsProcessor - __call__ [[autodoc]] EncoderRepetitionPenaltyLogitsProcessor - __call__ [[autodoc]] EpsilonLogitsWarper - __call__ [[autodoc]] EtaLogitsWarper - __call__ [[autodoc]] ExponentialDecayLengthPenalty - __call__ [[autodoc]] ForcedBOSTokenLogitsProcessor - __call__ [[autodoc]] ForcedEOSTokenLogitsProcessor - __call__ [[autodoc]] ForceTokensLogitsProcessor - __call__ [[autodoc]] HammingDiversityLogitsProcessor - __call__ [[autodoc]] InfNanRemoveLogitsProcessor - __call__ [[autodoc]] LogitNormalization - __call__ [[autodoc]] LogitsProcessor - __call__ [[autodoc]] LogitsProcessorList - __call__ [[autodoc]] LogitsWarper - __call__ [[autodoc]] MinLengthLogitsProcessor - __call__ [[autodoc]] MinNewTokensLengthLogitsProcessor - __call__ [[autodoc]] NoBadWordsLogitsProcessor - __call__ [[autodoc]] NoRepeatNGramLogitsProcessor - __call__ [[autodoc]] PrefixConstrainedLogitsProcessor - __call__ [[autodoc]] RepetitionPenaltyLogitsProcessor - __call__ [[autodoc]] SequenceBiasLogitsProcessor - __call__ [[autodoc]] SuppressTokensAtBeginLogitsProcessor - __call__ [[autodoc]] SuppressTokensLogitsProcessor - __call__ [[autodoc]] TemperatureLogitsWarper - __call__ [[autodoc]] TopKLogitsWarper - __call__ [[autodoc]] TopPLogitsWarper - __call__ [[autodoc]] TypicalLogitsWarper - __call__ [[autodoc]] UnbatchedClassifierFreeGuidanceLogitsProcessor - __call__ [[autodoc]] WhisperTimeStampLogitsProcessor - __call__ ### TensorFlow [[autodoc]] TFForcedBOSTokenLogitsProcessor - __call__ [[autodoc]] TFForcedEOSTokenLogitsProcessor - __call__ [[autodoc]] TFForceTokensLogitsProcessor - __call__ [[autodoc]] TFLogitsProcessor - __call__ [[autodoc]] TFLogitsProcessorList - __call__ [[autodoc]] TFLogitsWarper - __call__ [[autodoc]] TFMinLengthLogitsProcessor - __call__ [[autodoc]] TFNoBadWordsLogitsProcessor - __call__ [[autodoc]] TFNoRepeatNGramLogitsProcessor - __call__ [[autodoc]] TFRepetitionPenaltyLogitsProcessor - __call__ [[autodoc]] TFSuppressTokensAtBeginLogitsProcessor - __call__ [[autodoc]] TFSuppressTokensLogitsProcessor - __call__ [[autodoc]] TFTemperatureLogitsWarper - __call__ [[autodoc]] TFTopKLogitsWarper - __call__ [[autodoc]] TFTopPLogitsWarper - __call__ ### FLAX [[autodoc]] FlaxForcedBOSTokenLogitsProcessor - __call__ [[autodoc]] FlaxForcedEOSTokenLogitsProcessor - __call__ [[autodoc]] FlaxForceTokensLogitsProcessor - __call__ [[autodoc]] FlaxLogitsProcessor - __call__ [[autodoc]] FlaxLogitsProcessorList - __call__ [[autodoc]] FlaxLogitsWarper - __call__ [[autodoc]] FlaxMinLengthLogitsProcessor - __call__ [[autodoc]] FlaxSuppressTokensAtBeginLogitsProcessor - __call__ [[autodoc]] FlaxSuppressTokensLogitsProcessor - __call__ [[autodoc]] FlaxTemperatureLogitsWarper - __call__ [[autodoc]] FlaxTopKLogitsWarper - __call__ [[autodoc]] FlaxTopPLogitsWarper - __call__ [[autodoc]] FlaxWhisperTimeStampLogitsProcessor - __call__ ## StoppingCriteria [`StoppingCriteria`] を䜿甚しお、(EOS トヌクン以倖の) 生成を停止するタむミングを倉曎できたす。これは PyTorch 実装でのみ利甚可胜であるこずに泚意しおください。 [[autodoc]] StoppingCriteria - __call__ [[autodoc]] StoppingCriteriaList - __call__ [[autodoc]] MaxLengthCriteria - __call__ [[autodoc]] MaxTimeCriteria - __call__ ## Constraints [`Constraint`] を䜿甚するず、生成時に出力に特定のトヌクンたたはシヌケンスが含たれるように匷制できたす。これは PyTorch 実装でのみ利甚可胜であるこずに泚意しおください。 [[autodoc]] Constraint [[autodoc]] PhrasalConstraint [[autodoc]] DisjunctiveConstraint [[autodoc]] ConstraintListState ## BeamSearch [[autodoc]] BeamScorer - process - finalize [[autodoc]] BeamSearchScorer - process - finalize [[autodoc]] ConstrainedBeamSearchScorer - process - finalize ## Utilities [[autodoc]] top_k_top_p_filtering [[autodoc]] tf_top_k_top_p_filtering ## Streamers [[autodoc]] TextStreamer [[autodoc]] TextIteratorStreamer
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/internal/time_series_utils.md
<!--Copyright 2023 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # 時系列ナヌティリティ このペヌゞには、時系列ベヌスのモデルに䜿甚できるすべおのナヌティリティ関数ずクラスがリストされたす。 これらのほずんどは、時系列モデルのコヌドを研究しおいる堎合、たたは分散出力クラスのコレクションに远加したい堎合にのみ圹立ちたす。 ## Distributional Output [[autodoc]] time_series_utils.NormalOutput [[autodoc]] time_series_utils.StudentTOutput [[autodoc]] time_series_utils.NegativeBinomialOutput
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/internal/tokenization_utils.md
<!--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. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Utilities for Tokenizers このペヌゞには、トヌクナむザヌによっお䜿甚されるすべおのナヌティリティ関数 (䞻にクラス) がリストされたす。 [`~tokenization_utils_base.PreTrainedTokenizerBase`] 間の共通メ゜ッドを実装したす。 [`PreTrainedTokenizer`] ず [`PreTrainedTokenizerFast`] およびミックスむン [`~tokenization_utils_base.SpecialTokensMixin`]。 これらのほずんどは、ラむブラリ内のトヌクナむザヌのコヌドを孊習する堎合にのみ圹に立ちたす。 ## PreTrainedTokenizerBase [[autodoc]] tokenization_utils_base.PreTrainedTokenizerBase - __call__ - all ## SpecialTokensMixin [[autodoc]] tokenization_utils_base.SpecialTokensMixin ## Enums and namedtuples [[autodoc]] tokenization_utils_base.TruncationStrategy [[autodoc]] tokenization_utils_base.CharSpan [[autodoc]] tokenization_utils_base.TokenSpan
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/internal/image_processing_utils.md
!--Copyright 2022 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # 画像プロセッサ甚ナヌティリティ このペヌゞには、画像プロセッサヌで䜿甚されるすべおのナヌティリティヌ関数がリストされおいたす。䞻に機胜的なものです。 画像を凊理するために䜿甚される倉換。 これらのほずんどは、ラむブラリ内の画像プロセッサのコヌドを孊習する堎合にのみ圹に立ちたす。 ## Image Transformations [[autodoc]] image_transforms.center_crop [[autodoc]] image_transforms.center_to_corners_format [[autodoc]] image_transforms.corners_to_center_format [[autodoc]] image_transforms.id_to_rgb [[autodoc]] image_transforms.normalize [[autodoc]] image_transforms.pad [[autodoc]] image_transforms.rgb_to_id [[autodoc]] image_transforms.rescale [[autodoc]] image_transforms.resize [[autodoc]] image_transforms.to_pil_image ## ImageProcessingMixin [[autodoc]] image_processing_utils.ImageProcessingMixin
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/internal/trainer_utils.md
<!--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. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # トレヌナヌ甚ナヌティリティ このペヌゞには、[`Trainer`] で䜿甚されるすべおのナヌティリティ関数がリストされおいたす。 これらのほずんどは、ラむブラリ内のトレヌナヌのコヌドを孊習する堎合にのみ圹に立ちたす。 ## Utilities [[autodoc]] EvalPrediction [[autodoc]] IntervalStrategy [[autodoc]] enable_full_determinism [[autodoc]] set_seed [[autodoc]] torch_distributed_zero_first ## Callbacks internals [[autodoc]] trainer_callback.CallbackHandler ## Distributed Evaluation [[autodoc]] trainer_pt_utils.DistributedTensorGatherer ## Distributed Evaluation [[autodoc]] HfArgumentParser ## Debug Utilities [[autodoc]] debug_utils.DebugUnderflowOverflow
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/internal/pipelines_utils.md
<!--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. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # パむプラむン甚のナヌティリティ このペヌゞには、ラむブラリがパむプラむンに提䟛するすべおのナヌティリティ関数がリストされたす。 これらのほずんどは、ラむブラリ内のモデルのコヌドを研究する堎合にのみ圹に立ちたす。 ## Argument handling [[autodoc]] pipelines.ArgumentHandler [[autodoc]] pipelines.ZeroShotClassificationArgumentHandler [[autodoc]] pipelines.QuestionAnsweringArgumentHandler ## Data format [[autodoc]] pipelines.PipelineDataFormat [[autodoc]] pipelines.CsvPipelineDataFormat [[autodoc]] pipelines.JsonPipelineDataFormat [[autodoc]] pipelines.PipedPipelineDataFormat ## Utilities [[autodoc]] pipelines.PipelineException
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/main_classes/agent.md
<!--Copyright 2023 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # ゚ヌゞェントずツヌル <Tip warning={true}> Transformers Agents は実隓的な API であり、い぀でも倉曎される可胜性がありたす。゚ヌゞェントから返される結果 API たたは基瀎ずなるモデルは倉曎される傟向があるため、倉曎される可胜性がありたす。 </Tip> ゚ヌゞェントずツヌルの詳现に぀いおは、[入門ガむド](../transformers_agents) を必ずお読みください。このペヌゞ 基瀎ずなるクラスの API ドキュメントが含たれおいたす。 ## ゚ヌゞェント 私たちは 3 皮類の゚ヌゞェントを提䟛したす。[`HfAgent`] はオヌプン゜ヌス モデルの掚論゚ンドポむントを䜿甚し、[`LocalAgent`] は遞択したモデルをロヌカルで䜿甚し、[`OpenAiAgent`] は OpenAI クロヌズド モデルを䜿甚したす。 ### HfAgent [[autodoc]] HfAgent ### LocalAgent [[autodoc]] LocalAgent ### OpenAiAgent [[autodoc]] OpenAiAgent ### AzureOpenAiAgent [[autodoc]] AzureOpenAiAgent ### Agent [[autodoc]] Agent - chat - run - prepare_for_new_chat ## Tools ### load_tool [[autodoc]] load_tool ### Tool [[autodoc]] Tool ### PipelineTool [[autodoc]] PipelineTool ### RemoteTool [[autodoc]] RemoteTool ### launch_gradio_demo [[autodoc]] launch_gradio_demo ## ゚ヌゞェントの皮類 ゚ヌゞェントはツヌル間であらゆる皮類のオブゞェクトを凊理できたす。ツヌルは完党にマルチモヌダルであるため、受け取りず返品が可胜です テキスト、画像、オヌディオ、ビデオなどのタむプ。ツヌル間の互換性を高めるためだけでなく、 これらの戻り倀を ipython (jupyter、colab、ipython ノヌトブックなど) で正しくレンダリングするには、ラッパヌ クラスを実装したす。 このタむプの呚り。 ラップされたオブゞェクトは最初ず同じように動䜜し続けるはずです。テキストオブゞェクトは䟝然ずしお文字列たたは画像ずしお動䜜する必芁がありたす オブゞェクトは䟝然ずしお `PIL.Image` ずしお動䜜するはずです。 これらのタむプには、次の 3 ぀の特定の目的がありたす。 - 型に察しお `to_raw` を呌び出すず、基になるオブゞェクトが返されるはずです - 型に察しお `to_string` を呌び出すず、オブゞェクトを文字列ずしお返す必芁がありたす。`AgentText` の堎合は文字列になる可胜性がありたす。 ただし、他のむンスタンスのオブゞェクトのシリアル化されたバヌゞョンのパスになりたす。 - ipython カヌネルで衚瀺するず、オブゞェクトが正しく衚瀺されるはずです ### AgentText [[autodoc]] transformers.tools.agent_types.AgentText ### AgentImage [[autodoc]] transformers.tools.agent_types.AgentImage ### AgentAudio [[autodoc]] transformers.tools.agent_types.AgentAudio
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/main_classes/feature_extractor.md
<!--Copyright 2023 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Feature Extractor フィヌチャヌ゚クストラクタは、オヌディオたたはビゞョンモデルのための入力フィヌチャヌの準備を担圓しおいたす。これには、シヌケンスからのフィヌチャヌ抜出䟋オヌディオファむルの前凊理からLog-Melスペクトログラムフィヌチャヌぞの倉換、画像からのフィヌチャヌ抜出䟋画像ファむルのクロッピング、たたパディング、正芏化、そしおNumpy、PyTorch、TensorFlowテン゜ルぞの倉換も含たれたす。 ## FeatureExtractionMixin [[autodoc]] feature_extraction_utils.FeatureExtractionMixin - from_pretrained - save_pretrained ## SequenceFeatureExtractor [[autodoc]] SequenceFeatureExtractor - pad ## BatchFeature [[autodoc]] BatchFeature ## ImageFeatureExtractionMixin [[autodoc]] image_utils.ImageFeatureExtractionMixin
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/main_classes/text_generation.md
<!--Copyright 2022 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Generation 各フレヌムワヌクには、それぞれの `GenerationMixin` クラスに実装されたテキスト生成のための Generate メ゜ッドがありたす。 - PyTorch [`~generation.GenerationMixin.generate`] は [`~generation.GenerationMixin`] に実装されおいたす。 - TensorFlow [`~generation.TFGenerationMixin.generate`] は [`~generation.TFGenerationMixin`] に実装されおいたす。 - Flax/JAX [`~generation.FlaxGenerationMixin.generate`] は [`~generation.FlaxGenerationMixin`] に実装されおいたす。 遞択したフレヌムワヌクに関係なく、[`~generation.GenerationConfig`] を䜿甚しお生成メ゜ッドをパラメヌタ化できたす。 クラスむンスタンス。動䜜を制埡する生成パラメヌタの完党なリストに぀いおは、このクラスを参照しおください。 生成方法のこず。 モデルの生成構成を怜査する方法、デフォルトずは䜕か、パラメヌタヌをアドホックに倉曎する方法を孊習するには、 カスタマむズされた生成構成を䜜成しお保存する方法に぀いおは、「 [テキスト生成戊略ガむド](../generation_strategies)。このガむドでは、関連機胜の䜿甚方法に぀いおも説明しおいたす。 トヌクンストリヌミングのような。 ## GenerationConfig [[autodoc]] generation.GenerationConfig - from_pretrained - from_model_config - save_pretrained ## GenerationMixin [[autodoc]] generation.GenerationMixin - generate - compute_transition_scores - greedy_search - sample - beam_search - beam_sample - contrastive_search - group_beam_search - constrained_beam_search ## TFGenerationMixin [[autodoc]] generation.TFGenerationMixin - generate - compute_transition_scores ## FlaxGenerationMixin [[autodoc]] generation.FlaxGenerationMixin - generate
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/main_classes/tokenizer.md
<!--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. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Tokenizer トヌクナむザヌは、モデルの入力の準備を担圓したす。ラむブラリには、すべおのモデルのトヌクナむザヌが含たれおいたす。ほずんど トヌクナむザヌの䞀郚は、完党な Python 実装ず、 Rust ラむブラリ [🀗 Tokenizers](https://github.com/huggingface/tokenizers)。 「高速」実装では次のこずが可胜になりたす。 1. 特にバッチトヌクン化を行う堎合の倧幅なスピヌドアップず 2. 元の文字列 (文字ず単語) ずトヌクン空間の間でマッピングする远加のメ゜ッド (䟋: 特定の文字を含むトヌクンのむンデックス、たたは特定のトヌクンに察応する文字の範囲。 基本クラス [`PreTrainedTokenizer`] および [`PreTrainedTokenizerFast`] モデル入力の文字列入力を゚ンコヌドし (以䞋を参照)、Python をむンスタンス化/保存するための䞀般的なメ゜ッドを実装したす。 ロヌカル ファむルたたはディレクトリ、たたはラむブラリによっお提䟛される事前トレヌニング枈みトヌクナむザヌからの「高速」トヌクナむザヌ (HuggingFace の AWS S3 リポゞトリからダりンロヌド)。二人ずも頌りにしおいるのは、 共通メ゜ッドを含む [`~tokenization_utils_base.PreTrainedTokenizerBase`] [`~tokenization_utils_base.SpecialTokensMixin`]。 したがっお、[`PreTrainedTokenizer`] ず [`PreTrainedTokenizerFast`] はメむンを実装したす。 すべおのトヌクナむザヌを䜿甚するためのメ゜ッド: - トヌクン化 (文字列をサブワヌド トヌクン文字列に分割)、トヌクン文字列を ID に倉換したり、その逆の倉換を行ったりしたす。 ゚ンコヌド/デコヌド (぀たり、トヌクン化ず敎数ぞの倉換)。 - 基瀎ずなる構造 (BPE、SentencePiece...) から独立した方法で、語圙に新しいトヌクンを远加したす。 - 特別なトヌクン (マスク、文の始たりなど) の管理: トヌクンの远加、属性ぞの割り圓お。 トヌクナむザヌにより、簡単にアクセスでき、トヌクン化䞭に分割されないようにするこずができたす。 [`BatchEncoding`] は、 [`~tokenization_utils_base.PreTrainedTokenizerBase`] の゚ンコヌド メ゜ッド (`__call__`、 `encode_plus` および `batch_encode_plus`) であり、Python 蟞曞から掟生しおいたす。トヌクナむザヌが玔粋な Python の堎合 tokenizer の堎合、このクラスは暙準の Python 蟞曞ず同じように動䜜し、によっお蚈算されたさたざたなモデル入力を保持したす。 これらのメ゜ッド (`input_ids`、`attention_mask`...)。トヌクナむザヌが「高速」トヌクナむザヌである堎合 (぀たり、 HuggingFace [トヌクナむザヌ ラむブラリ](https://github.com/huggingface/tokenizers))、このクラスはさらに提䟛したす 元の文字列 (文字ず単語) ず トヌクンスペヌス (䟋: 指定された文字たたは察応する文字の範囲を構成するトヌクンのむンデックスの取埗) 䞎えられたトヌクンに。 ## PreTrainedTokenizer [[autodoc]] PreTrainedTokenizer - __call__ - apply_chat_template - batch_decode - decode - encode - push_to_hub - all ## PreTrainedTokenizerFast [`PreTrainedTokenizerFast`] は [tokenizers](https://huggingface.co/docs/tokenizers) ラむブラリに䟝存したす。 🀗 トヌクナむザヌ ラむブラリから取埗したトヌクナむザヌは、 🀗 トランスに非垞に簡単にロヌドされたす。これがどのように行われるかを理解するには、[🀗 tokenizers からの tokenizers を䜿甚する](../fast_tokenizers) ペヌゞを参照しおください。 [[autodoc]] PreTrainedTokenizerFast - __call__ - apply_chat_template - batch_decode - decode - encode - push_to_hub - all ## BatchEncoding [[autodoc]] BatchEncoding
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/main_classes/optimizer_schedules.md
<!--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. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Optimization `.optimization` モゞュヌルは以䞋を提䟛したす。 - モデルの埮調敎に䜿甚できる重み枛衰が修正されたオプティマむザヌ、および - `_LRSchedule` から継承するスケゞュヌル オブゞェクトの圢匏のいく぀かのスケゞュヌル: - 耇数のバッチの募配を环積するための募配环積クラス ## AdamW (PyTorch) [[autodoc]] AdamW ## AdaFactor (PyTorch) [[autodoc]] Adafactor ## AdamWeightDecay (TensorFlow) [[autodoc]] AdamWeightDecay [[autodoc]] create_optimizer ## Schedules ### Learning Rate Schedules (Pytorch) [[autodoc]] SchedulerType [[autodoc]] get_scheduler [[autodoc]] get_constant_schedule [[autodoc]] get_constant_schedule_with_warmup <img alt="" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/warmup_constant_schedule.png"/> [[autodoc]] get_cosine_schedule_with_warmup <img alt="" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/warmup_cosine_schedule.png"/> [[autodoc]] get_cosine_with_hard_restarts_schedule_with_warmup <img alt="" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/warmup_cosine_hard_restarts_schedule.png"/> [[autodoc]] get_linear_schedule_with_warmup <img alt="" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/warmup_linear_schedule.png"/> [[autodoc]] get_polynomial_decay_schedule_with_warmup [[autodoc]] get_inverse_sqrt_schedule ### Warmup (TensorFlow) [[autodoc]] WarmUp ## Gradient Strategies ### GradientAccumulator (TensorFlow) [[autodoc]] GradientAccumulator
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/main_classes/model.md
<!--Copyright 2023 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Models ベヌスクラスである [`PreTrainedModel`]、[`TFPreTrainedModel`]、[`FlaxPreTrainedModel`] は、モデルの読み蟌みず保存に関する共通のメ゜ッドを実装しおおり、これはロヌカルのファむルやディレクトリから、たたはラむブラリが提䟛する事前孊習モデル構成HuggingFaceのAWS S3リポゞトリからダりンロヌドからモデルを読み蟌むために䜿甚できたす。 [`PreTrainedModel`] ず [`TFPreTrainedModel`] は、次の共通のメ゜ッドも実装しおいたす - 語圙に新しいトヌクンが远加された堎合に、入力トヌクン埋め蟌みのリサむズを行う - モデルのアテンションヘッドを刈り蟌む 各モデルに共通するその他のメ゜ッドは、[`~modeling_utils.ModuleUtilsMixin`]PyTorchモデル甚および[`~modeling_tf_utils.TFModuleUtilsMixin`]TensorFlowモデル甚で定矩されおおり、テキスト生成の堎合、[`~generation.GenerationMixin`]PyTorchモデル甚、[`~generation.TFGenerationMixin`]TensorFlowモデル甚、および[`~generation.FlaxGenerationMixin`]Flax/JAXモデル甚もありたす。 ## PreTrainedModel [[autodoc]] PreTrainedModel - push_to_hub - all <a id='from_pretrained-torch-dtype'></a> ### 倧芏暡モデルの読み蟌み Transformers 4.20.0では、[`~PreTrainedModel.from_pretrained`] メ゜ッドが再蚭蚈され、[Accelerate](https://huggingface.co/docs/accelerate/big_modeling) を䜿甚しお倧芏暡モデルを扱うこずが可胜になりたした。これには Accelerate >= 0.9.0 ず PyTorch >= 1.9.0 が必芁です。以前の方法でフルモデルを䜜成し、その埌事前孊習の重みを読み蟌む代わりにこれにはメモリ内のモデルサむズが2倍必芁で、ランダムに初期化されたモデル甚ず重み甚の2぀が必芁でした、モデルを空の倖殻ずしお䜜成し、事前孊習の重みが読み蟌たれるずきにパラメヌタヌを実䜓化するオプションが远加されたした。 このオプションは `low_cpu_mem_usage=True` で有効にできたす。モデルはたず空の重みを持぀メタデバむス䞊に䜜成され、その埌状態蟞曞が内郚に読み蟌たれたすシャヌドされたチェックポむントの堎合、シャヌドごずに読み蟌たれたす。この方法で䜿甚される最倧RAMは、モデルの完党なサむズだけです。 ```py from transformers import AutoModelForSeq2SeqLM t0pp = AutoModelForSeq2SeqLM.from_pretrained("bigscience/T0pp", low_cpu_mem_usage=True) ``` さらに、モデルが完党にRAMに収たらない堎合珟時点では掚論のみ有効、異なるデバむスにモデルを盎接配眮できたす。`device_map="auto"` を䜿甚するず、Accelerateは各レむダヌをどのデバむスに配眮するかを決定し、最速のデバむスGPUを最倧限に掻甚し、残りの郚分をCPU、あるいはGPU RAMが䞍足しおいる堎合はハヌドドラむブにオフロヌドしたす。モデルが耇数のデバむスに分割されおいおも、通垞どおり実行されたす。 `device_map` を枡す際、`low_cpu_mem_usage` は自動的に `True` に蚭定されるため、それを指定する必芁はありたせん。 ```py from transformers import AutoModelForSeq2SeqLM t0pp = AutoModelForSeq2SeqLM.from_pretrained("bigscience/T0pp", device_map="auto") ``` モデルがデバむス間でどのように分割されたかは、その `hf_device_map` 属性を芋るこずで確認できたす: ```py t0pp.hf_device_map ``` ```python out {'shared': 0, 'decoder.embed_tokens': 0, 'encoder': 0, 'decoder.block.0': 0, 'decoder.block.1': 1, 'decoder.block.2': 1, 'decoder.block.3': 1, 'decoder.block.4': 1, 'decoder.block.5': 1, 'decoder.block.6': 1, 'decoder.block.7': 1, 'decoder.block.8': 1, 'decoder.block.9': 1, 'decoder.block.10': 1, 'decoder.block.11': 1, 'decoder.block.12': 1, 'decoder.block.13': 1, 'decoder.block.14': 1, 'decoder.block.15': 1, 'decoder.block.16': 1, 'decoder.block.17': 1, 'decoder.block.18': 1, 'decoder.block.19': 1, 'decoder.block.20': 1, 'decoder.block.21': 1, 'decoder.block.22': 'cpu', 'decoder.block.23': 'cpu', 'decoder.final_layer_norm': 'cpu', 'decoder.dropout': 'cpu', 'lm_head': 'cpu'} ``` 同じフォヌマットに埓っお、独自のデバむスマップを䜜成するこずもできたすレむダヌ名からデバむスぞの蟞曞です。モデルのすべおのパラメヌタを指定されたデバむスにマップする必芁がありたすが、1぀のレむダヌが完党に同じデバむスにある堎合、そのレむダヌのサブモゞュヌルのすべおがどこに行くかの詳现を瀺す必芁はありたせん。䟋えば、次のデバむスマップはT0ppに適しおいたすGPUメモリがある堎合: ```python device_map = {"shared": 0, "encoder": 0, "decoder": 1, "lm_head": 1} ``` モデルのメモリぞの圱響を最小限に抑えるもう 1 ぀の方法は、䜎粟床の dtype (`torch.float16` など) でモデルをむンスタンス化するか、以䞋で説明する盎接量子化手法を䜿甚するこずです。 ### Model Instantiation dtype Pytorch では、モデルは通垞 `torch.float32` 圢匏でむンスタンス化されたす。これは、しようずするず問題になる可胜性がありたす 重みが fp16 にあるモデルをロヌドするず、2 倍のメモリが必芁になるためです。この制限を克服するには、次のこずができたす。 `torch_dtype` 匕数を䜿甚しお、目的の `dtype` を明瀺的に枡したす。 ```python model = T5ForConditionalGeneration.from_pretrained("t5", torch_dtype=torch.float16) ``` たたは、モデルを垞に最適なメモリ パタヌンでロヌドしたい堎合は、特別な倀 `"auto"` を䜿甚できたす。 そしお、`dtype` はモデルの重みから自動的に導出されたす。 ```python model = T5ForConditionalGeneration.from_pretrained("t5", torch_dtype="auto") ``` スクラッチからむンスタンス化されたモデルには、どの `dtype` を䜿甚するかを指瀺するこずもできたす。 ```python config = T5Config.from_pretrained("t5") model = AutoModel.from_config(config) ``` Pytorch の蚭蚈により、この機胜は浮動小数点 dtype でのみ䜿甚できたす。 ## ModuleUtilsMixin [[autodoc]] modeling_utils.ModuleUtilsMixin ## TFPreTrainedModel [[autodoc]] TFPreTrainedModel - push_to_hub - all ## TFModelUtilsMixin [[autodoc]] modeling_tf_utils.TFModelUtilsMixin ## FlaxPreTrainedModel [[autodoc]] FlaxPreTrainedModel - push_to_hub - all ## Pushing to the Hub [[autodoc]] utils.PushToHubMixin ## Sharded checkpoints [[autodoc]] modeling_utils.load_sharded_checkpoint
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/main_classes/pipelines.md
<!--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. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Pipelines パむプラむンは、掚論にモデルを䜿うための簡単で優れた方法である。パむプラむンは、耇雑なコヌドのほずんどを抜象化したオブゞェクトです。 パむプラむンは、ラむブラリから耇雑なコヌドのほずんどを抜象化したオブゞェクトで、名前付き固有衚珟認識、マスク蚀語モデリング、感情分析、特城抜出、質問応答などのタスクに特化したシンプルなAPIを提䟛したす。 Recognition、Masked Language Modeling、Sentiment Analysis、Feature Extraction、Question Answeringなどのタスクに特化したシンプルなAPIを提䟛したす。以䞋を参照のこず。 [タスク抂芁](../task_summary)を参照しおください。 パむプラむンの抜象化には2぀のカテゎリヌがある - [`pipeline`] は、他のすべおのパむプラむンをカプセル化する最も匷力なオブゞェクトです。 - タスク固有のパむプラむンは、[オヌディオ](#audio)、[コンピュヌタヌ ビゞョン](#computer-vision)、[自然蚀語凊理](#natural-language-processing)、および [マルチモヌダル](#multimodal) タスクで䜿甚できたす。 ## The pipeline abstraction *パむプラむン* 抜象化は、他のすべおの利甚可胜なパむプラむンのラッパヌです。他のものず同様にむンスタンス化されたす パむプラむンですが、さらなる生掻の質を提䟛できたす。 1 ぀の項目に察する単玔な呌び出し: ```python >>> pipe = pipeline("text-classification") >>> pipe("This restaurant is awesome") [{'label': 'POSITIVE', 'score': 0.9998743534088135}] ``` [ハブ](https://huggingface.co) の特定のモデルを䜿甚したい堎合は、モデルがオンになっおいる堎合はタスクを無芖できたす。 ハブはすでにそれを定矩しおいたす。 ```python >>> pipe = pipeline(model="roberta-large-mnli") >>> pipe("This restaurant is awesome") [{'label': 'NEUTRAL', 'score': 0.7313136458396912}] ``` 倚くの項目に察しおパむプラむンを呌び出すには、*list* を䜿甚しおパむプラむンを呌び出すこずができたす。 ```python >>> pipe = pipeline("text-classification") >>> pipe(["This restaurant is awesome", "This restaurant is awful"]) [{'label': 'POSITIVE', 'score': 0.9998743534088135}, {'label': 'NEGATIVE', 'score': 0.9996669292449951}] ``` 完党なデヌタセットを反埩するには、`Dataset`を盎接䜿甚するこずをお勧めしたす。これは、割り圓おる必芁がないこずを意味したす デヌタセット党䜓を䞀床に凊理するこずも、自分でバッチ凊理を行う必芁もありたせん。これはカスタムルヌプず同じくらい速く動䜜するはずです。 GPU。それが問題でない堎合は、ためらわずに問題を䜜成しおください。 ```python import datasets from transformers import pipeline from transformers.pipelines.pt_utils import KeyDataset from tqdm.auto import tqdm pipe = pipeline("automatic-speech-recognition", model="facebook/wav2vec2-base-960h", device=0) dataset = datasets.load_dataset("superb", name="asr", split="test") # KeyDataset (only *pt*) will simply return the item in the dict returned by the dataset item # as we're not interested in the *target* part of the dataset. For sentence pair use KeyPairDataset for out in tqdm(pipe(KeyDataset(dataset, "file"))): print(out) # {"text": "NUMBER TEN FRESH NELLY IS WAITING ON YOU GOOD NIGHT HUSBAND"} # {"text": ....} # .... ``` 䜿いやすくするために、ゞェネレヌタヌを䜿甚するこずもできたす。 ```python from transformers import pipeline pipe = pipeline("text-classification") def data(): while True: # This could come from a dataset, a database, a queue or HTTP request # in a server # Caveat: because this is iterative, you cannot use `num_workers > 1` variable # to use multiple threads to preprocess data. You can still have 1 thread that # does the preprocessing while the main runs the big inference yield "This is a test" for out in pipe(data()): print(out) # {"text": "NUMBER TEN FRESH NELLY IS WAITING ON YOU GOOD NIGHT HUSBAND"} # {"text": ....} # .... ``` [[autodoc]] pipeline ## Pipeline batching すべおのパむプラむンでバッチ凊理を䜿甚できたす。これはうたくいきたす パむプラむンがストリヌミング機胜を䜿甚するずきは垞に (぀たり、リスト、`dataset`、たたは `generator`を枡すずき)。 ```python from transformers import pipeline from transformers.pipelines.pt_utils import KeyDataset import datasets dataset = datasets.load_dataset("imdb", name="plain_text", split="unsupervised") pipe = pipeline("text-classification", device=0) for out in pipe(KeyDataset(dataset, "text"), batch_size=8, truncation="only_first"): print(out) # [{'label': 'POSITIVE', 'score': 0.9998743534088135}] # Exactly the same output as before, but the content are passed # as batches to the model ``` <Tip warning={true}> ただし、これによっおパフォヌマンスが自動的に向䞊するわけではありたせん。状況に応じお、10 倍の高速化たたは 5 倍の䜎速化のいずれかになりたす。 ハヌドりェア、デヌタ、䜿甚されおいる実際のモデルに぀いお。 䞻に高速化である䟋: </Tip> ```python from transformers import pipeline from torch.utils.data import Dataset from tqdm.auto import tqdm pipe = pipeline("text-classification", device=0) class MyDataset(Dataset): def __len__(self): return 5000 def __getitem__(self, i): return "This is a test" dataset = MyDataset() for batch_size in [1, 8, 64, 256]: print("-" * 30) print(f"Streaming batch_size={batch_size}") for out in tqdm(pipe(dataset, batch_size=batch_size), total=len(dataset)): pass ``` ``` # On GTX 970 ------------------------------ Streaming no batching 100%|██████████████████████████████████████████████████████████████████████| 5000/5000 [00:26<00:00, 187.52it/s] ------------------------------ Streaming batch_size=8 100%|█████████████████████████████████████████████████████████████████████| 5000/5000 [00:04<00:00, 1205.95it/s] ------------------------------ Streaming batch_size=64 100%|█████████████████████████████████████████████████████████████████████| 5000/5000 [00:02<00:00, 2478.24it/s] ------------------------------ Streaming batch_size=256 100%|█████████████████████████████████████████████████████████████████████| 5000/5000 [00:01<00:00, 2554.43it/s] (diminishing returns, saturated the GPU) ``` 最も速床が䜎䞋する䟋: ```python class MyDataset(Dataset): def __len__(self): return 5000 def __getitem__(self, i): if i % 64 == 0: n = 100 else: n = 1 return "This is a test" * n ``` これは、他の文に比べお非垞に長い文が時折ありたす。その堎合、**党䜓**のバッチは 400 である必芁がありたす。 トヌクンが長いため、バッチ党䜓が [64, 4] ではなく [64, 400] になり、速床が倧幅に䜎䞋したす。さらに悪いこずに、 バッチが倧きくなるず、プログラムは単玔にクラッシュしたす。 ``` ------------------------------ Streaming no batching 100%|█████████████████████████████████████████████████████████████████████| 1000/1000 [00:05<00:00, 183.69it/s] ------------------------------ Streaming batch_size=8 100%|█████████████████████████████████████████████████████████████████████| 1000/1000 [00:03<00:00, 265.74it/s] ------------------------------ Streaming batch_size=64 100%|██████████████████████████████████████████████████████████████████████| 1000/1000 [00:26<00:00, 37.80it/s] ------------------------------ Streaming batch_size=256 0%| | 0/1000 [00:00<?, ?it/s] Traceback (most recent call last): File "/home/nicolas/src/transformers/test.py", line 42, in <module> for out in tqdm(pipe(dataset, batch_size=256), total=len(dataset)): .... q = q / math.sqrt(dim_per_head) # (bs, n_heads, q_length, dim_per_head) RuntimeError: CUDA out of memory. Tried to allocate 376.00 MiB (GPU 0; 3.95 GiB total capacity; 1.72 GiB already allocated; 354.88 MiB free; 2.46 GiB reserved in total by PyTorch) ``` この問題に察する適切な (䞀般的な) 解決策はなく、䜿甚できる距離はナヌスケヌスによっお異なる堎合がありたす。のルヌル 芪指 ナヌザヌにずっおの経隓則は次のずおりです。 - **ハヌドりェアを䜿甚しお、負荷に察するパフォヌマンスを枬定したす。枬っお、枬っお、枬り続ける。実数ずいうのは、 進むべき唯䞀の方法。** - レむテンシに制玄がある堎合 (実際の補品が掚論を実行しおいる堎合)、バッチ凊理を行わないでください。 - CPU を䜿甚しおいる堎合は、バッチ凊理を行わないでください。 - GPU でスルヌプットを䜿甚しおいる堎合 (倧量の静的デヌタでモデルを実行したい堎合)、次のようにしたす。 - sequence_length (「自然な」デヌタ) のサむズに぀いおたったくわからない堎合は、デフォルトではバッチ凊理や枬定を行わず、 暫定的に远加しおみたす。倱敗した堎合に回埩するために OOM チェックを远加したす (倱敗した堎合は、ある時点で回埩したす)。 sequence_length を制埡したす。) - sequence_length が非垞に芏則的である堎合、バッチ凊理は非垞に興味深いものずなる可胜性が高く、枬定しおプッシュしおください。 OOM が発生するたで続けたす。 - GPU が倧きいほど、バッチ凊理がより興味深いものになる可胜性が高くなりたす。 - バッチ凊理を有効にしたらすぐに、OOM を適切に凊理できるこずを確認しおください。 ## Pipeline chunk batching `zero-shot-classification` ず `question-answering` は、単䞀の入力で結果が埗られる可胜性があるずいう意味で、少し特殊です。 モデルの耇数の前方パス。通垞の状況では、これにより `batch_size` 匕数に関する問題が発生したす。 この問題を回避するために、これらのパむプラむンはどちらも少し特殊になっおおり、代わりに `ChunkPipeline` になっおいたす。 通垞の `Pipeline`。芁するに ```python preprocessed = pipe.preprocess(inputs) model_outputs = pipe.forward(preprocessed) outputs = pipe.postprocess(model_outputs) ``` 今は次のようになりたす: ```python all_model_outputs = [] for preprocessed in pipe.preprocess(inputs): model_outputs = pipe.forward(preprocessed) all_model_outputs.append(model_outputs) outputs = pipe.postprocess(all_model_outputs) ``` パむプラむンは以䞋で䜿甚されるため、これはコヌドに察しお非垞に透過的である必芁がありたす。 同じ方法。 パむプラむンはバッチを自動的に凊理できるため、これは簡略化されたビュヌです。気にする必芁はないずいう意味です 入力が実際にトリガヌする前方パスの数に぀いおは、`batch_size` を最適化できたす。 入力ずは独立しお。前のセクションの泚意事項が匕き続き適甚されたす。 ## Pipeline custom code 特定のパむプラむンをオヌバヌラむドする堎合。 目の前のタスクに関する問題を䜜成するこずを躊躇しないでください。パむプラむンの目暙は、䜿いやすく、ほずんどのナヌザヌをサポヌトするこずです。 したがっお、`transformers`があなたのナヌスケヌスをサポヌトする可胜性がありたす。 単玔に詊しおみたい堎合は、次のこずができたす。 - 遞択したパむプラむンをサブクラス化したす ```python class MyPipeline(TextClassificationPipeline): def postprocess(): # Your code goes here scores = scores * 100 # And here my_pipeline = MyPipeline(model=model, tokenizer=tokenizer, ...) # or if you use *pipeline* function, then: my_pipeline = pipeline(model="xxxx", pipeline_class=MyPipeline) ``` これにより、必芁なカスタム コヌドをすべお実行できるようになりたす。 ## Implementing a pipeline [Implementing a new pipeline](../add_new_pipeline) ## Audio オヌディオ タスクに䜿甚できるパむプラむンには次のものがありたす。 ### AudioClassificationPipeline [[autodoc]] AudioClassificationPipeline - __call__ - all ### AutomaticSpeechRecognitionPipeline [[autodoc]] AutomaticSpeechRecognitionPipeline - __call__ - all ### TextToAudioPipeline [[autodoc]] TextToAudioPipeline - __call__ - all ### ZeroShotAudioClassificationPipeline [[autodoc]] ZeroShotAudioClassificationPipeline - __call__ - all ## Computer vision コンピュヌタヌ ビゞョン タスクに䜿甚できるパむプラむンには次のものがありたす。 ### DepthEstimationPipeline [[autodoc]] DepthEstimationPipeline - __call__ - all ### ImageClassificationPipeline [[autodoc]] ImageClassificationPipeline - __call__ - all ### ImageSegmentationPipeline [[autodoc]] ImageSegmentationPipeline - __call__ - all ### ImageToImagePipeline [[autodoc]] ImageToImagePipeline - __call__ - all ### ObjectDetectionPipeline [[autodoc]] ObjectDetectionPipeline - __call__ - all ### VideoClassificationPipeline [[autodoc]] VideoClassificationPipeline - __call__ - all ### ZeroShotImageClassificationPipeline [[autodoc]] ZeroShotImageClassificationPipeline - __call__ - all ### ZeroShotObjectDetectionPipeline [[autodoc]] ZeroShotObjectDetectionPipeline - __call__ - all ## Natural Language Processing 自然蚀語凊理タスクに䜿甚できるパむプラむンには次のものがありたす。 ### ConversationalPipeline [[autodoc]] Conversation [[autodoc]] ConversationalPipeline - __call__ - all ### FillMaskPipeline [[autodoc]] FillMaskPipeline - __call__ - all ### NerPipeline [[autodoc]] NerPipeline 詳现に぀いおは、[`TokenClassificationPipeline`] を参照しおください。 ### QuestionAnsweringPipeline [[autodoc]] QuestionAnsweringPipeline - __call__ - all ### SummarizationPipeline [[autodoc]] SummarizationPipeline - __call__ - all ### TableQuestionAnsweringPipeline [[autodoc]] TableQuestionAnsweringPipeline - __call__ ### TextClassificationPipeline [[autodoc]] TextClassificationPipeline - __call__ - all ### TextGenerationPipeline [[autodoc]] TextGenerationPipeline - __call__ - all ### Text2TextGenerationPipeline [[autodoc]] Text2TextGenerationPipeline - __call__ - all ### TokenClassificationPipeline [[autodoc]] TokenClassificationPipeline - __call__ - all ### TranslationPipeline [[autodoc]] TranslationPipeline - __call__ - all ### ZeroShotClassificationPipeline [[autodoc]] ZeroShotClassificationPipeline - __call__ - all ## Multimodal マルチモヌダル タスクに䜿甚できるパむプラむンには次のものがありたす。 ### DocumentQuestionAnsweringPipeline [[autodoc]] DocumentQuestionAnsweringPipeline - __call__ - all ### FeatureExtractionPipeline [[autodoc]] FeatureExtractionPipeline - __call__ - all ### ImageToTextPipeline [[autodoc]] ImageToTextPipeline - __call__ - all ### VisualQuestionAnsweringPipeline [[autodoc]] VisualQuestionAnsweringPipeline - __call__ - all ## Parent class: `Pipeline` [[autodoc]] Pipeline
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/main_classes/keras_callbacks.md
<!--Copyright 2023 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Keras callbacks Keras を䜿甚しお Transformers モデルをトレヌニングする堎合、䞀般的な凊理を自動化するために䜿甚できるラむブラリ固有のコヌルバックがいく぀かありたす。 タスク: ## KerasMetricCallback [[autodoc]] KerasMetricCallback ## PushToHubCallback [[autodoc]] PushToHubCallback
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/main_classes/output.md
<!--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. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Model outputs すべおのモデルには、[`~utils.ModelOutput`] のサブクラスのむンスタンスである出力がありたす。それらは モデルによっお返されるすべおの情報を含むデヌタ構造ですが、タプルたたは 蟞曞。 これがどのようになるかを䟋で芋おみたしょう。 ```python from transformers import BertTokenizer, BertForSequenceClassification import torch tokenizer = BertTokenizer.from_pretrained("bert-base-uncased") model = BertForSequenceClassification.from_pretrained("bert-base-uncased") inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") labels = torch.tensor([1]).unsqueeze(0) # Batch size 1 outputs = model(**inputs, labels=labels) ``` `outputs`オブゞェクトは[`~modeling_outputs.SequenceClassifierOutput`]である。 これは、オプションで `loss`、`logits`、オプションで `hidden_states`、オプションで `attentions` 属性を持぀こずを意味したす。 オプションの `attentions` 属性を持぀こずを意味する。ここでは、`labels`を枡したので`loss`があるが、`hidden_states`ず`attentions`はない。 `output_hidden_states=True`や`output_attentions=True`を枡しおいないので、`hidden_states`ず`attentions`はない。 `output_attentions=True`を枡さなかったからだ。 <Tip> `output_hidden_states=True`を枡すず、`outputs.hidden_states[-1]`が `outputs.last_hidden_states` ず正確に䞀臎するこずを期埅するかもしれない。 しかし、必ずしもそうなるずは限りたせん。モデルによっおは、最埌に隠された状態が返されたずきに、正芏化やその埌の凊理を適甚するものもありたす。 </Tip> 通垞ず同じように各属性にアクセスできたす。その属性がモデルから返されなかった堎合は、 は `None`を取埗したす。ここで、たずえば`outputs.loss`はモデルによっお蚈算された損倱であり、`outputs.attentions`は `None`。 `outputs`オブゞェクトをタプルずしお考える堎合、`None`倀を持たない属性のみが考慮されたす。 たずえば、ここには 2 ぀の芁玠、`loss`、次に`logits`がありたす。 ```python outputs[:2] ``` たずえば、タプル `(outputs.loss, Outputs.logits)` を返したす。 `outputs`オブゞェクトを蟞曞ずしお考慮する堎合、「None」を持たない属性のみが考慮されたす。 䟡倀芳。たずえば、ここには`loss` ず `logits`ずいう 2 ぀のキヌがありたす。 ここでは、耇数のモデル タむプで䜿甚される汎甚モデルの出力を文曞化したす。具䜓的な出力タむプは次のずおりです。 察応するモデルのペヌゞに蚘茉されおいたす。 ## ModelOutput [[autodoc]] utils.ModelOutput - to_tuple ## BaseModelOutput [[autodoc]] modeling_outputs.BaseModelOutput ## BaseModelOutputWithPooling [[autodoc]] modeling_outputs.BaseModelOutputWithPooling ## BaseModelOutputWithCrossAttentions [[autodoc]] modeling_outputs.BaseModelOutputWithCrossAttentions ## BaseModelOutputWithPoolingAndCrossAttentions [[autodoc]] modeling_outputs.BaseModelOutputWithPoolingAndCrossAttentions ## BaseModelOutputWithPast [[autodoc]] modeling_outputs.BaseModelOutputWithPast ## BaseModelOutputWithPastAndCrossAttentions [[autodoc]] modeling_outputs.BaseModelOutputWithPastAndCrossAttentions ## Seq2SeqModelOutput [[autodoc]] modeling_outputs.Seq2SeqModelOutput ## CausalLMOutput [[autodoc]] modeling_outputs.CausalLMOutput ## CausalLMOutputWithCrossAttentions [[autodoc]] modeling_outputs.CausalLMOutputWithCrossAttentions ## CausalLMOutputWithPast [[autodoc]] modeling_outputs.CausalLMOutputWithPast ## MaskedLMOutput [[autodoc]] modeling_outputs.MaskedLMOutput ## Seq2SeqLMOutput [[autodoc]] modeling_outputs.Seq2SeqLMOutput ## NextSentencePredictorOutput [[autodoc]] modeling_outputs.NextSentencePredictorOutput ## SequenceClassifierOutput [[autodoc]] modeling_outputs.SequenceClassifierOutput ## Seq2SeqSequenceClassifierOutput [[autodoc]] modeling_outputs.Seq2SeqSequenceClassifierOutput ## MultipleChoiceModelOutput [[autodoc]] modeling_outputs.MultipleChoiceModelOutput ## TokenClassifierOutput [[autodoc]] modeling_outputs.TokenClassifierOutput ## QuestionAnsweringModelOutput [[autodoc]] modeling_outputs.QuestionAnsweringModelOutput ## Seq2SeqQuestionAnsweringModelOutput [[autodoc]] modeling_outputs.Seq2SeqQuestionAnsweringModelOutput ## Seq2SeqSpectrogramOutput [[autodoc]] modeling_outputs.Seq2SeqSpectrogramOutput ## SemanticSegmenterOutput [[autodoc]] modeling_outputs.SemanticSegmenterOutput ## ImageClassifierOutput [[autodoc]] modeling_outputs.ImageClassifierOutput ## ImageClassifierOutputWithNoAttention [[autodoc]] modeling_outputs.ImageClassifierOutputWithNoAttention ## DepthEstimatorOutput [[autodoc]] modeling_outputs.DepthEstimatorOutput ## Wav2Vec2BaseModelOutput [[autodoc]] modeling_outputs.Wav2Vec2BaseModelOutput ## XVectorOutput [[autodoc]] modeling_outputs.XVectorOutput ## Seq2SeqTSModelOutput [[autodoc]] modeling_outputs.Seq2SeqTSModelOutput ## Seq2SeqTSPredictionOutput [[autodoc]] modeling_outputs.Seq2SeqTSPredictionOutput ## SampleTSPredictionOutput [[autodoc]] modeling_outputs.SampleTSPredictionOutput ## TFBaseModelOutput [[autodoc]] modeling_tf_outputs.TFBaseModelOutput ## TFBaseModelOutputWithPooling [[autodoc]] modeling_tf_outputs.TFBaseModelOutputWithPooling ## TFBaseModelOutputWithPoolingAndCrossAttentions [[autodoc]] modeling_tf_outputs.TFBaseModelOutputWithPoolingAndCrossAttentions ## TFBaseModelOutputWithPast [[autodoc]] modeling_tf_outputs.TFBaseModelOutputWithPast ## TFBaseModelOutputWithPastAndCrossAttentions [[autodoc]] modeling_tf_outputs.TFBaseModelOutputWithPastAndCrossAttentions ## TFSeq2SeqModelOutput [[autodoc]] modeling_tf_outputs.TFSeq2SeqModelOutput ## TFCausalLMOutput [[autodoc]] modeling_tf_outputs.TFCausalLMOutput ## TFCausalLMOutputWithCrossAttentions [[autodoc]] modeling_tf_outputs.TFCausalLMOutputWithCrossAttentions ## TFCausalLMOutputWithPast [[autodoc]] modeling_tf_outputs.TFCausalLMOutputWithPast ## TFMaskedLMOutput [[autodoc]] modeling_tf_outputs.TFMaskedLMOutput ## TFSeq2SeqLMOutput [[autodoc]] modeling_tf_outputs.TFSeq2SeqLMOutput ## TFNextSentencePredictorOutput [[autodoc]] modeling_tf_outputs.TFNextSentencePredictorOutput ## TFSequenceClassifierOutput [[autodoc]] modeling_tf_outputs.TFSequenceClassifierOutput ## TFSeq2SeqSequenceClassifierOutput [[autodoc]] modeling_tf_outputs.TFSeq2SeqSequenceClassifierOutput ## TFMultipleChoiceModelOutput [[autodoc]] modeling_tf_outputs.TFMultipleChoiceModelOutput ## TFTokenClassifierOutput [[autodoc]] modeling_tf_outputs.TFTokenClassifierOutput ## TFQuestionAnsweringModelOutput [[autodoc]] modeling_tf_outputs.TFQuestionAnsweringModelOutput ## TFSeq2SeqQuestionAnsweringModelOutput [[autodoc]] modeling_tf_outputs.TFSeq2SeqQuestionAnsweringModelOutput ## FlaxBaseModelOutput [[autodoc]] modeling_flax_outputs.FlaxBaseModelOutput ## FlaxBaseModelOutputWithPast [[autodoc]] modeling_flax_outputs.FlaxBaseModelOutputWithPast ## FlaxBaseModelOutputWithPooling [[autodoc]] modeling_flax_outputs.FlaxBaseModelOutputWithPooling ## FlaxBaseModelOutputWithPastAndCrossAttentions [[autodoc]] modeling_flax_outputs.FlaxBaseModelOutputWithPastAndCrossAttentions ## FlaxSeq2SeqModelOutput [[autodoc]] modeling_flax_outputs.FlaxSeq2SeqModelOutput ## FlaxCausalLMOutputWithCrossAttentions [[autodoc]] modeling_flax_outputs.FlaxCausalLMOutputWithCrossAttentions ## FlaxMaskedLMOutput [[autodoc]] modeling_flax_outputs.FlaxMaskedLMOutput ## FlaxSeq2SeqLMOutput [[autodoc]] modeling_flax_outputs.FlaxSeq2SeqLMOutput ## FlaxNextSentencePredictorOutput [[autodoc]] modeling_flax_outputs.FlaxNextSentencePredictorOutput ## FlaxSequenceClassifierOutput [[autodoc]] modeling_flax_outputs.FlaxSequenceClassifierOutput ## FlaxSeq2SeqSequenceClassifierOutput [[autodoc]] modeling_flax_outputs.FlaxSeq2SeqSequenceClassifierOutput ## FlaxMultipleChoiceModelOutput [[autodoc]] modeling_flax_outputs.FlaxMultipleChoiceModelOutput ## FlaxTokenClassifierOutput [[autodoc]] modeling_flax_outputs.FlaxTokenClassifierOutput ## FlaxQuestionAnsweringModelOutput [[autodoc]] modeling_flax_outputs.FlaxQuestionAnsweringModelOutput ## FlaxSeq2SeqQuestionAnsweringModelOutput [[autodoc]] modeling_flax_outputs.FlaxSeq2SeqQuestionAnsweringModelOutput
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/main_classes/processors.md
<!--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. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Processors Transformers ラむブラリでは、プロセッサは 2 ぀の異なる意味を持ちたす。 - [Wav2Vec2](../model_doc/wav2vec2) などのマルチモヌダル モデルの入力を前凊理するオブゞェクト (音声ずテキスト) たたは [CLIP](../model_doc/clip) (テキストずビゞョン) - 叀いバヌゞョンのラむブラリで GLUE たたは SQUAD のデヌタを前凊理するために䜿甚されおいたオブゞェクトは非掚奚になりたした。 ## Multi-modal processors マルチモヌダル モデルでは、オブゞェクトが耇数のモダリティ (テキスト、 芖芚ず音声。これは、2 ぀以䞊の凊理オブゞェクトをグルヌプ化するプロセッサヌず呌ばれるオブゞェクトによっお凊理されたす。 トヌクナむザヌ (テキスト モダリティ甚)、画像プロセッサヌ (芖芚甚)、特城抜出噚 (オヌディオ甚) など。 これらのプロセッサは、保存およびロヌド機胜を実装する次の基本クラスを継承したす。 [[autodoc]] ProcessorMixin ## Deprecated processors すべおのプロセッサは、同じアヌキテクチャに埓っおいたす。 [`~data.processors.utils.DataProcessor`]。プロセッサは次のリストを返したす。 [`~data.processors.utils.InputExample`]。これら [`~data.processors.utils.InputExample`] は次のように倉換できたす。 [`~data.processors.utils.Input features`] をモデルにフィヌドしたす。 [[autodoc]] data.processors.utils.DataProcessor [[autodoc]] data.processors.utils.InputExample [[autodoc]] data.processors.utils.InputFeatures ## GLUE [䞀般蚀語理解評䟡 (GLUE)](https://gluebenchmark.com/) は、 既存の NLU タスクの倚様なセットにわたるモデルのパフォヌマンス。玙ず同時発売された [GLUE: A 自然蚀語理解のためのマルチタスクベンチマヌクおよび分析プラットフォヌム](https://openreview.net/pdf?id=rJ4km2R5t7) このラむブラリは、MRPC、MNLI、MNLI (䞍䞀臎)、CoLA、SST2、STSB、 QQP、QNLI、RTE、WNLI。 それらのプロセッサは次のずおりです。 - [`~data.processors.utils.MrpcProcessor`] - [`~data.processors.utils.MnliProcessor`] - [`~data.processors.utils.MnliMismatchedProcessor`] - [`~data.processors.utils.Sst2Processor`] - [`~data.processors.utils.StsbProcessor`] - [`~data.processors.utils.QqpProcessor`] - [`~data.processors.utils.QnliProcessor`] - [`~data.processors.utils.RteProcessor`] - [`~data.processors.utils.WnliProcessor`] さらに、次のメ゜ッドを䜿甚しお、デヌタ ファむルから倀をロヌドし、それらをリストに倉換するこずができたす。 [`~data.processors.utils.InputExample`]。 [[autodoc]] data.processors.glue.glue_convert_examples_to_features ## XNLI [クロスリンガル NLI コヌパス (XNLI)](https://www.nyu.edu/projects/bowman/xnli/) は、 蚀語を超えたテキスト衚珟の品質。 XNLI は、[*MultiNLI*](http://www.nyu.edu/projects/bowman/multinli/) に基づくクラりド゜ヌスのデヌタセットです。テキストのペアには、15 個のテキスト含意アノテヌションがラベル付けされおいたす。 さたざたな蚀語 (英語などの高リ゜ヌス蚀語ずスワヒリ語などの䜎リ゜ヌス蚀語の䞡方を含む)。 論文 [XNLI: Evaluating Cross-lingual Sentence Representations](https://arxiv.org/abs/1809.05053) ず同時にリリヌスされたした。 このラむブラリは、XNLI デヌタをロヌドするプロセッサをホストしたす。 - [`~data.processors.utils.XnliProcessor`] テストセットにはゎヌルドラベルが付いおいるため、評䟡はテストセットで行われたすのでご了承ください。 これらのプロセッサを䜿甚する䟋は、[run_xnli.py](https://github.com/huggingface/transformers/tree/main/examples/pytorch/text-classification/run_xnli.py) スクリプトに瀺されおいたす。 ## SQuAD [The Stanford Question Answering Dataset (SQuAD)](https://rajpurkar.github.io/SQuAD-explorer//) は、次のベンチマヌクです。 質問応答に関するモデルのパフォヌマンスを評䟡したす。 v1.1 ず v2.0 の 2 ぀のバヌゞョンが利甚可胜です。最初のバヌゞョン (v1.1) は、論文 [SQuAD: 100,000+ question for Machine Comprehension of Text](https://arxiv.org/abs/1606.05250) ずずもにリリヌスされたした。 2 番目のバヌゞョン (v2.0) は、論文 [Know What You Don't ず同時にリリヌスされたした。 知っおおくべき: SQuAD の答えられない質問](https://arxiv.org/abs/1806.03822)。 このラむブラリは、次の 2 ぀のバヌゞョンのそれぞれのプロセッサをホストしたす。 ### Processors それらのプロセッサは次のずおりです。 - [`~data.processors.utils.SquadV1Processor`] - [`~data.processors.utils.SquadV2Processor`] どちらも抜象クラス [`~data.processors.utils.SquadProcessor`] を継承しおいたす。 [[autodoc]] data.processors.squad.SquadProcessor - all さらに、次のメ゜ッドを䜿甚しお、SQuAD の䟋を次の圢匏に倉換できたす。 モデルの入力ずしお䜿甚できる [`~data.processors.utils.SquadFeatures`]。 [[autodoc]] data.processors.squad.squad_convert_examples_to_features これらのプロセッサず前述の方法は、デヌタを含むファむルだけでなく、 *tensorflow_datasets* パッケヌゞ。以䞋に䟋を瀺したす。 ### Example usage 以䞋にプロセッサを䜿甚した䟋ず、デヌタ ファむルを䜿甚した倉換方法を瀺したす。 ```python # Loading a V2 processor processor = SquadV2Processor() examples = processor.get_dev_examples(squad_v2_data_dir) # Loading a V1 processor processor = SquadV1Processor() examples = processor.get_dev_examples(squad_v1_data_dir) features = squad_convert_examples_to_features( examples=examples, tokenizer=tokenizer, max_seq_length=max_seq_length, doc_stride=args.doc_stride, max_query_length=max_query_length, is_training=not evaluate, ) ``` *tensorflow_datasets* の䜿甚は、デヌタ ファむルを䜿甚するのず同じくらい簡単です。 ```python # tensorflow_datasets only handle Squad V1. tfds_examples = tfds.load("squad") examples = SquadV1Processor().get_examples_from_dataset(tfds_examples, evaluate=evaluate) features = squad_convert_examples_to_features( examples=examples, tokenizer=tokenizer, max_seq_length=max_seq_length, doc_stride=args.doc_stride, max_query_length=max_query_length, is_training=not evaluate, ) ``` これらのプロセッサを䜿甚する別の䟋は、[run_squad.py](https://github.com/huggingface/transformers/tree/main/examples/legacy/question-answering/run_squad.py) スクリプトに瀺されおいたす。
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/main_classes/trainer.md
<!--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. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Trainer [`Trainer`] クラスは、ほずんどの暙準的なナヌスケヌスに察しお、PyTorch で機胜を完党にトレヌニングするための API を提䟛したす。これは、[サンプル スクリプト](https://github.com/huggingface/transformers/tree/main/examples) のほずんどで䜿甚されおいたす。 [`Trainer`] をむンスタンス化する前に、トレヌニング䞭にカスタマむズのすべおのポむントにアクセスするために [`TrainingArguments`] を䜜成したす。 この API は、耇数の GPU/TPU での分散トレヌニング、[NVIDIA Apex](https://github.com/NVIDIA/apex) および PyTorch のネむティブ AMP による混合粟床をサポヌトしたす。 [`Trainer`] には、䞊蚘の機胜をサポヌトする基本的なトレヌニング ルヌプが含たれおいたす。カスタム動䜜を挿入するには、それらをサブクラス化し、次のメ゜ッドをオヌバヌラむドしたす。 - **get_train_dataloader** -- トレヌニング デヌタロヌダヌを䜜成したす。 - **get_eval_dataloader** -- 評䟡甚デヌタロヌダヌを䜜成したす。 - **get_test_dataloader** -- テスト デヌタロヌダヌを䜜成したす。 - **log** -- トレヌニングを監芖しおいるさたざたなオブゞェクトに関する情報をログに蚘録したす。 - **create_optimizer_and_scheduler** -- オプティマむザず孊習率スケゞュヌラが枡されなかった堎合にセットアップしたす。 初期化。 `create_optimizer`メ゜ッドず`create_scheduler`メ゜ッドをサブクラス化たたはオヌバヌラむドするこずもできるこずに泚意しおください。 別々に。 - **create_optimizer** -- init で枡されなかった堎合にオプティマむザヌをセットアップしたす。 - **create_scheduler** -- init で枡されなかった堎合、孊習率スケゞュヌラを蚭定したす。 - **compute_loss** - トレヌニング入力のバッチの損倱を蚈算したす。 - **training_step** -- トレヌニング ステップを実行したす。 - **prediction_step** -- 評䟡/テスト ステップを実行したす。 - **evaluate** -- 評䟡ルヌプを実行し、メトリクスを返したす。 - **predict** -- テスト セットの予枬 (ラベルが䜿甚可胜な堎合はメトリクスも含む) を返したす。 <Tip warning={true}> [`Trainer`] クラスは 🀗 Transformers モデル甚に最適化されおおり、驚くべき動䜜をする可胜性がありたす 他の機皮で䜿甚する堎合。独自のモデルで䜿甚する堎合は、次の点を確認しおください。 - モデルは垞に [`~utils.ModelOutput`] のタプルたたはサブクラスを返したす。 - `labels` 匕数が指定され、その損倱が最初の倀ずしお返される堎合、モデルは損倱を蚈算できたす。 タプルの芁玠 (モデルがタプルを返す堎合) - モデルは耇数のラベル匕数を受け入れるこずができたす ([`TrainingArguments`] で `label_names` を䜿甚しお、その名前を [`Trainer`] に瀺したす) が、それらのいずれにも `"label"` ずいう名前を付ける必芁はありたせん。 </Tip> 以䞋は、加重損倱を䜿甚するように [`Trainer`] をカスタマむズする方法の䟋です (䞍均衡なトレヌニング セットがある堎合に圹立ちたす)。 ```python from torch import nn from transformers import Trainer class CustomTrainer(Trainer): def compute_loss(self, model, inputs, return_outputs=False): labels = inputs.pop("labels") # forward pass outputs = model(**inputs) logits = outputs.get("logits") # compute custom loss (suppose one has 3 labels with different weights) loss_fct = nn.CrossEntropyLoss(weight=torch.tensor([1.0, 2.0, 3.0], device=model.device)) loss = loss_fct(logits.view(-1, self.model.config.num_labels), labels.view(-1)) return (loss, outputs) if return_outputs else loss ``` PyTorch [`Trainer`] のトレヌニング ルヌプの動䜜をカスタマむズするもう 1 ぀の方法は、トレヌニング ルヌプの状態を怜査できる [callbacks](コヌルバック) を䜿甚するこずです (進行状況レポヌト、TensorBoard たたは他の ML プラットフォヌムでのログ蚘録など)。決定早期停止など。 ## Trainer [[autodoc]] Trainer - all ## Seq2SeqTrainer [[autodoc]] Seq2SeqTrainer - evaluate - predict ## TrainingArguments [[autodoc]] TrainingArguments - all ## Seq2SeqTrainingArguments [[autodoc]] Seq2SeqTrainingArguments - all ## Checkpoints デフォルトでは、[`Trainer`] はすべおのチェックポむントを、 [`TrainingArguments`] を䜿甚しおいたす。これらは、xxx を含む`checkpoint-xxx`ずいう名前のサブフォルダヌに保存されたす。 それはトレヌニングの段階でした。 チェックポむントからトレヌニングを再開するには、次のいずれかを䜿甚しお [`Trainer.train`] を呌び出したす。 - `resume_from_checkpoint=True` は最新のチェックポむントからトレヌニングを再開したす - `resume_from_checkpoint=checkpoint_dir` ディレクトリ内の特定のチェックポむントからトレヌニングを再開したす 合栌した。 さらに、`push_to_hub=True` を䜿甚するず、モデル ハブにチェックポむントを簡単に保存できたす。デフォルトでは、すべお 䞭間チェックポむントに保存されたモデルは別のコミットに保存されたすが、オプティマむザヌの状態は保存されたせん。適応できたす [`TrainingArguments`] の `hub-strategy` 倀を次のいずれかにしたす。 - `"checkpoint"`: 最新のチェックポむントも last-checkpoint ずいう名前のサブフォルダヌにプッシュされたす。 `trainer.train(resume_from_checkpoint="output_dir/last-checkpoint")` を䜿甚しおトレヌニングを簡単に再開したす。 - `"all_checkpoints"`: すべおのチェックポむントは、出力フォルダヌに衚瀺されるようにプッシュされたす (したがっお、1 ぀のチェックポむントが埗られたす) 最終リポゞトリ内のフォルダヌごずのチェックポむント フォルダヌ) ## Logging デフォルトでは、[`Trainer`] はメむンプロセスに `logging.INFO` を䜿甚し、レプリカがある堎合には `logging.WARNING` を䜿甚したす。 これらのデフォルトは、[`TrainingArguments`] の 5 ぀の `logging` レベルのいずれかを䜿甚するようにオヌバヌラむドできたす。 匕数: - `log_level` - メむンプロセス甚 - `log_level_replica` - レプリカ甚 さらに、[`TrainingArguments`] の `log_on_each_node` が `False` に蚭定されおいる堎合、メむン ノヌドのみが メむン プロセスのログ レベル蚭定を䜿甚するず、他のすべおのノヌドはレプリカのログ レベル蚭定を䜿甚したす。 [`Trainer`] は、`transformers` のログ レベルをノヌドごずに個別に蚭定するこずに泚意しおください。 [`Trainer.__init__`]。したがっお、他の機胜を利甚する堎合は、これをより早く蚭定するこずをお勧めしたす (次の䟋を参照)。 [`Trainer`] オブゞェクトを䜜成する前の `transformers` 機胜。 これをアプリケヌションで䜿甚する方法の䟋を次に瀺したす。 ```python [...] logger = logging.getLogger(__name__) # 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)], ) # set the main code and the modules it uses to the same log-level according to the node 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) trainer = Trainer(...) ``` そしお、メむン ノヌドず他のすべおのノヌドで重耇する可胜性が高いものを出力しないように譊告するだけを衚瀺したい堎合は、 譊告: 次のように実行できたす。 ```bash my_app.py ... --log_level warning --log_level_replica error ``` マルチノヌド環境で、各ノヌドのメむンプロセスのログを繰り返したくない堎合は、次のようにしたす。 䞊蚘を次のように倉曎したす。 ```bash my_app.py ... --log_level warning --log_level_replica error --log_on_each_node 0 ``` その埌、最初のノヌドのメむン プロセスのみが「譊告」レベルでログに蚘録され、メむン ノヌド䞊の他のすべおのプロセスはログに蚘録されたす。 ノヌドず他のノヌド䞊のすべおのプロセスは「゚ラヌ」レベルでログに蚘録されたす。 アプリケヌションをできるだけ静かにする必芁がある堎合は、次のようにしたす。 ```bash my_app.py ... --log_level error --log_level_replica error --log_on_each_node 0 ``` (マルチノヌド環境の堎合は `--log_on_each_node 0` を远加したす) ## Randomness [`Trainer`] によっお生成されたチェックポむントから再開する堎合、すべおの努力がその状態を埩元するために行われたす。 _python_、_numpy_、および _pytorch_ の RNG 状態は、そのチェックポむントを保存した時点ず同じ状態になりたす。 これにより、「停止しお再開」ずいうスタむルのトレヌニングが、ノンストップトレヌニングに可胜な限り近づけられるはずです。 ただし、さたざたなデフォルトの非決定的な pytorch 蚭定により、これは完党に機胜しない可胜性がありたす。フルをご垌望の堎合は 決定論に぀いおは、[ランダム性の゜ヌスの制埡](https://pytorch.org/docs/stable/notes/randomness) を参照しおください。ドキュメントで説明されおいるように、これらの蚭定の䞀郚は 物事を決定論的にするもの (䟋: `torch.backends.cudnn.deterministic`) は物事を遅くする可胜性があるため、これは デフォルトでは実行できたせんが、必芁に応じお自分で有効にするこずができたす。 ## Specific GPUs Selection どの GPU をどのような順序で䜿甚するかをプログラムに指瀺する方法に぀いお説明したす。 [`DistributedDataParallel`](https://pytorch.org/docs/stable/generated/torch.nn.Parallel.DistributedDataParallel.html) を䜿甚しお GPU のサブセットのみを䜿甚する堎合、䜿甚する GPU の数を指定するだけです。 。たずえば、GPU が 4 ぀あるが、最初の 2 ぀を䜿甚したい堎合は、次のようにしたす。 ```bash torchrun --nproc_per_node=2 trainer-program.py ... ``` [`accelerate`](https://github.com/huggingface/accelerate) たたは [`deepspeed`](https://github.com/microsoft/DeepSpeed) がむンストヌルされおいる堎合は、次を䜿甚しお同じこずを達成するこずもできたす。の䞀぀ ```bash accelerate launch --num_processes 2 trainer-program.py ... ``` ```bash deepspeed --num_gpus 2 trainer-program.py ... ``` これらのランチャヌを䜿甚するために、Accelerate たたは [Deepspeed 統合](deepspeed) 機胜を䜿甚する必芁はありたせん。 これたでは、プログラムに䜿甚する GPU の数を指瀺できたした。次に、特定の GPU を遞択し、その順序を制埡する方法に぀いお説明したす。 次の環境倉数は、䜿甚する GPU ずその順序を制埡するのに圹立ちたす。 **`CUDA_VISIBLE_DEVICES`** 耇数の GPU があり、そのうちの 1 ぀たたはいく぀かの GPU だけを䜿甚したい堎合は、環境倉数 `CUDA_VISIBLE_DEVICES` を䜿甚する GPU のリストに蚭定したす。 たずえば、4 ぀の GPU (0、1、2、3) があるずしたす。物理 GPU 0 ず 2 のみで実行するには、次のようにしたす。 ```bash CUDA_VISIBLE_DEVICES=0,2 torchrun trainer-program.py ... ``` したがっお、pytorch は 2 ぀の GPU のみを認識し、物理 GPU 0 ず 2 はそれぞれ `cuda:0` ず `cuda:1` にマッピングされたす。 順序を倉曎するこずもできたす。 ```bash CUDA_VISIBLE_DEVICES=2,0 torchrun trainer-program.py ... ``` ここでは、物理 GPU 0 ず 2 がそれぞれ`cuda:1`ず`cuda:0`にマッピングされおいたす。 䞊蚘の䟋はすべお `DistributedDataParallel` 䜿甚パタヌンのものですが、同じ方法が [`DataParallel`](https://pytorch.org/docs/stable/generated/torch.nn.DataParallel.html) でも機胜したす。 ```bash CUDA_VISIBLE_DEVICES=2,0 python trainer-program.py ... ``` GPU のない環境を゚ミュレヌトするには、次のようにこの環境倉数を空の倀に蚭定するだけです。 ```bash CUDA_VISIBLE_DEVICES= python trainer-program.py ... ``` 他の環境倉数ず同様に、これらをコマンド ラむンに远加する代わりに、次のように゚クスポヌトするこずもできたす。 ```bash export CUDA_VISIBLE_DEVICES=0,2 torchrun trainer-program.py ... ``` ただし、この方法では、以前に環境倉数を蚭定したこずを忘れお、なぜ間違った GPU が䜿甚されおいるのか理解できない可胜性があるため、混乱を招く可胜性がありたす。したがっお、このセクションのほずんどの䟋で瀺されおいるように、同じコマンド ラむンで特定の実行に察しおのみ環境倉数を蚭定するのが䞀般的です。 **`CUDA_DEVICE_ORDER`** 物理デバむスの順序を制埡する远加の環境倉数 `CUDA_DEVICE_ORDER` がありたす。遞択肢は次の 2 ぀です。 1. PCIe バス ID 順 (`nvidia-smi` の順序ず䞀臎) - これがデフォルトです。 ```bash export CUDA_DEVICE_ORDER=PCI_BUS_ID ``` 2. GPU コンピュヌティング胜力順に䞊べる ```bash export CUDA_DEVICE_ORDER=FASTEST_FIRST ``` ほずんどの堎合、この環境倉数を気にする必芁はありたせんが、叀い GPU ず新しい GPU が物理的に挿入されおいるため、遅い叀いカヌドが遅くなっおいるように芋えるような偏ったセットアップを行っおいる堎合には、非垞に圹立ちたす。初め。これを解決する 1 ぀の方法は、カヌドを亀換するこずです。ただし、カヌドを亀換できない堎合 (デバむスの冷华が圱響を受けた堎合など)、`CUDA_DEVICE_ORDER=FASTEST_FIRST`を蚭定するず、垞に新しい高速カヌドが最初に配眮されたす。ただし、`nvidia-smi`は䟝然ずしお PCIe の順序でレポヌトするため、倚少混乱するでしょう。 順序を入れ替えるもう 1 ぀の解決策は、以䞋を䜿甚するこずです。 ```bash export CUDA_VISIBLE_DEVICES=1,0 ``` この䟋では 2 ぀の GPU だけを䜿甚しおいたすが、もちろん、コンピュヌタヌに搭茉されおいる数の GPU にも同じこずが圓おはたりたす。 たた、この環境倉数を蚭定する堎合は、`~/.bashrc` ファむルたたはその他の起動蚭定ファむルに蚭定しお、忘れるのが最善です。 ## Trainer Integrations [`Trainer`] は、トレヌニングを劇的に改善する可胜性のあるラむブラリをサポヌトするように拡匵されたした。 時間ずはるかに倧きなモデルに適合したす。 珟圚、サヌドパヌティの゜リュヌション [DeepSpeed](https://github.com/microsoft/DeepSpeed) および [PyTorch FSDP](https://pytorch.org/docs/stable/fsdp.html) をサポヌトしおいたす。論文 [ZeRO: メモリの最適化] 兆パラメヌタ モデルのトレヌニングに向けお、Samyam Rajbhandari、Jeff Rasley、Olatunji Ruwase、Yuxiong He 著](https://arxiv.org/abs/1910.02054)。 この提䟛されるサポヌトは、この蚘事の執筆時点では新しくお実隓的なものです。 DeepSpeed ず PyTorch FSDP のサポヌトはアクティブであり、それに関する問題は歓迎したすが、FairScale 統合は PyTorch メむンに統合されおいるため、もうサポヌトしおいたせん ([PyTorch FSDP 統合](#pytorch-fully-sharded-data-parallel)) <a id='zero-install-notes'></a> ### CUDA Extension Installation Notes この蚘事の執筆時点では、Deepspeed を䜿甚するには、CUDA C++ コヌドをコンパむルする必芁がありたす。 すべおのむンストヌルの問題は、[Deepspeed](https://github.com/microsoft/DeepSpeed/issues) の察応する GitHub の問題を通じお察凊する必芁がありたすが、ビルド䞭に発生する可胜性のある䞀般的な問題がいく぀かありたす。 CUDA 拡匵機胜を構築する必芁がある PyTorch 拡匵機胜。 したがっお、次の操䜜を実行䞭に CUDA 関連のビルドの問題が発生した堎合は、次のずおりです。 ```bash pip install deepspeed ``` たず次の泚意事項をお読みください。 これらのノヌトでは、`pytorch` が CUDA `10.2` でビルドされた堎合に䜕をすべきかの䟋を瀺したす。あなたの状況が次のような堎合 異なる堎合は、バヌゞョン番号を目的のバヌゞョンに調敎するこずを忘れないでください。 #### Possible problem #1 Pytorch には独自の CUDA ツヌルキットが付属しおいたすが、これら 2 ぀のプロゞェクトをビルドするには、同䞀バヌゞョンの CUDA が必芁です。 システム党䜓にむンストヌルされたす。 たずえば、Python 環境に `cudatoolkit==10.2` を指定しお `pytorch` をむンストヌルした堎合は、次のものも必芁です。 CUDA `10.2` がシステム党䜓にむンストヌルされたした。 正確な堎所はシステムによっお異なる堎合がありたすが、倚くのシステムでは`/usr/local/cuda-10.2`が最も䞀般的な堎所です。 Unix システム。 CUDA が正しく蚭定され、`PATH`環境倉数に远加されるず、 次のようにしおむンストヌル堎所を指定したす。 ```bash which nvcc ``` CUDA がシステム党䜓にむンストヌルされおいない堎合は、最初にむンストヌルしおください。お気に入りを䜿甚しお手順を芋぀けるこずができたす 怜玢゚ンゞン。たずえば、Ubuntu を䜿甚しおいる堎合は、[ubuntu cuda 10.2 install](https://www.google.com/search?q=ubuntu+cuda+10.2+install) を怜玢するずよいでしょう。 #### Possible problem #2 もう 1 ぀の考えられる䞀般的な問題は、システム党䜓に耇数の CUDA ツヌルキットがむンストヌルされおいる可胜性があるこずです。たずえばあなた がある可胜性があり ```bash /usr/local/cuda-10.2 /usr/local/cuda-11.0 ``` この状況では、`PATH` および `LD_LIBRARY_PATH` 環境倉数に以䞋が含たれおいるこずを確認する必芁がありたす。 目的の CUDA バヌゞョンぞの正しいパス。通垞、パッケヌゞ むンストヌラヌは、これらに、 最埌のバヌゞョンがむンストヌルされたした。適切なパッケヌゞが芋぀からないためにパッケヌゞのビルドが倱敗するずいう問題が発生した堎合は、 CUDA バヌゞョンがシステム党䜓にむンストヌルされおいるにもかかわらず、前述の 2 ぀を調敎する必芁があるこずを意味したす 環境倉数。 たず、その内容を芋おみたしょう。 ```bash echo $PATH echo $LD_LIBRARY_PATH ``` それで、䞭に䜕が入っおいるかがわかりたす。 `LD_LIBRARY_PATH` が空である可胜性がありたす。 `PATH` は実行可胜ファむルが存圚する堎所をリストし、`LD_LIBRARY_PATH` は共有ラむブラリの堎所を瀺したす。 探すこずです。どちらの堎合も、前の゚ントリが埌の゚ントリより優先されたす。 `:` は耇数を区切るために䜿甚されたす ゚ントリ。 ここで、ビルド プログラムに特定の CUDA ツヌルキットの堎所を指瀺するには、最初にリストされる垌望のパスを挿入したす。 やっおいるこず ```bash export PATH=/usr/local/cuda-10.2/bin:$PATH export LD_LIBRARY_PATH=/usr/local/cuda-10.2/lib64:$LD_LIBRARY_PATH ``` 既存の倀を䞊曞きするのではなく、先頭に远加するこずに泚意しおください。 もちろん、必芁に応じおバヌゞョン番号やフルパスを調敎したす。割り圓おたディレクトリが実際に機胜するこずを確認しおください 存圚する。 `lib64` サブディレクトリは、`libcudart.so` などのさたざたな CUDA `.so` オブゞェクトが存圚する堎所です。 システムでは別の名前が付けられたすが、珟実を反映するように調敎しおください。 #### Possible problem #3 䞀郚の叀い CUDA バヌゞョンは、新しいコンパむラでのビルドを拒吊する堎合がありたす。たずえば、あなたは`gcc-9`を持っおいたすが、それが必芁です `gcc-7`。 それにはさたざたな方法がありたす。 最新の CUDA ツヌルキットをむンストヌルできる堎合は、通垞、新しいコンパむラがサポヌトされおいるはずです。 あるいは、既に所有しおいるコンパむラに加えお、䞋䜍バヌゞョンのコンパむラをむンストヌルするこずもできたす。 すでに存圚したすが、デフォルトではないため、ビルドシステムはそれを認識できたせん。 「gcc-7」がむンストヌルされおいるが、 ビルドシステムが芋぀からないずいうメッセヌゞを衚瀺する堎合は、次の方法で解決できる可胜性がありたす。 ```bash sudo ln -s /usr/bin/gcc-7 /usr/local/cuda-10.2/bin/gcc sudo ln -s /usr/bin/g++-7 /usr/local/cuda-10.2/bin/g++ ``` ここでは、`/usr/local/cuda-10.2/bin/gcc` から `gcc-7` ぞのシンボリックリンクを䜜成しおいたす。 `/usr/local/cuda-10.2/bin/` は `PATH` 環境倉数内にある必芁がありたす (前の問題の解決策を参照)。 `gcc-7` (および `g++7`) が芋぀かるはずで、ビルドは成功したす。 い぀ものように、状況に合わせお䟋のパスを線集しおください。 ### PyTorch Fully Sharded Data parallel より倧きなバッチ サむズで巚倧なモデルのトレヌニングを高速化するには、完党にシャヌド化されたデヌタ䞊列モデルを䜿甚できたす。 このタむプのデヌタ䞊列パラダむムでは、オプティマむザヌの状態、募配、パラメヌタヌをシャヌディングするこずで、より倚くのデヌタず倧芏暡なモデルをフィッティングできたす。 この機胜ずその利点の詳现に぀いおは、[完党シャヌディング デヌタ䞊列ブログ](https://pytorch.org/blog/introducing-pytorch-full-sharded-data-Parallel-api/) をご芧ください。 最新の PyTorch の Fully Sharded Data Parallel (FSDP) トレヌニング機胜を統合したした。 必芁なのは、蚭定を通じお有効にするこずだけです。 **FSDP サポヌトに必芁な PyTorch バヌゞョン**: PyTorch Nightly (リリヌス埌にこれを読んだ堎合は 1.12.0) FSDP を有効にしたモデルの保存は、最近の修正でのみ利甚できるためです。 **䜿甚法** - 配垃されたランチャヌが远加されおいるこずを確認しおください ただ䜿甚しおいない堎合は、`-m torch.distributed.launch --nproc_per_node=NUMBER_OF_GPUS_YOU_HAVE`を䜿甚したす。 - **シャヌディング戊略**: - FULL_SHARD : デヌタ䞊列ワヌカヌ/GPU にわたるシャヌド オプティマむザヌの状態 + 募配 + モデル パラメヌタヌ。 このためには、コマンドラむン匕数に`--fsdp full_shard`を远加したす。 - SHARD_GRAD_OP : シャヌド オプティマむザヌの状態 + デヌタ䞊列ワヌカヌ/GPU 党䜓の募配。 このためには、コマンドラむン匕数に`--fsdp shard_grad_op`を远加したす。 - NO_SHARD : シャヌディングなし。このためには、コマンドラむン匕数に`--fsdp no_shard`を远加したす。 - パラメヌタず募配を CPU にオフロヌドするには、 コマンドラむン匕数に`--fsdp "full_shard offload"`たたは`--fsdp "shard_grad_op offload"`を远加したす。 - `default_auto_wrap_policy` を䜿甚しお FSDP でレむダヌを自動的に再垰的にラップするには、 コマンドラむン匕数に`--fsdp "full_shard auto_wrap"`たたは`--fsdp "shard_grad_op auto_wrap"`を远加したす。 - CPU オフロヌドず自動ラッピングの䞡方を有効にするには、 コマンドラむン匕数に`--fsdp "full_shard offload auto_wrap"`たたは`--fsdp "shard_grad_op offload auto_wrap"`を远加したす。 - 残りの FSDP 構成は、`--fsdp_config <path_to_fsdp_config.json>`を介しお枡されたす。それは、次のいずれかの堎所です。 FSDP json 構成ファむル (䟋: `fsdp_config.json`)、たたはすでにロヌドされおいる json ファむルを `dict` ずしお䜿甚したす。 - 自動ラッピングが有効な堎合は、トランスベヌスの自動ラップ ポリシヌたたはサむズ ベヌスの自動ラップ ポリシヌを䜿甚できたす。 - トランスフォヌマヌベヌスの自動ラップポリシヌの堎合、構成ファむルで `fsdp_transformer_layer_cls_to_wrap` を指定するこずをお勧めしたす。指定しない堎合、䜿甚可胜な堎合、デフォルト倀は `model._no_split_modules` になりたす。 これは、ラップするトランスフォヌマヌ局クラス名のリスト (倧文字ず小文字を区別) を指定したす (䟋: [`BertLayer`]、[`GPTJBlock`]、[`T5Block`] ...)。 重みを共有するサブモゞュヌル (埋め蟌み局など) が異なる FSDP ラップされたナニットにならないようにする必芁があるため、これは重芁です。 このポリシヌを䜿甚するず、マルチヘッド アテンションずそれに続くいく぀かの MLP レむダヌを含むブロックごずにラッピングが発生したす。 共有埋め蟌みを含む残りの局は、同じ最も倖偎の FSDP ナニットにラップされるのが䟿利です。 したがっお、トランスベヌスのモデルにはこれを䜿甚しおください。 - サむズベヌスの自動ラップポリシヌの堎合は、蚭定ファむルに`fsdp_min_num_params`を远加しおください。 自動ラッピングのための FSDP のパラメヌタの最小数を指定したす。 - 蚭定ファむルで `fsdp_backward_prefetch` を指定できるようになりたした。次のパラメヌタのセットをい぀プリフェッチするかを制埡したす。 `backward_pre` ず `backward_pos` が利甚可胜なオプションです。 詳现に぀いおは、`torch.distributed.fsdp.full_sharded_data_Parallel.BackwardPrefetch`を参照しおください。 - 蚭定ファむルで `fsdp_forward_prefetch` を指定できるようになりたした。次のパラメヌタのセットをい぀プリフェッチするかを制埡したす。 `True`の堎合、FSDP はフォワヌド パスでの実行䞭に、次に来るオヌルギャザヌを明瀺的にプリフェッチしたす。 - 蚭定ファむルで `limit_all_gathers` を指定できるようになりたした。 `True`の堎合、FSDP は CPU スレッドを明瀺的に同期しお、実行䞭のオヌルギャザが倚すぎるのを防ぎたす。 - `activation_checkpointing`を蚭定ファむルで指定できるようになりたした。 `True`の堎合、FSDP アクティベヌション チェックポむントは、FSDP のアクティベヌションをクリアするこずでメモリ䜿甚量を削枛する手法です。 特定のレむダヌを凊理し、バックワヌド パス䞭にそれらを再蚈算したす。事実䞊、これは䜙分な蚈算時間を犠牲にしたす メモリ䜿甚量を削枛したす。 **泚意すべき泚意点がいく぀かありたす** - これは `generate` ず互換性がないため、 `--predict_with_generate` ずも互換性がありたせん すべおの seq2seq/clm スクリプト (翻蚳/芁玄/clm など)。 問題 [#21667](https://github.com/huggingface/transformers/issues/21667) を参照しおください。 ### PyTorch/XLA Fully Sharded Data parallel TPU ナヌザヌの皆様に朗報です。 PyTorch/XLA は FSDP をサポヌトするようになりたした。 最新の Fully Sharded Data Parallel (FSDP) トレヌニングがすべおサポヌトされおいたす。 詳现に぀いおは、[FSDP を䜿甚した Cloud TPU での PyTorch モデルのスケヌリング](https://pytorch.org/blog/scaling-pytorch-models-on-cloud-tpus-with-fsdp/) および [PyTorch/XLA 実装 を参照しおください。 FSDP の](https://github.com/pytorch/xla/tree/master/torch_xla/distributed/fsdp) 必芁なのは、蚭定を通じお有効にするこずだけです。 **FSDP サポヌトに必芁な PyTorch/XLA バヌゞョン**: >=2.0 **䜿甚法** `--fsdp "full shard"` を、`--fsdp_config <path_to_fsdp_config.json>` に加えられる次の倉曎ずずもに枡したす。 - PyTorch/XLA FSDP を有効にするには、`xla`を`True`に蚭定する必芁がありたす。 - `xla_fsdp_settings` 倀は、XLA FSDP ラッピング パラメヌタを栌玍する蟞曞です。 オプションの完党なリストに぀いおは、[こちら]( https://github.com/pytorch/xla/blob/master/torch_xla/distributed/fsdp/xla_full_sharded_data_Parallel.py)。 - `xla_fsdp_grad_ckpt`。 `True`の堎合、ネストされた XLA FSDP でラップされた各レむダヌ䞊で募配チェックポむントを䜿甚したす。 この蚭定は、xla フラグが true に蚭定されおおり、自動ラッピング ポリシヌが指定されおいる堎合にのみ䜿甚できたす。 `fsdp_min_num_params` たたは `fsdp_transformer_layer_cls_to_wrap`。 - トランスフォヌマヌ ベヌスの自動ラップ ポリシヌたたはサむズ ベヌスの自動ラップ ポリシヌのいずれかを䜿甚できたす。 - トランスフォヌマヌベヌスの自動ラップポリシヌの堎合、構成ファむルで `fsdp_transformer_layer_cls_to_wrap` を指定するこずをお勧めしたす。指定しない堎合、䜿甚可胜な堎合、デフォルト倀は `model._no_split_modules` になりたす。 これは、ラップするトランスフォヌマヌ局クラス名のリスト (倧文字ず小文字を区別) を指定したす (䟋: [`BertLayer`]、[`GPTJBlock`]、[`T5Block`] ...)。 重みを共有するサブモゞュヌル (埋め蟌み局など) が異なる FSDP ラップされたナニットにならないようにする必芁があるため、これは重芁です。 このポリシヌを䜿甚するず、マルチヘッド アテンションずそれに続くいく぀かの MLP レむダヌを含むブロックごずにラッピングが発生したす。 共有埋め蟌みを含む残りの局は、同じ最も倖偎の FSDP ナニットにラップされるのが䟿利です。 したがっお、トランスベヌスのモデルにはこれを䜿甚しおください。 - サむズベヌスの自動ラップポリシヌの堎合は、蚭定ファむルに`fsdp_min_num_params`を远加しおください。 自動ラッピングのための FSDP のパラメヌタの最小数を指定したす。 ### Using Trainer for accelerated PyTorch Training on Mac PyTorch v1.12 リリヌスにより、開発者ず研究者は Apple シリコン GPU を利甚しおモデル トレヌニングを倧幅に高速化できたす。 これにより、プロトタむピングや埮調敎などの機械孊習ワヌクフロヌを Mac 䞊でロヌカルで実行できるようになりたす。 PyTorch のバック゚ンドずしおの Apple の Metal Performance Shaders (MPS) はこれを可胜にし、新しい `"mps"` デバむス経由で䜿甚できたす。 これにより、蚈算グラフずプリミティブが MPS Graph フレヌムワヌクず MPS によっお提䟛される調敎されたカヌネルにマッピングされたす。 詳现に぀いおは、公匏ドキュメント [Mac での Accelerated PyTorch Training の玹介](https://pytorch.org/blog/introducing-accelerated-pytorch-training-on-mac/) を参照しおください。 および [MPS バック゚ンド](https://pytorch.org/docs/stable/notes/mps.html)。 <Tip warning={false}> MacOS マシンに PyTorch >= 1.13 (執筆時点ではナむトリヌ バヌゞョン) をむンストヌルするこずを匷くお勧めしたす。 トランスベヌスのモデルのモデルの正確性ずパフォヌマンスの向䞊に関連する䞻芁な修正が行われおいたす。 詳现に぀いおは、https://github.com/pytorch/pytorch/issues/82707 を参照しおください。 </Tip> **Apple Silicon チップを䜿甚したトレヌニングず掚論の利点** 1. ナヌザヌがロヌカルで倧芏暡なネットワヌクやバッチ サむズをトレヌニングできるようにしたす 2. ナニファむド メモリ アヌキテクチャにより、デヌタ取埗の遅延が短瞮され、GPU がメモリ ストア党䜓に盎接アクセスできるようになりたす。 したがっお、゚ンドツヌ゚ンドのパフォヌマンスが向䞊したす。 3. クラりドベヌスの開発に関連するコストや远加のロヌカル GPU の必芁性を削枛したす。 **前提条件**: mps サポヌトを備えたトヌチをむンストヌルするには、 この玠晎らしいメディア蚘事 [GPU アクセラレヌションが M1 Mac の PyTorch に登堎](https://medium.com/towards-data-science/gpu-acceleration-comes-to-pytorch-on-m1-macs-195c399efcc1) に埓っおください。 。 **䜿甚法** `mps` デバむスは、`cuda` デバむスが䜿甚される方法ず同様に利甚可胜な堎合、デフォルトで䜿甚されたす。 したがっお、ナヌザヌによるアクションは必芁ありたせん。 たずえば、以䞋のコマンドを䜿甚しお、Apple Silicon GPU を䜿甚しお公匏の Glue テキスト分類タスクを (ルヌト フォルダヌから) 実行できたす。 ```bash export TASK_NAME=mrpc python examples/pytorch/text-classification/run_glue.py \ --model_name_or_path bert-base-cased \ --task_name $TASK_NAME \ --do_train \ --do_eval \ --max_seq_length 128 \ --per_device_train_batch_size 32 \ --learning_rate 2e-5 \ --num_train_epochs 3 \ --output_dir /tmp/$TASK_NAME/ \ --overwrite_output_dir ``` **泚意すべきいく぀かの泚意事項** 1. 䞀郚の PyTorch 操䜜は mps に実装されおいないため、゚ラヌがスロヌされたす。 これを回避する 1 ぀の方法は、環境倉数 `PYTORCH_ENABLE_MPS_FALLBACK=1` を蚭定するこずです。 これらの操䜜では CPU にフォヌルバックしたす。ただし、それでも UserWarning がスロヌされたす。 2. 分散セットアップ`gloo`および`nccl`は、`mps`デバむスでは動䜜したせん。 これは、珟圚「mps」デバむス タむプの単䞀 GPU のみを䜿甚できるこずを意味したす。 最埌に、芚えおおいおください。 🀗 `Trainer` は MPS バック゚ンドのみを統合するため、 MPS バック゚ンドの䜿甚に関しお問題や質問がある堎合は、 [PyTorch GitHub](https://github.com/pytorch/pytorch/issues) に問題を提出しおください。 ## Using Accelerate Launcher with Trainer 加速しおトレヌナヌにパワヌを䞎えたしょう。ナヌザヌが期埅するこずに関しおは、次のずおりです。 - トレヌナヌ匕数に察しお FSDP、DeepSpeed などのトレヌナヌ むンテレヌションを倉曎せずに䜿甚し続けるこずができたす。 - トレヌナヌで Accelerate Launcher を䜿甚できるようになりたした (掚奚)。 トレヌナヌで Accelerate Launcher を䜿甚する手順: 1. 🀗 Accelerate がむンストヌルされおいるこずを確認しおください。Accelerate がないず `Trainer` を䜿甚するこずはできたせん。そうでない堎合は、`pip install accelerate`しおください。 Accelerate のバヌゞョンを曎新する必芁がある堎合もありたす: `pip install activate --upgrade` 2. `accelerate config`を実行し、アンケヌトに蚘入したす。以䞋は加速蚭定の䟋です。  DDP マルチノヌド マルチ GPU 構成: ```yaml compute_environment: LOCAL_MACHINE distributed_type: MULTI_GPU downcast_bf16: 'no' gpu_ids: all machine_rank: 0 #change rank as per the node main_process_ip: 192.168.20.1 main_process_port: 9898 main_training_function: main mixed_precision: fp16 num_machines: 2 num_processes: 8 rdzv_backend: static same_network: true tpu_env: [] tpu_use_cluster: false tpu_use_sudo: false use_cpu: false ``` b. FSDP config: ```yaml compute_environment: LOCAL_MACHINE distributed_type: FSDP downcast_bf16: 'no' fsdp_config: fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP fsdp_backward_prefetch_policy: BACKWARD_PRE fsdp_forward_prefetch: true fsdp_offload_params: false fsdp_sharding_strategy: 1 fsdp_state_dict_type: FULL_STATE_DICT fsdp_sync_module_states: true fsdp_transformer_layer_cls_to_wrap: BertLayer fsdp_use_orig_params: true machine_rank: 0 main_training_function: main mixed_precision: bf16 num_machines: 1 num_processes: 2 rdzv_backend: static same_network: true tpu_env: [] tpu_use_cluster: false tpu_use_sudo: false use_cpu: false ``` c.ファむルを指す DeepSpeed 構成: ```yaml compute_environment: LOCAL_MACHINE deepspeed_config: deepspeed_config_file: /home/user/configs/ds_zero3_config.json zero3_init_flag: true distributed_type: DEEPSPEED downcast_bf16: 'no' machine_rank: 0 main_training_function: main num_machines: 1 num_processes: 4 rdzv_backend: static same_network: true tpu_env: [] tpu_use_cluster: false tpu_use_sudo: false use_cpu: false ``` d.加速プラグむンを䜿甚した DeepSpeed 構成: ```yaml compute_environment: LOCAL_MACHINE deepspeed_config: gradient_accumulation_steps: 1 gradient_clipping: 0.7 offload_optimizer_device: cpu offload_param_device: cpu zero3_init_flag: true zero_stage: 2 distributed_type: DEEPSPEED downcast_bf16: 'no' machine_rank: 0 main_training_function: main mixed_precision: bf16 num_machines: 1 num_processes: 4 rdzv_backend: static same_network: true tpu_env: [] tpu_use_cluster: false tpu_use_sudo: false use_cpu: false ``` 3. 加速蚭定たたはランチャヌ匕数によっお䞊蚘で凊理された匕数以倖の匕数を䜿甚しお、トレヌナヌ スクリプトを実行したす。 以䞋は、䞊蚘の FSDP 構成で`accelerate launcher`を䜿甚しお`run_glue.py`を実行する䟋です。 ```bash cd transformers accelerate launch \ ./examples/pytorch/text-classification/run_glue.py \ --model_name_or_path bert-base-cased \ --task_name $TASK_NAME \ --do_train \ --do_eval \ --max_seq_length 128 \ --per_device_train_batch_size 16 \ --learning_rate 5e-5 \ --num_train_epochs 3 \ --output_dir /tmp/$TASK_NAME/ \ --overwrite_output_dir ``` 4. `accelerate launch`するための cmd 匕数を盎接䜿甚するこずもできたす。䞊の䟋は次のようにマッピングされたす。 ```bash cd transformers accelerate launch --num_processes=2 \ --use_fsdp \ --mixed_precision=bf16 \ --fsdp_auto_wrap_policy=TRANSFORMER_BASED_WRAP \ --fsdp_transformer_layer_cls_to_wrap="BertLayer" \ --fsdp_sharding_strategy=1 \ --fsdp_state_dict_type=FULL_STATE_DICT \ ./examples/pytorch/text-classification/run_glue.py --model_name_or_path bert-base-cased \ --task_name $TASK_NAME \ --do_train \ --do_eval \ --max_seq_length 128 \ --per_device_train_batch_size 16 \ --learning_rate 5e-5 \ --num_train_epochs 3 \ --output_dir /tmp/$TASK_NAME/ \ --overwrite_output_dir ``` 詳现に぀いおは、🀗 Accelerate CLI ガむドを参照しおください: [🀗 Accelerate スクリプトの起動](https://huggingface.co/docs/accelerate/basic_tutorials/launch)。 移動されたセクション: [ <a href="./deepspeed#deepspeed-trainer-integration">DeepSpeed</a><a id="deepspeed"></a> | <a href="./deepspeed#deepspeed-installation">Installation</a><a id="installation"></a> | <a href="./deepspeed#deepspeed-multi-gpu">Deployment with multiple GPUs</a><a id="deployment-with-multiple-gpus"></a> | <a href="./deepspeed#deepspeed-one-gpu">Deployment with one GPU</a><a id="deployment-with-one-gpu"></a> | <a href="./deepspeed#deepspeed-notebook">Deployment in Notebooks</a><a id="deployment-in-notebooks"></a> | <a href="./deepspeed#deepspeed-config">Configuration</a><a id="configuration"></a> | <a href="./deepspeed#deepspeed-config-passing">Passing Configuration</a><a id="passing-configuration"></a> | <a href="./deepspeed#deepspeed-config-shared">Shared Configuration</a><a id="shared-configuration"></a> | <a href="./deepspeed#deepspeed-zero">ZeRO</a><a id="zero"></a> | <a href="./deepspeed#deepspeed-zero2-config">ZeRO-2 Config</a><a id="zero-2-config"></a> | <a href="./deepspeed#deepspeed-zero3-config">ZeRO-3 Config</a><a id="zero-3-config"></a> | <a href="./deepspeed#deepspeed-nvme">NVMe Support</a><a id="nvme-support"></a> | <a href="./deepspeed#deepspeed-zero2-zero3-performance">ZeRO-2 vs ZeRO-3 Performance</a><a id="zero-2-vs-zero-3-performance"></a> | <a href="./deepspeed#deepspeed-zero2-example">ZeRO-2 Example</a><a id="zero-2-example"></a> | <a href="./deepspeed#deepspeed-zero3-example">ZeRO-3 Example</a><a id="zero-3-example"></a> | <a href="./deepspeed#deepspeed-optimizer">Optimizer</a><a id="optimizer"></a> | <a href="./deepspeed#deepspeed-scheduler">Scheduler</a><a id="scheduler"></a> | <a href="./deepspeed#deepspeed-fp32">fp32 Precision</a><a id="fp32-precision"></a> | <a href="./deepspeed#deepspeed-amp">Automatic Mixed Precision</a><a id="automatic-mixed-precision"></a> | <a href="./deepspeed#deepspeed-bs">Batch Size</a><a id="batch-size"></a> | <a href="./deepspeed#deepspeed-grad-acc">Gradient Accumulation</a><a id="gradient-accumulation"></a> | <a href="./deepspeed#deepspeed-grad-clip">Gradient Clipping</a><a id="gradient-clipping"></a> | <a href="./deepspeed#deepspeed-weight-extraction">Getting The Model Weights Out</a><a id="getting-the-model-weights-out"></a> ]
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/main_classes/data_collator.md
<!--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. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # デヌタ照合者 デヌタ照合噚は、デヌタセット芁玠のリストを入力ずしお䜿甚しおバッチを圢成するオブゞェクトです。これらの芁玠は、 `train_dataset` たたは `eval_dataset` の芁玠ず同じ型。 バッチを構築できるようにするために、デヌタ照合者は䜕らかの凊理 (パディングなど) を適甚する堎合がありたす。そのうちのいく぀かは [`DataCollat​​orForLanguageModeling`]) ランダムなデヌタ拡匵 (ランダム マスキングなど) も適甚したす 圢成されたバッチ䞊で。 䜿甚䟋は、[サンプル スクリプト](../examples) たたは [サンプル ノヌトブック](../notebooks) にありたす。 ## Default data collator [[autodoc]] data.data_collator.default_data_collator ## DefaultDataCollator [[autodoc]] data.data_collator.DefaultDataCollator ## DataCollatorWithPadding [[autodoc]] data.data_collator.DataCollatorWithPadding ## DataCollatorForTokenClassification [[autodoc]] data.data_collator.DataCollatorForTokenClassification ## DataCollatorForSeq2Seq [[autodoc]] data.data_collator.DataCollatorForSeq2Seq ## DataCollatorForLanguageModeling [[autodoc]] data.data_collator.DataCollatorForLanguageModeling - numpy_mask_tokens - tf_mask_tokens - torch_mask_tokens ## DataCollatorForWholeWordMask [[autodoc]] data.data_collator.DataCollatorForWholeWordMask - numpy_mask_tokens - tf_mask_tokens - torch_mask_tokens ## DataCollatorForPermutationLanguageModeling [[autodoc]] data.data_collator.DataCollatorForPermutationLanguageModeling - numpy_mask_tokens - tf_mask_tokens - torch_mask_tokens
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/main_classes/deepspeed.md
<!--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. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # DeepSpeed Integration [DeepSpeed](https://github.com/microsoft/DeepSpeed) は、[ZeRO 論文](https://arxiv.org/abs/1910.02054) で説明されおいるすべおを実装したす。珟圚、次のものを完党にサポヌトしおいたす。 1. オプティマむザヌの状態分割 (ZeRO ステヌゞ 1) 2. 募配分割 (ZeRO ステヌゞ 2) 3. パラメヌタヌの分割 (ZeRO ステヌゞ 3) 4. カスタム混合粟床トレヌニング凊理 5. 䞀連の高速 CUDA 拡匵ベヌスのオプティマむザヌ 6. CPU および NVMe ぞの ZeRO オフロヌド ZeRO-Offload には独自の専甚ペヌパヌがありたす: [ZeRO-Offload: Democratizing Billion-Scale Model Training](https://arxiv.org/abs/2101.06840)。 NVMe サポヌトに぀いおは、論文 [ZeRO-Infinity: Breaking the GPU Memory Wall for Extreme Scale Deep Learning](https://arxiv.org/abs/2104.07857)。 DeepSpeed ZeRO-2 は、その機胜が掚論には圹に立たないため、䞻にトレヌニングのみに䜿甚されたす。 DeepSpeed ZeRO-3 は、巚倧なモデルを耇数の GPU にロヌドできるため、掚論にも䜿甚できたす。 単䞀の GPU では䞍可胜です。 🀗 Transformers は、2 ぀のオプションを介しお [DeepSpeed](https://github.com/microsoft/DeepSpeed) を統合したす。 1. [`Trainer`] によるコア DeepSpeed 機胜の統合。䜕でもやっおくれるタむプです 統合の堎合 - カスタム構成ファむルを指定するか、テンプレヌトを䜿甚するだけで、他に䜕もする必芁はありたせん。たいおいの このドキュメントではこの機胜に焊点を圓おおいたす。 2. [`Trainer`] を䜿甚せず、DeepSpeed を統合した独自のトレヌナヌを䜿甚したい堎合 `from_pretrained` や `from_config` などのコア機胜には、重芁な機胜の統合が含たれおいたす。 ZeRO ステヌゞ 3 以降の `zero.Init`などの DeepSpeed の郚分。この機胜を掻甚するには、次のドキュメントをお読みください。 [非トレヌナヌ DeepSpeed 統合](#nontrainer-deepspeed-integration)。 統合されおいるもの: トレヌニング 1. DeepSpeed ZeRO トレヌニングは、ZeRO-Infinity (CPU および NVME オフロヌド) を䜿甚しお完党な ZeRO ステヌゞ 1、2、および 3 をサポヌトしたす。 掚論 1. DeepSpeed ZeRO Inference は、ZeRO-Infinity による ZeRO ステヌゞ 3 をサポヌトしたす。トレヌニングず同じ ZeRO プロトコルを䜿甚したすが、 オプティマむザず lr スケゞュヌラは䜿甚せず、ステヌゞ 3 のみが関連したす。詳现に぀いおは、以䞋を参照しおください。 [れロ掚論](#zero-inference)。 DeepSpeed Inference もありたす。これは、Tensor Parallelism の代わりに Tensor Parallelism を䜿甚するたったく異なるテクノロゞヌです。 ZeRO (近日公開)。 <a id='deepspeed-trainer-integration'></a> ## Trainer Deepspeed Integration <a id='deepspeed-installation'></a> ### Installation pypi 経由でラむブラリをむンストヌルしたす。 ```bash pip install deepspeed ``` たたは`tansformers`, `extras`経由: ```bash pip install transformers[deepspeed] ``` たたは、[DeepSpeed の GitHub ペヌゞ](https://github.com/microsoft/deepspeed#installation) で詳现を確認しおください。 [高床なむンストヌル](https://www.deepspeed.ai/tutorials/advanced-install/)。 それでもビルドに苊劎する堎合は、たず [CUDA 拡匵機胜のむンストヌル ノヌト](trainer#cuda-extension-installation-notes) を必ず読んでください。 拡匵機胜を事前ビルドせず、実行時に拡匵機胜がビルドされるこずに䟝存しおおり、䞊蚘の解決策をすべお詊した堎合 それが圹に立たなかった堎合、次に詊すべきこずは、モゞュヌルをむンストヌルする前にモゞュヌルを事前にビルドするこずです。 DeepSpeed のロヌカル ビルドを䜜成するには: ```bash git clone https://github.com/microsoft/DeepSpeed/ cd DeepSpeed rm -rf build TORCH_CUDA_ARCH_LIST="8.6" DS_BUILD_CPU_ADAM=1 DS_BUILD_UTILS=1 pip install . \ --global-option="build_ext" --global-option="-j8" --no-cache -v \ --disable-pip-version-check 2>&1 | tee build.log ``` NVMe オフロヌドを䜿甚する堎合は、䞊蚘の手順に`DS_BUILD_AIO=1`を含める必芁がありたす (たた、 *libaio-dev* システム党䜓にむンストヌルしたす)。 `TORCH_CUDA_ARCH_LIST` を線集しお、䜿甚する GPU カヌドのアヌキテクチャのコヌドを挿入したす。すべおを仮定するず あなたのカヌドは同じで、次の方法でアヌチを取埗できたす。 ```bash CUDA_VISIBLE_DEVICES=0 python -c "import torch; print(torch.cuda.get_device_capability())" ``` したがっお、`8, 6`を取埗した堎合は、`TORCH_CUDA_ARCH_LIST="8.6"`を䜿甚したす。耇数の異なるカヌドをお持ちの堎合は、すべおをリストするこずができたす それらのうち、`TORCH_CUDA_ARCH_LIST="6.1;8.6"`が奜きです 耇数のマシンで同じセットアップを䜿甚する必芁がある堎合は、バむナリ ホむヌルを䜜成したす。 ```bash git clone https://github.com/microsoft/DeepSpeed/ cd DeepSpeed rm -rf build TORCH_CUDA_ARCH_LIST="8.6" DS_BUILD_CPU_ADAM=1 DS_BUILD_UTILS=1 \ python setup.py build_ext -j8 bdist_wheel ``` `dist/deepspeed-0.3.13+8cd046f-cp38-cp38-linux_x86_64.whl`のようなものが生成されるので、これをむンストヌルできたす `pip install deepspeed-0.3.13+8cd046f-cp38-cp38-linux_x86_64.whl`ずしおロヌカルたたは他のマシンにむンストヌルしたす。 繰り返したすが、`TORCH_CUDA_ARCH_LIST`をタヌゲット アヌキテクチャに合わせお調敎するこずを忘れないでください。 NVIDIA GPU の完党なリストず、それに察応する **コンピュヌティング機胜** (この蚘事の Arch ず同じ) を芋぀けるこずができたす。 コンテキスト) [ここ](https://developer.nvidia.com/cuda-gpus)。 以䞋を䜿甚しお、pytorch が構築されたアヌチを確認できたす。 ```bash python -c "import torch; print(torch.cuda.get_arch_list())" ``` ここでは、むンストヌルされおいる GPU の 1 ぀のアヌチを芋぀ける方法を説明したす。たずえば、GPU 0 の堎合: ```bash CUDA_VISIBLE_DEVICES=0 python -c "import torch; \ print(torch.cuda.get_device_properties(torch.device('cuda')))" ``` 出力が次の堎合: ```bash _CudaDeviceProperties(name='GeForce RTX 3090', major=8, minor=6, total_memory=24268MB, multi_processor_count=82) ``` そうすれば、このカヌドのアヌチが`8.6`であるこずがわかりたす。 `TORCH_CUDA_ARCH_LIST` を完党に省略するこずもできたす。そうすれば、ビルド プログラムが自動的にク゚リを実行したす。 ビルドが行われる GPU のアヌキテクチャ。これは、タヌゲット マシンの GPU ず䞀臎する堎合もあれば、䞀臎しない堎合もありたす。 目的のアヌチを明瀺的に指定するこずをお勧めしたす。 提案されたこずをすべお詊しおもただビルドの問題が発生する堎合は、GitHub の問題に進んでください。 [ディヌプスピヌド](https://github.com/microsoft/DeepSpeed/issues)、 <a id='deepspeed-multi-gpu'></a> ### Deployment with multiple GPUs DeepSpeed 統合をデプロむするには、[`Trainer`] コマンド ラむン匕数を調敎しお新しい匕数 `--deepspeed ds_config.json` を含めたす。ここで、`ds_config.json` は DeepSpeed 構成ファむルです。 [こちら](https://www.deepspeed.ai/docs/config-json/)に蚘茉されおいたす。ファむル名はあなた次第です。 DeepSpeed の`add_config_arguments`ナヌティリティを䜿甚しお、必芁なコマンド ラむン匕数をコヌドに远加するこずをお勧めしたす。 詳现に぀いおは、[DeepSpeed の匕数解析](https://deepspeed.readthedocs.io/en/latest/initialize.html#argument-parsing) ドキュメントを参照しおください。 ここで遞択したランチャヌを䜿甚できたす。 pytorch ランチャヌを匕き続き䜿甚できたす。 ```bash torch.distributed.run --nproc_per_node=2 your_program.py <normal cl args> --deepspeed ds_config.json ``` たたは、`deepspeed`によっお提䟛されるランチャヌを䜿甚したす。 ```bash deepspeed --num_gpus=2 your_program.py <normal cl args> --deepspeed ds_config.json ``` ご芧のずおり、匕数は同じではありたせんが、ほずんどのニヌズではどちらでも機胜したす。の さたざたなノヌドず GPU を構成する方法の詳现に぀いおは、[こちら](https://www.deepspeed.ai/getting-started/#resource-configuration-multi-node) を参照しおください。 `deepspeed`ランチャヌを䜿甚し、利甚可胜なすべおの GPU を䜿甚したい堎合は、`--num_gpus`フラグを省略するだけです。 以䞋は、利甚可胜なすべおの GPU をデプロむする DeepSpeed で`run_translation.py`を実行する䟋です。 ```bash deepspeed examples/pytorch/translation/run_translation.py \ --deepspeed tests/deepspeed/ds_config_zero3.json \ --model_name_or_path t5-small --per_device_train_batch_size 1 \ --output_dir output_dir --overwrite_output_dir --fp16 \ --do_train --max_train_samples 500 --num_train_epochs 1 \ --dataset_name wmt16 --dataset_config "ro-en" \ --source_lang en --target_lang ro ``` DeepSpeed のドキュメントには、`--deepspeed --deepspeed_config ds_config.json`が衚瀺される可胜性が高いこずに泚意しおください。 DeepSpeed 関連の匕数が 2 ぀ありたすが、簡単にするためであり、凊理すべき匕数がすでに非垞に倚いためです。 この 2 ぀を 1 ぀の匕数に結合したした。 実際の䜿甚䟋に぀いおは、この [投皿](https://github.com/huggingface/transformers/issues/8771#issuecomment-759248400) を参照しおください。 <a id='deepspeed-one-gpu'></a> ### Deployment with one GPU 1 ぀の GPU で DeepSpeed をデプロむするには、[`Trainer`] コマンド ラむン匕数を次のように調敎したす。 ```bash deepspeed --num_gpus=1 examples/pytorch/translation/run_translation.py \ --deepspeed tests/deepspeed/ds_config_zero2.json \ --model_name_or_path t5-small --per_device_train_batch_size 1 \ --output_dir output_dir --overwrite_output_dir --fp16 \ --do_train --max_train_samples 500 --num_train_epochs 1 \ --dataset_name wmt16 --dataset_config "ro-en" \ --source_lang en --target_lang ro ``` これは耇数の GPU の堎合ずほが同じですが、ここでは、DeepSpeed に 1 ぀の GPU だけを䜿甚するように明瀺的に指瀺したす。 `--num_gpus=1`。デフォルトでは、DeepSpeed は指定されたノヌド䞊で認識できるすべおの GPU をデプロむしたす。起動する GPU が 1 ぀だけの堎合 の堎合、この匕数は必芁ありたせん。次の [ドキュメント](https://www.deepspeed.ai/getting-started/#resource-configuration-multi-node) では、ランチャヌ オプションに぀いお説明しおいたす。 1 ぀の GPU だけで DeepSpeed を䜿甚したいのはなぜですか? 1. 䞀郚の蚈算ずメモリをホストの CPU ず RAM に委任できる ZeRO オフロヌド機胜を備えおいるため、 モデルのニヌズに合わせおより倚くの GPU リ゜ヌスを残しおおきたす。より倧きなバッチ サむズ、たたは非垞に倧きなモデルのフィッティングを可胜にする 普通は合わないでしょう。 2. スマヌトな GPU メモリ管理システムを提䟛し、メモリの断片化を最小限に抑えたす。 より倧きなモデルずデヌタ バッチ。 次に構成に぀いお詳しく説明したすが、単䞀の GPU で倧幅な改善を実珟するための鍵は次のずおりです。 DeepSpeed を䜿甚するには、構成ファむルに少なくずも次の構成が必芁です。 ```json { "zero_optimization": { "stage": 2, "offload_optimizer": { "device": "cpu", "pin_memory": true }, "allgather_partitions": true, "allgather_bucket_size": 2e8, "reduce_scatter": true, "reduce_bucket_size": 2e8, "overlap_comm": true, "contiguous_gradients": true } } ``` これにより、オプティマむザヌのオフロヌドやその他の重芁な機胜が有効になりたす。バッファ サむズを詊しおみるずよいでしょう。 詳现に぀いおは、以䞋のディスカッションを参照しおください。 このタむプのデプロむメントの実際的な䜿甚䟋に぀いおは、この [投皿](https://github.com/huggingface/transformers/issues/8771#issuecomment-759176685) を参照しおください。 このドキュメントで詳しく説明されおいるように、CPU および NVMe オフロヌドを備えた ZeRO-3 を詊すこずもできたす。 ノヌト - GPU 0 ずは異なる特定の GPU で実行する必芁がある堎合、`CUDA_VISIBLE_DEVICES` を䜿甚しお制限するこずはできたせん。 利甚可胜な GPU の衚瀺範囲。代わりに、次の構文を䜿甚する必芁がありたす。 ```bash deepspeed --include localhost:1 examples/pytorch/translation/run_translation.py ... ``` この䟋では、DeepSpeed に GPU 1 (2 番目の GPU) を䜿甚するように指瀺したす。 <a id='deepspeed-multi-node'></a> ### 耇数のノヌドを䜿甚したデプロむメント このセクションの情報は DeepSpeed 統合に固有のものではなく、あらゆるマルチノヌド プログラムに適甚できたす。ただし、DeepSpeed は、SLURM 環境でない限り、他のランチャヌよりも䜿いやすい`deepspeed`ランチャヌを提䟛したす。 このセクションでは、それぞれ 8 GPU を備えた 2 ぀のノヌドがあるず仮定したす。たた、最初のノヌドには `ssh hostname1` を䜿甚しお、2 番目のノヌドには `ssh hostname2` を䜿甚しお接続できたす。䞡方ずもパスワヌドなしでロヌカルの ssh 経由で盞互に接続できる必芁がありたす。もちろん、これらのホスト (ノヌド) 名を、䜜業しおいる実際のホスト名に倉曎する必芁がありたす。 #### The torch.distributed.run launcher たずえば、`torch.distributed.run` を䜿甚するには、次のようにしたす。 ```bash python -m torch.distributed.run --nproc_per_node=8 --nnode=2 --node_rank=0 --master_addr=hostname1 \ --master_port=9901 your_program.py <normal cl args> --deepspeed ds_config.json ``` 各ノヌドに SSH で接続し、それぞれのノヌドで同じコマンドを実行する必芁がありたす。急ぐ必芁はありたせん。ランチャヌは䞡方のノヌドが同期するたで埅機したす。 詳现に぀いおは、[torchrun](https://pytorch.org/docs/stable/elastic/run.html) を参照しおください。ちなみに、これは pytorch の数バヌゞョン前の`torch.distributed.launch`を眮き換えたランチャヌでもありたす。 #### ディヌプスピヌド ランチャヌ 代わりに`deepspeed`ランチャヌを䜿甚するには、たず`hostfile`ファむルを䜜成する必芁がありたす。 ``` hostname1 slots=8 hostname2 slots=8 ``` そしお、次のように起動できたす。 ```bash deepspeed --num_gpus 8 --num_nodes 2 --hostfile hostfile --master_addr hostname1 --master_port=9901 \ your_program.py <normal cl args> --deepspeed ds_config.json ``` `torch.distributed.run`ランチャヌずは異なり、`deepspeed`は䞡方のノヌドでこのコマンドを自動的に起動したす。 詳现に぀いおは、[リ゜ヌス構成 (マルチノヌド)](https://www.deepspeed.ai/getting-started/#resource-configuration-multi-node) を参照しおください。 #### Launching in a SLURM environment SLURM 環境では、次のアプロヌチを䜿甚できたす。以䞋は、特定の SLURM 環境に適合させるために必芁な slurm スクリプト `launch.slurm` です。 ```bash #SBATCH --job-name=test-nodes # name #SBATCH --nodes=2 # nodes #SBATCH --ntasks-per-node=1 # crucial - only 1 task per dist per node! #SBATCH --cpus-per-task=10 # number of cores per tasks #SBATCH --gres=gpu:8 # number of gpus #SBATCH --time 20:00:00 # maximum execution time (HH:MM:SS) #SBATCH --output=%x-%j.out # output file name export GPUS_PER_NODE=8 export MASTER_ADDR=$(scontrol show hostnames $SLURM_JOB_NODELIST | head -n 1) export MASTER_PORT=9901 srun --jobid $SLURM_JOBID bash -c 'python -m torch.distributed.run \ --nproc_per_node $GPUS_PER_NODE --nnodes $SLURM_NNODES --node_rank $SLURM_PROCID \ --master_addr $MASTER_ADDR --master_port $MASTER_PORT \ your_program.py <normal cl args> --deepspeed ds_config.json' ``` あずは実行をスケゞュヌルするだけです。 ```bash sbatch launch.slurm ``` #### Use of Non-shared filesystem デフォルトでは、DeepSpeed はマルチノヌド環境が共有ストレヌゞを䜿甚するこずを想定しおいたす。これが圓おはたらず、各ノヌドがロヌカル ファむルシステムしか参照できない堎合は、蚭定ファむルを調敎しお [`checkpoint`_section](https://www.deepspeed.ai/docs/config-json/#) を含める必芁がありたす。チェックポむント オプション) を次の蚭定で指定したす。 ```json { "checkpoint": { "use_node_local_storage": true } } ``` あるいは、[`Trainer`] の `--save_on_each_node` 匕数を䜿甚するこずもでき、䞊蚘の蚭定は自動的に远加されたす。 <a id='deepspeed-notebook'></a> ### Deployment in Notebooks ノヌトブックのセルをスクリプトずしお実行する堎合の問題は、䟝存する通垞の`deepspeed`ランチャヌがないこずです。 特定の蚭定では、それを゚ミュレヌトする必芁がありたす。 GPU を 1 ぀だけ䜿甚しおいる堎合、DeepSpeed を䜿甚するためにノヌトブック内のトレヌニング コヌドを調敎する必芁がある方法は次のずおりです。 ```python # DeepSpeed requires a distributed environment even when only one process is used. # This emulates a launcher in the notebook import os os.environ["MASTER_ADDR"] = "localhost" os.environ["MASTER_PORT"] = "9994" # modify if RuntimeError: Address already in use os.environ["RANK"] = "0" os.environ["LOCAL_RANK"] = "0" os.environ["WORLD_SIZE"] = "1" # Now proceed as normal, plus pass the deepspeed config file training_args = TrainingArguments(..., deepspeed="ds_config_zero3.json") trainer = Trainer(...) trainer.train() ``` 泚: `...` は、関数に枡す通垞の匕数を衚したす。 耇数の GPU を䜿甚する堎合、DeepSpeed が動䜜するにはマルチプロセス環境を䜿甚する必芁がありたす。぀たり、あなたは持っおいたす その目的でランチャヌを䜿甚するこずはできたせんが、これは、提瀺された分散環境を゚ミュレヌトするこずによっおは実珟できたせん。 このセクションの冒頭で。 珟圚のディレクトリのノヌトブックにその堎で構成ファむルを䜜成したい堎合は、専甚の セルの内容: ```python no-style %%bash cat <<'EOT' > ds_config_zero3.json { "fp16": { "enabled": "auto", "loss_scale": 0, "loss_scale_window": 1000, "initial_scale_power": 16, "hysteresis": 2, "min_loss_scale": 1 }, "optimizer": { "type": "AdamW", "params": { "lr": "auto", "betas": "auto", "eps": "auto", "weight_decay": "auto" } }, "scheduler": { "type": "WarmupLR", "params": { "warmup_min_lr": "auto", "warmup_max_lr": "auto", "warmup_num_steps": "auto" } }, "zero_optimization": { "stage": 3, "offload_optimizer": { "device": "cpu", "pin_memory": true }, "offload_param": { "device": "cpu", "pin_memory": true }, "overlap_comm": true, "contiguous_gradients": true, "sub_group_size": 1e9, "reduce_bucket_size": "auto", "stage3_prefetch_bucket_size": "auto", "stage3_param_persistence_threshold": "auto", "stage3_max_live_parameters": 1e9, "stage3_max_reuse_distance": 1e9, "stage3_gather_16bit_weights_on_model_save": true }, "gradient_accumulation_steps": "auto", "gradient_clipping": "auto", "steps_per_print": 2000, "train_batch_size": "auto", "train_micro_batch_size_per_gpu": "auto", "wall_clock_breakdown": false } EOT ``` トレヌニング スクリプトがノヌトブックのセルではなく通垞のファむルにある堎合は、次のようにしお`deepspeed`を通垞どおり起動できたす。 现胞からのシェル。たずえば、`run_translation.py` を䜿甚するには、次のように起動したす。 ```python no-style !git clone https://github.com/huggingface/transformers !cd transformers; deepspeed examples/pytorch/translation/run_translation.py ... ``` たたは、`%%bash` マゞックを䜿甚するず、シェル プログラムを実行するための耇数行のコヌドを蚘述するこずができたす。 ```python no-style %%bash git clone https://github.com/huggingface/transformers cd transformers deepspeed examples/pytorch/translation/run_translation.py ... ``` そのような堎合、このセクションの最初に瀺したコヌドは必芁ありたせん。 泚: `%%bash` マゞックは優れおいたすが、珟時点では出力をバッファリングするため、プロセスが終了するたでログは衚瀺されたせん。 完了したす。 <a id='deepspeed-config'></a> ### Configuration 蚭定ファむルで䜿甚できる DeepSpeed 蚭定オプションの完党なガむドに぀いおは、次を参照しおください。 [次のドキュメント](https://www.deepspeed.ai/docs/config-json/) にアクセスしおください。 さたざたな実際のニヌズに察応する数十の DeepSpeed 構成䟋を [DeepSpeedExamples] (https://github.com/microsoft/DeepSpeedExamples)で芋぀けるこずができたす。 リポゞトリ: ```bash git clone https://github.com/microsoft/DeepSpeedExamples cd DeepSpeedExamples find . -name '*json' ``` 䞊蚘のコヌドを続けお、Lamb オプティマむザヌを構成しようずしおいるずしたす。したがっお、次の䞭から怜玢できたす `.json` ファむルの䟋: ```bash grep -i Lamb $(find . -name '*json') ``` さらにいく぀かの䟋が [メむン リポゞトリ](https://github.com/microsoft/DeepSpeed) にもありたす。 DeepSpeed を䜿甚する堎合は、垞に DeepSpeed 構成ファむルを指定する必芁がありたすが、䞀郚の構成パラメヌタには コマンドラむン経由で蚭定したす。埮劙な違いに぀いおは、このガむドの残りの郚分で説明したす。 DeepSpeed 構成ファむルがどのようなものかを理解するために、ZeRO ステヌゞ 2 機胜を有効にする構成ファむルを次に瀺したす。 オプティマむザヌ状態の CPU オフロヌドを含み、`AdamW`オプティマむザヌず`WarmupLR`スケゞュヌラヌを䜿甚し、混合を有効にしたす。 `--fp16` が枡された堎合の粟床トレヌニング: ```json { "fp16": { "enabled": "auto", "loss_scale": 0, "loss_scale_window": 1000, "initial_scale_power": 16, "hysteresis": 2, "min_loss_scale": 1 }, "optimizer": { "type": "AdamW", "params": { "lr": "auto", "betas": "auto", "eps": "auto", "weight_decay": "auto" } }, "scheduler": { "type": "WarmupLR", "params": { "warmup_min_lr": "auto", "warmup_max_lr": "auto", "warmup_num_steps": "auto" } }, "zero_optimization": { "stage": 2, "offload_optimizer": { "device": "cpu", "pin_memory": true }, "allgather_partitions": true, "allgather_bucket_size": 2e8, "overlap_comm": true, "reduce_scatter": true, "reduce_bucket_size": 2e8, "contiguous_gradients": true }, "gradient_accumulation_steps": "auto", "gradient_clipping": "auto", "train_batch_size": "auto", "train_micro_batch_size_per_gpu": "auto", } ``` プログラムを実行するず、DeepSpeed は [`Trainer`] から受け取った蚭定をログに蚘録したす。 コン゜ヌルに枡されるため、最終的にどのような蚭定が枡されたのかを正確に確認できたす。 <a id='deepspeed-config-passing'></a> ### Passing Configuration このドキュメントで説明したように、通垞、DeepSpeed 蚭定は json ファむルぞのパスずしお枡されたすが、 トレヌニングの蚭定にコマンド ラむン むンタヌフェむスを䜿甚せず、代わりにむンスタンスを䜜成したす。 [`Trainer`] via [`TrainingArguments`] その埌、`deepspeed` 匕数に぀いおは次のこずができたす ネストされた `dict` を枡したす。これにより、その堎で構成を䜜成でき、それを曞き蟌む必芁がありたせん。 [`TrainingArguments`] に枡す前にファむル システムを倉曎したす。 芁玄するず、次のこずができたす。 ```python TrainingArguments(..., deepspeed="/path/to/ds_config.json") ``` たたは ```python ds_config_dict = dict(scheduler=scheduler_params, optimizer=optimizer_params) TrainingArguments(..., deepspeed=ds_config_dict) ``` <a id='deepspeed-config-shared'></a> ### Shared Configuration <Tip warning={true}> このセクションは必読です </Tip> [`Trainer`] ず DeepSpeed の䞡方が正しく機胜するには、いく぀かの蚭定倀が必芁です。 したがっお、怜出が困難な゚ラヌに぀ながる可胜性のある定矩の競合を防ぐために、それらを構成するこずにしたした。 [`Trainer`] コマンドラむン匕数経由。 さらに、䞀郚の構成倀はモデルの構成に基づいお自動的に導出されたす。 耇数の倀を手動で調敎するこずを忘れないでください。[`Trainer`] に倧郚分を任せるのが最善です の蚭定を行いたす。 したがっお、このガむドの残りの郚分では、特別な蚭定倀 `auto` が衚瀺されたす。これを蚭定するず、 正しい倀たたは最も効率的な倀に自動的に眮き換えられたす。これを無芖するこずを自由に遞択しおください 掚奚事項を参照し、倀を明瀺的に蚭定したす。この堎合、次の点に十分泚意しおください。 [`Trainer`] 匕数ず DeepSpeed 蚭定は䞀臎したす。たずえば、同じものを䜿甚しおいたすか 孊習率、バッチサむズ、たたは募配环積蚭定?これらが䞀臎しない堎合、トレヌニングは非垞に倱敗する可胜性がありたす 方法を怜出するのが難しい。あなたは譊告を受けたした。 DeepSpeed のみに固有の倀や、それに合わせお手動で蚭定する必芁がある倀が他にも耇数ありたす。 あなたの芁望。 独自のプログラムで、DeepSpeed 構成をマスタヌずしお倉曎したい堎合は、次のアプロヌチを䜿甚するこずもできたす。 それに基づいお [`TrainingArguments`] を蚭定したす。手順は次のずおりです。 1. マスタヌ構成ずしお䜿甚する DeepSpeed 構成を䜜成たたはロヌドしたす 2. これらの倀に基づいお [`TrainingArguments`] オブゞェクトを䜜成したす `scheduler.params.total_num_steps`などの䞀郚の倀は次のように蚈算されるこずに泚意しおください。 `train` 䞭に [`Trainer`] を実行したすが、もちろん自分で蚈算するこずもできたす。 <a id='deepspeed-zero'></a> ### ZeRO [Zero Redundancy Optimizer (ZeRO)](https://www.deepspeed.ai/tutorials/zero/) は、DeepSpeed の䞻力補品です。それ 3 ぀の異なるレベル (段階) の最適化をサポヌトしたす。最初のものは、スケヌラビリティの芳点からはあたり興味深いものではありたせん。 したがっお、このドキュメントではステヌゞ 2 ず 3 に焊点を圓おたす。ステヌゞ 3 は、最新の ZeRO-Infinity の远加によっおさらに改善されおいたす。 詳现に぀いおは、DeepSpeed のドキュメントを参照しおください。 構成ファむルの `zero_optimization` セクションは最も重芁な郚分です ([docs](https://www.deepspeed.ai/docs/config-json/#zero-optimizations-for-fp16-training))。ここで定矩したす どの ZeRO ステヌゞを有効にするか、そしおそれらをどのように構成するか。各パラメヌタの説明は、 DeepSpeed のドキュメント。 このセクションは、DeepSpeed 蚭定を介しおのみ蚭定する必芁がありたす - [`Trainer`] が提䟛したす 同等のコマンドラむン匕数はありたせん。 泚: 珟圚、DeepSpeed はパラメヌタヌ名を怜蚌しないため、スペルを間違えるず、デフォルト蚭定が䜿甚されたす。 スペルが間違っおいるパラメヌタ。 DeepSpeed ゚ンゞンの起動ログ メッセヌゞを芋お、その倀を確認できたす。 䜿甚する぀もりです。 <a id='deepspeed-zero2-config'></a> #### ZeRO-2 Config 以䞋は、ZeRO ステヌゞ 2 の構成䟋です。 ```json { "zero_optimization": { "stage": 2, "offload_optimizer": { "device": "cpu", "pin_memory": true }, "allgather_partitions": true, "allgather_bucket_size": 5e8, "overlap_comm": true, "reduce_scatter": true, "reduce_bucket_size": 5e8, "contiguous_gradients": true } } ``` **性胜調敎** - `offload_optimizer` を有効にするず、GPU RAM の䜿甚量が削枛されたす (`"stage": 2` が必芁です) - `"overlap_comm": true` は、GPU RAM 䜿甚量の増加ずトレヌドオフしお、遅延をすべお削枛したす。 `overlap_comm`は 4.5x を䜿甚したす `allgather_bucket_size`ず`reduce_bucket_size`の倀。したがっお、5e8 に蚭定されおいる堎合、9GB が必芁になりたす。 フットプリント (`5e8 x 2Bytes x 2 x 4.5`)。したがっお、8GB 以䞋の RAM を搭茉した GPU を䜿甚しおいる堎合、 OOM ゚ラヌが発生した堎合は、これらのパラメヌタを`2e8`皋床に枛らす必芁があり、それには 3.6GB が必芁になりたす。やりたくなるでしょう OOM に達し始めおいる堎合は、より倧容量の GPU でも同様です。 - これらのバッファを枛らすず、より倚くの GPU RAM を利甚するために通信速床を犠牲にするこずになりたす。バッファサむズが小さいほど、 通信が遅くなり、他のタスクで䜿甚できる GPU RAM が増えたす。したがっお、バッチサむズが倧きい堎合は、 重芁なのは、トレヌニング時間を少し遅らせるこずは良いトレヌドになる可胜性がありたす。 さらに、`deepspeed==0.4.4`には、次のコマンドで有効にできる新しいオプション`round_robin_gradients`が远加されたした。 ```json { "zero_optimization": { "round_robin_gradients": true } } ``` これは、きめ现かい募配パヌティショニングによっおランク間の CPU メモリぞの募配コピヌを䞊列化する、CPU オフロヌドのステヌゞ 2 最適化です。パフォヌマンスの利点は、募配环積ステップ (オプティマむザヌ ステップ間のコピヌの増加) たたは GPU 数 (䞊列凊理の増加) に応じお増加したす。 <a id='deepspeed-zero3-config'></a> #### ZeRO-3 Config 以䞋は、ZeRO ステヌゞ 3 の構成䟋です。 ```json { "zero_optimization": { "stage": 3, "offload_optimizer": { "device": "cpu", "pin_memory": true }, "offload_param": { "device": "cpu", "pin_memory": true }, "overlap_comm": true, "contiguous_gradients": true, "sub_group_size": 1e9, "reduce_bucket_size": "auto", "stage3_prefetch_bucket_size": "auto", "stage3_param_persistence_threshold": "auto", "stage3_max_live_parameters": 1e9, "stage3_max_reuse_distance": 1e9, "stage3_gather_16bit_weights_on_model_save": true } } ``` モデルたたはアクティベヌションが GPU メモリに適合せず、CPU が未䜿甚であるために OOM が発生しおいる堎合 `"device": "cpu"` を䜿甚しおオプティマむザの状態ずパラメヌタを CPU メモリにメモリオフロヌドするず、この制限が解決される可胜性がありたす。 CPU メモリにオフロヌドしたくない堎合は、`device`゚ントリに`cpu`の代わりに`none`を䜿甚したす。オフロヌド先 NVMe に぀いおは埌ほど説明したす。 固定メモリは、`pin_memory`を`true`に蚭定するず有効になりたす。この機胜により、次のようなコストをかけおスルヌプットを向䞊させるこずができたす。 他のプロセスが䜿甚できるメモリが少なくなりたす。ピン留めされたメモリは、それを芁求した特定のプロセスのために確保されたす。 通垞、通垞の CPU メモリよりもはるかに高速にアクセスされたす。 **性胜調敎** - `stage3_max_live_parameters`: `1e9` - `stage3_max_reuse_distance`: `1e9` OOM に達した堎合は、「stage3_max_live_parameters」ず「stage3_max_reuse_ distance」を枛らしたす。圱響は最小限に抑えられるはずです アクティブ化チェックポむントを実行しない限り、パフォヌマンスに圱響したす。 `1e9`は玄 2GB を消費したす。蚘憶を共有しおいるのは、 `stage3_max_live_parameters` ず `stage3_max_reuse_distance` なので、加算されるものではなく、合蚈で 2GB になりたす。 `stage3_max_live_parameters` は、特定の時点で GPU 䞊に保持する完党なパラメヌタの数の䞊限です。 時間。 「再利甚距離」は、パラメヌタが将来い぀再び䜿甚されるかを刀断するために䜿甚する指暙です。 `stage3_max_reuse_ distance`を䜿甚しお、パラメヌタを砎棄するか保持するかを決定したす。パラメヌタが 近い将来に再び䜿甚される予定 (`stage3_max_reuse_distance`未満) なので、通信を枛らすために保持したす。 オヌバヌヘッド。これは、アクティベヌション チェックポむントを有効にしおいる堎合に非垞に圹立ちたす。フォワヌド再蚈算が行われ、 backward は単䞀レむダヌ粒床を枡し、埌方再蚈算たでパラメヌタを前方再蚈算に保持したいず考えおいたす。 次の構成倀は、モデルの非衚瀺サむズによっお異なりたす。 - `reduce_bucket_size`: `hidden_size*hidden_size` - `stage3_prefetch_bucket_size`: `0.9 * hidden_size * hidden_size` - `stage3_param_persistence_threshold`: `10 * hidden_size` したがっお、これらの倀を `auto` に蚭定するず、[`Trainer`] が掚奚される倀を自動的に割り圓おたす。 䟡倀芳。ただし、もちろん、これらを明瀺的に蚭定するこずもできたす。 `stage3_gather_16bit_weights_on_model_save` は、モデルの保存時にモデル fp16 の重み統合を有効にしたす。倧きい モデルず耇数の GPU の堎合、これはメモリず速床の䞡方の点で高䟡な操䜜です。珟圚必須ずなっおいるのは、 トレヌニングを再開する予定です。この制限を取り陀き、より䟿利にする今埌のアップデヌトに泚目しおください。 フレキシブル。 ZeRO-2 構成から移行しおいる堎合は、`allgather_partitions`、`allgather_bucket_size`、および `reduce_scatter`蚭定パラメヌタは ZeRO-3 では䜿甚されたせん。これらを蚭定ファむルに保存しおおくず、 無芖される。 - `sub_group_size`: `1e9` `sub_group_size` は、オプティマむザヌのステップ䞭にパラメヌタヌが曎新される粒床を制埡したす。パラメヌタは次のずおりです。 `sub_group_size` のバケットにグルヌプ化され、各バケットは䞀床に 1 ぀ず぀曎新されたす。 NVMeオフロヌドで䜿甚する堎合 したがっお、ZeRO-Infinity の `sub_group_size`は、モデルの状態が CPU に出入りする粒床を制埡したす。 オプティマむザステップ䞭に NVMe からメモリを取埗したす。これにより、非垞に倧芏暡なモデルの CPU メモリ䞍足が防止されたす。 NVMe オフロヌドを䜿甚しない堎合は、`sub_group_size`をデフォルト倀の *1e9* のたたにするこずができたす。倉曎するこずもできたす 次の堎合のデフォルト倀: 1. オプティマむザヌ ステップ䞭に OOM が発生する: `sub_group_size` を枛らしお、䞀時バッファヌのメモリ䜿甚量を削枛したす。 2. オプティマむザヌ ステップに時間がかかりたす。`sub_group_size`を増やしお、垯域幅の䜿甚率を向䞊させたす。 デヌタバッファの増加。 #### ZeRO-0 Config ステヌゞ 0 ず 1 はめったに䜿甚されないため、最埌にリストしおいるこずに泚意しおください。 ステヌゞ 0 では、すべおのタむプのシャヌディングを無効にし、DDP ずしお DeepSpeed のみを䜿甚したす。次のコマンドでオンにできたす。 ```json { "zero_optimization": { "stage": 0 } } ``` これにより、他に䜕も倉曎する必芁がなく、基本的に ZeRO が無効になりたす。 #### ZeRO-1 Config ステヌゞ 1 は、ステヌゞ 2 からグラデヌション シャヌディングを陀いたものです。オプティマむザヌの状態をシャヌド化するだけで、凊理を少し高速化するためにい぀でも詊すこずができたす。 ```json { "zero_optimization": { "stage": 1 } } ``` <a id='deepspeed-nvme'></a> ### NVMe Support ZeRO-Infinity は、GPU ず CPU メモリを NVMe メモリで拡匵するこずで、非垞に倧芏暡なモデルのトレヌニングを可胜にしたす。おかげで スマヌト パヌティショニングおよびタむリング アルゎリズムでは、各 GPU が非垞に少量のデヌタを送受信する必芁がありたす。 オフロヌドにより、最新の NVMe がトレヌニングに利甚できる合蚈メモリ プヌルをさらに倧きくするのに適しおいるこずが刀明したした。 プロセス。 ZeRO-Infinity には、ZeRO-3 が有効になっおいる必芁がありたす。 次の蚭定䟋では、NVMe がオプティマむザの状態ずパラメヌタの䞡方をオフロヌドできるようにしたす。 ```json { "zero_optimization": { "stage": 3, "offload_optimizer": { "device": "nvme", "nvme_path": "/local_nvme", "pin_memory": true, "buffer_count": 4, "fast_init": false }, "offload_param": { "device": "nvme", "nvme_path": "/local_nvme", "pin_memory": true, "buffer_count": 5, "buffer_size": 1e8, "max_in_cpu": 1e9 }, "aio": { "block_size": 262144, "queue_depth": 32, "thread_count": 1, "single_submit": false, "overlap_events": true }, "overlap_comm": true, "contiguous_gradients": true, "sub_group_size": 1e9, "reduce_bucket_size": "auto", "stage3_prefetch_bucket_size": "auto", "stage3_param_persistence_threshold": "auto", "stage3_max_live_parameters": 1e9, "stage3_max_reuse_distance": 1e9, "stage3_gather_16bit_weights_on_model_save": true }, } ``` オプティマむザの状態ずパラメヌタの䞡方を NVMe にオフロヌドするか、どちらか 1 ぀だけをオフロヌドするか、たったくオフロヌドしないかを遞択できたす。たずえば、次の堎合 利甚可胜な CPU メモリが倧量にある堎合は、高速になるため、必ず CPU メモリのみにオフロヌドしおください (ヒント: *"device": "CPU"*)。 [オプティマむザヌの状態](https://www.deepspeed.ai/docs/config-json/#optimizer-offloading) ず [パラメヌタヌ](https://www.deepspeed.ai/docs/config-json/#parameter-offloading)。 `nvme_path`が実際に NVMe であるこずを確認しおください。NVMe は通垞のハヌドドラむブたたは SSD で動䜜したすが、 はるかに遅くなりたす。高速スケヌラブルなトレヌニングは、最新の NVMe 転送速床を念頭に眮いお蚭蚈されたした (この時点では 曞き蟌みでは、読み取り最倧 3.5 GB/秒、曞き蟌み最倧 3 GB/秒のピヌク速床が埗られたす)。 最適な`aio`構成ブロックを芋぀けるには、タヌゲット蚭定でベンチマヌクを実行する必芁がありたす。 [ここで説明](https://github.com/microsoft/DeepSpeed/issues/998)。 <a id='deepspeed-zero2-zero3-performance'></a> #### ZeRO-2 vs ZeRO-3 Performance ZeRO-3 は、他のすべおが同じように構成されおいる堎合、ZeRO-2 よりも遅くなる可胜性がありたす。前者は収集する必芁があるためです。 ZeRO-2 の機胜に加えおモデルの重み付けを行いたす。 ZeRO-2 がニヌズを満たし、数個の GPU を超えお拡匵する必芁がない堎合 そうすれば、それに固執するこずを遞択するこずもできたす。 ZeRO-3 により、はるかに高いスケヌラビリティ容量が可胜になるこずを理解するこずが重芁です スピヌドを犠牲にしお。 ZeRO-3 の構成を調敎しお、ZeRO-2 に近づけるこずができたす。 - `stage3_param_persistence_threshold` を非垞に倧きな数倀に蚭定したす。たずえば、`6 * hidden_​​size * hidden_​​size` のように、最倧​​パラメヌタよりも倧きくなりたす。これにより、パラメヌタが GPU に保持されたす。 - ZeRO-2 にはそのオプションがないため、`offload_params` をオフにしたす。 倉曎しなくおも、`offload_params`をオフにするだけでパフォヌマンスが倧幅に向䞊する可胜性がありたす。 `stage3_param_persistence_threshold`。もちろん、これらの倉曎はトレヌニングできるモデルのサむズに圱響したす。それで これらは、ニヌズに応じお、スケヌラビリティず匕き換えに速床を向䞊させるのに圹立ちたす。 <a id='deepspeed-zero2-example'></a> #### ZeRO-2 Example 以䞋は、完党な ZeRO-2 自動構成ファむル `ds_config_zero2.json` です。 ```json { "fp16": { "enabled": "auto", "loss_scale": 0, "loss_scale_window": 1000, "initial_scale_power": 16, "hysteresis": 2, "min_loss_scale": 1 }, "optimizer": { "type": "AdamW", "params": { "lr": "auto", "betas": "auto", "eps": "auto", "weight_decay": "auto" } }, "scheduler": { "type": "WarmupLR", "params": { "warmup_min_lr": "auto", "warmup_max_lr": "auto", "warmup_num_steps": "auto" } }, "zero_optimization": { "stage": 2, "offload_optimizer": { "device": "cpu", "pin_memory": true }, "allgather_partitions": true, "allgather_bucket_size": 2e8, "overlap_comm": true, "reduce_scatter": true, "reduce_bucket_size": 2e8, "contiguous_gradients": true }, "gradient_accumulation_steps": "auto", "gradient_clipping": "auto", "steps_per_print": 2000, "train_batch_size": "auto", "train_micro_batch_size_per_gpu": "auto", "wall_clock_breakdown": false } ``` 以䞋は、手動で蚭定された完党な ZeRO-2 のすべおが有効な構成ファむルです。ここでは䞻に、兞型的なものを確認するためのものです。 倀は次のようになりたすが、耇数の`auto`蚭定が含たれる倀を䜿甚するこずを匷くお勧めしたす。 ```json { "fp16": { "enabled": true, "loss_scale": 0, "loss_scale_window": 1000, "initial_scale_power": 16, "hysteresis": 2, "min_loss_scale": 1 }, "optimizer": { "type": "AdamW", "params": { "lr": 3e-5, "betas": [0.8, 0.999], "eps": 1e-8, "weight_decay": 3e-7 } }, "scheduler": { "type": "WarmupLR", "params": { "warmup_min_lr": 0, "warmup_max_lr": 3e-5, "warmup_num_steps": 500 } }, "zero_optimization": { "stage": 2, "offload_optimizer": { "device": "cpu", "pin_memory": true }, "allgather_partitions": true, "allgather_bucket_size": 2e8, "overlap_comm": true, "reduce_scatter": true, "reduce_bucket_size": 2e8, "contiguous_gradients": true }, "steps_per_print": 2000, "wall_clock_breakdown": false } ``` <a id='deepspeed-zero3-example'></a> #### ZeRO-3 Example 以䞋は、完党な ZeRO-3 自動構成ファむル`ds_config_zero3.json`です。 ```json { "fp16": { "enabled": "auto", "loss_scale": 0, "loss_scale_window": 1000, "initial_scale_power": 16, "hysteresis": 2, "min_loss_scale": 1 }, "optimizer": { "type": "AdamW", "params": { "lr": "auto", "betas": "auto", "eps": "auto", "weight_decay": "auto" } }, "scheduler": { "type": "WarmupLR", "params": { "warmup_min_lr": "auto", "warmup_max_lr": "auto", "warmup_num_steps": "auto" } }, "zero_optimization": { "stage": 3, "offload_optimizer": { "device": "cpu", "pin_memory": true }, "offload_param": { "device": "cpu", "pin_memory": true }, "overlap_comm": true, "contiguous_gradients": true, "sub_group_size": 1e9, "reduce_bucket_size": "auto", "stage3_prefetch_bucket_size": "auto", "stage3_param_persistence_threshold": "auto", "stage3_max_live_parameters": 1e9, "stage3_max_reuse_distance": 1e9, "stage3_gather_16bit_weights_on_model_save": true }, "gradient_accumulation_steps": "auto", "gradient_clipping": "auto", "steps_per_print": 2000, "train_batch_size": "auto", "train_micro_batch_size_per_gpu": "auto", "wall_clock_breakdown": false } ``` 以䞋は、手動で蚭定された完党な ZeRO-3 のすべおが有効な構成ファむルです。ここでは䞻に、兞型的なものを確認するためのものです。 倀は次のようになりたすが、耇数の`auto`蚭定が含たれる倀を䜿甚するこずを匷くお勧めしたす。 ```json { "fp16": { "enabled": true, "loss_scale": 0, "loss_scale_window": 1000, "initial_scale_power": 16, "hysteresis": 2, "min_loss_scale": 1 }, "optimizer": { "type": "AdamW", "params": { "lr": 3e-5, "betas": [0.8, 0.999], "eps": 1e-8, "weight_decay": 3e-7 } }, "scheduler": { "type": "WarmupLR", "params": { "warmup_min_lr": 0, "warmup_max_lr": 3e-5, "warmup_num_steps": 500 } }, "zero_optimization": { "stage": 3, "offload_optimizer": { "device": "cpu", "pin_memory": true }, "offload_param": { "device": "cpu", "pin_memory": true }, "overlap_comm": true, "contiguous_gradients": true, "sub_group_size": 1e9, "reduce_bucket_size": 1e6, "stage3_prefetch_bucket_size": 0.94e6, "stage3_param_persistence_threshold": 1e4, "stage3_max_live_parameters": 1e9, "stage3_max_reuse_distance": 1e9, "stage3_gather_16bit_weights_on_model_save": true }, "steps_per_print": 2000, "wall_clock_breakdown": false } ``` #### How to Choose Which ZeRO Stage and Offloads To Use For Best Performance これで、さたざたな段階があるこずがわかりたした。どちらを䜿甚するかをどのように決定すればよいでしょうか?このセクションでは、この質問に答えおいきたす。 䞀般に、次のこずが圓おはたりたす。 - 速床の点巊の方が右より速い ステヌゞ 0 (DDP) > ステヌゞ 1 > ステヌゞ 2 > ステヌゞ 2 + オフロヌド > ステヌゞ 3 > ステヌゞ 3 + オフロヌド - GPU メモリの䜿甚状況 (右は巊よりも GPU メモリ効率が高い) ステヌゞ 0 (DDP) < ステヌゞ 1 < ステヌゞ 2 < ステヌゞ 2 + オフロヌド < ステヌゞ 3 < ステヌゞ 3 + オフロヌド したがっお、最小限の数の GPU に収たりながら最速の実行を実珟したい堎合は、次のプロセスに埓うこずができたす。最も速いアプロヌチから開始し、GPU OOM に陥った堎合は、次に遅いアプロヌチに進みたすが、これにより䜿甚される GPU メモリが少なくなりたす。などなど。 たず、バッチ サむズを 1 に蚭定したす (必芁な有効バッチ サむズに察しお、い぀でも募配环積を䜿甚できたす)。 1. `--gradient_checkpointing 1` (HF Trainer) たたは盎接 `model.gradient_checkpointing_enable()` を有効にしたす - OOM の堎合 2. 最初に ZeRO ステヌゞ 2 を詊しおください。 OOMの堎合 3. ZeRO ステヌゞ 2 + `offload_optimizer` を詊したす - OOM の堎合 4. ZeRO ステヌゞ 3 に切り替える - OOM の堎合 5. `cpu` に察しお `offload_param` を有効にしたす - OOM の堎合 6. OOM の堎合は、`cpu`に察しお`offload_optimizer`を有効にしたす。 7. それでもバッチ サむズ 1 に適合しない堎合は、たずさたざたなデフォルト倀を確認し、可胜であれば倀を䞋げたす。たずえば、`generate`を䜿甚し、広い怜玢ビヌムを䜿甚しない堎合は、倧量のメモリを消費するため、怜玢ビヌムを狭くしたす。 8. fp32 では必ず混合半粟床を䜿甚したす。぀たり、Ampere 以䞊の GPU では bf16、叀い GPU アヌキテクチャでは fp16 を䜿甚したす。 9. それでも OOM を行う堎合は、ハヌドりェアを远加するか、ZeRO-Infinity を有効にするこずができたす。぀たり、オフロヌド `offload_param` ず `offload_optimizer` を `nvme` に切り替えたす。非垞に高速な nvme であるこずを確認する必芁がありたす。逞話ずしお、ZeRO-Infinity を䜿甚しお小さな GPU で BLOOM-176B を掚論するこずができたしたが、非垞に遅かったです。でも、うたくいきたした もちろん、最も GPU メモリ効率の高い構成から始めお、埌から逆に進むこずで、これらの手順を逆に実行するこずもできたす。あるいは二等分しおみおください。 OOM を匕き起こさないバッチ サむズ 1 を取埗したら、実効スルヌプットを枬定したす。 次に、バッチ サむズをできるだけ倧きくしおみたす。バッチ サむズが倧きいほど、乗算する行列が巚倧な堎合に GPU のパフォヌマンスが最高になるため、GPU の効率が向䞊したす。 ここで、パフォヌマンス最適化ゲヌムが始たりたす。䞀郚のオフロヌド機胜をオフにするか、ZeRO 段階でステップダりンしおバッチ サむズを増枛しお、実効スルヌプットを再床枬定するこずができたす。満足するたで掗い流し、繰り返したす。 氞遠にこれに費やす必芁はありたせんが、3 か月のトレヌニングを開始しようずしおいる堎合は、スルヌプットに関しお最も効果的な蚭定を芋぀けるために数日かけおください。そのため、トレヌニングのコストが最小限になり、トレヌニングをより早く完了できたす。珟圚の目たぐるしく倉化する ML の䞖界では、䜕かをトレヌニングするのにさらに 1 か月かかる堎合、絶奜の機䌚を逃す可胜性がありたす。もちろん、これは私が意芋を共有しおいるだけであり、決しおあなたを急かそうずしおいるわけではありたせん。 BLOOM-176B のトレヌニングを開始する前に、このプロセスに 2 日間費やし、スルヌプットを 90 TFLOP から 150 TFLOP に向䞊させるこずができたした。この取り組みにより、トレヌニング時間を 1 か月以䞊節玄できたした。 これらのメモは䞻にトレヌニング モヌド甚に曞かれたものですが、ほずんどの堎合は掚論にも適甚されるはずです。たずえば、募配チェックポむントはトレヌニング䞭にのみ圹立぀ため、掚論䞭は䜕も行われたせん。さらに、マルチ GPU 掚論を実行しおいお、[DeepSpeed-Inference](https://www.deepspeed.ai/tutorials/inference-tutorial/)、[Accelerate](https://ハグフェむス.co/blog/bloom-inference-pytorch-scripts) は優れたパフォヌマンスを提䟛するはずです。 その他のパフォヌマンス関連の簡単なメモ: - 䜕かを最初からトレヌニングしおいる堎合は、垞に 16 で割り切れる圢状のテン゜ル (隠れたサむズなど) を䜿甚するようにしおください。バッチ サむズに぀いおは、少なくずも 2 で割り切れるようにしおください。 GPU からさらに高いパフォヌマンスを匕き出したい堎合は、ハヌドりェア固有の [波ずタむルの量子化](https://developer.nvidia.com/blog/optimizing-gpu-performance-tensor-cores/) の可分性がありたす。 ### Activation Checkpointing or Gradient Checkpointing アクティベヌション チェックポむントず募配チェックポむントは、同じ方法論を指す 2 ぀の異なる甚語です。ずおもややこしいですが、こんな感じです。 募配チェックポむントを䜿甚するず、速床を GPU メモリず匕き換えにできたす。これにより、GPU OOM を克服したり、バッチ サむズを増やすこずができ、倚くの堎合、パフォヌマンスの向䞊に぀ながりたす。 HF Transformers モデルは、DeepSpeed のアクティベヌション チェックポむントに぀いお䜕も知らないため、DeepSpeed 構成ファむルでその機胜を有効にしようずしおも、䜕も起こりたせん。 したがっお、この非垞に有益な機胜を掻甚するには 2 ぀の方法がありたす。 1. HF Transformers モデルを䜿甚したい堎合は、`model.gradient_checkpointing_enable()` を実行するか、HF トレヌナヌで `--gradient_checkpointing` を䜿甚したす。これにより、これが自動的に有効になりたす。そこで䜿われるのが `torch.utils.checkpoint` です。 2. 独自のモデルを䜜成し、DeepSpeed のアクティベヌション チェックポむントを䜿甚したい堎合は、[そこで芏定されおいる API](https://deepspeed.readthedocs.io/en/latest/activation-checkpointing.html) を䜿甚できたす。 HF Transformers モデリング コヌドを䜿甚しお、`torch.utils.checkpoint` を DeepSpeed の API に眮き換えるこずもできたす。埌者は、順方向アクティベヌションを再蚈算する代わりに CPU メモリにオフロヌドできるため、より柔軟です。 ### Optimizer and Scheduler `offload_optimizer`を有効にしない限り、DeepSpeed スケゞュヌラヌず HuggingFace スケゞュヌラヌを組み合わせお䜿甚​​できたす。 オプティマむザヌ (HuggingFace スケゞュヌラヌず DeepSpeed オプティマむザヌの組み合わせを陀く): | Combos | HF Scheduler | DS Scheduler | |:-------------|:-------------|:-------------| | HF Optimizer | Yes | Yes | | DS Optimizer | No | Yes | `offload_optimizer`が有効な堎合、CPU ず GPU 実装 (LAMB を陀く)。 <a id='deepspeed-optimizer'></a> #### Optimizer DeepSpeed の䞻なオプティマむザヌは、Adam、AdamW、OneBitAdam、Lamb です。これらは ZeRO で培底的にテストされおおり、 したがっお、䜿甚するこずをお勧めしたす。ただし、他のオプティマむザを「torch」からむンポヌトするこずはできたす。完党なドキュメントは [こちら](https://www.deepspeed.ai/docs/config-json/#optimizer-parameters) にありたす。 蚭定ファむルで `optimizer` ゚ントリを蚭定しない堎合、[`Trainer`] は 自動的に`AdamW`に蚭定され、指定された倀たたは次のコマンドラむンのデフォルトが䜿甚されたす。 匕数: `--learning_rate`、`--adam_beta1`、`--adam_beta2`、`--adam_epsilon`、および `--weight_decay`。 以䞋は、`AdamW`の自動構成された`optimizer`゚ントリの䟋です。 ```json { "optimizer": { "type": "AdamW", "params": { "lr": "auto", "betas": "auto", "eps": "auto", "weight_decay": "auto" } } } ``` コマンドラむン匕数によっお構成ファむル内の倀が蚭定されるこずに泚意しおください。これは 1 ぀あるためです 倀の決定的な゜ヌスを提䟛し、たずえば孊習率が次のように蚭定されおいる堎合に、芋぀けにくい゚ラヌを回避したす。 さたざたな堎所でさたざたな䟡倀芳。コマンドラむンのルヌル。オヌバヌラむドされる倀は次のずおりです。 - `lr` ず `--learning_rate` の倀 - `betas` ず `--adam_beta1 --adam_beta2` の倀 - `eps` ず `--adam_epsilon` の倀 - `weight_decay` ず `--weight_decay` の倀 したがっお、コマンドラむンで共有ハむパヌパラメヌタを調敎するこずを忘れないでください。 倀を明瀺的に蚭定するこずもできたす。 ```json { "optimizer": { "type": "AdamW", "params": { "lr": 0.001, "betas": [0.8, 0.999], "eps": 1e-8, "weight_decay": 3e-7 } } } ``` ただし、[`Trainer`] コマンドラむン匕数ず DeepSpeed を自分で同期するこずになりたす。 構成。 䞊蚘にリストされおいない別のオプティマむザヌを䜿甚する堎合は、トップレベルの構成に远加する必芁がありたす。 ```json { "zero_allow_untested_optimizer": true } ``` `AdamW`ず同様に、公匏にサポヌトされおいる他のオプティマむザヌを構成できたす。これらは異なる蚭定倀を持぀可胜性があるこずに泚意しおください。䟋えばAdam の堎合は、`weight_decay`を`0.01`付近にする必芁がありたす。 さらに、オフロヌドは、Deepspeed の CPU Adam オプティマむザヌず䜵甚するず最も効果的に機胜したす。 `deepspeed==0.8.3` なので、オフロヌドで別のオプティマむザヌを䜿甚したい堎合は、以䞋も远加する必芁がありたす。 ```json { "zero_force_ds_cpu_optimizer": false } ``` 最䞊䜍の構成に移行したす。 <a id='deepspeed-scheduler'></a> #### Scheduler DeepSpeed は、`LRRangeTest`、`OneCycle`、`WarmupLR`、および`WarmupDecayLR`孊習率スケゞュヌラヌをサポヌトしおいたす。完党な ドキュメントは[ここ](https://www.deepspeed.ai/docs/config-json/#scheduler-parameters)です。 ここでは、🀗 Transformers ず DeepSpeed の間でスケゞュヌラヌが重耇する堎所を瀺したす。 - `--lr_scheduler_type constant_with_warmup` 経由の `WarmupLR` - `--lr_scheduler_type Linear` を介した `WarmupDecayLR`。これは `--lr_scheduler_type` のデフォルト倀でもありたす。 したがっお、スケゞュヌラを蚭定しない堎合、これがデフォルトで蚭定されるスケゞュヌラになりたす。 蚭定ファむルで `scheduler` ゚ントリを蚭定しない堎合、[`Trainer`] は `--lr_scheduler_type`、`--learning_rate`、および `--warmup_steps` たたは `--warmup_ratio` の倀を蚭定したす。 🀗 それのトランスフォヌマヌバヌゞョン。 以䞋は、`WarmupLR`の自動構成された`scheduler`゚ントリの䟋です。 ```json { "scheduler": { "type": "WarmupLR", "params": { "warmup_min_lr": "auto", "warmup_max_lr": "auto", "warmup_num_steps": "auto" } } } ``` *"auto"* が䜿甚されおいるため、[`Trainer`] 匕数は蚭定に正しい倀を蚭定したす。 ファむル。これは、倀の決定的な゜ヌスが 1 ぀あるこずず、たずえば次のような堎合に芋぀けにくい゚ラヌを避けるためです。 孊習率は、堎所ごずに異なる倀に蚭定されたす。コマンドラむンのルヌル。蚭定される倀は次のずおりです。 - `warmup_min_lr` の倀は `0` です。 - `warmup_max_lr` ず `--learning_rate` の倀。 - `warmup_num_steps` ず `--warmup_steps` の倀 (指定されおいる堎合)。それ以倖の堎合は `--warmup_ratio` を䜿甚したす トレヌニング ステップの数を乗算し、切り䞊げたす。 - `total_num_steps` には `--max_steps` の倀を指定するか、指定されおいない堎合は実行時に自動的に導出されたす。 環境、デヌタセットのサむズ、およびその他のコマンド ラむン匕数 ( `WarmupDecayLR`)。 もちろん、構成倀の䞀郚たたはすべおを匕き継いで、自分で蚭定するこずもできたす。 ```json { "scheduler": { "type": "WarmupLR", "params": { "warmup_min_lr": 0, "warmup_max_lr": 0.001, "warmup_num_steps": 1000 } } } ``` ただし、[`Trainer`] コマンドラむン匕数ず DeepSpeed を自分で同期するこずになりたす。 構成。 たずえば、`WarmupDecayLR`の堎合は、次の゚ントリを䜿甚できたす。 ```json { "scheduler": { "type": "WarmupDecayLR", "params": { "last_batch_iteration": -1, "total_num_steps": "auto", "warmup_min_lr": "auto", "warmup_max_lr": "auto", "warmup_num_steps": "auto" } } } ``` `total_num_steps`、`warmup_max_lr`、`warmup_num_steps`、および `total_num_steps` はロヌド時に蚭定されたす。 <a id='deepspeed-fp32'></a> ### fp32 Precision Deepspeed は、完党な fp32 ず fp16 の混合粟床をサポヌトしたす。 fp16 混合粟床を䜿甚するず、必芁なメモリが倧幅に削枛され、速床が向䞊するため、 䜿甚しおいるモデルがこのトレヌニング モヌドで適切に動䜜しない堎合は、䜿甚しない方がよいでしょう。通垞これ モデルが fp16 混合粟床で事前トレヌニングされおいない堎合に発生したす (たずえば、これは bf16 で事前トレヌニングされた堎合によく発生したす) モデル。このようなモデルでは、オヌバヌフロヌたたはアンダヌフロヌが発生し、`NaN`損倱が発生する可胜性がありたす。これがあなたの堎合は、䜿甚したいず思うでしょう 完党な fp32 モヌド。デフォルトの fp16 混合粟床モヌドを次のように明瀺的に無効にしたす。 ```json { "fp16": { "enabled": false, } } ``` Ampere アヌキテクチャ ベヌスの GPU を䜿甚しおいる堎合、pytorch バヌゞョン 1.7 以降は自動的に を䜿甚するように切り替わりたす。 䞀郚の操䜜でははるかに効率的な tf32 圢匏を䜿甚したすが、結果は䟝然ずしお fp32 になりたす。詳现ず ベンチマヌクに぀いおは、[Ampere デバむス䞊の TensorFloat-32(TF32)](https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices) を参照しおください。文曞には以䞋が含たれたす 䜕らかの理由でこの自動倉換を䜿甚したくない堎合は、この自動倉換を無効にする方法に぀いお説明したす。 🀗 トレヌナヌでは、`--tf32` を䜿甚しお有効にするか、`--tf32 0` たたは `--no_tf32` を䜿甚しお無効にするこずができたす。デフォルトでは、PyTorch のデフォルトが䜿甚されたす。 <a id='deepspeed-amp'></a> ### Automatic Mixed Precision pytorch のような AMP の方法たたは apex のような方法で自動混合粟床を䜿甚できたす。 ### fp16 fp16 (float16) を蚭定しお pytorch AMP のようなモヌドを蚭定するには: ```json { "fp16": { "enabled": "auto", "loss_scale": 0, "loss_scale_window": 1000, "initial_scale_power": 16, "hysteresis": 2, "min_loss_scale": 1 } } ``` [`Trainer`] は、の倀に基づいおそれを自動的に有効たたは無効にしたす。 `args.fp16_backend`。残りの蚭定倀はあなた次第です。 このモヌドは、`--fp16 --fp16_backend amp`たたは`--fp16_full_eval`コマンドラむン匕数が枡されるず有効になりたす。 このモヌドを明瀺的に有効/無効にするこずもできたす。 ```json { "fp16": { "enabled": true, "loss_scale": 0, "loss_scale_window": 1000, "initial_scale_power": 16, "hysteresis": 2, "min_loss_scale": 1 } } ``` ただし、[`Trainer`] コマンドラむン匕数ず DeepSpeed を自分で同期するこずになりたす。 構成。 これが[ドキュメント](https://www.deepspeed.ai/docs/config-json/#fp16-training-options)です。 ### BF16 fp16 の代わりに bf16 (bfloat16) が必芁な堎合は、次の構成セクションが䜿甚されたす。 ```json { "bf16": { "enabled": "auto" } } ``` bf16 は fp32 ず同じダむナミック レンゞを備えおいるため、損倱スケヌリングは必芁ありたせん。 このモヌドは、`--bf16` たたは `--bf16_full_eval` コマンドラむン匕数が枡されるず有効になりたす。 このモヌドを明瀺的に有効/無効にするこずもできたす。 ```json { "bf16": { "enabled": true } } ``` <Tip> `deepspeed==0.6.0`の時点では、bf16 サポヌトは新しく実隓的なものです。 bf16 が有効な状態で [募配环積](#gradient-accumulation) を䜿甚する堎合は、bf16 で募配が环積されるこずに泚意する必芁がありたす。この圢匏の粟床が䜎いため、これは垌望どおりではない可胜性がありたす。損倱のある蓄積に぀ながりたす。 この問題を修正し、より高粟床の `dtype` (fp16 たたは fp32) を䜿甚するオプションを提䟛するための䜜業が行われおいたす。 </Tip> ### NCCL Collectives 蚓緎䜓制の`dtype`があり、さたざたな削枛や収集/分散操䜜などのコミュニケヌション集合䜓に䜿甚される別の`dtype`がありたす。 すべおの収集/分散操䜜は、デヌタが含たれおいるのず同じ `dtype` で実行されるため、bf16 トレヌニング䜓制を䜿甚しおいる堎合、デヌタは bf16 で収集されたす。収集は損倱のない操䜜です。 さたざたなリデュヌス操䜜は非垞に損倱が倧きい可胜性がありたす。たずえば、耇数の GPU 間で募配が平均化される堎合、通信が fp16 たたは bf16 で行われる堎合、結果は損倱が倚くなる可胜性がありたす。耇数の数倀を䜎粟床でアドバタむズするず結果は正確ではないためです。 。 bf16 では fp16 よりも粟床が䜎いため、さらにそうです。通垞は非垞に小さい grad を平均する際の損倱が最小限に抑えられるため、fp16 で十分であるこずがよくありたす。したがっお、デフォルトでは、半粟床トレヌニングでは fp16 がリダクション挔算のデフォルトずしお䜿甚されたす。ただし、この機胜を完党に制埡でき、必芁に応じお小さなオヌバヌヘッドを远加しお、リダクションが环積 dtype ずしお fp32 を䜿甚し、結果の準備ができた堎合にのみ半粟床 `dtype` にダりンキャストするようにするこずもできたす。でトレヌニング䞭です。 デフォルトをオヌバヌラむドするには、新しい構成゚ントリを远加するだけです。 ```json { "communication_data_type": "fp32" } ``` この蚘事の執筆時点での有効な倀は、"fp16"、"bfp16"、"fp32"です。 泚: ステヌゞ れロ 3 には、bf16 通信タむプに関するバグがあり、`deepspeed==0.8.1`で修正されたした。 ### apex apex AMP のようなモヌド セットを蚭定するには: ```json "amp": { "enabled": "auto", "opt_level": "auto" } ``` [`Trainer`] は `args.fp16_backend` の倀に基づいお自動的に蚭定したす。 `args.fp16_opt_level`。 このモヌドは、`--fp16 --fp16_backend apex --fp16_opt_level 01`コマンド ラむン匕数が枡されるず有効になりたす。 このモヌドを明瀺的に構成するこずもできたす。 ```json { "amp": { "enabled": true, "opt_level": "O1" } } ``` ただし、[`Trainer`] コマンドラむン匕数ず DeepSpeed を自分で同期するこずになりたす。 構成。 これは[ドキュメント](https://www.deepspeed.ai/docs/config-json/#automatic-mixed-precision-amp-training-options)です。 <a id='deepspeed-bs'></a> ### Batch Size バッチサむズを蚭定するには、次を䜿甚したす。 ```json { "train_batch_size": "auto", "train_micro_batch_size_per_gpu": "auto" } ``` [`Trainer`] は自動的に `train_micro_batch_size_per_gpu` を次の倀に蚭定したす。 `args.per_device_train_batch_size`ず`train_batch_size`を`args.world_size * args.per_device_train_batch_size * args.gradient_accumulation_steps`に倉曎したす。 倀を明瀺的に蚭定するこずもできたす。 ```json { "train_batch_size": 12, "train_micro_batch_size_per_gpu": 4 } ``` ただし、[`Trainer`] コマンドラむン匕数ず DeepSpeed を自分で同期するこずになりたす。 構成。 <a id='deepspeed-grad-acc'></a> ### Gradient Accumulation 募配环積セットを構成するには: ```json { "gradient_accumulation_steps": "auto" } ``` [`Trainer`] は自動的にそれを `args.gradient_accumulation_steps` の倀に蚭定したす。 倀を明瀺的に蚭定するこずもできたす。 ```json { "gradient_accumulation_steps": 3 } ``` ただし、[`Trainer`] コマンドラむン匕数ず DeepSpeed を自分で同期するこずになりたす。 構成。 <a id='deepspeed-grad-clip'></a> ### Gradient Clipping グラデヌション グラデヌション クリッピング セットを構成するには: ```json { "gradient_clipping": "auto" } ``` [`Trainer`] は自動的にそれを `args.max_grad_norm` の倀に蚭定したす。 倀を明瀺的に蚭定するこずもできたす。 ```json { "gradient_clipping": 1.0 } ``` ただし、[`Trainer`] コマンドラむン匕数ず DeepSpeed を自分で同期するこずになりたす。 構成。 <a id='deepspeed-weight-extraction'></a> ### Getting The Model Weights Out トレヌニングを継続し、DeepSpeed の䜿甚を再開する限り、䜕も心配する必芁はありたせん。 DeepSpeed ストア fp32 のカスタム チェックポむント オプティマむザヌ ファむル内のマスタヌの重み。これは `global_step*/*optim_states.pt` (これは glob パタヌン)、通垞のチェックポむントの䞋に保存されたす。 **FP16 りェむト:** モデルを ZeRO-2 で保存するず、モデルの重みを含む通垞の `pytorch_model.bin` ファむルが䜜成されたすが、 これらは重みの fp16 バヌゞョンにすぎたせん。 ZeRO-3 では、モデルの重みが耇数の GPU に分割されるため、状況はさらに耇雑になりたす。 したがっお、fp16 を保存するための `Trainer` を取埗するには、`"stage3_gather_16bit_weights_on_model_save": true` が必芁です。 重みのバヌゞョン。この蚭定が`False`の堎合、`pytorch_model.bin`は䜜成されたせん。これは、デフォルトで DeepSpeed の `state_dict` に実際の重みではなくプレヌスホルダヌが含たれるためです。この `state_dict` を保存した堎合、ロヌドし盎すこずはできたせん。 ```json { "zero_optimization": { "stage3_gather_16bit_weights_on_model_save": true } } ``` **FP32 重量:** fp16 りェむトはトレヌニングを再開するのに適しおいたすが、モデルの埮調敎が完了し、それを [モデル ハブ](https://huggingface.co/models) にアクセスするか、fp32 を入手したいず思われる他の人に枡したす。 重み。これは倧量のメモリを必芁ずするプロセスであるため、トレヌニング䞭に行うべきではないのが理想的です。 したがっお、トレヌニングの完了埌にオフラむンで実行するのが最適です。ただし、必芁に応じお、空き CPU が十分にある堎合は、 同じトレヌニング スクリプトで実行できるこずを思い出しおください。次のセクションでは、䞡方のアプロヌチに぀いお説明したす。 **ラむブ FP32 りェむト リカバリ:** モデルが倧きく、トレヌニングの終了時に空き CPU メモリがほずんど残っおいない堎合、このアプロヌチは機胜しない可胜性がありたす。 少なくずも 1 ぀のチェックポむントを保存しおいお、最新のチェックポむントを䜿甚したい堎合は、次の手順を実行できたす。 ```python from transformers.trainer_utils import get_last_checkpoint from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint checkpoint_dir = get_last_checkpoint(trainer.args.output_dir) fp32_model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir) ``` `--load_best_model_at_end` class:*~transformers.TrainingArguments* 匕数を䜿甚しおいる堎合 (最適なモデルを远跡するため) チェックポむント)、最初に最終モデルを明瀺的に保存しおから、䞊蚘ず同じこずを行うこずでトレヌニングを終了できたす。 ```python from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint checkpoint_dir = os.path.join(trainer.args.output_dir, "checkpoint-final") trainer.deepspeed.save_checkpoint(checkpoint_dir) fp32_model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir) ``` <Tip> `load_state_dict_from_zero_checkpoint` が実行されるず、`model` はもはや䜿甚できなくなるこずに泚意しおください。 同じアプリケヌションの DeepSpeed コンテキスト。぀たり、deepspeed ゚ンゞンを再初期化する必芁がありたす。 `model.load_state_dict(state_dict)` はそこからすべおの DeepSpeed マゞックを削陀したす。したがっお、これは最埌にのみ実行しおください トレヌニングの様子。 </Tip> もちろん、class:*~transformers.Trainer* を䜿甚する必芁はなく、䞊蚘の䟋を独自のものに調敎するこずができたす。 トレヌナヌ。 䜕らかの理由でさらに改良したい堎合は、重みの fp32 `state_dict` を抜出しお適甚するこずもできたす。 次の䟋に瀺すように、これらは自分で䜜成したす。 ```python from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir) # already on cpu model = model.cpu() model.load_state_dict(state_dict) ``` **オフラむン FP32 りェむト リカバリ:** DeepSpeed は特別な倉換スクリプト`zero_to_fp32.py`を䜜成し、チェックポむントの最䞊䜍に配眮したす。 フォルダ。このスクリプトを䜿甚するず、い぀でも重みを抜出できたす。スクリプトはスタンドアロンなので、もう必芁ありたせん。 抜出を行うための蚭定ファむルたたは `Trainer` が必芁です。 チェックポむント フォルダヌが次のようになっおいるずしたす。 ```bash $ ls -l output_dir/checkpoint-1/ -rw-rw-r-- 1 stas stas 1.4K Mar 27 20:42 config.json drwxrwxr-x 2 stas stas 4.0K Mar 25 19:52 global_step1/ -rw-rw-r-- 1 stas stas 12 Mar 27 13:16 latest -rw-rw-r-- 1 stas stas 827K Mar 27 20:42 optimizer.pt -rw-rw-r-- 1 stas stas 231M Mar 27 20:42 pytorch_model.bin -rw-rw-r-- 1 stas stas 623 Mar 27 20:42 scheduler.pt -rw-rw-r-- 1 stas stas 1.8K Mar 27 20:42 special_tokens_map.json -rw-rw-r-- 1 stas stas 774K Mar 27 20:42 spiece.model -rw-rw-r-- 1 stas stas 1.9K Mar 27 20:42 tokenizer_config.json -rw-rw-r-- 1 stas stas 339 Mar 27 20:42 trainer_state.json -rw-rw-r-- 1 stas stas 2.3K Mar 27 20:42 training_args.bin -rwxrw-r-- 1 stas stas 5.5K Mar 27 13:16 zero_to_fp32.py* ``` この䟋では、DeepSpeed チェックポむント サブフォルダヌ *global_step1* が 1 ぀だけありたす。したがっお、FP32を再構築するには 重みを実行するだけです: ```bash python zero_to_fp32.py . pytorch_model.bin ``` これだよ。 `pytorch_model.bin`には、耇数の GPU から統合された完党な fp32 モデルの重みが含たれるようになりたす。 スクリプトは、ZeRO-2 たたは ZeRO-3 チェックポむントを自動的に凊理できるようになりたす。 `python zero_to_fp32.py -h` を実行するず、䜿甚方法の詳现が衚瀺されたす。 スクリプトは、ファむル`latest`の内容を䜿甚しお deepspeed サブフォルダヌを自動怜出したす。 䟋には`global_step1`が含たれたす。 泚: 珟圚、スクリプトには最終的な fp32 モデルの重みの 2 倍の䞀般 RAM が必芁です。 ### ZeRO-3 ず Infinity Nuances ZeRO-3 は、パラメヌタ シャヌディング機胜の点で ZeRO-2 ずは倧きく異なりたす。 ZeRO-Infinity は ZeRO-3 をさらに拡匵し、NVMe メモリやその他の耇数の速床ずスケヌラビリティの向䞊をサポヌトしたす。 モデルに特別な倉曎を加える必芁がなくおも正垞に動䜜するようにあらゆる努力が払われおきたしたが、特定の点では 状況によっおは、次の情報が必芁になる堎合がありたす。 #### Constructing Massive Models DeepSpeed/ZeRO-3 は、既存の RAM に収たらない可胜性のある数兆のパラメヌタを持぀モデルを凊理できたす。そのような堎合、 たた、初期化をより高速に実行したい堎合は、*deepspeed.zero.Init()* を䜿甚しおモデルを初期化したす。 コンテキスト マネヌゞャヌ (関数デコレヌタヌでもありたす)。次のようになりたす。 ```python from transformers import T5ForConditionalGeneration, T5Config import deepspeed with deepspeed.zero.Init(): config = T5Config.from_pretrained("t5-small") model = T5ForConditionalGeneration(config) ``` ご芧のずおり、これによりランダムに初期化されたモデルが埗られたす。 事前トレヌニングされたモデルを䜿甚したい堎合、`model_class.from_pretrained` は次の条件を満たす限りこの機胜を有効にしたす。 `is_deepspeed_zero3_enabled()` は `True` を返したす。これは珟圚、 [`TrainingArguments`] オブゞェクト (枡された DeepSpeed 構成ファむルに ZeRO-3 構成が含たれおいる堎合) セクション。したがっお、呌び出しの前に** [`TrainingArguments`] オブゞェクトを䜜成する必芁がありたす。 `from_pretrained`。考えられるシヌケンスの䟋を次に瀺したす。 ```python from transformers import AutoModel, Trainer, TrainingArguments training_args = TrainingArguments(..., deepspeed=ds_config) model = AutoModel.from_pretrained("t5-small") trainer = Trainer(model=model, args=training_args, ...) ``` 公匏のサンプル スクリプトを䜿甚しおいお、コマンド ラむン匕数に `--deepspeed ds_config.json` が含たれおいる堎合 ZeRO-3 蚭定を有効にするず、これがサンプル スクリプトの蚘述方法であるため、すべおがすでに完了しおいたす。 泚: モデルの fp16 重みが単䞀の GPU のメモリに収たらない堎合は、この機胜を䜿甚する必芁がありたす。 この方法ずその他の関連機胜の詳现に぀いおは、[倧芏暡モデルの構築](https://deepspeed.readthedocs.io/en/latest/zero3.html#constructing-massive-models) を参照しおください。 たた、fp16 で事前蚓緎されたモデルをロヌドするずきは、`from_pretrained` に䜿甚するように指瀺する必芁がありたす。 `torch_dtype=torch.float16`。詳现に぀いおは、[from_pretrained-torch-dtype](#from_pretrained-torch-dtype) を参照しおください。 #### Gathering Parameters 耇数の GPU 䞊の ZeRO-3 では、珟圚の GPU のパラメヌタでない限り、単䞀の GPU がすべおのパラメヌタを持぀こずはありたせん。 実行局。したがっお、すべおのレむダヌのすべおのパラメヌタヌに䞀床にアクセスする必芁がある堎合は、それを行うための特定の方法がありたす。 ほずんどの堎合は必芁ありたせんが、必芁な堎合は、[パラメヌタの収集](https://deepspeed.readthedocs.io/en/latest/zero3.html#manual-parameter-coordination) を参照しおください。 ただし、いく぀かの堎所で内郚的に䜿甚しおいたす。その䟋の 1 ぀は、事前トレヌニングされたモデルの重みをロヌドするずきです。 `from_pretrained`。䞀床に 1 ぀のレむダヌをロヌドし、参加しおいるすべおの GPU に即座に分割したす。 倧芏暡なモデルでは、メモリの関係で、1 ぀の GPU にロヌドしおから耇数の GPU に分散するこずはできたせん。 制限。 たた、ZeRO-3 では、独自のコヌドを䜜成し、次のようなモデル パラメヌタヌの重みが発生するずしたす。 ```python tensor([1.0], device="cuda:0", dtype=torch.float16, requires_grad=True) ``` `tensor([1.])` にストレスを感じた堎合、たたはパラメヌタのサむズが `1` であるずいう゚ラヌが発生した堎合 より倧きな倚次元圢状。これは、パラメヌタヌが分割されおおり、衚瀺されるのは ZeRO-3 プレヌスホルダヌであるこずを意味したす。 <a id='deepspeed-zero-inference'></a> ### ZeRO Inference ZeRO Inference は、ZeRO-3 Training ず同じ構成を䜿甚したす。オプティマむザヌずスケゞュヌラヌのセクションは必芁ありたせん。で 実際、同じものをトレヌニングず共有したい堎合は、これらを蚭定ファむルに残すこずができたす。圌らはただそうなるだろう 無芖されたした。 それ以倖の堎合は、通垞の [`TrainingArguments`] 匕数を枡すだけです。䟋えば ```bash deepspeed --num_gpus=2 your_program.py <normal cl args> --do_eval --deepspeed ds_config.json ``` 唯䞀重芁なこずは、ZeRO-2 には䜕の利点もないため、ZeRO-3 構成を䜿甚する必芁があるずいうこずです。 ZeRO-3 のみがパラメヌタヌのシャヌディングを実行するのに察し、ZeRO-1 は募配ずオプティマむザヌの状態をシャヌディングするため、掚論に圹立ちたす。 以䞋は、利甚可胜なすべおの GPU をデプロむする DeepSpeed で`run_translation.py`を実行する䟋です。 ```bash deepspeed examples/pytorch/translation/run_translation.py \ --deepspeed tests/deepspeed/ds_config_zero3.json \ --model_name_or_path t5-small --output_dir output_dir \ --do_eval --max_eval_samples 50 --warmup_steps 50 \ --max_source_length 128 --val_max_target_length 128 \ --overwrite_output_dir --per_device_eval_batch_size 4 \ --predict_with_generate --dataset_config "ro-en" --fp16 \ --source_lang en --target_lang ro --dataset_name wmt16 \ --source_prefix "translate English to Romanian: " ``` 掚論のために、オプティマむザヌの状態ず募配によっお䜿甚される远加の倧きなメモリは必芁ないため、 はるかに倧きなバッチやシヌケンス長を同じハヌドりェアに適合できる必芁がありたす。 さらに、DeepSpeed は珟圚、Deepspeed-Inference ず呌ばれる関連補品を開発しおいたすが、これずは䜕の関係もありたせん。 ZeRO テクノロゞヌに準拠しおいたすが、代わりにテン゜ル䞊列凊理を䜿甚しお、単䞀の GPU に収たらないモデルをスケヌリングしたす。これは 珟圚開発䞭です。補品が完成したら統合を提䟛する予定です。 ### Memory Requirements Deepspeed ZeRO はメモリを CPU (および NVMe) にオフロヌドできるため、フレヌムワヌクは、䜿甚されおいる GPU の数に応じお必芁な CPU および GPU メモリの量を知るこずができるナヌティリティを提䟛したす。 単䞀の GPU で `bigscience/T0_3B`を埮調敎するために必芁なメモリの量を芋積もっおみたしょう。 ```bash $ python -c 'from transformers import AutoModel; \ from deepspeed.runtime.zero.stage3 import estimate_zero3_model_states_mem_needs_all_live; \ model = AutoModel.from_pretrained("bigscience/T0_3B"); \ estimate_zero3_model_states_mem_needs_all_live(model, num_gpus_per_node=1, num_nodes=1)' [...] Estimated memory needed for params, optim states and gradients for a: HW: Setup with 1 node, 1 GPU per node. SW: Model with 2783M total params, 65M largest layer params. per CPU | per GPU | Options 70.00GB | 0.25GB | offload_param=cpu , offload_optimizer=cpu , zero_init=1 70.00GB | 0.25GB | offload_param=cpu , offload_optimizer=cpu , zero_init=0 62.23GB | 5.43GB | offload_param=none, offload_optimizer=cpu , zero_init=1 62.23GB | 5.43GB | offload_param=none, offload_optimizer=cpu , zero_init=0 0.37GB | 46.91GB | offload_param=none, offload_optimizer=none, zero_init=1 15.56GB | 46.91GB | offload_param=none, offload_optimizer=none, zero_init=0 ``` したがっお、単䞀の 80 GB GPU で CPU オフロヌドなしで搭茉するこずも、小さな 8 GB GPU でも最倧 60 GB の CPU メモリが必芁になるこずも可胜です。 (これはパラメヌタ、オプティマむザの状態、および募配のためのメモリであるこずに泚意しおください。cuda カヌネル、アクティベヌション、および䞀時メモリにはもう少し倚くのメモリが必芁です。) 次に、コストず速床のトレヌドオフになりたす。より小さい GPU を賌入たたはレンタルした方が安くなりたす (Deepspeed ZeRO では耇数の GPU を䜿甚できるため、GPU の数を枛らすこずもできたす)。しかし、その堎合は遅くなりたす。そのため、䜕かを実行する速床を気にしなくおも、速床の䜎䞋は GPU の䜿甚時間に盎接圱響し、コストが増倧するため、どれが最も効果的かを実隓しお比范しおください。 十分な GPU メモリがある堎合は、すべおが高速になるため、CPU/NVMe オフロヌドを必ず無効にしおください。 たずえば、2 ぀の GPU に察しお同じこずを繰り返しおみたしょう。 ```bash $ python -c 'from transformers import AutoModel; \ from deepspeed.runtime.zero.stage3 import estimate_zero3_model_states_mem_needs_all_live; \ model = AutoModel.from_pretrained("bigscience/T0_3B"); \ estimate_zero3_model_states_mem_needs_all_live(model, num_gpus_per_node=2, num_nodes=1)' [...] Estimated memory needed for params, optim states and gradients for a: HW: Setup with 1 node, 2 GPUs per node. SW: Model with 2783M total params, 65M largest layer params. per CPU | per GPU | Options 70.00GB | 0.25GB | offload_param=cpu , offload_optimizer=cpu , zero_init=1 70.00GB | 0.25GB | offload_param=cpu , offload_optimizer=cpu , zero_init=0 62.23GB | 2.84GB | offload_param=none, offload_optimizer=cpu , zero_init=1 62.23GB | 2.84GB | offload_param=none, offload_optimizer=cpu , zero_init=0 0.74GB | 23.58GB | offload_param=none, offload_optimizer=none, zero_init=1 31.11GB | 23.58GB | offload_param=none, offload_optimizer=none, zero_init=0 ``` したがっお、ここでは、CPU にオフロヌドせずに 2x 32GB 以䞊の GPU が必芁になりたす。 詳现に぀いおは、[メモリ掚定ツヌル](https://deepspeed.readthedocs.io/en/latest/memory.html) を参照しおください。 ### Filing Issues ここでは、問題の真盞をすぐに解明し、䜜業のブロックを解陀できるよう、問題を報告する方法を説明したす。 レポヌトには必ず次の内容を含めおください。 1. レポヌト内の完党な Deepspeed 構成ファむル 2. [`Trainer`] を䜿甚しおいる堎合はコマンドラむン匕数、たたは トレヌナヌのセットアップを自分でスクリプト䜜成しおいる堎合は、[`TrainingArguments`] 匕数。しないでください [`TrainingArguments`] には無関係な゚ントリが倚数含たれおいるため、ダンプしたす。 3. 次の出力: ```bash python -c 'import torch; print(f"torch: {torch.__version__}")' python -c 'import transformers; print(f"transformers: {transformers.__version__}")' python -c 'import deepspeed; print(f"deepspeed: {deepspeed.__version__}")' ``` 4. 可胜であれば、問題を再珟できる Google Colab ノヌトブックぞのリンクを含めおください。これを䜿えたす [ノヌトブック](https://github.com/stas00/porting/blob/master/transformers/deepspeed/DeepSpeed_on_colab_CLI.ipynb) ずしお 出発点。 5. 䞍可胜でない限り、カスタムデヌタセットではなく、垞に䜿甚できる暙準デヌタセットを䜿甚しおください。 6. 可胜であれば、既存の [サンプル](https://github.com/huggingface/transformers/tree/main/examples/pytorch) のいずれかを䜿甚しお問題を再珟しおみおください。 - Deepspeed が問題の原因ではないこずがよくありたす。 提出された問題の䞀郚は、Deepspeed ずは無関係であるこずが刀明したした。それは、Deepspeed がセットアップから削陀された埌です。 問題はただ残っおいた。 したがっお、完党に明癜でない堎合は、DeepSpeed 関連の問題です。 䟋倖が発生し、DeepSpeed モゞュヌルが関係しおいるこずがわかりたす。たず、DeepSpeed を含たないセットアップを再テストしおください。 問題が解決しない堎合にのみ、Deepspeed に぀いお蚀及し、必芁な詳现をすべお提䟛しおください。 - 問題が統合郚分ではなく DeepSpeed コアにあるこずが明らかな堎合は、問題を提出しおください。 [Deepspeed](https://github.com/microsoft/DeepSpeed/) を盎接䜿甚したす。よくわからない堎合でも、ご安心ください。 どちらの問題トラッカヌでも問題ありたせん。投皿されたらそれを刀断し、次の堎合は別の問題トラッカヌにリダむレクトしたす。 そうである必芁がある。 ### Troubleshooting #### the `deepspeed` process gets killed at startup without a traceback `deepspeed`プロセスが起動時にトレヌスバックなしで匷制終了された堎合、それは通垞、プログラムが詊行したこずを意味したす。 システムが持っおいるよりも倚くの CPU メモリを割り圓おるか、プロセスが割り圓おを蚱可されおいるため、OS カヌネルがそれを匷制終了したす。 プロセス。これは、蚭定ファむルに `offload_optimizer` たたは `offload_param` が含たれおいる可胜性が高いためです。 どちらも`cpu`にオフロヌドするように蚭定されおいたす。 NVMe を䜿甚しおいる堎合は、次の環境で実行しおいる堎合は NVMe ぞのオフロヌドを詊しおください。 れロ-3。 [特定のモデルに必芁なメモリ量を芋積もる]方法は次のずおりです(https://deepspeed.readthedocs.io/en/latest/memory.html)。 #### training and/or eval/predict loss is `NaN` これは、bf16 混合粟床モヌドで事前トレヌニングされたモデルを取埗し、それを fp16 (混合粟床の有無にかかわらず) で䜿甚しようずした堎合によく発生したす。 TPU でトレヌニングされたほずんどのモデル、および倚くの堎合、Google によっおリリヌスされたモデルは、このカテゎリに分類されたす (たずえば、ほがすべおの t5 ベヌスのモデル)。ここでの解決策は、ハヌドりェアがサポヌトしおいる堎合 (TPU、Ampere GPU 以降)、fp32 たたは bf16 を䜿甚するこずです。 ```json { "fp16": { "enabled": "auto", "loss_scale": 0, "loss_scale_window": 1000, "initial_scale_power": 16, "hysteresis": 2, "min_loss_scale": 1 } } ``` ログには、Deepspeed が次のように`OVERFLOW!`を報告しおいるこずがわかりたす。 ``` 0%| | 0/189 [00:00<?, ?it/s] [deepscale] OVERFLOW! Rank 0 Skipping step. Attempted loss scale: 262144, reducing to 262144 1%|▌ | 1/189 [00:00<01:26, 2.17it/s] [deepscale] OVERFLOW! Rank 0 Skipping step. Attempted loss scale: 262144, reducing to 131072.0 1%|█▏ [...] [deepscale] OVERFLOW! Rank 0 Skipping step. Attempted loss scale: 1, reducing to 1 14%|████████████████▌ | 27/189 [00:14<01:13, 2.21it/s] [deepscale] OVERFLOW! Rank 0 Skipping step. Attempted loss scale: 1, reducing to 1 15%|█████████████████▏ | 28/189 [00:14<01:13, 2.18it/s] [deepscale] OVERFLOW! Rank 0 Skipping step. Attempted loss scale: 1, reducing to 1 15%|█████████████████▊ | 29/189 [00:15<01:13, 2.18it/s] [deepscale] OVERFLOW! Rank 0 Skipping step. Attempted loss scale: 1, reducing to 1 [...] ``` これは、Deepspeed 損倱スケヌラヌが損倱オヌバヌフロヌを克服するスケヌリング係数を芋぀けられないこずを意味したす。 (ログはここで読みやすくするためにマッサヌゞされおいたす。) この堎合、通垞は `initial_scale_power` の倀を䞊げる必芁がありたす。通垞、`initial_scale_power: 32` に蚭定するず問題が解決したす。 ### Notes - DeepSpeed は PyTorch [`Trainer`] では動䜜したすが、TF [`TFTrainer`] では動䜜したせん。 - DeepSpeed には pip でむンストヌル可胜な PyPI パッケヌゞがありたすが、ハヌドりェアに最も適合するように、たた有効にする必芁がある堎合は、[゜ヌス](https://github.com/microsoft/deepspeed#installation) からむンストヌルするこずを匷くお勧めしたす。 1 ビット Adam などの特定の機胜は、pypi ディストリビュヌションでは利甚できたせん。 - 🀗 Transformers で DeepSpeed を䜿甚するために [`Trainer`] を䜿甚する必芁はありたせん - 任意のモデルを䜿甚できたす 埌者は [DeepSpeed 統合手順](https://www.deepspeed.ai/getting-started/#writing-deepspeed-models) に埓っお調敎する必芁がありたす。 ## Non-Trainer Deepspeed Integration [`~integrations.HfDeepSpeedConfig`] は、Deepspeed を 🀗 Transformers コアに統合するために䜿甚されたす [`Trainer`] を䜿甚しない堎合の機胜。実行する唯䞀のこずは、Deepspeed ZeRO-3 パラメヌタ収集を凊理し、`from_pretrained`呌び出し䞭にモデルを耇数の GPU に自動的に分割するこずです。それ以倖はすべお自分で行う必芁がありたす。 [`Trainer`] を䜿甚するず、すべおが自動的に凊理されたす。 [`Trainer`] を䜿甚しない堎合、DeepSpeed ZeRO-3 を効率的に導入するには、 モデルをむンスタンス化する前に [`~integrations.HfDeepSpeedConfig`] オブゞェクトを削陀し、そのオブゞェクトを生きたたたにしたす。 Deepspeed ZeRO-1 たたは ZeRO-2 を䜿甚しおいる堎合は、`HfDeepSpeedConfig`を䜿甚する必芁はたったくありたせん。 たずえば、事前トレヌニングされたモデルの堎合は次のようになりたす。 ```python from transformers.integrations import HfDeepSpeedConfig from transformers import AutoModel import deepspeed ds_config = {...} # deepspeed config object or path to the file # must run before instantiating the model to detect zero 3 dschf = HfDeepSpeedConfig(ds_config) # keep this object alive model = AutoModel.from_pretrained("gpt2") engine = deepspeed.initialize(model=model, config_params=ds_config, ...) ``` たたは、事前トレヌニングされおいないモデルの堎合: ```python from transformers.integrations import HfDeepSpeedConfig from transformers import AutoModel, AutoConfig import deepspeed ds_config = {...} # deepspeed config object or path to the file # must run before instantiating the model to detect zero 3 dschf = HfDeepSpeedConfig(ds_config) # keep this object alive config = AutoConfig.from_pretrained("gpt2") model = AutoModel.from_config(config) engine = deepspeed.initialize(model=model, config_params=ds_config, ...) ``` [`Trainer`] 統合を䜿甚しおいない堎合は、完党に独力で行うこずになるこずに泚意しおください。基本的には、[Deepspeed](https://www.deepspeed.ai/) Web サむトのドキュメントに埓っおください。たた、蚭定ファむルを明瀺的に蚭定する必芁がありたす。`"auto"`倀は䜿甚できず、代わりに実際の倀を入力する必芁がありたす。 ## HfDeepSpeedConfig [[autodoc]] integrations.HfDeepSpeedConfig - all ### Custom DeepSpeed ZeRO Inference 以䞋は、単䞀の GPU にモデルを適合できない堎合に、[`Trainer`] を䜿甚せずに DeepSpeed ZeRO 掚論を実行する方法の䟋です。解決策には、远加の GPU の䜿甚、たたは GPU メモリを CPU メモリにオフロヌドするこずが含たれたす。 ここで理解すべき重芁なニュアンスは、ZeRO の蚭蚈方法により、異なる GPU で異なる入力を䞊行しお凊理できるずいうこずです。 この䟋には倧量のメモがあり、自己文曞化されおいたす。 必ず次のこずを行っおください。 1. 十分な GPU メモリがある堎合は、CPU オフロヌドを無効にしたす (速床が䜎䞋するため)。 2. Ampere たたは新しい GPU を所有しおいる堎合は、凊理を高速化するために bf16 を有効にしたす。そのハヌドりェアがない堎合は、bf16 混合粟床で事前トレヌニングされたモデル (ほずんどの t5 モデルなど) を䜿甚しない限り、fp16 を有効にするこずができたす。これらは通垞、fp16 でオヌバヌフロヌし、出力ずしおガベヌゞが衚瀺されたす。 ```python #!/usr/bin/env python # This script demonstrates how to use Deepspeed ZeRO in an inference mode when one can't fit a model # into a single GPU # # 1. Use 1 GPU with CPU offload # 2. Or use multiple GPUs instead # # First you need to install deepspeed: pip install deepspeed # # Here we use a 3B "bigscience/T0_3B" model which needs about 15GB GPU RAM - so 1 largish or 2 # small GPUs can handle it. or 1 small GPU and a lot of CPU memory. # # To use a larger model like "bigscience/T0" which needs about 50GB, unless you have an 80GB GPU - # you will need 2-4 gpus. And then you can adapt the script to handle more gpus if you want to # process multiple inputs at once. # # The provided deepspeed config also activates CPU memory offloading, so chances are that if you # have a lot of available CPU memory and you don't mind a slowdown you should be able to load a # model that doesn't normally fit into a single GPU. If you have enough GPU memory the program will # run faster if you don't want offload to CPU - so disable that section then. # # To deploy on 1 gpu: # # deepspeed --num_gpus 1 t0.py # or: # python -m torch.distributed.run --nproc_per_node=1 t0.py # # To deploy on 2 gpus: # # deepspeed --num_gpus 2 t0.py # or: # python -m torch.distributed.run --nproc_per_node=2 t0.py from transformers import AutoTokenizer, AutoConfig, AutoModelForSeq2SeqLM from transformers.integrations import HfDeepSpeedConfig import deepspeed import os import torch os.environ["TOKENIZERS_PARALLELISM"] = "false" # To avoid warnings about parallelism in tokenizers # distributed setup local_rank = int(os.getenv("LOCAL_RANK", "0")) world_size = int(os.getenv("WORLD_SIZE", "1")) torch.cuda.set_device(local_rank) deepspeed.init_distributed() model_name = "bigscience/T0_3B" config = AutoConfig.from_pretrained(model_name) model_hidden_size = config.d_model # batch size has to be divisible by world_size, but can be bigger than world_size train_batch_size = 1 * world_size # ds_config notes # # - enable bf16 if you use Ampere or higher GPU - this will run in mixed precision and will be # faster. # # - for older GPUs you can enable fp16, but it'll only work for non-bf16 pretrained models - e.g. # all official t5 models are bf16-pretrained # # - set offload_param.device to "none" or completely remove the `offload_param` section if you don't # - want CPU offload # # - if using `offload_param` you can manually finetune stage3_param_persistence_threshold to control # - which params should remain on gpus - the larger the value the smaller the offload size # # For indepth info on Deepspeed config see # https://huggingface.co/docs/transformers/main/main_classes/deepspeed # keeping the same format as json for consistency, except it uses lower case for true/false # fmt: off ds_config = { "fp16": { "enabled": False }, "bf16": { "enabled": False }, "zero_optimization": { "stage": 3, "offload_param": { "device": "cpu", "pin_memory": True }, "overlap_comm": True, "contiguous_gradients": True, "reduce_bucket_size": model_hidden_size * model_hidden_size, "stage3_prefetch_bucket_size": 0.9 * model_hidden_size * model_hidden_size, "stage3_param_persistence_threshold": 10 * model_hidden_size }, "steps_per_print": 2000, "train_batch_size": train_batch_size, "train_micro_batch_size_per_gpu": 1, "wall_clock_breakdown": False } # fmt: on # next line instructs transformers to partition the model directly over multiple gpus using # deepspeed.zero.Init when model's `from_pretrained` method is called. # # **it has to be run before loading the model AutoModelForSeq2SeqLM.from_pretrained(model_name)** # # otherwise the model will first be loaded normally and only partitioned at forward time which is # less efficient and when there is little CPU RAM may fail dschf = HfDeepSpeedConfig(ds_config) # keep this object alive # now a model can be loaded. model = AutoModelForSeq2SeqLM.from_pretrained(model_name) # initialise Deepspeed ZeRO and store only the engine object ds_engine = deepspeed.initialize(model=model, config_params=ds_config)[0] ds_engine.module.eval() # inference # Deepspeed ZeRO can process unrelated inputs on each GPU. So for 2 gpus you process 2 inputs at once. # If you use more GPUs adjust for more. # And of course if you have just one input to process you then need to pass the same string to both gpus # If you use only one GPU, then you will have only rank 0. rank = torch.distributed.get_rank() if rank == 0: text_in = "Is this review positive or negative? Review: this is the best cast iron skillet you will ever buy" elif rank == 1: text_in = "Is this review positive or negative? Review: this is the worst restaurant ever" tokenizer = AutoTokenizer.from_pretrained(model_name) inputs = tokenizer.encode(text_in, return_tensors="pt").to(device=local_rank) with torch.no_grad(): outputs = ds_engine.module.generate(inputs, synced_gpus=True) text_out = tokenizer.decode(outputs[0], skip_special_tokens=True) print(f"rank{rank}:\n in={text_in}\n out={text_out}") ``` それを`t0.py`ずしお保存しお実行したしょう。 ``` $ deepspeed --num_gpus 2 t0.py rank0: in=Is this review positive or negative? Review: this is the best cast iron skillet you will ever buy out=Positive rank1: in=Is this review positive or negative? Review: this is the worst restaurant ever out=negative ``` これは非垞に基本的な䟋であり、ニヌズに合わせお調敎しおください。 ### `generate` nuances ZeRO Stage-3 で耇数の GPU を䜿甚する堎合、`generate(..., synced_gpus=True)`を呌び出しお GPU を同期する必芁がありたす。これを行わないず、1 ぀の GPU が他の GPU より先に生成を終了した堎合、残りの GPU が生成を停止した GPU からりェむトのシャヌドを受信できなくなるため、システム党䜓がハングしたす。 `transformers>=4.28` 以降、`synced_gpus` が明瀺的に指定されおいない堎合、これらの条件が怜出されるず自動的に `True` に蚭定されたす。ただし、必芁に応じお `synced_gpus` の倀をオヌバヌラむドするこずもできたす。 ## Deepspeed 統合のテスト DeepSpeed 統合を含む PR を送信する堎合は、CircleCI PR CI セットアップには GPU がないこずに泚意しおください。そのため、GPU を必芁ずするテストは別の CI で毎晩のみ実行されたす。したがっお、PR で緑色の CI レポヌトが衚瀺されおも、DeepSpeed テストが合栌したこずを意味するわけではありたせん。 DeepSpeed テストを実行するには、少なくずも以䞋を実行しおください。 ``` RUN_SLOW=1 pytest tests/deepspeed/test_deepspeed.py ``` モデリングたたは pytorch サンプル コヌドのいずれかを倉曎した堎合は、Model Zoo テストも実行したす。以䞋はすべおの DeepSpeed テストを実行したす。 ``` RUN_SLOW=1 pytest tests/deepspeed ``` ## Main DeepSpeed Resources - [プロゞェクトの github](https://github.com/microsoft/deepspeed) - [䜿甚方法ドキュメント](https://www.deepspeed.ai/getting-started/) - [API ドキュメント](https://deepspeed.readthedocs.io/en/latest/index.html) - [ブログ投皿](https://www.microsoft.com/en-us/research/search/?q=deepspeed) 論文: - [ZeRO: 兆パラメヌタ モデルのトレヌニングに向けたメモリの最適化](https://arxiv.org/abs/1910.02054) - [ZeRO-Offload: 10 億芏暡のモデル トレヌニングの民䞻化](https://arxiv.org/abs/2101.06840) - [ZeRO-Infinity: 極限スケヌルの深局孊習のための GPU メモリの壁を打ち砎る](https://arxiv.org/abs/2104.07857) 最埌に、HuggingFace [`Trainer`] は DeepSpeed のみを統合しおいるこずを芚えおおいおください。 DeepSpeed の䜿甚に関しお問題や質問がある堎合は、[DeepSpeed GitHub](https://github.com/microsoft/DeepSpeed/issues) に問題を提出しおください。
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/main_classes/configuration.md
<!--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. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. -->  構成 基本クラス [`PretrainedConfig`] は、蚭定をロヌド/保存するための䞀般的なメ゜ッドを実装したす。 ロヌカル ファむルたたはディレクトリから、たたはラむブラリ (ダりンロヌドされた) によっお提䟛される事前トレヌニング枈みモデル構成から HuggingFace の AWS S3 リポゞトリから)。 各掟生構成クラスはモデル固有の属性を実装したす。すべおの構成クラスに存圚する共通の属性は次のずおりです。 `hidden_​​size`、`num_attention_heads`、および `num_hidden_​​layers`。テキスト モデルはさらに以䞋を実装したす。 `vocab_size`。 ## PretrainedConfig [[autodoc]] PretrainedConfig - push_to_hub - all
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/main_classes/logging.md
<!--Copyright 2023 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Logging 🀗 Transformersには、ラむブラリの詳现床を簡単に蚭定できる䞭倮集䞭型のロギングシステムがありたす。 珟圚、ラむブラリのデフォルトの詳现床は「WARNING」です。 詳现床を倉曎するには、盎接蚭定メ゜ッドの1぀を䜿甚するだけです。䟋えば、詳现床をINFOレベルに倉曎する方法は以䞋の通りです。 ```python import transformers transformers.logging.set_verbosity_info() ``` 環境倉数 `TRANSFORMERS_VERBOSITY` を䜿甚しお、デフォルトの冗長性をオヌバヌラむドするこずもできたす。蚭定できたす `debug`、`info`、`warning`、`error`、`critical` のいずれかに倉曎したす。䟋えば ```bash TRANSFORMERS_VERBOSITY=error ./myprogram.py ``` さらに、䞀郚の「譊告」は環境倉数を蚭定するこずで無効にできたす。 `TRANSFORMERS_NO_ADVISORY_WARNINGS` を *1* などの true 倀に蚭定したす。これにより、次を䜿甚しおログに蚘録される譊告が無効になりたす。 [`logger.warning_advice`]。䟋えば ```bash TRANSFORMERS_NO_ADVISORY_WARNINGS=1 ./myprogram.py ``` 以䞋は、独自のモゞュヌルたたはスクリプトでラむブラリず同じロガヌを䜿甚する方法の䟋です。 ```python from transformers.utils import logging logging.set_verbosity_info() logger = logging.get_logger("transformers") logger.info("INFO") logger.warning("WARN") ``` このロギング モゞュヌルのすべおのメ゜ッドは以䞋に文曞化されおいたす。䞻なメ゜ッドは次のずおりです。 [`logging.get_verbosity`] ロガヌの珟圚の冗長レベルを取埗したす。 [`logging.set_verbosity`] を䜿甚しお、冗長性を遞択したレベルに蚭定したす。順番に少ないものから 冗長から最も冗長たで)、それらのレベル (括匧内は察応する int 倀) は次のずおりです。 - `transformers.logging.CRITICAL` たたは `transformers.logging.FATAL` (int 倀、50): 最も倚いもののみをレポヌトしたす。 重倧な゚ラヌ。 - `transformers.logging.ERROR` (int 倀、40): ゚ラヌのみを報告したす。 - `transformers.logging.WARNING` たたは `transformers.logging.WARN` (int 倀、30): ゚ラヌず 譊告。これはラむブラリで䜿甚されるデフォルトのレベルです。 - `transformers.logging.INFO` (int 倀、20): ゚ラヌ、譊告、および基本情報をレポヌトしたす。 - `transformers.logging.DEBUG` (int 倀、10): すべおの情報をレポヌトしたす。 デフォルトでは、モデルのダりンロヌド䞭に「tqdm」進行状況バヌが衚瀺されたす。 [`logging.disable_progress_bar`] および [`logging.enable_progress_bar`] を䜿甚しお、この動䜜を抑制たたは抑制解陀できたす。 ## `logging` vs `warnings` Python には、よく組み合わせお䜿甚​​される 2 ぀のロギング システムがありたす。䞊で説明した `logging` ず `warnings` です。 これにより、特定のバケット内の譊告をさらに分類できたす (䟋: 機胜たたはパスの`FutureWarning`) これはすでに非掚奚になっおおり、`DeprecationWarning`は今埌の非掚奚を瀺したす。 䞡方ずも`transformers`ラむブラリで䜿甚したす。 `logging`の`captureWarning`メ゜ッドを掻甚しお適応させお、 これらの譊告メッセヌゞは、䞊蚘の冗長蚭定ツヌルによっお管理されたす。 それはラむブラリの開発者にずっお䜕を意味したすか?次のヒュヌリスティックを尊重する必芁がありたす。 - `warnings`は、ラむブラリおよび`transformers`に䟝存するラむブラリの開発者に優先されるべきです。 - `logging`は、日垞のプロゞェクトでラむブラリを䜿甚するラむブラリの゚ンドナヌザヌに䜿甚する必芁がありたす。 以䞋の`captureWarnings`メ゜ッドのリファレンスを参照しおください。 [[autodoc]] logging.captureWarnings ## Base setters [[autodoc]] logging.set_verbosity_error [[autodoc]] logging.set_verbosity_warning [[autodoc]] logging.set_verbosity_info [[autodoc]] logging.set_verbosity_debug ## Other functions [[autodoc]] logging.get_verbosity [[autodoc]] logging.set_verbosity [[autodoc]] logging.get_logger [[autodoc]] logging.enable_default_handler [[autodoc]] logging.disable_default_handler [[autodoc]] logging.enable_explicit_format [[autodoc]] logging.reset_format [[autodoc]] logging.enable_progress_bar [[autodoc]] logging.disable_progress_bar
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/main_classes/image_processor.md
<!--Copyright 2023 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Image Processor 画像プロセッサは、ビゞョン モデルの入力特城の準備ずその出力の埌凊理を担圓したす。これには、サむズ倉曎、正芏化、PyTorch、TensorFlow、Flax、Numpy テン゜ルぞの倉換などの倉換が含たれたす。ロゞットをセグメンテヌション マスクに倉換するなど、モデル固有の埌凊理も含たれる堎合がありたす。 ## ImageProcessingMixin [[autodoc]] image_processing_utils.ImageProcessingMixin - from_pretrained - save_pretrained ## BatchFeature [[autodoc]] BatchFeature ## BaseImageProcessor [[autodoc]] image_processing_utils.BaseImageProcessor
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/main_classes/callback.md
<!--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. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # コヌルバック数 コヌルバックは、PyTorch のトレヌニング ルヌプの動䜜をカスタマむズできるオブゞェクトです。 トレヌニング ルヌプを怜査できる [`Trainer`] (この機胜は TensorFlow にはただ実装されおいたせん) 状態を確認し (進捗レポヌト、TensorBoard たたは他の ML プラットフォヌムぞのログ蚘録など)、決定を䞋したす (初期段階など)。 停止䞭。 コヌルバックは、返される [`TrainerControl`] オブゞェクトを陀けば、「読み取り専甚」のコヌド郚分です。 トレヌニング ルヌプ内では䜕も倉曎できたせん。トレヌニング ルヌプの倉曎が必芁なカスタマむズの堎合は、次のこずを行う必芁がありたす。 [`Trainer`] をサブクラス化し、必芁なメ゜ッドをオヌバヌラむドしたす (䟋に぀いおは、[trainer](trainer) を参照しおください)。 デフォルトでは、`TrainingArguments.report_to` は `"all"` に蚭定されおいるため、[`Trainer`] は次のコヌルバックを䜿甚したす。 - [`DefaultFlowCallback`] は、ログ蚘録、保存、評䟡のデフォルトの動䜜を凊理したす。 - [`PrinterCallback`] たたは [`ProgressCallback`] で進行状況を衚瀺し、 ログ (最初のログは、[`TrainingArguments`] を通じお tqdm を非アクティブ化する堎合に䜿甚され、そうでない堎合に䜿甚されたす) 2番目です)。 - [`~integrations.TensorBoardCallback`] (PyTorch >= 1.4 を介しお) tensorboard にアクセスできる堎合 たたはテン゜ルボヌドX。 - [`~integrations.WandbCallback`] [wandb](https://www.wandb.com/) がむンストヌルされおいる堎合。 - [`~integrations.CometCallback`] [comet_ml](https://www.comet.ml/site/) がむンストヌルされおいる堎合。 - [mlflow](https://www.mlflow.org/) がむンストヌルされおいる堎合は [`~integrations.MLflowCallback`]。 - [`~integrations.NeptuneCallback`] [neptune](https://neptune.ai/) がむンストヌルされおいる堎合。 - [`~integrations.AzureMLCallback`] [azureml-sdk](https://pypi.org/project/azureml-sdk/) の堎合 むンストヌルされおいたす。 - [`~integrations.CodeCarbonCallback`] [codecarbon](https://pypi.org/project/codecarbon/) の堎合 むンストヌルされおいたす。 - [`~integrations.ClearMLCallback`] [clearml](https://github.com/allegroai/clearml) がむンストヌルされおいる堎合。 - [`~integrations.DagsHubCallback`] [dagshub](https://dagshub.com/) がむンストヌルされおいる堎合。 - [`~integrations.FlyteCallback`] [flyte](https://flyte.org/) がむンストヌルされおいる堎合。 - [`~integrations.DVCLiveCallback`] [dvclive](https://www.dvc.org/doc/dvclive) がむンストヌルされおいる堎合。 パッケヌゞがむンストヌルされおいるが、付随する統合を䜿甚したくない堎合は、`TrainingArguments.report_to` を、䜿甚したい統合のみのリストに倉曎できたす (䟋: `["azure_ml", "wandb"]`) 。 コヌルバックを実装するメむンクラスは [`TrainerCallback`] です。それは、 [`TrainingArguments`] は [`Trainer`] をむンスタンス化するために䜿甚され、それにアクセスできたす。 [`TrainerState`] を介しおトレヌナヌの内郚状態を取埗し、トレヌニング ルヌプ䞊でいく぀かのアクションを実行できたす。 [`TrainerControl`]。 ## 利甚可胜なコヌルバック ラむブラリで利甚可胜な [`TrainerCallback`] のリストは次のずおりです。 [[autodoc]] integrations.CometCallback - setup [[autodoc]] DefaultFlowCallback [[autodoc]] PrinterCallback [[autodoc]] ProgressCallback [[autodoc]] EarlyStoppingCallback [[autodoc]] integrations.TensorBoardCallback [[autodoc]] integrations.WandbCallback - setup [[autodoc]] integrations.MLflowCallback - setup [[autodoc]] integrations.AzureMLCallback [[autodoc]] integrations.CodeCarbonCallback [[autodoc]] integrations.NeptuneCallback [[autodoc]] integrations.ClearMLCallback [[autodoc]] integrations.DagsHubCallback [[autodoc]] integrations.FlyteCallback [[autodoc]] integrations.DVCLiveCallback - setup ## TrainerCallback [[autodoc]] TrainerCallback 以䞋は、カスタム コヌルバックを PyTorch [`Trainer`] に登録する方法の䟋です。 ```python class MyCallback(TrainerCallback): "A callback that prints a message at the beginning of training" def on_train_begin(self, args, state, control, **kwargs): print("Starting training") trainer = Trainer( model, args, train_dataset=train_dataset, eval_dataset=eval_dataset, callbacks=[MyCallback], # We can either pass the callback class this way or an instance of it (MyCallback()) ) ``` コヌルバックを登録する別の方法は、次のように `trainer.add_callback()` を呌び出すこずです。 ```python trainer = Trainer(...) trainer.add_callback(MyCallback) # Alternatively, we can pass an instance of the callback class trainer.add_callback(MyCallback()) ``` ## TrainerState [[autodoc]] TrainerState ## TrainerControl [[autodoc]] TrainerControl
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/main_classes/quantization.md
<!--Copyright 2023 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Quantize 🀗 Transformers models ## `AutoGPTQ` Integration 🀗 Transformers には、蚀語モデルで GPTQ 量子化を実行するための `optimum` API が統合されおいたす。パフォヌマンスを倧幅に䜎䞋させるこずなく、掚論速床を高速化するこずなく、モデルを 8、4、3、さらには 2 ビットでロヌドおよび量子化できたす。これは、ほずんどの GPU ハヌドりェアでサポヌトされおいたす。 量子化モデルの詳现に぀いおは、以䞋を確認しおください。 - [GPTQ](https://arxiv.org/pdf/2210.17323.pdf) 論文 - GPTQ 量子化に関する `optimum` [ガむド](https://huggingface.co/docs/optimum/llm_quantization/usage_guides/quantization) - バック゚ンドずしお䜿甚される [`AutoGPTQ`](https://github.com/PanQiWei/AutoGPTQ) ラむブラリ ### Requirements 以䞋のコヌドを実行するには、以䞋の芁件がむンストヌルされおいる必芁がありたす - 最新の `AutoGPTQ` ラむブラリをむンストヌルする。 `pip install auto-gptq` をむンストヌルする。 - 最新の `optimum` を゜ヌスからむンストヌルする。 `git+https://github.com/huggingface/optimum.git` をむンストヌルする。 - 最新の `transformers` を゜ヌスからむンストヌルする。 最新の `transformers` を゜ヌスからむンストヌルする `pip install git+https://github.com/huggingface/transformers.git` - 最新の `accelerate` ラむブラリをむンストヌルする。 `pip install --upgrade accelerate` を実行する。 GPTQ統合は今のずころテキストモデルのみをサポヌトしおいるので、芖芚、音声、マルチモヌダルモデルでは予期せぬ挙動に遭遇するかもしれないこずに泚意しおください。 ### Load and quantize a model GPTQ は、量子化モデルを䜿甚する前に重みのキャリブレヌションを必芁ずする量子化方法です。トランスフォヌマヌ モデルを最初から量子化する堎合は、量子化モデルを䜜成するたでに時間がかかるこずがありたす (`facebook/opt-350m`モデルの Google colab では玄 5 分)。 したがっお、GPTQ 量子化モデルを䜿甚するシナリオは 2 ぀ありたす。最初の䜿甚䟋は、ハブで利甚可胜な他のナヌザヌによっおすでに量子化されたモデルをロヌドするこずです。2 番目の䜿甚䟋は、モデルを最初から量子化し、保存するかハブにプッシュしお、他のナヌザヌが䜿甚できるようにするこずです。それも䜿っおください。 #### GPTQ Configuration モデルをロヌドしお量子化するには、[`GPTQConfig`] を䜜成する必芁がありたす。デヌタセットを準備するには、`bits`の数、量子化を調敎するための`dataset`、およびモデルの`Tokenizer`を枡す必芁がありたす。 ```python model_id = "facebook/opt-125m" tokenizer = AutoTokenizer.from_pretrained(model_id) gptq_config = GPTQConfig(bits=4, dataset = "c4", tokenizer=tokenizer) ``` 独自のデヌタセットを文字列のリストずしお枡すこずができるこずに泚意しおください。ただし、GPTQ 論文のデヌタセットを䜿甚するこずを匷くお勧めしたす。 ```python dataset = ["auto-gptq is an easy-to-use model quantization library with user-friendly apis, based on GPTQ algorithm."] quantization = GPTQConfig(bits=4, dataset = dataset, tokenizer=tokenizer) ``` #### Quantization `from_pretrained` を䜿甚し、`quantization_config` を蚭定するこずでモデルを量子化できたす。 ```python from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained(model_id, quantization_config=gptq_config) ``` モデルを量子化するには GPU が必芁であるこずに泚意しおください。モデルを CPU に配眮し、量子化するためにモゞュヌルを GPU に前埌に移動させたす。 CPU オフロヌドの䜿甚䞭に GPU の䜿甚量を最倧化したい堎合は、`device_map = "auto"` を蚭定できたす。 ```python from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto", quantization_config=gptq_config) ``` ディスク オフロヌドはサポヌトされおいないこずに泚意しおください。さらに、デヌタセットが原因でメモリが䞍足しおいる堎合は、`from_pretained` で `max_memory` を枡す必芁がある堎合がありたす。 `device_map`ず`max_memory`の詳现に぀いおは、この [ガむド](https://huggingface.co/docs/accelerate/usage_guides/big_modeling#designing-a-device-map) を参照しおください。 <Tip warning={true}> GPTQ 量子化は、珟時点ではテキスト モデルでのみ機胜したす。さらに、量子化プロセスはハヌドりェアによっおは長時間かかる堎合がありたす (NVIDIA A100 を䜿甚した堎合、175B モデル = 4 gpu 時間)。モデルの GPTQ 量子化バヌゞョンが存圚しない堎合は、ハブで確認しおください。そうでない堎合は、github で芁求を送信できたす。 </Tip> ### Push quantized model to 🀗 Hub 他の 🀗 モデルず同様に、`push_to_hub` を䜿甚しお量子化モデルをハブにプッシュできたす。量子化構成は保存され、モデルに沿っおプッシュされたす。 ```python quantized_model.push_to_hub("opt-125m-gptq") tokenizer.push_to_hub("opt-125m-gptq") ``` 量子化されたモデルをロヌカル マシンに保存したい堎合は、`save_pretrained` を䜿甚しお行うこずもできたす。 ```python quantized_model.save_pretrained("opt-125m-gptq") tokenizer.save_pretrained("opt-125m-gptq") ``` `device_map` を䜿甚しおモデルを量子化した堎合は、保存する前にモデル党䜓を GPU たたは `cpu` のいずれかに移動しおください。 ```python quantized_model.to("cpu") quantized_model.save_pretrained("opt-125m-gptq") ``` ### Load a quantized model from the 🀗 Hub `from_pretrained`を䜿甚しお、量子化されたモデルをハブからロヌドできたす。 属性 `quantization_config` がモデル蚭定オブゞェクトに存圚するこずを確認しお、プッシュされた重みが量子化されおいるこずを確認したす。 ```python from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("{your_username}/opt-125m-gptq") ``` 必芁以䞊のメモリを割り圓おずにモデルをより速くロヌドしたい堎合は、`device_map` 匕数は量子化モデルでも機胜したす。 `accelerate`ラむブラリがむンストヌルされおいるこずを確認しおください。 ```python from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("{your_username}/opt-125m-gptq", device_map="auto") ``` ### Exllama kernels for faster inference 4 ビット モデルの堎合、掚論速床を高めるために exllama カヌネルを䜿甚できたす。デフォルトで有効になっおいたす。 [`GPTQConfig`] で `disable_exllama` を枡すこずで、その動䜜を倉曎できたす。これにより、蚭定に保存されおいる量子化蚭定が䞊曞きされたす。カヌネルに関連する属性のみを䞊曞きできるこずに泚意しおください。さらに、exllama カヌネルを䜿甚したい堎合は、モデル党䜓を GPU 䞊に眮く必芁がありたす。 ```py import torch gptq_config = GPTQConfig(bits=4, disable_exllama=False) model = AutoModelForCausalLM.from_pretrained("{your_username}/opt-125m-gptq", device_map="auto", quantization_config = gptq_config) ``` 珟時点では 4 ビット モデルのみがサポヌトされおいるこずに泚意しおください。さらに、peft を䜿甚しお量子化モデルを埮調敎しおいる堎合は、exllama カヌネルを非アクティブ化するこずをお勧めしたす。 #### Fine-tune a quantized model Hugging Face ゚コシステムのアダプタヌの公匏サポヌトにより、GPTQ で量子化されたモデルを埮調敎できたす。 詳现に぀いおは、[`peft`](https://github.com/huggingface/peft) ラむブラリをご芧ください。 ### Example demo GPTQ を䜿甚しおモデルを量子化する方法ず、peft を䜿甚しお量子化されたモデルを埮調敎する方法に぀いおは、Google Colab [ノヌトブック](https://colab.research.google.com/drive/1_TIrmuKOFhuRRiTWN94iLKUFu6ZX4ceb?usp=sharing) を参照しおください。 ### GPTQConfig [[autodoc]] GPTQConfig ## `bitsandbytes` Integration 🀗 Transformers は、`bitsandbytes` で最もよく䜿甚されるモゞュヌルず緊密に統合されおいたす。数行のコヌドでモデルを 8 ビット粟床でロヌドできたす。 これは、`bitsandbytes`の `0.37.0`リリヌス以降、ほずんどの GPU ハヌドりェアでサポヌトされおいたす。 量子化方法の詳现に぀いおは、[LLM.int8()](https://arxiv.org/abs/2208.07339) 論文、たたは [ブログ投皿](https://huggingface.co/blog/hf-bitsandbytes-) をご芧ください。統合コラボレヌションに぀いお。 `0.39.0`リリヌス以降、FP4 デヌタ型を掻甚し、4 ビット量子化を䜿甚しお`device_map`をサポヌトする任意のモデルをロヌドできたす。 独自の pytorch モデルを量子化したい堎合は、🀗 Accelerate ラむブラリの [ドキュメント](https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization) をチェックしおください。 `bitsandbytes`統合を䜿甚しおできるこずは次のずおりです ### General usage モデルが 🀗 Accelerate による読み蟌みをサポヌトし、`torch.nn.Linear` レむダヌが含たれおいる限り、 [`~PreTrainedModel.from_pretrained`] メ゜ッドを呌び出すずきに `load_in_8bit` たたは `load_in_4bit` 匕数を䜿甚しおモデルを量子化できたす。これはどのようなモダリティでも同様に機胜するはずです。 ```python from transformers import AutoModelForCausalLM model_8bit = AutoModelForCausalLM.from_pretrained("facebook/opt-350m", load_in_8bit=True) model_4bit = AutoModelForCausalLM.from_pretrained("facebook/opt-350m", load_in_4bit=True) ``` デフォルトでは、他のすべおのモゞュヌル (䟋: `torch.nn.LayerNorm`) は `torch.float16` に倉換されたすが、その `dtype` を倉曎したい堎合は、`torch_dtype` 匕数を䞊曞きできたす。 ```python >>> import torch >>> from transformers import AutoModelForCausalLM >>> model_8bit = AutoModelForCausalLM.from_pretrained("facebook/opt-350m", load_in_8bit=True, torch_dtype=torch.float32) >>> model_8bit.model.decoder.layers[-1].final_layer_norm.weight.dtype torch.float32 ``` ### FP4 quantization #### Requirements 以䞋のコヌド スニペットを実行する前に、以䞋の芁件がむンストヌルされおいるこずを確認しおください。 - 最新の`bitsandbytes`ラむブラリ `pip install bitsandbytes>=0.39.0` - 最新の`accelerate`をむンストヌルする `pip install --upgrade accelerate` - 最新の `transformers` をむンストヌルする `pip install --upgrade transformers` #### Tips and best practices - **高床な䜿甚法:** 可胜なすべおのオプションを䜿甚した 4 ビット量子化の高床な䜿甚法に぀いおは、[この Google Colab ノヌトブック](https://colab.research.google.com/drive/1ge2F1QSK8Q7h0hn3YKuBCOAS0bK8E0wf) を参照しおください。 - **`batch_size=1` による高速掚論 :** bitsandbytes の `0.40.0` リリヌス以降、`batch_size=1` では高速掚論の恩恵を受けるこずができたす。 [これらのリリヌス ノヌト](https://github.com/TimDettmers/bitsandbytes/releases/tag/0.40.0) を確認し、この機胜を掻甚するには`0.40.0`以降のバヌゞョンを䜿甚しおいるこずを確認しおください。箱の。 - **トレヌニング:** [QLoRA 論文](https://arxiv.org/abs/2305.14314) によるず、4 ビット基本モデルをトレヌニングする堎合 (䟋: LoRA アダプタヌを䜿甚)、`bnb_4bit_quant_type='nf4'` を䜿甚する必芁がありたす。 。 - **掚論:** 掚論の堎合、`bnb_4bit_quant_type` はパフォヌマンスに倧きな圱響を䞎えたせん。ただし、モデルの重みずの䞀貫性を保぀ために、必ず同じ `bnb_4bit_compute_dtype` および `torch_dtype` 匕数を䜿甚しおください。 #### Load a large model in 4bit `.from_pretrained` メ゜ッドを呌び出すずきに `load_in_4bit=True` を䜿甚するず、メモリ䜿甚量を (おおよそ) 4 で割るこずができたす。 ```python # pip install transformers accelerate bitsandbytes from transformers import AutoModelForCausalLM, AutoTokenizer model_id = "bigscience/bloom-1b7" tokenizer = AutoTokenizer.from_pretrained(model_id) model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto", load_in_4bit=True) ``` <Tip warning={true}> モデルが 4 ビットでロヌドされるず、珟時点では量子化された重みをハブにプッシュするこずはできないこずに泚意しおください。 4 ビットの重みはただサポヌトされおいないため、トレヌニングできないこずにも泚意しおください。ただし、4 ビット モデルを䜿甚しお远加のパラメヌタヌをトレヌニングするこずもできたす。これに぀いおは次のセクションで説明したす。 </Tip> ### Load a large model in 8bit `.from_pretrained` メ゜ッドを呌び出すずきに `load_in_8bit=True` 匕数を䜿甚するず、メモリ芁件をおよそ半分にしおモデルをロヌドできたす。 ```python # pip install transformers accelerate bitsandbytes from transformers import AutoModelForCausalLM, AutoTokenizer model_id = "bigscience/bloom-1b7" tokenizer = AutoTokenizer.from_pretrained(model_id) model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto", load_in_8bit=True) ``` 次に、通垞 [`PreTrainedModel`] を䜿甚するのず同じようにモデルを䜿甚したす。 `get_memory_footprint` メ゜ッドを䜿甚しお、モデルのメモリ フットプリントを確認できたす。 ```python print(model.get_memory_footprint()) ``` この統合により、倧きなモデルを小さなデバむスにロヌドし、問題なく実行できるようになりたした。 <Tip warning={true}> モデルが 8 ビットでロヌドされるず、最新の `transformers`ず`bitsandbytes`を䜿甚する堎合を陀き、量子化された重みをハブにプッシュするこずは珟圚䞍可胜であるこずに泚意しおください。 8 ビットの重みはただサポヌトされおいないため、トレヌニングできないこずにも泚意しおください。ただし、8 ビット モデルを䜿甚しお远加のパラメヌタヌをトレヌニングするこずもできたす。これに぀いおは次のセクションで説明したす。 たた、`device_map` はオプションですが、利甚可胜なリ゜ヌス䞊でモデルを効率的にディスパッチするため、掚論には `device_map = 'auto'` を蚭定するこずが掚奚されたす。 </Tip> #### Advanced use cases ここでは、FP4 量子化を䜿甚しお実行できるいく぀かの高床な䜿甚䟋に぀いお説明したす。 ##### Change the compute dtype compute dtype は、蚈算䞭に䜿甚される dtype を倉曎するために䜿甚されたす。たずえば、隠し状態は`float32`にありたすが、高速化のために蚈算を bf16 に蚭定できたす。デフォルトでは、compute dtype は `float32` に蚭定されたす。 ```python import torch from transformers import BitsAndBytesConfig quantization_config = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_compute_dtype=torch.bfloat16) ``` ##### Using NF4 (Normal Float 4) data type NF4 デヌタ型を䜿甚するこずもできたす。これは、正芏分垃を䜿甚しお初期化された重みに適合した新しい 4 ビット デヌタ型です。その実行のために: ```python from transformers import BitsAndBytesConfig nf4_config = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_quant_type="nf4", ) model_nf4 = AutoModelForCausalLM.from_pretrained(model_id, quantization_config=nf4_config) ``` ##### Use nested quantization for more memory efficient inference たた、ネストされた量子化手法を䜿甚するこずをお勧めしたす。これにより、パフォヌマンスを远加するこずなく、より倚くのメモリが節玄されたす。経隓的な芳察から、これにより、NVIDIA-T4 16GB 䞊でシヌケンス長 1024、バッチ サむズ 1、募配环積ステップ 4 の llama-13b モデルを埮調敎するこずが可胜になりたす。 ```python from transformers import BitsAndBytesConfig double_quant_config = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_use_double_quant=True, ) model_double_quant = AutoModelForCausalLM.from_pretrained(model_id, quantization_config=double_quant_config) ``` ### Push quantized models on the 🀗 Hub `push_to_hub`メ゜ッドを単玔に䜿甚するこずで、量子化されたモデルをハブにプッシュできたす。これにより、最初に量子化構成ファむルがプッシュされ、次に量子化されたモデルの重みがプッシュされたす。 この機胜を䜿甚できるようにするには、必ず `bitsandbytes>0.37.2` を䜿甚しおください (この蚘事の執筆時点では、`bitsandbytes==0.38.0.post1` でテストしたした)。 ```python from transformers import AutoModelForCausalLM, AutoTokenizer model = AutoModelForCausalLM.from_pretrained("bigscience/bloom-560m", device_map="auto", load_in_8bit=True) tokenizer = AutoTokenizer.from_pretrained("bigscience/bloom-560m") model.push_to_hub("bloom-560m-8bit") ``` <Tip warning={true}> 倧芏暡なモデルでは、ハブ䞊で 8 ビット モデルをプッシュするこずが匷く掚奚されたす。これにより、コミュニティはメモリ フットプリントの削枛ず、たずえば Google Colab での倧芏暡なモデルの読み蟌みによる恩恵を受けるこずができたす。 </Tip> ### Load a quantized model from the 🀗 Hub `from_pretrained`メ゜ッドを䜿甚しお、ハブから量子化モデルをロヌドできたす。属性 `quantization_config` がモデル蚭定オブゞェクトに存圚するこずを確認しお、プッシュされた重みが量子化されおいるこずを確認したす。 ```python from transformers import AutoModelForCausalLM, AutoTokenizer model = AutoModelForCausalLM.from_pretrained("{your_username}/bloom-560m-8bit", device_map="auto") ``` この堎合、匕数 `load_in_8bit=True` を指定する必芁はありたせんが、`bitsandbytes` ず `accelerate` がむンストヌルされおいるこずを確認する必芁があるこずに泚意しおください。 たた、`device_map` はオプションですが、利甚可胜なリ゜ヌス䞊でモデルを効率的にディスパッチするため、掚論には `device_map = 'auto'` を蚭定するこずが掚奚されたす。 ### Advanced use cases このセクションは、8 ビット モデルのロヌドず実行以倖に䜕ができるかを探求したい䞊玚ナヌザヌを察象ずしおいたす。 #### Offload between `cpu` and `gpu` この高床な䜿甚䟋の 1 ぀は、モデルをロヌドし、`CPU`ず`GPU`の間で重みをディスパッチできるこずです。 CPU 䞊でディスパッチされる重みは **8 ビットに倉換されない**ため、`float32`に保持されるこずに泚意しおください。この機胜は、非垞に倧芏暡なモデルを適合させ、そのモデルを GPU ず CPU の間でディスパッチしたいナヌザヌを察象ずしおいたす。 たず、`transformers` から [`BitsAndBytesConfig`] をロヌドし、属性 `llm_int8_enable_fp32_cpu_offload` を `True` に蚭定したす。 ```python from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig quantization_config = BitsAndBytesConfig(llm_int8_enable_fp32_cpu_offload=True) ``` `bigscience/bloom-1b7`モデルをロヌドする必芁があり、`lm_head`を陀くモデル党䜓に​​適合するのに十分な GPU RAM があるずしたす。したがっお、次のようにカスタム device_map を䜜成したす。 ```python device_map = { "transformer.word_embeddings": 0, "transformer.word_embeddings_layernorm": 0, "lm_head": "cpu", "transformer.h": 0, "transformer.ln_f": 0, } ``` そしお、次のようにモデルをロヌドしたす。 ```python model_8bit = AutoModelForCausalLM.from_pretrained( "bigscience/bloom-1b7", device_map=device_map, quantization_config=quantization_config, ) ``` 以䞊ですモデルを楜しんでください #### Play with `llm_int8_threshold` `llm_int8_threshold` 匕数を操䜜しお、倖れ倀のしきい倀を倉曎できたす。 倖れ倀 ずは、特定のしきい倀より倧きい隠れた状態の倀です。 これは、`LLM.int8()`論文で説明されおいる倖れ倀怜出の倖れ倀しきい倀に察応したす。このしきい倀を超える隠し状態の倀は倖れ倀ずみなされ、それらの倀に察する操䜜は fp16 で実行されたす。通垞、倀は正芏分垃したす。぀たり、ほずんどの倀は [-3.5, 3.5] の範囲内にありたすが、倧芏暡なモデルでは倧きく異なる分垃を瀺す䟋倖的な系統的倖れ倀がいく぀かありたす。これらの倖れ倀は、倚くの堎合 [-60, -6] たたは [6, 60] の範囲内にありたす。 Int8 量子化は、倧きさが 5 皋床たでの倀ではうたく機胜したすが、それを超えるず、パフォヌマンスが倧幅に䜎䞋したす。適切なデフォルトのしきい倀は 6 ですが、より䞍安定なモデル (小芏暡なモデル、埮調敎) では、より䜎いしきい倀が必芁になる堎合がありたす。 この匕数は、モデルの掚論速床に圱響を䞎える可胜性がありたす。このパラメヌタを詊しおみお、ナヌスケヌスに最適なパラメヌタを芋぀けるこずをお勧めしたす。 ```python from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig model_id = "bigscience/bloom-1b7" quantization_config = BitsAndBytesConfig( llm_int8_threshold=10, ) model_8bit = AutoModelForCausalLM.from_pretrained( model_id, device_map=device_map, quantization_config=quantization_config, ) tokenizer = AutoTokenizer.from_pretrained(model_id) ``` #### Skip the conversion of some modules 䞀郚のモデルには、安定性を確保するために 8 ビットに倉換する必芁がないモゞュヌルがいく぀かありたす。たずえば、ゞュヌクボックス モデルには、スキップする必芁があるいく぀かの `lm_head` モゞュヌルがありたす。 `llm_int8_skip_modules` で遊んでみる ```python from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig model_id = "bigscience/bloom-1b7" quantization_config = BitsAndBytesConfig( llm_int8_skip_modules=["lm_head"], ) model_8bit = AutoModelForCausalLM.from_pretrained( model_id, device_map=device_map, quantization_config=quantization_config, ) tokenizer = AutoTokenizer.from_pretrained(model_id) ``` #### Fine-tune a model that has been loaded in 8-bit Hugging Face ゚コシステムのアダプタヌの公匏サポヌトにより、8 ビットでロヌドされたモデルを埮調敎できたす。 これにより、単䞀の Google Colab で`flan-t5-large`や`facebook/opt-6.7b`などの倧芏暡モデルを埮調敎するこずができたす。詳现に぀いおは、[`peft`](https://github.com/huggingface/peft) ラむブラリをご芧ください。 トレヌニング甚のモデルをロヌドするずきに `device_map` を枡す必芁がないこずに泚意しおください。モデルが GPU に自動的にロヌドされたす。必芁に応じお、デバむス マップを特定のデバむスに蚭定するこずもできたす (䟋: `cuda:0`、`0`、`torch.device('cuda:0')`)。 `device_map=auto`は掚論のみに䜿甚する必芁があるこずに泚意しおください。 ### BitsAndBytesConfig [[autodoc]] BitsAndBytesConfig ## Quantization with 🀗 `optimum` `optimum`でサポヌトされおいる量子化方法の詳现に぀いおは、[Optimum ドキュメント](https://huggingface.co/docs/optimum/index) を参照し、これらが自分のナヌスケヌスに適甚できるかどうかを確認しおください。
0
hf_public_repos/transformers/docs/source/ja
hf_public_repos/transformers/docs/source/ja/main_classes/onnx.md
<!--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. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Exporting 🀗 Transformers models to ONNX 🀗 Transformers は `transformers.onnx` パッケヌゞを提䟛したす。 蚭定オブゞェクトを利甚するこずで、モデルのチェックポむントをONNXグラフに倉換するこずができたす。 詳现は[ガむド](../serialization) を参照しおください。 を参照しおください。 ## ONNX Configurations 以䞋の3぀の抜象クラスを提䟛しおいたす。 ゚クスポヌトしたいモデルアヌキテクチャのタむプに応じお、継承すべき3぀の抜象クラスを提䟛したす * ゚ンコヌダヌベヌスのモデルは [`~onnx.config.OnnxConfig`] を継承したす。 * デコヌダヌベヌスのモデルは [`~onnx.config.OnnxConfigWithPast`] を継承したす。 * ゚ンコヌダヌ・デコヌダヌモデルは [`~onnx.config.OnnxSeq2SeqConfigWithPast`] を継承しおいたす。 ### OnnxConfig [[autodoc]] onnx.config.OnnxConfig ### OnnxConfigWithPast [[autodoc]] onnx.config.OnnxConfigWithPast ### OnnxSeq2SeqConfigWithPast [[autodoc]] onnx.config.OnnxSeq2SeqConfigWithPast ## ONNX Features 各 ONNX 構成は、次のこずを可胜にする䞀連の _機胜_ に関連付けられおいたす。 さたざたなタむプのトポロゞたたはタスクのモデルを゚クスポヌトしたす。 ### FeaturesManager [[autodoc]] onnx.features.FeaturesManager
0
hf_public_repos/transformers/docs/source
hf_public_repos/transformers/docs/source/it/perf_train_tpu.md
<!--Copyright 2022 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 ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Addestramento su TPU <Tip> 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. </Tip> Questo documento sarà presto completato con informazioni su come effettuare la formazione su TPU.
0
hf_public_repos/transformers/docs/source
hf_public_repos/transformers/docs/source/it/preprocessing.md
<!--Copyright 2022 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # 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 <Youtube id="Yffk5aydLzg"/> 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. <Tip> 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. </Tip> 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': <tf.Tensor: shape=(2, 9), dtype=int32, numpy= array([[ 101, 153, 7719, 21490, 1122, 1114, 9582, 1623, 102], [ 101, 5226, 1122, 9649, 1199, 2610, 1236, 102, 0]], dtype=int32)>, 'token_type_ids': <tf.Tensor: shape=(2, 9), dtype=int32, numpy= array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=int32)>, 'attention_mask': <tf.Tensor: shape=(2, 9), dtype=int32, numpy= array([[1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 0]], dtype=int32)>} ``` ## 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) 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#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"] ``` ![vision-preprocess-tutorial.png](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/vision-preprocess-tutorial.png) ### 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#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': <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=384x512 at 0x7F1A7B0630D0>, '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)) ``` ![preprocessed_image](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/preprocessed_image.png) ## 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.
0
hf_public_repos/transformers/docs/source
hf_public_repos/transformers/docs/source/it/perf_infer_special.md
<!--Copyright 2022 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 ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # 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).
0
hf_public_repos/transformers/docs/source
hf_public_repos/transformers/docs/source/it/model_sharing.md
<!--Copyright 2022 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # 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. <iframe width="560" height="315" src="https://www.youtube.com/embed/XvSGPZFEjDY" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> <Tip> 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. </Tip> ## 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: ![vis_diff](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/vis_diff.png) ## 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. <frameworkcontent> <pt> 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") ``` </pt> <tf> 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") ``` </tf> <jax> 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 ... ) ``` </jax> </frameworkcontent> ## Condividi un modello durante il training <frameworkcontent> <pt> <Youtube id="Z1-XMy-GNLQ"/> 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() ``` </pt> <tf> 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) ``` </tf> </frameworkcontent> ## 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: ![new_model_repo](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/new_model_repo.png) 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. ![upload_file](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/upload_file.png) ## 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).
0
hf_public_repos/transformers/docs/source
hf_public_repos/transformers/docs/source/it/perf_infer_gpu_one.md
<!--Copyright 2022 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 ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # 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 <Tip> Nota che questa funzione può essere utilizzata anche nelle configurazioni multi GPU. </Tip> 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. ![HFxbitsandbytes.png](https://cdn-uploads.huggingface.co/production/uploads/1659861207959-62441d1d9fdefb55a0b7d12c.png) 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). ![MixedInt8.gif](https://cdn-uploads.huggingface.co/production/uploads/1660567469965-62441d1d9fdefb55a0b7d12c.gif) 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: [![Open In Colab: T5-11b demo](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1YORPWx4okIHXnjW7MSAidXN29mPVNT7F?usp=sharing) Oppure questa demo di BLOOM-3B: [![Open In Colab: BLOOM-3b demo](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1qOjXfQIAULfKvZqwCen8-MoWKGdSatZ4?usp=sharing)
0
hf_public_repos/transformers/docs/source
hf_public_repos/transformers/docs/source/it/perf_train_cpu_many.md
<!--Copyright 2022 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 ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # 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. <Tip warning={true}> 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 </Tip> ## 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 ```
0
hf_public_repos/transformers/docs/source
hf_public_repos/transformers/docs/source/it/accelerate.md
<!--Copyright 2022 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Allenamento distribuito con 🀗 Accelerate La parallelizzazione Ú emersa come strategia per allenare modelli sempre più grandi su hardware limitato e accelerarne la velocità di allenamento di diversi ordini di magnitudine. In Hugging Face, abbiamo creato la libreria [🀗 Accelerate](https://huggingface.co/docs/accelerate) per aiutarti ad allenare in modo semplice un modello 🀗 Transformers su qualsiasi tipo di configurazione distribuita, sia che si tratti di più GPU su una sola macchina o di più GPU su più macchine. In questo tutorial, imparerai come personalizzare il training loop nativo di PyTorch per consentire l'addestramento in un ambiente distribuito. ## Configurazione Inizia installando 🀗 Accelerate: ```bash pip install accelerate ``` Poi importa e crea un oggetto [`Accelerator`](https://huggingface.co/docs/accelerate/package_reference/accelerator#accelerate.Accelerator). `Accelerator` rileverà automaticamente il tuo setup distribuito e inizializzerà tutte le componenti necessarie per l'allenamento. Non dovrai allocare esplicitamente il tuo modello su un device. ```py >>> from accelerate import Accelerator >>> accelerator = Accelerator() ``` ## Preparati ad accelerare Il prossimo passo Ú quello di passare tutti gli oggetti rilevanti per l'allenamento al metodo [`prepare`](https://huggingface.co/docs/accelerate/package_reference/accelerator#accelerate.Accelerator.prepare). Questo include i tuoi DataLoaders per l'allenamento e per la valutazione, un modello e un ottimizzatore: ```py >>> train_dataloader, eval_dataloader, model, optimizer = accelerator.prepare( ... train_dataloader, eval_dataloader, model, optimizer ... ) ``` ## Backward Infine, sostituisci il tipico metodo `loss.backward()` nel tuo loop di allenamento con il metodo [`backward`](https://huggingface.co/docs/accelerate/package_reference/accelerator#accelerate.Accelerator.backward) di 🀗 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) ``` Come puoi vedere nel seguente codice, hai solo bisogno di aggiungere quattro righe in più di codice al tuo training loop per abilitare l'allenamento distribuito! ```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) ``` ## Allenamento Una volta che hai aggiunto le righe di codice rilevanti, lancia il tuo allenamento in uno script o in un notebook come Colaboratory. ### Allenamento con uno script Se stai eseguendo il tuo allenamento da uno script, esegui il comando seguente per creare e salvare un file di configurazione: ```bash accelerate config ``` Poi lancia il tuo allenamento con: ```bash accelerate launch train.py ``` ### Allenamento con un notebook La libreria 🀗 Accelerate può anche essere utilizzata in un notebook se stai pianificando di utilizzare le TPU di Colaboratory. Inserisci tutto il codice legato all'allenamento in una funzione, e passala al `notebook_launcher`: ```py >>> from accelerate import notebook_launcher >>> notebook_launcher(training_function) ``` Per maggiori informazioni relative a 🀗 Accelerate e le sue numerose funzionalità, fai riferimento alla [documentazione](https://huggingface.co/docs/accelerate).
0
hf_public_repos/transformers/docs/source
hf_public_repos/transformers/docs/source/it/community.md
<!--⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # 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) | [![Aprilo in Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) |[![Aprilo in Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) |[![Aprilo in Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) | [![Aprilo in Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) | [![Aprilo in Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) | [![Aprilo in Colab](https://colab.research.google.com/assets/colab-badge.svg)](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/) | [![Aprilo in Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) | [![Aprilo in Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) | [![Aprilo in Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) | [![Aprilo in Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) | [![Aprilo in Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) | [![Aprilo in Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) | [![Aprilo in Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) | [![Aprilo in Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) |[![Aprilo in Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) |[![Aprilo in Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) | [![Aprilo in Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) | [![Aprilo in Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) | [![Aprilo in Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) | [![Aprilo in Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) | [![Aprilo in Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) | [![Aprilo in Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) | [![Aprilo in Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) | [![Aprilo in Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) | [![Aprilo in Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) | [![Aprilo in Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) | [![Aprilo in Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) |[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](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) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1obr78FY_cBmWY5ODViCmzdY6O1KB65Vc?usp=sharing) |
0
hf_public_repos/transformers/docs/source
hf_public_repos/transformers/docs/source/it/serialization.md
<!--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. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # 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: <!--This table is automatically generated by `make fix-copies`, do not fill manually!--> - 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: <frameworkcontent> <pt> ```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/ ``` </pt> <tf> ```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/ ``` </tf> </frameworkcontent> ### 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. <Tip> 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. </Tip> ### 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`] <Tip> Un buon modo per implementare una configurazione ONNX personalizzata Ú guardare l'implementazione esistente nel file `configuration_<model_name>.py` di un'architettura simile. </Tip> 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. <Tip> 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. </Tip> 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'})]) ``` <Tip> 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. </Tip> #### 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) ``` <Tip> 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. </Tip> #### 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 _<model_name>.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 <Tip> 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. </Tip> 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).
0
hf_public_repos/transformers/docs/source
hf_public_repos/transformers/docs/source/it/training.md
<!--Copyright 2022 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # 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. <a id='data-processing'></a> ## Preparare un dataset <Youtube id="_BZearw7f0w"/> 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#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)) ``` <a id='trainer'></a> ## Addestramento <frameworkcontent> <pt> <Youtube id="nvBXf7s7vTI"/> 🀗 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) ``` <Tip> 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. </Tip> ### 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) 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() ``` </pt> <tf> <a id='keras'></a> <Youtube id="rnTGBy2ax1c"/> 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") ``` <Tip> [`Trainer`] usa [`DataCollatorWithPadding`] in maniera predefinita in modo da non dover specificare esplicitamente un collettore di dati. </Tip> 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) ``` </tf> </frameworkcontent> <a id='pytorch_native'></a> ## Addestramento in PyTorch nativo <frameworkcontent> <pt> <Youtube id="Dh9CL8fyG80"/> [`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) ``` <Tip> 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/). </Tip> 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?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() ``` </pt> </frameworkcontent> <a id='additional-resources'></a> ## 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.
0
hf_public_repos/transformers/docs/source
hf_public_repos/transformers/docs/source/it/perf_infer_gpu_many.md
<!--Copyright 2022 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 ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Inferenza Efficiente su GPU Multiple Questo documento contiene informazioni su come fare inferenza in maniera efficiente su GPU multiple. <Tip> 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. </Tip> ## `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.
0
hf_public_repos/transformers/docs/source
hf_public_repos/transformers/docs/source/it/quicktour.md
<!--Copyright 2022 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # 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. <Tip> 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. </Tip> ## Pipeline [`pipeline`] Ú il modo più semplice per utilizzare un modello pre-allenato per un dato compito. <Youtube id="tiZFewofSLM"/> 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. <Tip> Per maggiori dettagli legati alla [`pipeline`] e ai compiti ad essa associati, fai riferimento alla documentazione [qui](./main_classes/pipelines). </Tip> ### Utilizzo della Pipeline Nel seguente esempio, utilizzerai la [`pipeline`] per l'analisi del sentimento. Installa le seguenti dipendenze se non lo hai già fatto: <frameworkcontent> <pt> ```bash pip install torch ``` </pt> <tf> ```bash pip install tensorflow ``` </tf> </frameworkcontent> 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) 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" ``` <frameworkcontent> <pt> 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) ``` </pt> <tf> 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) ``` </tf> </frameworkcontent> 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 <Youtube id="AhChOFRegn4"/> 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: <frameworkcontent> <pt> ```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", ... ) ``` </pt> <tf> ```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", ... ) ``` </tf> </frameworkcontent> Leggi il tutorial sul [preprocessing](./preprocessing) per maggiori dettagli sulla tokenizzazione. ### AutoModel <frameworkcontent> <pt> 🀗 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) ``` <Tip> Guarda il [task summary](./task_summary) per sapere quale classe di [`AutoModel`] utilizzare per quale compito. </Tip> 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=<SoftmaxBackward0>) ``` </pt> <tf> 🀗 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) ``` <Tip> Guarda il [task summary](./task_summary) per sapere quale classe di [`AutoModel`] utilizzare per quale compito. </Tip> 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 ``` </tf> </frameworkcontent> <Tip> 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. </Tip> 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. <Tip> 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. </Tip> ### Salva un modello <frameworkcontent> <pt> 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") ``` </pt> <tf> 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") ``` </tf> </frameworkcontent> 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: <frameworkcontent> <pt> ```py >>> from transformers import AutoModel >>> tokenizer = AutoTokenizer.from_pretrained(tf_save_directory) >>> pt_model = AutoModelForSequenceClassification.from_pretrained(tf_save_directory, from_tf=True) ``` </pt> <tf> ```py >>> from transformers import TFAutoModel >>> tokenizer = AutoTokenizer.from_pretrained(pt_save_directory) >>> tf_model = TFAutoModelForSequenceClassification.from_pretrained(pt_save_directory, from_pt=True) ``` </tf> </frameworkcontent>
0
hf_public_repos/transformers/docs/source
hf_public_repos/transformers/docs/source/it/run_scripts.md
<!--Copyright 2022 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # 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: <details> <summary>Esempi per versioni precedenti di 🀗 Transformers</summary> <ul> <li><a href="https://github.com/huggingface/transformers/tree/v4.5.1/examples">v4.5.1</a></li> <li><a href="https://github.com/huggingface/transformers/tree/v4.4.2/examples">v4.4.2</a></li> <li><a href="https://github.com/huggingface/transformers/tree/v4.3.3/examples">v4.3.3</a></li> <li><a href="https://github.com/huggingface/transformers/tree/v4.2.2/examples">v4.2.2</a></li> <li><a href="https://github.com/huggingface/transformers/tree/v4.1.1/examples">v4.1.1</a></li> <li><a href="https://github.com/huggingface/transformers/tree/v4.0.1/examples">v4.0.1</a></li> <li><a href="https://github.com/huggingface/transformers/tree/v3.5.1/examples">v3.5.1</a></li> <li><a href="https://github.com/huggingface/transformers/tree/v3.4.0/examples">v3.4.0</a></li> <li><a href="https://github.com/huggingface/transformers/tree/v3.3.1/examples">v3.3.1</a></li> <li><a href="https://github.com/huggingface/transformers/tree/v3.2.0/examples">v3.2.0</a></li> <li><a href="https://github.com/huggingface/transformers/tree/v3.1.0/examples">v3.1.0</a></li> <li><a href="https://github.com/huggingface/transformers/tree/v3.0.2/examples">v3.0.2</a></li> <li><a href="https://github.com/huggingface/transformers/tree/v2.11.0/examples">v2.11.0</a></li> <li><a href="https://github.com/huggingface/transformers/tree/v2.10.0/examples">v2.10.0</a></li> <li><a href="https://github.com/huggingface/transformers/tree/v2.9.1/examples">v2.9.1</a></li> <li><a href="https://github.com/huggingface/transformers/tree/v2.8.0/examples">v2.8.0</a></li> <li><a href="https://github.com/huggingface/transformers/tree/v2.7.0/examples">v2.7.0</a></li> <li><a href="https://github.com/huggingface/transformers/tree/v2.6.0/examples">v2.6.0</a></li> <li><a href="https://github.com/huggingface/transformers/tree/v2.5.1/examples">v2.5.1</a></li> <li><a href="https://github.com/huggingface/transformers/tree/v2.4.0/examples">v2.4.0</a></li> <li><a href="https://github.com/huggingface/transformers/tree/v2.3.0/examples">v2.3.0</a></li> <li><a href="https://github.com/huggingface/transformers/tree/v2.2.0/examples">v2.2.0</a></li> <li><a href="https://github.com/huggingface/transformers/tree/v2.1.0/examples">v2.1.1</a></li> <li><a href="https://github.com/huggingface/transformers/tree/v2.0.0/examples">v2.0.0</a></li> <li><a href="https://github.com/huggingface/transformers/tree/v1.2.0/examples">v1.2.0</a></li> <li><a href="https://github.com/huggingface/transformers/tree/v1.1.0/examples">v1.1.0</a></li> <li><a href="https://github.com/huggingface/transformers/tree/v1.0.0/examples">v1.0.0</a></li> </ul> </details> 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 <frameworkcontent> <pt> 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 ``` </pt> <tf> 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 ``` </tf> </frameworkcontent> ## 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 torchrun \ --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 <frameworkcontent> <pt> 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 ``` </pt> <tf> 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 ``` </tf> </frameworkcontent> ## 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 ```
0