def init_data(self, use_cuda) -> None:
        test_device = torch.device('cuda:0') if use_cuda else \
            torch.device('cpu:0')
        if not use_cuda:
            torch.set_num_threads(1)

        torch.set_grad_enabled(False)
        self.cfg = BertConfig()

        self.torch_encoder_layer = BertEncoder(self.cfg)
        self.torch_encoder_layer.eval()

        if use_cuda:
            self.torch_encoder_layer.to(test_device)

        self.batch_size = 1
        self.seq_length = 40
        self.hidden_size = self.cfg.hidden_size
        self.input_tensor = torch.rand(size=(self.batch_size, self.seq_length,
                                             self.hidden_size),
                                       dtype=torch.float32,
                                       device=test_device)

        self.attention_mask = torch.ones((self.batch_size, self.seq_length),
                                         dtype=torch.float32,
                                         device=test_device)
        self.attention_mask = self.attention_mask[:, None, None, :]
        self.attention_mask = (1.0 - self.attention_mask) * -10000.0

        self.turbo_bert_encoder = turbo_transformers.BertEncoder.from_torch(
            self.torch_encoder_layer)
示例#2
0
 def __init__(self, config):
     super(BertModel, self).__init__(config)
     self.config = config
     self.embeddings = BertEmbeddings(config)
     self.encoder = BertEncoder(config)
     self.pooler = BertPooler(config)
     self.init_weights()
示例#3
0
    def __init__(self, config):
        super(BertImgModel, self).__init__(config)
        self.embeddings = BertEmbeddings(config)
        self.encoder = BertEncoder(config)#CaptionBertEncoder(config)
        self.pooler = BertPooler(config)

        self.img_dim = config.img_feature_dim
        logger.info('BertImgModel Image Dimension: {}'.format(self.img_dim))
        self.img_feature_type = config.img_feature_type
        if hasattr(config, 'use_img_layernorm'):
            self.use_img_layernorm = config.use_img_layernorm
        else:
            self.use_img_layernorm = None

        if config.img_feature_type == 'dis_code':
            self.code_embeddings = nn.Embedding(config.code_voc, config.code_dim, padding_idx=0)
            self.img_embedding = nn.Linear(config.code_dim, self.config.hidden_size, bias=True)
        elif config.img_feature_type == 'dis_code_t': # transpose
            self.code_embeddings = nn.Embedding(config.code_voc, config.code_dim, padding_idx=0)
            self.img_embedding = nn.Linear(config.code_size, self.config.hidden_size, bias=True)
        elif config.img_feature_type == 'dis_code_scale': # scaled
            self.input_embeddings = nn.Linear(config.code_dim, config.code_size, bias=True)
            self.code_embeddings = nn.Embedding(config.code_voc, config.code_dim, padding_idx=0)
            self.img_embedding = nn.Linear(config.code_dim, self.config.hidden_size, bias=True)
        else:
            self.img_embedding = nn.Linear(self.img_dim, self.config.hidden_size, bias=True)
            self.dropout = nn.Dropout(config.hidden_dropout_prob)
            if self.use_img_layernorm:
                self.LayerNorm = LayerNorm(config.hidden_size, eps=config.img_layer_norm_eps)
示例#4
0
 def __init__(self, config):
     super(BojoneModel, self).__init__(config)
     self.config = config
     self.embeddings = BertEmbeddings(config)
     self.encoder = BertEncoder(config)
     self.cls = BertPreTrainingHeads(self.embeddings.word_embeddings.weight,
                                     config)
     self.init_weights()
示例#5
0
文件: model.py 项目: peleiden/daLUKE
    def __init__(self,
        bert_config: BertConfig,
        ent_vocab_size: int,
        ent_embed_size: int,
    ):
        super().__init__(bert_config, ent_vocab_size, ent_embed_size)

        self.encoder = BertEncoder(bert_config)
示例#6
0
    def __init__(self, config):
        super().__init__(config)
        self.config = config

        self.embeddings = BertCharacterEmbeddings(config)
        self.encoder = BertEncoder(config)
        self.pooler = BertPooler(config)

        self.init_weights()
示例#7
0
 def __init__(self, config, tokenizer, device):
     super().__init__()
     self.config = config
     self.tokenizer = tokenizer
     self.embeddings = BertEmbeddings(self.config)
     self.corrector = BertEncoder(self.config)
     self.mask_token_id = self.tokenizer.mask_token_id
     self.cls = BertOnlyMLMHead(self.config)
     self._device = device
示例#8
0
    def __init__(self, config, args):
        super().__init__(config)
        self.config = config

        self.embeddings = BertEmbeddings(config)
        self.encoder = BertEncoder(config)
        self.pooler = BertPooler(config)
        self.MAG = MAG(config, args)

        self.init_weights()
