sat ( SwissArmyTransformer )は、独自の変圧器バリアントを開発するための柔軟で強力なライブラリです。
sat 「スイスアーミーナイフ」にちなんで命名されています。つまり、すべてのモデル(BERT、GPT、T5、GLM、COGVIEW、VIT ...など)が同じバックボーンコードを共有し、いくつかの余分な軽量ミキシンで用途の多い使用法に対応します。
sat 、 deepspeed-ZeROとモデルの並列性を搭載しており、大規模なモデル(100m〜20Bパラメーター)の前脱直および微調整のベストプラクティスを提供することを目指しています。
pip install SwissArmyTransformer
たった1つの行にモデルに依存しないコンポーネント(プレフィックスチューニング)を追加します!
class ClassificationModel ( GLMModel ): # can also be BertModel, RobertaModel, etc.
def __init__ ( self , args , transformer = None , ** kwargs ):
super (). __init__ ( args , transformer = transformer , ** kwargs )
self . add_mixin ( 'classification_head' , MLPHeadMixin ( args . hidden_size , 2048 , 1 ))
# Arm an arbitrary model with Prefix-tuning with this line!
self . add_mixin ( 'prefix-tuning' , PrefixTuningMixin ( args . num_layers , args . hidden_size // args . num_attention_heads , args . num_attention_heads , args . prefix_len )) model , args = AutoModel . from_pretrained ( 'glm-10b-chinese' , args )
model . add_mixin ( 'auto-regressive' , CachedAutoregressiveMixin ())
# Generate a sequence with beam search
from sat . generation . autoregressive_sampling import filling_sequence
from sat . generation . sampling_strategies import BeamSearchStrategy
output , * mems = filling_sequence ( model , input_seq ,
batch_size = args . batch_size ,
strategy = BeamSearchStrategy ( args . batch_size ))最小限のコードで変圧器ベースのモデルを構築します。 GLMに言及しましたが、これは標準の変圧器(ベースモデルと呼ばれる)とは、埋め込み(およびトレーニング損失)の標準変圧器(およびベースメモデルと呼ばれます)です。コーディング時には、関連する部分にのみ集中する必要があります。
class BlockPositionEmbeddingMixin ( BaseMixin ):
# Here define parameters for the mixin
def __init__ ( self , max_sequence_length , hidden_size , init_method_std = 0.02 ):
super ( BlockPositionEmbeddingMixin , self ). __init__ ()
self . max_sequence_length = max_sequence_length
self . hidden_size = hidden_size
self . block_position_embeddings = torch . nn . Embedding ( max_sequence_length , hidden_size )
torch . nn . init . normal_ ( self . block_position_embeddings . weight , mean = 0.0 , std = init_method_std )
# Here define the method for the mixin
def position_embedding_forward ( self , position_ids , ** kwargs ):
position_ids , block_position_ids = position_ids [:, 0 ], position_ids [:, 1 ]
position_embeddings = self . transformer . position_embeddings ( position_ids )
block_position_embeddings = self . block_position_embeddings ( block_position_ids )
return position_embeddings + block_position_embeddings
class GLMModel ( BaseModel ):
def __init__ ( self , args , transformer = None ):
super (). __init__ ( args , transformer = transformer )
self . add_mixin ( 'block_position_embedding' ,
BlockPositionEmbeddingMixin ( args . max_sequence_length , args . hidden_size )
) # Add the mixin for GLMトレーニングの包括的なサポート。 sat目的は、PretrainingとFinetuningのベストプラクティスを提供することを目指しています。ここでは、 forward_stepとcreate_dataset_functionのみを完了する必要があります。
--num_nodes 、 --num_gpusおよび単純なhostfileを指定して、トレーニングを複数のGPUまたはノードに拡張します。memmapを自動拡張およびシャッフルします。(推論のために)SATでBert使用する最も典型的なPythonファイルは次のとおりです。
# @File: inference_bert.py
from sat import get_args , get_tokenizer , AutoModel
# Parse args, initialize the environment. This is necessary.
args = get_args ()
# Automatically download and load model. Will also dump model-related hyperparameters to args.
model , args = AutoModel . from_pretrained ( 'bert-base-uncased' , args )
# Get the BertTokenizer according to args.tokenizer_type (automatically set).
tokenizer = get_tokenizer ( args )
# Here to use bert as you want!
# ...その後、コードを介して実行できます
SAT_HOME=/path/to/download python inference_bert.py --mode inference公式にサポートされているすべてのモデル名はurls.pyにあります。
微調整または前処理するのは、変圧器も非常に簡単です!
# @File: finetune_bert.py
from sat import get_args , get_tokenizer , AutoModel
from sat . model . mixins import MLPHeadMixin
def create_dataset_function ( path , args ):
# Here to load the dataset
# ...
assert isinstance ( dataset , torch . utils . data . Dataset )
return dataset
def forward_step ( data_iterator , model , args , timers ):
inputs = next ( data_iterator ) # from the dataset of create_dataset_function.
loss , * others = model ( inputs )
return loss
# Parse args, initialize the environment. This is necessary.
args = get_args ()
model , args = AutoModel . from_pretrained ( 'bert-base-uncased' , args )
tokenizer = get_tokenizer ( args )
# Here to use bert as you want!
model . del_mixin ( 'bert-final' )
model . add_mixin ( 'classification_head' , MLPHeadMixin ( args . hidden_size , 2048 , 1 ))
# ONE LINE to train!
# args already includes hyperparams such as lr, train-iters, zero-stage ...
training_main ( args ,
model_cls = model ,
forward_step_function = forward_step , # user define
create_dataset_function = create_dataset_function # user define
)その後、コードを介して実行できます
deepspeed --include localhost:0,1 finetune_bert.py
--experiment-name ftbert
--mode finetune --train-iters 1000 --save /path/to/save
--train-data /path/to/train --valid-data /path/to/valid
--lr 0.00002 --batch-size 8 --zero-stage 1 --fp16ここでは、GPUS 0,1で並列データを使用します。また、 --hostfile /path/to/hostfileを介して、相互接続された多くのマシンでトレーニングを開始することもできます。詳細については、チュートリアルをご覧ください。
独自のモデルを作成するには、標準トランスの違いを考慮するだけです。たとえば、注意操作を改善するアイデアがある場合:
from sat . model import BaseMixin
class MyAttention ( BaseMixin ):
def __init__ ( self , hidden_size ):
super ( MyAttention , self ). __init__ ()
# MyAttention may needs some new params, e.g. a learnable alpha.
self . learnable_alpha = torch . nn . Parameter ( torch . ones ( hidden_size ))
# This is a hook function, the name `attention_fn` is special.
def attention_fn ( q , k , v , mask , dropout = None , ** kwargs ):
# Code for my attention.
# ...
return attention_resultsここで、 attention_fnはフック関数であり、デフォルトのアクションを新しい関数に置き換えます。利用可能なすべてのフックは、transformer_defaults.pyにあります。これで、 add_mixin使用して、Bert、VIT、CogViewなどのすべての変圧器に変更を適用できます。詳細については、チュートリアルをご覧ください。
現在、私たちは紙を持っていないので、あなたは私たちを正式に引用する必要はありません!〜
このプロジェクトが研究またはエンジニアリングに役立つ場合は、 footnote{https://github.com/THUDM/SwissArmyTransformer}を使用して、私たちに言及し、他の人にSwissArmyTransformerを推奨してください。
SATを寄付するためのチュートリアルは途中です!
このプロジェクトは、Deepspeed、Megatron-LM、およびHuggingface Transformers(のユーザー)に基づいています。彼らの素晴らしい仕事をありがとう。