1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
|
git lfs install git clone https://huggingface.co/hfl/chinese-roberta-wwm-ext
GIT_LFS_SKIP_SMUDGE=1
""" from transformers import AutoTokenizer, AutoModelForMaskedLM
tokenizer = AutoTokenizer.from_pretrained("ckiplab/albert-tiny-chinese")
model = AutoModelForMaskedLM.from_pretrained("ckiplab/albert-tiny-chinese") """
from transformers import AutoConfig,AutoModel,AutoTokenizer,AdamW,get_linear_schedule_with_warmup,logging import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import TensorDataset,SequentialSampler,RandomSampler,DataLoader MODEL_NAME="bert-base-chinese"
config = AutoConfig.from_pretrained(MODEL_NAME) config
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME) tokenizer """ PreTrainedTokenizerFast(name_or_path='bert-base-chinese', vocab_size=21128, model_max_len=512, is_fast=True, padding_side='right', truncation_side='right', special_tokens={'unk_token': '[UNK]', 'sep_token': '[SEP]', 'pad_token': '[PAD]', 'cls_token': '[CLS]', 'mask_token': '[MASK]'}) """
tokenizer.all_special_ids """ [100, 102, 0, 101, 103] """
tokenizer.all_special_tokens """ ['[UNK]', '[SEP]', '[PAD]', '[CLS]', '[MASK]'] """
tokenizer.vocab_size
""" encode( self, text, text_pair, add_special_tokens, padding, truncation, max_length, stride, return_tensors, **kwargs ) -> List[int] Converts a string to a sequence of ids (integer), using the tokenizer and vocabulary. """
text="我在北京工作" token_ids=tokenizer.encode(text) token_ids
tokenizer.convert_ids_to_tokens(token_ids)
token_ids=tokenizer.encode(text,padding=True,max_length=30,add_special_tokens=True) token_ids
token_ids=tokenizer.encode(text,padding="max_length",max_length=30,add_special_tokens=True) token_ids
token_ids=tokenizer.encode(text,padding="max_length",max_length=30,add_special_tokens=True,return_tensors='pt') token_ids
""" 确实是plus版本 主要是返回相关的参数多了 def encode_plus( self, text, text_pair, add_special_tokens, padding, truncation, max_length, stride, return_tensors, return_tensors, return_token_type_ids, return_attention_mask, return_overflowing_tokens, return_special_tokens_mask, return_offsets_mapping, return_length, verbose, **kwargs ) -> BatchEncoding: """
token_ids=tokenizer.encode_plus( text,padding="max_length", max_length=30, add_special_tokens=True, return_tensors='pt', return_token_type_ids=True, return_attention_mask=True ) token_ids
""" 返回 1.pytorch的tensor格式id 2.token_type_ids 3.attention_mask
{ 'input_ids': tensor([ [ 101, 2769, 1762, 1266, 776, 2339, 868, 102, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ]), 'token_type_ids': tensor([ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ]), 'attention_mask': tensor([ [1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ]) } """
model=AutoModel.from_pretrained(MODEL_NAME) model
""" 查看模型结构
BertModel( (embeddings): BertEmbeddings( (word_embeddings): Embedding(21128, 768, padding_idx=0) (position_embeddings): Embedding(512, 768) (token_type_embeddings): Embedding(2, 768) (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True) (dropout): Dropout(p=0.1, inplace=False) ) (encoder): BertEncoder( (layer): ModuleList( (0)-(11): BertLayer( # 12个一样的BertLayer构成encoder (attention): BertAttention( (self): BertSelfAttention( (query): Linear(in_features=768, out_features=768, bias=True) (key): Linear(in_features=768, out_features=768, bias=True) (value): Linear(in_features=768, out_features=768, bias=True) (dropout): Dropout(p=0.1, inplace=False) ) (output): BertSelfOutput( (dense): Linear(in_features=768, out_features=768, bias=True) (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True) (dropout): Dropout(p=0.1, inplace=False) ) ) (intermediate): BertIntermediate( (dense): Linear(in_features=768, out_features=3072, bias=True) (intermediate_act_fn): GELUActivation() ) (output): BertOutput( (dense): Linear(in_features=3072, out_features=768, bias=True) (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True) (dropout): Dropout(p=0.1, inplace=False) ) ) ) ) (pooler): BertPooler( (dense): Linear(in_features=768, out_features=768, bias=True) (activation): Tanh() ) ) """
outputs=model(token_ids['input_ids'],token_ids['attention_mask'])
outputs.keys() """ odict_keys(['last_hidden_state', 'pooler_output']) """
last_hidden_state= outputs[0].shape outputs[1].shape outputs[0][:,0].shape
config.update({ 'output_hidden_states':True }) model=AutoModel.from_pretrained(MODEL_NAME,config=config) outputs=model(token_ids['input_ids'],token_ids['token_type_ids']) outputs.keys() """ odict_keys(['last_hidden_state', 'pooler_output', 'hidden_states']) """
|