示例#9
0
    def __init__(self, config, add_pooling_layer=True):
        super().__init__(config)
        self.config = config

        self.embeddings = KBertEmbeddings(config)
        self.encoder = BertEncoder(config)

        self.pooler = BertPooler(config) if add_pooling_layer else None

        self.init_weights()
示例#10
0
    def __init__(self, config: LukeConfig):
        super(LukeModel, self).__init__()

        self.config = config

        self.encoder = BertEncoder(config)
        self.pooler = BertPooler(config)

        if self.config.bert_model_name and "roberta" in self.config.bert_model_name:
            self.embeddings = RobertaEmbeddings(config)
            self.embeddings.token_type_embeddings.requires_grad = False
        else:
            self.embeddings = BertEmbeddings(config)
        self.entity_embeddings = EntityEmbeddings(config)
示例#11
0
    def __init__(self, config, add_pooling_layer=True):
        # Call the init one parent class up. Otherwise, the model will be defined twice.
        BertPreTrainedModel.__init__(self, config)
        self.config = config

        self.embeddings = BertEmbeddings(config)
        self.encoder = BertEncoder(config)

        self.pooler = BertPooler(config) if add_pooling_layer else None

        # Sparsify linear modules.
        self.sparsify_model()

        self.init_weights()
示例#12
0
文件: core.py 项目: billzyx/WavBERT
 def __init__(self, config, add_pooling_layer=True):
     super().__init__(config, add_pooling_layer)
     self.config = config
     self.encoder = BertEncoder(config)
     self.word_embedding_predictor = BertWordEmbeddingsPredictor(config)
     if hasattr(self.config, 'word_predictor_pre_training'
                ) and not self.config.word_predictor_pre_training:
         for param in self.word_embedding_predictor.parameters():
             param.requires_grad = False
     # self.word_embedding_shifter = BertWordEmbeddingsPredictor(config)
     # self.word_embedding_predictor = nn.Embedding(
     #     config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id,
     #     _weight=self.get_input_embeddings().weight)
     if hasattr(config, 'train_original') and not config.train_original:
         for param in self.embeddings.parameters():
             param.requires_grad = False
         for param in self.pooler.parameters():
             param.requires_grad = False
         for param in self.encoder.parameters():
             param.requires_grad = False
     # self.length_predictor = nn.Conv1d(in_channels=config.hidden_size,
     #                      out_channels=1, kernel_size=1)
     self.init_weights()
示例#13
0
def get_modules(params_dict):
    modules = {}
    params = copy.deepcopy(params_dict)
    params["attention_probs_dropout_prob"] = params.pop("attention_dropout")
    params["hidden_dropout_prob"] = params.pop("hidden_dropout")

    torch.manual_seed(1234)
    hf_module = BertEncoder(BertConfig(**params))
    modules["bert"] = hf_module

    torch.manual_seed(1234)
    hf_module = RobertaEncoder(RobertaConfig(**params))
    modules["roberta"] = hf_module

    torch.manual_seed(1234)
    hf_module = ElectraEncoder(ElectraConfig(**params))
    modules["electra"] = hf_module

    return modules
    def __init__(self, config, visual_embedding_dim):
        super().__init__()

        # Attributes
        self.config = config
        self.config.visual_embedding_dim = visual_embedding_dim
        self.num_labels = config.num_labels

        # Build Bert
        self.embeddings = BertVisioLinguisticEmbeddings(self.config)
        self.encoder = BertEncoder(self.config)
        self.pooler = BertPooler(self.config)

        # Add classification head
        # Added sigmoid activation to smooth the output
        self.dropout = nn.Dropout(self.config.hidden_dropout_prob)
        self.classifier = nn.Sequential(
            BertPredictionHeadTransform(self.config),
            nn.Linear(self.config.hidden_size, self.num_labels), nn.Sigmoid())

        self.init_weights()
示例#15
0
    def __init__(self, config):
        super().__init__(config)

        self.embeddings = BertEmbeddings(config)
        self.encoder = BertEncoder(config)
        self.init_weights()
