def from_params(cls,params: Params, vocab: Vocabulary) -> 'Embedding': # type: ignore cuda_device = params.pop("cuda_device",-1) use_glove_embedding = params.pop("use_glove_embedding", False) #glove_dimension_size = params.pop("glove_dimension_size",300) use_elmo_embedding = params.pop("use_elmo_embedding", False) use_verb_index_embedding = params.pop("use_verb_index_embedding",False) verb_index_embedding_dimension = params.pop("verb_index_embedding_dimension",50) use_visual_score_embedding = params.pop("use_visual_score_embedding",False) num_embeddings = vocab.get_vocab_size() #0 = padding, 1 = unknow, the rest is vocabulary embedding_dim = 0 # test if to use elmo embedding if use_elmo_embedding: elmo_token_embedder = Elmo.from_params(params.pop("elmo")) embedding_dim = embedding_dim + elmo_token_embedder.get_output_dim() # current dimension for elmo embedding - 512*2 = 1024 else: elmo_token_embedder = None if use_glove_embedding: # glove_embeddings an Embeddings with dimension of 300 #glove_embedder = get_glove_embedder(num_embeddings,glove_dimension_size,vocab) glove_embedder = Embedding.from_params(vocab, params.pop("glove_embedder")) embedding_dim = embedding_dim + glove_embedder.get_output_dim() else: glove_embedder = None if use_verb_index_embedding: # suffix_embeddings: need two elements for 0 (non-metaphore) and 1 (is metaphore) verb_index_embedder = Embedding(2, verb_index_embedding_dimension) embedding_dim = embedding_dim + verb_index_embedder.get_output_dim() # for suffix embedding else: verb_index_embedder = None if use_visual_score_embedding: # use pretrained weight matrix visual_score_embedder = Embedding.from_params(vocab, params.pop("visual_embedder")) embedding_dim = embedding_dim + visual_score_embedder.get_output_dim() else: visual_score_embedder = None if cuda_device == -1: is_gpu = False else: is_gpu = True return cls(num_embeddings=num_embeddings,embedding_dim=embedding_dim, glove_embedder=glove_embedder, elmo_embedder=elmo_token_embedder, verb_index_embedder=verb_index_embedder, visual_score_embedder=visual_score_embedder,is_gpu=is_gpu)
class BidirectionalEndpointSpanExtractor(SpanExtractor): """ Represents spans from a bidirectional encoder as a concatenation of two different representations of the span endpoints, one for the forward direction of the encoder and one from the backward direction. This type of representation encodes some subtelty, because when you consider the forward and backward directions separately, the end index of the span for the backward direction's representation is actually the start index. By default, this ``SpanExtractor`` represents spans as ``sequence_tensor[inclusive_span_end] - sequence_tensor[exclusive_span_start]`` meaning that the representation is the difference between the the last word in the span and the word `before` the span started. Note that the start and end indices are with respect to the direction that the RNN is going in, so for the backward direction, the start/end indices are reversed. Additionally, the width of the spans can be embedded and concatenated on to the final combination. The following other types of representation are supported for both the forward and backward directions, assuming that ``x = span_start_embeddings`` and ``y = span_end_embeddings``. ``x``, ``y``, ``x*y``, ``x+y``, ``x-y``, ``x/y``, where each of those binary operations is performed elementwise. You can list as many combinations as you want, comma separated. For example, you might give ``x,y,x*y`` as the ``combination`` parameter to this class. The computed similarity function would then be ``[x; y; x*y]``, which can then be optionally concatenated with an embedded representation of the width of the span. Parameters ---------- input_dim : ``int``, required. The final dimension of the ``sequence_tensor``. forward_combination : str, optional (default = "y-x"). The method used to combine the ``forward_start_embeddings`` and ``forward_end_embeddings`` for the forward direction of the bidirectional representation. See above for a full description. backward_combination : str, optional (default = "y-x"). The method used to combine the ``backward_start_embeddings`` and ``backward_end_embeddings`` for the backward direction of the bidirectional representation. See above for a full description. num_width_embeddings : ``int``, optional (default = None). Specifies the number of buckets to use when representing span width features. span_width_embedding_dim : ``int``, optional (default = None). The embedding size for the span_width features. bucket_widths : ``bool``, optional (default = False). Whether to bucket the span widths into log-space buckets. If ``False``, the raw span widths are used. use_sentinels : ``bool``, optional (default = ``True``). If ``True``, sentinels are used to represent exclusive span indices for the elements in the first and last positions in the sequence (as the exclusive indices for these elements are outside of the the sequence boundary). This is not strictly necessary, as you may know that your exclusive start and end indices are always within your sequence representation, such as if you have appended/prepended <START> and <END> tokens to your sequence. """ def __init__(self, input_dim: int, forward_combination: str = "y-x", backward_combination: str = "y-x", num_width_embeddings: int = None, span_width_embedding_dim: int = None, bucket_widths: bool = False, use_sentinels: bool = True) -> None: super().__init__() self._input_dim = input_dim self._forward_combination = forward_combination self._backward_combination = backward_combination self._num_width_embeddings = num_width_embeddings self._bucket_widths = bucket_widths if self._input_dim % 2 != 0: raise ConfigurationError( "The input dimension is not divisible by 2, but the " "BidirectionalEndpointSpanExtractor assumes the embedded representation " "is bidirectional (and hence divisible by 2).") if num_width_embeddings is not None and span_width_embedding_dim is not None: self._span_width_embedding = Embedding(num_width_embeddings, span_width_embedding_dim) elif not all( [num_width_embeddings is None, span_width_embedding_dim is None]): raise ConfigurationError( "To use a span width embedding representation, you must" "specify both num_width_buckets and span_width_embedding_dim.") else: self._span_width_embedding = None self._use_sentinels = use_sentinels if use_sentinels: self._start_sentinel = Parameter( torch.randn([1, 1, int(input_dim / 2)])) self._end_sentinel = Parameter( torch.randn([1, 1, int(input_dim / 2)])) def get_input_dim(self) -> int: return self._input_dim def get_output_dim(self) -> int: unidirectional_dim = int(self._input_dim / 2) forward_combined_dim = util.get_combined_dim( self._forward_combination, [unidirectional_dim, unidirectional_dim]) backward_combined_dim = util.get_combined_dim( self._backward_combination, [unidirectional_dim, unidirectional_dim]) if self._span_width_embedding is not None: return forward_combined_dim + backward_combined_dim + \ self._span_width_embedding.get_output_dim() return forward_combined_dim + backward_combined_dim @overrides def forward( self, sequence_tensor: torch.FloatTensor, span_indices: torch.LongTensor, sequence_mask: torch.LongTensor = None, span_indices_mask: torch.LongTensor = None) -> torch.FloatTensor: # Both of shape (batch_size, sequence_length, embedding_size / 2) forward_sequence, backward_sequence = sequence_tensor.split(int( self._input_dim / 2), dim=-1) forward_sequence = forward_sequence.contiguous() backward_sequence = backward_sequence.contiguous() # shape (batch_size, num_spans) span_starts, span_ends = [ index.squeeze(-1) for index in span_indices.split(1, dim=-1) ] if span_indices_mask is not None: span_starts = span_starts * span_indices_mask span_ends = span_ends * span_indices_mask # We want `exclusive` span starts, so we remove 1 from the forward span starts # as the AllenNLP ``SpanField`` is inclusive. # shape (batch_size, num_spans) exclusive_span_starts = span_starts - 1 # shape (batch_size, num_spans, 1) start_sentinel_mask = ( exclusive_span_starts == -1).long().unsqueeze(-1) # We want `exclusive` span ends for the backward direction # (so that the `start` of the span in that direction is exlusive), so # we add 1 to the span ends as the AllenNLP ``SpanField`` is inclusive. exclusive_span_ends = span_ends + 1 if sequence_mask is not None: # shape (batch_size) sequence_lengths = util.get_lengths_from_binary_sequence_mask( sequence_mask) else: # shape (batch_size), filled with the sequence length size of the sequence_tensor. sequence_lengths = util.ones_like( sequence_tensor[:, 0, 0]).long() * sequence_tensor.size(1) # shape (batch_size, num_spans, 1) end_sentinel_mask = (exclusive_span_ends == sequence_lengths.unsqueeze( -1)).long().unsqueeze(-1) # As we added 1 to the span_ends to make them exclusive, which might have caused indices # equal to the sequence_length to become out of bounds, we multiply by the inverse of the # end_sentinel mask to erase these indices (as we will replace them anyway in the block below). # The same argument follows for the exclusive span start indices. exclusive_span_ends = exclusive_span_ends * ( 1 - end_sentinel_mask.squeeze(-1)) exclusive_span_starts = exclusive_span_starts * ( 1 - start_sentinel_mask.squeeze(-1)) # We'll check the indices here at runtime, because it's difficult to debug # if this goes wrong and it's tricky to get right. if (exclusive_span_starts < 0).any() or ( exclusive_span_ends > sequence_lengths.unsqueeze(-1)).any(): raise ValueError( f"Adjusted span indices must lie inside the length of the sequence tensor, " f"but found: exclusive_span_starts: {exclusive_span_starts}, " f"exclusive_span_ends: {exclusive_span_ends} for a sequence tensor with lengths " f"{sequence_lengths}.") # Forward Direction: start indices are exclusive. Shape (batch_size, num_spans, input_size / 2) forward_start_embeddings = util.batched_index_select( forward_sequence, exclusive_span_starts) # Forward Direction: end indices are inclusive, so we can just use span_ends. # Shape (batch_size, num_spans, input_size / 2) forward_end_embeddings = util.batched_index_select( forward_sequence, span_ends) # Backward Direction: The backward start embeddings use the `forward` end # indices, because we are going backwards. # Shape (batch_size, num_spans, input_size / 2) backward_start_embeddings = util.batched_index_select( backward_sequence, exclusive_span_ends) # Backward Direction: The backward end embeddings use the `forward` start # indices, because we are going backwards. # Shape (batch_size, num_spans, input_size / 2) backward_end_embeddings = util.batched_index_select( backward_sequence, span_starts) if self._use_sentinels: # If we're using sentinels, we need to replace all the elements which were # outside the dimensions of the sequence_tensor with either the start sentinel, # or the end sentinel. float_end_sentinel_mask = end_sentinel_mask.float() float_start_sentinel_mask = start_sentinel_mask.float() forward_start_embeddings = forward_start_embeddings * (1 - float_start_sentinel_mask) \ + float_start_sentinel_mask * self._start_sentinel backward_start_embeddings = backward_start_embeddings * (1 - float_end_sentinel_mask) \ + float_end_sentinel_mask * self._end_sentinel # Now we combine the forward and backward spans in the manner specified by the # respective combinations and concatenate these representations. # Shape (batch_size, num_spans, forward_combination_dim) forward_spans = util.combine_tensors( self._forward_combination, [forward_start_embeddings, forward_end_embeddings]) # Shape (batch_size, num_spans, backward_combination_dim) backward_spans = util.combine_tensors( self._backward_combination, [backward_start_embeddings, backward_end_embeddings]) # Shape (batch_size, num_spans, forward_combination_dim + backward_combination_dim) span_embeddings = torch.cat([forward_spans, backward_spans], -1) if self._span_width_embedding is not None: # Embed the span widths and concatenate to the rest of the representations. if self._bucket_widths: span_widths = util.bucket_values( span_ends - span_starts, num_total_buckets=self._num_width_embeddings) else: span_widths = span_ends - span_starts span_width_embeddings = self._span_width_embedding(span_widths) return torch.cat([span_embeddings, span_width_embeddings], -1) if span_indices_mask is not None: return span_embeddings * span_indices_mask.float().unsqueeze(-1) return span_embeddings @classmethod def from_params(cls, params: Params) -> "BidirectionalEndpointSpanExtractor": input_dim = params.pop_int("input_dim") forward_combination = params.pop("forward_combination", "y-x") backward_combination = params.pop("backward_combination", "x-y") num_width_embeddings = params.pop_int("num_width_embeddings", None) span_width_embedding_dim = params.pop_int("span_width_embedding_dim", None) bucket_widths = params.pop_bool("bucket_widths", False) use_sentinels = params.pop_bool("use_sentinels", True) return BidirectionalEndpointSpanExtractor( input_dim=input_dim, forward_combination=forward_combination, backward_combination=backward_combination, num_width_embeddings=num_width_embeddings, span_width_embedding_dim=span_width_embedding_dim, bucket_widths=bucket_widths, use_sentinels=use_sentinels)
class EndpointSpanExtractor(SpanExtractor): """ Represents spans as a combination of the embeddings of their endpoints. Additionally, the width of the spans can be embedded and concatenated on to the final combination. The following types of representation are supported, assuming that `x = span_start_embeddings` and `y = span_end_embeddings`. `x`, `y`, `x*y`, `x+y`, `x-y`, `x/y`, where each of those binary operations is performed elementwise. You can list as many combinations as you want, comma separated. For example, you might give `x,y,x*y` as the `combination` parameter to this class. The computed similarity function would then be `[x; y; x*y]`, which can then be optionally concatenated with an embedded representation of the width of the span. # Parameters input_dim : `int`, required. The final dimension of the `sequence_tensor`. combination : `str`, optional (default = "x,y"). The method used to combine the `start_embedding` and `end_embedding` representations. See above for a full description. num_width_embeddings : `int`, optional (default = None). Specifies the number of buckets to use when representing span width features. span_width_embedding_dim : `int`, optional (default = None). The embedding size for the span_width features. bucket_widths : `bool`, optional (default = False). Whether to bucket the span widths into log-space buckets. If `False`, the raw span widths are used. use_exclusive_start_indices : `bool`, optional (default = `False`). If `True`, the start indices extracted are converted to exclusive indices. Sentinels are used to represent exclusive span indices for the elements in the first position in the sequence (as the exclusive indices for these elements are outside of the the sequence boundary) so that start indices can be exclusive. NOTE: This option can be helpful to avoid the pathological case in which you want span differences for length 1 spans - if you use inclusive indices, you will end up with an `x - x` operation for length 1 spans, which is not good. """ def __init__( self, input_dim: int, combination: str = "x,y", num_width_embeddings: int = None, span_width_embedding_dim: int = None, bucket_widths: bool = False, use_exclusive_start_indices: bool = False, ) -> None: super().__init__() self._input_dim = input_dim self._combination = combination self._num_width_embeddings = num_width_embeddings self._bucket_widths = bucket_widths self._use_exclusive_start_indices = use_exclusive_start_indices if use_exclusive_start_indices: self._start_sentinel = Parameter( torch.randn([1, 1, int(input_dim)])) if num_width_embeddings is not None and span_width_embedding_dim is not None: self._span_width_embedding = Embedding(num_width_embeddings, span_width_embedding_dim) elif not all( [num_width_embeddings is None, span_width_embedding_dim is None]): raise ConfigurationError( "To use a span width embedding representation, you must" "specify both num_width_buckets and span_width_embedding_dim.") else: self._span_width_embedding = None def get_input_dim(self) -> int: return self._input_dim def get_output_dim(self) -> int: combined_dim = util.get_combined_dim( self._combination, [self._input_dim, self._input_dim]) if self._span_width_embedding is not None: return combined_dim + self._span_width_embedding.get_output_dim() return combined_dim @overrides def forward( self, sequence_tensor: torch.FloatTensor, span_indices: torch.LongTensor, sequence_mask: torch.LongTensor = None, span_indices_mask: torch.LongTensor = None, ) -> None: # shape (batch_size, num_spans) span_starts, span_ends = [ index.squeeze(-1) for index in span_indices.split(1, dim=-1) ] if span_indices_mask is not None: # It's not strictly necessary to multiply the span indices by the mask here, # but it's possible that the span representation was padded with something other # than 0 (such as -1, which would be an invalid index), so we do so anyway to # be safe. span_starts = span_starts * span_indices_mask span_ends = span_ends * span_indices_mask if not self._use_exclusive_start_indices: if sequence_tensor.size(-1) != self._input_dim: raise ValueError( f"Dimension mismatch expected ({sequence_tensor.size(-1)}) " f"received ({self._input_dim}).") start_embeddings = util.batched_index_select( sequence_tensor, span_starts) end_embeddings = util.batched_index_select(sequence_tensor, span_ends) else: # We want `exclusive` span starts, so we remove 1 from the forward span starts # as the AllenNLP `SpanField` is inclusive. # shape (batch_size, num_spans) exclusive_span_starts = span_starts - 1 # shape (batch_size, num_spans, 1) start_sentinel_mask = ( exclusive_span_starts == -1).long().unsqueeze(-1) exclusive_span_starts = exclusive_span_starts * ( 1 - start_sentinel_mask.squeeze(-1)) # We'll check the indices here at runtime, because it's difficult to debug # if this goes wrong and it's tricky to get right. if (exclusive_span_starts < 0).any(): raise ValueError( f"Adjusted span indices must lie inside the the sequence tensor, " f"but found: exclusive_span_starts: {exclusive_span_starts}." ) start_embeddings = util.batched_index_select( sequence_tensor, exclusive_span_starts) end_embeddings = util.batched_index_select(sequence_tensor, span_ends) # We're using sentinels, so we need to replace all the elements which were # outside the dimensions of the sequence_tensor with the start sentinel. float_start_sentinel_mask = start_sentinel_mask.float() start_embeddings = ( start_embeddings * (1 - float_start_sentinel_mask) + float_start_sentinel_mask * self._start_sentinel) combined_tensors = util.combine_tensors( self._combination, [start_embeddings, end_embeddings]) if self._span_width_embedding is not None: # Embed the span widths and concatenate to the rest of the representations. if self._bucket_widths: span_widths = util.bucket_values( span_ends - span_starts, num_total_buckets=self._num_width_embeddings) else: span_widths = span_ends - span_starts span_width_embeddings = self._span_width_embedding(span_widths) combined_tensors = torch.cat( [combined_tensors, span_width_embeddings], -1) if span_indices_mask is not None: return combined_tensors * span_indices_mask.unsqueeze(-1).float() return combined_tensors
class BidirectionalEndpointSpanExtractor(SpanExtractor): """ Represents spans from a bidirectional encoder as a concatenation of two different representations of the span endpoints, one for the forward direction of the encoder and one from the backward direction. This type of representation encodes some subtelty, because when you consider the forward and backward directions separately, the end index of the span for the backward direction's representation is actually the start index. By default, this ``SpanExtractor`` represents spans as ``sequence_tensor[inclusive_span_end] - sequence_tensor[exclusive_span_start]`` meaning that the representation is the difference between the the last word in the span and the word `before` the span started. Note that the start and end indices are with respect to the direction that the RNN is going in, so for the backward direction, the start/end indices are reversed. Additionally, the width of the spans can be embedded and concatenated on to the final combination. The following other types of representation are supported for both the forward and backward directions, assuming that ``x = span_start_embeddings`` and ``y = span_end_embeddings``. ``x``, ``y``, ``x*y``, ``x+y``, ``x-y``, ``x/y``, where each of those binary operations is performed elementwise. You can list as many combinations as you want, comma separated. For example, you might give ``x,y,x*y`` as the ``combination`` parameter to this class. The computed similarity function would then be ``[x; y; x*y]``, which can then be optionally concatenated with an embedded representation of the width of the span. Parameters ---------- input_dim : ``int``, required. The final dimension of the ``sequence_tensor``. forward_combination : str, optional (default = "y-x"). The method used to combine the ``forward_start_embeddings`` and ``forward_end_embeddings`` for the forward direction of the bidirectional representation. See above for a full description. backward_combination : str, optional (default = "y-x"). The method used to combine the ``backward_start_embeddings`` and ``backward_end_embeddings`` for the backward direction of the bidirectional representation. See above for a full description. num_width_embeddings : ``int``, optional (default = None). Specifies the number of buckets to use when representing span width features. span_width_embedding_dim : ``int``, optional (default = None). The embedding size for the span_width features. bucket_widths : ``bool``, optional (default = False). Whether to bucket the span widths into log-space buckets. If ``False``, the raw span widths are used. use_sentinels : ``bool``, optional (default = ``True``). If ``True``, sentinels are used to represent exclusive span indices for the elements in the first and last positions in the sequence (as the exclusive indices for these elements are outside of the the sequence boundary). This is not strictly necessary, as you may know that your exclusive start and end indices are always within your sequence representation, such as if you have appended/prepended <START> and <END> tokens to your sequence. """ def __init__(self, input_dim: int, forward_combination: str = "y-x", backward_combination: str = "y-x", num_width_embeddings: int = None, span_width_embedding_dim: int = None, bucket_widths: bool = False, use_sentinels: bool = True) -> None: super().__init__() self._input_dim = input_dim self._forward_combination = forward_combination self._backward_combination = backward_combination self._num_width_embeddings = num_width_embeddings self._bucket_widths = bucket_widths if self._input_dim % 2 != 0: raise ConfigurationError("The input dimension is not divisible by 2, but the " "BidirectionalEndpointSpanExtractor assumes the embedded representation " "is bidirectional (and hence divisible by 2).") if num_width_embeddings is not None and span_width_embedding_dim is not None: self._span_width_embedding = Embedding(num_width_embeddings, span_width_embedding_dim) elif not all([num_width_embeddings is None, span_width_embedding_dim is None]): raise ConfigurationError("To use a span width embedding representation, you must" "specify both num_width_buckets and span_width_embedding_dim.") else: self._span_width_embedding = None self._use_sentinels = use_sentinels if use_sentinels: self._start_sentinel = Parameter(torch.randn([1, 1, int(input_dim / 2)])) self._end_sentinel = Parameter(torch.randn([1, 1, int(input_dim / 2)])) def get_input_dim(self) -> int: return self._input_dim def get_output_dim(self) -> int: unidirectional_dim = int(self._input_dim / 2) forward_combined_dim = util.get_combined_dim(self._forward_combination, [unidirectional_dim, unidirectional_dim]) backward_combined_dim = util.get_combined_dim(self._backward_combination, [unidirectional_dim, unidirectional_dim]) if self._span_width_embedding is not None: return forward_combined_dim + backward_combined_dim + \ self._span_width_embedding.get_output_dim() return forward_combined_dim + backward_combined_dim @overrides def forward(self, sequence_tensor: torch.FloatTensor, span_indices: torch.LongTensor, sequence_mask: torch.LongTensor = None, span_indices_mask: torch.LongTensor = None) -> torch.FloatTensor: # Both of shape (batch_size, sequence_length, embedding_size / 2) forward_sequence, backward_sequence = sequence_tensor.split(int(self._input_dim / 2), dim=-1) forward_sequence = forward_sequence.contiguous() backward_sequence = backward_sequence.contiguous() # shape (batch_size, num_spans) span_starts, span_ends = [index.squeeze(-1) for index in span_indices.split(1, dim=-1)] if span_indices_mask is not None: span_starts = span_starts * span_indices_mask span_ends = span_ends * span_indices_mask # We want `exclusive` span starts, so we remove 1 from the forward span starts # as the AllenNLP ``SpanField`` is inclusive. # shape (batch_size, num_spans) exclusive_span_starts = span_starts - 1 # shape (batch_size, num_spans, 1) start_sentinel_mask = (exclusive_span_starts == -1).long().unsqueeze(-1) # We want `exclusive` span ends for the backward direction # (so that the `start` of the span in that direction is exlusive), so # we add 1 to the span ends as the AllenNLP ``SpanField`` is inclusive. exclusive_span_ends = span_ends + 1 if sequence_mask is not None: # shape (batch_size) sequence_lengths = util.get_lengths_from_binary_sequence_mask(sequence_mask) else: # shape (batch_size), filled with the sequence length size of the sequence_tensor. sequence_lengths = util.ones_like(sequence_tensor[:, 0, 0]).long() * sequence_tensor.size(1) # shape (batch_size, num_spans, 1) end_sentinel_mask = (exclusive_span_ends == sequence_lengths.unsqueeze(-1)).long().unsqueeze(-1) # As we added 1 to the span_ends to make them exclusive, which might have caused indices # equal to the sequence_length to become out of bounds, we multiply by the inverse of the # end_sentinel mask to erase these indices (as we will replace them anyway in the block below). # The same argument follows for the exclusive span start indices. exclusive_span_ends = exclusive_span_ends * (1 - end_sentinel_mask.squeeze(-1)) exclusive_span_starts = exclusive_span_starts * (1 - start_sentinel_mask.squeeze(-1)) # We'll check the indices here at runtime, because it's difficult to debug # if this goes wrong and it's tricky to get right. if (exclusive_span_starts < 0).any() or (exclusive_span_ends > sequence_lengths.unsqueeze(-1)).any(): raise ValueError(f"Adjusted span indices must lie inside the length of the sequence tensor, " f"but found: exclusive_span_starts: {exclusive_span_starts}, " f"exclusive_span_ends: {exclusive_span_ends} for a sequence tensor with lengths " f"{sequence_lengths}.") # Forward Direction: start indices are exclusive. Shape (batch_size, num_spans, input_size / 2) forward_start_embeddings = util.batched_index_select(forward_sequence, exclusive_span_starts) # Forward Direction: end indices are inclusive, so we can just use span_ends. # Shape (batch_size, num_spans, input_size / 2) forward_end_embeddings = util.batched_index_select(forward_sequence, span_ends) # Backward Direction: The backward start embeddings use the `forward` end # indices, because we are going backwards. # Shape (batch_size, num_spans, input_size / 2) backward_start_embeddings = util.batched_index_select(backward_sequence, exclusive_span_ends) # Backward Direction: The backward end embeddings use the `forward` start # indices, because we are going backwards. # Shape (batch_size, num_spans, input_size / 2) backward_end_embeddings = util.batched_index_select(backward_sequence, span_starts) if self._use_sentinels: # If we're using sentinels, we need to replace all the elements which were # outside the dimensions of the sequence_tensor with either the start sentinel, # or the end sentinel. float_end_sentinel_mask = end_sentinel_mask.float() float_start_sentinel_mask = start_sentinel_mask.float() forward_start_embeddings = forward_start_embeddings * (1 - float_start_sentinel_mask) \ + float_start_sentinel_mask * self._start_sentinel backward_start_embeddings = backward_start_embeddings * (1 - float_end_sentinel_mask) \ + float_end_sentinel_mask * self._end_sentinel # Now we combine the forward and backward spans in the manner specified by the # respective combinations and concatenate these representations. # Shape (batch_size, num_spans, forward_combination_dim) forward_spans = util.combine_tensors(self._forward_combination, [forward_start_embeddings, forward_end_embeddings]) # Shape (batch_size, num_spans, backward_combination_dim) backward_spans = util.combine_tensors(self._backward_combination, [backward_start_embeddings, backward_end_embeddings]) # Shape (batch_size, num_spans, forward_combination_dim + backward_combination_dim) span_embeddings = torch.cat([forward_spans, backward_spans], -1) if self._span_width_embedding is not None: # Embed the span widths and concatenate to the rest of the representations. if self._bucket_widths: span_widths = util.bucket_values(span_ends - span_starts, num_total_buckets=self._num_width_embeddings) else: span_widths = span_ends - span_starts span_width_embeddings = self._span_width_embedding(span_widths) return torch.cat([span_embeddings, span_width_embeddings], -1) if span_indices_mask is not None: return span_embeddings * span_indices_mask.float().unsqueeze(-1) return span_embeddings @classmethod def from_params(cls, params: Params) -> "BidirectionalEndpointSpanExtractor": input_dim = params.pop_int("input_dim") forward_combination = params.pop("forward_combination", "y-x") backward_combination = params.pop("backward_combination", "x-y") num_width_embeddings = params.pop_int("num_width_embeddings", None) span_width_embedding_dim = params.pop_int("span_width_embedding_dim", None) bucket_widths = params.pop_bool("bucket_widths", False) use_sentinels = params.pop_bool("use_sentinels", True) return BidirectionalEndpointSpanExtractor(input_dim=input_dim, forward_combination=forward_combination, backward_combination=backward_combination, num_width_embeddings=num_width_embeddings, span_width_embedding_dim=span_width_embedding_dim, bucket_widths=bucket_widths, use_sentinels=use_sentinels)
class EndpointSpanExtractor(SpanExtractor): """ Represents spans as a combination of the embeddings of their endpoints. Additionally, the width of the spans can be embedded and concatenated on to the final combination. The following types of representation are supported, assuming that ``x = span_start_embeddings`` and ``y = span_end_embeddings``. ``x``, ``y``, ``x*y``, ``x+y``, ``x-y``, ``x/y``, where each of those binary operations is performed elementwise. You can list as many combinations as you want, comma separated. For example, you might give ``x,y,x*y`` as the ``combination`` parameter to this class. The computed similarity function would then be ``[x; y; x*y]``, which can then be optionally concatenated with an embedded representation of the width of the span. Parameters ---------- input_dim : ``int``, required. The final dimension of the ``sequence_tensor``. combination : str, optional (default = "x-y"). The method used to combine the ``start_embedding`` and ``end_embedding`` representations. See above for a full description. num_width_embeddings : ``int``, optional (default = None). Specifies the number of buckets to use when representing span width features. span_width_embedding_dim : ``int``, optional (default = None). The embedding size for the span_width features. bucket_widths : ``bool``, optional (default = False). Whether to bucket the span widths into log-space buckets. If ``False``, the raw span widths are used. """ def __init__(self, input_dim: int, combination: str = "x-y", num_width_embeddings: int = None, span_width_embedding_dim: int = None, bucket_widths: bool = False) -> None: super().__init__() self._input_dim = input_dim self._combination = combination self._num_width_embeddings = num_width_embeddings self._bucket_widths = bucket_widths if num_width_embeddings is not None and span_width_embedding_dim is not None: self._span_width_embedding = Embedding(num_width_embeddings, span_width_embedding_dim) elif not all( [num_width_embeddings is None, span_width_embedding_dim is None]): raise ConfigurationError( "To use a span width embedding representation, you must" "specify both num_width_buckets and span_width_embedding_dim.") else: self._span_width_embedding = None def get_input_dim(self) -> int: return self._input_dim def get_output_dim(self) -> int: combined_dim = get_combined_dim(self._combination, [self._input_dim, self._input_dim]) if self._span_width_embedding is not None: return combined_dim + self._span_width_embedding.get_output_dim() return combined_dim @overrides def forward(self, sequence_tensor: torch.FloatTensor, span_indices: torch.LongTensor, sequence_mask: torch.LongTensor = None, span_indices_mask: torch.LongTensor = None) -> None: # shape (batch_size, num_spans) span_starts, span_ends = [ index.squeeze(-1) for index in span_indices.split(1, dim=-1) ] if span_indices_mask is not None: # It's not strictly necessary to multiply the span indices by the mask here, # but it's possible that the span representation was padded with something other # than 0 (such as -1, which would be an invalid index), so we do so anyway to # be safe. span_starts = span_starts * span_indices_mask span_ends = span_ends * span_indices_mask start_embeddings = batched_index_select(sequence_tensor, span_starts) end_embeddings = batched_index_select(sequence_tensor, span_ends) combined_tensors = combine_tensors(self._combination, [start_embeddings, end_embeddings]) if self._span_width_embedding is not None: # Embed the span widths and concatenate to the rest of the representations. if self._bucket_widths: span_widths = bucket_values( span_ends - span_starts, num_total_buckets=self._num_width_embeddings) else: span_widths = span_ends - span_starts span_width_embeddings = self._span_width_embedding(span_widths) return torch.cat([combined_tensors, span_width_embeddings], -1) if span_indices_mask is not None: return combined_tensors * span_indices_mask.unsqueeze(-1).float() return combined_tensors @classmethod def from_params(cls, params: Params) -> "EndpointSpanExtractor": input_dim = params.pop_int("input_dim") combination = params.pop("combination", "x-y") num_width_embeddings = params.pop_int("num_width_embeddings", None) span_width_embedding_dim = params.pop_int("span_width_embedding_dim", None) bucket_widths = params.pop_bool("bucket_widths", False) params.assert_empty(cls.__name__) return EndpointSpanExtractor( input_dim=input_dim, combination=combination, num_width_embeddings=num_width_embeddings, span_width_embedding_dim=span_width_embedding_dim, bucket_widths=bucket_widths)
class EndpointSpanExtractor(SpanExtractor): """ Represents spans as a combination of the embeddings of their endpoints. Additionally, the width of the spans can be embedded and concatenated on to the final combination. The following types of representation are supported, assuming that ``x = span_start_embeddings`` and ``y = span_end_embeddings``. ``x``, ``y``, ``x*y``, ``x+y``, ``x-y``, ``x/y``, where each of those binary operations is performed elementwise. You can list as many combinations as you want, comma separated. For example, you might give ``x,y,x*y`` as the ``combination`` parameter to this class. The computed similarity function would then be ``[x; y; x*y]``, which can then be optionally concatenated with an embedded representation of the width of the span. Parameters ---------- input_dim : ``int``, required. The final dimension of the ``sequence_tensor``. combination : str, optional (default = "x,y"). The method used to combine the ``start_embedding`` and ``end_embedding`` representations. See above for a full description. num_width_embeddings : ``int``, optional (default = None). Specifies the number of buckets to use when representing span width features. span_width_embedding_dim : ``int``, optional (default = None). The embedding size for the span_width features. bucket_widths : ``bool``, optional (default = False). Whether to bucket the span widths into log-space buckets. If ``False``, the raw span widths are used. use_exclusive_start_indices : ``bool``, optional (default = ``False``). If ``True``, the start indices extracted are converted to exclusive indices. Sentinels are used to represent exclusive span indices for the elements in the first position in the sequence (as the exclusive indices for these elements are outside of the the sequence boundary) so that start indices can be exclusive. NOTE: This option can be helpful to avoid the pathological case in which you want span differences for length 1 spans - if you use inclusive indices, you will end up with an ``x - x`` operation for length 1 spans, which is not good. """ def __init__(self, input_dim: int, combination: str = "x,y", num_width_embeddings: int = None, span_width_embedding_dim: int = None, bucket_widths: bool = False, use_exclusive_start_indices: bool = False) -> None: super().__init__() self._input_dim = input_dim self._combination = combination self._num_width_embeddings = num_width_embeddings self._bucket_widths = bucket_widths self._use_exclusive_start_indices = use_exclusive_start_indices if use_exclusive_start_indices: self._start_sentinel = Parameter(torch.randn([1, 1, int(input_dim)])) if num_width_embeddings is not None and span_width_embedding_dim is not None: self._span_width_embedding = Embedding(num_width_embeddings, span_width_embedding_dim) elif not all([num_width_embeddings is None, span_width_embedding_dim is None]): raise ConfigurationError("To use a span width embedding representation, you must" "specify both num_width_buckets and span_width_embedding_dim.") else: self._span_width_embedding = None def get_input_dim(self) -> int: return self._input_dim def get_output_dim(self) -> int: combined_dim = util.get_combined_dim(self._combination, [self._input_dim, self._input_dim]) if self._span_width_embedding is not None: return combined_dim + self._span_width_embedding.get_output_dim() return combined_dim @overrides def forward(self, sequence_tensor: torch.FloatTensor, span_indices: torch.LongTensor, sequence_mask: torch.LongTensor = None, span_indices_mask: torch.LongTensor = None) -> None: # shape (batch_size, num_spans) span_starts, span_ends = [index.squeeze(-1) for index in span_indices.split(1, dim=-1)] if span_indices_mask is not None: # It's not strictly necessary to multiply the span indices by the mask here, # but it's possible that the span representation was padded with something other # than 0 (such as -1, which would be an invalid index), so we do so anyway to # be safe. span_starts = span_starts * span_indices_mask span_ends = span_ends * span_indices_mask if not self._use_exclusive_start_indices: start_embeddings = util.batched_index_select(sequence_tensor, span_starts) end_embeddings = util.batched_index_select(sequence_tensor, span_ends) else: # We want `exclusive` span starts, so we remove 1 from the forward span starts # as the AllenNLP ``SpanField`` is inclusive. # shape (batch_size, num_spans) exclusive_span_starts = span_starts - 1 # shape (batch_size, num_spans, 1) start_sentinel_mask = (exclusive_span_starts == -1).long().unsqueeze(-1) exclusive_span_starts = exclusive_span_starts * (1 - start_sentinel_mask.squeeze(-1)) # We'll check the indices here at runtime, because it's difficult to debug # if this goes wrong and it's tricky to get right. if (exclusive_span_starts < 0).any(): raise ValueError(f"Adjusted span indices must lie inside the the sequence tensor, " f"but found: exclusive_span_starts: {exclusive_span_starts}.") start_embeddings = util.batched_index_select(sequence_tensor, exclusive_span_starts) end_embeddings = util.batched_index_select(sequence_tensor, span_ends) # We're using sentinels, so we need to replace all the elements which were # outside the dimensions of the sequence_tensor with the start sentinel. float_start_sentinel_mask = start_sentinel_mask.float() start_embeddings = start_embeddings * (1 - float_start_sentinel_mask) \ + float_start_sentinel_mask * self._start_sentinel combined_tensors = util.combine_tensors(self._combination, [start_embeddings, end_embeddings]) if self._span_width_embedding is not None: # Embed the span widths and concatenate to the rest of the representations. if self._bucket_widths: span_widths = util.bucket_values(span_ends - span_starts, num_total_buckets=self._num_width_embeddings) else: span_widths = span_ends - span_starts span_width_embeddings = self._span_width_embedding(span_widths) return torch.cat([combined_tensors, span_width_embeddings], -1) if span_indices_mask is not None: return combined_tensors * span_indices_mask.unsqueeze(-1).float() return combined_tensors
class AttentionSpanExtractor(SpanExtractor): def __init__(self, input_dim: int, combination: str = "max", num_width_embeddings: int = None, span_width_embedding_dim: int = None, bucket_widths: bool = False, use_exclusive_start_indices: bool = False) -> None: super().__init__() self._input_dim = input_dim self._combination = combination self._num_width_embeddings = num_width_embeddings self._bucket_widths = bucket_widths if bucket_widths: raise ConfigurationError("not support") self._use_exclusive_start_indices = use_exclusive_start_indices if use_exclusive_start_indices: raise ConfigurationError("not support") if num_width_embeddings is not None and span_width_embedding_dim is not None: self._span_width_embedding = Embedding(num_width_embeddings, span_width_embedding_dim) elif not all( [num_width_embeddings is None, span_width_embedding_dim is None]): raise ConfigurationError( "To use a span width embedding representation, you must" "specify both num_width_buckets and span_width_embedding_dim.") else: self._span_width_embedding = None # the allennlp SelfAttentiveSpanExtractor doesn't include span width embedding. self._self_attentive = SelfAttentiveSpanExtractor(self._input_dim) def get_input_dim(self) -> int: return self._input_dim def get_output_dim(self) -> int: combined_dim = self._input_dim if self._span_width_embedding is not None: return combined_dim + self._span_width_embedding.get_output_dim() return combined_dim @overrides def forward(self, sequence_tensor: torch.FloatTensor, span_indices: torch.LongTensor, sequence_mask: torch.LongTensor = None, span_indices_mask: torch.LongTensor = None) -> None: span_embeddings = self._self_attentive(sequence_tensor, span_indices, sequence_mask, span_indices_mask) if self._span_width_embedding is not None: # both of shape (batch_size, num_spans, 1) span_starts, span_ends = span_indices.split(1, dim=-1) # shape (batch_size, num_spans, 1) # These span widths are off by 1, because the span ends are `inclusive`. span_widths = span_ends - span_starts # Embed the span widths and concatenate to the rest of the representations. span_width_embeddings = self._span_width_embedding( span_widths.squeeze(-1)) span_embeddings = torch.cat( [span_embeddings, span_width_embeddings], -1) return span_embeddings
class PoolingSpanExtractor(SpanExtractor): def __init__(self, input_dim: int, combination: str = "max", num_width_embeddings: int = None, span_width_embedding_dim: int = None, bucket_widths: bool = False, use_exclusive_start_indices: bool = False) -> None: super().__init__() self._input_dim = input_dim self._combination = combination self._num_width_embeddings = num_width_embeddings self._bucket_widths = bucket_widths if bucket_widths: raise ConfigurationError("not support") self._use_exclusive_start_indices = use_exclusive_start_indices if use_exclusive_start_indices: raise ConfigurationError("not support") if num_width_embeddings is not None and span_width_embedding_dim is not None: self._span_width_embedding = Embedding(num_width_embeddings, span_width_embedding_dim) elif not all( [num_width_embeddings is None, span_width_embedding_dim is None]): raise ConfigurationError( "To use a span width embedding representation, you must" "specify both num_width_buckets and span_width_embedding_dim.") else: self._span_width_embedding = None def get_input_dim(self) -> int: return self._input_dim def get_output_dim(self) -> int: combined_dim = self._input_dim if self._span_width_embedding is not None: return combined_dim + self._span_width_embedding.get_output_dim() return combined_dim @overrides def forward(self, sequence_tensor: torch.FloatTensor, span_indices: torch.LongTensor, sequence_mask: torch.LongTensor = None, span_indices_mask: torch.LongTensor = None) -> None: # both of shape (batch_size, num_spans, 1) span_starts, span_ends = span_indices.split(1, dim=-1) # shape (batch_size, num_spans, 1) # These span widths are off by 1, because the span ends are `inclusive`. span_widths = span_ends - span_starts # We need to know the maximum span width so we can # generate indices to extract the spans from the sequence tensor. # These indices will then get masked below, such that if the length # of a given span is smaller than the max, the rest of the values # are masked. max_batch_span_width = span_widths.max().item() + 1 # Shape: (1, 1, max_batch_span_width) max_span_range_indices = util.get_range_vector( max_batch_span_width, util.get_device_of(sequence_tensor)).view(1, 1, -1) # Shape: (batch_size, num_spans, max_batch_span_width) # This is a broadcasted comparison - for each span we are considering, # we are creating a range vector of size max_span_width, but masking values # which are greater than the actual length of the span. # # We're using <= here (and for the mask below) because the span ends are # inclusive, so we want to include indices which are equal to span_widths rather # than using it as a non-inclusive upper bound. span_mask = (max_span_range_indices <= span_widths).float() raw_span_indices = span_ends - max_span_range_indices # We also don't want to include span indices which are less than zero, # which happens because some spans near the beginning of the sequence # have an end index < max_batch_span_width, so we add this to the mask here. span_mask = span_mask * (raw_span_indices >= 0).float() span_indices = torch.nn.functional.relu( raw_span_indices.float()).long() # Shape: (batch_size * num_spans * max_batch_span_width) flat_span_indices = util.flatten_and_batch_shift_indices( span_indices, sequence_tensor.size(1)) # Shape: (batch_size, num_spans, max_batch_span_width, embedding_dim) span_embeddings = util.batched_index_select(sequence_tensor, span_indices, flat_span_indices) # Shape: (batch_size, num_spans, embedding_dim) # span_embeddings = util.masked_max(span_embeddings, span_mask.unsqueeze(-1), dim=2) span_embeddings = util.masked_mean(span_embeddings, span_mask.unsqueeze(-1), dim=2) if self._span_width_embedding is not None: # Embed the span widths and concatenate to the rest of the representations. span_width_embeddings = self._span_width_embedding( span_widths.squeeze(-1)) span_embeddings = torch.cat( [span_embeddings, span_width_embeddings], -1) return span_embeddings