sat ( SwissArmyTransformer )는 자신의 변압기 변형을 개발할 수있는 유연하고 강력한 라이브러리입니다.
sat "Swiss Army Knife"의 이름을 따서 명명되었습니다. 즉, 모든 모델 (예 : Bert, Gpt, T5, GLM, Cogview, Vit ...)은 동일한 백본 코드를 공유 하고 여분의 가벼운 믹스 인과 함께 다양한 사용법을 제공합니다.
sat deepspeed-ZeRO 및 Model 병렬 처리로 구동되며, 대형 모델 (100m ~ 20B 매개 변수)을위한 사전 조정 및 최종 조정을위한 모범 사례를 제공하는 것을 목표로합니다.
pip install SwissArmyTransformer
한 줄만 모델에 대한 모형 구성 요소, 예를 들어 접두사 튜닝을 추가하십시오 !
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 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 여기서 우리는 GPU 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 추천하십시오.
기고를위한 튜토리얼이 진행 중입니다!
이 프로젝트는 DeepSpeed, Megatron-LM 및 Huggingface Transformers를 기반으로합니다. 그들의 멋진 일에 감사드립니다.