├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── data └── encoder-updated.json └── src ├── bart-large-graph-linear.mk ├── bart-large-long.mk ├── bart-large.mk ├── bart_decode_parallel.py ├── convert_model_to_long.py ├── fairseq ├── .github │ ├── ISSUE_TEMPLATE.md │ ├── ISSUE_TEMPLATE │ │ ├── bug_report.md │ │ ├── documentation.md │ │ ├── feature_request.md │ │ └── how-to-question.md │ ├── PULL_REQUEST_TEMPLATE.md │ └── workflows │ │ ├── build.yml │ │ └── build_windows.yml ├── .gitignore ├── .gitmodules ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── docs │ ├── Makefile │ ├── _static │ │ └── theme_overrides.css │ ├── command_line_tools.rst │ ├── conf.py │ ├── criterions.rst │ ├── data.rst │ ├── docutils.conf │ ├── getting_started.rst │ ├── index.rst │ ├── lr_scheduler.rst │ ├── make.bat │ ├── models.rst │ ├── modules.rst │ ├── optim.rst │ ├── overview.rst │ ├── requirements.txt │ ├── tasks.rst │ ├── tutorial_classifying_names.rst │ └── tutorial_simple_lstm.rst ├── eval_lm.py ├── examples │ ├── .gitignore │ ├── __init__.py │ ├── backtranslation │ │ ├── README.md │ │ ├── deduplicate_lines.py │ │ ├── extract_bt_data.py │ │ ├── prepare-de-monolingual.sh │ │ ├── prepare-wmt18en2de.sh │ │ ├── sacrebleu.sh │ │ └── tokenized_bleu.sh │ ├── bart │ │ ├── README.glue.md │ │ ├── README.md │ │ └── README.summarization.md │ ├── byte_level_bpe │ │ ├── README.md │ │ ├── get_bitext.py │ │ ├── get_data.sh │ │ └── gru_transformer.py │ ├── camembert │ │ └── README.md │ ├── conv_seq2seq │ │ └── README.md │ ├── cross_lingual_language_model │ │ └── README.md │ ├── joint_alignment_translation │ │ ├── README.md │ │ └── prepare-wmt18en2de_no_norm_no_escape_no_agressive.sh │ ├── language_model │ │ ├── README.adaptive_inputs.md │ │ ├── README.conv.md │ │ ├── README.md │ │ └── prepare-wikitext-103.sh │ ├── layerdrop │ │ └── README.md │ ├── mbart │ │ └── README.md │ ├── megatron_11b │ │ ├── README.md │ │ └── detok.py │ ├── noisychannel │ │ ├── README.md │ │ ├── __init__.py │ │ ├── rerank.py │ │ ├── rerank_generate.py │ │ ├── rerank_options.py │ │ ├── rerank_score_bw.py │ │ ├── rerank_score_lm.py │ │ ├── rerank_tune.py │ │ └── rerank_utils.py │ ├── nonautoregressive_translation │ │ ├── README.md │ │ └── scripts.md │ ├── paraphraser │ │ ├── README.md │ │ └── paraphrase.py │ ├── pay_less_attention_paper │ │ └── README.md │ ├── quant_noise │ │ ├── README.md │ │ └── transformer_quantization_config.yaml │ ├── roberta │ │ ├── README.custom_classification.md │ │ ├── README.glue.md │ │ ├── README.md │ │ ├── README.pretraining.md │ │ ├── README.race.md │ │ ├── commonsense_qa │ │ │ ├── README.md │ │ │ ├── __init__.py │ │ │ ├── commonsense_qa_task.py │ │ │ └── download_cqa_data.sh │ │ ├── multiprocessing_bpe_encoder.py │ │ ├── preprocess_GLUE_tasks.sh │ │ ├── preprocess_RACE.py │ │ ├── preprocess_RACE.sh │ │ └── wsc │ │ │ ├── README.md │ │ │ ├── __init__.py │ │ │ ├── wsc_criterion.py │ │ │ ├── wsc_task.py │ │ │ └── wsc_utils.py │ ├── scaling_nmt │ │ └── README.md │ ├── simultaneous_translation │ │ ├── README.md │ │ ├── __init__.py │ │ ├── criterions │ │ │ ├── __init__.py │ │ │ └── label_smoothed_cross_entropy_latency_augmented.py │ │ ├── docs │ │ │ ├── baseline.md │ │ │ └── evaluation.md │ │ ├── eval │ │ │ ├── __init__.py │ │ │ ├── agents │ │ │ │ ├── __init__.py │ │ │ │ ├── agent.py │ │ │ │ ├── simul_trans_agent.py │ │ │ │ ├── simul_trans_text_agent.py │ │ │ │ └── word_splitter.py │ │ │ ├── client.py │ │ │ ├── eval_latency.py │ │ │ ├── evaluate.py │ │ │ ├── scorers │ │ │ │ ├── __init__.py │ │ │ │ ├── scorer.py │ │ │ │ └── text_scorer.py │ │ │ └── server.py │ │ ├── models │ │ │ ├── __init__.py │ │ │ └── transformer_monotonic_attention.py │ │ ├── modules │ │ │ ├── __init__.py │ │ │ ├── monotonic_multihead_attention.py │ │ │ └── monotonic_transformer_layer.py │ │ └── utils │ │ │ ├── __init__.py │ │ │ ├── functions.py │ │ │ └── latency.py │ ├── speech_recognition │ │ ├── README.md │ │ ├── __init__.py │ │ ├── criterions │ │ │ ├── ASG_loss.py │ │ │ ├── CTC_loss.py │ │ │ ├── __init__.py │ │ │ └── cross_entropy_acc.py │ │ ├── data │ │ │ ├── __init__.py │ │ │ ├── asr_dataset.py │ │ │ ├── collaters.py │ │ │ ├── data_utils.py │ │ │ └── replabels.py │ │ ├── datasets │ │ │ ├── asr_prep_json.py │ │ │ └── prepare-librispeech.sh │ │ ├── infer.py │ │ ├── models │ │ │ ├── __init__.py │ │ │ ├── vggtransformer.py │ │ │ └── w2l_conv_glu_enc.py │ │ ├── tasks │ │ │ ├── __init__.py │ │ │ └── speech_recognition.py │ │ ├── utils │ │ │ └── wer_utils.py │ │ └── w2l_decoder.py │ ├── stories │ │ └── README.md │ ├── translation │ │ ├── README.md │ │ ├── prepare-iwslt14.sh │ │ ├── prepare-iwslt17-multilingual.sh │ │ ├── prepare-wmt14en2de.sh │ │ └── prepare-wmt14en2fr.sh │ ├── translation_moe │ │ ├── README.md │ │ ├── score.py │ │ └── src │ │ │ ├── __init__.py │ │ │ ├── logsumexp_moe.py │ │ │ ├── mean_pool_gating_network.py │ │ │ └── translation_moe.py │ ├── wav2vec │ │ ├── README.md │ │ ├── vq-wav2vec_featurize.py │ │ ├── wav2vec_featurize.py │ │ └── wav2vec_manifest.py │ ├── wmt19 │ │ └── README.md │ └── xlmr │ │ └── README.md ├── fairseq.gif ├── fairseq │ ├── __init__.py │ ├── benchmark │ │ ├── __init__.py │ │ ├── dummy_lm.py │ │ ├── dummy_masked_lm.py │ │ └── dummy_model.py │ ├── binarizer.py │ ├── bleu.py │ ├── checkpoint_utils.py │ ├── clib │ │ ├── libbleu │ │ │ ├── libbleu.cpp │ │ │ └── module.cpp │ │ ├── libnat │ │ │ └── edit_dist.cpp │ │ └── libnat_cuda │ │ │ ├── binding.cpp │ │ │ ├── edit_dist.cu │ │ │ └── edit_dist.h │ ├── criterions │ │ ├── __init__.py │ │ ├── adaptive_loss.py │ │ ├── binary_cross_entropy.py │ │ ├── composite_loss.py │ │ ├── cross_entropy.py │ │ ├── fairseq_criterion.py │ │ ├── label_smoothed_cross_entropy.py │ │ ├── label_smoothed_cross_entropy_with_alignment.py │ │ ├── legacy_masked_lm.py │ │ ├── masked_lm.py │ │ ├── nat_loss.py │ │ ├── sentence_prediction.py │ │ └── sentence_ranking.py │ ├── data │ │ ├── __init__.py │ │ ├── append_token_dataset.py │ │ ├── audio │ │ │ ├── __init__.py │ │ │ └── raw_audio_dataset.py │ │ ├── backtranslation_dataset.py │ │ ├── base_wrapper_dataset.py │ │ ├── colorize_dataset.py │ │ ├── concat_dataset.py │ │ ├── concat_sentences_dataset.py │ │ ├── data_utils.py │ │ ├── data_utils_fast.pyx │ │ ├── denoising_dataset.py │ │ ├── dictionary.py │ │ ├── encoders │ │ │ ├── __init__.py │ │ │ ├── byte_bpe.py │ │ │ ├── byte_utils.py │ │ │ ├── bytes.py │ │ │ ├── characters.py │ │ │ ├── fastbpe.py │ │ │ ├── gpt2_bpe.py │ │ │ ├── gpt2_bpe_utils.py │ │ │ ├── hf_bert_bpe.py │ │ │ ├── hf_byte_bpe.py │ │ │ ├── moses_tokenizer.py │ │ │ ├── nltk_tokenizer.py │ │ │ ├── sentencepiece_bpe.py │ │ │ ├── space_tokenizer.py │ │ │ ├── subword_nmt_bpe.py │ │ │ └── utils.py │ │ ├── fairseq_dataset.py │ │ ├── id_dataset.py │ │ ├── indexed_dataset.py │ │ ├── iterators.py │ │ ├── language_pair_dataset.py │ │ ├── legacy │ │ │ ├── __init__.py │ │ │ ├── block_pair_dataset.py │ │ │ ├── masked_lm_dataset.py │ │ │ └── masked_lm_dictionary.py │ │ ├── list_dataset.py │ │ ├── lm_context_window_dataset.py │ │ ├── lru_cache_dataset.py │ │ ├── mask_tokens_dataset.py │ │ ├── monolingual_dataset.py │ │ ├── multi_corpus_sampled_dataset.py │ │ ├── nested_dictionary_dataset.py │ │ ├── noising.py │ │ ├── num_samples_dataset.py │ │ ├── numel_dataset.py │ │ ├── offset_tokens_dataset.py │ │ ├── pad_dataset.py │ │ ├── plasma_utils.py │ │ ├── prepend_dataset.py │ │ ├── prepend_token_dataset.py │ │ ├── raw_label_dataset.py │ │ ├── replace_dataset.py │ │ ├── resampling_dataset.py │ │ ├── roll_dataset.py │ │ ├── round_robin_zip_datasets.py │ │ ├── shorten_dataset.py │ │ ├── sort_dataset.py │ │ ├── strip_token_dataset.py │ │ ├── subsample_dataset.py │ │ ├── token_block_dataset.py │ │ ├── token_block_utils_fast.pyx │ │ ├── transform_eos_dataset.py │ │ └── transform_eos_lang_pair_dataset.py │ ├── distributed_utils.py │ ├── file_io.py │ ├── file_utils.py │ ├── hub_utils.py │ ├── incremental_decoding_utils.py │ ├── iterative_refinement_generator.py │ ├── legacy_distributed_data_parallel.py │ ├── logging │ │ ├── __init__.py │ │ ├── meters.py │ │ ├── metrics.py │ │ └── progress_bar.py │ ├── model_parallel │ │ ├── __init__.py │ │ ├── criterions │ │ │ ├── __init__.py │ │ │ └── vocab_parallel_cross_entropy.py │ │ ├── megatron_trainer.py │ │ ├── models │ │ │ ├── __init__.py │ │ │ ├── roberta │ │ │ │ ├── __init__.py │ │ │ │ └── model.py │ │ │ ├── transformer.py │ │ │ └── transformer_lm.py │ │ └── modules │ │ │ ├── __init__.py │ │ │ ├── multihead_attention.py │ │ │ ├── transformer_layer.py │ │ │ ├── transformer_sentence_encoder.py │ │ │ └── transformer_sentence_encoder_layer.py │ ├── models │ │ ├── __init__.py │ │ ├── bart │ │ │ ├── __init__.py │ │ │ ├── hub_interface.py │ │ │ └── model.py │ │ ├── composite_encoder.py │ │ ├── distributed_fairseq_model.py │ │ ├── fairseq_decoder.py │ │ ├── fairseq_encoder.py │ │ ├── fairseq_incremental_decoder.py │ │ ├── fairseq_model.py │ │ ├── fconv.py │ │ ├── fconv_lm.py │ │ ├── fconv_self_att.py │ │ ├── huggingface │ │ │ ├── __init__.py │ │ │ └── hf_gpt2.py │ │ ├── lightconv.py │ │ ├── lightconv_lm.py │ │ ├── lstm.py │ │ ├── lstm_lm.py │ │ ├── masked_lm.py │ │ ├── model_utils.py │ │ ├── multilingual_transformer.py │ │ ├── nat │ │ │ ├── __init__.py │ │ │ ├── cmlm_transformer.py │ │ │ ├── fairseq_nat_model.py │ │ │ ├── insertion_transformer.py │ │ │ ├── iterative_nonautoregressive_transformer.py │ │ │ ├── levenshtein_transformer.py │ │ │ ├── levenshtein_utils.py │ │ │ ├── nat_crf_transformer.py │ │ │ ├── nonautoregressive_ensembles.py │ │ │ └── nonautoregressive_transformer.py │ │ ├── roberta │ │ │ ├── __init__.py │ │ │ ├── alignment_utils.py │ │ │ ├── hub_interface.py │ │ │ ├── model.py │ │ │ ├── model_camembert.py │ │ │ └── model_xlmr.py │ │ ├── transformer.py │ │ ├── transformer_align.py │ │ ├── transformer_from_pretrained_xlm.py │ │ ├── transformer_lm.py │ │ └── wav2vec.py │ ├── modules │ │ ├── __init__.py │ │ ├── adaptive_input.py │ │ ├── adaptive_softmax.py │ │ ├── beamable_mm.py │ │ ├── character_token_embedder.py │ │ ├── conv_tbc.py │ │ ├── cross_entropy.py │ │ ├── cuda_utils.cu │ │ ├── downsampled_multihead_attention.py │ │ ├── dynamic_convolution.py │ │ ├── dynamic_crf_layer.py │ │ ├── dynamicconv_layer │ │ │ ├── __init__.py │ │ │ ├── cuda_function_gen.py │ │ │ ├── dynamicconv_cuda.cpp │ │ │ ├── dynamicconv_cuda.cuh │ │ │ ├── dynamicconv_cuda_kernel.cu │ │ │ ├── dynamicconv_layer.py │ │ │ ├── dynamiconv_cpu.cpp │ │ │ └── setup.py │ │ ├── fp32_group_norm.py │ │ ├── gelu.py │ │ ├── grad_multiply.py │ │ ├── gumbel_vector_quantizer.py │ │ ├── kmeans_vector_quantizer.py │ │ ├── layer_drop.py │ │ ├── layer_norm.py │ │ ├── learned_positional_embedding.py │ │ ├── lightconv_layer │ │ │ ├── __init__.py │ │ │ ├── cuda_function_gen.py │ │ │ ├── lightconv_cuda.cpp │ │ │ ├── lightconv_cuda.cuh │ │ │ ├── lightconv_cuda_kernel.cu │ │ │ ├── lightconv_layer.py │ │ │ └── setup.py │ │ ├── lightweight_convolution.py │ │ ├── linearized_convolution.py │ │ ├── longformer_multihead_attention.py │ │ ├── multihead_attention.py │ │ ├── positional_embedding.py │ │ ├── quant_noise.py │ │ ├── quantization │ │ │ ├── __init__.py │ │ │ ├── pq │ │ │ │ ├── __init__.py │ │ │ │ ├── em.py │ │ │ │ ├── modules │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── qconv.py │ │ │ │ │ ├── qemb.py │ │ │ │ │ └── qlinear.py │ │ │ │ ├── pq.py │ │ │ │ └── utils.py │ │ │ ├── quantization_options.py │ │ │ └── scalar │ │ │ │ ├── __init__.py │ │ │ │ ├── modules │ │ │ │ ├── __init__.py │ │ │ │ ├── qact.py │ │ │ │ ├── qconv.py │ │ │ │ ├── qemb.py │ │ │ │ └── qlinear.py │ │ │ │ ├── ops.py │ │ │ │ └── utils.py │ │ ├── scalar_bias.py │ │ ├── sinusoidal_positional_embedding.py │ │ ├── sparse_multihead_attention.py │ │ ├── sparse_transformer_sentence_encoder.py │ │ ├── sparse_transformer_sentence_encoder_layer.py │ │ ├── transformer_layer.py │ │ ├── transformer_sentence_encoder.py │ │ ├── transformer_sentence_encoder_layer.py │ │ ├── unfold.py │ │ └── vggblock.py │ ├── nan_detector.py │ ├── optim │ │ ├── __init__.py │ │ ├── adadelta.py │ │ ├── adafactor.py │ │ ├── adagrad.py │ │ ├── adam.py │ │ ├── adamax.py │ │ ├── bmuf.py │ │ ├── fairseq_optimizer.py │ │ ├── fp16_optimizer.py │ │ ├── fused_adam.py │ │ ├── fused_lamb.py │ │ ├── lr_scheduler │ │ │ ├── __init__.py │ │ │ ├── cosine_lr_scheduler.py │ │ │ ├── fairseq_lr_scheduler.py │ │ │ ├── fixed_schedule.py │ │ │ ├── inverse_square_root_schedule.py │ │ │ ├── polynomial_decay_schedule.py │ │ │ ├── reduce_lr_on_plateau.py │ │ │ ├── tri_stage_lr_scheduler.py │ │ │ └── triangular_lr_scheduler.py │ │ ├── nag.py │ │ └── sgd.py │ ├── options.py │ ├── pdb.py │ ├── quantization_utils.py │ ├── registry.py │ ├── search.py │ ├── sequence_generator.py │ ├── sequence_scorer.py │ ├── tasks │ │ ├── __init__.py │ │ ├── audio_pretraining.py │ │ ├── cross_lingual_lm.py │ │ ├── denoising.py │ │ ├── fairseq_task.py │ │ ├── language_modeling.py │ │ ├── legacy_masked_lm.py │ │ ├── masked_lm.py │ │ ├── multilingual_denoising.py │ │ ├── multilingual_masked_lm.py │ │ ├── multilingual_translation.py │ │ ├── semisupervised_translation.py │ │ ├── sentence_prediction.py │ │ ├── sentence_ranking.py │ │ ├── translation.py │ │ ├── translation_from_pretrained_bart.py │ │ ├── translation_from_pretrained_xlm.py │ │ └── translation_lev.py │ ├── tokenizer.py │ ├── trainer.py │ └── utils.py ├── fairseq_cli │ ├── __init__.py │ ├── eval_lm.py │ ├── generate.py │ ├── interactive.py │ ├── preprocess.py │ ├── score.py │ ├── train.py │ └── validate.py ├── fairseq_logo.png ├── generate.py ├── hubconf.py ├── interactive.py ├── preprocess.py ├── pyproject.toml ├── score.py ├── scripts │ ├── __init__.py │ ├── average_checkpoints.py │ ├── build_sym_alignment.py │ ├── compare_namespaces.py │ ├── compound_split_bleu.sh │ ├── convert_dictionary.lua │ ├── convert_model.lua │ ├── count_docs.py │ ├── read_binarized.py │ ├── rm_pt.py │ ├── sacrebleu_pregen.sh │ ├── shard_docs.py │ ├── split_train_valid_docs.py │ ├── spm_decode.py │ ├── spm_encode.py │ └── spm_train.py ├── setup.py ├── tests │ ├── __init__.py │ ├── gpu │ │ ├── __init__.py │ │ ├── test_binaries_gpu.py │ │ └── transformer_quantization_config.yaml │ ├── speech_recognition │ │ ├── __init__.py │ │ ├── asr_test_base.py │ │ ├── test_collaters.py │ │ ├── test_cross_entropy.py │ │ ├── test_data_utils.py │ │ └── test_vggtransformer.py │ ├── test_average_checkpoints.py │ ├── test_backtranslation_dataset.py │ ├── test_binaries.py │ ├── test_bmuf.py │ ├── test_character_token_embedder.py │ ├── test_concat_dataset.py │ ├── test_convtbc.py │ ├── test_dictionary.py │ ├── test_export.py │ ├── test_file_io.py │ ├── test_iterators.py │ ├── test_label_smoothing.py │ ├── test_lstm_jitable.py │ ├── test_memory_efficient_fp16.py │ ├── test_metrics.py │ ├── test_multi_corpus_sampled_dataset.py │ ├── test_multihead_attention.py │ ├── test_noising.py │ ├── test_reproducibility.py │ ├── test_resampling_dataset.py │ ├── test_sequence_generator.py │ ├── test_sequence_scorer.py │ ├── test_sparse_multihead_attention.py │ ├── test_token_block_dataset.py │ ├── test_train.py │ ├── test_utils.py │ └── utils.py ├── train.py └── validate.py ├── graph_construction.py ├── graph_utils.py └── prepare_data.py /.gitignore: -------------------------------------------------------------------------------- 1 | data/*zip 2 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | ## Code of Conduct 2 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 3 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 4 | opensource-codeofconduct@amazon.com with any additional questions or comments. 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of 4 | this software and associated documentation files (the "Software"), to deal in 5 | the Software without restriction, including without limitation the rights to 6 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software is furnished to do so. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 10 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 11 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 12 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 13 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 14 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 15 | 16 | -------------------------------------------------------------------------------- /src/fairseq/.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ## 👉 [Please follow one of these issue templates](https://github.com/pytorch/fairseq/issues/new/choose) 👈 2 | 3 | Note: to keep the backlog clean and actionable, issues may be immediately closed if they do not follow one of the above issue templates. 4 | -------------------------------------------------------------------------------- /src/fairseq/.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: 🐛 Bug Report 3 | about: Submit a bug report to help us improve 4 | labels: 'bug, needs triage' 5 | --- 6 | 7 | ## 🐛 Bug 8 | 9 | 10 | 11 | ### To Reproduce 12 | 13 | Steps to reproduce the behavior (**always include the command you ran**): 14 | 15 | 1. Run cmd '....' 16 | 2. See error 17 | 18 | 19 | 20 | 21 | #### Code sample 22 | 24 | 25 | ### Expected behavior 26 | 27 | 28 | 29 | ### Environment 30 | 31 | - fairseq Version (e.g., 1.0 or master): 32 | - PyTorch Version (e.g., 1.0) 33 | - OS (e.g., Linux): 34 | - How you installed fairseq (`pip`, source): 35 | - Build command you used (if compiling from source): 36 | - Python version: 37 | - CUDA/cuDNN version: 38 | - GPU models and configuration: 39 | - Any other relevant information: 40 | 41 | ### Additional context 42 | 43 | 44 | -------------------------------------------------------------------------------- /src/fairseq/.github/ISSUE_TEMPLATE/documentation.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: 📚 Documentation/Typos 3 | about: Report an issue related to documentation or a typo 4 | labels: 'documentation, needs triage' 5 | --- 6 | 7 | ## 📚 Documentation 8 | 9 | For typos and doc fixes, please go ahead and: 10 | 11 | 1. Create an issue. 12 | 2. Fix the typo. 13 | 3. Submit a PR. 14 | 15 | Thanks! 16 | -------------------------------------------------------------------------------- /src/fairseq/.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: 🚀 Feature Request 3 | about: Submit a proposal/request for a new feature 4 | labels: 'enhancement, help wanted, needs triage' 5 | --- 6 | 7 | ## 🚀 Feature Request 8 | 9 | 10 | ### Motivation 11 | 12 | 13 | 14 | ### Pitch 15 | 16 | 17 | 18 | ### Alternatives 19 | 20 | 21 | 22 | ### Additional context 23 | 24 | 25 | -------------------------------------------------------------------------------- /src/fairseq/.github/ISSUE_TEMPLATE/how-to-question.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: ❓ Questions/Help 3 | about: If you have questions, please first search existing issues and docs 4 | labels: 'question, needs triage' 5 | --- 6 | 7 | ## ❓ Questions and Help 8 | 9 | ### Before asking: 10 | 1. search the issues. 11 | 2. search the docs. 12 | 13 | 14 | 15 | #### What is your question? 16 | 17 | #### Code 18 | 19 | 20 | 21 | #### What have you tried? 22 | 23 | #### What's your environment? 24 | 25 | - fairseq Version (e.g., 1.0 or master): 26 | - PyTorch Version (e.g., 1.0) 27 | - OS (e.g., Linux): 28 | - How you installed fairseq (`pip`, source): 29 | - Build command you used (if compiling from source): 30 | - Python version: 31 | - CUDA/cuDNN version: 32 | - GPU models and configuration: 33 | - Any other relevant information: 34 | -------------------------------------------------------------------------------- /src/fairseq/.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | # Before submitting 2 | 3 | - [ ] Was this discussed/approved via a Github issue? (no need for typos, doc improvements) 4 | - [ ] Did you read the [contributor guideline](https://github.com/pytorch/fairseq/blob/master/CONTRIBUTING.md)? 5 | - [ ] Did you make sure to update the docs? 6 | - [ ] Did you write any new necessary tests? 7 | 8 | ## What does this PR do? 9 | Fixes # (issue). 10 | 11 | ## PR review 12 | Anyone in the community is free to review the PR once the tests have passed. 13 | If we didn't discuss your PR in Github issues there's a high chance it will not be merged. 14 | 15 | ## Did you have fun? 16 | Make sure you had fun coding 🙃 17 | -------------------------------------------------------------------------------- /src/fairseq/.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: build 2 | 3 | on: 4 | # Trigger the workflow on push to master or any pull request 5 | push: 6 | branches: 7 | - master 8 | pull_request: 9 | 10 | jobs: 11 | build: 12 | 13 | strategy: 14 | max-parallel: 4 15 | matrix: 16 | platform: [ubuntu-latest, macos-latest] 17 | python-version: [3.6, 3.7] 18 | 19 | runs-on: ${{ matrix.platform }} 20 | 21 | steps: 22 | - uses: actions/checkout@v1 23 | - name: Set up Python ${{ matrix.python-version }} 24 | uses: actions/setup-python@v1 25 | with: 26 | python-version: ${{ matrix.python-version }} 27 | - name: Conditionally install pytorch 28 | if: matrix.platform == 'windows-latest' 29 | run: pip3 install torch -f https://download.pytorch.org/whl/torch_stable.html 30 | - name: Install locally 31 | run: | 32 | python -m pip install --upgrade pip 33 | python setup.py build_ext --inplace 34 | python -m pip install --editable . 35 | - name: Lint with flake8 36 | run: | 37 | pip install flake8 38 | # stop the build if there are Python syntax errors or undefined names 39 | flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics 40 | # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide 41 | flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics 42 | - name: Run tests 43 | run: | 44 | python setup.py test 45 | -------------------------------------------------------------------------------- /src/fairseq/.github/workflows/build_windows.yml: -------------------------------------------------------------------------------- 1 | name: build_windows 2 | 3 | on: 4 | # Trigger the workflow on push to master or any pull request 5 | push: 6 | branches: 7 | - master 8 | pull_request: 9 | 10 | jobs: 11 | build: 12 | 13 | strategy: 14 | max-parallel: 4 15 | matrix: 16 | platform: [windows-latest] 17 | python-version: [3.6, 3.7] 18 | 19 | runs-on: ${{ matrix.platform }} 20 | 21 | steps: 22 | - uses: actions/checkout@v1 23 | - name: Set up Python ${{ matrix.python-version }} 24 | uses: actions/setup-python@v1 25 | with: 26 | python-version: ${{ matrix.python-version }} 27 | - name: Conditionally install pytorch 28 | if: matrix.platform == 'windows-latest' 29 | run: pip3 install torch -f https://download.pytorch.org/whl/torch_stable.html 30 | - name: Install locally 31 | run: | 32 | python -m pip install --upgrade pip 33 | python setup.py build_ext --inplace 34 | python -m pip install --editable . 35 | - name: Lint with flake8 36 | run: | 37 | pip install flake8 38 | # stop the build if there are Python syntax errors or undefined names 39 | flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics 40 | # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide 41 | flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics 42 | - name: Run tests 43 | run: | 44 | python setup.py test 45 | -------------------------------------------------------------------------------- /src/fairseq/.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "fairseq/models/huggingface/transformers"] 2 | path = fairseq/models/huggingface/transformers 3 | url = https://github.com/myleott/transformers.git 4 | branch = fairseq 5 | [submodule "fairseq/model_parallel/megatron"] 6 | path = fairseq/model_parallel/megatron 7 | url = https://github.com/ngoyal2707/Megatron-LM 8 | branch = fairseq 9 | -------------------------------------------------------------------------------- /src/fairseq/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Facebook AI Research Sequence-to-Sequence Toolkit (fairseq) 2 | We want to make contributing to this project as easy and transparent as 3 | possible. 4 | 5 | ## Pull Requests 6 | We actively welcome your pull requests. 7 | 8 | 1. Fork the repo and create your branch from `master`. 9 | 2. If you've added code that should be tested, add tests. 10 | 3. If you've changed APIs, update the documentation. 11 | 4. Ensure the test suite passes. 12 | 5. Make sure your code lints. 13 | 6. If you haven't already, complete the Contributor License Agreement ("CLA"). 14 | 15 | ## Contributor License Agreement ("CLA") 16 | In order to accept your pull request, we need you to submit a CLA. You only need 17 | to do this once to work on any of Facebook's open source projects. 18 | 19 | Complete your CLA here: 20 | 21 | ## Issues 22 | We use GitHub issues to track public bugs. Please ensure your description is 23 | clear and has sufficient instructions to be able to reproduce the issue. 24 | 25 | ## License 26 | By contributing to Facebook AI Research Sequence-to-Sequence Toolkit (fairseq), 27 | you agree that your contributions will be licensed under the LICENSE file in 28 | the root directory of this source tree. 29 | -------------------------------------------------------------------------------- /src/fairseq/LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Facebook, Inc. and its affiliates. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/fairseq/docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = python -msphinx 7 | SPHINXPROJ = fairseq 8 | SOURCEDIR = . 9 | BUILDDIR = _build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) -------------------------------------------------------------------------------- /src/fairseq/docs/_static/theme_overrides.css: -------------------------------------------------------------------------------- 1 | .wy-table-responsive table td kbd { 2 | white-space: nowrap; 3 | } 4 | .wy-table-responsive table td { 5 | white-space: normal !important; 6 | } 7 | .wy-table-responsive { 8 | overflow: visible !important; 9 | } 10 | -------------------------------------------------------------------------------- /src/fairseq/docs/command_line_tools.rst: -------------------------------------------------------------------------------- 1 | .. _Command-line Tools: 2 | 3 | Command-line Tools 4 | ================== 5 | 6 | Fairseq provides several command-line tools for training and evaluating models: 7 | 8 | - :ref:`fairseq-preprocess`: Data pre-processing: build vocabularies and binarize training data 9 | - :ref:`fairseq-train`: Train a new model on one or multiple GPUs 10 | - :ref:`fairseq-generate`: Translate pre-processed data with a trained model 11 | - :ref:`fairseq-interactive`: Translate raw text with a trained model 12 | - :ref:`fairseq-score`: BLEU scoring of generated translations against reference translations 13 | - :ref:`fairseq-eval-lm`: Language model evaluation 14 | 15 | 16 | .. _fairseq-preprocess: 17 | 18 | fairseq-preprocess 19 | ~~~~~~~~~~~~~~~~~~ 20 | .. automodule:: preprocess 21 | 22 | .. argparse:: 23 | :module: fairseq.options 24 | :func: get_preprocessing_parser 25 | :prog: fairseq-preprocess 26 | 27 | 28 | .. _fairseq-train: 29 | 30 | fairseq-train 31 | ~~~~~~~~~~~~~ 32 | .. automodule:: train 33 | 34 | .. argparse:: 35 | :module: fairseq.options 36 | :func: get_training_parser 37 | :prog: fairseq-train 38 | 39 | 40 | .. _fairseq-generate: 41 | 42 | fairseq-generate 43 | ~~~~~~~~~~~~~~~~ 44 | .. automodule:: generate 45 | 46 | .. argparse:: 47 | :module: fairseq.options 48 | :func: get_generation_parser 49 | :prog: fairseq-generate 50 | 51 | 52 | .. _fairseq-interactive: 53 | 54 | fairseq-interactive 55 | ~~~~~~~~~~~~~~~~~~~ 56 | .. automodule:: interactive 57 | 58 | .. argparse:: 59 | :module: fairseq.options 60 | :func: get_interactive_generation_parser 61 | :prog: fairseq-interactive 62 | 63 | 64 | .. _fairseq-score: 65 | 66 | fairseq-score 67 | ~~~~~~~~~~~~~ 68 | .. automodule:: score 69 | 70 | .. argparse:: 71 | :module: fairseq_cli.score 72 | :func: get_parser 73 | :prog: fairseq-score 74 | 75 | 76 | .. _fairseq-eval-lm: 77 | 78 | fairseq-eval-lm 79 | ~~~~~~~~~~~~~~~ 80 | .. automodule:: eval_lm 81 | 82 | .. argparse:: 83 | :module: fairseq.options 84 | :func: get_eval_lm_parser 85 | :prog: fairseq-eval-lm 86 | -------------------------------------------------------------------------------- /src/fairseq/docs/criterions.rst: -------------------------------------------------------------------------------- 1 | .. role:: hidden 2 | :class: hidden-section 3 | 4 | .. _Criterions: 5 | 6 | Criterions 7 | ========== 8 | 9 | Criterions compute the loss function given the model and batch, roughly:: 10 | 11 | loss = criterion(model, batch) 12 | 13 | .. automodule:: fairseq.criterions 14 | :members: 15 | 16 | .. autoclass:: fairseq.criterions.FairseqCriterion 17 | :members: 18 | :undoc-members: 19 | 20 | .. autoclass:: fairseq.criterions.adaptive_loss.AdaptiveLoss 21 | :members: 22 | :undoc-members: 23 | .. autoclass:: fairseq.criterions.composite_loss.CompositeLoss 24 | :members: 25 | :undoc-members: 26 | .. autoclass:: fairseq.criterions.cross_entropy.CrossEntropyCriterion 27 | :members: 28 | :undoc-members: 29 | .. autoclass:: fairseq.criterions.label_smoothed_cross_entropy.LabelSmoothedCrossEntropyCriterion 30 | :members: 31 | :undoc-members: 32 | -------------------------------------------------------------------------------- /src/fairseq/docs/data.rst: -------------------------------------------------------------------------------- 1 | .. role:: hidden 2 | :class: hidden-section 3 | 4 | .. module:: fairseq.data 5 | 6 | Data Loading and Utilities 7 | ========================== 8 | 9 | .. _datasets: 10 | 11 | Datasets 12 | -------- 13 | 14 | **Datasets** define the data format and provide helpers for creating 15 | mini-batches. 16 | 17 | .. autoclass:: fairseq.data.FairseqDataset 18 | :members: 19 | .. autoclass:: fairseq.data.LanguagePairDataset 20 | :members: 21 | .. autoclass:: fairseq.data.MonolingualDataset 22 | :members: 23 | 24 | **Helper Datasets** 25 | 26 | These datasets wrap other :class:`fairseq.data.FairseqDataset` instances and 27 | provide additional functionality: 28 | 29 | .. autoclass:: fairseq.data.BacktranslationDataset 30 | :members: 31 | .. autoclass:: fairseq.data.ConcatDataset 32 | :members: 33 | .. autoclass:: fairseq.data.ResamplingDataset 34 | :members: 35 | .. autoclass:: fairseq.data.RoundRobinZipDatasets 36 | :members: 37 | .. autoclass:: fairseq.data.TransformEosDataset 38 | :members: 39 | 40 | 41 | Dictionary 42 | ---------- 43 | 44 | .. autoclass:: fairseq.data.Dictionary 45 | :members: 46 | 47 | 48 | Iterators 49 | --------- 50 | 51 | .. autoclass:: fairseq.data.CountingIterator 52 | :members: 53 | .. autoclass:: fairseq.data.EpochBatchIterator 54 | :members: 55 | .. autoclass:: fairseq.data.GroupedIterator 56 | :members: 57 | .. autoclass:: fairseq.data.ShardedIterator 58 | :members: 59 | -------------------------------------------------------------------------------- /src/fairseq/docs/docutils.conf: -------------------------------------------------------------------------------- 1 | [writers] 2 | option-limit=0 3 | -------------------------------------------------------------------------------- /src/fairseq/docs/index.rst: -------------------------------------------------------------------------------- 1 | .. fairseq documentation master file, created by 2 | sphinx-quickstart on Fri Aug 17 21:45:30 2018. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | :github_url: https://github.com/pytorch/fairseq 7 | 8 | 9 | fairseq documentation 10 | ===================== 11 | 12 | Fairseq is a sequence modeling toolkit written in `PyTorch 13 | `_ that allows researchers and developers to 14 | train custom models for translation, summarization, language modeling and other 15 | text generation tasks. 16 | 17 | .. toctree:: 18 | :maxdepth: 1 19 | :caption: Getting Started 20 | 21 | getting_started 22 | command_line_tools 23 | 24 | .. toctree:: 25 | :maxdepth: 1 26 | :caption: Extending Fairseq 27 | 28 | overview 29 | tutorial_simple_lstm 30 | tutorial_classifying_names 31 | 32 | .. toctree:: 33 | :maxdepth: 2 34 | :caption: Library Reference 35 | 36 | tasks 37 | models 38 | criterions 39 | optim 40 | lr_scheduler 41 | data 42 | modules 43 | 44 | 45 | Indices and tables 46 | ================== 47 | 48 | * :ref:`genindex` 49 | * :ref:`search` 50 | -------------------------------------------------------------------------------- /src/fairseq/docs/lr_scheduler.rst: -------------------------------------------------------------------------------- 1 | .. role:: hidden 2 | :class: hidden-section 3 | 4 | .. _Learning Rate Schedulers: 5 | 6 | Learning Rate Schedulers 7 | ======================== 8 | 9 | Learning Rate Schedulers update the learning rate over the course of training. 10 | Learning rates can be updated after each update via :func:`step_update` or at 11 | epoch boundaries via :func:`step`. 12 | 13 | .. automodule:: fairseq.optim.lr_scheduler 14 | :members: 15 | 16 | .. autoclass:: fairseq.optim.lr_scheduler.FairseqLRScheduler 17 | :members: 18 | :undoc-members: 19 | 20 | .. autoclass:: fairseq.optim.lr_scheduler.cosine_lr_scheduler.CosineSchedule 21 | :members: 22 | :undoc-members: 23 | .. autoclass:: fairseq.optim.lr_scheduler.fixed_schedule.FixedSchedule 24 | :members: 25 | :undoc-members: 26 | .. autoclass:: fairseq.optim.lr_scheduler.inverse_square_root_schedule.InverseSquareRootSchedule 27 | :members: 28 | :undoc-members: 29 | .. autoclass:: fairseq.optim.lr_scheduler.reduce_lr_on_plateau.ReduceLROnPlateau 30 | :members: 31 | :undoc-members: 32 | .. autoclass:: fairseq.optim.lr_scheduler.triangular_lr_scheduler.TriangularSchedule 33 | :members: 34 | :undoc-members: 35 | -------------------------------------------------------------------------------- /src/fairseq/docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | pushd %~dp0 4 | 5 | REM Command file for Sphinx documentation 6 | 7 | if "%SPHINXBUILD%" == "" ( 8 | set SPHINXBUILD=python -msphinx 9 | ) 10 | set SOURCEDIR=. 11 | set BUILDDIR=_build 12 | set SPHINXPROJ=fairseq 13 | 14 | if "%1" == "" goto help 15 | 16 | %SPHINXBUILD% >NUL 2>NUL 17 | if errorlevel 9009 ( 18 | echo. 19 | echo.The Sphinx module was not found. Make sure you have Sphinx installed, 20 | echo.then set the SPHINXBUILD environment variable to point to the full 21 | echo.path of the 'sphinx-build' executable. Alternatively you may add the 22 | echo.Sphinx directory to PATH. 23 | echo. 24 | echo.If you don't have Sphinx installed, grab it from 25 | echo.http://sphinx-doc.org/ 26 | exit /b 1 27 | ) 28 | 29 | %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% 30 | goto end 31 | 32 | :help 33 | %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% 34 | 35 | :end 36 | popd 37 | -------------------------------------------------------------------------------- /src/fairseq/docs/modules.rst: -------------------------------------------------------------------------------- 1 | Modules 2 | ======= 3 | 4 | Fairseq provides several stand-alone :class:`torch.nn.Module` classes that may 5 | be helpful when implementing a new :class:`~fairseq.models.BaseFairseqModel`. 6 | 7 | .. automodule:: fairseq.modules 8 | :members: 9 | :undoc-members: 10 | -------------------------------------------------------------------------------- /src/fairseq/docs/optim.rst: -------------------------------------------------------------------------------- 1 | .. role:: hidden 2 | :class: hidden-section 3 | 4 | .. _optimizers: 5 | 6 | Optimizers 7 | ========== 8 | 9 | Optimizers update the Model parameters based on the gradients. 10 | 11 | .. automodule:: fairseq.optim 12 | :members: 13 | 14 | .. autoclass:: fairseq.optim.FairseqOptimizer 15 | :members: 16 | :undoc-members: 17 | 18 | .. autoclass:: fairseq.optim.adadelta.Adadelta 19 | :members: 20 | :undoc-members: 21 | .. autoclass:: fairseq.optim.adagrad.Adagrad 22 | :members: 23 | :undoc-members: 24 | .. autoclass:: fairseq.optim.adafactor.FairseqAdafactor 25 | :members: 26 | :undoc-members: 27 | .. autoclass:: fairseq.optim.adam.FairseqAdam 28 | :members: 29 | :undoc-members: 30 | .. autoclass:: fairseq.optim.fp16_optimizer.FP16Optimizer 31 | :members: 32 | :undoc-members: 33 | .. autoclass:: fairseq.optim.nag.FairseqNAG 34 | :members: 35 | :undoc-members: 36 | .. autoclass:: fairseq.optim.sgd.SGD 37 | :members: 38 | :undoc-members: 39 | -------------------------------------------------------------------------------- /src/fairseq/docs/requirements.txt: -------------------------------------------------------------------------------- 1 | sphinx<2.0 2 | sphinx-argparse 3 | -------------------------------------------------------------------------------- /src/fairseq/docs/tasks.rst: -------------------------------------------------------------------------------- 1 | .. role:: hidden 2 | :class: hidden-section 3 | 4 | .. module:: fairseq.tasks 5 | 6 | .. _Tasks: 7 | 8 | Tasks 9 | ===== 10 | 11 | Tasks store dictionaries and provide helpers for loading/iterating over 12 | Datasets, initializing the Model/Criterion and calculating the loss. 13 | 14 | Tasks can be selected via the ``--task`` command-line argument. Once selected, a 15 | task may expose additional command-line arguments for further configuration. 16 | 17 | Example usage:: 18 | 19 | # setup the task (e.g., load dictionaries) 20 | task = fairseq.tasks.setup_task(args) 21 | 22 | # build model and criterion 23 | model = task.build_model(args) 24 | criterion = task.build_criterion(args) 25 | 26 | # load datasets 27 | task.load_dataset('train') 28 | task.load_dataset('valid') 29 | 30 | # iterate over mini-batches of data 31 | batch_itr = task.get_batch_iterator( 32 | task.dataset('train'), max_tokens=4096, 33 | ) 34 | for batch in batch_itr: 35 | # compute the loss 36 | loss, sample_size, logging_output = task.get_loss( 37 | model, criterion, batch, 38 | ) 39 | loss.backward() 40 | 41 | 42 | Translation 43 | ----------- 44 | 45 | .. autoclass:: fairseq.tasks.translation.TranslationTask 46 | 47 | .. _language modeling: 48 | 49 | Language Modeling 50 | ----------------- 51 | 52 | .. autoclass:: fairseq.tasks.language_modeling.LanguageModelingTask 53 | 54 | 55 | Adding new tasks 56 | ---------------- 57 | 58 | .. autofunction:: fairseq.tasks.register_task 59 | .. autoclass:: fairseq.tasks.FairseqTask 60 | :members: 61 | :undoc-members: 62 | -------------------------------------------------------------------------------- /src/fairseq/eval_lm.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 -u 2 | # Copyright (c) Facebook, Inc. and its affiliates. 3 | # 4 | # This source code is licensed under the MIT license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | 7 | from fairseq_cli.eval_lm import cli_main 8 | 9 | 10 | if __name__ == '__main__': 11 | cli_main() 12 | -------------------------------------------------------------------------------- /src/fairseq/examples/.gitignore: -------------------------------------------------------------------------------- 1 | !*/*.sh 2 | !*/*.md 3 | -------------------------------------------------------------------------------- /src/fairseq/examples/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | __version__ = '0.9.0' 7 | 8 | import examples.noisychannel # noqa 9 | -------------------------------------------------------------------------------- /src/fairseq/examples/backtranslation/deduplicate_lines.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Copyright (c) Facebook, Inc. and its affiliates. 3 | # 4 | # This source code is licensed under the MIT license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | 7 | import argparse 8 | import fileinput 9 | import hashlib 10 | from multiprocessing import Pool 11 | import sys 12 | 13 | 14 | def get_hashes_and_lines(raw_line): 15 | hash = hashlib.md5(raw_line).hexdigest() 16 | return hash, raw_line 17 | 18 | 19 | def main(): 20 | parser = argparse.ArgumentParser() 21 | parser.add_argument('--workers', type=int, default=10) 22 | parser.add_argument('files', nargs='*', help='input files') 23 | args = parser.parse_args() 24 | 25 | seen = set() 26 | with fileinput.input(args.files, mode='rb') as h: 27 | pool = Pool(args.workers) 28 | results = pool.imap_unordered(get_hashes_and_lines, h, 1000) 29 | for i, (hash, raw_line) in enumerate(results): 30 | if hash not in seen: 31 | seen.add(hash) 32 | sys.stdout.buffer.write(raw_line) 33 | if i % 1000000 == 0: 34 | print(i, file=sys.stderr, end="", flush=True) 35 | elif i % 100000 == 0: 36 | print(".", file=sys.stderr, end="", flush=True) 37 | print(file=sys.stderr, flush=True) 38 | 39 | 40 | if __name__ == '__main__': 41 | main() 42 | -------------------------------------------------------------------------------- /src/fairseq/examples/backtranslation/sacrebleu.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if [ $# -ne 5 ]; then 4 | echo "usage: $0 [dataset=wmt14/full] [langpair=en-de] [databin] [bpecode] [model]" 5 | exit 6 | fi 7 | 8 | 9 | DATASET=$1 10 | LANGPAIR=$2 11 | DATABIN=$3 12 | BPECODE=$4 13 | MODEL=$5 14 | 15 | SRCLANG=$(echo $LANGPAIR | cut -d '-' -f 1) 16 | TGTLANG=$(echo $LANGPAIR | cut -d '-' -f 2) 17 | 18 | 19 | BPEROOT=examples/backtranslation/subword-nmt/subword_nmt 20 | if [ ! -e $BPEROOT ]; then 21 | BPEROOT=subword-nmt/subword_nmt 22 | if [ ! -e $BPEROOT ]; then 23 | echo 'Cloning Subword NMT repository (for BPE pre-processing)...' 24 | git clone https://github.com/rsennrich/subword-nmt.git 25 | fi 26 | fi 27 | 28 | 29 | sacrebleu -t $DATASET -l $LANGPAIR --echo src \ 30 | | sacremoses tokenize -a -l $SRCLANG -q \ 31 | | python $BPEROOT/apply_bpe.py -c $BPECODE \ 32 | | fairseq-interactive $DATABIN --path $MODEL \ 33 | -s $SRCLANG -t $TGTLANG \ 34 | --beam 5 --remove-bpe --buffer-size 1024 --max-tokens 8000 \ 35 | | grep ^H- | cut -f 3- \ 36 | | sacremoses detokenize -l $TGTLANG -q \ 37 | | sacrebleu -t $DATASET -l $LANGPAIR 38 | -------------------------------------------------------------------------------- /src/fairseq/examples/backtranslation/tokenized_bleu.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if [ $# -ne 5 ]; then 4 | echo "usage: $0 [dataset=wmt14/full] [langpair=en-de] [databin] [bpecode] [model]" 5 | exit 6 | fi 7 | 8 | 9 | DATASET=$1 10 | LANGPAIR=$2 11 | DATABIN=$3 12 | BPECODE=$4 13 | MODEL=$5 14 | 15 | SRCLANG=$(echo $LANGPAIR | cut -d '-' -f 1) 16 | TGTLANG=$(echo $LANGPAIR | cut -d '-' -f 2) 17 | 18 | 19 | BPEROOT=examples/backtranslation/subword-nmt/subword_nmt 20 | if [ ! -e $BPEROOT ]; then 21 | BPEROOT=subword-nmt/subword_nmt 22 | if [ ! -e $BPEROOT ]; then 23 | echo 'Cloning Subword NMT repository (for BPE pre-processing)...' 24 | git clone https://github.com/rsennrich/subword-nmt.git 25 | fi 26 | fi 27 | 28 | 29 | TMP_REF=$(mktemp) 30 | 31 | sacrebleu -t $DATASET -l $LANGPAIR --echo ref -q \ 32 | | sacremoses normalize -l $TGTLANG -q \ 33 | | sacremoses tokenize -a -l $TGTLANG -q \ 34 | > $TMP_REF 35 | 36 | sacrebleu -t $DATASET -l $LANGPAIR --echo src -q \ 37 | | sacremoses normalize -l $SRCLANG -q \ 38 | | sacremoses tokenize -a -l $SRCLANG -q \ 39 | | python $BPEROOT/apply_bpe.py -c $BPECODE \ 40 | | python interactive.py $DATABIN --path $MODEL \ 41 | -s $SRCLANG -t $TGTLANG \ 42 | --beam 5 --remove-bpe --buffer-size 1024 --max-tokens 8000 \ 43 | | grep ^H- | cut -f 3- \ 44 | | python score.py --ref $TMP_REF 45 | 46 | rm -f $TMP_REF 47 | -------------------------------------------------------------------------------- /src/fairseq/examples/byte_level_bpe/get_data.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Copyright (c) Facebook, Inc. and its affiliates. 4 | # 5 | # This source code is licensed under the MIT license found in the 6 | # LICENSE file in the root directory of this source tree. 7 | 8 | PY_BIN_ROOT= 9 | 10 | # PyPI dependency 11 | ${PY_BIN_ROOT}pip install sentencepiece sacremoses 12 | 13 | # Get data 14 | if [ ! -d "data" ]; then 15 | mkdir data 16 | fi 17 | 18 | if [ ! -f "data/fr-en.tgz" ]; then 19 | wget https://wit3.fbk.eu/archive/2017-01-trnted/texts/fr/en/fr-en.tgz -P data 20 | tar xvf data/fr-en.tgz -C data 21 | fi 22 | ${PY_BIN_ROOT}python get_bitext.py --bpe-vocab 16384 --byte-vocab --char-vocab 23 | for VOCAB_SIZE in 2048 4096; do 24 | ${PY_BIN_ROOT}python get_bitext.py --bpe-vocab ${VOCAB_SIZE} --bbpe-vocab ${VOCAB_SIZE} 25 | done 26 | rm -r data/fr-en data/fr-en.tgz 27 | 28 | # Generate binary dataset 29 | ${PY_BIN_ROOT}/fairseq-preprocess --source-lang fr --target-lang en --destdir data/bin_bpe16384 --joined-dictionary \ 30 | --workers "$(nproc)" --trainpref data/train.moses.bpe16384 --validpref data/valid.moses.bpe16384 \ 31 | --testpref data/test.moses.bpe16384 32 | 33 | ${PY_BIN_ROOT}/fairseq-preprocess --source-lang fr --target-lang en --destdir data/bin_bytes --joined-dictionary \ 34 | --workers "$(nproc)" --trainpref data/train.moses.bytes --validpref data/valid.moses.bytes \ 35 | --testpref data/test.moses.bytes 36 | 37 | ${PY_BIN_ROOT}/fairseq-preprocess --source-lang fr --target-lang en --destdir data/bin_chars --joined-dictionary \ 38 | --workers "$(nproc)" --trainpref data/train.moses.chars --validpref data/valid.moses.chars \ 39 | --testpref data/test.moses.chars 40 | 41 | for VOCAB_SIZE in 2048 4096; do 42 | for TYPE in bbpe bpe; do 43 | ${PY_BIN_ROOT}/fairseq-preprocess --source-lang fr --target-lang en --destdir "data/bin_${TYPE}${VOCAB_SIZE}" \ 44 | --joined-dictionary --workers "$(nproc)" --trainpref "data/train.moses.${TYPE}${VOCAB_SIZE}" \ 45 | --validpref "data/valid.moses.${TYPE}${VOCAB_SIZE}" --testpref "data/test.moses.${TYPE}${VOCAB_SIZE}" 46 | done 47 | done 48 | -------------------------------------------------------------------------------- /src/fairseq/examples/conv_seq2seq/README.md: -------------------------------------------------------------------------------- 1 | # Convolutional Sequence to Sequence Learning (Gehring et al., 2017) 2 | 3 | ## Pre-trained models 4 | 5 | Description | Dataset | Model | Test set(s) 6 | ---|---|---|--- 7 | Convolutional
([Gehring et al., 2017](https://arxiv.org/abs/1705.03122)) | [WMT14 English-French](http://statmt.org/wmt14/translation-task.html#Download) | [download (.tar.bz2)](https://dl.fbaipublicfiles.com/fairseq/models/wmt14.v2.en-fr.fconv-py.tar.bz2) | newstest2014:
[download (.tar.bz2)](https://dl.fbaipublicfiles.com/fairseq/data/wmt14.v2.en-fr.newstest2014.tar.bz2)
newstest2012/2013:
[download (.tar.bz2)](https://dl.fbaipublicfiles.com/fairseq/data/wmt14.v2.en-fr.ntst1213.tar.bz2) 8 | Convolutional
([Gehring et al., 2017](https://arxiv.org/abs/1705.03122)) | [WMT14 English-German](http://statmt.org/wmt14/translation-task.html#Download) | [download (.tar.bz2)](https://dl.fbaipublicfiles.com/fairseq/models/wmt14.en-de.fconv-py.tar.bz2) | newstest2014:
[download (.tar.bz2)](https://dl.fbaipublicfiles.com/fairseq/data/wmt14.en-de.newstest2014.tar.bz2) 9 | Convolutional
([Gehring et al., 2017](https://arxiv.org/abs/1705.03122)) | [WMT17 English-German](http://statmt.org/wmt17/translation-task.html#Download) | [download (.tar.bz2)](https://dl.fbaipublicfiles.com/fairseq/models/wmt17.v2.en-de.fconv-py.tar.bz2) | newstest2014:
[download (.tar.bz2)](https://dl.fbaipublicfiles.com/fairseq/data/wmt17.v2.en-de.newstest2014.tar.bz2) 10 | 11 | ## Example usage 12 | 13 | See the [translation README](../translation/README.md) for instructions on reproducing results for WMT'14 En-De and 14 | WMT'14 En-Fr using the `fconv_wmt_en_de` and `fconv_wmt_en_fr` model architectures. 15 | 16 | ## Citation 17 | 18 | ```bibtex 19 | @inproceedings{gehring2017convs2s, 20 | title = {Convolutional Sequence to Sequence Learning}, 21 | author = {Gehring, Jonas, and Auli, Michael and Grangier, David and Yarats, Denis and Dauphin, Yann N}, 22 | booktitle = {Proc. of ICML}, 23 | year = 2017, 24 | } 25 | ``` 26 | -------------------------------------------------------------------------------- /src/fairseq/examples/language_model/README.adaptive_inputs.md: -------------------------------------------------------------------------------- 1 | # Adaptive Input Representations for Neural Language Modeling (Baevski and Auli, 2018) 2 | 3 | ## Pre-trained models 4 | 5 | Description | Parameters | Dataset | Model and Test set(s) 6 | ---|---:|---|--- 7 | Adaptive Inputs
([Baevski and Auli, 2018](https://arxiv.org/abs/1809.10853)) | 1026M | [Google Billion Words](https://github.com/ciprian-chelba/1-billion-word-language-modeling-benchmark) | [download (.tar.bz2)](https://dl.fbaipublicfiles.com/fairseq/models/lm/adaptive_lm_gbw_huge.tar.bz2) 8 | Adaptive Inputs
([Baevski and Auli, 2018](https://arxiv.org/abs/1809.10853)) | 247M | [WikiText-103](https://blog.einstein.ai/the-wikitext-long-term-dependency-language-modeling-dataset/) | [download (.tar.bz2)](https://dl.fbaipublicfiles.com/fairseq/models/lm/adaptive_lm_wiki103.v2.tar.bz2) 9 | 10 | ## Training an LM with adaptive inputs 11 | 12 | First, see the general [language modeling README](README.md) for instructions on 13 | preprocessing the WikiText-103 data. 14 | 15 | Then use the following training command to train a model with adaptive inputs 16 | using the `transformer_lm_wiki103` model architecture: 17 | ```bash 18 | fairseq-train --task language_modeling \ 19 | data-bin/wikitext-103 \ 20 | --save-dir checkpoints/transformer_wikitext-103 \ 21 | --arch transformer_lm_wiki103 \ 22 | --max-update 286000 --max-lr 1.0 --t-mult 2 --lr-period-updates 270000 --lr-scheduler cosine --lr-shrink 0.75 \ 23 | --warmup-updates 16000 --warmup-init-lr 1e-07 --min-lr 1e-09 --optimizer nag --lr 0.0001 --clip-norm 0.1 \ 24 | --criterion adaptive_loss --max-tokens 3072 --update-freq 3 --tokens-per-sample 3072 --seed 1 \ 25 | --sample-break-mode none --skip-invalid-size-inputs-valid-test --ddp-backend=no_c10d 26 | ``` 27 | 28 | ## Citation 29 | 30 | ```bibtex 31 | @inproceedings{ 32 | baevski2018adaptive, 33 | title={Adaptive Input Representations for Neural Language Modeling}, 34 | author={Alexei Baevski and Michael Auli}, 35 | booktitle={International Conference on Learning Representations}, 36 | year={2019}, 37 | url={https://openreview.net/forum?id=ByxZX20qFQ}, 38 | } 39 | ``` 40 | -------------------------------------------------------------------------------- /src/fairseq/examples/language_model/README.conv.md: -------------------------------------------------------------------------------- 1 | # Language Modeling with Gated Convolutional Networks (Dauphin et al., 2017) 2 | 3 | ## Example usage 4 | 5 | First download and preprocess the data following the main [language modeling README](README.md). 6 | 7 | Then to train a convolutional LM using the `fconv_lm_dauphin_wikitext103` 8 | architecture: 9 | ```bash 10 | fairseq-train --task language_modeling \ 11 | data-bin/wikitext-103 \ 12 | --save-dir checkpoints/fconv_wikitext-103 \ 13 | --arch fconv_lm_dauphin_wikitext103 \ 14 | --max-epoch 35 \ --optimizer nag \ 15 | --lr 1.0 --lr-scheduler reduce_lr_on_plateau --lr-shrink 0.5 \ 16 | --clip-norm 0.1 --dropout 0.2 --weight-decay 5e-06 --criterion adaptive_loss \ 17 | --adaptive-softmax-cutoff 10000,20000,200000 --max-tokens 1024 --tokens-per-sample 1024 \ 18 | --ddp-backend=no_c10d 19 | ``` 20 | 21 | And evaluate with: 22 | ```bash 23 | fairseq-eval-lm data-bin/wikitext-103 --path checkpoints/fconv_wiki103/checkpoint_best.pt 24 | ``` 25 | 26 | ## Citation 27 | 28 | ```bibtex 29 | @inproceedings{dauphin2017language, 30 | title={Language Modeling with Gated Convolutional Networks}, 31 | author={Dauphin, Yann N and Fan, Angela and Auli, Michael and Grangier, David}, 32 | booktitle={Proceedings of the 34th International Conference on Machine Learning-Volume 70}, 33 | pages={933--941}, 34 | year={2017}, 35 | organization={JMLR} 36 | } 37 | ``` 38 | -------------------------------------------------------------------------------- /src/fairseq/examples/language_model/prepare-wikitext-103.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Adapted from https://github.com/facebookresearch/MIXER/blob/master/prepareData.sh 3 | 4 | URLS=( 5 | "https://s3.amazonaws.com/research.metamind.io/wikitext/wikitext-103-v1.zip" 6 | ) 7 | FILES=( 8 | "wikitext-103-v1.zip" 9 | ) 10 | 11 | for ((i=0;i<${#URLS[@]};++i)); do 12 | file=${FILES[i]} 13 | if [ -f $file ]; then 14 | echo "$file already exists, skipping download" 15 | else 16 | url=${URLS[i]} 17 | wget "$url" 18 | if [ -f $file ]; then 19 | echo "$url successfully downloaded." 20 | else 21 | echo "$url not successfully downloaded." 22 | exit -1 23 | fi 24 | if [ ${file: -4} == ".tgz" ]; then 25 | tar zxvf $file 26 | elif [ ${file: -4} == ".tar" ]; then 27 | tar xvf $file 28 | elif [ ${file: -4} == ".zip" ]; then 29 | unzip $file 30 | fi 31 | fi 32 | done 33 | cd .. 34 | -------------------------------------------------------------------------------- /src/fairseq/examples/megatron_11b/detok.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 -u 2 | # Copyright (c) Facebook, Inc. and its affiliates. 3 | # 4 | # This source code is licensed under the MIT license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | 7 | import argparse 8 | import fileinput 9 | import sacremoses 10 | 11 | 12 | def main(): 13 | parser = argparse.ArgumentParser(description='') 14 | parser.add_argument('files', nargs='*', help='input files') 15 | args = parser.parse_args() 16 | 17 | detok = sacremoses.MosesDetokenizer() 18 | 19 | for line in fileinput.input(args.files, openhook=fileinput.hook_compressed): 20 | print(detok.detokenize(line.strip().split(' ')).replace(' @', '').replace('@ ', '').replace(' =', '=').replace('= ', '=').replace(' – ', '–')) 21 | 22 | 23 | if __name__ == '__main__': 24 | main() 25 | -------------------------------------------------------------------------------- /src/fairseq/examples/noisychannel/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from .rerank_options import * # noqa 7 | -------------------------------------------------------------------------------- /src/fairseq/examples/noisychannel/rerank_score_lm.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import os 7 | 8 | from fairseq import options 9 | 10 | from . import rerank_options, rerank_utils 11 | 12 | 13 | def score_lm(args): 14 | using_nbest = args.nbest_list is not None 15 | pre_gen, left_to_right_preprocessed_dir, right_to_left_preprocessed_dir, \ 16 | backwards_preprocessed_dir, lm_preprocessed_dir = \ 17 | rerank_utils.get_directories(args.data_dir_name, args.num_rescore, args.gen_subset, 18 | args.gen_model_name, args.shard_id, args.num_shards, 19 | args.sampling, args.prefix_len, args.target_prefix_frac, 20 | args.source_prefix_frac) 21 | 22 | predictions_bpe_file = pre_gen+"/generate_output_bpe.txt" 23 | if using_nbest: 24 | print("Using predefined n-best list from interactive.py") 25 | predictions_bpe_file = args.nbest_list 26 | 27 | gen_output = rerank_utils.BitextOutputFromGen(predictions_bpe_file, bpe_symbol=args.remove_bpe, nbest=using_nbest) 28 | 29 | if args.language_model is not None: 30 | lm_score_file = rerank_utils.rescore_file_name(pre_gen, args.prefix_len, args.lm_name, lm_file=True) 31 | 32 | if args.language_model is not None and not os.path.isfile(lm_score_file): 33 | print("STEP 4.5: language modeling for P(T)") 34 | if args.lm_bpe_code is None: 35 | bpe_status = "no bpe" 36 | elif args.lm_bpe_code == "shared": 37 | bpe_status = "shared" 38 | else: 39 | bpe_status = "different" 40 | 41 | rerank_utils.lm_scoring(lm_preprocessed_dir, bpe_status, gen_output, pre_gen, 42 | args.lm_dict, args.lm_name, args.language_model, 43 | args.lm_bpe_code, 128, lm_score_file, args.target_lang, 44 | args.source_lang, prefix_len=args.prefix_len) 45 | 46 | 47 | def cli_main(): 48 | parser = rerank_options.get_reranking_parser() 49 | args = options.parse_args_and_arch(parser) 50 | score_lm(args) 51 | 52 | 53 | if __name__ == '__main__': 54 | cli_main() 55 | -------------------------------------------------------------------------------- /src/fairseq/examples/quant_noise/transformer_quantization_config.yaml: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | # This file defines example configuration arguments for quantizing 7 | # a transformer model with product quantization 8 | 9 | # Number of Centroids for Product Quantization, by default 256 (byte-aligned) 10 | n_centroids: 11 | Linear: 12 | key: in_features 13 | value: {"*": 256} 14 | Embedding: 15 | key: embedding_dim 16 | value: {"*": 256} 17 | 18 | # Block Sizes for Product Quantization 19 | # We suggest: 8 for FFN, 4 for ATTN, 4 for embedding projections, 8 for embeddings 20 | block_sizes: 21 | Linear: 22 | key: fuzzy_name 23 | value: {fc: 8, attn: 4, emb: 4} 24 | Embedding: 25 | key: fuzzy_name 26 | value: {emb: 8} 27 | 28 | # Layers to Quantize Sequentially 29 | # We suggest: first FFN, then EMB, then ATTN 30 | layers_to_quantize: 31 | - decoder\\.layers\\.\d+\\.fc[12] 32 | - decoder\\.embed_tokens\\.embeddings\\.[012]\\.[01] 33 | - decoder\\.layers\\.\d+\\.self_attn\\.(k_proj|v_proj|q_proj|out_proj) 34 | -------------------------------------------------------------------------------- /src/fairseq/examples/roberta/commonsense_qa/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from . import commonsense_qa_task # noqa 7 | -------------------------------------------------------------------------------- /src/fairseq/examples/roberta/commonsense_qa/download_cqa_data.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Copyright (c) Facebook, Inc. and its affiliates. 3 | # 4 | # This source code is licensed under the MIT license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | 7 | OUTDIR=data/CommonsenseQA 8 | 9 | mkdir -p $OUTDIR 10 | 11 | wget -O $OUTDIR/train.jsonl https://s3.amazonaws.com/commensenseqa/train_rand_split.jsonl 12 | wget -O $OUTDIR/valid.jsonl https://s3.amazonaws.com/commensenseqa/dev_rand_split.jsonl 13 | wget -O $OUTDIR/test.jsonl https://s3.amazonaws.com/commensenseqa/test_rand_split_no_answers.jsonl 14 | wget -O $OUTDIR/dict.txt https://dl.fbaipublicfiles.com/fairseq/gpt2_bpe/dict.txt 15 | -------------------------------------------------------------------------------- /src/fairseq/examples/roberta/preprocess_RACE.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Copyright (c) Facebook, Inc. and its affiliates. 3 | # 4 | # This source code is licensed under the MIT license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | 7 | 8 | # data should be downloaded and processed with reprocess_RACE.py 9 | if [[ $# -ne 2 ]]; then 10 | echo "Run as following:" 11 | echo "./examples/roberta/preprocess_RACE.sh " 12 | exit 1 13 | fi 14 | 15 | RACE_DATA_FOLDER=$1 16 | OUT_DATA_FOLDER=$2 17 | 18 | # download bpe encoder.json, vocabulary and fairseq dictionary 19 | wget -N 'https://dl.fbaipublicfiles.com/fairseq/gpt2_bpe/encoder.json' 20 | wget -N 'https://dl.fbaipublicfiles.com/fairseq/gpt2_bpe/vocab.bpe' 21 | wget -N 'https://dl.fbaipublicfiles.com/fairseq/gpt2_bpe/dict.txt' 22 | 23 | SPLITS="train dev test-middle test-high" 24 | INPUT_TYPES="input0 input1 input2 input3 input4" 25 | for INPUT_TYPE in $INPUT_TYPES 26 | do 27 | for SPLIT in $SPLITS 28 | do 29 | echo "BPE encoding $SPLIT/$INPUT_TYPE" 30 | python -m examples.roberta.multiprocessing_bpe_encoder \ 31 | --encoder-json encoder.json \ 32 | --vocab-bpe vocab.bpe \ 33 | --inputs "$RACE_DATA_FOLDER/$SPLIT.$INPUT_TYPE" \ 34 | --outputs "$RACE_DATA_FOLDER/$SPLIT.$INPUT_TYPE.bpe" \ 35 | --workers 10 \ 36 | --keep-empty; 37 | 38 | done 39 | done 40 | 41 | for INPUT_TYPE in $INPUT_TYPES 42 | do 43 | LANG="input$INPUT_TYPE" 44 | fairseq-preprocess \ 45 | --only-source \ 46 | --trainpref "$RACE_DATA_FOLDER/train.$INPUT_TYPE.bpe" \ 47 | --validpref "$RACE_DATA_FOLDER/dev.$INPUT_TYPE.bpe" \ 48 | --testpref "$RACE_DATA_FOLDER/test-middle.$INPUT_TYPE.bpe,$RACE_DATA_FOLDER/test-high.$INPUT_TYPE.bpe" \ 49 | --destdir "$OUT_DATA_FOLDER/$INPUT_TYPE" \ 50 | --workers 10 \ 51 | --srcdict dict.txt; 52 | done 53 | 54 | rm -rf "$OUT_DATA_FOLDER/label" 55 | mkdir -p "$OUT_DATA_FOLDER/label" 56 | cp "$RACE_DATA_FOLDER/train.label" "$OUT_DATA_FOLDER/label/" 57 | cp "$RACE_DATA_FOLDER/dev.label" "$OUT_DATA_FOLDER/label/valid.label" 58 | cp "$RACE_DATA_FOLDER/test-middle.label" "$OUT_DATA_FOLDER/label/test.label" 59 | cp "$RACE_DATA_FOLDER/test-high.label" "$OUT_DATA_FOLDER/label/test1.label" 60 | -------------------------------------------------------------------------------- /src/fairseq/examples/roberta/wsc/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from . import wsc_criterion # noqa 7 | from . import wsc_task # noqa 8 | -------------------------------------------------------------------------------- /src/fairseq/examples/simultaneous_translation/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from . import criterions, models, eval # noqa 7 | -------------------------------------------------------------------------------- /src/fairseq/examples/simultaneous_translation/criterions/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import importlib 7 | import os 8 | 9 | for file in os.listdir(os.path.dirname(__file__)): 10 | if file.endswith(".py") and not file.startswith("_"): 11 | criterion_name = file[: file.find(".py")] 12 | importlib.import_module( 13 | "examples.simultaneous_translation.criterions." + criterion_name 14 | ) 15 | -------------------------------------------------------------------------------- /src/fairseq/examples/simultaneous_translation/eval/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | -------------------------------------------------------------------------------- /src/fairseq/examples/simultaneous_translation/eval/agents/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import importlib 7 | import os 8 | from fairseq import registry 9 | 10 | build_agent, register_agent, MONOTONIC_AGENT = registry.setup_registry('--agent-type') 11 | 12 | 13 | DEFAULT_EOS = '' 14 | GET = 0 15 | SEND = 1 16 | 17 | for file in os.listdir(os.path.dirname(__file__)): 18 | if file.endswith('.py') and not file.startswith('_'): 19 | module = file[:file.find('.py')] 20 | importlib.import_module('agents.' + module) 21 | -------------------------------------------------------------------------------- /src/fairseq/examples/simultaneous_translation/eval/agents/agent.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from . import GET, SEND, DEFAULT_EOS 7 | import time 8 | from multiprocessing.pool import ThreadPool as Pool 9 | from functools import partial 10 | 11 | 12 | class Agent(object): 13 | "an agent needs to follow this pattern" 14 | def __init__(self, *args, **kwargs): 15 | pass 16 | 17 | def init_states(self, *args, **kwargs): 18 | raise NotImplementedError 19 | 20 | def update_states(self, states, new_state): 21 | raise NotImplementedError 22 | 23 | def finish_eval(self, states, new_state): 24 | raise NotImplementedError 25 | 26 | def policy(self, state): 27 | raise NotImplementedError 28 | 29 | def reset(self): 30 | raise NotImplementedError 31 | 32 | def decode(self, session, low=0, high=100000, num_thread=10): 33 | corpus_info = session.corpus_info() 34 | high = min(corpus_info["num_sentences"] - 1, high) 35 | if low >= high: 36 | return 37 | 38 | t0 = time.time() 39 | if num_thread > 1: 40 | with Pool(10) as p: 41 | p.map( 42 | partial(self._decode_one, session), 43 | [sent_id for sent_id in range(low, high + 1)] 44 | ) 45 | else: 46 | for sent_id in range(low, high + 1): 47 | self._decode_one(session, sent_id) 48 | 49 | print(f'Finished {low} to {high} in {time.time() - t0}s') 50 | 51 | def _decode_one(self, session, sent_id): 52 | action = {} 53 | self.reset() 54 | states = self.init_states() 55 | while action.get('value', None) != DEFAULT_EOS: 56 | # take an action 57 | action = self.policy(states) 58 | 59 | if action['key'] == GET: 60 | new_states = session.get_src(sent_id, action["value"]) 61 | states = self.update_states(states, new_states) 62 | 63 | elif action['key'] == SEND: 64 | session.send_hypo(sent_id, action['value']) 65 | print(" ".join(states["tokens"]["tgt"])) 66 | -------------------------------------------------------------------------------- /src/fairseq/examples/simultaneous_translation/eval/scorers/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import importlib 7 | import os 8 | from fairseq import registry 9 | ( 10 | build_scorer, 11 | register_scorer, 12 | SCORER_REGISTRIES 13 | ) = registry.setup_registry('--scorer-type') 14 | 15 | for file in os.listdir(os.path.dirname(__file__)): 16 | if file.endswith('.py') and not file.startswith('_'): 17 | module = file[:file.find('.py')] 18 | importlib.import_module('scorers.' + module) 19 | -------------------------------------------------------------------------------- /src/fairseq/examples/simultaneous_translation/eval/scorers/text_scorer.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from . scorer import SimulScorer 7 | from . import register_scorer 8 | 9 | 10 | @register_scorer("text") 11 | class SimulTextScorer(SimulScorer): 12 | def __init__(self, args): 13 | super().__init__(args) 14 | self.data = { 15 | "src": self._load_text_file(args.src_file, split=True), 16 | "tgt": self._load_text_file(args.tgt_file, split=False) 17 | } 18 | 19 | def send_src(self, sent_id, *args): 20 | if self.steps[sent_id] >= len(self.data["src"][sent_id]): 21 | dict_to_return = { 22 | "sent_id": sent_id, 23 | "segment_id": self.steps[sent_id], 24 | "segment": self.eos 25 | } 26 | # Consider EOS 27 | self.steps[sent_id] = len(self.data["src"][sent_id]) + 1 28 | else: 29 | dict_to_return = { 30 | "sent_id": sent_id, 31 | "segment_id": self.steps[sent_id], 32 | "segment": self.data["src"][sent_id][self.steps[sent_id]] 33 | } 34 | 35 | self.steps[sent_id] += 1 36 | 37 | return dict_to_return 38 | 39 | def src_lengths(self): 40 | # +1 for eos 41 | return [len(sent) + 1 for sent in self.data["src"]] 42 | -------------------------------------------------------------------------------- /src/fairseq/examples/simultaneous_translation/models/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import importlib 7 | import os 8 | 9 | for file in os.listdir(os.path.dirname(__file__)): 10 | if file.endswith('.py') and not file.startswith('_'): 11 | model_name = file[:file.find('.py')] 12 | importlib.import_module('examples.simultaneous_translation.models.' + model_name) 13 | -------------------------------------------------------------------------------- /src/fairseq/examples/simultaneous_translation/modules/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import importlib 7 | import os 8 | 9 | from fairseq import registry 10 | ( 11 | build_monotonic_attention, 12 | register_monotonic_attention, 13 | MONOTONIC_ATTENTION_REGISTRY 14 | ) = registry.setup_registry('--simul-type') 15 | 16 | for file in os.listdir(os.path.dirname(__file__)): 17 | if file.endswith('.py') and not file.startswith('_'): 18 | model_name = file[:file.find('.py')] 19 | importlib.import_module('examples.simultaneous_translation.modules.' + model_name) 20 | -------------------------------------------------------------------------------- /src/fairseq/examples/simultaneous_translation/modules/monotonic_transformer_layer.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from fairseq.modules import ( 7 | LayerNorm, 8 | TransformerEncoderLayer, 9 | TransformerDecoderLayer 10 | ) 11 | 12 | from . import build_monotonic_attention 13 | 14 | 15 | class TransformerMonotonicEncoderLayer(TransformerEncoderLayer): 16 | 17 | def forward(self, x, encoder_padding_mask): 18 | seq_len, _, _ = x.size() 19 | attn_mask = x.new_ones([seq_len, seq_len]).triu(1) 20 | attn_mask = attn_mask.masked_fill(attn_mask.bool(), float('-inf')) 21 | return super().forward(x, encoder_padding_mask, attn_mask) 22 | 23 | 24 | class TransformerMonotonicDecoderLayer(TransformerDecoderLayer): 25 | 26 | def __init__(self, args, no_encoder_attn=False, add_bias_kv=False, add_zero_attn=False): 27 | super().__init__( 28 | args, 29 | no_encoder_attn=True, 30 | add_bias_kv=add_bias_kv, 31 | add_zero_attn=add_zero_attn 32 | ) 33 | self.encoder_attn = build_monotonic_attention(args) 34 | self.encoder_attn_layer_norm = LayerNorm( 35 | self.embed_dim, 36 | export=getattr(args, 'char_inputs', False) 37 | ) 38 | 39 | def prune_incremental_state(self, incremental_state): 40 | def prune(module): 41 | input_buffer = module._get_input_buffer(incremental_state) 42 | for key in ["prev_key", "prev_value"]: 43 | if input_buffer[key].size(2) > 1: 44 | input_buffer[key] = input_buffer[key][:, :, :-1, :] 45 | else: 46 | input_buffer = {} 47 | break 48 | module._set_input_buffer(incremental_state, input_buffer) 49 | prune(self.self_attn) 50 | 51 | def get_steps(self, incremental_state): 52 | return ( 53 | self.encoder_attn 54 | ._get_monotonic_buffer( 55 | incremental_state 56 | ).get("step", 0) 57 | ) 58 | -------------------------------------------------------------------------------- /src/fairseq/examples/simultaneous_translation/utils/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import importlib 7 | import os 8 | 9 | 10 | # automatically import any Python files in the criterions/ directory 11 | for file in os.listdir(os.path.dirname(__file__)): 12 | if file.endswith('.py') and not file.startswith('_'): 13 | module = file[:file.find('.py')] 14 | importlib.import_module('examples.simultaneous_translation.utils.' + module) 15 | -------------------------------------------------------------------------------- /src/fairseq/examples/speech_recognition/__init__.py: -------------------------------------------------------------------------------- 1 | from . import tasks, criterions, models # noqa 2 | -------------------------------------------------------------------------------- /src/fairseq/examples/speech_recognition/criterions/__init__.py: -------------------------------------------------------------------------------- 1 | import importlib 2 | import os 3 | 4 | 5 | # ASG loss requires wav2letter 6 | blacklist = set() 7 | try: 8 | import wav2letter 9 | except ImportError: 10 | blacklist.add("ASG_loss.py") 11 | 12 | for file in os.listdir(os.path.dirname(__file__)): 13 | if file.endswith(".py") and not file.startswith("_") and file not in blacklist: 14 | criterion_name = file[: file.find(".py")] 15 | importlib.import_module( 16 | "examples.speech_recognition.criterions." + criterion_name 17 | ) 18 | -------------------------------------------------------------------------------- /src/fairseq/examples/speech_recognition/data/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from .asr_dataset import AsrDataset 7 | 8 | __all__ = [ 9 | 'AsrDataset', 10 | ] 11 | -------------------------------------------------------------------------------- /src/fairseq/examples/speech_recognition/data/replabels.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # Copyright (c) Facebook, Inc. and its affiliates. 4 | # 5 | # This source code is licensed under the MIT license found in the 6 | # LICENSE file in the root directory of this source tree. 7 | 8 | """ 9 | Replabel transforms for use with wav2letter's ASG criterion. 10 | """ 11 | 12 | 13 | def replabel_symbol(i): 14 | """ 15 | Replabel symbols used in wav2letter, currently just "1", "2", ... 16 | This prevents training with numeral tokens, so this might change in the future 17 | """ 18 | return str(i) 19 | 20 | 21 | def pack_replabels(tokens, dictionary, max_reps): 22 | """ 23 | Pack a token sequence so that repeated symbols are replaced by replabels 24 | """ 25 | if len(tokens) == 0 or max_reps <= 0: 26 | return tokens 27 | 28 | replabel_value_to_idx = [0] * (max_reps + 1) 29 | for i in range(1, max_reps + 1): 30 | replabel_value_to_idx[i] = dictionary.index(replabel_symbol(i)) 31 | 32 | result = [] 33 | prev_token = -1 34 | num_reps = 0 35 | for token in tokens: 36 | if token == prev_token and num_reps < max_reps: 37 | num_reps += 1 38 | else: 39 | if num_reps > 0: 40 | result.append(replabel_value_to_idx[num_reps]) 41 | num_reps = 0 42 | result.append(token) 43 | prev_token = token 44 | if num_reps > 0: 45 | result.append(replabel_value_to_idx[num_reps]) 46 | return result 47 | 48 | 49 | def unpack_replabels(tokens, dictionary, max_reps): 50 | """ 51 | Unpack a token sequence so that replabels are replaced by repeated symbols 52 | """ 53 | if len(tokens) == 0 or max_reps <= 0: 54 | return tokens 55 | 56 | replabel_idx_to_value = {} 57 | for i in range(1, max_reps + 1): 58 | replabel_idx_to_value[dictionary.index(replabel_symbol(i))] = i 59 | 60 | result = [] 61 | prev_token = -1 62 | for token in tokens: 63 | try: 64 | for _ in range(replabel_idx_to_value[token]): 65 | result.append(prev_token) 66 | prev_token = -1 67 | except KeyError: 68 | result.append(token) 69 | prev_token = token 70 | return result 71 | -------------------------------------------------------------------------------- /src/fairseq/examples/speech_recognition/models/__init__.py: -------------------------------------------------------------------------------- 1 | import importlib 2 | import os 3 | 4 | for file in os.listdir(os.path.dirname(__file__)): 5 | if file.endswith('.py') and not file.startswith('_'): 6 | model_name = file[:file.find('.py')] 7 | importlib.import_module('examples.speech_recognition.models.' + model_name) 8 | -------------------------------------------------------------------------------- /src/fairseq/examples/speech_recognition/tasks/__init__.py: -------------------------------------------------------------------------------- 1 | import importlib 2 | import os 3 | 4 | for file in os.listdir(os.path.dirname(__file__)): 5 | if file.endswith('.py') and not file.startswith('_'): 6 | task_name = file[:file.find('.py')] 7 | importlib.import_module('examples.speech_recognition.tasks.' + task_name) 8 | -------------------------------------------------------------------------------- /src/fairseq/examples/translation_moe/src/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from . import translation_moe # noqa 7 | -------------------------------------------------------------------------------- /src/fairseq/examples/translation_moe/src/logsumexp_moe.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import torch 7 | 8 | 9 | class LogSumExpMoE(torch.autograd.Function): 10 | """Standard LogSumExp forward pass, but use *posterior* for the backward. 11 | 12 | See `"Mixture Models for Diverse Machine Translation: Tricks of the Trade" 13 | (Shen et al., 2019) `_. 14 | """ 15 | 16 | @staticmethod 17 | def forward(ctx, logp, posterior, dim=-1): 18 | ctx.save_for_backward(posterior) 19 | ctx.dim = dim 20 | return torch.logsumexp(logp, dim=dim) 21 | 22 | @staticmethod 23 | def backward(ctx, grad_output): 24 | posterior, = ctx.saved_tensors 25 | grad_logp = grad_output.unsqueeze(ctx.dim) * posterior 26 | return grad_logp, None, None 27 | -------------------------------------------------------------------------------- /src/fairseq/examples/translation_moe/src/mean_pool_gating_network.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import torch 7 | import torch.nn.functional as F 8 | 9 | 10 | class MeanPoolGatingNetwork(torch.nn.Module): 11 | """A simple mean-pooling gating network for selecting experts. 12 | 13 | This module applies mean pooling over an encoder's output and returns 14 | reponsibilities for each expert. The encoder format is expected to match 15 | :class:`fairseq.models.transformer.TransformerEncoder`. 16 | """ 17 | 18 | def __init__(self, embed_dim, num_experts, dropout=None): 19 | super().__init__() 20 | self.embed_dim = embed_dim 21 | self.num_experts = num_experts 22 | 23 | self.fc1 = torch.nn.Linear(embed_dim, embed_dim) 24 | self.dropout = torch.nn.Dropout(dropout) if dropout is not None else None 25 | self.fc2 = torch.nn.Linear(embed_dim, num_experts) 26 | 27 | def forward(self, encoder_out): 28 | if not ( 29 | hasattr(encoder_out, 'encoder_out') 30 | and hasattr(encoder_out, 'encoder_padding_mask') 31 | and encoder_out.encoder_out.size(2) == self.embed_dim 32 | ): 33 | raise ValueError('Unexpected format for encoder_out') 34 | 35 | # mean pooling over time 36 | encoder_padding_mask = encoder_out.encoder_padding_mask # B x T 37 | encoder_out = encoder_out.encoder_out.transpose(0, 1) # B x T x C 38 | if encoder_padding_mask is not None: 39 | encoder_out = encoder_out.clone() # required because of transpose above 40 | encoder_out[encoder_padding_mask] = 0 41 | ntokens = torch.sum(~encoder_padding_mask, dim=1, keepdim=True) 42 | x = torch.sum(encoder_out, dim=1) / ntokens.type_as(encoder_out) 43 | else: 44 | x = torch.mean(encoder_out, dim=1) 45 | 46 | x = torch.tanh(self.fc1(x)) 47 | if self.dropout is not None: 48 | x = self.dropout(x) 49 | x = self.fc2(x) 50 | return F.log_softmax(x, dim=-1, dtype=torch.float32).type_as(x) 51 | -------------------------------------------------------------------------------- /src/fairseq/fairseq.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amazon-science/BartGraphSumm/9681651faad37938909cacb1d7b998f911ab3d9b/src/fairseq/fairseq.gif -------------------------------------------------------------------------------- /src/fairseq/fairseq/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | __all__ = ['pdb'] 7 | __version__ = '0.9.0' 8 | 9 | import sys 10 | 11 | # backwards compatibility to support `from fairseq.meters import AverageMeter` 12 | from fairseq.logging import meters, metrics, progress_bar # noqa 13 | sys.modules['fairseq.meters'] = meters 14 | sys.modules['fairseq.metrics'] = metrics 15 | sys.modules['fairseq.progress_bar'] = progress_bar 16 | 17 | import fairseq.criterions # noqa 18 | import fairseq.models # noqa 19 | import fairseq.modules # noqa 20 | import fairseq.optim # noqa 21 | import fairseq.optim.lr_scheduler # noqa 22 | import fairseq.pdb # noqa 23 | import fairseq.tasks # noqa 24 | 25 | import fairseq.benchmark # noqa 26 | import fairseq.model_parallel # noqa 27 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/benchmark/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | # import models/tasks to register them 7 | from . import ( # noqa 8 | dummy_lm, 9 | dummy_masked_lm, 10 | dummy_model, 11 | ) 12 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/clib/libbleu/module.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017-present, Facebook, Inc. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under the license found in the 6 | * LICENSE file in the root directory of this source tree. 7 | */ 8 | 9 | #include 10 | 11 | 12 | static PyMethodDef method_def[] = { 13 | {NULL, NULL, 0, NULL} 14 | }; 15 | 16 | static struct PyModuleDef module_def = { 17 | PyModuleDef_HEAD_INIT, 18 | "libbleu", /* name of module */ 19 | NULL, /* module documentation, may be NULL */ 20 | -1, /* size of per-interpreter state of the module, 21 | or -1 if the module keeps state in global variables. */ 22 | method_def 23 | }; 24 | 25 | 26 | #if PY_MAJOR_VERSION == 2 27 | PyMODINIT_FUNC init_libbleu() 28 | #else 29 | PyMODINIT_FUNC PyInit_libbleu() 30 | #endif 31 | { 32 | PyObject *m = PyModule_Create(&module_def); 33 | if (!m) { 34 | return NULL; 35 | } 36 | return m; 37 | } 38 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/clib/libnat_cuda/binding.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017-present, Facebook, Inc. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under the license found in the 6 | * LICENSE file in the root directory of this source tree. 7 | */ 8 | 9 | /* 10 | This code is partially adpoted from https://github.com/1ytic/pytorch-edit-distance 11 | */ 12 | 13 | #include "edit_dist.h" 14 | #include 15 | 16 | #ifndef TORCH_CHECK 17 | #define TORCH_CHECK AT_CHECK 18 | #endif 19 | 20 | #define CHECK_CUDA(x) TORCH_CHECK(x.type().is_cuda(), #x " must be a CUDA tensor") 21 | #define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x " must be contiguous") 22 | #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) 23 | 24 | 25 | torch::Tensor LevenshteinDistance( 26 | torch::Tensor source, 27 | torch::Tensor target, 28 | torch::Tensor source_length, 29 | torch::Tensor target_length) { 30 | 31 | CHECK_INPUT(source); 32 | CHECK_INPUT(target); 33 | CHECK_INPUT(source_length); 34 | CHECK_INPUT(target_length); 35 | return LevenshteinDistanceCuda(source, target, source_length, target_length); 36 | } 37 | 38 | torch::Tensor GenerateDeletionLabel( 39 | torch::Tensor source, 40 | torch::Tensor operations) { 41 | 42 | CHECK_INPUT(source); 43 | CHECK_INPUT(operations); 44 | return GenerateDeletionLabelCuda(source, operations); 45 | } 46 | 47 | std::pair GenerateInsertionLabel( 48 | torch::Tensor target, 49 | torch::Tensor operations) { 50 | 51 | CHECK_INPUT(target); 52 | CHECK_INPUT(operations); 53 | return GenerateInsertionLabelCuda(target, operations); 54 | } 55 | 56 | PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { 57 | m.def("levenshtein_distance", &LevenshteinDistance, "Levenshtein distance"); 58 | m.def("generate_deletion_labels", &GenerateDeletionLabel, "Generate Deletion Label"); 59 | m.def("generate_insertion_labels", &GenerateInsertionLabel, "Generate Insertion Label"); 60 | } 61 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/clib/libnat_cuda/edit_dist.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017-present, Facebook, Inc. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under the license found in the 6 | * LICENSE file in the root directory of this source tree. 7 | */ 8 | 9 | #pragma once 10 | 11 | #include 12 | 13 | torch::Tensor LevenshteinDistanceCuda( 14 | torch::Tensor source, 15 | torch::Tensor target, 16 | torch::Tensor source_length, 17 | torch::Tensor target_length); 18 | 19 | torch::Tensor GenerateDeletionLabelCuda( 20 | torch::Tensor source, 21 | torch::Tensor operations); 22 | 23 | std::pair GenerateInsertionLabelCuda( 24 | torch::Tensor source, 25 | torch::Tensor operations); 26 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/criterions/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import importlib 7 | import os 8 | 9 | from fairseq import registry 10 | from fairseq.criterions.fairseq_criterion import FairseqCriterion, LegacyFairseqCriterion 11 | 12 | 13 | build_criterion, register_criterion, CRITERION_REGISTRY = registry.setup_registry( 14 | '--criterion', 15 | base_class=FairseqCriterion, 16 | default='cross_entropy', 17 | ) 18 | 19 | 20 | # automatically import any Python files in the criterions/ directory 21 | for file in os.listdir(os.path.dirname(__file__)): 22 | if file.endswith('.py') and not file.startswith('_'): 23 | module = file[:file.find('.py')] 24 | importlib.import_module('fairseq.criterions.' + module) 25 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/data/append_token_dataset.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import numpy as np 7 | import torch 8 | 9 | from . import BaseWrapperDataset 10 | 11 | 12 | class AppendTokenDataset(BaseWrapperDataset): 13 | 14 | def __init__(self, dataset, token=None): 15 | super().__init__(dataset) 16 | self.token = token 17 | if token is not None: 18 | self._sizes = np.array(dataset.sizes) + 1 19 | else: 20 | self._sizes = dataset.sizes 21 | 22 | def __getitem__(self, idx): 23 | item = self.dataset[idx] 24 | if self.token is not None: 25 | item = torch.cat([item, item.new([self.token])]) 26 | return item 27 | 28 | @property 29 | def sizes(self): 30 | return self._sizes 31 | 32 | def num_tokens(self, index): 33 | n = self.dataset.num_tokens(index) 34 | if self.token is not None: 35 | n += 1 36 | return n 37 | 38 | def size(self, index): 39 | n = self.dataset.size(index) 40 | if self.token is not None: 41 | n += 1 42 | return n 43 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/data/audio/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amazon-science/BartGraphSumm/9681651faad37938909cacb1d7b998f911ab3d9b/src/fairseq/fairseq/data/audio/__init__.py -------------------------------------------------------------------------------- /src/fairseq/fairseq/data/base_wrapper_dataset.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from torch.utils.data.dataloader import default_collate 7 | 8 | from . import FairseqDataset 9 | 10 | 11 | class BaseWrapperDataset(FairseqDataset): 12 | 13 | def __init__(self, dataset): 14 | super().__init__() 15 | self.dataset = dataset 16 | 17 | def __getitem__(self, index): 18 | return self.dataset[index] 19 | 20 | def __len__(self): 21 | return len(self.dataset) 22 | 23 | def collater(self, samples): 24 | if hasattr(self.dataset, 'collater'): 25 | return self.dataset.collater(samples) 26 | else: 27 | return default_collate(samples) 28 | 29 | @property 30 | def sizes(self): 31 | return self.dataset.sizes 32 | 33 | def num_tokens(self, index): 34 | return self.dataset.num_tokens(index) 35 | 36 | def size(self, index): 37 | return self.dataset.size(index) 38 | 39 | def ordered_indices(self): 40 | return self.dataset.ordered_indices() 41 | 42 | @property 43 | def supports_prefetch(self): 44 | return getattr(self.dataset, 'supports_prefetch', False) 45 | 46 | def prefetch(self, indices): 47 | self.dataset.prefetch(indices) 48 | 49 | def set_epoch(self, epoch): 50 | super().set_epoch(epoch) 51 | if hasattr(self.dataset, 'set_epoch'): 52 | self.dataset.set_epoch(epoch) 53 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/data/colorize_dataset.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import torch 7 | 8 | from . import BaseWrapperDataset 9 | 10 | 11 | class ColorizeDataset(BaseWrapperDataset): 12 | """ Adds 'colors' property to net input that is obtained from the provided color getter for use by models """ 13 | def __init__(self, dataset, color_getter): 14 | super().__init__(dataset) 15 | self.color_getter = color_getter 16 | 17 | def collater(self, samples): 18 | base_collate = super().collater(samples) 19 | if len(base_collate) > 0: 20 | base_collate["net_input"]["colors"] = torch.tensor( 21 | list(self.color_getter(self.dataset, s["id"]) for s in samples), 22 | dtype=torch.long, 23 | ) 24 | return base_collate 25 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/data/concat_sentences_dataset.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import torch 7 | 8 | from . import FairseqDataset 9 | 10 | 11 | class ConcatSentencesDataset(FairseqDataset): 12 | 13 | def __init__(self, *datasets): 14 | super().__init__() 15 | self.datasets = datasets 16 | assert all(len(ds) == len(datasets[0]) for ds in datasets), \ 17 | 'datasets must have the same length' 18 | 19 | def __getitem__(self, index): 20 | return torch.cat([ds[index] for ds in self.datasets]) 21 | 22 | def __len__(self): 23 | return len(self.datasets[0]) 24 | 25 | def collater(self, samples): 26 | return self.datasets[0].collater(samples) 27 | 28 | @property 29 | def sizes(self): 30 | return sum(ds.sizes for ds in self.datasets) 31 | 32 | def num_tokens(self, index): 33 | return sum(ds.num_tokens(index) for ds in self.datasets) 34 | 35 | def size(self, index): 36 | return sum(ds.size(index) for ds in self.datasets) 37 | 38 | def ordered_indices(self): 39 | return self.datasets[0].ordered_indices() 40 | 41 | @property 42 | def supports_prefetch(self): 43 | return any( 44 | getattr(ds, 'supports_prefetch', False) for ds in self.datasets 45 | ) 46 | 47 | def prefetch(self, indices): 48 | for ds in self.datasets: 49 | if getattr(ds, 'supports_prefetch', False): 50 | ds.prefetch(indices) 51 | 52 | def set_epoch(self, epoch): 53 | super().set_epoch(epoch) 54 | for ds in self.datasets: 55 | if hasattr(ds, 'set_epoch'): 56 | ds.set_epoch(epoch) 57 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/data/data_utils_fast.pyx: -------------------------------------------------------------------------------- 1 | # cython: language_level=3 2 | # Copyright (c) Facebook, Inc. and its affiliates. 3 | # 4 | # This source code is licensed under the MIT license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | 7 | import numpy as np 8 | 9 | cimport cython 10 | cimport numpy as np 11 | 12 | DTYPE = np.int64 13 | ctypedef np.int64_t DTYPE_t 14 | 15 | 16 | cdef _is_batch_full(list batch, long num_tokens, long max_tokens, long max_sentences): 17 | if len(batch) == 0: 18 | return 0 19 | if max_sentences > 0 and len(batch) == max_sentences: 20 | return 1 21 | if max_tokens > 0 and num_tokens > max_tokens: 22 | return 1 23 | return 0 24 | 25 | 26 | @cython.cdivision(True) 27 | cpdef list batch_by_size_fast( 28 | np.ndarray[DTYPE_t, ndim=1] indices, 29 | num_tokens_fn, 30 | long max_tokens, 31 | long max_sentences, 32 | int bsz_mult, 33 | ): 34 | cdef long sample_len = 0 35 | cdef list sample_lens = [] 36 | cdef list batch = [] 37 | cdef list batches = [] 38 | cdef long mod_len 39 | cdef long i 40 | cdef long idx 41 | cdef long num_tokens 42 | cdef DTYPE_t[:] indices_view = indices 43 | 44 | for i in range(len(indices_view)): 45 | idx = indices_view[i] 46 | num_tokens = num_tokens_fn(idx) 47 | sample_lens.append(num_tokens) 48 | sample_len = max(sample_len, num_tokens) 49 | 50 | assert max_tokens <= 0 or sample_len <= max_tokens, ( 51 | "sentence at index {} of size {} exceeds max_tokens " 52 | "limit of {}!".format(idx, sample_len, max_tokens) 53 | ) 54 | num_tokens = (len(batch) + 1) * sample_len 55 | 56 | if _is_batch_full(batch, num_tokens, max_tokens, max_sentences): 57 | mod_len = max( 58 | bsz_mult * (len(batch) // bsz_mult), 59 | len(batch) % bsz_mult, 60 | ) 61 | batches.append(batch[:mod_len]) 62 | batch = batch[mod_len:] 63 | sample_lens = sample_lens[mod_len:] 64 | sample_len = max(sample_lens) if len(sample_lens) > 0 else 0 65 | batch.append(idx) 66 | if len(batch) > 0: 67 | batches.append(batch) 68 | return batches 69 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/data/encoders/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | 7 | import importlib 8 | import os 9 | 10 | from fairseq import registry 11 | 12 | 13 | build_tokenizer, register_tokenizer, TOKENIZER_REGISTRY = registry.setup_registry( 14 | '--tokenizer', 15 | default=None, 16 | ) 17 | 18 | 19 | build_bpe, register_bpe, BPE_REGISTRY = registry.setup_registry( 20 | '--bpe', 21 | default=None, 22 | ) 23 | 24 | 25 | # automatically import any Python files in the encoders/ directory 26 | for file in os.listdir(os.path.dirname(__file__)): 27 | if file.endswith('.py') and not file.startswith('_'): 28 | module = file[:file.find('.py')] 29 | importlib.import_module('fairseq.data.encoders.' + module) 30 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/data/encoders/byte_bpe.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | 7 | from fairseq import file_utils 8 | from fairseq.data.encoders import register_bpe 9 | from fairseq.data.encoders.byte_utils import (byte_encode, smart_byte_decode, 10 | SPACE, SPACE_ESCAPE) 11 | 12 | 13 | @register_bpe('byte_bpe') 14 | class ByteBPE(object): 15 | @staticmethod 16 | def add_args(parser): 17 | # fmt: off 18 | parser.add_argument('--sentencepiece-model-path', type=str, 19 | help='path to sentencepiece model') 20 | # fmt: on 21 | 22 | def __init__(self, args): 23 | vocab = file_utils.cached_path(args.sentencepiece_model_path) 24 | try: 25 | import sentencepiece as spm 26 | self.sp = spm.SentencePieceProcessor() 27 | self.sp.Load(vocab) 28 | except ImportError: 29 | raise ImportError('Please install sentencepiece with: pip install sentencepiece') 30 | 31 | def encode(self, x: str) -> str: 32 | byte_encoded = byte_encode(x) 33 | return SPACE.join(self.sp.EncodeAsPieces(byte_encoded)) 34 | 35 | @staticmethod 36 | def decode(x: str) -> str: 37 | unescaped = x.replace(SPACE, '').replace(SPACE_ESCAPE, SPACE) 38 | return smart_byte_decode(unescaped) 39 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/data/encoders/byte_utils.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import re 7 | 8 | WHITESPACE_NORMALIZER = re.compile(r'\s+') 9 | SPACE = chr(32) 10 | SPACE_ESCAPE = chr(9601) 11 | # excluding non-breaking space (160) here 12 | PRINTABLE_LATIN = set( 13 | list(range(32, 126 + 1)) + list(range(161, 172 + 1)) + 14 | list(range(174, 255 + 1)) 15 | ) 16 | BYTE_TO_BCHAR = { 17 | b: chr(b) if b in PRINTABLE_LATIN else chr(256 + b) for b in range(256) 18 | } 19 | BCHAR_TO_BYTE = {bc: b for b, bc in BYTE_TO_BCHAR.items()} 20 | 21 | 22 | def byte_encode(x: str) -> str: 23 | normalized = WHITESPACE_NORMALIZER.sub(SPACE, x) 24 | return ''.join([BYTE_TO_BCHAR[b] for b in normalized.encode('utf-8')]) 25 | 26 | 27 | def byte_decode(x: str) -> str: 28 | try: 29 | return bytes([BCHAR_TO_BYTE[bc] for bc in x]).decode('utf-8') 30 | except ValueError: 31 | return '' 32 | 33 | 34 | def smart_byte_decode(x: str) -> str: 35 | output = byte_decode(x) 36 | if output == '': 37 | # DP the best recovery (max valid chars) if it's broken 38 | n_bytes = len(x) 39 | f = [0 for _ in range(n_bytes + 1)] 40 | pt = [0 for _ in range(n_bytes + 1)] 41 | for i in range(1, n_bytes + 1): 42 | f[i], pt[i] = f[i - 1], i - 1 43 | for j in range(1, min(4, i) + 1): 44 | if f[i - j] + 1 > f[i] and len(byte_decode(x[i - j: i])) > 0: 45 | f[i], pt[i] = f[i - j] + 1, i - j 46 | cur_pt = n_bytes 47 | while cur_pt > 0: 48 | if f[cur_pt] == f[pt[cur_pt]] + 1: 49 | output = byte_decode(x[pt[cur_pt]: cur_pt]) + output 50 | cur_pt = pt[cur_pt] 51 | return output 52 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/data/encoders/bytes.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | 7 | from fairseq.data.encoders import register_bpe 8 | from fairseq.data.encoders.byte_utils import (byte_encode, smart_byte_decode, 9 | SPACE, SPACE_ESCAPE) 10 | 11 | 12 | @register_bpe('bytes') 13 | class Bytes(object): 14 | def __init__(self, args): 15 | pass 16 | 17 | @staticmethod 18 | def add_args(parser): 19 | pass 20 | 21 | @staticmethod 22 | def encode(x: str) -> str: 23 | encoded = byte_encode(x) 24 | escaped = encoded.replace(SPACE, SPACE_ESCAPE) 25 | return SPACE.join(list(escaped)) 26 | 27 | @staticmethod 28 | def decode(x: str) -> str: 29 | unescaped = x.replace(SPACE, '').replace(SPACE_ESCAPE, SPACE) 30 | return smart_byte_decode(unescaped) 31 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/data/encoders/characters.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | 7 | from fairseq.data.encoders import register_bpe 8 | 9 | SPACE = chr(32) 10 | SPACE_ESCAPE = chr(9601) 11 | 12 | 13 | @register_bpe('characters') 14 | class Characters(object): 15 | def __init__(self, args): 16 | pass 17 | 18 | @staticmethod 19 | def add_args(parser): 20 | pass 21 | 22 | @staticmethod 23 | def encode(x: str) -> str: 24 | escaped = x.replace(SPACE, SPACE_ESCAPE) 25 | return SPACE.join(list(escaped)) 26 | 27 | @staticmethod 28 | def decode(x: str) -> str: 29 | return x.replace(SPACE, '').replace(SPACE_ESCAPE, SPACE) 30 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/data/encoders/fastbpe.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from fairseq import file_utils 7 | from fairseq.data.encoders import register_bpe 8 | 9 | 10 | @register_bpe('fastbpe') 11 | class fastBPE(object): 12 | 13 | @staticmethod 14 | def add_args(parser): 15 | # fmt: off 16 | parser.add_argument('--bpe-codes', type=str, 17 | help='path to fastBPE BPE') 18 | # fmt: on 19 | 20 | def __init__(self, args): 21 | if args.bpe_codes is None: 22 | raise ValueError('--bpe-codes is required for --bpe=fastbpe') 23 | codes = file_utils.cached_path(args.bpe_codes) 24 | try: 25 | import fastBPE 26 | self.bpe = fastBPE.fastBPE(codes) 27 | self.bpe_symbol = "@@ " 28 | except ImportError: 29 | raise ImportError('Please install fastBPE with: pip install fastBPE') 30 | 31 | def encode(self, x: str) -> str: 32 | return self.bpe.apply([x])[0] 33 | 34 | def decode(self, x: str) -> str: 35 | return (x + ' ').replace(self.bpe_symbol, '').rstrip() 36 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/data/encoders/gpt2_bpe.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from fairseq import file_utils 7 | from fairseq.data.encoders import register_bpe 8 | 9 | from .gpt2_bpe_utils import get_encoder 10 | 11 | 12 | DEFAULT_ENCODER_JSON = 'https://dl.fbaipublicfiles.com/fairseq/gpt2_bpe/encoder.json' 13 | DEFAULT_VOCAB_BPE = 'https://dl.fbaipublicfiles.com/fairseq/gpt2_bpe/vocab.bpe' 14 | 15 | 16 | @register_bpe('gpt2') 17 | class GPT2BPE(object): 18 | 19 | @staticmethod 20 | def add_args(parser): 21 | # fmt: off 22 | parser.add_argument('--gpt2-encoder-json', type=str, 23 | default=DEFAULT_ENCODER_JSON, 24 | help='path to encoder.json') 25 | parser.add_argument('--gpt2-vocab-bpe', type=str, 26 | default=DEFAULT_VOCAB_BPE, 27 | help='path to vocab.bpe') 28 | # fmt: on 29 | 30 | def __init__(self, args): 31 | encoder_json = file_utils.cached_path( 32 | getattr(args, 'gpt2_encoder_json', DEFAULT_ENCODER_JSON) 33 | ) 34 | vocab_bpe = file_utils.cached_path( 35 | getattr(args, 'gpt2_vocab_bpe', DEFAULT_VOCAB_BPE) 36 | ) 37 | self.bpe = get_encoder(encoder_json, vocab_bpe) 38 | 39 | def encode(self, x: str) -> str: 40 | return ' '.join(map(str, self.bpe.encode(x))) 41 | 42 | def decode(self, x: str) -> str: 43 | return self.bpe.decode([ 44 | int(tok) if tok not in {'', ''} else tok 45 | for tok in x.split() 46 | ]) 47 | 48 | def is_beginning_of_word(self, x: str) -> bool: 49 | return self.decode(x).startswith(' ') 50 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/data/encoders/hf_bert_bpe.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from fairseq.data.encoders import register_bpe 7 | 8 | 9 | @register_bpe('bert') 10 | class BertBPE(object): 11 | 12 | @staticmethod 13 | def add_args(parser): 14 | # fmt: off 15 | parser.add_argument('--bpe-cased', action='store_true', 16 | help='set for cased BPE', 17 | default=False) 18 | parser.add_argument('--bpe-vocab-file', type=str, 19 | help='bpe vocab file.') 20 | # fmt: on 21 | 22 | def __init__(self, args): 23 | try: 24 | from pytorch_transformers import BertTokenizer 25 | from pytorch_transformers.tokenization_utils import clean_up_tokenization 26 | except ImportError: 27 | raise ImportError( 28 | 'Please install 1.0.0 version of pytorch_transformers' 29 | 'with: pip install pytorch-transformers' 30 | ) 31 | 32 | if 'bpe_vocab_file' in args: 33 | self.bert_tokenizer = BertTokenizer( 34 | args.bpe_vocab_file, 35 | do_lower_case=not args.bpe_cased 36 | ) 37 | else: 38 | vocab_file_name = 'bert-base-cased' if args.bpe_cased else 'bert-base-uncased' 39 | self.bert_tokenizer = BertTokenizer.from_pretrained(vocab_file_name) 40 | self.clean_up_tokenization = clean_up_tokenization 41 | 42 | def encode(self, x: str) -> str: 43 | return ' '.join(self.bert_tokenizer.tokenize(x)) 44 | 45 | def decode(self, x: str) -> str: 46 | return self.clean_up_tokenization( 47 | self.bert_tokenizer.convert_tokens_to_string(x.split(' ')) 48 | ) 49 | 50 | def is_beginning_of_word(self, x: str) -> bool: 51 | return not x.startswith('##') 52 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/data/encoders/hf_byte_bpe.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from fairseq.data.encoders import register_bpe 7 | 8 | 9 | @register_bpe('hf_byte_bpe') 10 | class HuggingFaceByteLevelBPE(object): 11 | 12 | @staticmethod 13 | def add_args(parser): 14 | # fmt: off 15 | parser.add_argument('--bpe-merges', help='path to merges.txt') 16 | parser.add_argument('--bpe-vocab', help='path to vocab.json') 17 | parser.add_argument('--bpe-add-prefix-space', action='store_true', 18 | help='add prefix space before encoding') 19 | # fmt: on 20 | 21 | def __init__(self, args): 22 | try: 23 | from tokenizers import ByteLevelBPETokenizer 24 | except ImportError: 25 | raise ImportError( 26 | 'Please install huggingface/tokenizers with: ' 27 | 'pip install tokenizers' 28 | ) 29 | 30 | self.bpe = ByteLevelBPETokenizer( 31 | args.bpe_vocab, 32 | args.bpe_merges, 33 | add_prefix_space=getattr(args, 'bpe_add_prefix_space', False), 34 | ) 35 | 36 | def encode(self, x: str) -> str: 37 | return ' '.join(map(str, self.bpe.encode(x).ids)) 38 | 39 | def decode(self, x: str) -> str: 40 | return self.bpe.decode([ 41 | int(tok) if tok not in {'', ''} else tok 42 | for tok in x.split() 43 | ]) 44 | 45 | def is_beginning_of_word(self, x: str) -> bool: 46 | return self.decode(x).startswith(' ') 47 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/data/encoders/moses_tokenizer.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from fairseq.data.encoders import register_tokenizer 7 | 8 | 9 | @register_tokenizer('moses') 10 | class MosesTokenizer(object): 11 | 12 | @staticmethod 13 | def add_args(parser): 14 | # fmt: off 15 | parser.add_argument('--moses-source-lang', metavar='SRC', 16 | help='source language') 17 | parser.add_argument('--moses-target-lang', metavar='TARGET', 18 | help='target language') 19 | parser.add_argument('--moses-no-dash-splits', action='store_true', default=False, 20 | help='don\'t apply dash split rules') 21 | parser.add_argument('--moses-no-escape', action='store_true', default=False, 22 | help='don\'t perform HTML escaping on apostrophy, quotes, etc.') 23 | # fmt: on 24 | 25 | def __init__(self, args): 26 | self.args = args 27 | 28 | if getattr(args, 'moses_source_lang', None) is None: 29 | args.moses_source_lang = getattr(args, 'source_lang', 'en') 30 | if getattr(args, 'moses_target_lang', None) is None: 31 | args.moses_target_lang = getattr(args, 'target_lang', 'en') 32 | 33 | try: 34 | from sacremoses import MosesTokenizer, MosesDetokenizer 35 | self.tok = MosesTokenizer(args.moses_source_lang) 36 | self.detok = MosesDetokenizer(args.moses_target_lang) 37 | except ImportError: 38 | raise ImportError('Please install Moses tokenizer with: pip install sacremoses') 39 | 40 | def encode(self, x: str) -> str: 41 | return self.tok.tokenize( 42 | x, 43 | aggressive_dash_splits=(not self.args.moses_no_dash_splits), 44 | return_str=True, 45 | escape=(not self.args.moses_no_escape), 46 | ) 47 | 48 | def decode(self, x: str) -> str: 49 | return self.detok.detokenize(x.split()) 50 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/data/encoders/nltk_tokenizer.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from fairseq.data.encoders import register_tokenizer 7 | 8 | 9 | @register_tokenizer('nltk') 10 | class NLTKTokenizer(object): 11 | 12 | def __init__(self, source_lang=None, target_lang=None): 13 | try: 14 | from nltk.tokenize import word_tokenize 15 | self.word_tokenize = word_tokenize 16 | except ImportError: 17 | raise ImportError('Please install nltk with: pip install nltk') 18 | 19 | def encode(self, x: str) -> str: 20 | return ' '.join(self.word_tokenize(x)) 21 | 22 | def decode(self, x: str) -> str: 23 | return x 24 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/data/encoders/sentencepiece_bpe.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from fairseq import file_utils 7 | from fairseq.data.encoders import register_bpe 8 | 9 | 10 | @register_bpe('sentencepiece') 11 | class SentencepieceBPE(object): 12 | 13 | @staticmethod 14 | def add_args(parser): 15 | # fmt: off 16 | parser.add_argument('--sentencepiece-vocab', type=str, 17 | help='path to sentencepiece vocab') 18 | # fmt: on 19 | 20 | def __init__(self, args): 21 | vocab = file_utils.cached_path(args.sentencepiece_vocab) 22 | try: 23 | import sentencepiece as spm 24 | self.sp = spm.SentencePieceProcessor() 25 | self.sp.Load(vocab) 26 | except ImportError: 27 | raise ImportError('Please install sentencepiece with: pip install sentencepiece') 28 | 29 | def encode(self, x: str) -> str: 30 | return ' '.join(self.sp.EncodeAsPieces(x)) 31 | 32 | def decode(self, x: str) -> str: 33 | return x.replace(' ', '').replace('\u2581', ' ').strip() 34 | 35 | def is_beginning_of_word(self, x: str) -> bool: 36 | if x in ['', '', '', '']: 37 | # special elements are always considered beginnings 38 | # HACK: this logic is already present in fairseq/tasks/masked_lm.py 39 | # but these special tokens are also contained in the sentencepiece 40 | # vocabulary which causes duplicate special tokens. This hack makes 41 | # sure that they are all taken into account. 42 | return True 43 | return x.startswith('\u2581') 44 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/data/encoders/space_tokenizer.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import re 7 | 8 | from fairseq.data.encoders import register_tokenizer 9 | 10 | 11 | @register_tokenizer('space') 12 | class SpaceTokenizer(object): 13 | 14 | def __init__(self, source_lang=None, target_lang=None): 15 | self.space_tok = re.compile(r"\s+") 16 | 17 | def encode(self, x: str) -> str: 18 | return self.space_tok.sub(' ', x) 19 | 20 | def decode(self, x: str) -> str: 21 | return x 22 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/data/encoders/subword_nmt_bpe.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from fairseq import file_utils 7 | from fairseq.data.encoders import register_bpe 8 | 9 | 10 | @register_bpe('subword_nmt') 11 | class SubwordNMTBPE(object): 12 | 13 | @staticmethod 14 | def add_args(parser): 15 | # fmt: off 16 | parser.add_argument('--bpe-codes', type=str, 17 | help='path to subword NMT BPE') 18 | parser.add_argument('--bpe-separator', default='@@', 19 | help='BPE separator') 20 | # fmt: on 21 | 22 | def __init__(self, args): 23 | if args.bpe_codes is None: 24 | raise ValueError('--bpe-codes is required for --bpe=subword_nmt') 25 | codes = file_utils.cached_path(args.bpe_codes) 26 | try: 27 | from subword_nmt import apply_bpe 28 | bpe_parser = apply_bpe.create_parser() 29 | bpe_args = bpe_parser.parse_args([ 30 | '--codes', codes, 31 | '--separator', args.bpe_separator, 32 | ]) 33 | self.bpe = apply_bpe.BPE( 34 | bpe_args.codes, 35 | bpe_args.merges, 36 | bpe_args.separator, 37 | None, 38 | bpe_args.glossaries, 39 | ) 40 | self.bpe_symbol = bpe_args.separator + ' ' 41 | except ImportError: 42 | raise ImportError('Please install subword_nmt with: pip install subword-nmt') 43 | 44 | def encode(self, x: str) -> str: 45 | return self.bpe.process_line(x) 46 | 47 | def decode(self, x: str) -> str: 48 | return (x + ' ').replace(self.bpe_symbol, '').rstrip() 49 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/data/encoders/utils.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import torch 7 | from fairseq.data import encoders 8 | 9 | 10 | def get_whole_word_mask(args, dictionary): 11 | bpe = encoders.build_bpe(args) 12 | if bpe is not None: 13 | def is_beginning_of_word(i): 14 | if i < dictionary.nspecial: 15 | # special elements are always considered beginnings 16 | return True 17 | tok = dictionary[i] 18 | if tok.startswith('madeupword'): 19 | return True 20 | try: 21 | return bpe.is_beginning_of_word(tok) 22 | except ValueError: 23 | return True 24 | mask_whole_words = torch.ByteTensor(list( 25 | map(is_beginning_of_word, range(len(dictionary))) 26 | )) 27 | return mask_whole_words 28 | return None 29 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/data/id_dataset.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import torch 7 | 8 | from . import FairseqDataset 9 | 10 | 11 | class IdDataset(FairseqDataset): 12 | 13 | def __getitem__(self, index): 14 | return index 15 | 16 | def __len__(self): 17 | return 0 18 | 19 | def collater(self, samples): 20 | return torch.tensor(samples) 21 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/data/legacy/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from .masked_lm_dictionary import BertDictionary, MaskedLMDictionary 7 | from .block_pair_dataset import BlockPairDataset 8 | from .masked_lm_dataset import MaskedLMDataset 9 | 10 | __all__ = [ 11 | 'BertDictionary', 12 | 'BlockPairDataset', 13 | 'MaskedLMDataset', 14 | 'MaskedLMDictionary', 15 | ] 16 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/data/legacy/masked_lm_dictionary.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from fairseq.data import Dictionary 7 | 8 | 9 | class MaskedLMDictionary(Dictionary): 10 | """ 11 | Dictionary for Masked Language Modelling tasks. This extends Dictionary by 12 | adding the mask symbol. 13 | """ 14 | def __init__( 15 | self, 16 | pad='', 17 | eos='', 18 | unk='', 19 | mask='', 20 | ): 21 | super().__init__(pad=pad, eos=eos, unk=unk) 22 | self.mask_word = mask 23 | self.mask_index = self.add_symbol(mask) 24 | self.nspecial = len(self.symbols) 25 | 26 | def mask(self): 27 | """Helper to get index of mask symbol""" 28 | return self.mask_index 29 | 30 | 31 | class BertDictionary(MaskedLMDictionary): 32 | """ 33 | Dictionary for BERT task. This extends MaskedLMDictionary by adding support 34 | for cls and sep symbols. 35 | """ 36 | def __init__( 37 | self, 38 | pad='', 39 | eos='', 40 | unk='', 41 | mask='', 42 | cls='', 43 | sep='' 44 | ): 45 | super().__init__(pad=pad, eos=eos, unk=unk) 46 | self.cls_word = cls 47 | self.sep_word = sep 48 | self.cls_index = self.add_symbol(cls) 49 | self.sep_index = self.add_symbol(sep) 50 | self.nspecial = len(self.symbols) 51 | 52 | def cls(self): 53 | """Helper to get index of cls symbol""" 54 | return self.cls_index 55 | 56 | def sep(self): 57 | """Helper to get index of sep symbol""" 58 | return self.sep_index 59 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/data/list_dataset.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from . import BaseWrapperDataset 7 | 8 | 9 | class ListDataset(BaseWrapperDataset): 10 | 11 | def __init__(self, dataset, sizes=None): 12 | super().__init__(dataset) 13 | self._sizes = sizes 14 | 15 | def __iter__(self): 16 | for x in self.dataset: 17 | yield x 18 | 19 | def collater(self, samples): 20 | return samples 21 | 22 | @property 23 | def sizes(self): 24 | return self._sizes 25 | 26 | def num_tokens(self, index): 27 | return self.sizes[index] 28 | 29 | def size(self, index): 30 | return self.sizes[index] 31 | 32 | def set_epoch(self, epoch): 33 | pass 34 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/data/lru_cache_dataset.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from functools import lru_cache 7 | 8 | from . import BaseWrapperDataset 9 | 10 | 11 | class LRUCacheDataset(BaseWrapperDataset): 12 | 13 | def __init__(self, dataset, token=None): 14 | super().__init__(dataset) 15 | 16 | @lru_cache(maxsize=8) 17 | def __getitem__(self, index): 18 | return self.dataset[index] 19 | 20 | @lru_cache(maxsize=8) 21 | def collater(self, samples): 22 | return self.dataset.collater(samples) 23 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/data/num_samples_dataset.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from . import FairseqDataset 7 | 8 | 9 | class NumSamplesDataset(FairseqDataset): 10 | 11 | def __getitem__(self, index): 12 | return 1 13 | 14 | def __len__(self): 15 | return 0 16 | 17 | def collater(self, samples): 18 | return sum(samples) 19 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/data/numel_dataset.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import numpy as np 7 | import torch 8 | 9 | from . import BaseWrapperDataset 10 | 11 | 12 | class NumelDataset(BaseWrapperDataset): 13 | 14 | def __init__(self, dataset, reduce=False): 15 | super().__init__(dataset) 16 | self.reduce = reduce 17 | 18 | def __getitem__(self, index): 19 | item = self.dataset[index] 20 | if torch.is_tensor(item): 21 | return torch.numel(item) 22 | else: 23 | return np.size(item) 24 | 25 | def __len__(self): 26 | return len(self.dataset) 27 | 28 | def collater(self, samples): 29 | if self.reduce: 30 | return sum(samples) 31 | else: 32 | return torch.tensor(samples) 33 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/data/offset_tokens_dataset.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from . import BaseWrapperDataset 7 | 8 | 9 | class OffsetTokensDataset(BaseWrapperDataset): 10 | 11 | def __init__(self, dataset, offset): 12 | super().__init__(dataset) 13 | self.offset = offset 14 | 15 | def __getitem__(self, idx): 16 | return self.dataset[idx] + self.offset 17 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/data/pad_dataset.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from fairseq.data import data_utils 7 | 8 | from . import BaseWrapperDataset 9 | 10 | 11 | class PadDataset(BaseWrapperDataset): 12 | 13 | def __init__(self, dataset, pad_idx, left_pad): 14 | super().__init__(dataset) 15 | self.pad_idx = pad_idx 16 | self.left_pad = left_pad 17 | 18 | def collater(self, samples): 19 | return data_utils.collate_tokens(samples, self.pad_idx, left_pad=self.left_pad) 20 | 21 | 22 | class LeftPadDataset(PadDataset): 23 | 24 | def __init__(self, dataset, pad_idx): 25 | super().__init__(dataset, pad_idx, left_pad=True) 26 | 27 | 28 | class RightPadDataset(PadDataset): 29 | 30 | def __init__(self, dataset, pad_idx): 31 | super().__init__(dataset, pad_idx, left_pad=False) 32 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/data/prepend_dataset.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import numpy as np 7 | import torch 8 | 9 | from . import BaseWrapperDataset 10 | 11 | 12 | class PrependDataset(BaseWrapperDataset): 13 | def __init__(self, dataset, prepend_getter, ensure_first_token_is=None): 14 | super().__init__(dataset) 15 | self.prepend_getter = prepend_getter 16 | self.ensure_first_token = ensure_first_token_is 17 | 18 | def __getitem__(self, idx): 19 | item = self.dataset[idx] 20 | is_tuple = isinstance(item, tuple) 21 | src = item[0] if is_tuple else item 22 | 23 | assert self.ensure_first_token is None or src[0] == self.ensure_first_token 24 | prepend_idx = self.prepend_getter(self.dataset, idx) 25 | assert isinstance(prepend_idx, int) 26 | src[0] = prepend_idx 27 | item = tuple((src,) + item[1:]) if is_tuple else src 28 | return item 29 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/data/prepend_token_dataset.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import numpy as np 7 | import torch 8 | 9 | from . import BaseWrapperDataset 10 | 11 | 12 | class PrependTokenDataset(BaseWrapperDataset): 13 | 14 | def __init__(self, dataset, token=None): 15 | super().__init__(dataset) 16 | self.token = token 17 | if token is not None: 18 | self._sizes = np.array(dataset.sizes) + 1 19 | else: 20 | self._sizes = dataset.sizes 21 | 22 | def __getitem__(self, idx): 23 | item = self.dataset[idx] 24 | if self.token is not None: 25 | item = torch.cat([item.new([self.token]), item]) 26 | return item 27 | 28 | @property 29 | def sizes(self): 30 | return self._sizes 31 | 32 | def num_tokens(self, index): 33 | n = self.dataset.num_tokens(index) 34 | if self.token is not None: 35 | n += 1 36 | return n 37 | 38 | def size(self, index): 39 | n = self.dataset.size(index) 40 | if self.token is not None: 41 | n += 1 42 | return n 43 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/data/raw_label_dataset.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import torch 7 | 8 | from . import FairseqDataset 9 | 10 | 11 | class RawLabelDataset(FairseqDataset): 12 | 13 | def __init__(self, labels): 14 | super().__init__() 15 | self.labels = labels 16 | 17 | def __getitem__(self, index): 18 | return self.labels[index] 19 | 20 | def __len__(self): 21 | return len(self.labels) 22 | 23 | def collater(self, samples): 24 | return torch.tensor(samples) 25 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/data/replace_dataset.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from . import BaseWrapperDataset 7 | 8 | 9 | class ReplaceDataset(BaseWrapperDataset): 10 | """Replaces tokens found in the dataset by a specified replacement token 11 | 12 | Args: 13 | dataset (~torch.utils.data.Dataset): dataset to replace tokens in 14 | replace_map(Dictionary[int,int]): map of token to replace -> replacement token 15 | offsets (List[int]): do not replace tokens before (from left if pos, right if neg) this offset. should be 16 | as many as the number of objects returned by the underlying dataset __getitem__ method. 17 | """ 18 | 19 | def __init__(self, dataset, replace_map, offsets): 20 | super().__init__(dataset) 21 | assert len(replace_map) > 0 22 | self.replace_map = replace_map 23 | self.offsets = offsets 24 | 25 | def __getitem__(self, index): 26 | item = self.dataset[index] 27 | is_tuple = isinstance(item, tuple) 28 | srcs = item if is_tuple else [item] 29 | 30 | for offset, src in zip(self.offsets, srcs): 31 | for k, v in self.replace_map.items(): 32 | src_off = src[offset:] if offset >= 0 else src[:offset] 33 | src_off.masked_fill_(src_off == k, v) 34 | 35 | item = srcs if is_tuple else srcs[0] 36 | return item 37 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/data/roll_dataset.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import torch 7 | 8 | from . import BaseWrapperDataset 9 | 10 | 11 | class RollDataset(BaseWrapperDataset): 12 | 13 | def __init__(self, dataset, shifts): 14 | super().__init__(dataset) 15 | self.shifts = shifts 16 | 17 | def __getitem__(self, index): 18 | item = self.dataset[index] 19 | return torch.roll(item, self.shifts) 20 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/data/sort_dataset.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import numpy as np 7 | 8 | from . import BaseWrapperDataset 9 | 10 | 11 | class SortDataset(BaseWrapperDataset): 12 | 13 | def __init__(self, dataset, sort_order): 14 | super().__init__(dataset) 15 | if not isinstance(sort_order, (list, tuple)): 16 | sort_order = [sort_order] 17 | self.sort_order = sort_order 18 | 19 | assert all(len(so) == len(dataset) for so in sort_order) 20 | 21 | def ordered_indices(self): 22 | return np.lexsort(self.sort_order) 23 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/data/strip_token_dataset.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from . import BaseWrapperDataset 7 | 8 | 9 | class StripTokenDataset(BaseWrapperDataset): 10 | 11 | def __init__(self, dataset, id_to_strip): 12 | super().__init__(dataset) 13 | self.id_to_strip = id_to_strip 14 | 15 | def __getitem__(self, index): 16 | item = self.dataset[index] 17 | while len(item) > 0 and item[-1] == self.id_to_strip: 18 | item = item[:-1] 19 | while len(item) > 0 and item[0] == self.id_to_strip: 20 | item = item[1:] 21 | return item 22 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/incremental_decoding_utils.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from typing import Dict, Optional 7 | import uuid 8 | 9 | from torch import Tensor 10 | 11 | 12 | class FairseqIncrementalState(object): 13 | 14 | def __init__(self, *args, **kwargs): 15 | super().__init__(*args, **kwargs) 16 | self.init_incremental_state() 17 | 18 | def init_incremental_state(self): 19 | self._incremental_state_id = str(uuid.uuid4()) 20 | 21 | def _get_full_incremental_state_key(self, key: str) -> str: 22 | return "{}.{}".format(self._incremental_state_id, key) 23 | 24 | def get_incremental_state( 25 | self, 26 | incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]], 27 | key: str, 28 | ) -> Optional[Dict[str, Optional[Tensor]]]: 29 | """Helper for getting incremental state for an nn.Module.""" 30 | full_key = self._get_full_incremental_state_key(key) 31 | if incremental_state is None or full_key not in incremental_state: 32 | return None 33 | return incremental_state[full_key] 34 | 35 | def set_incremental_state( 36 | self, 37 | incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]], 38 | key: str, 39 | value: Dict[str, Optional[Tensor]], 40 | ) -> Optional[Dict[str, Dict[str, Optional[Tensor]]]]: 41 | """Helper for setting incremental state for an nn.Module.""" 42 | if incremental_state is not None: 43 | full_key = self._get_full_incremental_state_key(key) 44 | incremental_state[full_key] = value 45 | return incremental_state 46 | 47 | 48 | def with_incremental_state(cls): 49 | cls.__bases__ = (FairseqIncrementalState,) + tuple(b for b in cls.__bases__ if b != FairseqIncrementalState) 50 | return cls 51 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/logging/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amazon-science/BartGraphSumm/9681651faad37938909cacb1d7b998f911ab3d9b/src/fairseq/fairseq/logging/__init__.py -------------------------------------------------------------------------------- /src/fairseq/fairseq/model_parallel/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from . import criterions, modules, models # noqa 7 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/model_parallel/criterions/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import importlib 7 | import os 8 | 9 | 10 | # automatically import any Python files in the criterions/ directory 11 | for file in os.listdir(os.path.dirname(__file__)): 12 | if file.endswith('.py') and not file.startswith('_'): 13 | module = file[:file.find('.py')] 14 | importlib.import_module('fairseq.model_parallel.criterions.' + module) 15 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/model_parallel/megatron_trainer.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | """ 7 | Train a network across multiple GPUs. 8 | """ 9 | 10 | from fairseq import distributed_utils 11 | from fairseq.trainer import Trainer 12 | 13 | try: 14 | from fairseq.model_parallel.megatron.mpu import ( 15 | get_data_parallel_group, 16 | get_data_parallel_rank, 17 | get_data_parallel_world_size, 18 | get_model_parallel_group, 19 | get_model_parallel_src_rank, 20 | ) 21 | has_megatron_submodule = True 22 | except (ImportError, ModuleNotFoundError): 23 | has_megatron_submodule = False 24 | 25 | 26 | class MegatronTrainer(Trainer): 27 | """Main class for model parallel with data parallel training. 28 | """ 29 | def __init__(self, args, task, model, criterion): 30 | if not has_megatron_submodule: 31 | raise ImportError( 32 | '\n\nPlease install the megatron submodule:' 33 | '\n\n git submodule update --init ' 34 | 'fairseq/model_parallel/megatron' 35 | ) 36 | super().__init__(args, task, model, criterion) 37 | 38 | @property 39 | def data_parallel_world_size(self): 40 | return get_data_parallel_world_size() 41 | 42 | @property 43 | def data_parallel_process_group(self): 44 | return get_data_parallel_group() 45 | 46 | @property 47 | def data_parallel_rank(self): 48 | return get_data_parallel_rank() 49 | 50 | @property 51 | def is_data_parallel_master(self): 52 | return get_model_parallel_src_rank() == 0 53 | 54 | def clip_grad_norm(self, clip_norm): 55 | def _aggregate_model_parallel_grad_norm(total_norm): 56 | total_norm = total_norm ** 2 57 | distributed_utils.all_reduce(total_norm, group=get_model_parallel_group()) 58 | total_norm = total_norm ** 0.5 59 | return total_norm 60 | return self.optimizer.clip_grad_norm( 61 | clip_norm, 62 | aggregate_norm_fn=_aggregate_model_parallel_grad_norm, 63 | ) 64 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/model_parallel/models/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import importlib 7 | import os 8 | 9 | 10 | # automatically import any Python files in the models/ directory 11 | models_dir = os.path.dirname(__file__) 12 | for file in os.listdir(models_dir): 13 | path = os.path.join(models_dir, file) 14 | if not file.startswith('_') and not file.startswith('.') and (file.endswith('.py') or os.path.isdir(path)): 15 | model_name = file[:file.find('.py')] if file.endswith('.py') else file 16 | module = importlib.import_module('fairseq.model_parallel.models.' + model_name) 17 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/model_parallel/models/roberta/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from .model import * # noqa 7 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/model_parallel/modules/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from .multihead_attention import ModelParallelMultiheadAttention 7 | from .transformer_layer import ModelParallelTransformerEncoderLayer, ModelParallelTransformerDecoderLayer 8 | from .transformer_sentence_encoder_layer import ModelParallelTransformerSentenceEncoderLayer 9 | from .transformer_sentence_encoder import ModelParallelTransformerSentenceEncoder 10 | 11 | __all__ = [ 12 | 'ModelParallelMultiheadAttention', 13 | 'ModelParallelTransformerEncoderLayer', 14 | 'ModelParallelTransformerDecoderLayer', 15 | 'ModelParallelTransformerSentenceEncoder', 16 | 'ModelParallelTransformerSentenceEncoderLayer', 17 | ] 18 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/model_parallel/modules/transformer_sentence_encoder.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from typing import Optional, Tuple 7 | 8 | import torch 9 | import torch.nn as nn 10 | import torch.nn.functional as F 11 | from fairseq.modules import ( 12 | LayerNorm, 13 | MultiheadAttention, 14 | PositionalEmbedding, 15 | TransformerSentenceEncoder, 16 | ) 17 | 18 | from fairseq.model_parallel.modules import ( 19 | ModelParallelTransformerSentenceEncoderLayer, 20 | ) 21 | 22 | try: 23 | from fairseq.model_parallel.megatron.mpu import ( 24 | copy_to_model_parallel_region, 25 | gather_from_model_parallel_region, 26 | VocabParallelEmbedding, 27 | ) 28 | has_megatron_submodule = True 29 | except (ImportError, ModuleNotFoundError): 30 | has_megatron_submodule = False 31 | 32 | import random 33 | 34 | 35 | class ModelParallelTransformerSentenceEncoder(TransformerSentenceEncoder): 36 | """ 37 | Implementation for a Model Parallel Bi-directional Transformer based 38 | Sentence Encoder used in BERT/XLM style pre-trained models. 39 | """ 40 | def build_embedding(self, vocab_size, embedding_dim, padding_idx): 41 | return VocabParallelEmbedding(vocab_size, embedding_dim, padding_idx) 42 | 43 | def build_transformer_sentence_encoder_layer( 44 | self, 45 | embedding_dim, 46 | ffn_embedding_dim, 47 | num_attention_heads, 48 | dropout, 49 | attention_dropout, 50 | activation_dropout, 51 | activation_fn, 52 | export, 53 | **unused, 54 | ): 55 | return ModelParallelTransformerSentenceEncoderLayer( 56 | embedding_dim=embedding_dim, 57 | ffn_embedding_dim=ffn_embedding_dim, 58 | num_attention_heads=num_attention_heads, 59 | dropout=dropout, 60 | attention_dropout=attention_dropout, 61 | activation_dropout=activation_dropout, 62 | activation_fn=activation_fn, 63 | export=export, 64 | ) 65 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/models/bart/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from .hub_interface import * # noqa 7 | from .model import * # noqa 8 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/models/composite_encoder.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from fairseq.models import FairseqEncoder 7 | 8 | 9 | class CompositeEncoder(FairseqEncoder): 10 | """ 11 | A wrapper around a dictionary of :class:`FairseqEncoder` objects. 12 | 13 | We run forward on each encoder and return a dictionary of outputs. The first 14 | encoder's dictionary is used for initialization. 15 | 16 | Args: 17 | encoders (dict): a dictionary of :class:`FairseqEncoder` objects. 18 | """ 19 | 20 | def __init__(self, encoders): 21 | super().__init__(next(iter(encoders.values())).dictionary) 22 | self.encoders = encoders 23 | for key in self.encoders: 24 | self.add_module(key, self.encoders[key]) 25 | 26 | def forward(self, src_tokens, src_lengths): 27 | """ 28 | Args: 29 | src_tokens (LongTensor): tokens in the source language of shape 30 | `(batch, src_len)` 31 | src_lengths (LongTensor): lengths of each source sentence of shape 32 | `(batch)` 33 | 34 | Returns: 35 | dict: 36 | the outputs from each Encoder 37 | """ 38 | encoder_out = {} 39 | for key in self.encoders: 40 | encoder_out[key] = self.encoders[key](src_tokens, src_lengths) 41 | return encoder_out 42 | 43 | def reorder_encoder_out(self, encoder_out, new_order): 44 | """Reorder encoder output according to new_order.""" 45 | for key in self.encoders: 46 | encoder_out[key] = self.encoders[key].reorder_encoder_out(encoder_out[key], new_order) 47 | return encoder_out 48 | 49 | def max_positions(self): 50 | return min(self.encoders[key].max_positions() for key in self.encoders) 51 | 52 | def upgrade_state_dict(self, state_dict): 53 | for key in self.encoders: 54 | self.encoders[key].upgrade_state_dict(state_dict) 55 | return state_dict 56 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/models/huggingface/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import importlib 7 | import os 8 | 9 | 10 | # automatically import any Python files in the models/huggingface/ directory 11 | models_dir = os.path.dirname(__file__) 12 | for file in os.listdir(models_dir): 13 | path = os.path.join(models_dir, file) 14 | if ( 15 | not file.startswith('_') 16 | and not file.startswith('.') 17 | and (file.endswith('.py') or os.path.isdir(path)) 18 | ): 19 | model_name = file[:file.find('.py')] if file.endswith('.py') else file 20 | module = importlib.import_module('fairseq.models.huggingface.' + model_name) 21 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/models/nat/__init__.py: -------------------------------------------------------------------------------- 1 | from .fairseq_nat_model import * 2 | from .nonautoregressive_transformer import * 3 | from .nat_crf_transformer import * 4 | from .iterative_nonautoregressive_transformer import * 5 | from .cmlm_transformer import * 6 | from .levenshtein_transformer import * 7 | from .insertion_transformer import * 8 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/models/roberta/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from .hub_interface import * # noqa 7 | from .model import * # noqa 8 | from .model_camembert import * # noqa 9 | from .model_xlmr import * # noqa 10 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/models/roberta/model_camembert.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | """ 6 | CamemBERT: a Tasty French Language Model 7 | """ 8 | 9 | from fairseq.models import register_model 10 | 11 | from .hub_interface import RobertaHubInterface 12 | from .model import RobertaModel 13 | 14 | 15 | @register_model('camembert') 16 | class CamembertModel(RobertaModel): 17 | 18 | @classmethod 19 | def hub_models(cls): 20 | return { 21 | 'camembert': 'http://dl.fbaipublicfiles.com/fairseq/models/camembert-base.tar.gz', 22 | 'camembert.v0': 'http://dl.fbaipublicfiles.com/fairseq/models/camembert-base.tar.gz', 23 | 'camembert-base': 'http://dl.fbaipublicfiles.com/fairseq/models/camembert-base.tar.gz', 24 | 'camembert-large': 'http://dl.fbaipublicfiles.com/fairseq/models/camembert-large.tar.gz', 25 | 'camembert-base-ccnet': 'http://dl.fbaipublicfiles.com/fairseq/models/camembert-base-ccnet.tar.gz', 26 | 'camembert-base-ccnet-4gb': 'http://dl.fbaipublicfiles.com/fairseq/models/camembert-base-ccnet-4gb.tar.gz', 27 | 'camembert-base-wikipedia-4gb': 'http://dl.fbaipublicfiles.com/fairseq/models/camembert-base-wikipedia-4gb.tar.gz', 28 | 'camembert-base-oscar-4gb': 'http://dl.fbaipublicfiles.com/fairseq/models/camembert-base-oscar-4gb.tar.gz', 29 | } 30 | 31 | @classmethod 32 | def from_pretrained(cls, model_name_or_path, checkpoint_file='model.pt', data_name_or_path='.', bpe='sentencepiece', **kwargs): 33 | from fairseq import hub_utils 34 | x = hub_utils.from_pretrained( 35 | model_name_or_path, 36 | checkpoint_file, 37 | data_name_or_path, 38 | archive_map=cls.hub_models(), 39 | bpe=bpe, 40 | load_checkpoint_heads=True, 41 | **kwargs, 42 | ) 43 | return RobertaHubInterface(x['args'], x['task'], x['models'][0]) 44 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/models/roberta/model_xlmr.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | """ 6 | Unsupervised Cross-lingual Representation Learning at Scale 7 | """ 8 | 9 | from fairseq.models import register_model 10 | 11 | from .hub_interface import RobertaHubInterface 12 | from .model import RobertaModel 13 | 14 | 15 | @register_model('xlmr') 16 | class XLMRModel(RobertaModel): 17 | 18 | @classmethod 19 | def hub_models(cls): 20 | return { 21 | 'xlmr.base': 'http://dl.fbaipublicfiles.com/fairseq/models/xlmr.base.tar.gz', 22 | 'xlmr.large': 'http://dl.fbaipublicfiles.com/fairseq/models/xlmr.large.tar.gz', 23 | } 24 | 25 | @classmethod 26 | def from_pretrained(cls, model_name_or_path, checkpoint_file='model.pt', data_name_or_path='.', bpe='sentencepiece', **kwargs): 27 | from fairseq import hub_utils 28 | x = hub_utils.from_pretrained( 29 | model_name_or_path, 30 | checkpoint_file, 31 | data_name_or_path, 32 | archive_map=cls.hub_models(), 33 | bpe=bpe, 34 | load_checkpoint_heads=True, 35 | **kwargs, 36 | ) 37 | return RobertaHubInterface(x['args'], x['task'], x['models'][0]) 38 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/modules/beamable_mm.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import torch 7 | import torch.nn as nn 8 | 9 | 10 | class BeamableMM(nn.Module): 11 | """This module provides an optimized MM for beam decoding with attention. 12 | 13 | It leverage the fact that the source-side of the input is replicated beam 14 | times and the target-side of the input is of width one. This layer speeds up 15 | inference by replacing the inputs {(bsz x 1 x nhu), (bsz x sz2 x nhu)} 16 | with smaller inputs {(bsz/beam x beam x nhu), (bsz/beam x sz2 x nhu)}. 17 | """ 18 | def __init__(self, beam_size=None): 19 | super(BeamableMM, self).__init__() 20 | self.beam_size = beam_size 21 | 22 | def forward(self, input1, input2): 23 | if ( 24 | not self.training and # test mode 25 | self.beam_size is not None and # beam size is set 26 | input1.dim() == 3 and # only support batched input 27 | input1.size(1) == 1 # single time step update 28 | ): 29 | bsz, beam = input1.size(0), self.beam_size 30 | 31 | # bsz x 1 x nhu --> bsz/beam x beam x nhu 32 | input1 = input1[:, 0, :].unfold(0, beam, beam).transpose(2, 1) 33 | 34 | # bsz x sz2 x nhu --> bsz/beam x sz2 x nhu 35 | input2 = input2.unfold(0, beam, beam)[:, :, :, 0] 36 | 37 | # use non batched operation if bsz = beam 38 | if input1.size(0) == 1: 39 | output = torch.mm(input1[0, :, :], input2[0, :, :]) 40 | else: 41 | output = input1.bmm(input2) 42 | return output.view(bsz, 1, -1) 43 | else: 44 | return input1.bmm(input2) 45 | 46 | def set_beam_size(self, beam_size): 47 | self.beam_size = beam_size 48 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/modules/conv_tbc.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import torch 7 | from torch.nn.modules.utils import _single 8 | 9 | 10 | class ConvTBC(torch.nn.Module): 11 | """1D convolution over an input of shape (time x batch x channel) 12 | 13 | The implementation uses gemm to perform the convolution. This implementation 14 | is faster than cuDNN for small kernel sizes. 15 | """ 16 | def __init__(self, in_channels, out_channels, kernel_size, padding=0): 17 | super(ConvTBC, self).__init__() 18 | self.in_channels = in_channels 19 | self.out_channels = out_channels 20 | self.kernel_size = _single(kernel_size) 21 | self.padding = _single(padding) 22 | 23 | self.weight = torch.nn.Parameter(torch.Tensor( 24 | self.kernel_size[0], in_channels, out_channels)) 25 | self.bias = torch.nn.Parameter(torch.Tensor(out_channels)) 26 | 27 | def forward(self, input): 28 | return torch.conv_tbc(input.contiguous(), self.weight, self.bias, self.padding[0]) 29 | 30 | def __repr__(self): 31 | s = ('{name}({in_channels}, {out_channels}, kernel_size={kernel_size}' 32 | ', padding={padding}') 33 | if self.bias is None: 34 | s += ', bias=False' 35 | s += ')' 36 | return s.format(name=self.__class__.__name__, **self.__dict__) 37 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/modules/cross_entropy.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import logging 7 | 8 | import torch 9 | import torch.nn.functional as F 10 | 11 | 12 | logger = logging.getLogger(__name__) 13 | 14 | 15 | def _cross_entropy_pytorch(logits, target, ignore_index=None, reduction='mean'): 16 | lprobs = F.log_softmax(logits, dim=-1, dtype=torch.float32) 17 | return F.nll_loss( 18 | lprobs, target, ignore_index=ignore_index, reduction=reduction, 19 | ) 20 | 21 | 22 | try: 23 | import xentropy_cuda 24 | from apex.contrib import xentropy 25 | 26 | logger.info('using fused cross entropy') 27 | 28 | def cross_entropy(logits, target, ignore_index=-100, reduction='mean'): 29 | if logits.device == torch.device('cpu'): 30 | return _cross_entropy_pytorch(logits, target, ignore_index, reduction) 31 | else: 32 | half_to_float = (logits.dtype == torch.half) 33 | losses = xentropy.SoftmaxCrossEntropyLoss.apply( 34 | logits, target, 0.0, ignore_index, half_to_float, 35 | ) 36 | if reduction == 'sum': 37 | return losses.sum() 38 | elif reduction == 'mean': 39 | if ignore_index >= 0: 40 | return losses.sum() / target.ne(ignore_index).sum() 41 | else: 42 | return losses.mean() 43 | elif reduction == 'none': 44 | return losses 45 | else: 46 | raise NotImplementedError 47 | 48 | except ImportError: 49 | 50 | def cross_entropy(logits, target, ignore_index=-100, reduction='mean'): 51 | return _cross_entropy_pytorch(logits, target, ignore_index, reduction) 52 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/modules/dynamicconv_layer/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from .dynamicconv_layer import DynamicconvLayer # noqa 7 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/modules/dynamicconv_layer/dynamicconv_cuda.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Facebook, Inc. and its affiliates. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | #include 9 | #include 10 | 11 | std::vector dynamicconv_cuda_forward( 12 | at::Tensor input, 13 | at::Tensor filters, 14 | int padding_l); 15 | 16 | std::vector dynamicconv_cuda_backward( 17 | at::Tensor gradOutput, 18 | int padding_l, 19 | at::Tensor input, 20 | at::Tensor filters); 21 | 22 | 23 | #define CHECK_CUDA(x) AT_ASSERTM(x.type().is_cuda(), #x " must be a CUDA tensor") 24 | #define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x " must be contiguous") 25 | #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) 26 | 27 | std::vector dynamicconv_forward( 28 | at::Tensor input, 29 | at::Tensor filters, 30 | int padding_l) { 31 | 32 | CHECK_INPUT(input); 33 | CHECK_INPUT(filters); 34 | 35 | return dynamicconv_cuda_forward(input, filters, 36 | padding_l); 37 | } 38 | 39 | std::vector dynamicconv_backward( 40 | at::Tensor gradOutput, 41 | int padding_l, 42 | at::Tensor input, 43 | at::Tensor filters) { 44 | 45 | CHECK_INPUT(gradOutput); 46 | CHECK_INPUT(input); 47 | CHECK_INPUT(filters); 48 | 49 | return dynamicconv_cuda_backward(gradOutput, padding_l, 50 | input, filters); 51 | } 52 | 53 | PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { 54 | m.def("forward", &dynamicconv_forward, "dynamicconv forward (CUDA)"); 55 | m.def("backward", &dynamicconv_backward, "dynamicconv backward (CUDA)"); 56 | } 57 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/modules/dynamicconv_layer/dynamicconv_cuda.cuh: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Facebook, Inc. and its affiliates. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | #include 9 | #include 10 | 11 | #include 12 | #include 13 | #include 14 | 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | 22 | #include 23 | #include 24 | #include 25 | 26 | #define SHFL_MASK 0xffffffff 27 | 28 | template 29 | __global__ 30 | void dynamicconv_forward_kernel(const scalar_t* input, 31 | const scalar_t* weight, 32 | int minibatch, 33 | int sequenceLength, 34 | int numFeatures, 35 | int numFiltersInBlock, 36 | int numHeads, 37 | scalar_t* output); 38 | 39 | template 40 | __global__ 41 | void dynamicconv_backward_kernel( 42 | const scalar_t* gradOutput, // B * C * T 43 | const scalar_t* input, // B * C * T 44 | const scalar_t* weight, 45 | int minibatch, 46 | int sequenceLength, 47 | int numFeatures, 48 | int numFiltersInBlock, 49 | int numHeads, 50 | scalar_t* gradWeight, 51 | scalar_t* gradInput); // B * H * k * T 52 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/modules/dynamicconv_layer/dynamiconv_cpu.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | std::vector dynamicconv_cpu_forward( 5 | float* input, 6 | float* filters, 7 | int padding_l); 8 | 9 | std::vector dynamicconv_cpu_backward( 10 | float* gradOutput, 11 | int padding_l, 12 | float* input, 13 | float* filters); 14 | 15 | std::vector dynamicconv_forward( 16 | float* input, 17 | float* filters, 18 | int padding_l) { 19 | 20 | return dynamicconv_cpu_forward(input, filters, padding_l); 21 | } 22 | 23 | std::vector dynamicconv_backward( 24 | float* gradOutput, 25 | int padding_l, 26 | float* input, 27 | float* filters) { 28 | 29 | return dynamicconv_cpu_backward(gradOutput, padding_l, input, filters); 30 | } 31 | 32 | PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { 33 | m.def("forward", &dynamicconv_forward, "dynamicconv forward (CPU)"); 34 | m.def("backward", &dynamicconv_backward, "dynamicconv backward (CPU)"); 35 | } 36 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/modules/dynamicconv_layer/setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (c) Facebook, Inc. and its affiliates. 3 | # 4 | # This source code is licensed under the MIT license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | 7 | from setuptools import setup 8 | from torch.utils.cpp_extension import CUDAExtension, BuildExtension 9 | 10 | setup( 11 | name='dynamicconv_layer', 12 | ext_modules=[ 13 | CUDAExtension( 14 | name='dynamicconv_cuda', 15 | sources=[ 16 | 'dynamicconv_cuda.cpp', 17 | 'dynamicconv_cuda_kernel.cu', 18 | ], 19 | ), 20 | ], 21 | cmdclass={ 22 | 'build_ext': BuildExtension 23 | }) 24 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/modules/fp32_group_norm.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | """ 6 | Layer norm done in fp32 (for fp16 training) 7 | """ 8 | 9 | import torch.nn as nn 10 | import torch.nn.functional as F 11 | 12 | 13 | class Fp32GroupNorm(nn.GroupNorm): 14 | def __init__(self, *args, **kwargs): 15 | super().__init__(*args, **kwargs) 16 | 17 | def forward(self, input): 18 | output = F.group_norm( 19 | input.float(), 20 | self.num_groups, 21 | self.weight.float() if self.weight is not None else None, 22 | self.bias.float() if self.bias is not None else None, 23 | self.eps, 24 | ) 25 | return output.type_as(input) 26 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/modules/gelu.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | """ 6 | See "Gaussian Error Linear Units (GELUs)" by Dan Hendrycks and Kevin Gimpel with 7 | the corresponding GitHub repo: https://github.com/hendrycks/GELUs 8 | """ 9 | 10 | import math 11 | 12 | import torch 13 | import torch.nn as nn 14 | 15 | 16 | def gelu_accurate(x): 17 | if not hasattr(gelu_accurate, "_a"): 18 | gelu_accurate._a = math.sqrt(2 / math.pi) 19 | return ( 20 | 0.5 * x * (1 + torch.tanh(gelu_accurate._a * (x + 0.044715 * torch.pow(x, 3)))) 21 | ) 22 | 23 | 24 | def gelu(x: torch.Tensor) -> torch.Tensor: 25 | return torch.nn.functional.gelu(x.float()).type_as(x) 26 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/modules/grad_multiply.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import torch 7 | 8 | 9 | class GradMultiply(torch.autograd.Function): 10 | @staticmethod 11 | def forward(ctx, x, scale): 12 | ctx.scale = scale 13 | res = x.new(x) 14 | return res 15 | 16 | @staticmethod 17 | def backward(ctx, grad): 18 | return grad * ctx.scale, None 19 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/modules/layer_drop.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | """ 6 | LayerDrop as described in https://arxiv.org/abs/1909.11556. 7 | """ 8 | 9 | import torch 10 | import torch.nn as nn 11 | 12 | 13 | class LayerDropModuleList(nn.ModuleList): 14 | """ 15 | A LayerDrop implementation based on :class:`torch.nn.ModuleList`. 16 | 17 | We refresh the choice of which layers to drop every time we iterate 18 | over the LayerDropModuleList instance. During evaluation we always 19 | iterate over all layers. 20 | 21 | Usage:: 22 | 23 | layers = LayerDropList(p=0.5, modules=[layer1, layer2, layer3]) 24 | for layer in layers: # this might iterate over layers 1 and 3 25 | x = layer(x) 26 | for layer in layers: # this might iterate over all layers 27 | x = layer(x) 28 | for layer in layers: # this might not iterate over any layers 29 | x = layer(x) 30 | 31 | Args: 32 | p (float): probability of dropping out each layer 33 | modules (iterable, optional): an iterable of modules to add 34 | """ 35 | 36 | def __init__(self, p, modules=None): 37 | super().__init__(modules) 38 | self.p = p 39 | 40 | def __iter__(self): 41 | dropout_probs = torch.empty(len(self)).uniform_() 42 | for i, m in enumerate(super().__iter__()): 43 | if not self.training or (dropout_probs[i] > self.p): 44 | yield m 45 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/modules/layer_norm.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import torch 7 | import torch.nn as nn 8 | import torch.nn.functional as F 9 | 10 | 11 | try: 12 | from apex.normalization import FusedLayerNorm as _FusedLayerNorm 13 | 14 | has_fused_layernorm = True 15 | 16 | class FusedLayerNorm(_FusedLayerNorm): 17 | @torch.jit.unused 18 | def forward(self, x): 19 | if not x.is_cuda: 20 | return super().forward(x) 21 | else: 22 | with torch.cuda.device(x.device): 23 | return super().forward(x) 24 | 25 | except ImportError: 26 | has_fused_layernorm = False 27 | 28 | 29 | def LayerNorm(normalized_shape, eps=1e-5, elementwise_affine=True, export=False): 30 | if not export and torch.cuda.is_available() and has_fused_layernorm: 31 | return FusedLayerNorm(normalized_shape, eps, elementwise_affine) 32 | return torch.nn.LayerNorm(normalized_shape, eps, elementwise_affine) 33 | 34 | 35 | class Fp32LayerNorm(nn.LayerNorm): 36 | def __init__(self, *args, **kwargs): 37 | super().__init__(*args, **kwargs) 38 | 39 | def forward(self, input): 40 | output = F.layer_norm( 41 | input.float(), 42 | self.normalized_shape, 43 | self.weight.float() if self.weight is not None else None, 44 | self.bias.float() if self.bias is not None else None, 45 | self.eps, 46 | ) 47 | return output.type_as(input) 48 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/modules/lightconv_layer/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from .lightconv_layer import LightconvLayer # noqa 7 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/modules/lightconv_layer/lightconv_cuda.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Facebook, Inc. and its affiliates. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | */ 7 | 8 | #include 9 | #include 10 | 11 | std::vector lightconv_cuda_forward( 12 | at::Tensor input, 13 | at::Tensor filters, 14 | int padding_l); 15 | 16 | std::vector lightconv_cuda_backward( 17 | at::Tensor gradOutput, 18 | int padding_l, 19 | at::Tensor input, 20 | at::Tensor filters); 21 | 22 | 23 | #define CHECK_CUDA(x) AT_ASSERTM(x.type().is_cuda(), #x " must be a CUDA tensor") 24 | #define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x " must be contiguous") 25 | #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) 26 | 27 | std::vector lightconv_forward( 28 | at::Tensor input, 29 | at::Tensor filters, 30 | int padding_l) { 31 | 32 | CHECK_INPUT(input); 33 | CHECK_INPUT(filters); 34 | 35 | return lightconv_cuda_forward(input, filters, padding_l); 36 | } 37 | 38 | std::vector lightconv_backward( 39 | at::Tensor gradOutput, 40 | int padding_l, 41 | at::Tensor input, 42 | at::Tensor filters) { 43 | 44 | CHECK_INPUT(gradOutput); 45 | CHECK_INPUT(input); 46 | CHECK_INPUT(filters); 47 | 48 | return lightconv_cuda_backward(gradOutput, padding_l, input, filters); 49 | } 50 | 51 | PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { 52 | m.def("forward", &lightconv_forward, "lighconv forward (CUDA)"); 53 | m.def("backward", &lightconv_backward, "lighconv backward (CUDA)"); 54 | } 55 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/modules/lightconv_layer/setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (c) Facebook, Inc. and its affiliates. 3 | # 4 | # This source code is licensed under the MIT license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | 7 | from setuptools import setup 8 | from torch.utils.cpp_extension import CUDAExtension, BuildExtension 9 | 10 | setup( 11 | name='lightconv_layer', 12 | ext_modules=[ 13 | CUDAExtension('lightconv_cuda', [ 14 | 'lightconv_cuda.cpp', 15 | 'lightconv_cuda_kernel.cu', 16 | ]), 17 | ], 18 | cmdclass={ 19 | 'build_ext': BuildExtension 20 | }) 21 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/modules/positional_embedding.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import torch.nn as nn 7 | from .learned_positional_embedding import LearnedPositionalEmbedding 8 | from .sinusoidal_positional_embedding import SinusoidalPositionalEmbedding 9 | 10 | 11 | def PositionalEmbedding( 12 | num_embeddings: int, 13 | embedding_dim: int, 14 | padding_idx: int, 15 | learned: bool = False, 16 | ): 17 | if learned: 18 | # if padding_idx is specified then offset the embedding ids by 19 | # this index and adjust num_embeddings appropriately 20 | # TODO: The right place for this offset would be inside 21 | # LearnedPositionalEmbedding. Move this there for a cleaner implementation. 22 | if padding_idx is not None: 23 | num_embeddings = num_embeddings + padding_idx + 1 24 | m = LearnedPositionalEmbedding(num_embeddings, embedding_dim, padding_idx) 25 | nn.init.normal_(m.weight, mean=0, std=embedding_dim ** -0.5) 26 | if padding_idx is not None: 27 | nn.init.constant_(m.weight[padding_idx], 0) 28 | else: 29 | m = SinusoidalPositionalEmbedding( 30 | embedding_dim, padding_idx, init_size=num_embeddings + padding_idx + 1, 31 | ) 32 | return m 33 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/modules/quantization/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amazon-science/BartGraphSumm/9681651faad37938909cacb1d7b998f911ab3d9b/src/fairseq/fairseq/modules/quantization/__init__.py -------------------------------------------------------------------------------- /src/fairseq/fairseq/modules/quantization/pq/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from .utils import SizeTracker, quantize_model_ # NOQA 7 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/modules/quantization/pq/modules/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from .qconv import PQConv2d # NOQA 7 | from .qlinear import PQLinear # NOQA 8 | from .qemb import PQEmbedding # NOQA 9 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/modules/quantization/quantization_options.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | 7 | def parse_config_yaml(yaml_data): 8 | # Initialize to default options. 9 | quantization_options = { 10 | "n_centroids": { 11 | "Linear": ["in_features", {"*": 256}], 12 | "Embedding": ["embedding_dim", {"*": 256}], 13 | }, 14 | "block_sizes": { 15 | "Linear": ["fuzzy_name", {"fc": 8, "attn": 4, "emb": 4}], 16 | "Embedding": ["fuzzy_name", {"emb": 8}], 17 | }, 18 | "layers_to_quantize": [ 19 | "decoder\\.layers\\.\\d+\\.fc[12]", 20 | "decoder\\.embed_tokens\\.embeddings\\.[012]\\.[01]", 21 | "decoder\\.layers\\.\\d+\\.self_attn\\.(k_proj|v_proj|q_proj|out_proj)", 22 | ], 23 | } 24 | 25 | if "n_centroids" in yaml_data: 26 | quantization_options["n_centroids"] = { 27 | layer: convert_yaml_to_tuple(layer_data) 28 | for layer, layer_data in yaml_data["n_centroids"].items() 29 | } 30 | if "block_sizes" in yaml_data: 31 | quantization_options["block_sizes"] = { 32 | layer: convert_yaml_to_tuple(layer_data) 33 | for layer, layer_data in yaml_data["block_sizes"].items() 34 | } 35 | if "layers_to_quantize" in yaml_data: 36 | quantization_options["layers_to_quantize"] = yaml_data["layers_to_quantize"] 37 | 38 | return quantization_options 39 | 40 | 41 | def convert_yaml_to_tuple(yaml_dictionary): 42 | """Converts a yaml dictionary with two keys: `key` and `value` into a two 43 | argument tuple of those values.""" 44 | return (yaml_dictionary["key"], yaml_dictionary["value"]) 45 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/modules/quantization/scalar/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from .utils import quantize_model_ # NOQA 7 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/modules/quantization/scalar/modules/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from .qconv import IntConv2d # NOQA 7 | from .qlinear import IntLinear # NOQA 8 | from .qemb import IntEmbedding # NOQA 9 | from .qact import ActivationQuantizer # NOQA 10 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/modules/quantization/scalar/ops.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import torch 7 | 8 | 9 | def emulate_int(w, bits, method, scale=None, zero_point=None): 10 | q = globals()[f"emulate_int{bits}_{method}"] 11 | return q(w, scale=scale, zero_point=zero_point) 12 | 13 | 14 | def quantize(w, scale, zero_point): 15 | return (torch.clamp(torch.round(w / scale + zero_point), 0, 255) - zero_point) * scale 16 | 17 | 18 | def emulate_int8_histogram(w, scale=None, zero_point=None): 19 | if scale is None: 20 | obs = torch.quantization.observer.HistogramObserver() 21 | _ = obs(w.float()) 22 | scale, zero_point = obs.calculate_qparams() 23 | scale = scale.cuda().type_as(w) 24 | zero_point = zero_point.cuda().type_as(w) 25 | return quantize(w, scale, zero_point), scale, zero_point 26 | 27 | 28 | def emulate_int8_channel(w, scale=None, zero_point=None): 29 | if scale is None: 30 | obs = torch.quantization.observer.PerChannelMinMaxObserver( 31 | ch_axis=-1, qscheme=torch.per_channel_symmetric 32 | ) 33 | _ = obs(w) 34 | scale, zero_point, ch_axis = obs.get_qparams() 35 | scale = scale.cuda().type_as(w) 36 | zero_point = zero_point.cuda().type_as(w) 37 | return quantize(w, scale, zero_point), scale, zero_point 38 | 39 | 40 | def emulate_int8_tensor(w, scale=None, zero_point=None): 41 | if scale is None: 42 | obs = torch.quantization.observer.MinMaxObserver() 43 | _ = obs(w) 44 | scale, zero_point = obs.calculate_qparams() 45 | scale = scale.cuda().type_as(w) 46 | zero_point = zero_point.cuda().type_as(w) 47 | return quantize(w, scale, zero_point), scale, zero_point 48 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/modules/scalar_bias.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | # 6 | 7 | import torch 8 | 9 | 10 | class ScalarBias(torch.autograd.Function): 11 | """ 12 | Adds a vector of scalars, used in self-attention mechanism to allow 13 | the model to optionally attend to this vector instead of the past 14 | """ 15 | 16 | @staticmethod 17 | def forward(ctx, input, dim, bias_init): 18 | size = list(input.size()) 19 | size[dim] += 1 20 | output = input.new(*size).fill_(bias_init) 21 | output.narrow(dim, 1, size[dim] - 1).copy_(input) 22 | ctx.dim = dim 23 | return output 24 | 25 | @staticmethod 26 | def backward(ctx, grad): 27 | return grad.narrow(ctx.dim, 1, grad.size(ctx.dim) - 1), None, None 28 | 29 | 30 | def scalar_bias(input, dim, bias_init=0): 31 | return ScalarBias.apply(input, dim, bias_init) 32 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/modules/sparse_transformer_sentence_encoder_layer.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from fairseq.modules import TransformerSentenceEncoderLayer 7 | from fairseq.modules.sparse_multihead_attention import SparseMultiheadAttention 8 | 9 | 10 | class SparseTransformerSentenceEncoderLayer(TransformerSentenceEncoderLayer): 11 | """ 12 | Implements a Sprase Transformer Encoder Layer (see SparseMultiheadAttention) 13 | """ 14 | 15 | def __init__( 16 | self, 17 | embedding_dim: int = 768, 18 | ffn_embedding_dim: int = 3072, 19 | num_attention_heads: int = 8, 20 | dropout: float = 0.1, 21 | attention_dropout: float = 0.1, 22 | activation_dropout: float = 0.1, 23 | activation_fn: str = 'relu', 24 | export: bool = False, 25 | is_bidirectional: bool = True, 26 | stride: int = 32, 27 | expressivity: int = 8, 28 | ) -> None: 29 | 30 | super().__init__( 31 | embedding_dim, ffn_embedding_dim, num_attention_heads, dropout, 32 | attention_dropout, activation_dropout, activation_fn, export 33 | ) 34 | 35 | self.self_attn = SparseMultiheadAttention( 36 | self.embedding_dim, 37 | num_attention_heads, 38 | dropout=attention_dropout, 39 | add_bias_kv=False, 40 | add_zero_attn=False, 41 | self_attention=True, 42 | is_bidirectional=is_bidirectional, 43 | stride=stride, 44 | expressivity=expressivity, 45 | ) 46 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/modules/unfold.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import torch.nn.functional as F 7 | 8 | 9 | def unfold1d(x, kernel_size, padding_l, pad_value=0): 10 | '''unfold T x B x C to T x B x C x K''' 11 | if kernel_size > 1: 12 | T, B, C = x.size() 13 | x = F.pad(x, (0, 0, 0, 0, padding_l, kernel_size - 1 - padding_l), value=pad_value) 14 | x = x.as_strided((T, B, C, kernel_size), (B*C, C, 1, B*C)) 15 | else: 16 | x = x.unsqueeze(3) 17 | return x 18 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/optim/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import importlib 7 | import os 8 | 9 | from fairseq import registry 10 | from fairseq.optim.fairseq_optimizer import FairseqOptimizer 11 | from fairseq.optim.fp16_optimizer import FP16Optimizer, MemoryEfficientFP16Optimizer 12 | from fairseq.optim.bmuf import FairseqBMUF # noqa 13 | 14 | 15 | __all__ = [ 16 | 'FairseqOptimizer', 17 | 'FP16Optimizer', 18 | 'MemoryEfficientFP16Optimizer', 19 | ] 20 | 21 | 22 | build_optimizer, register_optimizer, OPTIMIZER_REGISTRY = registry.setup_registry( 23 | '--optimizer', 24 | base_class=FairseqOptimizer, 25 | default='nag', 26 | ) 27 | 28 | 29 | # automatically import any Python files in the optim/ directory 30 | for file in os.listdir(os.path.dirname(__file__)): 31 | if file.endswith('.py') and not file.startswith('_'): 32 | module = file[:file.find('.py')] 33 | importlib.import_module('fairseq.optim.' + module) 34 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/optim/adadelta.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import torch.optim 7 | 8 | from . import FairseqOptimizer, register_optimizer 9 | 10 | 11 | @register_optimizer('adadelta') 12 | class Adadelta(FairseqOptimizer): 13 | def __init__(self, args, params): 14 | super().__init__(args) 15 | self._optimizer = torch.optim.Adadelta(params, **self.optimizer_config) 16 | 17 | @staticmethod 18 | def add_args(parser): 19 | """Add optimizer-specific arguments to the parser.""" 20 | # fmt: off 21 | parser.add_argument('--adadelta-rho', type=float, default=0.9, metavar='RHO', 22 | help='coefficient used for computing a running average of squared gradients') 23 | parser.add_argument('--adadelta-eps', type=float, default=1e-6, metavar='EPS', 24 | help='term added to the denominator to improve numerical stability') 25 | parser.add_argument('--weight-decay', '--wd', default=0.0, type=float, metavar='WD', 26 | help='weight decay') 27 | parser.add_argument('--anneal-eps', action='store_true', help='flag to anneal eps') 28 | # fmt: on 29 | 30 | @property 31 | def optimizer_config(self): 32 | """ 33 | Return a kwarg dictionary that will be used to override optimizer 34 | args stored in checkpoints. This allows us to load a checkpoint and 35 | resume training using a different set of optimizer args, e.g., with a 36 | different learning rate. 37 | """ 38 | return { 39 | 'lr': self.args.lr[0], 40 | 'rho': self.args.adadelta_rho, 41 | 'eps': self.args.adadelta_eps, 42 | 'weight_decay': self.args.weight_decay, 43 | } 44 | 45 | @property 46 | def supports_flat_params(self): 47 | return True 48 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/optim/adagrad.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import torch.optim 7 | 8 | from . import FairseqOptimizer, register_optimizer 9 | 10 | 11 | @register_optimizer('adagrad') 12 | class Adagrad(FairseqOptimizer): 13 | def __init__(self, args, params): 14 | super().__init__(args) 15 | self._optimizer = torch.optim.Adagrad(params, **self.optimizer_config) 16 | 17 | @staticmethod 18 | def add_args(parser): 19 | """Add optimizer-specific arguments to the parser.""" 20 | # fmt: off 21 | parser.add_argument('--weight-decay', '--wd', default=0.0, type=float, metavar='WD', 22 | help='weight decay') 23 | # fmt: on 24 | 25 | @property 26 | def optimizer_config(self): 27 | """ 28 | Return a kwarg dictionary that will be used to override optimizer 29 | args stored in checkpoints. This allows us to load a checkpoint and 30 | resume training using a different set of optimizer args, e.g., with a 31 | different learning rate. 32 | """ 33 | return { 34 | 'lr': self.args.lr[0], 35 | 'weight_decay': self.args.weight_decay, 36 | } 37 | 38 | @property 39 | def supports_flat_params(self): 40 | return True 41 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/optim/fused_lamb.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from fairseq.optim import FairseqOptimizer, register_optimizer 7 | 8 | 9 | @register_optimizer('lamb') 10 | class FairseqLAMB(FairseqOptimizer): 11 | """LAMB optimizer.""" 12 | 13 | def __init__(self, args, params): 14 | super().__init__(args) 15 | try: 16 | from apex.optimizers import FusedLAMB 17 | self._optimizer = FusedLAMB(params, **self.optimizer_config) 18 | except ImportError: 19 | raise ImportError('Please install apex to use LAMB optimizer') 20 | 21 | @staticmethod 22 | def add_args(parser): 23 | """Add optimizer-specific arguments to the parser.""" 24 | # fmt: off 25 | parser.add_argument('--lamb-betas', default='(0.9, 0.999)', metavar='B', 26 | help='betas for LAMB optimizer') 27 | parser.add_argument('--lamb-eps', type=float, default=1e-8, metavar='D', 28 | help='epsilon for LAMB optimizer') 29 | parser.add_argument('--weight-decay', '--wd', default=0.0, type=float, metavar='WD', 30 | help='weight decay') 31 | # fmt: on 32 | 33 | @property 34 | def optimizer_config(self): 35 | """ 36 | Return a kwarg dictionary that will be used to override optimizer 37 | args stored in checkpoints. This allows us to load a checkpoint and 38 | resume training using a different set of optimizer args, e.g., with a 39 | different learning rate. 40 | """ 41 | return { 42 | 'lr': self.args.lr[0], 43 | 'betas': eval(self.args.lamb_betas), 44 | 'eps': self.args.lamb_eps, 45 | 'weight_decay': self.args.weight_decay, 46 | } 47 | 48 | @property 49 | def supports_flat_params(self): 50 | return False 51 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/optim/lr_scheduler/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import importlib 7 | import os 8 | 9 | from fairseq import registry 10 | from fairseq.optim.lr_scheduler.fairseq_lr_scheduler import FairseqLRScheduler 11 | 12 | 13 | build_lr_scheduler, register_lr_scheduler, LR_SCHEDULER_REGISTRY = registry.setup_registry( 14 | '--lr-scheduler', 15 | base_class=FairseqLRScheduler, 16 | default='fixed', 17 | ) 18 | 19 | # automatically import any Python files in the optim/lr_scheduler/ directory 20 | for file in os.listdir(os.path.dirname(__file__)): 21 | if file.endswith('.py') and not file.startswith('_'): 22 | module = file[:file.find('.py')] 23 | importlib.import_module('fairseq.optim.lr_scheduler.' + module) 24 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/optim/lr_scheduler/fairseq_lr_scheduler.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from .. import FairseqOptimizer 7 | 8 | 9 | class FairseqLRScheduler(object): 10 | 11 | def __init__(self, args, optimizer): 12 | super().__init__() 13 | if not isinstance(optimizer, FairseqOptimizer): 14 | raise ValueError('optimizer must be an instance of FairseqOptimizer') 15 | self.args = args 16 | self.optimizer = optimizer 17 | self.best = None 18 | 19 | @staticmethod 20 | def add_args(parser): 21 | """Add arguments to the parser for this LR scheduler.""" 22 | pass 23 | 24 | def state_dict(self): 25 | """Return the LR scheduler state dict.""" 26 | return {'best': self.best} 27 | 28 | def load_state_dict(self, state_dict): 29 | """Load an LR scheduler state dict.""" 30 | self.best = state_dict['best'] 31 | 32 | def step(self, epoch, val_loss=None): 33 | """Update the learning rate at the end of the given epoch.""" 34 | if val_loss is not None: 35 | if self.best is None: 36 | self.best = val_loss 37 | else: 38 | self.best = min(self.best, val_loss) 39 | 40 | def step_update(self, num_updates): 41 | """Update the learning rate after each update.""" 42 | return self.optimizer.get_lr() 43 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/optim/sgd.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import torch.optim 7 | 8 | from . import FairseqOptimizer, register_optimizer 9 | 10 | 11 | @register_optimizer('sgd') 12 | class SGD(FairseqOptimizer): 13 | def __init__(self, args, params): 14 | super().__init__(args) 15 | self._optimizer = torch.optim.SGD(params, **self.optimizer_config) 16 | 17 | @staticmethod 18 | def add_args(parser): 19 | """Add optimizer-specific arguments to the parser.""" 20 | # fmt: off 21 | parser.add_argument('--momentum', default=0.0, type=float, metavar='M', 22 | help='momentum factor') 23 | parser.add_argument('--weight-decay', '--wd', default=0.0, type=float, metavar='WD', 24 | help='weight decay') 25 | # fmt: on 26 | 27 | @property 28 | def optimizer_config(self): 29 | """ 30 | Return a kwarg dictionary that will be used to override optimizer 31 | args stored in checkpoints. This allows us to load a checkpoint and 32 | resume training using a different set of optimizer args, e.g., with a 33 | different learning rate. 34 | """ 35 | return { 36 | 'lr': self.args.lr[0], 37 | 'momentum': self.args.momentum, 38 | 'weight_decay': self.args.weight_decay, 39 | } 40 | 41 | @property 42 | def supports_flat_params(self): 43 | return True 44 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/pdb.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import multiprocessing 7 | import os 8 | import pdb 9 | import sys 10 | 11 | 12 | __all__ = ['set_trace'] 13 | 14 | 15 | _stdin = [None] 16 | _stdin_lock = multiprocessing.Lock() 17 | try: 18 | _stdin_fd = sys.stdin.fileno() 19 | except Exception: 20 | _stdin_fd = None 21 | 22 | 23 | class MultiprocessingPdb(pdb.Pdb): 24 | """A Pdb wrapper that works in a multiprocessing environment. 25 | 26 | Usage: `from fairseq import pdb; pdb.set_trace()` 27 | """ 28 | 29 | def __init__(self): 30 | pdb.Pdb.__init__(self, nosigint=True) 31 | 32 | def _cmdloop(self): 33 | stdin_bak = sys.stdin 34 | with _stdin_lock: 35 | try: 36 | if _stdin_fd is not None: 37 | if not _stdin[0]: 38 | _stdin[0] = os.fdopen(_stdin_fd) 39 | sys.stdin = _stdin[0] 40 | self.cmdloop() 41 | finally: 42 | sys.stdin = stdin_bak 43 | 44 | 45 | def set_trace(): 46 | pdb = MultiprocessingPdb() 47 | pdb.set_trace(sys._getframe().f_back) 48 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/tasks/translation_from_pretrained_xlm.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | from fairseq.data.legacy.masked_lm_dictionary import MaskedLMDictionary 7 | from fairseq.tasks.translation import TranslationTask 8 | 9 | from . import register_task 10 | 11 | 12 | @register_task("translation_from_pretrained_xlm") 13 | class TranslationFromPretrainedXLMTask(TranslationTask): 14 | """ 15 | Same as TranslationTask except use the MaskedLMDictionary class so that 16 | we can load data that was binarized with the MaskedLMDictionary class. 17 | 18 | This task should be used for the entire training pipeline when we want to 19 | train an NMT model from a pretrained XLM checkpoint: binarizing NMT data, 20 | training NMT with the pretrained XLM checkpoint, and subsequent evaluation 21 | of that trained model. 22 | """ 23 | 24 | @classmethod 25 | def load_dictionary(cls, filename): 26 | """Load the masked LM dictionary from the filename 27 | 28 | Args: 29 | filename (str): the filename 30 | """ 31 | return MaskedLMDictionary.load(filename) 32 | -------------------------------------------------------------------------------- /src/fairseq/fairseq/tokenizer.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import re 7 | 8 | SPACE_NORMALIZER = re.compile(r"\s+") 9 | 10 | 11 | def tokenize_line(line): 12 | line = SPACE_NORMALIZER.sub(" ", line) 13 | line = line.strip() 14 | return line.split() 15 | -------------------------------------------------------------------------------- /src/fairseq/fairseq_cli/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amazon-science/BartGraphSumm/9681651faad37938909cacb1d7b998f911ab3d9b/src/fairseq/fairseq_cli/__init__.py -------------------------------------------------------------------------------- /src/fairseq/fairseq_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amazon-science/BartGraphSumm/9681651faad37938909cacb1d7b998f911ab3d9b/src/fairseq/fairseq_logo.png -------------------------------------------------------------------------------- /src/fairseq/generate.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 -u 2 | # Copyright (c) Facebook, Inc. and its affiliates. 3 | # 4 | # This source code is licensed under the MIT license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | 7 | from fairseq_cli.generate import cli_main 8 | 9 | 10 | if __name__ == '__main__': 11 | cli_main() 12 | -------------------------------------------------------------------------------- /src/fairseq/hubconf.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import functools 7 | 8 | from fairseq.hub_utils import BPEHubInterface as bpe # noqa 9 | from fairseq.hub_utils import TokenizerHubInterface as tokenizer # noqa 10 | from fairseq.models import MODEL_REGISTRY 11 | 12 | 13 | dependencies = [ 14 | 'numpy', 15 | 'regex', 16 | 'requests', 17 | 'torch', 18 | ] 19 | 20 | 21 | # torch.hub doesn't build Cython components, so if they are not found then try 22 | # to build them here 23 | try: 24 | import fairseq.data.token_block_utils_fast 25 | except (ImportError, ModuleNotFoundError): 26 | try: 27 | import cython 28 | import os 29 | from setuptools import sandbox 30 | sandbox.run_setup( 31 | os.path.join(os.path.dirname(__file__), 'setup.py'), 32 | ['build_ext', '--inplace'], 33 | ) 34 | except (ImportError, ModuleNotFoundError): 35 | print( 36 | 'Unable to build Cython components. Please make sure Cython is ' 37 | 'installed if the torch.hub model you are loading depends on it.' 38 | ) 39 | 40 | 41 | for _model_type, _cls in MODEL_REGISTRY.items(): 42 | for model_name in _cls.hub_models().keys(): 43 | globals()[model_name] = functools.partial( 44 | _cls.from_pretrained, 45 | model_name, 46 | ) 47 | # to simplify the interface we only expose named models 48 | # globals()[_model_type] = _cls.from_pretrained 49 | -------------------------------------------------------------------------------- /src/fairseq/interactive.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 -u 2 | # Copyright (c) Facebook, Inc. and its affiliates. 3 | # 4 | # This source code is licensed under the MIT license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | 7 | from fairseq_cli.interactive import cli_main 8 | 9 | 10 | if __name__ == '__main__': 11 | cli_main() 12 | -------------------------------------------------------------------------------- /src/fairseq/preprocess.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 -u 2 | # Copyright (c) Facebook, Inc. and its affiliates. 3 | # 4 | # This source code is licensed under the MIT license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | 7 | from fairseq_cli.preprocess import cli_main 8 | 9 | 10 | if __name__ == '__main__': 11 | cli_main() 12 | -------------------------------------------------------------------------------- /src/fairseq/pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools", "wheel", "cython"] 3 | build-backend = "setuptools.build_meta" 4 | -------------------------------------------------------------------------------- /src/fairseq/score.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 -u 2 | # Copyright (c) Facebook, Inc. and its affiliates. 3 | # 4 | # This source code is licensed under the MIT license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | 7 | from fairseq_cli.score import cli_main 8 | 9 | 10 | if __name__ == '__main__': 11 | cli_main() 12 | -------------------------------------------------------------------------------- /src/fairseq/scripts/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amazon-science/BartGraphSumm/9681651faad37938909cacb1d7b998f911ab3d9b/src/fairseq/scripts/__init__.py -------------------------------------------------------------------------------- /src/fairseq/scripts/compare_namespaces.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Helper script to compare two argparse.Namespace objects.""" 3 | 4 | from argparse import Namespace # noqa 5 | 6 | 7 | def main(): 8 | 9 | ns1 = eval(input('Namespace 1: ')) 10 | ns2 = eval(input('Namespace 2: ')) 11 | 12 | def keys(ns): 13 | ks = set() 14 | for k in dir(ns): 15 | if not k.startswith('_'): 16 | ks.add(k) 17 | return ks 18 | 19 | k1 = keys(ns1) 20 | k2 = keys(ns2) 21 | 22 | def print_keys(ks, ns1, ns2=None): 23 | for k in ks: 24 | if ns2 is None: 25 | print('{}\t{}'.format(k, getattr(ns1, k, None))) 26 | else: 27 | print('{}\t{}\t{}'.format(k, getattr(ns1, k, None), getattr(ns2, k, None))) 28 | 29 | print('Keys unique to namespace 1:') 30 | print_keys(k1 - k2, ns1) 31 | print() 32 | 33 | print('Keys unique to namespace 2:') 34 | print_keys(k2 - k1, ns2) 35 | print() 36 | 37 | print('Overlapping keys with different values:') 38 | ks = [k for k in k1 & k2 if getattr(ns1, k, 'None') != getattr(ns2, k, 'None')] 39 | print_keys(ks, ns1, ns2) 40 | print() 41 | 42 | 43 | if __name__ == '__main__': 44 | main() 45 | -------------------------------------------------------------------------------- /src/fairseq/scripts/compound_split_bleu.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if [ $# -ne 1 ]; then 4 | echo "usage: $0 GENERATE_PY_OUTPUT" 5 | exit 1 6 | fi 7 | 8 | GEN=$1 9 | 10 | SYS=$GEN.sys 11 | REF=$GEN.ref 12 | 13 | if [ $(tail -n 1 $GEN | grep BLEU | wc -l) -ne 1 ]; then 14 | echo "not done generating" 15 | exit 16 | fi 17 | 18 | grep ^H $GEN | awk -F '\t' '{print $NF}' | perl -ple 's{(\S)-(\S)}{$1 ##AT##-##AT## $2}g' > $SYS 19 | grep ^T $GEN | cut -f2- | perl -ple 's{(\S)-(\S)}{$1 ##AT##-##AT## $2}g' > $REF 20 | fairseq-score --sys $SYS --ref $REF 21 | -------------------------------------------------------------------------------- /src/fairseq/scripts/convert_dictionary.lua: -------------------------------------------------------------------------------- 1 | -- Copyright (c) Facebook, Inc. and its affiliates. 2 | -- 3 | -- This source code is licensed under the MIT license found in the 4 | -- LICENSE file in the root directory of this source tree. 5 | -- 6 | -- Usage: convert_dictionary.lua 7 | require 'fairseq' 8 | require 'torch' 9 | require 'paths' 10 | 11 | if #arg < 1 then 12 | print('usage: convert_dictionary.lua ') 13 | os.exit(1) 14 | end 15 | if not paths.filep(arg[1]) then 16 | print('error: file does not exit: ' .. arg[1]) 17 | os.exit(1) 18 | end 19 | 20 | dict = torch.load(arg[1]) 21 | dst = paths.basename(arg[1]):gsub('.th7', '.txt') 22 | assert(dst:match('.txt$')) 23 | 24 | f = io.open(dst, 'w') 25 | for idx, symbol in ipairs(dict.index_to_symbol) do 26 | if idx > dict.cutoff then 27 | break 28 | end 29 | f:write(symbol) 30 | f:write(' ') 31 | f:write(dict.index_to_freq[idx]) 32 | f:write('\n') 33 | end 34 | f:close() 35 | -------------------------------------------------------------------------------- /src/fairseq/scripts/count_docs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (c) Facebook, Inc. and its affiliates. 3 | # 4 | # This source code is licensed under the MIT license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | """ 7 | Count the number of documents and average number of lines and tokens per 8 | document in a large file. Documents should be separated by a single empty line. 9 | """ 10 | 11 | import argparse 12 | import gzip 13 | import sys 14 | 15 | import numpy as np 16 | 17 | 18 | def main(): 19 | parser = argparse.ArgumentParser() 20 | parser.add_argument('input') 21 | parser.add_argument('--gzip', action='store_true') 22 | args = parser.parse_args() 23 | 24 | def gopen(): 25 | if args.gzip: 26 | return gzip.open(args.input, 'r') 27 | else: 28 | return open(args.input, 'r', encoding='utf-8') 29 | 30 | num_lines = [] 31 | num_toks = [] 32 | with gopen() as h: 33 | num_docs = 1 34 | num_lines_in_doc = 0 35 | num_toks_in_doc = 0 36 | for i, line in enumerate(h): 37 | if len(line.strip()) == 0: # empty line indicates new document 38 | num_docs += 1 39 | num_lines.append(num_lines_in_doc) 40 | num_toks.append(num_toks_in_doc) 41 | num_lines_in_doc = 0 42 | num_toks_in_doc = 0 43 | else: 44 | num_lines_in_doc += 1 45 | num_toks_in_doc += len(line.rstrip().split()) 46 | if i % 1000000 == 0: 47 | print(i, file=sys.stderr, end="", flush=True) 48 | elif i % 100000 == 0: 49 | print(".", file=sys.stderr, end="", flush=True) 50 | print(file=sys.stderr, flush=True) 51 | 52 | print("found {} docs".format(num_docs)) 53 | print("average num lines per doc: {}".format(np.mean(num_lines))) 54 | print("average num toks per doc: {}".format(np.mean(num_toks))) 55 | 56 | 57 | if __name__ == '__main__': 58 | main() 59 | -------------------------------------------------------------------------------- /src/fairseq/scripts/read_binarized.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (c) Facebook, Inc. and its affiliates. 3 | # 4 | # This source code is licensed under the MIT license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | 7 | import argparse 8 | 9 | from fairseq.data import data_utils, Dictionary, indexed_dataset 10 | 11 | 12 | def get_parser(): 13 | parser = argparse.ArgumentParser( 14 | description='writes text from binarized file to stdout') 15 | # fmt: off 16 | parser.add_argument('--dataset-impl', help='dataset implementation', 17 | choices=indexed_dataset.get_available_dataset_impl()) 18 | parser.add_argument('--dict', metavar='FP', help='dictionary containing known words', default=None) 19 | parser.add_argument('--input', metavar='FP', required=True, help='binarized file to read') 20 | # fmt: on 21 | 22 | return parser 23 | 24 | 25 | def main(): 26 | parser = get_parser() 27 | args = parser.parse_args() 28 | 29 | dictionary = Dictionary.load(args.dict) if args.dict is not None else None 30 | dataset = data_utils.load_indexed_dataset( 31 | args.input, 32 | dictionary, 33 | dataset_impl=args.dataset_impl, 34 | default='lazy', 35 | ) 36 | 37 | for tensor_line in dataset: 38 | if dictionary is None: 39 | line = ' '.join([str(int(x)) for x in tensor_line]) 40 | else: 41 | line = dictionary.string(tensor_line) 42 | 43 | print(line) 44 | 45 | 46 | if __name__ == '__main__': 47 | main() 48 | -------------------------------------------------------------------------------- /src/fairseq/scripts/sacrebleu_pregen.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if [ $# -ne 4 ]; then 4 | echo "usage: $0 TESTSET SRCLANG TGTLANG GEN" 5 | exit 1 6 | fi 7 | 8 | TESTSET=$1 9 | SRCLANG=$2 10 | TGTLANG=$3 11 | 12 | GEN=$4 13 | 14 | echo 'Cloning Moses github repository (for tokenization scripts)...' 15 | git clone https://github.com/moses-smt/mosesdecoder.git 16 | 17 | SCRIPTS=mosesdecoder/scripts 18 | DETOKENIZER=$SCRIPTS/tokenizer/detokenizer.perl 19 | 20 | grep ^H $GEN \ 21 | | sed 's/^H\-//' \ 22 | | sort -n -k 1 \ 23 | | cut -f 3 \ 24 | | perl $DETOKENIZER -l $TGTLANG \ 25 | | sed "s/ - /-/g" \ 26 | > $GEN.sorted.detok 27 | 28 | sacrebleu --test-set $TESTSET --language-pair "${SRCLANG}-${TGTLANG}" < $GEN.sorted.detok 29 | -------------------------------------------------------------------------------- /src/fairseq/scripts/shard_docs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (c) Facebook, Inc. and its affiliates. 3 | # 4 | # This source code is licensed under the MIT license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | """ 7 | Split a large file into shards while respecting document boundaries. Documents 8 | should be separated by a single empty line. 9 | """ 10 | 11 | import argparse 12 | import contextlib 13 | 14 | 15 | def main(): 16 | parser = argparse.ArgumentParser() 17 | parser.add_argument('input') 18 | parser.add_argument('--num-shards', type=int) 19 | args = parser.parse_args() 20 | 21 | assert args.num_shards is not None and args.num_shards > 1 22 | 23 | with open(args.input, 'r', encoding='utf-8') as h: 24 | with contextlib.ExitStack() as stack: 25 | outputs = [ 26 | stack.enter_context(open(args.input + ".shard" + str(i), "w", encoding="utf-8")) 27 | for i in range(args.num_shards) 28 | ] 29 | 30 | doc = [] 31 | first_doc = [True]*args.num_shards 32 | 33 | def output_doc(i): 34 | if not first_doc[i]: 35 | outputs[i].write("\n") 36 | first_doc[i] = False 37 | for line in doc: 38 | outputs[i].write(line) 39 | doc.clear() 40 | 41 | num_docs = 0 42 | for line in h: 43 | if line.strip() == "": # empty line indicates new document 44 | output_doc(num_docs % args.num_shards) 45 | num_docs += 1 46 | else: 47 | doc.append(line) 48 | output_doc(num_docs % args.num_shards) 49 | 50 | 51 | if __name__ == '__main__': 52 | main() 53 | -------------------------------------------------------------------------------- /src/fairseq/scripts/spm_decode.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Copyright (c) Facebook, Inc. and its affiliates. 3 | # All rights reserved. 4 | # 5 | # This source code is licensed under the license found in the 6 | # LICENSE file in the root directory of this source tree. 7 | 8 | from __future__ import absolute_import, division, print_function, unicode_literals 9 | 10 | import argparse 11 | 12 | import sentencepiece as spm 13 | 14 | 15 | def main(): 16 | parser = argparse.ArgumentParser() 17 | parser.add_argument("--model", required=True, 18 | help="sentencepiece model to use for decoding") 19 | parser.add_argument("--input", required=True, help="input file to decode") 20 | parser.add_argument("--input_format", choices=["piece", "id"], default="piece") 21 | args = parser.parse_args() 22 | 23 | sp = spm.SentencePieceProcessor() 24 | sp.Load(args.model) 25 | 26 | if args.input_format == "piece": 27 | def decode(l): 28 | return "".join(sp.DecodePieces(l)) 29 | elif args.input_format == "id": 30 | def decode(l): 31 | return "".join(sp.DecodeIds(l)) 32 | else: 33 | raise NotImplementedError 34 | 35 | def tok2int(tok): 36 | # remap reference-side (represented as <>) to 0 37 | return int(tok) if tok != "<>" else 0 38 | 39 | with open(args.input, "r", encoding="utf-8") as h: 40 | for line in h: 41 | if args.input_format == "id": 42 | print(decode(list(map(tok2int, line.rstrip().split())))) 43 | elif args.input_format == "piece": 44 | print(decode(line.rstrip().split())) 45 | 46 | if __name__ == "__main__": 47 | main() 48 | -------------------------------------------------------------------------------- /src/fairseq/scripts/spm_train.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Copyright (c) Facebook, Inc. and its affiliates. 3 | # All rights reserved. 4 | # 5 | # This source code is licensed under the license found in the 6 | # LICENSE file in the root directory of this source tree. 7 | 8 | from __future__ import absolute_import, division, print_function, unicode_literals 9 | 10 | import sys 11 | 12 | import sentencepiece as spm 13 | 14 | 15 | if __name__ == "__main__": 16 | spm.SentencePieceTrainer.Train(" ".join(sys.argv[1:])) 17 | -------------------------------------------------------------------------------- /src/fairseq/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amazon-science/BartGraphSumm/9681651faad37938909cacb1d7b998f911ab3d9b/src/fairseq/tests/__init__.py -------------------------------------------------------------------------------- /src/fairseq/tests/gpu/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amazon-science/BartGraphSumm/9681651faad37938909cacb1d7b998f911ab3d9b/src/fairseq/tests/gpu/__init__.py -------------------------------------------------------------------------------- /src/fairseq/tests/gpu/transformer_quantization_config.yaml: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | # This file defines example configuration arguments for quantizing 7 | # a transformer model with product quantization 8 | 9 | n_centroids: 10 | Linear: 11 | key: in_features 12 | value: {"*": 8} 13 | Embedding: 14 | key: embedding_dim 15 | value: {"*": 8} 16 | 17 | block_sizes: 18 | Linear: 19 | key: fuzzy_name 20 | value: {fc: 8, attn: 4, emb: 4} 21 | Embedding: 22 | key: fuzzy_name 23 | value: {emb: 8} 24 | 25 | layers_to_quantize: 26 | - decoder\\.layers\\.\d+\\.fc[12] 27 | - decoder\\.embed_tokens\\.embeddings\\.[012]\\.[01] 28 | - decoder\\.layers\\.\d+\\.self_attn\\.(k_proj|v_proj|q_proj|out_proj) 29 | -------------------------------------------------------------------------------- /src/fairseq/tests/speech_recognition/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amazon-science/BartGraphSumm/9681651faad37938909cacb1d7b998f911ab3d9b/src/fairseq/tests/speech_recognition/__init__.py -------------------------------------------------------------------------------- /src/fairseq/tests/speech_recognition/test_collaters.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (c) Facebook, Inc. and its affiliates. 3 | # 4 | # This source code is licensed under the MIT license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | 7 | import unittest 8 | 9 | import numpy as np 10 | import torch 11 | from examples.speech_recognition.data.collaters import Seq2SeqCollater 12 | 13 | 14 | class TestSeq2SeqCollator(unittest.TestCase): 15 | def test_collate(self): 16 | 17 | eos_idx = 1 18 | pad_idx = 0 19 | collater = Seq2SeqCollater( 20 | feature_index=0, label_index=1, pad_index=pad_idx, eos_index=eos_idx 21 | ) 22 | 23 | # 2 frames in the first sample and 3 frames in the second one 24 | frames1 = np.array([[7, 8], [9, 10]]) 25 | frames2 = np.array([[1, 2], [3, 4], [5, 6]]) 26 | target1 = np.array([4, 2, 3, eos_idx]) 27 | target2 = np.array([3, 2, eos_idx]) 28 | sample1 = {"id": 0, "data": [frames1, target1]} 29 | sample2 = {"id": 1, "data": [frames2, target2]} 30 | batch = collater.collate([sample1, sample2]) 31 | 32 | # collate sort inputs by frame's length before creating the batch 33 | self.assertTensorEqual(batch["id"], torch.tensor([1, 0])) 34 | self.assertEqual(batch["ntokens"], 7) 35 | self.assertTensorEqual( 36 | batch["net_input"]["src_tokens"], 37 | torch.tensor( 38 | [[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [pad_idx, pad_idx]]] 39 | ), 40 | ) 41 | self.assertTensorEqual( 42 | batch["net_input"]["prev_output_tokens"], 43 | torch.tensor([[eos_idx, 3, 2, pad_idx], [eos_idx, 4, 2, 3]]), 44 | ) 45 | self.assertTensorEqual(batch["net_input"]["src_lengths"], torch.tensor([3, 2])) 46 | self.assertTensorEqual( 47 | batch["target"], 48 | torch.tensor([[3, 2, eos_idx, pad_idx], [4, 2, 3, eos_idx]]), 49 | ) 50 | self.assertEqual(batch["nsentences"], 2) 51 | 52 | def assertTensorEqual(self, t1, t2): 53 | self.assertEqual(t1.size(), t2.size(), "size mismatch") 54 | self.assertEqual(t1.ne(t2).long().sum(), 0) 55 | 56 | 57 | if __name__ == "__main__": 58 | unittest.main() 59 | -------------------------------------------------------------------------------- /src/fairseq/tests/speech_recognition/test_cross_entropy.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (c) Facebook, Inc. and its affiliates. 3 | # 4 | # This source code is licensed under the MIT license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | 7 | from examples.speech_recognition.criterions.cross_entropy_acc import CrossEntropyWithAccCriterion 8 | from .asr_test_base import CrossEntropyCriterionTestBase 9 | 10 | 11 | class CrossEntropyWithAccCriterionTest(CrossEntropyCriterionTestBase): 12 | def setUp(self): 13 | self.criterion_cls = CrossEntropyWithAccCriterion 14 | super().setUp() 15 | 16 | def test_cross_entropy_all_correct(self): 17 | sample = self.get_test_sample(correct=True, soft_target=False, aggregate=False) 18 | loss, sample_size, logging_output = self.criterion( 19 | self.model, sample, "sum", log_probs=True 20 | ) 21 | assert logging_output["correct"] == 20 22 | assert logging_output["total"] == 20 23 | assert logging_output["sample_size"] == 20 24 | assert logging_output["ntokens"] == 20 25 | 26 | def test_cross_entropy_all_wrong(self): 27 | sample = self.get_test_sample(correct=False, soft_target=False, aggregate=False) 28 | loss, sample_size, logging_output = self.criterion( 29 | self.model, sample, "sum", log_probs=True 30 | ) 31 | assert logging_output["correct"] == 0 32 | assert logging_output["total"] == 20 33 | assert logging_output["sample_size"] == 20 34 | assert logging_output["ntokens"] == 20 35 | -------------------------------------------------------------------------------- /src/fairseq/tests/speech_recognition/test_data_utils.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Copyright (c) Facebook, Inc. and its affiliates. 3 | # 4 | # This source code is licensed under the MIT license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | import unittest 7 | 8 | import torch 9 | 10 | from examples.speech_recognition.data import data_utils 11 | 12 | 13 | class DataUtilsTest(unittest.TestCase): 14 | 15 | def test_normalization(self): 16 | sample_len1 = torch.tensor([[-0.7661, -1.3889, -2.0972, -0.9134, -0.7071, -0.9765, -0.8700, -0.8283, 17 | 0.7512, 1.3211, 2.1532, 2.1174, 1.2800, 1.2633, 1.6147, 1.6322, 18 | 2.0723, 3.1522, 3.2852, 2.2309, 2.5569, 2.2183, 2.2862, 1.5886, 19 | 0.8773, 0.8725, 1.2662, 0.9899, 1.1069, 1.3926, 1.2795, 1.1199, 20 | 1.1477, 1.2687, 1.3843, 1.1903, 0.8355, 1.1367, 1.2639, 1.4707]]) 21 | out = data_utils.apply_mv_norm(sample_len1) 22 | assert not torch.isnan(out).any() 23 | assert (out == sample_len1).all() 24 | -------------------------------------------------------------------------------- /src/fairseq/tests/test_character_token_embedder.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import torch 7 | import unittest 8 | 9 | from fairseq.data import Dictionary 10 | from fairseq.modules import CharacterTokenEmbedder 11 | 12 | 13 | class TestCharacterTokenEmbedder(unittest.TestCase): 14 | def test_character_token_embedder(self): 15 | vocab = Dictionary() 16 | vocab.add_symbol('hello') 17 | vocab.add_symbol('there') 18 | 19 | embedder = CharacterTokenEmbedder(vocab, [(2, 16), (4, 32), (8, 64), (16, 2)], 64, 5, 2) 20 | 21 | test_sents = [['hello', 'unk', 'there'], ['there'], ['hello', 'there']] 22 | max_len = max(len(s) for s in test_sents) 23 | input = torch.LongTensor(len(test_sents), max_len + 2).fill_(vocab.pad()) 24 | for i in range(len(test_sents)): 25 | input[i][0] = vocab.eos() 26 | for j in range(len(test_sents[i])): 27 | input[i][j + 1] = vocab.index(test_sents[i][j]) 28 | input[i][j + 2] = vocab.eos() 29 | embs = embedder(input) 30 | 31 | assert embs.size() == (len(test_sents), max_len + 2, 5) 32 | self.assertAlmostEqual(embs[0][0], embs[1][0]) 33 | self.assertAlmostEqual(embs[0][0], embs[0][-1]) 34 | self.assertAlmostEqual(embs[0][1], embs[2][1]) 35 | self.assertAlmostEqual(embs[0][3], embs[1][1]) 36 | 37 | embs.sum().backward() 38 | assert embedder.char_embeddings.weight.grad is not None 39 | 40 | def assertAlmostEqual(self, t1, t2): 41 | self.assertEqual(t1.size(), t2.size(), "size mismatch") 42 | self.assertLess((t1 - t2).abs().max(), 1e-6) 43 | 44 | 45 | if __name__ == '__main__': 46 | unittest.main() 47 | -------------------------------------------------------------------------------- /src/fairseq/tests/test_concat_dataset.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import unittest 7 | 8 | import torch 9 | from fairseq.data import LanguagePairDataset, TokenBlockDataset 10 | from fairseq.data.concat_dataset import ConcatDataset 11 | from tests.test_train import mock_dict 12 | 13 | 14 | class TestConcatDataset(unittest.TestCase): 15 | def setUp(self): 16 | d = mock_dict() 17 | tokens_1 = torch.LongTensor([1]).view(1, -1) 18 | tokens_ds1 = TokenBlockDataset( 19 | tokens_1, 20 | sizes=[tokens_1.size(-1)], 21 | block_size=1, 22 | pad=0, 23 | eos=1, 24 | include_targets=False, 25 | ) 26 | self.dataset_1 = LanguagePairDataset( 27 | tokens_ds1, tokens_ds1.sizes, d, shuffle=False 28 | ) 29 | tokens_2 = torch.LongTensor([2]).view(1, -1) 30 | tokens_ds2 = TokenBlockDataset( 31 | tokens_2, 32 | sizes=[tokens_2.size(-1)], 33 | block_size=1, 34 | pad=0, 35 | eos=1, 36 | include_targets=False, 37 | ) 38 | self.dataset_2 = LanguagePairDataset( 39 | tokens_ds2, tokens_ds2.sizes, d, shuffle=False 40 | ) 41 | 42 | def test_concat_dataset_basics(self): 43 | d = ConcatDataset( 44 | [self.dataset_1, self.dataset_2] 45 | ) 46 | assert(len(d) == 2) 47 | assert(d[0]['source'][0] == 1) 48 | assert(d[1]['source'][0] == 2) 49 | 50 | d = ConcatDataset( 51 | [self.dataset_1, self.dataset_2], sample_ratios=[1, 2] 52 | ) 53 | assert(len(d) == 3) 54 | assert(d[0]['source'][0] == 1) 55 | assert(d[1]['source'][0] == 2) 56 | assert(d[2]['source'][0] == 2) 57 | 58 | d = ConcatDataset( 59 | [self.dataset_1, self.dataset_2], sample_ratios=[2, 1] 60 | ) 61 | assert(len(d) == 3) 62 | assert(d[0]['source'][0] == 1) 63 | assert(d[1]['source'][0] == 1) 64 | assert(d[2]['source'][0] == 2) 65 | -------------------------------------------------------------------------------- /src/fairseq/tests/test_convtbc.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import torch 7 | import unittest 8 | from fairseq.modules import ConvTBC 9 | import torch.nn as nn 10 | 11 | 12 | class TestConvTBC(unittest.TestCase): 13 | 14 | def test_convtbc(self): 15 | # ksz, in_channels, out_channels 16 | conv_tbc = ConvTBC(4, 5, kernel_size=3, padding=1) 17 | # out_channels, in_channels, ksz 18 | conv1d = nn.Conv1d(4, 5, kernel_size=3, padding=1) 19 | 20 | conv_tbc.weight.data.copy_(conv1d.weight.data.transpose(0, 2)) 21 | conv_tbc.bias.data.copy_(conv1d.bias.data) 22 | 23 | input_tbc = torch.randn(7, 2, 4, requires_grad=True) 24 | input1d = input_tbc.data.transpose(0, 1).transpose(1, 2) 25 | input1d.requires_grad = True 26 | 27 | output_tbc = conv_tbc(input_tbc) 28 | output1d = conv1d(input1d) 29 | 30 | self.assertAlmostEqual(output_tbc.data.transpose(0, 1).transpose(1, 2), output1d.data) 31 | 32 | grad_tbc = torch.randn(output_tbc.size()) 33 | grad1d = grad_tbc.transpose(0, 1).transpose(1, 2).contiguous() 34 | 35 | output_tbc.backward(grad_tbc) 36 | output1d.backward(grad1d) 37 | 38 | self.assertAlmostEqual(conv_tbc.weight.grad.data.transpose(0, 2), conv1d.weight.grad.data) 39 | self.assertAlmostEqual(conv_tbc.bias.grad.data, conv1d.bias.grad.data) 40 | self.assertAlmostEqual(input_tbc.grad.data.transpose(0, 1).transpose(1, 2), input1d.grad.data) 41 | 42 | def assertAlmostEqual(self, t1, t2): 43 | self.assertEqual(t1.size(), t2.size(), "size mismatch") 44 | self.assertLess((t1 - t2).abs().max(), 1e-4) 45 | 46 | 47 | if __name__ == '__main__': 48 | unittest.main() 49 | -------------------------------------------------------------------------------- /src/fairseq/tests/test_file_io.py: -------------------------------------------------------------------------------- 1 | # This source code is licensed under the MIT license found in the 2 | # LICENSE file in the root directory of this source tree. 3 | 4 | import sys 5 | import tempfile 6 | import os 7 | import shutil 8 | 9 | from typing import Optional 10 | 11 | import unittest 12 | from unittest.mock import MagicMock 13 | 14 | 15 | class TestFileIO(unittest.TestCase): 16 | 17 | _tmpdir: Optional[str] = None 18 | _tmpfile: Optional[str] = None 19 | _tmpfile_contents = "Hello, World" 20 | 21 | @classmethod 22 | def setUpClass(cls) -> None: 23 | cls._tmpdir = tempfile.mkdtemp() 24 | with open(os.path.join(cls._tmpdir, "test.txt"), "w") as f: 25 | cls._tmpfile = f.name 26 | f.write(cls._tmpfile_contents) 27 | f.flush() 28 | 29 | @classmethod 30 | def tearDownClass(cls) -> None: 31 | # Cleanup temp working dir. 32 | if cls._tmpdir is not None: 33 | shutil.rmtree(cls._tmpdir) # type: ignore 34 | 35 | def test_file_io(self): 36 | from fairseq.file_io import PathManager 37 | with PathManager.open(os.path.join(self._tmpdir, "test.txt"), "r") as f: 38 | s = f.read() 39 | self.assertEqual(s, self._tmpfile_contents) 40 | 41 | def test_file_io_oss(self): 42 | # Mock fvcore to simulate oss environment. 43 | sys.modules['fvcore'] = MagicMock() 44 | from fairseq.file_io import PathManager 45 | with PathManager.open(os.path.join(self._tmpdir, "test.txt"), "r") as f: 46 | s = f.read() 47 | self.assertEqual(s, self._tmpfile_contents) 48 | -------------------------------------------------------------------------------- /src/fairseq/tests/test_memory_efficient_fp16.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import argparse 7 | import logging 8 | import unittest 9 | 10 | import torch 11 | 12 | from fairseq.optim.adam import FairseqAdam 13 | from fairseq.optim.fp16_optimizer import MemoryEfficientFP16Optimizer 14 | 15 | 16 | @unittest.skipIf(not torch.cuda.is_available(), 'test requires a GPU') 17 | class TestMemoryEfficientFP16(unittest.TestCase): 18 | 19 | def setUp(self): 20 | logging.disable(logging.CRITICAL) 21 | 22 | def tearDown(self): 23 | logging.disable(logging.NOTSET) 24 | 25 | def test_load_state_dict(self): 26 | # define simple FP16 model 27 | model = torch.nn.Linear(5, 5).cuda().half() 28 | params = list(model.parameters()) 29 | 30 | # initialize memory efficient FP16 optimizer 31 | optimizer = FairseqAdam( 32 | argparse.Namespace( 33 | lr=[0.00001], 34 | adam_betas='(0.9, 0.999)', 35 | adam_eps=1e-8, 36 | weight_decay=0.0, 37 | ), 38 | params, 39 | ) 40 | me_optimizer = MemoryEfficientFP16Optimizer( 41 | argparse.Namespace( 42 | fp16_init_scale=1, 43 | fp16_scale_window=1, 44 | fp16_scale_tolerance=1, 45 | threshold_loss_scale=1, 46 | min_loss_scale=1e-4, 47 | ), 48 | params, 49 | optimizer, 50 | ) 51 | 52 | # optimizer state is created in the first step 53 | loss = model(torch.rand(5).cuda().half()).sum() 54 | me_optimizer.backward(loss) 55 | me_optimizer.step() 56 | 57 | # reload state 58 | state = me_optimizer.state_dict() 59 | me_optimizer.load_state_dict(state) 60 | for k, v in me_optimizer.optimizer.state.items(): 61 | self.assertTrue(k.dtype == torch.float16) 62 | for v_i in v.values(): 63 | if torch.is_tensor(v_i): 64 | self.assertTrue(v_i.dtype == torch.float32) 65 | 66 | 67 | if __name__ == '__main__': 68 | unittest.main() 69 | -------------------------------------------------------------------------------- /src/fairseq/tests/test_multihead_attention.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # 3 | # This source code is licensed under the MIT license found in the 4 | # LICENSE file in the root directory of this source tree. 5 | 6 | import torch 7 | import unittest 8 | from fairseq.modules.multihead_attention import MultiheadAttention 9 | 10 | 11 | class TestMultiheadAttention(unittest.TestCase): 12 | def test_append_prev_key_padding_mask(self): 13 | bsz = 1 14 | src_len = 4 15 | 16 | cases = [ 17 | # no padding mask 18 | (None, None, None), 19 | # current padding mask only 20 | ( 21 | torch.tensor([[1]]).bool(), 22 | None, 23 | torch.tensor([[0, 0, 0, 1]]).bool(), 24 | ), 25 | # previous padding mask only 26 | ( 27 | None, 28 | torch.tensor([[0, 1, 0]]).bool(), 29 | torch.tensor([[0, 1, 0, 0]]).bool(), 30 | ), 31 | # both padding masks 32 | ( 33 | torch.tensor([[1]]).bool(), 34 | torch.tensor([[0, 1, 0]]).bool(), 35 | torch.tensor([[0, 1, 0, 1]]).bool(), 36 | ), 37 | ] 38 | for c in cases: 39 | key_padding_mask = MultiheadAttention._append_prev_key_padding_mask( 40 | c[0], 41 | c[1], 42 | batch_size=bsz, 43 | src_len=src_len, 44 | static_kv=False, 45 | ) 46 | 47 | if key_padding_mask is not None: 48 | self.assertTrue( 49 | torch.all(torch.eq(key_padding_mask, c[2])), 50 | f'Unexpected resultant key padding mask: {key_padding_mask}' 51 | f' given current: {c[0]} and previous: {c[1]}', 52 | ) 53 | self.assertEqual(key_padding_mask.size(0), bsz) 54 | self.assertEqual(key_padding_mask.size(1), src_len) 55 | else: 56 | self.assertIsNone(c[2]) 57 | 58 | 59 | if __name__ == '__main__': 60 | unittest.main() 61 | -------------------------------------------------------------------------------- /src/fairseq/train.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 -u 2 | # Copyright (c) Facebook, Inc. and its affiliates. 3 | # 4 | # This source code is licensed under the MIT license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | 7 | from fairseq_cli.train import cli_main 8 | 9 | 10 | if __name__ == '__main__': 11 | cli_main() 12 | -------------------------------------------------------------------------------- /src/fairseq/validate.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 -u 2 | # Copyright (c) Facebook, Inc. and its affiliates. 3 | # 4 | # This source code is licensed under the MIT license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | 7 | from fairseq_cli.validate import cli_main 8 | 9 | 10 | if __name__ == '__main__': 11 | cli_main() 12 | --------------------------------------------------------------------------------