code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def _calculate_aggregation_loss(
logits_aggregation,
aggregate_mask,
aggregation_labels,
use_answer_as_supervision,
num_aggregation_labels,
aggregation_loss_weight,
):
"""
Calculates the aggregation loss per example.
Args:
logits_aggregation (`tf.Tensor` of shape `(batch_siz... |
Calculates the aggregation loss per example.
Args:
logits_aggregation (`tf.Tensor` of shape `(batch_size, num_aggregation_labels)`):
Logits per aggregation operation.
aggregate_mask (`tf.Tensor` of shape `(batch_size, )`):
A mask set to 1 for examples that should use ag... | _calculate_aggregation_loss | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/modeling_tf_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/modeling_tf_tapas.py | Apache-2.0 |
def _calculate_expected_result(
dist_per_cell, numeric_values, numeric_values_scale, input_mask_float, logits_aggregation, config
):
"""
Calculates the expected result given cell and aggregation probabilities.
Args:
dist_per_cell (`tfp.distributions.Bernoulli`):
Cell selection distr... |
Calculates the expected result given cell and aggregation probabilities.
Args:
dist_per_cell (`tfp.distributions.Bernoulli`):
Cell selection distribution for each cell.
numeric_values (`tf.Tensor` of shape `(batch_size, seq_length)`):
Numeric values of every token. Nan ... | _calculate_expected_result | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/modeling_tf_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/modeling_tf_tapas.py | Apache-2.0 |
def _calculate_regression_loss(
answer,
aggregate_mask,
dist_per_cell,
numeric_values,
numeric_values_scale,
input_mask_float,
logits_aggregation,
config,
):
"""
Calculates the regression loss per example.
Args:
answer (`tf.Tensor` of shape `(batch_size,)`):
... |
Calculates the regression loss per example.
Args:
answer (`tf.Tensor` of shape `(batch_size,)`):
Answer for every example in the batch. Nan if there is no scalar answer.
aggregate_mask (`tf.Tensor` of shape `(batch_size,)`):
A mask set to 1 for examples that should use ... | _calculate_regression_loss | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/modeling_tf_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/modeling_tf_tapas.py | Apache-2.0 |
def create_segment_token_type_ids_from_sequences(
self, query_ids: List[int], table_values: List[TableValue]
) -> List[int]:
"""
Creates the segment token type IDs according to the query token IDs and a list of table values.
Args:
query_ids (`List[int]`): list of token I... |
Creates the segment token type IDs according to the query token IDs and a list of table values.
Args:
query_ids (`List[int]`): list of token IDs corresponding to the ID.
table_values (`List[TableValue]`): lift of table values, which are named tuples containing the
... | create_segment_token_type_ids_from_sequences | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def create_column_token_type_ids_from_sequences(
self, query_ids: List[int], table_values: List[TableValue]
) -> List[int]:
"""
Creates the column token type IDs according to the query token IDs and a list of table values.
Args:
query_ids (`List[int]`): list of token IDs... |
Creates the column token type IDs according to the query token IDs and a list of table values.
Args:
query_ids (`List[int]`): list of token IDs corresponding to the ID.
table_values (`List[TableValue]`): lift of table values, which are named tuples containing the
... | create_column_token_type_ids_from_sequences | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def create_row_token_type_ids_from_sequences(
self, query_ids: List[int], table_values: List[TableValue]
) -> List[int]:
"""
Creates the row token type IDs according to the query token IDs and a list of table values.
Args:
query_ids (`List[int]`): list of token IDs corre... |
Creates the row token type IDs according to the query token IDs and a list of table values.
Args:
query_ids (`List[int]`): list of token IDs corresponding to the ID.
table_values (`List[TableValue]`): lift of table values, which are named tuples containing the
t... | create_row_token_type_ids_from_sequences | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def build_inputs_with_special_tokens(
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
) -> List[int]:
"""
Build model inputs from a question and flattened table for question answering or sequence classification tasks
by concatenating and adding special tokens.
... |
Build model inputs from a question and flattened table for question answering or sequence classification tasks
by concatenating and adding special tokens.
Args:
token_ids_0 (`List[int]`): The ids of the question.
token_ids_1 (`List[int]`, *optional*): The ids of the fla... | build_inputs_with_special_tokens | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def get_special_tokens_mask(
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
) -> List[int]:
"""
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
special tokens ... |
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
special tokens using the tokenizer `prepare_for_model` method.
Args:
token_ids_0 (`List[int]`):
List of question IDs.
token_ids_1 (`List[int]`, *o... | get_special_tokens_mask | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def __call__(
self,
table: "pd.DataFrame",
queries: Optional[
Union[
TextInput,
PreTokenizedInput,
EncodedInput,
List[TextInput],
List[PreTokenizedInput],
List[EncodedInput],
]... |
Main method to tokenize and prepare for the model one or several sequence(s) related to a table.
Args:
table (`pd.DataFrame`):
Table containing tabular data. Note that all cell values must be text. Use *.astype(str)* on a Pandas
dataframe to convert it to st... | __call__ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def batch_encode_plus(
self,
table: "pd.DataFrame",
queries: Optional[
Union[
List[TextInput],
List[PreTokenizedInput],
List[EncodedInput],
]
] = None,
answer_coordinates: Optional[List[List[Tuple]]] = None,
... |
Prepare a table and a list of strings for the model.
<Tip warning={true}>
This method is deprecated, `__call__` should be used instead.
</Tip>
Args:
table (`pd.DataFrame`):
Table containing tabular data. Note that all cell values must be text. Use... | batch_encode_plus | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def _get_question_tokens(self, query):
"""Tokenizes the query, taking into account the max and min question length."""
query_tokens = self.tokenize(query)
if self.max_question_length is not None and len(query_tokens) > self.max_question_length:
logger.warning("Skipping query as its ... | Tokenizes the query, taking into account the max and min question length. | _get_question_tokens | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def encode(
self,
table: "pd.DataFrame",
query: Optional[
Union[
TextInput,
PreTokenizedInput,
EncodedInput,
]
] = None,
add_special_tokens: bool = True,
padding: Union[bool, str, PaddingStrategy] = F... |
Prepare a table and a string for the model. This method does not return token type IDs, attention masks, etc.
which are necessary for the model to work correctly. Use that method if you want to build your processing on
your own, otherwise refer to `__call__`.
Args:
table (`... | encode | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def encode_plus(
self,
table: "pd.DataFrame",
query: Optional[
Union[
TextInput,
PreTokenizedInput,
EncodedInput,
]
] = None,
answer_coordinates: Optional[List[Tuple]] = None,
answer_text: Optional[Li... |
Prepare a table and a string for the model.
Args:
table (`pd.DataFrame`):
Table containing tabular data. Note that all cell values must be text. Use *.astype(str)* on a Pandas
dataframe to convert it to string.
query (`str` or `List[str]`):
... | encode_plus | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def prepare_for_model(
self,
raw_table: "pd.DataFrame",
raw_query: Union[
TextInput,
PreTokenizedInput,
EncodedInput,
],
tokenized_table: Optional[TokenizedTable] = None,
query_tokens: Optional[TokenizedTable] = None,
answer_coo... |
Prepares a sequence of input id so that it can be used by the model. It adds special tokens, truncates
sequences if overflowing while taking into account the special tokens.
Args:
raw_table (`pd.DataFrame`):
The original table before any transformation (like tokeniz... | prepare_for_model | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def _get_truncated_table_rows(
self,
query_tokens: List[str],
tokenized_table: TokenizedTable,
num_rows: int,
num_columns: int,
max_length: int,
truncation_strategy: Union[str, TapasTruncationStrategy],
) -> Tuple[int, int]:
"""
Truncates a seq... |
Truncates a sequence pair in-place following the strategy.
Args:
query_tokens (`List[str]`):
List of strings corresponding to the tokenized query.
tokenized_table (`TokenizedTable`):
Tokenized table
num_rows (`int`):
T... | _get_truncated_table_rows | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def _tokenize_table(
self,
table=None,
):
"""
Tokenizes column headers and cell texts of a table.
Args:
table (`pd.Dataframe`):
Table. Returns: `TokenizedTable`: TokenizedTable object.
"""
tokenized_rows = []
tokenized_row ... |
Tokenizes column headers and cell texts of a table.
Args:
table (`pd.Dataframe`):
Table. Returns: `TokenizedTable`: TokenizedTable object.
| _tokenize_table | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def _get_table_values(self, table, num_columns, num_rows, num_tokens) -> Generator[TableValue, None, None]:
"""Iterates over partial table and returns token, column and row indexes."""
for tc in table.selected_tokens:
# First row is header row.
if tc.row_index >= num_rows + 1:
... | Iterates over partial table and returns token, column and row indexes. | _get_table_values | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def _get_table_boundaries(self, table):
"""Return maximal number of rows, columns and tokens."""
max_num_tokens = 0
max_num_columns = 0
max_num_rows = 0
for tc in table.selected_tokens:
max_num_columns = max(max_num_columns, tc.column_index + 1)
max_num_ro... | Return maximal number of rows, columns and tokens. | _get_table_boundaries | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def _get_max_num_tokens(self, question_tokens, tokenized_table, num_columns, num_rows, max_length):
"""Computes max number of tokens that can be squeezed into the budget."""
token_budget = self._get_token_budget(question_tokens, max_length)
_, _, max_num_tokens = self._get_table_boundaries(token... | Computes max number of tokens that can be squeezed into the budget. | _get_max_num_tokens | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def _get_numeric_column_ranks(self, column_ids, row_ids, table):
"""Returns column ranks for all numeric columns."""
ranks = [0] * len(column_ids)
inv_ranks = [0] * len(column_ids)
# original code from tf_example_utils.py of the original implementation
if table is not None:
... | Returns column ranks for all numeric columns. | _get_numeric_column_ranks | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def _get_numeric_sort_key_fn(self, table_numeric_values, value):
"""
Returns the sort key function for comparing value to table values. The function returned will be a suitable
input for the key param of the sort(). See number_annotation_utils._get_numeric_sort_key_fn for details
Args:
... |
Returns the sort key function for comparing value to table values. The function returned will be a suitable
input for the key param of the sort(). See number_annotation_utils._get_numeric_sort_key_fn for details
Args:
table_numeric_values: Numeric values of a column
val... | _get_numeric_sort_key_fn | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def _get_numeric_relations(self, question, column_ids, row_ids, table):
"""
Returns numeric relations embeddings
Args:
question: Question object.
column_ids: Maps word piece position to column id.
row_ids: Maps word piece position to row id.
table... |
Returns numeric relations embeddings
Args:
question: Question object.
column_ids: Maps word piece position to column id.
row_ids: Maps word piece position to row id.
table: The table containing the numeric cell values.
| _get_numeric_relations | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def _get_numeric_values(self, table, column_ids, row_ids):
"""Returns numeric values for computation of answer loss."""
numeric_values = [float("nan")] * len(column_ids)
if table is not None:
num_rows = table.shape[0]
num_columns = table.shape[1]
for col_in... | Returns numeric values for computation of answer loss. | _get_numeric_values | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def _get_numeric_values_scale(self, table, column_ids, row_ids):
"""Returns a scale to each token to down weigh the value of long words."""
numeric_values_scale = [1.0] * len(column_ids)
if table is None:
return numeric_values_scale
num_rows = table.shape[0]
num_co... | Returns a scale to each token to down weigh the value of long words. | _get_numeric_values_scale | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def _get_all_answer_ids_from_coordinates(
self,
column_ids,
row_ids,
answers_list,
):
"""Maps lists of answer coordinates to token indexes."""
answer_ids = [0] * len(column_ids)
found_answers = set()
all_answers = set()
for answers in answers_l... | Maps lists of answer coordinates to token indexes. | _get_all_answer_ids_from_coordinates | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def _get_all_answer_ids(self, column_ids, row_ids, answer_coordinates):
"""
Maps answer coordinates of a question to token indexes.
In the SQA format (TSV), the coordinates are given as (row, column) tuples. Here, we first swap them to
(column, row) format before calling _get_all_answer... |
Maps answer coordinates of a question to token indexes.
In the SQA format (TSV), the coordinates are given as (row, column) tuples. Here, we first swap them to
(column, row) format before calling _get_all_answer_ids_from_coordinates.
| _get_all_answer_ids | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def _find_tokens(self, text, segment):
"""Return start index of segment in text or None."""
logging.info(f"text: {text} {segment}")
for index in range(1 + len(text) - len(segment)):
for seg_index, seg_token in enumerate(segment):
if text[index + seg_index].piece != se... | Return start index of segment in text or None. | _find_tokens | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def _find_answer_coordinates_from_answer_text(
self,
tokenized_table,
answer_text,
):
"""Returns all occurrences of answer_text in the table."""
logging.info(f"answer text: {answer_text}")
for row_index, row in enumerate(tokenized_table.rows):
if row_index... | Returns all occurrences of answer_text in the table. | _find_answer_coordinates_from_answer_text | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def _find_answer_ids_from_answer_texts(
self,
column_ids,
row_ids,
tokenized_table,
answer_texts,
):
"""Maps question with answer texts to the first matching token indexes."""
answer_ids = [0] * len(column_ids)
for answer_text in answer_texts:
... | Maps question with answer texts to the first matching token indexes. | _find_answer_ids_from_answer_texts | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def _get_answer_ids(self, column_ids, row_ids, answer_coordinates):
"""Maps answer coordinates of a question to token indexes."""
answer_ids, missing_count = self._get_all_answer_ids(column_ids, row_ids, answer_coordinates)
if missing_count:
raise ValueError("Couldn't find all answe... | Maps answer coordinates of a question to token indexes. | _get_answer_ids | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def _get_mean_cell_probs(self, probabilities, segment_ids, row_ids, column_ids):
"""Computes average probability per cell, aggregating over tokens."""
coords_to_probs = collections.defaultdict(list)
for i, prob in self._get_cell_token_probs(probabilities, segment_ids, row_ids, column_ids):
... | Computes average probability per cell, aggregating over tokens. | _get_mean_cell_probs | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def convert_logits_to_predictions(self, data, logits, logits_agg=None, cell_classification_threshold=0.5):
"""
Converts logits of [`TapasForQuestionAnswering`] to actual predicted answer coordinates and optional
aggregation indices.
The original implementation, on which this function is... |
Converts logits of [`TapasForQuestionAnswering`] to actual predicted answer coordinates and optional
aggregation indices.
The original implementation, on which this function is based, can be found
[here](https://github.com/google-research/tapas/blob/4908213eb4df7aa988573350278b44c4dbe3... | convert_logits_to_predictions | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def _process_date_pattern(dp):
"""Compute a regex for each date pattern to use as a prefilter."""
pattern, mask = dp
regex = pattern
regex = regex.replace(".", re.escape("."))
regex = regex.replace("-", re.escape("-"))
regex = regex.replace(" ", r"\s+")
for field, field_regex in _FIELD_TO_RE... | Compute a regex for each date pattern to use as a prefilter. | _process_date_pattern | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def _get_numeric_value_from_date(date, mask):
"""Converts date (datetime Python object) to a NumericValue object with a Date object value."""
if date.year < _MIN_YEAR or date.year > _MAX_YEAR:
raise ValueError(f"Invalid year: {date.year}")
new_date = Date()
if mask.year:
new_date.year =... | Converts date (datetime Python object) to a NumericValue object with a Date object value. | _get_numeric_value_from_date | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def _parse_date(text):
"""Attempts to format a text as a standard date string (yyyy-mm-dd)."""
text = re.sub(r"Sept\b", "Sep", text)
for in_pattern, mask, regex in _PROCESSED_DATE_PATTERNS:
if not regex.match(text):
continue
try:
date = datetime.datetime.strptime(text... | Attempts to format a text as a standard date string (yyyy-mm-dd). | _parse_date | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def _parse_number(text):
"""Parses simple cardinal and ordinals numbers."""
for suffix in _ORDINAL_SUFFIXES:
if text.endswith(suffix):
text = text[: -len(suffix)]
break
text = text.replace(",", "")
try:
value = float(text)
except ValueError:
return Non... | Parses simple cardinal and ordinals numbers. | _parse_number | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def get_all_spans(text, max_ngram_length):
"""
Split a text into all possible ngrams up to 'max_ngram_length'. Split points are white space and punctuation.
Args:
text: Text to split.
max_ngram_length: maximal ngram length.
Yields:
Spans, tuples of begin-end index.
"""
start_i... |
Split a text into all possible ngrams up to 'max_ngram_length'. Split points are white space and punctuation.
Args:
text: Text to split.
max_ngram_length: maximal ngram length.
Yields:
Spans, tuples of begin-end index.
| get_all_spans | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def parse_text(text):
"""
Extracts longest number and date spans.
Args:
text: text to annotate
Returns:
List of longest numeric value spans.
"""
span_dict = collections.defaultdict(list)
for match in _NUMBER_PATTERN.finditer(text):
span_text = text[match.start() : match... |
Extracts longest number and date spans.
Args:
text: text to annotate
Returns:
List of longest numeric value spans.
| parse_text | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def _get_value_as_primitive_value(numeric_value):
"""Maps a NumericValue proto to a float or tuple of float."""
if numeric_value.float_value is not None:
return numeric_value.float_value
if numeric_value.date is not None:
date = numeric_value.date
value_tuple = [None, None, None]
... | Maps a NumericValue proto to a float or tuple of float. | _get_value_as_primitive_value | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def _consolidate_numeric_values(row_index_to_values, min_consolidation_fraction, debug_info):
"""
Finds the most common numeric values in a column and returns them
Args:
row_index_to_values:
For each row index all the values in that cell.
min_consolidation_fraction:
... |
Finds the most common numeric values in a column and returns them
Args:
row_index_to_values:
For each row index all the values in that cell.
min_consolidation_fraction:
Fraction of cells that need to have consolidated value.
debug_info:
Additional in... | _consolidate_numeric_values | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def _get_numeric_values(text):
"""Parses text and returns numeric values."""
numeric_spans = parse_text(text)
return itertools.chain(*(span.values for span in numeric_spans)) | Parses text and returns numeric values. | _get_numeric_values | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def _get_column_values(table, col_index):
"""
Parses text in column and returns a dict mapping row_index to values. This is the _get_column_values function from
number_annotation_utils.py of the original implementation
Args:
table: Pandas dataframe
col_index: integer, indicating the index o... |
Parses text in column and returns a dict mapping row_index to values. This is the _get_column_values function from
number_annotation_utils.py of the original implementation
Args:
table: Pandas dataframe
col_index: integer, indicating the index of the column to get the numeric values of
| _get_column_values | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def get_numeric_relation(value, other_value, sort_key_fn):
"""Compares two values and returns their relation or None."""
value = sort_key_fn(value)
other_value = sort_key_fn(other_value)
if value == other_value:
return Relation.EQ
if value < other_value:
return Relation.LT
if val... | Compares two values and returns their relation or None. | get_numeric_relation | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def add_numeric_values_to_question(question):
"""Adds numeric value spans to a question."""
original_text = question
question = normalize_for_match(question)
numeric_spans = parse_text(question)
return Question(original_text=original_text, text=question, numeric_spans=numeric_spans) | Adds numeric value spans to a question. | add_numeric_values_to_question | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def filter_invalid_unicode_from_table(table):
"""
Removes invalid unicode from table. Checks whether a table cell text contains an invalid unicode encoding. If yes,
reset the table cell text to an empty str and log a warning for each invalid cell
Args:
table: table to clean.
"""
# to do... |
Removes invalid unicode from table. Checks whether a table cell text contains an invalid unicode encoding. If yes,
reset the table cell text to an empty str and log a warning for each invalid cell
Args:
table: table to clean.
| filter_invalid_unicode_from_table | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def add_numeric_table_values(table, min_consolidation_fraction=0.7, debug_info=None):
"""
Parses text in table column-wise and adds the consolidated values. Consolidation refers to finding values with a
common types (date or number)
Args:
table:
Table to annotate.
min_consol... |
Parses text in table column-wise and adds the consolidated values. Consolidation refers to finding values with a
common types (date or number)
Args:
table:
Table to annotate.
min_consolidation_fraction:
Fraction of cells in a column that need to have consolidated va... | add_numeric_table_values | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapas/tokenization_tapas.py | Apache-2.0 |
def process_table(self, table_content: Dict):
"""
Given a table, TableLinearize aims at converting it into a flatten sequence with special symbols.
"""
assert "header" in table_content and "rows" in table_content, self.PROMPT_MESSAGE
# process header
table_str = self.proc... |
Given a table, TableLinearize aims at converting it into a flatten sequence with special symbols.
| process_table | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapex/tokenization_tapex.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapex/tokenization_tapex.py | Apache-2.0 |
def process_row(self, row: List, row_index: int):
"""
Given a row, TableLinearize aims at converting it into a flatten sequence with special symbols.
"""
row_str = ""
row_cell_values = []
for cell_value in row:
if isinstance(cell_value, int):
r... |
Given a row, TableLinearize aims at converting it into a flatten sequence with special symbols.
| process_row | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapex/tokenization_tapex.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapex/tokenization_tapex.py | Apache-2.0 |
def build_inputs_with_special_tokens(
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
) -> List[int]:
"""
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
adding special tokens. A TAPEX sequence has ... |
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
adding special tokens. A TAPEX sequence has the following format:
- single sequence: `<s> X </s>`
- pair of sequences: `<s> A </s></s> B </s>`
Args:
token_... | build_inputs_with_special_tokens | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapex/tokenization_tapex.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapex/tokenization_tapex.py | Apache-2.0 |
def create_token_type_ids_from_sequences(
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
) -> List[int]:
"""
Args:
Create a mask from the two sequences passed to be used in a sequence-pair classification task. TAPEX does not:
make use of token type ids,... |
Args:
Create a mask from the two sequences passed to be used in a sequence-pair classification task. TAPEX does not:
make use of token type ids, therefore a list of zeros is returned.
token_ids_0 (`List[int]`):
List of IDs.
token_ids_1 (`List[int]`, *opti... | create_token_type_ids_from_sequences | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapex/tokenization_tapex.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapex/tokenization_tapex.py | Apache-2.0 |
def __call__(
self,
table: Union["pd.DataFrame", List["pd.DataFrame"]] = None,
query: Optional[Union[TextInput, List[TextInput]]] = None,
answer: Union[str, List[str]] = None,
add_special_tokens: bool = True,
padding: Union[bool, str, PaddingStrategy] = False,
tru... |
Main method to tokenize and prepare for the model one or several table-sequence pair(s).
Args:
table (`pd.DataFrame`, `List[pd.DataFrame]`):
Table(s) containing tabular data.
query (`str` or `List[str]`, *optional*):
Sentence or batch of sentence... | __call__ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapex/tokenization_tapex.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapex/tokenization_tapex.py | Apache-2.0 |
def batch_encode_plus(
self,
table: Union["pd.DataFrame", List["pd.DataFrame"]],
query: Optional[List[TextInput]] = None,
answer: List[str] = None,
add_special_tokens: bool = True,
padding: Union[bool, str, PaddingStrategy] = False,
truncation: Union[bool, str] = ... |
<Tip warning={true}>
This method is deprecated, `__call__` should be used instead.
</Tip>
| batch_encode_plus | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapex/tokenization_tapex.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapex/tokenization_tapex.py | Apache-2.0 |
def _batch_prepare_for_model(
self,
table: Union["pd.DataFrame", List["pd.DataFrame"]],
query: Optional[Union[TextInput, List[TextInput]]] = None,
answer: Optional[Union[str, List[str]]] = None,
add_special_tokens: bool = True,
padding_strategy: PaddingStrategy = PaddingS... |
This method adds special tokens, truncates sequences if overflowing while taking into account the special
tokens and manages a moving window (with user defined stride) for overflowing tokens.
| _batch_prepare_for_model | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapex/tokenization_tapex.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapex/tokenization_tapex.py | Apache-2.0 |
def encode(
self,
table: "pd.DataFrame",
query: Optional[TextInput] = None,
answer: Optional[str] = None,
add_special_tokens: bool = True,
padding: Union[bool, str, PaddingStrategy] = False,
truncation: Union[bool, str, TruncationStrategy, TapexTruncationStrategy]... |
Prepare a table, a string and possible answer for the model. This method does not return token type IDs,
attention masks, etc. which are necessary for the model to work correctly. Use this method if you want to build
your processing on your own, otherwise refer to `__call__`.
| encode | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapex/tokenization_tapex.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapex/tokenization_tapex.py | Apache-2.0 |
def target_call_func(
self,
answer: Union[str, List[str]],
add_special_tokens: bool = True,
padding: Union[bool, str, PaddingStrategy] = False,
truncation: Union[bool, str, TruncationStrategy] = None,
max_length: Optional[int] = None,
stride: int = 0,
pad_... |
The method tokenizes and prepares the answer label for the model.
Args:
answer (`str` or `List[str]`):
Corresponding answer supervision to the queries for training the model.
| target_call_func | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapex/tokenization_tapex.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapex/tokenization_tapex.py | Apache-2.0 |
def target_batch_encode_plus(
self,
answer: List[str],
add_special_tokens: bool = True,
padding: Union[bool, str, PaddingStrategy] = False,
truncation: Union[bool, str] = None,
max_length: Optional[int] = None,
pad_to_multiple_of: Optional[int] = None,
ret... |
Prepare answer strings for the model.
Args:
answer `List[str]`:
Corresponding answer supervision to the queries for training the model.
| target_batch_encode_plus | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapex/tokenization_tapex.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapex/tokenization_tapex.py | Apache-2.0 |
def target_encode(
self,
answer: str,
add_special_tokens: bool = True,
padding: Union[bool, str, PaddingStrategy] = False,
truncation: Union[bool, str, TruncationStrategy, TapexTruncationStrategy] = None,
max_length: Optional[int] = None,
return_tensors: Optional[... |
Prepare the answer string for the model. This method does not return token type IDs, attention masks, etc.
which are necessary for the model to work correctly. Use this method if you want to build your processing on
your own, otherwise refer to `__call__`.
Args:
answer `str... | target_encode | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapex/tokenization_tapex.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapex/tokenization_tapex.py | Apache-2.0 |
def target_encode_plus(
self,
answer: str,
add_special_tokens: bool = True,
padding: Union[bool, str, PaddingStrategy] = False,
truncation: Union[bool, str] = None,
max_length: Optional[int] = None,
pad_to_multiple_of: Optional[int] = None,
return_tensors:... |
Prepare a answer string for the model.
Args:
answer `str`:
Corresponding answer supervision to the queries for training the model.
| target_encode_plus | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapex/tokenization_tapex.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapex/tokenization_tapex.py | Apache-2.0 |
def prepare_table_query(
self,
table,
query,
answer=None,
truncation_strategy=Union[str, TruncationStrategy, TapexTruncationStrategy],
max_length=None,
):
"""
This method can be used to linearize a table and add a corresponding query.
Optional... |
This method can be used to linearize a table and add a corresponding query.
Optionally, it also handles truncation of the table (cells).
An answer can be provided for more precise truncation.
| prepare_table_query | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapex/tokenization_tapex.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapex/tokenization_tapex.py | Apache-2.0 |
def truncate_table_rows(
self, table_content: Dict, question: str, answer: Optional[Union[str, List[str]]] = None, max_length=None
):
"""
Args:
table_content:
{"header": xxx, "rows": xxx, "id" (Optionally): xxx}
question:
natural language sentence
... |
Args:
table_content:
{"header": xxx, "rows": xxx, "id" (Optionally): xxx}
question:
natural language sentence
answer:
if for training, is the supervision; otherwise will be empty
| truncate_table_rows | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapex/tokenization_tapex.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapex/tokenization_tapex.py | Apache-2.0 |
def delete_unrelated_rows(self, table_content: Dict, question: str, answer: List, delete_ratio: float):
"""
The argument answer is used only during training.
"""
truncated_unrelated_indices = []
related_indices = []
if answer is None or len(answer) == 0:
answe... |
The argument answer is used only during training.
| delete_unrelated_rows | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/tapex/tokenization_tapex.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/tapex/tokenization_tapex.py | Apache-2.0 |
def get_parameter_projection(self, in_features: int) -> nn.Module:
r"""
Return the parameter projection layer that maps the input to the appropriate parameters of the distribution.
"""
return ParameterProjection(
in_features=in_features,
args_dim=self.args_dim,
... |
Return the parameter projection layer that maps the input to the appropriate parameters of the distribution.
| get_parameter_projection | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/time_series_transformer/modeling_time_series_transformer.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/time_series_transformer/modeling_time_series_transformer.py | Apache-2.0 |
def weighted_average(input_tensor: torch.Tensor, weights: Optional[torch.Tensor] = None, dim=None) -> torch.Tensor:
"""
Computes the weighted average of a given tensor across a given `dim`, masking values associated with weight zero,
meaning instead of `nan * 0 = nan` you will get `0 * 0 = 0`.
Args:
... |
Computes the weighted average of a given tensor across a given `dim`, masking values associated with weight zero,
meaning instead of `nan * 0 = nan` you will get `0 * 0 = 0`.
Args:
input_tensor (`torch.FloatTensor`):
Input tensor, of which the average must be computed.
weights ... | weighted_average | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/time_series_transformer/modeling_time_series_transformer.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/time_series_transformer/modeling_time_series_transformer.py | Apache-2.0 |
def forward(
self,
attention_mask: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optio... |
Args:
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
- 1 for tokens that are **not masked**,
- 0 for tokens that are... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/time_series_transformer/modeling_time_series_transformer.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/time_series_transformer/modeling_time_series_transformer.py | Apache-2.0 |
def forward(
self,
attention_mask: Optional[torch.Tensor] = None,
encoder_hidden_states: Optional[torch.FloatTensor] = None,
encoder_attention_mask: Optional[torch.LongTensor] = None,
head_mask: Optional[torch.Tensor] = None,
cross_attn_head_mask: Optional[torch.Tensor] =... |
Args:
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
- 1 for tokens that are **not masked**,
- 0 for tokens that are... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/time_series_transformer/modeling_time_series_transformer.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/time_series_transformer/modeling_time_series_transformer.py | Apache-2.0 |
def get_lagged_subsequences(
self, sequence: torch.Tensor, subsequences_length: int, shift: int = 0
) -> torch.Tensor:
"""
Returns lagged subsequences of a given sequence. Returns a tensor of shape (N, S, C, I),
where S = subsequences_length and I = len(indices), containing lagge... |
Returns lagged subsequences of a given sequence. Returns a tensor of shape (N, S, C, I),
where S = subsequences_length and I = len(indices), containing lagged subsequences. Specifically, lagged[i,
j, :, k] = sequence[i, -indices[k]-S+j, :].
Args:
sequence: Tensor
... | get_lagged_subsequences | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/time_series_transformer/modeling_time_series_transformer.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/time_series_transformer/modeling_time_series_transformer.py | Apache-2.0 |
def forward(
self,
past_values: torch.Tensor,
past_time_features: torch.Tensor,
past_observed_mask: torch.Tensor,
static_categorical_features: torch.Tensor,
static_real_features: torch.Tensor,
future_values: Optional[torch.Tensor] = None,
future_time_featu... |
Returns:
Examples:
```python
>>> from huggingface_hub import hf_hub_download
>>> import torch
>>> from transformers import TimeSeriesTransformerModel
>>> file = hf_hub_download(
... repo_id="kashif/tourism-monthly-batch", filename="train-batch.pt",... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/time_series_transformer/modeling_time_series_transformer.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/time_series_transformer/modeling_time_series_transformer.py | Apache-2.0 |
def forward(
self,
past_values: torch.Tensor,
past_time_features: torch.Tensor,
past_observed_mask: torch.Tensor,
static_categorical_features: torch.Tensor,
static_real_features: torch.Tensor,
future_values: Optional[torch.Tensor] = None,
future_time_featu... |
Returns:
future_observed_mask (`torch.BoolTensor` of shape `(batch_size, sequence_length)`, *optional*):
Boolean mask to indicate which `future_values` were observed and which were missing. Mask values selected
in `[0, 1]`:
- 1 for values that are **observed**,
... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/time_series_transformer/modeling_time_series_transformer.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/time_series_transformer/modeling_time_series_transformer.py | Apache-2.0 |
def forward(self, input):
"""
Args:
input (`torch.FloatTensor` of shape `(B, n_models, input_dim)`):
The input to the layer.
"""
# [ batch_size x n_models x output_dim ]
output = torch.einsum("eoi,bei->beo", self.weight, input)
if self.bias is ... |
Args:
input (`torch.FloatTensor` of shape `(B, n_models, input_dim)`):
The input to the layer.
| forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/trajectory_transformer/modeling_trajectory_transformer.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/trajectory_transformer/modeling_trajectory_transformer.py | Apache-2.0 |
def forward(
self,
trajectories: Optional[torch.LongTensor] = None,
past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
targets: Optional[torch.FloatTensor] = None,
attention_mask: Optional[torch.FloatTensor] = None,
use_cache: Optional[bool] = None,
out... |
Returns:
Examples:
```python
>>> from transformers import TrajectoryTransformerModel
>>> import torch
>>> model = TrajectoryTransformerModel.from_pretrained(
... "CarlCochet/trajectory-transformer-halfcheetah-medium-v2"
... )
>>> model.to(d... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/trajectory_transformer/modeling_trajectory_transformer.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/trajectory_transformer/modeling_trajectory_transformer.py | Apache-2.0 |
def get_output_embeddings(self):
"""Double-check if you are using adaptive softmax."""
if len(self.crit.out_layers) > 0:
return self.crit.out_layers[-1]
return None | Double-check if you are using adaptive softmax. | get_output_embeddings | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/transfo_xl/modeling_tf_transfo_xl.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/transfo_xl/modeling_tf_transfo_xl.py | Apache-2.0 |
def build_tf_to_pytorch_map(model, config):
"""
A map of modules from TF to PyTorch. This time I use a map to keep the PyTorch model as identical to the original
PyTorch model as possible.
"""
tf_to_pt_map = {}
if hasattr(model, "transformer"):
# We are loading in a TransfoXLLMHeadModel... |
A map of modules from TF to PyTorch. This time I use a map to keep the PyTorch model as identical to the original
PyTorch model as possible.
| build_tf_to_pytorch_map | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/transfo_xl/modeling_transfo_xl.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/transfo_xl/modeling_transfo_xl.py | Apache-2.0 |
def resize_token_embeddings(self, new_num_tokens: Optional[int] = None, layer: Optional[int] = -1):
"""
Resize input token embeddings matrix of the model if new_num_tokens != config.vocab_size. Take care of tying
weights embeddings afterwards if the model class has a *tie_weights()* method.
... |
Resize input token embeddings matrix of the model if new_num_tokens != config.vocab_size. Take care of tying
weights embeddings afterwards if the model class has a *tie_weights()* method.
Arguments:
new_num_tokens: (*optional*) int:
New number of tokens in the embed... | resize_token_embeddings | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/transfo_xl/modeling_transfo_xl.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/transfo_xl/modeling_transfo_xl.py | Apache-2.0 |
def tie_weights(self):
"""
Run this to be sure output and input (adaptive) softmax weights are tied
"""
if self.config.tie_word_embeddings:
for i in range(len(self.crit.out_layers)):
self._tie_or_clone_weights(self.crit.out_layers[i], self.transformer.word_em... |
Run this to be sure output and input (adaptive) softmax weights are tied
| tie_weights | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/transfo_xl/modeling_transfo_xl.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/transfo_xl/modeling_transfo_xl.py | Apache-2.0 |
def forward(self, hidden, labels=None, keep_order=False):
"""
Params:
hidden :: [len*bsz x d_proj]
labels :: [len*bsz
Return:
if labels is None: out :: [len*bsz x n_tokens] log probabilities of tokens over the vocabulary else: out ::
[(len-1)*bsz]... |
Params:
hidden :: [len*bsz x d_proj]
labels :: [len*bsz
Return:
if labels is None: out :: [len*bsz x n_tokens] log probabilities of tokens over the vocabulary else: out ::
[(len-1)*bsz] Negative log likelihood. We could replace this implementation by the... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/transfo_xl/modeling_transfo_xl_utilities.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/transfo_xl/modeling_transfo_xl_utilities.py | Apache-2.0 |
def log_prob(self, hidden):
r"""
Computes log probabilities for all \\(n\_classes\\) From:
https://github.com/pytorch/pytorch/blob/master/torch/nn/modules/adaptive.p
Args:
hidden (Tensor): a minibatch of example
Returns:
log-probabilities of for each cla... |
Computes log probabilities for all \\(n\_classes\\) From:
https://github.com/pytorch/pytorch/blob/master/torch/nn/modules/adaptive.p
Args:
hidden (Tensor): a minibatch of example
Returns:
log-probabilities of for each class \\(c\\) in range \\(0 <= c <= n\_clas... | log_prob | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/transfo_xl/modeling_transfo_xl_utilities.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/transfo_xl/modeling_transfo_xl_utilities.py | Apache-2.0 |
def tokenize_numbers(text_array: List[str]) -> List[str]:
"""
Splits large comma-separated numbers and floating point values. This is done by replacing commas with ' @,@ ' and
dots with ' @.@ '.
Args:
text_array: An already tokenized text as list.
Returns:
A list of strings with to... |
Splits large comma-separated numbers and floating point values. This is done by replacing commas with ' @,@ ' and
dots with ' @.@ '.
Args:
text_array: An already tokenized text as list.
Returns:
A list of strings with tokenized numbers.
Example:
```python
>>> tokenize_nu... | tokenize_numbers | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/transfo_xl/tokenization_transfo_xl.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/transfo_xl/tokenization_transfo_xl.py | Apache-2.0 |
def detokenize_numbers(text: str) -> str:
"""
Inverts the operation of *tokenize_numbers*. This is replacing ' @,@ ' and ' @.@' by ',' and '.'.
Args:
text: A string where the number should be detokenized.
Returns:
A detokenized string.
Example:
```python
>>> detokenize_nu... |
Inverts the operation of *tokenize_numbers*. This is replacing ' @,@ ' and ' @.@' by ',' and '.'.
Args:
text: A string where the number should be detokenized.
Returns:
A detokenized string.
Example:
```python
>>> detokenize_numbers("$ 5 @,@ 000 1 @.@ 73 m")
"$ 5,000 1.73... | detokenize_numbers | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/transfo_xl/tokenization_transfo_xl.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/transfo_xl/tokenization_transfo_xl.py | Apache-2.0 |
def count_sents(self, sents, verbose=False):
"""
sents : a list of sentences, each a list of tokenized symbols
"""
if verbose:
logger.info(f"counting {len(sents)} sents ...")
for idx, symbols in enumerate(sents):
if verbose and idx > 0 and idx % 500000 == ... |
sents : a list of sentences, each a list of tokenized symbols
| count_sents | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/transfo_xl/tokenization_transfo_xl.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/transfo_xl/tokenization_transfo_xl.py | Apache-2.0 |
def move_added_token(self, token: str, target_idx: int):
"""
Moves an added token to a specific position in the vocab. This method should be used when resizing an embedding
layer other than the last one in the `AdaptiveEmbedding` in order to move the token in the tokenizer from the
defau... |
Moves an added token to a specific position in the vocab. This method should be used when resizing an embedding
layer other than the last one in the `AdaptiveEmbedding` in order to move the token in the tokenizer from the
default position (at the very end) to the desired one.
Args:
... | move_added_token | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/transfo_xl/tokenization_transfo_xl.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/transfo_xl/tokenization_transfo_xl.py | Apache-2.0 |
def moses_pipeline(self, text: str) -> List[str]:
"""
Does basic tokenization using [`sacremoses.MosesPunctNormalizer`] and [`sacremoses.MosesTokenizer`] with
*aggressive_dash_splits=True* (see [`sacremoses.tokenize.MosesTokenizer.tokenize`]). Additionally, large
comma-separated numbers ... |
Does basic tokenization using [`sacremoses.MosesPunctNormalizer`] and [`sacremoses.MosesTokenizer`] with
*aggressive_dash_splits=True* (see [`sacremoses.tokenize.MosesTokenizer.tokenize`]). Additionally, large
comma-separated numbers and floating point values are split. E.g. "23,000 people are ... | moses_pipeline | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/transfo_xl/tokenization_transfo_xl.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/transfo_xl/tokenization_transfo_xl.py | Apache-2.0 |
def __init__(self, data, bsz, bptt, device="cpu", ext_len=None):
"""
data -- LongTensor -- the LongTensor is strictly ordered
"""
self.bsz = bsz
self.bptt = bptt
self.ext_len = ext_len if ext_len is not None else 0
self.device = device
# Work out how cle... |
data -- LongTensor -- the LongTensor is strictly ordered
| __init__ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/transfo_xl/tokenization_transfo_xl.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/transfo_xl/tokenization_transfo_xl.py | Apache-2.0 |
def __init__(self, data, bsz, bptt, device="cpu", ext_len=None, shuffle=False):
"""
data -- list[LongTensor] -- there is no order among the LongTensors
"""
self.data = data
self.bsz = bsz
self.bptt = bptt
self.ext_len = ext_len if ext_len is not None else 0
... |
data -- list[LongTensor] -- there is no order among the LongTensors
| __init__ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/transfo_xl/tokenization_transfo_xl.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/transfo_xl/tokenization_transfo_xl.py | Apache-2.0 |
def convert_tr_ocr_checkpoint(checkpoint_url, pytorch_dump_folder_path):
"""
Copy/paste/tweak model's weights to our VisionEncoderDecoderModel structure.
"""
# define encoder and decoder configs based on checkpoint_url
encoder_config = ViTConfig(image_size=384, qkv_bias=False)
decoder_config = T... |
Copy/paste/tweak model's weights to our VisionEncoderDecoderModel structure.
| convert_tr_ocr_checkpoint | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/trocr/convert_trocr_unilm_to_pytorch.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/trocr/convert_trocr_unilm_to_pytorch.py | Apache-2.0 |
def forward(
self,
input_ids=None,
attention_mask=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
head_mask=None,
cross_attn_head_mask=None,
past_key_values=None,
inputs_embeds=None,
use_cache=None,
output_attentions=... |
Args:
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
provide it.
Indices can be obtained using [`TrOCRTokenizer`]. See [`PreTr... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/trocr/modeling_trocr.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/trocr/modeling_trocr.py | Apache-2.0 |
def forward(
self,
input_ids=None,
attention_mask=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
head_mask=None,
cross_attn_head_mask=None,
past_key_values=None,
inputs_embeds=None,
labels=None,
use_cache=None,
... |
Args:
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
provide it.
Indices can be obtained using [`TrOCRTokenizer`]. See [`PreTr... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/trocr/modeling_trocr.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/trocr/modeling_trocr.py | Apache-2.0 |
def __call__(self, *args, **kwargs):
"""
When used in normal mode, this method forwards all its arguments to AutoFeatureExtractor's
[`~AutoFeatureExtractor.__call__`] and returns its output. If used in the context
[`~TrOCRProcessor.as_target_processor`] this method forwards all its argum... |
When used in normal mode, this method forwards all its arguments to AutoFeatureExtractor's
[`~AutoFeatureExtractor.__call__`] and returns its output. If used in the context
[`~TrOCRProcessor.as_target_processor`] this method forwards all its arguments to TrOCRTokenizer's
[`~TrOCRTokeniz... | __call__ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/trocr/processing_trocr.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/trocr/processing_trocr.py | Apache-2.0 |
def compute_contrastive_logits(
target_features: torch.FloatTensor,
negative_features: torch.FloatTensor,
predicted_features: torch.FloatTensor,
temperature: int = 1,
):
"""
Compute logits for contrastive loss based using cosine similarity as the distance measure betw... |
Compute logits for contrastive loss based using cosine similarity as the distance measure between
`[positive_feature, negative_features]` and `[predicted_features]`. Additionally, temperature can be applied.
| compute_contrastive_logits | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/unispeech/modeling_unispeech.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/unispeech/modeling_unispeech.py | Apache-2.0 |
def forward(
self,
input_values: Optional[torch.Tensor],
attention_mask: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple, UniSpeechForPreTraining... |
mask_time_indices (`torch.BoolTensor` of shape `(batch_size, sequence_length)`, *optional*):
Indices to mask extracted features for contrastive loss. When in training mode, model learns to predict
masked extracted features in *config.proj_codevector_dim* space.
sampled_negative_... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/unispeech/modeling_unispeech.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/unispeech/modeling_unispeech.py | Apache-2.0 |
def forward(
self,
input_values: Optional[torch.Tensor],
attention_mask: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple, UniSpeechSatForPreTrain... |
Returns:
Example:
```python
>>> import torch
>>> from transformers import Wav2Vec2FeatureExtractor, UniSpeechSatForPreTraining
>>> from transformers.models.unispeech_sat.modeling_unispeech_sat import _compute_mask_indices
>>> feature_extractor = Wav2Vec2Featur... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/unispeech_sat/modeling_unispeech_sat.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/unispeech_sat/modeling_unispeech_sat.py | Apache-2.0 |
def __call__(
self, videos: ImageInput, return_tensors: Optional[Union[str, TensorType]] = None, **kwargs
) -> BatchFeature:
"""
Main method to prepare for the model one or several video(s).
<Tip warning={true}>
NumPy arrays are converted to PIL images when resizing, so the... |
Main method to prepare for the model one or several video(s).
<Tip warning={true}>
NumPy arrays are converted to PIL images when resizing, so the most efficient is to pass PIL images.
</Tip>
Args:
videos (`List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.T... | __call__ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/videomae/feature_extraction_videomae.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/videomae/feature_extraction_videomae.py | Apache-2.0 |
def forward(
self,
pixel_values,
bool_masked_pos=None,
head_mask=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
):
r"""
Returns:
Examples:
```python
>>> from decord import VideoReader, cpu
... |
Returns:
Examples:
```python
>>> from decord import VideoReader, cpu
>>> import numpy as np
>>> from transformers import VideoMAEFeatureExtractor, VideoMAEModel
>>> from huggingface_hub import hf_hub_download
>>> def sample_frame_indices(clip_len, fr... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/videomae/modeling_videomae.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/videomae/modeling_videomae.py | Apache-2.0 |
def forward(
self,
pixel_values,
bool_masked_pos,
head_mask=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
):
r"""
Returns:
Examples:
```python
>>> from transformers import VideoMAEFeatureExt... |
Returns:
Examples:
```python
>>> from transformers import VideoMAEFeatureExtractor, VideoMAEForPreTraining
>>> import numpy as np
>>> import torch
>>> num_frames = 16
>>> video = list(np.random.randn(16, 3, 224, 224))
>>> feature_extractor = Vi... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/videomae/modeling_videomae.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/videomae/modeling_videomae.py | Apache-2.0 |
def forward(
self,
pixel_values: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
labels: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = No... |
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
`config.n... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/videomae/modeling_videomae.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/videomae/modeling_videomae.py | Apache-2.0 |
def convert_vilt_checkpoint(checkpoint_url, pytorch_dump_folder_path):
"""
Copy/paste/tweak model's weights to our ViLT structure.
"""
# define configuration and initialize HuggingFace model
config = ViltConfig(image_size=384, patch_size=32, tie_word_embeddings=False)
mlm_model = False
vqa_... |
Copy/paste/tweak model's weights to our ViLT structure.
| convert_vilt_checkpoint | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/vilt/convert_vilt_original_to_pytorch.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/vilt/convert_vilt_original_to_pytorch.py | Apache-2.0 |
def pad_and_create_pixel_mask(
self, pixel_values_list: List["torch.Tensor"], return_tensors: Optional[Union[str, TensorType]] = None
):
"""
Pad images up to the largest image in a batch and create a corresponding `pixel_mask`.
Args:
pixel_values_list (`List[torch.Tensor... |
Pad images up to the largest image in a batch and create a corresponding `pixel_mask`.
Args:
pixel_values_list (`List[torch.Tensor]`):
List of images (pixel values) to be padded. Each image should be a tensor of shape (C, H, W).
return_tensors (`str` or [`~utils... | pad_and_create_pixel_mask | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/vilt/feature_extraction_vilt.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/vilt/feature_extraction_vilt.py | Apache-2.0 |
def __call__(
self,
images: ImageInput,
pad_and_return_pixel_mask: Optional[bool] = True,
return_tensors: Optional[Union[str, TensorType]] = None,
**kwargs
) -> BatchFeature:
"""
Main method to prepare for the model one or several image(s).
<Tip warni... |
Main method to prepare for the model one or several image(s).
<Tip warning={true}>
NumPy arrays and PyTorch tensors are converted to PIL images when resizing, so the most efficient is to pass
PIL images.
</Tip>
Args:
images (`PIL.Image.Image`, `np.ndarray... | __call__ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/vilt/feature_extraction_vilt.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/vilt/feature_extraction_vilt.py | Apache-2.0 |
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.FloatTensor] = None,
token_type_ids: Optional[torch.LongTensor] = None,
pixel_values: Optional[torch.FloatTensor] = None,
pixel_mask: Optional[torch.LongTensor] = None,
... |
Returns:
Examples:
```python
>>> from transformers import ViltProcessor, ViltModel
>>> from PIL import Image
>>> import requests
>>> # prepare image and text
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.o... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/vilt/modeling_vilt.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/vilt/modeling_vilt.py | Apache-2.0 |
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.FloatTensor] = None,
token_type_ids: Optional[torch.LongTensor] = None,
pixel_values: Optional[torch.FloatTensor] = None,
pixel_mask: Optional[torch.LongTensor] = None,
... |
labels (*torch.LongTensor* of shape *(batch_size, sequence_length)*, *optional*):
Labels for computing the masked language modeling loss. Indices should be in *[-100, 0, ...,
config.vocab_size]* (see *input_ids* docstring) Tokens with indices set to *-100* are ignored (masked), the
... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/vilt/modeling_vilt.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/vilt/modeling_vilt.py | Apache-2.0 |
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.FloatTensor] = None,
token_type_ids: Optional[torch.LongTensor] = None,
pixel_values: Optional[torch.FloatTensor] = None,
pixel_mask: Optional[torch.LongTensor] = None,
... |
labels (`torch.FloatTensor` of shape `(batch_size, num_labels)`, *optional*):
Labels for computing the visual question answering loss. This tensor must be either a one-hot encoding of
all answers that are applicable for a given example in the batch, or a soft encoding indicating which
... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/vilt/modeling_vilt.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/vilt/modeling_vilt.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.