class TestBertEncoder(unittest.TestCase):
    def init_data(self, use_cuda) -> None:
        test_device = torch.device('cuda:0') if use_cuda else \
            torch.device('cpu:0')
        if not use_cuda:
            torch.set_num_threads(1)

        torch.set_grad_enabled(False)
        self.cfg = BertConfig()

        self.torch_encoder_layer = BertEncoder(self.cfg)
        self.torch_encoder_layer.eval()

        if use_cuda:
            self.torch_encoder_layer.to(test_device)

        self.batch_size = 1
        self.seq_length = 40
        self.hidden_size = self.cfg.hidden_size
        self.input_tensor = torch.rand(size=(self.batch_size, self.seq_length,
                                             self.hidden_size),
                                       dtype=torch.float32,
                                       device=test_device)

        self.attention_mask = torch.ones((self.batch_size, self.seq_length),
                                         dtype=torch.float32,
                                         device=test_device)
        self.attention_mask = self.attention_mask[:, None, None, :]
        self.attention_mask = (1.0 - self.attention_mask) * -10000.0

        self.turbo_bert_encoder = turbo_transformers.BertEncoder.from_torch(
            self.torch_encoder_layer)

    def check_torch_and_turbo(self, use_cuda=True):
        self.init_data(use_cuda=use_cuda)
        self.num_iter = 2

        turbo_bert_layer_result = None
        turbo_model = lambda: self.turbo_bert_encoder(self.input_tensor,
                                                      self.attention_mask,
                                                      output_attentions=True,
                                                      output_hidden_states=True
                                                      )

        turbo_bert_layer_result, turbo_qps, turbo_time_consume = \
            test_helper.run_model(turbo_model, use_cuda, self.num_iter)

        print(f"BertEncoder TurboTransform QPS, {turbo_qps}, ",
              f"Time Cost, {turbo_time_consume}")

        # turbo_bert_layer_result = self.turbo_bert_encoder(
        #     self.input_tensor,
        #     self.attention_mask,
        #     output_attentions = True,
        #     output_hidden_states = False)

        torch_model = lambda: self.torch_encoder_layer(
            self.input_tensor,
            self.attention_mask, [None] * self.cfg.num_hidden_layers,
            output_attentions=True,
            output_hidden_states=True)

        torch_bert_layer_result, torch_qps, torch_time_consume = \
            test_helper.run_model(torch_model, use_cuda, self.num_iter)

        print(f"BertEncoder Torch QPS, {torch_qps}, ",
              f"Time Cost, {torch_time_consume}")

        diff = torch.abs(torch_bert_layer_result[0] -
                         turbo_bert_layer_result[0])
        self.assertTrue(torch.max(diff) < 1e-2)

        # Note we did not print the last hidden_states, because it is the same as output
        # print(len(torch_bert_layer_result[1]), len(turbo_bert_layer_result[1]))
        # for a, b in zip(torch_bert_layer_result[1],
        #                 turbo_bert_layer_result[1]):
        #     diff = torch.abs(a - b)
        #     self.assertTrue(torch.max(diff) < 1e-2)

        # for a, b in zip(torch_bert_layer_result[2],
        #                 turbo_bert_layer_result[2]):
        #     diff = torch.abs(a - b)
        #     self.assertTrue(torch.max(diff) < 1e-2)

    def test_encoder(self):
        self.check_torch_and_turbo(use_cuda=False)
        if torch.cuda.is_available() and \
            turbo_transformers.config.is_compiled_with_cuda():
            self.check_torch_and_turbo(use_cuda=True)
