Ce référentiel contient la mise en œuvre officielle des expériences menées dans
? Structure de repo:
efficient-attention : une petite base de code autonome qui met en œuvre divers mécanismes d'attention efficaces. Veuillez consulter l'utilisation pour plus de détails.vit : base de code pour les expériences de classification d'images , qui est adaptée defairseq : une fourche modifiée de Fairseq pour les tâches linguistiques, y compris la traduction automatique et la modélisation du langage autorégressive .main.sh : un script bash pour lancer toutes les expériences.-e True sont directement transmis à la commande de formation. Vous pouvez transmettre des arguments personnalisés à la commande de formation en les ajoutant après -e True . Pour configurer l'environnement, exécutez les commandes suivantes pour installer les dépendances requises (recommandées dans un environnement virtuel):
# install packages
pip install -r requirements.txt
# install efficient-attention library
pip install -e efficient-attention
# OPTIONAL: install fairseq library for running language tasks
cd fairseq
python3 setup.py build develop
cd ..L'environnement est testé avec Python 3.8.10, Pytorch 1.12.0 et CUDA 11.3 . Notez également que notre fourche de Fairseq modifie plusieurs fichiers dans la base de code d'origine; L'utilisation de versions plus récentes de Fairseq pourrait conduire à des conflits de dépendance inattendus.
efficient-attention est une petite base de code autonome qui collecte plusieurs mécanismes d'attention efficaces.
add_attn_specific_args() dans le fichier python correspondant.argparse Parser, suivez l'extrait de code suivant: import argparse
from efficient_attention import AttentionFactory
# ...
parser = argparse . ArgumentParser ()
parser . add_argument ( '--attn-name' , default = 'softmax' , type = str , metavar = 'ATTN' ,
help = 'Name of attention model to use' )
# ...
temp_args , _ = parser . parse_known_args ()
# add attention-specific arguments to the parser
# struct_name: name of the inner namespace to store all attention-specific arguments
# prefix: prefix to prepend to all argument names
# for example, if prefix = encoder-attn, then for the argument --window-size
# we need to pass --encoder-attn-window-size
# this is useful to avoid argument name conflicts.
efficient_attention . AttentionFactory . add_attn_specific_args ( parser , temp_args . attn_name , struct_name = "attn_args" , prefix = "" )
# parse arguments to a namespace that supports nested attributes
args = parser . parse_args ( namespace = efficient_attention . NestedNamespace ())
# now we can access the attention-specific arguments via args.attn_args
print ( args . attn_args . window_size ) Dans une classe torch.nn.Module , vous pouvez créer un module d'attention efficace comme suit:
# we might want to pass attention-specific arguments to the attention module
# along with other related arguments
attn_args = {
** vars ( args . attn_args ),
** {
'dim' : args . embed_dim ,
'num_heads' : args . num_heads ,
'qkv_bias' : args . qkv_bias ,
'attn_drop' : args . attn_drop_rate ,
'proj_drop' : args . drop_rate ,
}
}
self . attn = AttentionFactory . build_attention ( attn_name = attn_name , attn_args = attn_args )
# the module can then be used as a normal function as
x = self . attn ( x ) Nous suivons la configuration similaire à Deit pour prétraiter l'ensemble de données ImageNet. Téléchargez ImageNet Train et Val Images et placez-les dans la structure du répertoire suivant afin qu'il puisse être compatible avec les datasets.ImageFolder TorchVision.
/path/to/imagenet/
train/
class1/
img1.jpeg
class2/
img2.jpeg
val/
class1/
img3.jpeg
class2/
img4.jpeg
Les commandes suivantes sont utilisées pour la formation et l'évaluation de divers transformateurs de vision avec LARA/EVA . La formation est supposée être effectuée avec 8 GPU.
Pour utiliser LARA/EVA dans différentes architectures de Deit:
# LARA: DeiT-tiny-p8
bash main.sh -m evit_tiny_p8 -p < dir-of-imagenet-data > -g 8 -d imagenet -e TRUE --dist-eval --num-workers 16 --clip-grad 5.0 --warmup-epochs 10 --seed 1 --attn-name lara --mis-type mis-opt --proposal-gen pool-mixed --alpha-coeff 2.0 --num-landmarks 49
# LARA: DeiT-tiny-p16
bash main.sh -m evit_tiny_p16 -p < dir-of-imagenet-data > -g 8 -d imagenet -e TRUE --dist-eval --num-workers 16 --clip-grad 5.0 --warmup-epochs 10 --seed 1 --attn-name lara --mis-type mis-opt --proposal-gen pool-mixed --alpha-coeff 2.0 --num-landmarks 49
# LARA: DeiT-small-p16
bash main.sh -m evit_small_p16 -p < dir-of-imagenet-data > -g 8 -d imagenet -e TRUE --dist-eval --num-workers 16 --clip-grad 5.0 --warmup-epochs 10 --seed 1 --attn-name lara --mis-type mis-opt --proposal-gen pool-mixed --alpha-coeff 2.0 --num-landmarks 49
# EVA: DeiT-tiny-p8
bash main.sh -m evit_tiny_p8 -p < dir-of-imagenet-data > -g 8 -d imagenet -e TRUE --dist-eval --num-workers 16 --clip-grad 5.0 --warmup-epochs 10 --seed 1 --attn-name eva --num-landmarks 49 --adaptive-proj default --window-size 7 --attn-2d --use-rpe
# EVA: DeiT-tiny-p16
bash main.sh -m evit_tiny_p16 -p < dir-of-imagenet-data > -g 8 -d imagenet -e TRUE --dist-eval --num-workers 16 --clip-grad 5.0 --warmup-epochs 10 --seed 1 --attn-name eva --num-landmarks 49 --adaptive-proj default --window-size 7 --attn-2d --use-rpe
# EVA: DeiT-small-p16
bash main.sh -m evit_small_p16 -p < dir-of-imagenet-data > -g 8 -d imagenet -e TRUE --dist-eval --num-workers 16 --clip-grad 5.0 --warmup-epochs 10 --seed 1 --attn-name eva --num-landmarks 49 --adaptive-proj default --window-size 7 --attn-2d --use-rpe Pour adapter LARA/EVA dans les architectures PVTV2:
# LARA Attention
bash main.sh -m pvt_medium2 -p < dir-of-imagenet-data > -g 8 -d imagenet -e TRUE --dist-eval --num-workers 16 --clip-grad 1.0 --drop-path-rate 0.3 --warmup-epochs 10 --seed 1 --attn-name lara --pool-module-type dense --mis-type mis-opt --proposal-gen pool-mixed --num-landmarks 49 --alpha-coeff 2.0 --repeated-aug
# EVA Attention
bash main.sh -m pvt_medium2 -p < dir-of-imagenet-data > -g 8 -d imagenet -e TRUE --dist-eval --num-workers 16 --clip-grad 5.0 --drop-path-rate 0.3 --warmup-epochs 10 --seed 1 --attn-name eva --num-landmarks 49 --adaptive-proj default --window-size 7 --attn-2d --use-rpe --repeated-augAlternativement, vous voudrez peut-être essayer d'autres mécanismes d'attention:
# Softmax Attention
bash main.sh -m evit_tiny_p8 -d imagenet -e TRUE --dist-eval --num-workers 16 --clip-grad 5.0 --warmup-epochs 10 --seed 1 --attn-name softmax
# RFA/Performer
bash main.sh -m evit_tiny_p8 -d imagenet -e TRUE --dist-eval --num-workers 16 --clip-grad 5.0 --warmup-epochs 10 --seed 1 --attn-name performer --proj-method favorp --approx-attn-dim 64
# Local Attention
bash main.sh -m evit_tiny_p8 -d imagenet -e TRUE --dist-eval --num-workers 16 --clip-grad 5.0 --warmup-epochs 10 --seed 1 --attn-name local --window-size 7 --attn-2d --use-rpeNous utilisons le prétraitement standard Fairseq pour préparer les données pour les tâches linguistiques.
WMT'14 EN-DE ;Wikitext-103 .-r <resume-ckpt-DIR> Spécifie le répertoire qui stocke vos points de contrôle pendant la formation et peut être utilisé pour reprendre la formation.--encoder-attn- (pour l'encodeur) / --decoder-attn- (pour le décodeur). Voir les exemples ci-dessous. # # LARA
CUDA_VISIBLE_DEVICES=0,1,2,3 bash main.sh -p < dir-of-your-bin-data > -d wmt -s lara_8 -g 4 -e TRUE --attn-name-encoder lara --encoder-attn-num-landmarks 8 --encoder-attn-proposal-gen adaptive-1d --encoder-attn-mis-type mis-opt
CUDA_VISIBLE_DEVICES=0,1,2,3 bash main.sh -p < dir-of-your-bin-data > -d wmt -s lara_16 -g 4 -e TRUE --attn-name-encoder lara --encoder-attn-num-landmarks 16 --encoder-attn-proposal-gen adaptive-1d --encoder-attn-mis-type mis-opt
CUDA_VISIBLE_DEVICES=0,1,2,3 bash main.sh -p < dir-of-your-bin-data > -d wmt -s lara_32 -g 4 -e TRUE --attn-name-encoder lara --encoder-attn-num-landmarks 32 --encoder-attn-proposal-gen adaptive-1d --encoder-attn-mis-type mis-opt
# # EVA
CUDA_VISIBLE_DEVICES=0,1,2,3 bash main.sh -p < dir-of-your-bin-data > -d wmt -s eva_8_8 -g 4 -e TRUE --attn-name-encoder eva --encoder-attn-window-size 8 --encoder-attn-num-landmarks 8 --encoder-attn-adaptive-proj no-ln --encoder-attn-use-t5-rpe --encoder-attn-overlap-window
CUDA_VISIBLE_DEVICES=0,1,2,3 bash main.sh -p < dir-of-your-bin-data > -d wmt -s eva_16_8 -g 4 -e TRUE --attn-name-encoder eva --encoder-attn-window-size 16 --encoder-attn-num-landmarks 8 --encoder-attn-adaptive-proj no-ln --encoder-attn-use-t5-rpe --encoder-attn-overlap-window
CUDA_VISIBLE_DEVICES=0,1,2,3 bash main.sh -p < dir-of-your-bin-data > -d wmt -s eva_32_8 -g 4 -e TRUE --attn-name-encoder eva --encoder-attn-window-size 32 --encoder-attn-num-landmarks 8 --encoder-attn-adaptive-proj no-ln --encoder-attn-use-t5-rpe --encoder-attn-overlap-window # Currently, LARA does not support causal masking yet.
# EVA on a 16-layer Transformer LM
CUDA_VISIBLE_DEVICES=0,1,2,3 bash main.sh -p < dir-of-your-bin-data > -m 16layers -d wikitext103 -s eva_128_8_16layers -g 4 -e TRUE --attn-name-decoder causal_eva --decoder-attn-window-size 128 --decoder-attn-causal --decoder-attn-adaptive-proj qk --decoder-attn-chunk-size 8 --decoder-attn-use-t5-rpe
# EVA on a 32-layer Transformer LM
CUDA_VISIBLE_DEVICES=0,1,2,3 bash main.sh -p < dir-of-your-bin-data > -m 32layers -d wikitext103 -s eva_128_8_32layers -g 4 -e TRUE --attn-name-decoder causal_eva --decoder-attn-window-size 128 --decoder-attn-causal --decoder-attn-adaptive-proj qk --decoder-attn-chunk-size 8 --decoder-attn-use-t5-rpe Pour la génération et l'évaluation, transmettez simplement l'argument -i true lorsque vous appelez main.sh pour effectuer la procédure d'inférence uniquement. Le chemin de contrôle peut être spécifié comme -c <your-ckpt-path> . Par exemple,
# Machine Translation
CUDA_VISIBLE_DEVICES=0 bash main.sh -i true -c < your-possibly-avg-checkpoint.pt > -p < dir-of-your-bin-data > -d wmt -g 1
# Autoregressive Language Modeling
CUDA_VISIBLE_DEVICES=0 bash main.sh -i true -c < your-checkpoint_last.pt > -p < dir-of-your-bin-data > -d wikitext103 -g 1 Nous fournissons également des points de contrôle de modèle EVA formés dans OneDrive pour les tâches de traduction automatique et de modélisation du langage:
@inproceedings { zheng2023efficient ,
title = { Efficient Attention via Control Variates } ,
author = { Lin Zheng and Jianbo Yuan and Chong Wang and Lingpeng Kong } ,
booktitle = { International Conference on Learning Representations } ,
year = { 2023 } ,
url = { https://openreview.net/forum?id=G-uNfHKrj46 }
} @inproceedings { zheng2022linear ,
title = { Linear complexity randomized self-attention mechanism } ,
author = { Lin Zheng and Chong Wang and Lingpeng Kong } ,
booktitle = { International Conference on Machine Learning } ,
pages = { 27011--27041 } ,
year = { 2022 } ,
organization = { PMLR }
}