textflint.generation_layer.transformation.CWS.cn_mlm¶
Use Bert to generate words.¶
-
class
textflint.generation_layer.transformation.CWS.cn_mlm.CnMLM(**kwargs)[source]¶ Bases:
textflint.generation_layer.transformation.transformation.TransformationUse Bert to generate words.
Example:
小明喜欢看书 -> 小明喜欢看报纸
-
class
textflint.generation_layer.transformation.CWS.cn_mlm.BertForMaskedLM(config)[source]¶ Bases:
transformers.models.bert.modeling_bert.BertPreTrainedModelBert Model with a language modeling head on top.
This model inherits from
PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
- Parameters:
- config (
BertConfig): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the
from_pretrained()method to load the model weights.
- config (
-
forward(input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, encoder_hidden_states=None, encoder_attention_mask=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None)[source]¶ The
BertForMaskedLMforward method, overrides the__call__()special method.Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.- Args:
- input_ids (
torch.LongTensorof shape(batch_size, sequence_length)): Indices of input sequence tokens in the vocabulary.
Indices can be obtained using
BertTokenizer. Seetransformers.PreTrainedTokenizer.encode()andtransformers.PreTrainedTokenizer.__call__()for details.- attention_mask (
torch.FloatTensorof shape(batch_size, sequence_length), optional): Mask to avoid performing attention on padding token indices. Mask values selected in
[0, 1]:1 for tokens that are not masked,
0 for tokens that are masked.
- token_type_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional): Segment token indices to indicate first and second portions of the inputs. Indices are selected in
[0, 1]:0 corresponds to a sentence A token,
1 corresponds to a sentence B token.
- position_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional): Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
[0, config.max_position_embeddings - 1].- head_mask (
torch.FloatTensorof shape(num_heads,)or(num_layers, num_heads), optional): Mask to nullify selected heads of the self-attention modules. Mask values selected in
[0, 1]:1 indicates the head is not masked,
0 indicates the head is masked.
- inputs_embeds (
torch.FloatTensorof shape(batch_size, sequence_length, hidden_size), optional): Optionally, instead of passing
input_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model’s internal embedding lookup matrix.- output_attentions (
bool, optional): Whether or not to return the attentions tensors of all attention layers. See
attentionsunder returned tensors for more detail.- output_hidden_states (
bool, optional): Whether or not to return the hidden states of all layers. See
hidden_statesunder returned tensors for more detail.- return_dict (
bool, optional): Whether or not to return a
ModelOutputinstead of a plain tuple.- labels (
torch.LongTensorof shape(batch_size, sequence_length), optional): Labels for computing the masked language modeling loss. Indices should be in
[-100, 0, ..., config.vocab_size](seeinput_idsdocstring) Tokens with indices set to-100are ignored (masked), the loss is only computed for the tokens with labels in[0, ..., config.vocab_size]
- input_ids (
- Returns:
MaskedLMOutputortuple(torch.FloatTensor): AMaskedLMOutput(ifreturn_dict=Trueis passed or whenconfig.return_dict=True) or a tuple oftorch.FloatTensorcomprising various elements depending on the configuration (BertConfig) and inputs.loss (
torch.FloatTensorof shape(1,), optional, returned whenlabelsis provided) – Masked language modeling (MLM) loss.logits (
torch.FloatTensorof shape(batch_size, sequence_length, config.vocab_size)) – Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).hidden_states (
tuple(torch.FloatTensor), optional, returned whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) – Tuple oftorch.FloatTensor(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size).Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (
tuple(torch.FloatTensor), optional, returned whenoutput_attentions=Trueis passed or whenconfig.output_attentions=True) – Tuple oftorch.FloatTensor(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length).Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
Example:
>>> from transformers import BertTokenizer, BertForMaskedLM >>> import torch >>> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') >>> model = BertForMaskedLM.from_pretrained('bert-base-uncased') >>> inputs = tokenizer("The capital of France is [MASK].", return_tensors="pt") >>> labels = tokenizer("The capital of France is Paris.", return_tensors="pt")["input_ids"] >>> outputs = model(**inputs, labels=labels) >>> loss = outputs.loss >>> logits = outputs.logits
-
training: bool¶
-
class
textflint.generation_layer.transformation.CWS.cn_mlm.BertTokenizer(vocab_file, do_lower_case=True, do_basic_tokenize=True, never_split=None, unk_token='[UNK]', sep_token='[SEP]', pad_token='[PAD]', cls_token='[CLS]', mask_token='[MASK]', tokenize_chinese_chars=True, strip_accents=None, **kwargs)[source]¶ Bases:
transformers.tokenization_utils.PreTrainedTokenizerConstruct a BERT tokenizer. Based on WordPiece.
This tokenizer inherits from
PreTrainedTokenizerwhich contains most of the main methods. Users should refer to this superclass for more information regarding those methods.- Args:
- vocab_file (
str): File containing the vocabulary.
- do_lower_case (
bool, optional, defaults toTrue): Whether or not to lowercase the input when tokenizing.
- do_basic_tokenize (
bool, optional, defaults toTrue): Whether or not to do basic tokenization before WordPiece.
- never_split (
Iterable, optional): Collection of tokens which will never be split during tokenization. Only has an effect when
do_basic_tokenize=True- unk_token (
str, optional, defaults to"[UNK]"): The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this token instead.
- sep_token (
str, optional, defaults to"[SEP]"): The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for sequence classification or for a text and a question for question answering. It is also used as the last token of a sequence built with special tokens.
- pad_token (
str, optional, defaults to"[PAD]"): The token used for padding, for example when batching sequences of different lengths.
- cls_token (
str, optional, defaults to"[CLS]"): The classifier token which is used when doing sequence classification (classification of the whole sequence instead of per-token classification). It is the first token of the sequence when built with special tokens.
- mask_token (
str, optional, defaults to"[MASK]"): The token used for masking values. This is the token used when training this model with masked language modeling. This is the token which the model will try to predict.
- tokenize_chinese_chars (
bool, optional, defaults toTrue): Whether or not to tokenize Chinese characters.
This should likely be deactivated for Japanese (see this issue).
- strip_accents: (
bool, optional): Whether or not to strip all accents. If this option is not specified, then it will be determined by the value for
lowercase(as in the original BERT).
- vocab_file (
-
vocab_files_names: Dict[str, str] = {'vocab_file': 'vocab.txt'}¶
-
pretrained_vocab_files_map: Dict[str, Dict[str, str]] = {'vocab_file': {'TurkuNLP/bert-base-finnish-cased-v1': 'https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/vocab.txt', 'TurkuNLP/bert-base-finnish-uncased-v1': 'https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/vocab.txt', 'bert-base-cased': 'https://huggingface.co/bert-base-cased/resolve/main/vocab.txt', 'bert-base-cased-finetuned-mrpc': 'https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/vocab.txt', 'bert-base-chinese': 'https://huggingface.co/bert-base-chinese/resolve/main/vocab.txt', 'bert-base-german-cased': 'https://huggingface.co/bert-base-german-cased/resolve/main/vocab.txt', 'bert-base-german-dbmdz-cased': 'https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/vocab.txt', 'bert-base-german-dbmdz-uncased': 'https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/vocab.txt', 'bert-base-multilingual-cased': 'https://huggingface.co/bert-base-multilingual-cased/resolve/main/vocab.txt', 'bert-base-multilingual-uncased': 'https://huggingface.co/bert-base-multilingual-uncased/resolve/main/vocab.txt', 'bert-base-uncased': 'https://huggingface.co/bert-base-uncased/resolve/main/vocab.txt', 'bert-large-cased': 'https://huggingface.co/bert-large-cased/resolve/main/vocab.txt', 'bert-large-cased-whole-word-masking': 'https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/vocab.txt', 'bert-large-cased-whole-word-masking-finetuned-squad': 'https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt', 'bert-large-uncased': 'https://huggingface.co/bert-large-uncased/resolve/main/vocab.txt', 'bert-large-uncased-whole-word-masking': 'https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/vocab.txt', 'bert-large-uncased-whole-word-masking-finetuned-squad': 'https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt', 'wietsedv/bert-base-dutch-cased': 'https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/vocab.txt'}}¶
-
pretrained_init_configuration: Dict[str, Dict[str, Any]] = {'TurkuNLP/bert-base-finnish-cased-v1': {'do_lower_case': False}, 'TurkuNLP/bert-base-finnish-uncased-v1': {'do_lower_case': True}, 'bert-base-cased': {'do_lower_case': False}, 'bert-base-cased-finetuned-mrpc': {'do_lower_case': False}, 'bert-base-chinese': {'do_lower_case': False}, 'bert-base-german-cased': {'do_lower_case': False}, 'bert-base-german-dbmdz-cased': {'do_lower_case': False}, 'bert-base-german-dbmdz-uncased': {'do_lower_case': True}, 'bert-base-multilingual-cased': {'do_lower_case': False}, 'bert-base-multilingual-uncased': {'do_lower_case': True}, 'bert-base-uncased': {'do_lower_case': True}, 'bert-large-cased': {'do_lower_case': False}, 'bert-large-cased-whole-word-masking': {'do_lower_case': False}, 'bert-large-cased-whole-word-masking-finetuned-squad': {'do_lower_case': False}, 'bert-large-uncased': {'do_lower_case': True}, 'bert-large-uncased-whole-word-masking': {'do_lower_case': True}, 'bert-large-uncased-whole-word-masking-finetuned-squad': {'do_lower_case': True}, 'wietsedv/bert-base-dutch-cased': {'do_lower_case': False}}¶
-
max_model_input_sizes: Dict[str, Optional[int]] = {'TurkuNLP/bert-base-finnish-cased-v1': 512, 'TurkuNLP/bert-base-finnish-uncased-v1': 512, 'bert-base-cased': 512, 'bert-base-cased-finetuned-mrpc': 512, 'bert-base-chinese': 512, 'bert-base-german-cased': 512, 'bert-base-german-dbmdz-cased': 512, 'bert-base-german-dbmdz-uncased': 512, 'bert-base-multilingual-cased': 512, 'bert-base-multilingual-uncased': 512, 'bert-base-uncased': 512, 'bert-large-cased': 512, 'bert-large-cased-whole-word-masking': 512, 'bert-large-cased-whole-word-masking-finetuned-squad': 512, 'bert-large-uncased': 512, 'bert-large-uncased-whole-word-masking': 512, 'bert-large-uncased-whole-word-masking-finetuned-squad': 512, 'wietsedv/bert-base-dutch-cased': 512}¶
-
convert_tokens_to_string(tokens)[source]¶ Converts a sequence of tokens (string) in a single string.
-
build_inputs_with_special_tokens(token_ids_0: List[int], token_ids_1: Optional[List[int]] = None) → List[int][source]¶ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. A BERT sequence has the following format:
single sequence:
[CLS] X [SEP]pair of sequences:
[CLS] A [SEP] B [SEP]
- Args:
- token_ids_0 (
List[int]): List of IDs to which the special tokens will be added.
- token_ids_1 (
List[int], optional): Optional second list of IDs for sequence pairs.
- token_ids_0 (
- Returns:
List[int]: List of input IDs with the appropriate special tokens.
-
get_special_tokens_mask(token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False) → List[int][source]¶ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding special tokens using the tokenizer
prepare_for_modelmethod.- Args:
- token_ids_0 (
List[int]): List of IDs.
- token_ids_1 (
List[int], optional): Optional second list of IDs for sequence pairs.
- already_has_special_tokens (
bool, optional, defaults toFalse): Whether or not the token list is already formatted with special tokens for the model.
- token_ids_0 (
- Returns:
List[int]: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
-
create_token_type_ids_from_sequences(token_ids_0: List[int], token_ids_1: Optional[List[int]] = None) → List[int][source]¶ Create a mask from the two sequences passed to be used in a sequence-pair classification task. A BERT sequence pair mask has the following format:
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 | first sequence | second sequence |
If
token_ids_1isNone, this method only returns the first portion of the mask (0s).- Args:
- token_ids_0 (
List[int]): List of IDs.
- token_ids_1 (
List[int], optional): Optional second list of IDs for sequence pairs.
- token_ids_0 (
- Returns:
List[int]: List of token type IDs according to the given sequence(s).
-
class
textflint.generation_layer.transformation.CWS.cn_mlm.CnProcessor(*args, **kwargs)[source]¶ Bases:
objectText Processor class implement NER.
-
static
tokenize(sent)[source]¶ tokenize fiction
- Parameters
sent (str) – the sentence need to be tokenized
- Returns
list.the tokens in it
-
static
-
class
textflint.generation_layer.transformation.CWS.cn_mlm.CnTextField(field_value, mask=None)[source]¶ Bases:
textflint.input_layer.component.field.field.FieldA helper class that represents input string that to be modified.
- Parameters
or list field_value (str) – the value of the field.
mask (int) – mask label.
-
cn_processor= <textflint.common.preprocess.cn_processor.CnProcessor object>¶
pos tags fiction
- Returns
ner tags
-
class
textflint.generation_layer.transformation.CWS.cn_mlm.Transformation(**kwargs)[source]¶ Bases:
abc.ABCAn abstract class for transforming a sequence of text to produce a list of potential adversarial example.
-
processor= <textflint.common.preprocess.en_processor.EnProcessor object>¶
-
transform(sample, n=1, field='x', **kwargs)[source]¶ Transform data sample to a list of Sample.
- Parameters
sample (Sample) – Data sample for augmentation.
n (int) – Max number of unique augmented output, default is 5.
field (str|list) – Indicate which fields to apply transformations.
**kwargs (dict) –
other auxiliary params.
- Returns
list of Sample
-