示例#17
0
文件: core.py 项目: billzyx/WavBERT
class ShiftBertModel(BertModel):
    """

    The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
    cross-attention is added between the self-attention layers, following the architecture described in `Attention is
    all you need <https://arxiv.org/abs/1706.03762>`__ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
    Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.

    To behave as an decoder the model needs to be initialized with the :obj:`is_decoder` argument of the configuration
    set to :obj:`True`. To be used in a Seq2Seq model, the model needs to initialized with both :obj:`is_decoder`
    argument and :obj:`add_cross_attention` set to :obj:`True`; an :obj:`encoder_hidden_states` is then expected as an
    input to the forward pass.
    """
    def __init__(self, config, add_pooling_layer=True):
        super().__init__(config, add_pooling_layer)
        self.config = config
        self.encoder = BertEncoder(config)
        self.word_embedding_predictor = BertWordEmbeddingsPredictor(config)
        if hasattr(self.config, 'word_predictor_pre_training'
                   ) and not self.config.word_predictor_pre_training:
            for param in self.word_embedding_predictor.parameters():
                param.requires_grad = False
        # self.word_embedding_shifter = BertWordEmbeddingsPredictor(config)
        # self.word_embedding_predictor = nn.Embedding(
        #     config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id,
        #     _weight=self.get_input_embeddings().weight)
        if hasattr(config, 'train_original') and not config.train_original:
            for param in self.embeddings.parameters():
                param.requires_grad = False
            for param in self.pooler.parameters():
                param.requires_grad = False
            for param in self.encoder.parameters():
                param.requires_grad = False
        # self.length_predictor = nn.Conv1d(in_channels=config.hidden_size,
        #                      out_channels=1, kernel_size=1)
        self.init_weights()

    def forward(
        self,
        input_ids=None,
        attention_mask=None,
        token_type_ids=None,
        shifter_embedding=None,
        position_ids=None,
        head_mask=None,
        inputs_embeds=None,
        encoder_hidden_states=None,
        encoder_attention_mask=None,
        output_attentions=None,
        output_hidden_states=None,
        return_dict=None,
    ):
        r"""
        encoder_hidden_states  (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
            Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
            the model is configured as a decoder.
        encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
            Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
            the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.
        """

        output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
        output_hidden_states = (output_hidden_states
                                if output_hidden_states is not None else
                                self.config.output_hidden_states)
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        if input_ids is not None and inputs_embeds is not None:
            raise ValueError(
                "You cannot specify both input_ids and inputs_embeds at the same time"
            )
        elif input_ids is not None:
            input_shape = input_ids.size()
        elif inputs_embeds is not None:
            input_shape = inputs_embeds.size()[:-1]
        else:
            raise ValueError(
                "You have to specify either input_ids or inputs_embeds")

        device = input_ids.device if input_ids is not None else inputs_embeds.device

        if attention_mask is None:
            attention_mask = torch.ones(input_shape, device=device)
        if token_type_ids is None:
            token_type_ids = torch.zeros(input_shape,
                                         dtype=torch.long,
                                         device=device)

        # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
        # ourselves in which case we just need to make it broadcastable to all heads.
        extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(
            attention_mask, input_shape, device)

        # If a 2D or 3D attention mask is provided for the cross-attention
        # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
        if self.config.is_decoder and encoder_hidden_states is not None:
            encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size(
            )
            encoder_hidden_shape = (encoder_batch_size,
                                    encoder_sequence_length)
            if encoder_attention_mask is None:
                encoder_attention_mask = torch.ones(encoder_hidden_shape,
                                                    device=device)
            encoder_extended_attention_mask = self.invert_attention_mask(
                encoder_attention_mask)
        else:
            encoder_extended_attention_mask = None

        # Prepare head mask if needed
        # 1.0 in head_mask indicate we keep the head
        # attention_probs has shape bsz x n_heads x N x N
        # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
        # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
        head_mask = self.get_head_mask(head_mask,
                                       self.config.num_hidden_layers)

        # use audio embedding if non-zero
        inputs_embeds = self.word_embedding_predictor(shifter_embedding)
        inputs_embeds_original = self.get_input_embeddings()(input_ids)
        inputs_embeds = torch.where(
            torch.sum(torch.abs(shifter_embedding), dim=-1, keepdim=True) >
            0.0, inputs_embeds, inputs_embeds_original)

        if hasattr(self.config, 'word_predictor_pre_training'
                   ) and self.config.word_predictor_pre_training:
            loss_fct = L1Loss()
            word_predictor_loss = loss_fct(inputs_embeds,
                                           inputs_embeds_original.detach())
            word_predictor_loss = word_predictor_loss * 100

        # inputs_embeds_shifter = self.word_embedding_shifter(shifter_embedding)
        # inputs_embeds = inputs_embeds + inputs_embeds_shifter
        # inputs_embeds = torch.where(torch.sum(torch.abs(shifter_embedding), dim=-1, keepdim=True) > 0.0,
        #                             inputs_embeds, inputs_embeds_original)

        embedding_output = self.embeddings(input_ids=input_ids,
                                           position_ids=position_ids,
                                           token_type_ids=token_type_ids,
                                           inputs_embeds=inputs_embeds)
        encoder_outputs = self.encoder(
            embedding_output,
            # shifter_embedding,
            attention_mask=extended_attention_mask,
            head_mask=head_mask,
            encoder_hidden_states=encoder_hidden_states,
            encoder_attention_mask=encoder_extended_attention_mask,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )
        sequence_output = encoder_outputs[0]
        pooled_output = self.pooler(
            sequence_output) if self.pooler is not None else None

        # length_output = sequence_output.permute(0, 2, 1)
        # length_output = self.length_predictor(length_output)
        # length_output = length_output.squeeze(1)

        if not return_dict:
            return (sequence_output, pooled_output) + encoder_outputs[1:]

        if hasattr(self.config, 'word_predictor_pre_training'
                   ) and self.config.word_predictor_pre_training:
            return BaseModelOutputWithPoolingAndCrossAttentionsAndWordPredictorLoss(
                last_hidden_state=sequence_output,
                pooler_output=pooled_output,
                hidden_states=encoder_outputs.hidden_states,
                attentions=encoder_outputs.attentions,
                cross_attentions=encoder_outputs.cross_attentions,
                word_predictor_loss=word_predictor_loss,
            )

        return BaseModelOutputWithPoolingAndCrossAttentions(
            last_hidden_state=sequence_output,
            pooler_output=pooled_output,
            hidden_states=encoder_outputs.hidden_states,
            attentions=encoder_outputs.attentions,
            cross_attentions=encoder_outputs.cross_attentions,
            # length_output=length_output,
        )
示例#18
0
    def __init__(self, config):
        super().__init__(config)

        self.prev_pred_embeddings = PrevPredEmbeddings(config)
        self.encoder = BertEncoder(config)
        self.init_weights()