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 forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
encoder_hidden_states: Optional[torch.Tensor] = None,
encoder_attention_mask: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
cross... |
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
the model is configured as a decoder.
encoder_attention_mask (... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/xlm_prophetnet/modeling_xlm_prophetnet.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/xlm_prophetnet/modeling_xlm_prophetnet.py | Apache-2.0 |
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
decoder_input_ids: Optional[torch.Tensor] = None,
decoder_attention_mask: Optional[torch.BoolTensor] = None,
head_mask: Optional[torch.Tensor] = None,
decod... |
Returns:
Example:
```python
>>> from transformers import XLMProphetNetTokenizer, XLMProphetNetModel
>>> tokenizer = XLMProphetNetTokenizer.from_pretrained("patrickvonplaten/xprophetnet-large-uncased-standalone")
>>> model = XLMProphetNetModel.from_pretrained("patrickv... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/xlm_prophetnet/modeling_xlm_prophetnet.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/xlm_prophetnet/modeling_xlm_prophetnet.py | Apache-2.0 |
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
decoder_input_ids: Optional[torch.Tensor] = None,
decoder_attention_mask: Optional[torch.BoolTensor] = None,
head_mask: Optional[torch.Tensor] = None,
decod... |
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the sequence classification/regression loss. Indices should be in `[-100, 0, ...,
config.vocab_size - 1]`. All labels set to `-100` are ignored (masked), the loss is only computed for
labe... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/xlm_prophetnet/modeling_xlm_prophetnet.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/xlm_prophetnet/modeling_xlm_prophetnet.py | Apache-2.0 |
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
encoder_hidden_states: Optional[torch.Tensor] = None,
encoder_attention_mask: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
cross... |
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
the model is configured as a decoder.
encoder_attention_mask (`... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/xlm_prophetnet/modeling_xlm_prophetnet.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/xlm_prophetnet/modeling_xlm_prophetnet.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]:
"""
Create a mask from the two sequences passed to be used in a sequence-pair classification task. XLMProphetNet
does not make use of token type ids, theref... |
Create a mask from the two sequences passed to be used in a sequence-pair classification task. XLMProphetNet
does not make use of token type ids, therefore a list of zeros is returned.
Args:
token_ids_0 (`List[int]`):
List of IDs.
token_ids_1 (`List[int]... | create_token_type_ids_from_sequences | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/xlm_prophetnet/tokenization_xlm_prophetnet.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/xlm_prophetnet/tokenization_xlm_prophetnet.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 XLMProphetNet seque... |
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
adding special tokens. A XLMProphetNet sequence has the following format:
- single sequence: `X [SEP]`
- pair of sequences: `A [SEP] B [SEP]`
Args:
token... | build_inputs_with_special_tokens | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/xlm_prophetnet/tokenization_xlm_prophetnet.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/xlm_prophetnet/tokenization_xlm_prophetnet.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,
position_ids: Optional[torch.LongTensor] = None,
head_mask: Optional[torch.FloatTensor] = None,
... |
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
the model is configured as a decoder.
encoder_attention_mask (... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/xlm_roberta/modeling_xlm_roberta.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/xlm_roberta/modeling_xlm_roberta.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,
position_ids: Optional[torch.LongTensor] = None,
head_mask: Optional[torch.FloatTensor] = None,
... |
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
the model is configured as a decoder.
encoder_attention_mask (... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/xlm_roberta_xl/modeling_xlm_roberta_xl.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/xlm_roberta_xl/modeling_xlm_roberta_xl.py | Apache-2.0 |
def rel_shift(self, x, klen=-1):
"""perform relative shift to form the relative attention score."""
x_size = shape_list(x)
x = tf.reshape(x, (x_size[1], x_size[0], x_size[2], x_size[3]))
x = x[1:, ...]
x = tf.reshape(x, (x_size[0], x_size[1] - 1, x_size[2], x_size[3]))
x... | perform relative shift to form the relative attention score. | rel_shift | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/xlnet/modeling_tf_xlnet.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/xlnet/modeling_tf_xlnet.py | Apache-2.0 |
def create_mask(self, qlen, mlen):
"""
Creates causal attention mask. Float mask where 1.0 indicates masked, 0.0 indicates not-masked.
Args:
qlen: TODO Lysandre didn't fill
mlen: TODO Lysandre didn't fill
```
same_length=False: same_lengt... |
Creates causal attention mask. Float mask where 1.0 indicates masked, 0.0 indicates not-masked.
Args:
qlen: TODO Lysandre didn't fill
mlen: TODO Lysandre didn't fill
```
same_length=False: same_length=True:
<mlen > < qlen > ... | create_mask | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/xlnet/modeling_tf_xlnet.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/xlnet/modeling_tf_xlnet.py | Apache-2.0 |
def call(
self,
input_ids: Optional[TFModelInputType] = None,
attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
mems: Optional[Union[np.ndarray, tf.Tensor]] = None,
perm_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
target_mapping: Optional[Union[np.nd... |
labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the cross entropy classification loss. Indices should be in `[0, ...,
config.vocab_size - 1]`.
Return:
Examples:
```python
>>> import tensorflow as tf
... | call | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/xlnet/modeling_tf_xlnet.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/xlnet/modeling_tf_xlnet.py | Apache-2.0 |
def build_tf_xlnet_to_pytorch_map(model, config, tf_weights=None):
"""
A map of modules from TF to PyTorch. 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"):
if hasattr(model, "lm_loss")... |
A map of modules from TF to PyTorch. I use a map to keep the PyTorch model as identical to the original PyTorch
model as possible.
| build_tf_xlnet_to_pytorch_map | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/xlnet/modeling_xlnet.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/xlnet/modeling_xlnet.py | Apache-2.0 |
def create_mask(self, qlen, mlen):
"""
Creates causal attention mask. Float mask where 1.0 indicates masked, 0.0 indicates not-masked.
Args:
qlen: Sequence length
mlen: Mask length
::
same_length=False: same_length=True: <mlen > < qlen > <mlen... |
Creates causal attention mask. Float mask where 1.0 indicates masked, 0.0 indicates not-masked.
Args:
qlen: Sequence length
mlen: Mask length
::
same_length=False: same_length=True: <mlen > < qlen > <mlen > < qlen >
^ [0 0 0 0 0 1 1 1 ... | create_mask | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/xlnet/modeling_xlnet.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/xlnet/modeling_xlnet.py | Apache-2.0 |
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
mems: Optional[torch.Tensor] = None,
perm_mask: Optional[torch.Tensor] = None,
target_mapping: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch... |
labels (`torch.LongTensor` of shape `(batch_size, num_predict)`, *optional*):
Labels for masked language modeling. `num_predict` corresponds to `target_mapping.shape[1]`. If
`target_mapping` is `None`, then `num_predict` corresponds to `sequence_length`.
The labels should c... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/xlnet/modeling_xlnet.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/xlnet/modeling_xlnet.py | Apache-2.0 |
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
mems: Optional[torch.Tensor] = None,
perm_mask: Optional[torch.Tensor] = None,
target_mapping: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch... |
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]`
where *num_choices* is the size of the second dimension of the input tensors. (see *input_ids* above)
| forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/xlnet/modeling_xlnet.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/xlnet/modeling_xlnet.py | Apache-2.0 |
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
mems: Optional[torch.Tensor] = None,
perm_mask: Optional[torch.Tensor] = None,
target_mapping: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch... |
start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for position (index) of the start of the labelled span for computing the token classification loss.
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/xlnet/modeling_xlnet.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/xlnet/modeling_xlnet.py | Apache-2.0 |
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: torch.Tensor,
causal_attention_mask: torch.Tensor,
output_attentions: Optional[bool] = False,
) -> Tuple[torch.FloatTensor]:
"""
Args:
hidden_states (`torch.FloatTensor`): input to the... |
Args:
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
attention_mask (`torch.FloatTensor`): attention mask of size
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/x_clip/modeling_x_clip.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/x_clip/modeling_x_clip.py | Apache-2.0 |
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bo... |
Returns:
Examples:
```python
>>> from transformers import CLIPTokenizer, XCLIPTextModel
>>> model = XCLIPTextModel.from_pretrained("microsoft/xclip-base-patch32")
>>> tokenizer = CLIPTokenizer.from_pretrained("microsoft/xclip-base-patch32")
>>> inputs = token... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/x_clip/modeling_x_clip.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/x_clip/modeling_x_clip.py | Apache-2.0 |
def forward(
self,
pixel_values: Optional[torch.FloatTensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple, BaseModelOutputWithPooling]:
r"""
Returns:
... |
Returns:
Examples:
```python
>>> from decord import VideoReader, cpu
>>> import torch
>>> import numpy as np
>>> from transformers import AutoProcessor, XCLIPVisionModel
>>> from huggingface_hub import hf_hub_download
>>> np.random.seed(0)
... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/x_clip/modeling_x_clip.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/x_clip/modeling_x_clip.py | Apache-2.0 |
def get_text_features(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: O... |
Returns:
text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by
applying the projection layer to the pooled output of [`XCLIPTextModel`].
Examples:
```python
>>> from transformers import AutoTokenizer, AutoModel
... | get_text_features | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/x_clip/modeling_x_clip.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/x_clip/modeling_x_clip.py | Apache-2.0 |
def get_video_features(
self,
pixel_values: Optional[torch.FloatTensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> torch.FloatTensor:
r"""
Returns:
video_f... |
Returns:
video_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The video embeddings obtained by
applying the projection layer to the pooled output of [`XCLIPVisionModel`] and
[`XCLIPMultiframeIntegrationTransformer`].
Examples:
```python
... | get_video_features | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/x_clip/modeling_x_clip.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/x_clip/modeling_x_clip.py | Apache-2.0 |
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
pixel_values: Optional[torch.FloatTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
return_loss: Optional[bool] = None,
output_attentions... |
Returns:
Examples:
```python
>>> from decord import VideoReader, cpu
>>> import torch
>>> import numpy as np
>>> from transformers import AutoProcessor, AutoModel
>>> from huggingface_hub import hf_hub_download
>>> np.random.seed(0)
... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/x_clip/modeling_x_clip.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/x_clip/modeling_x_clip.py | Apache-2.0 |
def __call__(self, text=None, videos=None, return_tensors=None, **kwargs):
"""
Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
and `kwargs` arguments to CLIPTokenizerFast's [`~CLIPTokenizerFast.__call__`] if `text` is not `None` to e... |
Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
and `kwargs` arguments to CLIPTokenizerFast's [`~CLIPTokenizerFast.__call__`] if `text` is not `None` to encode
the text. To prepare the image(s), this method forwards the `videos` and... | __call__ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/x_clip/processing_x_clip.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/x_clip/processing_x_clip.py | Apache-2.0 |
def __call__(
self,
images: ImageInput,
annotations: Union[List[Dict], List[List[Dict]]] = None,
return_segmentation_masks: Optional[bool] = False,
masks_path: Optional[pathlib.Path] = None,
padding: Optional[bool] = True,
return_tensors: Optional[Union[str, Tenso... |
Main method to prepare for the model one or several image(s) and optional annotations. Images are by default
padded up to the largest image in a batch.
<Tip warning={true}>
NumPy arrays and PyTorch tensors are converted to PIL images when resizing, so the most efficient is to pass
... | __call__ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/yolos/feature_extraction_yolos.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/yolos/feature_extraction_yolos.py | Apache-2.0 |
def pad(self, pixel_values_list: List["torch.Tensor"], return_tensors: Optional[Union[str, TensorType]] = None):
"""
Pad images up to the largest image in a batch.
Args:
pixel_values_list (`List[torch.Tensor]`):
List of images (pixel values) to be padded. Each image ... |
Pad images up to the largest image in a batch.
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.TensorType`], *optional*):
... | pad | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/yolos/feature_extraction_yolos.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/yolos/feature_extraction_yolos.py | Apache-2.0 |
def post_process_object_detection(
self, outputs, threshold: float = 0.5, target_sizes: Union[TensorType, List[Tuple]] = None
):
"""
Converts the output of [`YolosForObjectDetection`] into the format expected by the COCO api. Only supports
PyTorch.
Args:
outputs ... |
Converts the output of [`YolosForObjectDetection`] into the format expected by the COCO api. Only supports
PyTorch.
Args:
outputs ([`YolosObjectDetectionOutput`]):
Raw outputs of the model.
threshold (`float`, *optional*):
Score threshold... | post_process_object_detection | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/yolos/feature_extraction_yolos.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/yolos/feature_extraction_yolos.py | Apache-2.0 |
def forward(
self,
pixel_values: torch.FloatTensor,
labels: Optional[List[Dict]] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple, YolosObjectDetectionOutput]:
r... |
labels (`List[Dict]` of len `(batch_size,)`, *optional*):
Labels for computing the bipartite matching loss. List of dicts, each dictionary containing at least the
following 2 keys: `'class_labels'` and `'boxes'` (the class labels and bounding boxes of an image in the
batch r... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/models/yolos/modeling_yolos.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/models/yolos/modeling_yolos.py | Apache-2.0 |
def values_override(self) -> Optional[Mapping[str, Any]]:
"""
Dictionary of keys to override in the model's config before exporting
Returns:
Dictionary with the keys (and their corresponding values) to override
"""
if hasattr(self._config, "use_cache"):
r... |
Dictionary of keys to override in the model's config before exporting
Returns:
Dictionary with the keys (and their corresponding values) to override
| values_override | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/onnx/config.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/onnx/config.py | Apache-2.0 |
def is_torch_support_available(self) -> bool:
"""
The minimum PyTorch version required to export the model.
Returns:
`bool`: Whether the installed version of PyTorch is compatible with the model.
"""
if is_torch_available():
from transformers.utils import... |
The minimum PyTorch version required to export the model.
Returns:
`bool`: Whether the installed version of PyTorch is compatible with the model.
| is_torch_support_available | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/onnx/config.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/onnx/config.py | Apache-2.0 |
def use_external_data_format(num_parameters: int) -> bool:
"""
Flag indicating if the model requires using external data format
Args:
num_parameters: Number of parameter on the model
Returns:
True if model.num_parameters() * size_of(float32) >= 2Gb False otherwi... |
Flag indicating if the model requires using external data format
Args:
num_parameters: Number of parameter on the model
Returns:
True if model.num_parameters() * size_of(float32) >= 2Gb False otherwise
| use_external_data_format | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/onnx/config.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/onnx/config.py | Apache-2.0 |
def generate_dummy_inputs(
self,
preprocessor: Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"],
batch_size: int = -1,
seq_length: int = -1,
num_choices: int = -1,
is_pair: bool = False,
framework: Optional[TensorType] = None,
num_channels: int =... |
Generate inputs to provide to the ONNX exporter for the specific framework
Args:
preprocessor: ([`PreTrainedTokenizerBase`] or [`FeatureExtractionMixin`]):
The preprocessor associated with this model configuration.
batch_size (`int`, *optional*, defaults to -1):... | generate_dummy_inputs | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/onnx/config.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/onnx/config.py | Apache-2.0 |
def flatten_output_collection_property(cls, name: str, field: Iterable[Any]) -> Dict[str, Any]:
"""
Flatten any potential nested structure expanding the name of the field with the index of the element within the
structure.
Args:
name: The name of the nested structure
... |
Flatten any potential nested structure expanding the name of the field with the index of the element within the
structure.
Args:
name: The name of the nested structure
field: The structure to, potentially, be flattened
Returns:
(Dict[str, Any]): Out... | flatten_output_collection_property | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/onnx/config.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/onnx/config.py | Apache-2.0 |
def num_layers(self) -> int:
"""
The number of layers attribute retrieved from the model config. Override this for model configs where the
number of layers attribute is not called `num_layers`.
"""
if not hasattr(self._config, "num_layers"):
raise AttributeError(
... |
The number of layers attribute retrieved from the model config. Override this for model configs where the
number of layers attribute is not called `num_layers`.
| num_layers | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/onnx/config.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/onnx/config.py | Apache-2.0 |
def num_attention_heads(self) -> int:
"""
The number of attention heads attribute retrieved from the model config. Override this for model configs where
the number of attention heads attribute is not called `num_attention_heads`.
"""
if not hasattr(self._config, "num_attention_he... |
The number of attention heads attribute retrieved from the model config. Override this for model configs where
the number of attention heads attribute is not called `num_attention_heads`.
| num_attention_heads | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/onnx/config.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/onnx/config.py | Apache-2.0 |
def fill_with_past_key_values_(
self, inputs_or_outputs: Mapping[str, Mapping[int, str]], direction: str, inverted_values_shape: bool = False
):
"""
Fill the input_or_outputs mapping with past_key_values dynamic axes considering.
Args:
inputs_or_outputs: The mapping to f... |
Fill the input_or_outputs mapping with past_key_values dynamic axes considering.
Args:
inputs_or_outputs: The mapping to fill.
direction: either "inputs" or "outputs", it specifies whether input_or_outputs is the input mapping or the
output mapping, this is impo... | fill_with_past_key_values_ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/onnx/config.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/onnx/config.py | Apache-2.0 |
def export_pytorch(
preprocessor: Union["PreTrainedTokenizer", "FeatureExtractionMixin", "ProcessorMixin"],
model: "PreTrainedModel",
config: OnnxConfig,
opset: int,
output: Path,
tokenizer: "PreTrainedTokenizer" = None,
device: str = "cpu",
) -> Tuple[List[str], List[str]]:
"""
Expo... |
Export a PyTorch model to an ONNX Intermediate Representation (IR)
Args:
preprocessor: ([`PreTrainedTokenizer`], [`FeatureExtractionMixin`] or [`ProcessorMixin`]):
The preprocessor used for encoding the data.
model ([`PreTrainedModel`]):
The model to export.
con... | export_pytorch | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/onnx/convert.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/onnx/convert.py | Apache-2.0 |
def export_tensorflow(
preprocessor: Union["PreTrainedTokenizer", "FeatureExtractionMixin"],
model: "TFPreTrainedModel",
config: OnnxConfig,
opset: int,
output: Path,
tokenizer: "PreTrainedTokenizer" = None,
) -> Tuple[List[str], List[str]]:
"""
Export a TensorFlow model to an ONNX Inter... |
Export a TensorFlow model to an ONNX Intermediate Representation (IR)
Args:
preprocessor: ([`PreTrainedTokenizer`] or [`FeatureExtractionMixin`]):
The preprocessor used for encoding the data.
model ([`TFPreTrainedModel`]):
The model to export.
config ([`~onnx.co... | export_tensorflow | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/onnx/convert.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/onnx/convert.py | Apache-2.0 |
def export(
preprocessor: Union["PreTrainedTokenizer", "FeatureExtractionMixin", "ProcessorMixin"],
model: Union["PreTrainedModel", "TFPreTrainedModel"],
config: OnnxConfig,
opset: int,
output: Path,
tokenizer: "PreTrainedTokenizer" = None,
device: str = "cpu",
) -> Tuple[List[str], List[str... |
Export a Pytorch or TensorFlow model to an ONNX Intermediate Representation (IR)
Args:
preprocessor: ([`PreTrainedTokenizer`], [`FeatureExtractionMixin`] or [`ProcessorMixin`]):
The preprocessor used for encoding the data.
model ([`PreTrainedModel`] or [`TFPreTrainedModel`]):
... | export | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/onnx/convert.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/onnx/convert.py | Apache-2.0 |
def supported_features_mapping(
*supported_features: str, onnx_config_cls: str = None
) -> Dict[str, Callable[[PretrainedConfig], OnnxConfig]]:
"""
Generate the mapping between supported the features and their corresponding OnnxConfig for a given model.
Args:
*supported_features: The names of t... |
Generate the mapping between supported the features and their corresponding OnnxConfig for a given model.
Args:
*supported_features: The names of the supported features.
onnx_config_cls: The OnnxConfig full name corresponding to the model.
Returns:
The dictionary mapping a feature... | supported_features_mapping | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/onnx/features.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/onnx/features.py | Apache-2.0 |
def get_supported_features_for_model_type(
model_type: str, model_name: Optional[str] = None
) -> Dict[str, Callable[[PretrainedConfig], OnnxConfig]]:
"""
Tries to retrieve the feature -> OnnxConfig constructor map from the model type.
Args:
model_type (`str`):
... |
Tries to retrieve the feature -> OnnxConfig constructor map from the model type.
Args:
model_type (`str`):
The model type to retrieve the supported features for.
model_name (`str`, *optional*):
The name attribute of the model object, only used fo... | get_supported_features_for_model_type | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/onnx/features.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/onnx/features.py | Apache-2.0 |
def _validate_framework_choice(framework: str):
"""
Validates if the framework requested for the export is both correct and available, otherwise throws an
exception.
"""
if framework not in ["pt", "tf"]:
raise ValueError(
f"Only two frameworks are supp... |
Validates if the framework requested for the export is both correct and available, otherwise throws an
exception.
| _validate_framework_choice | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/onnx/features.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/onnx/features.py | Apache-2.0 |
def get_model_class_for_feature(feature: str, framework: str = "pt") -> Type:
"""
Attempts to retrieve an AutoModel class from a feature name.
Args:
feature (`str`):
The feature required.
framework (`str`, *optional*, defaults to `"pt"`):
... |
Attempts to retrieve an AutoModel class from a feature name.
Args:
feature (`str`):
The feature required.
framework (`str`, *optional*, defaults to `"pt"`):
The framework to use for the export.
Returns:
The AutoModel class co... | get_model_class_for_feature | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/onnx/features.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/onnx/features.py | Apache-2.0 |
def determine_framework(model: str, framework: str = None) -> str:
"""
Determines the framework to use for the export.
The priority is in the following order:
1. User input via `framework`.
2. If local checkpoint is provided, use the same framework as the checkpoint.
... |
Determines the framework to use for the export.
The priority is in the following order:
1. User input via `framework`.
2. If local checkpoint is provided, use the same framework as the checkpoint.
3. Available framework in environment, with priority given to PyTorch... | determine_framework | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/onnx/features.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/onnx/features.py | Apache-2.0 |
def get_model_from_feature(
feature: str, model: str, framework: str = None, cache_dir: str = None
) -> Union["PreTrainedModel", "TFPreTrainedModel"]:
"""
Attempts to retrieve a model from a model's name and the feature to be enabled.
Args:
feature (`str`):
... |
Attempts to retrieve a model from a model's name and the feature to be enabled.
Args:
feature (`str`):
The feature required.
model (`str`):
The name of the model to export.
framework (`str`, *optional*, defaults to `None`):
... | get_model_from_feature | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/onnx/features.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/onnx/features.py | Apache-2.0 |
def check_supported_model_or_raise(
model: Union["PreTrainedModel", "TFPreTrainedModel"], feature: str = "default"
) -> Tuple[str, Callable]:
"""
Check whether or not the model has the requested features.
Args:
model: The model to export.
feature: The name of... |
Check whether or not the model has the requested features.
Args:
model: The model to export.
feature: The name of the feature to check if it is available.
Returns:
(str) The type of the model (OnnxConfig) The OnnxConfig instance holding the model export pro... | check_supported_model_or_raise | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/onnx/features.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/onnx/features.py | Apache-2.0 |
def get_preprocessor(model_name: str) -> Optional[Union["AutoTokenizer", "AutoFeatureExtractor", "AutoProcessor"]]:
"""
Gets a preprocessor (tokenizer, feature extractor or processor) that is available for `model_name`.
Args:
model_name (`str`): Name of the model for which a preprocessor are loaded... |
Gets a preprocessor (tokenizer, feature extractor or processor) that is available for `model_name`.
Args:
model_name (`str`): Name of the model for which a preprocessor are loaded.
Returns:
`Optional[Union[AutoTokenizer, AutoFeatureExtractor, AutoProcessor]]`:
If a processor i... | get_preprocessor | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/onnx/utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/onnx/utils.py | Apache-2.0 |
def ffmpeg_read(bpayload: bytes, sampling_rate: int) -> np.array:
"""
Helper function to read an audio file through ffmpeg.
"""
ar = f"{sampling_rate}"
ac = "1"
format_for_conversion = "f32le"
ffmpeg_command = [
"ffmpeg",
"-i",
"pipe:0",
"-ac",
ac,
... |
Helper function to read an audio file through ffmpeg.
| ffmpeg_read | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/audio_classification.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/audio_classification.py | Apache-2.0 |
def __call__(
self,
inputs: Union[np.ndarray, bytes, str],
**kwargs,
):
"""
Classify the sequence(s) given as inputs. See the [`AutomaticSpeechRecognitionPipeline`] documentation for more
information.
Args:
inputs (`np.ndarray` or `bytes` or `str`... |
Classify the sequence(s) given as inputs. See the [`AutomaticSpeechRecognitionPipeline`] documentation for more
information.
Args:
inputs (`np.ndarray` or `bytes` or `str`):
The inputs is either a raw waveform (`np.ndarray` of shape (n, ) of type `np.float32` or `np... | __call__ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/audio_classification.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/audio_classification.py | Apache-2.0 |
def ffmpeg_microphone(
sampling_rate: int,
chunk_length_s: float,
format_for_conversion: str = "f32le",
):
"""
Helper function ro read raw microphone data.
"""
ar = f"{sampling_rate}"
ac = "1"
if format_for_conversion == "s16le":
size_of_sample = 2
elif format_for_convers... |
Helper function ro read raw microphone data.
| ffmpeg_microphone | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/audio_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/audio_utils.py | Apache-2.0 |
def ffmpeg_microphone_live(
sampling_rate: int,
chunk_length_s: float,
stream_chunk_s: Optional[int] = None,
stride_length_s: Optional[Union[Tuple[float, float], float]] = None,
format_for_conversion: str = "f32le",
):
"""
Helper function to read audio from the microphone file through ffmpeg... |
Helper function to read audio from the microphone file through ffmpeg. This will output `partial` overlapping
chunks starting from `stream_chunk_s` (if it is defined) until `chunk_length_s` is reached. It will make use of
striding to avoid errors on the "sides" of the various chunks.
Arguments:
... | ffmpeg_microphone_live | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/audio_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/audio_utils.py | Apache-2.0 |
def chunk_bytes_iter(iterator, chunk_len: int, stride: Tuple[int, int], stream: bool = False):
"""
Reads raw bytes from an iterator and does chunks of length `chunk_len`. Optionally adds `stride` to each chunks to
get overlaps. `stream` is used to return partial results even if a full `chunk_len` is not yet... |
Reads raw bytes from an iterator and does chunks of length `chunk_len`. Optionally adds `stride` to each chunks to
get overlaps. `stream` is used to return partial results even if a full `chunk_len` is not yet available.
| chunk_bytes_iter | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/audio_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/audio_utils.py | Apache-2.0 |
def _ffmpeg_stream(ffmpeg_command, buflen: int):
"""
Internal function to create the generator of data through ffmpeg
"""
bufsize = 2**24 # 16Mo
try:
with subprocess.Popen(ffmpeg_command, stdout=subprocess.PIPE, bufsize=bufsize) as ffmpeg_process:
while True:
raw... |
Internal function to create the generator of data through ffmpeg
| _ffmpeg_stream | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/audio_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/audio_utils.py | Apache-2.0 |
def rescale_stride(tokens_or_logits, stride, ratio):
"""
Rescales the stride values from audio space to tokens/logits space.
(160_000, 16_000, 16_000) -> (2000, 200, 200) for instance.
"""
# Shape is [B, SEQ] for tokens
# [B, SEQ, V] for logits
new_strides = []
for input_n, left, right... |
Rescales the stride values from audio space to tokens/logits space.
(160_000, 16_000, 16_000) -> (2000, 200, 200) for instance.
| rescale_stride | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/automatic_speech_recognition.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/automatic_speech_recognition.py | Apache-2.0 |
def __call__(
self,
inputs: Union[np.ndarray, bytes, str],
**kwargs,
):
"""
Classify the sequence(s) given as inputs. See the [`AutomaticSpeechRecognitionPipeline`] documentation for more
information.
Args:
inputs (`np.ndarray` or `bytes` or `str`... |
Classify the sequence(s) given as inputs. See the [`AutomaticSpeechRecognitionPipeline`] documentation for more
information.
Args:
inputs (`np.ndarray` or `bytes` or `str` or `dict`):
The inputs is either :
- `str` that is the filename of the aud... | __call__ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/automatic_speech_recognition.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/automatic_speech_recognition.py | Apache-2.0 |
def infer_framework_load_model(
model,
config: AutoConfig,
model_classes: Optional[Dict[str, Tuple[type]]] = None,
task: Optional[str] = None,
framework: Optional[str] = None,
**model_kwargs,
):
"""
Select framework (TensorFlow or PyTorch) to use from the `model` passed. Returns a tuple ... |
Select framework (TensorFlow or PyTorch) to use from the `model` passed. Returns a tuple (framework, model).
If `model` is instantiated, this function will just infer the framework from the model class. Otherwise `model` is
actually a checkpoint name and this method will try to instantiate it using `model... | infer_framework_load_model | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/base.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/base.py | Apache-2.0 |
def infer_framework_from_model(
model,
model_classes: Optional[Dict[str, Tuple[type]]] = None,
task: Optional[str] = None,
framework: Optional[str] = None,
**model_kwargs,
):
"""
Select framework (TensorFlow or PyTorch) to use from the `model` passed. Returns a tuple (framework, model).
... |
Select framework (TensorFlow or PyTorch) to use from the `model` passed. Returns a tuple (framework, model).
If `model` is instantiated, this function will just infer the framework from the model class. Otherwise `model` is
actually a checkpoint name and this method will try to instantiate it using `model... | infer_framework_from_model | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/base.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/base.py | Apache-2.0 |
def get_framework(model, revision: Optional[str] = None):
"""
Select framework (TensorFlow or PyTorch) to use.
Args:
model (`str`, [`PreTrainedModel`] or [`TFPreTrainedModel`]):
If both frameworks are installed, picks the one corresponding to the model passed (either a model class or
... |
Select framework (TensorFlow or PyTorch) to use.
Args:
model (`str`, [`PreTrainedModel`] or [`TFPreTrainedModel`]):
If both frameworks are installed, picks the one corresponding to the model passed (either a model class or
the model name). If no specific model is provided, defa... | get_framework | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/base.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/base.py | Apache-2.0 |
def get_default_model_and_revision(
targeted_task: Dict, framework: Optional[str], task_options: Optional[Any]
) -> Union[str, Tuple[str, str]]:
"""
Select a default model to use for a given task. Defaults to pytorch if ambiguous.
Args:
targeted_task (`Dict` ):
Dictionary representin... |
Select a default model to use for a given task. Defaults to pytorch if ambiguous.
Args:
targeted_task (`Dict` ):
Dictionary representing the given task, that should contain default models
framework (`str`, None)
"pt", "tf" or None, representing a specific framework if it... | get_default_model_and_revision | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/base.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/base.py | Apache-2.0 |
def save_binary(self, data: Union[dict, List[dict]]) -> str:
"""
Save the provided data object as a pickle-formatted binary data on the disk.
Args:
data (`dict` or list of `dict`): The data to store.
Returns:
`str`: Path where the data has been saved.
""... |
Save the provided data object as a pickle-formatted binary data on the disk.
Args:
data (`dict` or list of `dict`): The data to store.
Returns:
`str`: Path where the data has been saved.
| save_binary | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/base.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/base.py | Apache-2.0 |
def from_str(
format: str,
output_path: Optional[str],
input_path: Optional[str],
column: Optional[str],
overwrite=False,
) -> "PipelineDataFormat":
"""
Creates an instance of the right subclass of [`~pipelines.PipelineDataFormat`] depending on `format`.
... |
Creates an instance of the right subclass of [`~pipelines.PipelineDataFormat`] depending on `format`.
Args:
format: (`str`):
The format of the desired pipeline. Acceptable values are `"json"`, `"csv"` or `"pipe"`.
output_path (`str`, *optional*):
... | from_str | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/base.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/base.py | Apache-2.0 |
def save(self, data: List[dict]):
"""
Save the provided data object with the representation for the current [`~pipelines.PipelineDataFormat`].
Args:
data (`List[dict]`): The data to store.
"""
with open(self.output_path, "w") as f:
if len(data) > 0:
... |
Save the provided data object with the representation for the current [`~pipelines.PipelineDataFormat`].
Args:
data (`List[dict]`): The data to store.
| save | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/base.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/base.py | Apache-2.0 |
def save_pretrained(self, save_directory: str):
"""
Save the pipeline's model and tokenizer.
Args:
save_directory (`str`):
A path to the directory where to saved. It will be created if it doesn't exist.
"""
if os.path.isfile(save_directory):
... |
Save the pipeline's model and tokenizer.
Args:
save_directory (`str`):
A path to the directory where to saved. It will be created if it doesn't exist.
| save_pretrained | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/base.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/base.py | Apache-2.0 |
def device_placement(self):
"""
Context Manager allowing tensor allocation on the user-specified device in framework agnostic way.
Returns:
Context manager
Examples:
```python
# Explicitly ask for tensor allocation on CUDA device :0
pipe = pipeline(... |
Context Manager allowing tensor allocation on the user-specified device in framework agnostic way.
Returns:
Context manager
Examples:
```python
# Explicitly ask for tensor allocation on CUDA device :0
pipe = pipeline(..., device=0)
with pipe.device... | device_placement | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/base.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/base.py | Apache-2.0 |
def check_model_type(self, supported_models: Union[List[str], dict]):
"""
Check if the model class is in supported by the pipeline.
Args:
supported_models (`List[str]` or `dict`):
The list of models supported by the pipeline, or a dictionary with model class values.
... |
Check if the model class is in supported by the pipeline.
Args:
supported_models (`List[str]` or `dict`):
The list of models supported by the pipeline, or a dictionary with model class values.
| check_model_type | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/base.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/base.py | Apache-2.0 |
def add_user_input(self, text: str, overwrite: bool = False):
"""
Add a user input to the conversation for the next round. This populates the internal `new_user_input` field.
Args:
text (`str`): The user input for the next conversation round.
overwrite (`bool`, *optional... |
Add a user input to the conversation for the next round. This populates the internal `new_user_input` field.
Args:
text (`str`): The user input for the next conversation round.
overwrite (`bool`, *optional*, defaults to `False`):
Whether or not existing and unpr... | add_user_input | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/conversational.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/conversational.py | Apache-2.0 |
def mark_processed(self):
"""
Mark the conversation as processed (moves the content of `new_user_input` to `past_user_inputs`) and empties
the `new_user_input` field.
"""
if self.new_user_input:
self.past_user_inputs.append(self.new_user_input)
self.new_user_i... |
Mark the conversation as processed (moves the content of `new_user_input` to `past_user_inputs`) and empties
the `new_user_input` field.
| mark_processed | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/conversational.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/conversational.py | Apache-2.0 |
def iter_texts(self):
"""
Iterates over all blobs of the conversation.
Returns: Iterator of (is_user, text_chunk) in chronological order of the conversation. `is_user` is a `bool`,
`text_chunks` is a `str`.
"""
for user_input, generated_response in zip(self.past_user_inp... |
Iterates over all blobs of the conversation.
Returns: Iterator of (is_user, text_chunk) in chronological order of the conversation. `is_user` is a `bool`,
`text_chunks` is a `str`.
| iter_texts | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/conversational.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/conversational.py | Apache-2.0 |
def __repr__(self):
"""
Generates a string representation of the conversation.
Return:
`str`:
Example: Conversation id: 7d15686b-dc94-49f2-9c4b-c9eac6a1f114 user >> Going to the movies tonight - any
suggestions? bot >> The Big Lebowski
"""
ou... |
Generates a string representation of the conversation.
Return:
`str`:
Example: Conversation id: 7d15686b-dc94-49f2-9c4b-c9eac6a1f114 user >> Going to the movies tonight - any
suggestions? bot >> The Big Lebowski
| __repr__ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/conversational.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/conversational.py | Apache-2.0 |
def __call__(self, conversations: Union[Conversation, List[Conversation]], num_workers=0, **kwargs):
r"""
Generate responses for the conversation(s) given as inputs.
Args:
conversations (a [`Conversation`] or a list of [`Conversation`]):
Conversations to generate res... |
Generate responses for the conversation(s) given as inputs.
Args:
conversations (a [`Conversation`] or a list of [`Conversation`]):
Conversations to generate responses for.
clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
W... | __call__ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/conversational.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/conversational.py | Apache-2.0 |
def __call__(
self,
image: Union["Image.Image", str],
question: Optional[str] = None,
word_boxes: Tuple[str, List[float]] = None,
**kwargs,
):
"""
Answer the question(s) given as inputs by using the document(s). A document is defined as an image and an
... |
Answer the question(s) given as inputs by using the document(s). A document is defined as an image and an
optional list of (word, box) tuples which represent the text in the document. If the `word_boxes` are not
provided, it will use the Tesseract OCR engine (if available) to extract the words ... | __call__ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/document_question_answering.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/document_question_answering.py | Apache-2.0 |
def _get_bounding_box(self, box: "torch.Tensor") -> Dict[str, int]:
"""
Turns list [xmin, xmax, ymin, ymax] into dict { "xmin": xmin, ... }
Args:
box (`torch.Tensor`): Tensor containing the coordinates in corners format.
Returns:
bbox (`Dict[str, int]`): Dict co... |
Turns list [xmin, xmax, ymin, ymax] into dict { "xmin": xmin, ... }
Args:
box (`torch.Tensor`): Tensor containing the coordinates in corners format.
Returns:
bbox (`Dict[str, int]`): Dict containing the coordinates in corners format.
| _get_bounding_box | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/object_detection.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/object_detection.py | Apache-2.0 |
def __init__(self, loader, infer, params, loader_batch_size=None):
"""
Roughly equivalent to
```
for item in loader:
yield infer(item, **params)
```
Arguments:
loader (`torch.utils.data.DataLoader` or any iterator):
... |
Roughly equivalent to
```
for item in loader:
yield infer(item, **params)
```
Arguments:
loader (`torch.utils.data.DataLoader` or any iterator):
The iterator that will be used to apply `infer` on.
... | __init__ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/pt_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/pt_utils.py | Apache-2.0 |
def loader_batch_item(self):
"""
Return item located at `loader_batch_index` within the current `loader_batch_data`.
"""
if isinstance(self._loader_batch_data, torch.Tensor):
# Batch data is simple tensor, just fetch the slice
result = self._loader_batch_data[self... |
Return item located at `loader_batch_index` within the current `loader_batch_data`.
| loader_batch_item | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/pt_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/pt_utils.py | Apache-2.0 |
def decode_spans(
start: np.ndarray, end: np.ndarray, topk: int, max_answer_len: int, undesired_tokens: np.ndarray
) -> Tuple:
"""
Take the output of any `ModelForQuestionAnswering` and will generate probabilities for each span to be the actual
answer.
In addition, it filters out some unwanted/impo... |
Take the output of any `ModelForQuestionAnswering` and will generate probabilities for each span to be the actual
answer.
In addition, it filters out some unwanted/impossible cases like answer len being greater than max_answer_len or
answer end position being before the starting position. The method s... | decode_spans | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/question_answering.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/question_answering.py | Apache-2.0 |
def select_starts_ends(
start,
end,
p_mask,
attention_mask,
min_null_score=1000000,
top_k=1,
handle_impossible_answer=False,
max_answer_len=15,
):
"""
Takes the raw output of any `ModelForQuestionAnswering` and first normalizes its outputs and then uses
`decode_spans()` to ge... |
Takes the raw output of any `ModelForQuestionAnswering` and first normalizes its outputs and then uses
`decode_spans()` to generate probabilities for each span to be the actual answer.
Args:
start (`np.ndarray`): Individual start logits for each token.
end (`np.ndarray`): Individual end lo... | select_starts_ends | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/question_answering.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/question_answering.py | Apache-2.0 |
def create_sample(
question: Union[str, List[str]], context: Union[str, List[str]]
) -> Union[SquadExample, List[SquadExample]]:
"""
QuestionAnsweringPipeline leverages the [`SquadExample`] internally. This helper method encapsulate all the
logic for converting question(s) and contex... |
QuestionAnsweringPipeline leverages the [`SquadExample`] internally. This helper method encapsulate all the
logic for converting question(s) and context(s) to [`SquadExample`].
We currently support extractive question answering.
Arguments:
question (`str` or `List[str]`): ... | create_sample | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/question_answering.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/question_answering.py | Apache-2.0 |
def __call__(self, *args, **kwargs):
"""
Answer the question(s) given as inputs by using the context(s).
Args:
args ([`SquadExample`] or a list of [`SquadExample`]):
One or several [`SquadExample`] containing the question and context.
X ([`SquadExample`] ... |
Answer the question(s) given as inputs by using the context(s).
Args:
args ([`SquadExample`] or a list of [`SquadExample`]):
One or several [`SquadExample`] containing the question and context.
X ([`SquadExample`] or a list of [`SquadExample`], *optional*):
... | __call__ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/question_answering.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/question_answering.py | Apache-2.0 |
def span_to_answer(self, text: str, start: int, end: int) -> Dict[str, Union[str, int]]:
"""
When decoding from token probabilities, this method maps token indexes to actual word in the initial context.
Args:
text (`str`): The actual context to extract the answer from.
s... |
When decoding from token probabilities, this method maps token indexes to actual word in the initial context.
Args:
text (`str`): The actual context to extract the answer from.
start (`int`): The answer starting token index.
end (`int`): The answer end token index.
... | span_to_answer | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/question_answering.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/question_answering.py | Apache-2.0 |
def sequential_inference(self, **inputs):
"""
Inference used for models that need to process sequences in a sequential fashion, like the SQA models which
handle conversational query related to a table.
"""
if self.framework == "pt":
all_logits = []
all_agg... |
Inference used for models that need to process sequences in a sequential fashion, like the SQA models which
handle conversational query related to a table.
| sequential_inference | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/table_question_answering.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/table_question_answering.py | Apache-2.0 |
def __call__(self, *args, **kwargs):
r"""
Answers queries according to a table. The pipeline accepts several types of inputs which are detailed below:
- `pipeline(table, query)`
- `pipeline(table, [query])`
- `pipeline(table=table, query=query)`
- `pipeline(table=table, ... |
Answers queries according to a table. The pipeline accepts several types of inputs which are detailed below:
- `pipeline(table, query)`
- `pipeline(table, [query])`
- `pipeline(table=table, query=query)`
- `pipeline(table=table, query=[query])`
- `pipeline({"table": tab... | __call__ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/table_question_answering.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/table_question_answering.py | Apache-2.0 |
def __call__(self, *args, **kwargs):
r"""
Generate the output text(s) using text(s) given as inputs.
Args:
args (`str` or `List[str]`):
Input text for the encoder.
return_tensors (`bool`, *optional*, defaults to `False`):
Whether or not to... |
Generate the output text(s) using text(s) given as inputs.
Args:
args (`str` or `List[str]`):
Input text for the encoder.
return_tensors (`bool`, *optional*, defaults to `False`):
Whether or not to include the tensors of predictions (as token ind... | __call__ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/text2text_generation.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/text2text_generation.py | Apache-2.0 |
def check_inputs(self, input_length: int, min_length: int, max_length: int) -> bool:
"""
Checks whether there might be something wrong with given input with regard to the model.
"""
if max_length < min_length:
logger.warning(f"Your min_length={min_length} must be inferior tha... |
Checks whether there might be something wrong with given input with regard to the model.
| check_inputs | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/text2text_generation.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/text2text_generation.py | Apache-2.0 |
def __call__(self, *args, **kwargs):
"""
Classify the text(s) given as inputs.
Args:
args (`str` or `List[str]` or `Dict[str]`, or `List[Dict[str]]`):
One or several texts to classify. In order to use text pairs for your classification, you can send a
... |
Classify the text(s) given as inputs.
Args:
args (`str` or `List[str]` or `Dict[str]`, or `List[Dict[str]]`):
One or several texts to classify. In order to use text pairs for your classification, you can send a
dictionnary containing `{"text", "text_pair"}` ... | __call__ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/text_classification.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/text_classification.py | Apache-2.0 |
def __call__(self, inputs: Union[str, List[str]], **kwargs):
"""
Classify each token of the text(s) given as inputs.
Args:
inputs (`str` or `List[str]`):
One or several texts (or one list of texts) for token classification.
Return:
A list or a li... |
Classify each token of the text(s) given as inputs.
Args:
inputs (`str` or `List[str]`):
One or several texts (or one list of texts) for token classification.
Return:
A list or a list of list of `dict`: Each result comes as a list of dictionaries (one f... | __call__ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/token_classification.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/token_classification.py | Apache-2.0 |
def gather_pre_entities(
self,
sentence: str,
input_ids: np.ndarray,
scores: np.ndarray,
offset_mapping: Optional[List[Tuple[int, int]]],
special_tokens_mask: np.ndarray,
aggregation_strategy: AggregationStrategy,
) -> List[dict]:
"""Fuse various numpy... | Fuse various numpy arrays into dicts with all the information needed for aggregation | gather_pre_entities | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/token_classification.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/token_classification.py | Apache-2.0 |
def aggregate_words(self, entities: List[dict], aggregation_strategy: AggregationStrategy) -> List[dict]:
"""
Override tokens from a given word that disagree to force agreement on word boundaries.
Example: micro|soft| com|pany| B-ENT I-NAME I-ENT I-ENT will be rewritten with first strategy as m... |
Override tokens from a given word that disagree to force agreement on word boundaries.
Example: micro|soft| com|pany| B-ENT I-NAME I-ENT I-ENT will be rewritten with first strategy as microsoft|
company| B-ENT I-ENT
| aggregate_words | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/token_classification.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/token_classification.py | Apache-2.0 |
def group_sub_entities(self, entities: List[dict]) -> dict:
"""
Group together the adjacent tokens with the same entity predicted.
Args:
entities (`dict`): The entities predicted by the pipeline.
"""
# Get the first entity in the entity group
entity = entitie... |
Group together the adjacent tokens with the same entity predicted.
Args:
entities (`dict`): The entities predicted by the pipeline.
| group_sub_entities | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/token_classification.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/token_classification.py | Apache-2.0 |
def group_entities(self, entities: List[dict]) -> List[dict]:
"""
Find and group together the adjacent tokens with the same entity predicted.
Args:
entities (`dict`): The entities predicted by the pipeline.
"""
entity_groups = []
entity_group_disagg = []
... |
Find and group together the adjacent tokens with the same entity predicted.
Args:
entities (`dict`): The entities predicted by the pipeline.
| group_entities | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/token_classification.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/token_classification.py | Apache-2.0 |
def __call__(self, image: Union["Image.Image", str], question: str = None, **kwargs):
r"""
Answers open-ended questions about images. The pipeline accepts several types of inputs which are detailed
below:
- `pipeline(image=image, question=question)`
- `pipeline({"image": image, ... |
Answers open-ended questions about images. The pipeline accepts several types of inputs which are detailed
below:
- `pipeline(image=image, question=question)`
- `pipeline({"image": image, "question": question})`
- `pipeline([{"image": image, "question": question}])`
- `... | __call__ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/visual_question_answering.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/visual_question_answering.py | Apache-2.0 |
def _parse_and_tokenize(
self, sequence_pairs, padding=True, add_special_tokens=True, truncation=TruncationStrategy.ONLY_FIRST, **kwargs
):
"""
Parse arguments and tokenize only_first so that hypothesis (label) is not truncated
"""
return_tensors = self.framework
if s... |
Parse arguments and tokenize only_first so that hypothesis (label) is not truncated
| _parse_and_tokenize | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/zero_shot_classification.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/zero_shot_classification.py | Apache-2.0 |
def __call__(
self,
sequences: Union[str, List[str]],
*args,
**kwargs,
):
"""
Classify the sequence(s) given as inputs. See the [`ZeroShotClassificationPipeline`] documentation for more
information.
Args:
sequences (`str` or `List[str]`):
... |
Classify the sequence(s) given as inputs. See the [`ZeroShotClassificationPipeline`] documentation for more
information.
Args:
sequences (`str` or `List[str]`):
The sequence(s) to classify, will be truncated if the model input is too large.
candidate_lab... | __call__ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/zero_shot_classification.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/zero_shot_classification.py | Apache-2.0 |
def __call__(
self,
images: Union[str, List[str], "Image.Image", List["Image.Image"]],
text_queries: Union[str, List[str], List[List[str]]] = None,
**kwargs
):
"""
Detect objects (bounding boxes & classes) in the image(s) passed as inputs.
Args:
i... |
Detect objects (bounding boxes & classes) in the image(s) passed as inputs.
Args:
images (`str`, `List[str]`, `PIL.Image` or `List[PIL.Image]`):
The pipeline handles three types of images:
- A string containing an http url pointing to an image
... | __call__ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/pipelines/zero_shot_object_detection.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/pipelines/zero_shot_object_detection.py | Apache-2.0 |
def set_module_8bit_tensor_to_device(module, tensor_name, device, value=None):
"""
A helper function to set a given tensor (parameter of buffer) of a module on a specific device (note that doing
`param.to(device)` creates a new tensor not linked to the parameter, which is why we need this function). The
... |
A helper function to set a given tensor (parameter of buffer) of a module on a specific device (note that doing
`param.to(device)` creates a new tensor not linked to the parameter, which is why we need this function). The
function is adapted from `set_module_tensor_to_device` function from accelerate that ... | set_module_8bit_tensor_to_device | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/bitsandbytes.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/bitsandbytes.py | Apache-2.0 |
def replace_8bit_linear(model, threshold=6.0, modules_to_not_convert="lm_head"):
"""
A helper function to replace all `torch.nn.Linear` modules by `bnb.nn.Linear8bit` modules from the `bitsandbytes`
library. This will enable running your models using mixed int8 precision as described by the paper `GPT3.int8... |
A helper function to replace all `torch.nn.Linear` modules by `bnb.nn.Linear8bit` modules from the `bitsandbytes`
library. This will enable running your models using mixed int8 precision as described by the paper `GPT3.int8():
8-bit Matrix Multiplication for Transformers at Scale`. Make sure `bitsandbytes`... | replace_8bit_linear | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/bitsandbytes.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/bitsandbytes.py | Apache-2.0 |
def get_keys_to_not_convert(model):
r"""
An utility function to get the key of the module to keep in full precision if any For example for CausalLM modules
we may want to keep the lm_head in full precision for numerical stability reasons. For other architectures, we want
to keep the tied weights of the ... |
An utility function to get the key of the module to keep in full precision if any For example for CausalLM modules
we may want to keep the lm_head in full precision for numerical stability reasons. For other architectures, we want
to keep the tied weights of the model. The function will return a list of th... | get_keys_to_not_convert | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/bitsandbytes.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/bitsandbytes.py | Apache-2.0 |
def _get_indent(t):
"""Returns the indentation in the first line of t"""
search = re.search(r"^(\s*)\S", t)
return "" if search is None else search.groups()[0] | Returns the indentation in the first line of t | _get_indent | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/doc.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/doc.py | Apache-2.0 |
def _prepare_output_docstrings(output_type, config_class, min_indent=None):
"""
Prepares the return part of the docstring using `output_type`.
"""
output_docstring = output_type.__doc__
# Remove the head of the docstring to keep the list of args only
lines = output_docstring.split("\n")
i =... |
Prepares the return part of the docstring using `output_type`.
| _prepare_output_docstrings | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/doc.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/doc.py | Apache-2.0 |
def _proxies_to_metas(v):
"""Returns the underlying metadata for HFProxies, and behaves like the identity for the others."""
if isinstance(v, MetaDeviceAttribute):
return "meta"
if isinstance(v, torch.fx.Proxy):
if not (isinstance(v, HFProxy) and hasattr(v, "_metadata")):
raise R... | Returns the underlying metadata for HFProxies, and behaves like the identity for the others. | _proxies_to_metas | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/fx.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/fx.py | Apache-2.0 |
def _generate_dummy_input(
self, model: PreTrainedModel, input_name: str, shape: List[int]
) -> Dict[str, torch.Tensor]:
"""Generates dummy input for model inference recording."""
# Retrieving the model class, either from the "class_for_deserialization" attribute if the model was restored
... | Generates dummy input for model inference recording. | _generate_dummy_input | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/fx.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/fx.py | Apache-2.0 |
def trace(
self,
root: Union[torch.nn.Module, Callable[..., Any]],
concrete_args: Optional[Dict[str, Any]] = None,
dummy_inputs: Optional[Dict[str, Any]] = None,
complete_concrete_args_with_inputs_not_in_dummy_inputs: bool = True,
) -> Graph:
"""
Traces `root`... |
Traces `root` and returns the corresponding FX `torch.fx.Graph` representation. `root` can either be a
`torch.nn.Module` instance or a Python callable. Note that after this call, `self.root` may be different from
the `root` passed in here. For example, when a free function is passed to `trace()... | trace | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/fx.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/fx.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.