sat ( SwissArmyTransformer )是一个灵活而强大的库,可以开发自己的变压器变体。
sat以“瑞士军刀”的名字命名,这意味着所有模型(例如Bert,GPT,T5,GLM,Cogview,Vit ...)共享相同的骨干代码,并使用一些额外的轻量级混合物来迎合多种用途。
sat由deepspeed-ZeRO和模型并行性提供动力,旨在为大型模型提供预处理和填充的最佳实践(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 。
贡献SAT的教程即将在路上!
该项目基于DeepSpeed,Megatron-LM和HuggingFace Transformers的(用户)。感谢他们的出色工作。