Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions gliner/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@
split_past_key_values,
stack_past_key_values,
)
from .modeling.utils import extract_prompt_features
from .modeling.utils import extract_prompts_mask, extract_prompt_features
from .data_processing import (
BaseProcessor,
BiEncoderSpanProcessor,
Expand Down Expand Up @@ -681,9 +681,18 @@ def compile(self):
def _forward_inputs(self, batch: Dict[str, Any]) -> Dict[str, Any]:
"""The entries of a collated batch that the model forward takes."""
if self.is_runtime_model:
return dict(batch)
return self._runtime_inputs(batch, self.model.input_names)
return {key: value for key, value in batch.items() if key not in self._DECODE_ONLY_KEYS}

def _runtime_inputs(self, batch: Dict[str, Any], input_names: List[str]) -> Dict[str, Any]:
"""The batch entries an exported graph takes, adding ``prompts_mask`` when the graph declares it."""
inputs = dict(batch)
if "prompts_mask" in input_names and "prompts_mask" not in inputs:
inputs["prompts_mask"] = extract_prompts_mask(
batch["input_ids"], batch["attention_mask"], self.config.class_token_index
)
return inputs

_PRECISION_ALIASES = {"fp16", "float16", "half", "bf16", "bfloat16"}

_DTYPE_MAP = {
Expand Down Expand Up @@ -2342,6 +2351,7 @@ def _prepare_onnx_batch(self, batch: dict[str, torch.Tensor], **export_kwargs) -
inputs to pass to the wrapper and updated_spec may have modified input_names/dynamic_axes
"""
spec = self._get_onnx_input_spec()
batch = self._runtime_inputs(batch, spec["input_names"])
all_inputs = tuple(batch[name] for name in spec["input_names"])
return all_inputs, spec

Expand Down Expand Up @@ -3980,6 +3990,7 @@ def _get_onnx_input_spec(self) -> dict[str, Any]:
"text_lengths",
"span_idx",
"span_mask",
"prompts_mask",
],
"output_names": ["logits"],
"dynamic_axes": {
Expand All @@ -3989,6 +4000,7 @@ def _get_onnx_input_spec(self) -> dict[str, Any]:
"text_lengths": {0: "batch_size", 1: "value"},
"span_idx": {0: "batch_size", 1: "num_spans", 2: "idx"},
"span_mask": {0: "batch_size", 1: "num_spans"},
"prompts_mask": {0: "batch_size", 1: "num_classes"},
"logits": {
0: "batch_size",
1: "sequence_length",
Expand All @@ -4014,6 +4026,7 @@ def forward(
text_lengths,
span_idx,
span_mask,
prompts_mask,
):
out = self.core(
input_ids=input_ids,
Expand All @@ -4022,6 +4035,7 @@ def forward(
text_lengths=text_lengths,
span_idx=span_idx,
span_mask=span_mask,
prompts_mask=prompts_mask,
)
return out.logits if hasattr(out, "logits") else out[0]

Expand Down
19 changes: 15 additions & 4 deletions gliner/modeling/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -483,6 +483,7 @@ def _extract_prompt_features_and_word_embeddings(
attention_mask: torch.Tensor,
text_lengths: torch.Tensor,
words_mask: torch.Tensor,
**kwargs: Any,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
"""Extract entity label prompts and word embeddings from token embeddings.

Expand All @@ -492,6 +493,7 @@ def _extract_prompt_features_and_word_embeddings(
attention_mask: Attention mask of shape (B, L).
text_lengths: Length of each text sequence in batch.
words_mask: Mask indicating word boundaries.
**kwargs: ``max_text_length`` and ``prompts_mask`` for extract_prompt_features_and_word_embeddings.

Returns:
Tuple containing:
Expand All @@ -509,6 +511,7 @@ def _extract_prompt_features_and_word_embeddings(
words_mask,
self.config.embed_ent_token,
subtoken_pooling=getattr(self.config, "subtoken_pooling", "first"),
**kwargs,
)
return prompts_embedding, prompts_embedding_mask, words_embedding, mask

Expand All @@ -533,6 +536,8 @@ def get_representations(
Structured prompt and word representations.
"""
word_lengths = kwargs.pop("word_lengths", None)
shape_kwargs = {key: kwargs.pop(key, None) for key in ("max_text_length", "prompts_mask")}
shape_kwargs = {key: value for key, value in shape_kwargs.items() if value is not None}
token_embeds = self.token_rep_layer(input_ids, attention_mask, **kwargs)

use_precomputed = (
Expand All @@ -541,7 +546,7 @@ def get_representations(
)
if use_precomputed:
batch_size, _, embed_dim = token_embeds.shape
max_text_length = text_lengths.max()
max_text_length = shape_kwargs.get("max_text_length", text_lengths.max())
words_embedding, mask = extract_word_embeddings(
token_embeds,
words_mask,
Expand All @@ -558,7 +563,7 @@ def get_representations(
else:
prompts_embedding, prompts_embedding_mask, words_embedding, mask = (
self._extract_prompt_features_and_word_embeddings(
token_embeds, input_ids, attention_mask, text_lengths, words_mask
token_embeds, input_ids, attention_mask, text_lengths, words_mask, **shape_kwargs
)
)

Expand Down Expand Up @@ -647,16 +652,22 @@ def forward(
GLiNERBaseOutput containing logits, loss, and intermediate representations.
"""
encoder_kwargs = {key: kwargs[key] for key in ENCODER_KWARGS if key in kwargs}
target_W = span_idx.size(1) // self.config.max_width

representations = self.get_representations(
input_ids, attention_mask, text_lengths, words_mask, **encoder_kwargs
input_ids,
attention_mask,
text_lengths,
words_mask,
max_text_length=target_W,
prompts_mask=kwargs.get("prompts_mask"),
**encoder_kwargs,
)
prompts_embedding = representations.prompts_embedding
prompts_embedding_mask = representations.prompts_embedding_mask
words_embedding = representations.words_embedding
mask = representations.mask

target_W = span_idx.size(1) // self.config.max_width
words_embedding, mask = self._fit_length(words_embedding, mask, target_W)

span_idx = span_idx * span_mask.unsqueeze(-1)
Expand Down
78 changes: 44 additions & 34 deletions gliner/modeling/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,12 @@ def extract_first_word_embeddings(
embed_dim: int,
) -> torch.Tensor:
"""Select the first marked subtoken representation for each word."""
words_embedding = token_embeds.new_zeros((batch_size, max_text_length, embed_dim))
batch_indices, token_indices = torch.where(words_mask > 0)
target_word_indices = words_mask[batch_indices, token_indices] - 1
words_embedding[batch_indices, target_word_indices] = token_embeds[batch_indices, token_indices]
return words_embedding
# Unmarked subtokens scatter into an extra trailing slot that is dropped, keeping shapes static for export.
valid = (words_mask > 0) & (words_mask <= max_text_length)
target_word_indices = torch.where(valid, words_mask - 1, max_text_length)
words_embedding = token_embeds.new_zeros((batch_size, max_text_length + 1, embed_dim))
words_embedding.scatter_(1, target_word_indices.unsqueeze(-1).expand(-1, -1, embed_dim), token_embeds)
return words_embedding[:, :-1]


def extract_last_word_embeddings(
Expand All @@ -28,11 +29,11 @@ def extract_last_word_embeddings(
embed_dim: int,
) -> torch.Tensor:
"""Select the last marked subtoken representation for each word."""
words_embedding = token_embeds.new_zeros((batch_size, max_text_length, embed_dim))
batch_indices, token_indices = torch.where(words_mask > 0)
target_word_indices = words_mask[batch_indices, token_indices] - 1
words_embedding[batch_indices, target_word_indices] = token_embeds[batch_indices, token_indices]
return words_embedding
valid = (words_mask > 0) & (words_mask <= max_text_length)
target_word_indices = torch.where(valid, words_mask - 1, max_text_length)
words_embedding = token_embeds.new_zeros((batch_size, max_text_length + 1, embed_dim))
words_embedding.scatter_(1, target_word_indices.unsqueeze(-1).expand(-1, -1, embed_dim), token_embeds)
return words_embedding[:, :-1]


def extract_mean_word_embeddings(
Expand All @@ -45,11 +46,12 @@ def extract_mean_word_embeddings(
) -> torch.Tensor:
"""Mean-pool all attended subtoken representations for each word."""
valid_subtokens = (words_mask > 0) & attention_mask.bool() & (words_mask <= max_text_length)
batch_indices, token_indices = torch.where(valid_subtokens)
flat_word_indices = batch_indices * max_text_length + words_mask[batch_indices, token_indices] - 1
selected_embeddings = token_embeds[batch_indices, token_indices]
expanded_indices = flat_word_indices.unsqueeze(-1).expand(-1, embed_dim)
batch_offsets = torch.arange(batch_size, device=words_mask.device).unsqueeze(-1) * max_text_length
flat_output_size = batch_size * max_text_length
flat_word_indices = torch.where(valid_subtokens, batch_offsets + words_mask - 1, flat_output_size).reshape(-1)
selected_embeddings = token_embeds.reshape(-1, embed_dim)
expanded_indices = flat_word_indices.unsqueeze(-1).expand(-1, embed_dim)
flat_output_size = flat_output_size + 1

words_embedding = token_embeds.new_zeros((flat_output_size, embed_dim))
if torch.onnx.is_in_onnx_export():
Expand Down Expand Up @@ -80,7 +82,7 @@ def extract_mean_word_embeddings(
include_self=False,
)

return words_embedding.reshape(batch_size, max_text_length, embed_dim)
return words_embedding[:-1].reshape(batch_size, max_text_length, embed_dim)


def extract_max_word_embeddings(
Expand All @@ -93,11 +95,12 @@ def extract_max_word_embeddings(
) -> torch.Tensor:
"""Element-wise max-pool all attended subtoken representations for each word."""
valid_subtokens = (words_mask > 0) & attention_mask.bool() & (words_mask <= max_text_length)
batch_indices, token_indices = torch.where(valid_subtokens)
flat_word_indices = batch_indices * max_text_length + words_mask[batch_indices, token_indices] - 1
selected_embeddings = token_embeds[batch_indices, token_indices]
expanded_indices = flat_word_indices.unsqueeze(-1).expand(-1, embed_dim)
batch_offsets = torch.arange(batch_size, device=words_mask.device).unsqueeze(-1) * max_text_length
flat_output_size = batch_size * max_text_length
flat_word_indices = torch.where(valid_subtokens, batch_offsets + words_mask - 1, flat_output_size).reshape(-1)
selected_embeddings = token_embeds.reshape(-1, embed_dim)
expanded_indices = flat_word_indices.unsqueeze(-1).expand(-1, embed_dim)
flat_output_size = flat_output_size + 1

if torch.onnx.is_in_onnx_export():
# include_self=False is unsupported by the legacy ONNX exporter. Start
Expand Down Expand Up @@ -129,7 +132,7 @@ def extract_max_word_embeddings(
include_self=False,
)

return words_embedding.reshape(batch_size, max_text_length, embed_dim)
return words_embedding[:-1].reshape(batch_size, max_text_length, embed_dim)


def extract_word_embeddings(
Expand Down Expand Up @@ -180,6 +183,7 @@ def extract_prompt_features(
batch_size: int,
embed_dim: int,
embed_ent_token: bool = True,
prompts_mask: torch.Tensor | None = None,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""Extract prompt/entity type embeddings from special class tokens.

Expand Down Expand Up @@ -207,6 +211,8 @@ def extract_prompt_features(
embed_ent_token: If True, use the [ENT] token embedding itself.
If False, use the embedding of the token immediately after [ENT]
(i.e., the entity type name token). Default: True.
prompts_mask: Optional output of ``extract_prompts_mask``. Its width sets the number of
prompts, so exported graphs take it from an input shape instead of input values.

Returns:
Tuple containing:
Expand All @@ -223,33 +229,34 @@ def extract_prompt_features(
num_class_tokens = torch.sum(class_token_mask, dim=-1, keepdim=True)

# Maximum number of class tokens across batch
max_embed_dim = num_class_tokens.max()
max_embed_dim = num_class_tokens.max() if prompts_mask is None else prompts_mask.size(1)
aranged_class_idx = torch.arange(max_embed_dim, dtype=attention_mask.dtype, device=token_embeds.device).expand(
batch_size, -1
)

# Find valid positions (not padding)
batch_indices, target_class_idx = torch.where(aranged_class_idx < num_class_tokens)
_, class_indices = torch.where(class_token_mask)

# Optionally shift to token after [ENT] (the entity type name)
if not embed_ent_token:
class_indices += 1
token_embeds = token_embeds.roll(-1, dims=1)

# Initialize prompt embeddings tensor
prompts_embedding = torch.zeros(
batch_size, max_embed_dim, embed_dim, dtype=token_embeds.dtype, device=token_embeds.device
)
# Class tokens scatter to their rank in the row; other tokens go to a dropped trailing slot
target_class_idx = torch.where(class_token_mask, class_token_mask.long().cumsum(-1) - 1, max_embed_dim)
prompts_embedding = token_embeds.new_zeros((batch_size, max_embed_dim + 1, embed_dim))
prompts_embedding.scatter_(1, target_class_idx.unsqueeze(-1).expand(-1, -1, embed_dim), token_embeds)
prompts_embedding = prompts_embedding[:, :-1]

# Create mask for valid (non-padded) positions
prompts_embedding_mask = (aranged_class_idx < num_class_tokens).to(attention_mask.dtype)

# Extract embeddings at class token positions
prompts_embedding[batch_indices, target_class_idx] = token_embeds[batch_indices, class_indices]

return prompts_embedding, prompts_embedding_mask


def extract_prompts_mask(input_ids: torch.Tensor, attention_mask: torch.Tensor, class_token_index: int) -> torch.Tensor:
"""Mask of shape (batch_size, max_num_types) marking the prompts each row holds."""
num_class_tokens = (input_ids.eq(class_token_index) & attention_mask.gt(0)).sum(-1, keepdim=True)
aranged_class_idx = torch.arange(num_class_tokens.max(), device=input_ids.device)
return (aranged_class_idx < num_class_tokens).to(attention_mask.dtype)


def extract_prompt_features_and_word_embeddings(
class_token_index: int,
token_embeds: torch.Tensor,
Expand All @@ -259,6 +266,7 @@ def extract_prompt_features_and_word_embeddings(
words_mask: torch.Tensor,
embed_ent_token: bool = True,
subtoken_pooling: str = "first",
max_text_length: int | torch.Tensor | None = None,
**kwargs,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
"""Extract both prompt embeddings and word embeddings in one call.
Expand Down Expand Up @@ -287,6 +295,7 @@ def extract_prompt_features_and_word_embeddings(
use the token after [ENT] (the entity type name). Default: True.
subtoken_pooling: Reduction applied to subtokens belonging to the same
word. One of ``first``, ``last``, ``mean``, or ``max``.
max_text_length: Number of word slots. Defaults to ``text_lengths.max()``.
**kwargs: Additional keyword arguments passed to extract_prompt_features.

Returns:
Expand All @@ -301,7 +310,8 @@ def extract_prompt_features_and_word_embeddings(
Shape: (batch_size, max_text_length)
"""
batch_size, _, embed_dim = token_embeds.shape
max_text_length = text_lengths.max()
if max_text_length is None:
max_text_length = text_lengths.max()

# Extract prompt/entity type embeddings
prompts_embedding, prompts_embedding_mask = extract_prompt_features(
Expand Down
Loading