Python allennlp.nn.util.masked_softmax() Examples

The following are 14 code examples of allennlp.nn.util.masked_softmax(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module allennlp.nn.util , or try the search function .
Example #1
Source File: expected_risk_minimization.py    From magnitude with MIT License 6 votes vote down vote up
def decode(self,
               initial_state              ,
               decode_step             ,
               supervision                                     )                           :
        cost_function = supervision
        finished_states = self._get_finished_states(initial_state, decode_step)
        loss = initial_state.score[0].new_zeros(1)
        finished_model_scores = self._get_model_scores_by_batch(finished_states)
        finished_costs = self._get_costs_by_batch(finished_states, cost_function)
        for batch_index in finished_model_scores:
            # Finished model scores are log-probabilities of the predicted sequences. We convert
            # log probabilities into probabilities and re-normalize them to compute expected cost under
            # the distribution approximated by the beam search.

            costs = torch.cat([tensor.view(-1) for tensor in finished_costs[batch_index]])
            logprobs = torch.cat([tensor.view(-1) for tensor in finished_model_scores[batch_index]])
            # Unmasked softmax of log probabilities will convert them into probabilities and
            # renormalize them.
            renormalized_probs = nn_util.masked_softmax(logprobs, None)
            loss += renormalized_probs.dot(costs)
        mean_loss = loss / len(finished_model_scores)
        return {u'loss': mean_loss,
                u'best_action_sequences': self._get_best_action_sequences(finished_states)} 
Example #2
Source File: attentions.py    From R-net with MIT License 6 votes vote down vote up
def forward(self, inputs: Tensor, memory: Tensor, memory_mask: Tensor):
        if not self.batch_first:
            inputs = inputs.transpose(0, 1)
            memory = memory.transpose(0, 1)
            memory_mask = memory_mask.transpose(0, 1)

        input_ = self.input_linear(inputs)
        memory_ = self.memory_linear(memory)

        logits = torch.bmm(input_, memory_.transpose(2, 1)) / (self.attention_size ** 0.5)

        memory_mask = memory_mask.unsqueeze(1).expand(-1, inputs.size(1), -1)
        score = masked_softmax(logits, memory_mask, dim=-1)

        context = torch.bmm(score, memory)
        new_input = torch.cat([context, inputs], dim=-1)

        if not self.batch_first:
            return new_input.transpose(0, 1)
        return new_input 
Example #3
Source File: self_attentive_span_extractor.py    From allennlp with Apache License 2.0 5 votes vote down vote up
def forward(
        self,
        sequence_tensor: torch.FloatTensor,
        span_indices: torch.LongTensor,
        span_indices_mask: torch.BoolTensor = None,
    ) -> torch.FloatTensor:
        # shape (batch_size, sequence_length, 1)
        global_attention_logits = self._global_attention(sequence_tensor)

        # shape (batch_size, sequence_length, embedding_dim + 1)
        concat_tensor = torch.cat([sequence_tensor, global_attention_logits], -1)

        concat_output, span_mask = util.batched_span_select(concat_tensor, span_indices)

        # Shape: (batch_size, num_spans, max_batch_span_width, embedding_dim)
        span_embeddings = concat_output[:, :, :, :-1]
        # Shape: (batch_size, num_spans, max_batch_span_width)
        span_attention_logits = concat_output[:, :, :, -1]

        # Shape: (batch_size, num_spans, max_batch_span_width)
        span_attention_weights = util.masked_softmax(span_attention_logits, span_mask)

        # Do a weighted sum of the embedded spans with
        # respect to the normalised attention distributions.
        # Shape: (batch_size, num_spans, embedding_dim)
        attended_text_embeddings = util.weighted_sum(span_embeddings, span_attention_weights)

        if span_indices_mask is not None:
            # Above we were masking the widths of spans with respect to the max
            # span width in the batch. Here we are masking the spans which were
            # originally passed in as padding.
            return attended_text_embeddings * span_indices_mask.unsqueeze(-1)

        return attended_text_embeddings 
Example #4
Source File: attention.py    From allennlp with Apache License 2.0 5 votes vote down vote up
def forward(
        self, vector: torch.Tensor, matrix: torch.Tensor, matrix_mask: torch.BoolTensor = None
    ) -> torch.Tensor:
        similarities = self._forward_internal(vector, matrix)
        if self._normalize:
            return masked_softmax(similarities, matrix_mask)
        else:
            return similarities 
Example #5
Source File: util_test.py    From allennlp with Apache License 2.0 5 votes vote down vote up
def test_masked_softmax_no_mask(self):
        # Testing the general unmasked 1D case.
        vector_1d = torch.FloatTensor([[1.0, 2.0, 3.0]])
        vector_1d_softmaxed = util.masked_softmax(vector_1d, None).data.numpy()
        assert_array_almost_equal(
            vector_1d_softmaxed, numpy.array([[0.090031, 0.244728, 0.665241]])
        )
        assert_almost_equal(1.0, numpy.sum(vector_1d_softmaxed), decimal=6)

        vector_1d = torch.FloatTensor([[1.0, 2.0, 5.0]])
        vector_1d_softmaxed = util.masked_softmax(vector_1d, None).data.numpy()
        assert_array_almost_equal(vector_1d_softmaxed, numpy.array([[0.017148, 0.046613, 0.93624]]))

        # Testing the unmasked 1D case where the input is all 0s.
        vector_zero = torch.FloatTensor([[0.0, 0.0, 0.0]])
        vector_zero_softmaxed = util.masked_softmax(vector_zero, None).data.numpy()
        assert_array_almost_equal(
            vector_zero_softmaxed, numpy.array([[0.33333334, 0.33333334, 0.33333334]])
        )

        # Testing the general unmasked batched case.
        matrix = torch.FloatTensor([[1.0, 2.0, 5.0], [1.0, 2.0, 3.0]])
        masked_matrix_softmaxed = util.masked_softmax(matrix, None).data.numpy()
        assert_array_almost_equal(
            masked_matrix_softmaxed,
            numpy.array(
                [[0.01714783, 0.04661262, 0.93623955], [0.09003057, 0.24472847, 0.66524096]]
            ),
        )

        # Testing the unmasked batched case where one of the inputs are all 0s.
        matrix = torch.FloatTensor([[1.0, 2.0, 5.0], [0.0, 0.0, 0.0]])
        masked_matrix_softmaxed = util.masked_softmax(matrix, None).data.numpy()
        assert_array_almost_equal(
            masked_matrix_softmaxed,
            numpy.array(
                [[0.01714783, 0.04661262, 0.93623955], [0.33333334, 0.33333334, 0.33333334]]
            ),
        ) 
Example #6
Source File: attention.py    From magnitude with MIT License 5 votes vote down vote up
def forward(self,  # pylint: disable=arguments-differ
                vector              ,
                matrix              ,
                matrix_mask               = None)                :
        similarities = self._forward_internal(vector, matrix)
        if self._normalize:
            return masked_softmax(similarities, matrix_mask)
        else:
            return similarities 
Example #7
Source File: nlvr_decoder_step.py    From magnitude with MIT License 5 votes vote down vote up
def _get_next_state_info_with_agenda(
            state                  ,
            considered_actions                 ,
            action_logits              ,
            action_mask              ):                                                   
                                                                           
        u"""
        We return a list of log probabilities and checklist states corresponding to next actions that are
        not padding. This method is applicable to the case where we do not have target action
        sequences and are relying on agendas for training.
        """
        considered_action_probs = nn_util.masked_softmax(action_logits, action_mask)
        # Mixing model scores and agenda selection probabilities to compute the probabilities of all
        # actions for the next step and the corresponding new checklists.
        # All action logprobs will keep track of logprob corresponding to each local action index
        # for each instance.
        all_action_logprobs                                           = []
        all_new_checklist_states                             = []
        for group_index, instance_info in enumerate(izip(state.score,
                                                        considered_action_probs,
                                                        state.checklist_state)):
            (instance_score, instance_probs, instance_checklist_state) = instance_info
            # We will mix the model scores with agenda selection probabilities and compute their
            # logs to fill the following list with action indices and corresponding logprobs.
            instance_action_logprobs                                 = []
            instance_new_checklist_states                       = []
            for action_index, action_prob in enumerate(instance_probs):
                # This is the actual index of the action from the original list of actions.
                action = considered_actions[group_index][action_index]
                if action == -1:
                    # Ignoring padding.
                    continue
                new_checklist_state = instance_checklist_state.update(action)  # (terminal_actions, 1)
                instance_new_checklist_states.append(new_checklist_state)
                logprob = instance_score + torch.log(action_prob + 1e-13)
                instance_action_logprobs.append((action_index, logprob))
            all_action_logprobs.append(instance_action_logprobs)
            all_new_checklist_states.append(instance_new_checklist_states)
        return all_action_logprobs, all_new_checklist_states 
Example #8
Source File: util_test.py    From magnitude with MIT License 5 votes vote down vote up
def test_masked_softmax_no_mask(self):
        # Testing the general unmasked 1D case.
        vector_1d = torch.FloatTensor([[1.0, 2.0, 3.0]])
        vector_1d_softmaxed = util.masked_softmax(vector_1d, None).data.numpy()
        assert_array_almost_equal(vector_1d_softmaxed,
                                  numpy.array([[0.090031, 0.244728, 0.665241]]))
        assert_almost_equal(1.0, numpy.sum(vector_1d_softmaxed), decimal=6)

        vector_1d = torch.FloatTensor([[1.0, 2.0, 5.0]])
        vector_1d_softmaxed = util.masked_softmax(vector_1d, None).data.numpy()
        assert_array_almost_equal(vector_1d_softmaxed,
                                  numpy.array([[0.017148, 0.046613, 0.93624]]))

        # Testing the unmasked 1D case where the input is all 0s.
        vector_zero = torch.FloatTensor([[0.0, 0.0, 0.0]])
        vector_zero_softmaxed = util.masked_softmax(vector_zero, None).data.numpy()
        assert_array_almost_equal(vector_zero_softmaxed,
                                  numpy.array([[0.33333334, 0.33333334, 0.33333334]]))

        # Testing the general unmasked batched case.
        matrix = torch.FloatTensor([[1.0, 2.0, 5.0], [1.0, 2.0, 3.0]])
        masked_matrix_softmaxed = util.masked_softmax(matrix, None).data.numpy()
        assert_array_almost_equal(masked_matrix_softmaxed,
                                  numpy.array([[0.01714783, 0.04661262, 0.93623955],
                                               [0.09003057, 0.24472847, 0.66524096]]))

        # Testing the unmasked batched case where one of the inputs are all 0s.
        matrix = torch.FloatTensor([[1.0, 2.0, 5.0], [0.0, 0.0, 0.0]])
        masked_matrix_softmaxed = util.masked_softmax(matrix, None).data.numpy()
        assert_array_almost_equal(masked_matrix_softmaxed,
                                  numpy.array([[0.01714783, 0.04661262, 0.93623955],
                                               [0.33333334, 0.33333334, 0.33333334]])) 
Example #9
Source File: expected_risk_minimization.py    From allennlp-semparse with Apache License 2.0 5 votes vote down vote up
def decode(
        self,
        initial_state: State,
        transition_function: TransitionFunction,
        supervision: Callable[[StateType], torch.Tensor],
    ) -> Dict[str, torch.Tensor]:
        cost_function = supervision
        finished_states = self._get_finished_states(initial_state, transition_function)
        loss = initial_state.score[0].new_zeros(1)
        finished_model_scores = self._get_model_scores_by_batch(finished_states)
        finished_costs = self._get_costs_by_batch(finished_states, cost_function)
        for batch_index in finished_model_scores:
            # Finished model scores are log-probabilities of the predicted sequences. We convert
            # log probabilities into probabilities and re-normalize them to compute expected cost under
            # the distribution approximated by the beam search.

            costs = torch.cat([tensor.view(-1) for tensor in finished_costs[batch_index]])
            logprobs = torch.cat([tensor.view(-1) for tensor in finished_model_scores[batch_index]])
            # Unmasked softmax of log probabilities will convert them into probabilities and
            # renormalize them.
            renormalized_probs = nn_util.masked_softmax(logprobs, None)
            loss += renormalized_probs.dot(costs)
        mean_loss = loss / len(finished_model_scores)
        return {
            "loss": mean_loss,
            "best_final_states": self._get_best_final_states(finished_states),
        } 
Example #10
Source File: bahdanau_attention.py    From summarus with Apache License 2.0 5 votes vote down vote up
def forward(self,
                vector: torch.Tensor,
                matrix: torch.Tensor,
                matrix_mask: torch.Tensor = None,
                coverage: torch.Tensor = None) -> torch.Tensor:
        similarities = self._forward_internal(vector, matrix, coverage)
        if self._normalize:
            return masked_softmax(similarities, matrix_mask)
        else:
            return similarities 
Example #11
Source File: pointer_network.py    From R-net with MIT License 5 votes vote down vote up
def _question_pooling(self, question, question_mask):
        V_q = self.V_q.expand(question.size(0), question.size(1), -1)
        logits = self.question_linear(torch.cat([question, V_q], dim=-1)).squeeze(-1)
        score = masked_softmax(logits, question_mask, dim=0)
        state = torch.sum(score.unsqueeze(-1) * question, dim=0)
        return state 
Example #12
Source File: pointer_network.py    From R-net with MIT License 5 votes vote down vote up
def _passage_attention(self, passage, passage_mask, state):
        state_expand = state.unsqueeze(0).expand(passage.size(0), -1, -1)
        logits = self.passage_linear(torch.cat([passage, state_expand], dim=-1)).squeeze(-1)
        score = masked_softmax(logits, passage_mask, dim=0)
        cell_input = torch.sum(score.unsqueeze(-1) * passage, dim=0)
        return cell_input, logits 
Example #13
Source File: cells.py    From R-net with MIT License 5 votes vote down vote up
def forward(self, inputs: Tensor, memory: Tensor = None, memory_mask: Tensor = None, state: Tensor = None):
        """
        :param inputs:  B x H
        :param memory: T x B x H if not batch_first
        :param memory_mask: T x B if not batch_first
        :param state: B x H
        :return:
        """
        if self.batch_first:
            memory = memory.transpose(0, 1)
            memory_mask = memory_mask.transpose(0, 1)

        assert inputs.size(0) == memory.size(1) == memory_mask.size(
            1), "inputs batch size does not match memory batch size"

        memory_time_length = memory.size(0)

        if state is None:
            state = inputs.new_zeros(inputs.size(0), self.cell.hidden_size, requires_grad=False)

        if self.use_state:
            hx = state
            if isinstance(state, tuple):
                hx = state[0]
            attention_input = torch.cat([inputs, hx], dim=-1)
            attention_input = attention_input.unsqueeze(0).expand(memory_time_length, -1, -1)  # T B H
        else:
            attention_input = inputs.unsqueeze(0).expand(memory_time_length, -1, -1)

        attention_logits = self.attention_w(torch.cat([attention_input, memory], dim=-1)).squeeze(-1)

        attention_scores = masked_softmax(attention_logits, memory_mask, dim=0)

        attention_vector = torch.sum(attention_scores.unsqueeze(-1) * memory, dim=0)

        new_input = torch.cat([inputs, attention_vector], dim=-1)

        return self.cell(new_input, state) 
Example #14
Source File: prostruct_model.py    From propara with Apache License 2.0 4 votes vote down vote up
def compute_location_spans(self, contextual_seq_embedding, embedded_sentence_verb_entity, mask):
        # # ===============================================================test============================================
        # # Layer 5: Span prediction for before and after location
        # Shape: (batch_size, passage_length, encoding_dim * 4 + modeling_dim))
        batch_size, num_sentences, num_participants, sentence_length, encoder_dim = contextual_seq_embedding.shape
        #print("contextual_seq_embedding: ", contextual_seq_embedding.shape)
        # size(span_start_input_after): batch_size * num_sentences *
        #                                num_participants * sentence_length * (embedding_size+2+2*seq2seq_output_size)
        span_start_input_after = torch.cat([embedded_sentence_verb_entity, contextual_seq_embedding], dim=-1)

        #print("span_start_input_after: ", span_start_input_after.shape)
        # Shape: (bs, ns , np, sl)
        span_start_logits_after = self._span_start_predictor_after(span_start_input_after).squeeze(-1)
        #print("span_start_logits_after: ", span_start_logits_after.shape)

        # Shape: (bs, ns , np, sl)
        span_start_probs_after = util.masked_softmax(span_start_logits_after, mask)
        #print("span_start_probs_after: ", span_start_probs_after.shape)

        # span_start_representation_after: (bs, ns , np, encoder_dim)
        span_start_representation_after = util.weighted_sum(contextual_seq_embedding, span_start_probs_after)
        #print("span_start_representation_after: ", span_start_representation_after.shape)

        # span_tiled_start_representation_after: (bs, ns , np, sl, 2*seq2seq_output_size)
        span_tiled_start_representation_after = span_start_representation_after.unsqueeze(3).expand(batch_size,
                                                                                                    num_sentences,
                                                                                                    num_participants,
                                                                                                    sentence_length,
                                                                                                    encoder_dim)
        #print("span_tiled_start_representation_after: ", span_tiled_start_representation_after.shape)

        # Shape: (batch_size, passage_length, (embedding+2  + encoder_dim + encoder_dim + encoder_dim))
        span_end_representation_after = torch.cat([embedded_sentence_verb_entity,
                                                   contextual_seq_embedding,
                                                   span_tiled_start_representation_after,
                                                   contextual_seq_embedding * span_tiled_start_representation_after],
                                                  dim=-1)
        #print("span_end_representation_after: ", span_end_representation_after.shape)

        # Shape: (batch_size, passage_length, encoding_dim)
        encoded_span_end_after = self.time_distributed_encoder_span_end_after(span_end_representation_after, mask)
        #print("encoded_span_end_after: ", encoded_span_end_after.shape)

        span_end_logits_after = self._span_end_predictor_after(encoded_span_end_after).squeeze(-1)
        #print("span_end_logits_after: ", span_end_logits_after.shape)

        span_end_probs_after = util.masked_softmax(span_end_logits_after, mask)
        #print("span_end_probs_after: ", span_end_probs_after.shape)

        span_start_logits_after = util.replace_masked_values(span_start_logits_after, mask, -1e7)
        span_end_logits_after = util.replace_masked_values(span_end_logits_after, mask, -1e7)

        # Fixme: we should condition this on predicted_action so that we can output '-' when needed
        # Fixme: also add a functionality to be able to output '?': we can use span_start_probs_after, span_end_probs_after
        best_span_after = self.get_best_span(span_start_logits_after, span_end_logits_after)
        #print("best_span_after: ", best_span_after)
        return best_span_after, span_start_logits_after, span_end_logits_after