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, probabilities, temperature=1.0, eps=1e-4):
"""Compute the log binomial distribution for probabilities.
Args:
probabilities (`torch.Tensor` of shape `(batch_size, num_channels, height, width)`):
Tensor containing probabilities of each class.
temp... | Compute the log binomial distribution for probabilities.
Args:
probabilities (`torch.Tensor` of shape `(batch_size, num_channels, height, width)`):
Tensor containing probabilities of each class.
temperature (`float` or `torch.Tensor` of shape `(batch_size, num_channels, ... | forward | python | huggingface/transformers | src/transformers/models/zoedepth/modeling_zoedepth.py | https://github.com/huggingface/transformers/blob/master/src/transformers/models/zoedepth/modeling_zoedepth.py | Apache-2.0 |
def __init__(
self,
config,
in_features,
condition_dim,
n_classes=256,
bottleneck_factor=2,
):
"""Per-pixel MLP followed by a Conditional Log Binomial softmax.
Args:
in_features (`int`):
Number of input channels in the main... | Per-pixel MLP followed by a Conditional Log Binomial softmax.
Args:
in_features (`int`):
Number of input channels in the main feature.
condition_dim (`int`):
Number of input channels in the condition feature.
n_classes (`int`, *optional*, defa... | __init__ | python | huggingface/transformers | src/transformers/models/zoedepth/modeling_zoedepth.py | https://github.com/huggingface/transformers/blob/master/src/transformers/models/zoedepth/modeling_zoedepth.py | Apache-2.0 |
def forward(self, main_feature, condition_feature):
"""
Args:
main_feature (`torch.Tensor` of shape `(batch_size, num_channels, height, width)`):
Main feature.
condition_feature (torch.Tensor of shape `(batch_size, num_channels, height, width)`):
C... |
Args:
main_feature (`torch.Tensor` of shape `(batch_size, num_channels, height, width)`):
Main feature.
condition_feature (torch.Tensor of shape `(batch_size, num_channels, height, width)`):
Condition feature.
Returns:
`torch.Tensor`:... | forward | python | huggingface/transformers | src/transformers/models/zoedepth/modeling_zoedepth.py | https://github.com/huggingface/transformers/blob/master/src/transformers/models/zoedepth/modeling_zoedepth.py | Apache-2.0 |
def __init__(self, config, n_bins=16, mlp_dim=256, min_depth=1e-3, max_depth=10):
"""Bin center regressor network.
Can be "normed" or "unnormed". If "normed", bin centers are bounded on the (min_depth, max_depth) interval.
Args:
config (`int`):
Model configuration.
... | Bin center regressor network.
Can be "normed" or "unnormed". If "normed", bin centers are bounded on the (min_depth, max_depth) interval.
Args:
config (`int`):
Model configuration.
n_bins (`int`, *optional*, defaults to 16):
Number of bin centers... | __init__ | python | huggingface/transformers | src/transformers/models/zoedepth/modeling_zoedepth.py | https://github.com/huggingface/transformers/blob/master/src/transformers/models/zoedepth/modeling_zoedepth.py | Apache-2.0 |
def forward(self, x, prev_bin, prev_bin_embedding=None, interpolate=True):
"""
The forward pass of the attractor layer. This layer predicts the new bin centers based on the previous bin centers
and the attractor points (the latter are predicted by the MLP).
Args:
x (`torch.T... |
The forward pass of the attractor layer. This layer predicts the new bin centers based on the previous bin centers
and the attractor points (the latter are predicted by the MLP).
Args:
x (`torch.Tensor` of shape `(batch_size, num_channels, height, width)`):
Feature ... | forward | python | huggingface/transformers | src/transformers/models/zoedepth/modeling_zoedepth.py | https://github.com/huggingface/transformers/blob/master/src/transformers/models/zoedepth/modeling_zoedepth.py | Apache-2.0 |
def forward(self, x, prev_bin, prev_bin_embedding=None, interpolate=True):
"""
The forward pass of the attractor layer. This layer predicts the new bin centers based on the previous bin centers
and the attractor points (the latter are predicted by the MLP).
Args:
x (`torch.T... |
The forward pass of the attractor layer. This layer predicts the new bin centers based on the previous bin centers
and the attractor points (the latter are predicted by the MLP).
Args:
x (`torch.Tensor` of shape (batch_size, num_channels, height, width)`):
Feature b... | forward | python | huggingface/transformers | src/transformers/models/zoedepth/modeling_zoedepth.py | https://github.com/huggingface/transformers/blob/master/src/transformers/models/zoedepth/modeling_zoedepth.py | Apache-2.0 |
def __init__(self, in_features, out_features, mlp_dim=128):
"""Projector MLP.
Args:
in_features (`int`):
Number of input channels.
out_features (`int`):
Number of output channels.
mlp_dim (`int`, *optional*, defaults to 128):
... | Projector MLP.
Args:
in_features (`int`):
Number of input channels.
out_features (`int`):
Number of output channels.
mlp_dim (`int`, *optional*, defaults to 128):
Hidden dimension.
| __init__ | python | huggingface/transformers | src/transformers/models/zoedepth/modeling_zoedepth.py | https://github.com/huggingface/transformers/blob/master/src/transformers/models/zoedepth/modeling_zoedepth.py | Apache-2.0 |
def __init__(self, config):
"""ViT-like transformer block
Args:
config (`ZoeDepthConfig`):
Model configuration class defining the model architecture.
"""
super().__init__()
in_channels = config.bottleneck_features
self.transformer_encoder = ... | ViT-like transformer block
Args:
config (`ZoeDepthConfig`):
Model configuration class defining the model architecture.
| __init__ | python | huggingface/transformers | src/transformers/models/zoedepth/modeling_zoedepth.py | https://github.com/huggingface/transformers/blob/master/src/transformers/models/zoedepth/modeling_zoedepth.py | Apache-2.0 |
def positional_encoding_1d(self, batch_size, sequence_length, embedding_dim, device="cpu", dtype=torch.float32):
"""Generate positional encodings
Args:
sequence_length (int): Sequence length
embedding_dim (int): Embedding dimension
Returns:
torch.Tensor: Pos... | Generate positional encodings
Args:
sequence_length (int): Sequence length
embedding_dim (int): Embedding dimension
Returns:
torch.Tensor: Positional encodings.
| positional_encoding_1d | python | huggingface/transformers | src/transformers/models/zoedepth/modeling_zoedepth.py | https://github.com/huggingface/transformers/blob/master/src/transformers/models/zoedepth/modeling_zoedepth.py | Apache-2.0 |
def forward(self, x):
"""Forward pass
Args:
x (torch.Tensor - NCHW): Input feature tensor
Returns:
torch.Tensor - Transformer output embeddings of shape (batch_size, sequence_length, embedding_dim)
"""
embeddings = self.embedding_convPxP(x).flatten(2) #... | Forward pass
Args:
x (torch.Tensor - NCHW): Input feature tensor
Returns:
torch.Tensor - Transformer output embeddings of shape (batch_size, sequence_length, embedding_dim)
| forward | python | huggingface/transformers | src/transformers/models/zoedepth/modeling_zoedepth.py | https://github.com/huggingface/transformers/blob/master/src/transformers/models/zoedepth/modeling_zoedepth.py | Apache-2.0 |
def forward(
self,
pixel_values: torch.FloatTensor,
labels: Optional[torch.LongTensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple[torch.Tensor], DepthEstimatorOutp... |
labels (`torch.LongTensor` of shape `(batch_size, height, width)`, *optional*):
Ground truth depth estimation maps for computing the loss.
Examples:
```python
>>> from transformers import AutoImageProcessor, ZoeDepthForDepthEstimation
>>> import torch
>>> im... | forward | python | huggingface/transformers | src/transformers/models/zoedepth/modeling_zoedepth.py | https://github.com/huggingface/transformers/blob/master/src/transformers/models/zoedepth/modeling_zoedepth.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 | huggingface/transformers | src/transformers/pipelines/audio_classification.py | https://github.com/huggingface/transformers/blob/master/src/transformers/pipelines/audio_classification.py | Apache-2.0 |
def ffmpeg_microphone(
sampling_rate: int,
chunk_length_s: float,
format_for_conversion: str = "f32le",
ffmpeg_input_device: Optional[str] = None,
ffmpeg_additional_args: Optional[list[str]] = None,
):
"""
Helper function to read audio from a microphone using ffmpeg. The default input device... |
Helper function to read audio from a microphone using ffmpeg. The default input device will be used unless another
input device is specified using the `ffmpeg_input_device` argument. Uses 'alsa' on Linux, 'avfoundation' on MacOS and
'dshow' on Windows.
Arguments:
sampling_rate (`int`):
... | ffmpeg_microphone | python | huggingface/transformers | src/transformers/pipelines/audio_utils.py | https://github.com/huggingface/transformers/blob/master/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",
ffmpeg_input_device: Optional[str] = None,
ffmpeg_additional_args: Optional[... |
Helper function to read audio from a microphone using 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. The default input device will b... | ffmpeg_microphone_live | python | huggingface/transformers | src/transformers/pipelines/audio_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/pipelines/audio_utils.py | Apache-2.0 |
def _get_microphone_name():
"""
Retrieve the microphone name in Windows .
"""
command = ["ffmpeg", "-list_devices", "true", "-f", "dshow", "-i", ""]
try:
ffmpeg_devices = subprocess.run(command, text=True, stderr=subprocess.PIPE, encoding="utf-8")
microphone_lines = [line for line i... |
Retrieve the microphone name in Windows .
| _get_microphone_name | python | huggingface/transformers | src/transformers/pipelines/audio_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/pipelines/audio_utils.py | Apache-2.0 |
def __call__(
self,
inputs: Union[np.ndarray, bytes, str],
**kwargs,
):
"""
Transcribe the audio sequence(s) given as inputs to text. See the [`AutomaticSpeechRecognitionPipeline`]
documentation for more information.
Args:
inputs (`np.ndarray` or ... |
Transcribe the audio sequence(s) given as inputs to text. See the [`AutomaticSpeechRecognitionPipeline`]
documentation for more information.
Args:
inputs (`np.ndarray` or `bytes` or `str` or `dict`):
The inputs is either :
- `str` that is either ... | __call__ | python | huggingface/transformers | src/transformers/pipelines/automatic_speech_recognition.py | https://github.com/huggingface/transformers/blob/master/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 | huggingface/transformers | src/transformers/pipelines/base.py | https://github.com/huggingface/transformers/blob/master/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 | huggingface/transformers | src/transformers/pipelines/base.py | https://github.com/huggingface/transformers/blob/master/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 | huggingface/transformers | src/transformers/pipelines/base.py | https://github.com/huggingface/transformers/blob/master/src/transformers/pipelines/base.py | Apache-2.0 |
def get_default_model_and_revision(
targeted_task: Dict, framework: Optional[str], task_options: Optional[Any]
) -> Tuple[str, str]:
"""
Select a default model to use for a given task. Defaults to pytorch if ambiguous.
Args:
targeted_task (`Dict`):
Dictionary representing the given t... |
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 | huggingface/transformers | src/transformers/pipelines/base.py | https://github.com/huggingface/transformers/blob/master/src/transformers/pipelines/base.py | Apache-2.0 |
def load_assistant_model(
model: "PreTrainedModel",
assistant_model: Optional[Union[str, "PreTrainedModel"]],
assistant_tokenizer: Optional[PreTrainedTokenizer],
) -> Tuple[Optional["PreTrainedModel"], Optional[PreTrainedTokenizer]]:
"""
Prepares the assistant model and the assistant tokenizer for a... |
Prepares the assistant model and the assistant tokenizer for a pipeline whose model that can call `generate`.
Args:
model ([`PreTrainedModel`]):
The main model that will be used by the pipeline to make predictions.
assistant_model (`str` or [`PreTrainedModel`], *optional*):
... | load_assistant_model | python | huggingface/transformers | src/transformers/pipelines/base.py | https://github.com/huggingface/transformers/blob/master/src/transformers/pipelines/base.py | Apache-2.0 |
def save_pretrained(
self,
save_directory: Union[str, os.PathLike],
safe_serialization: bool = True,
**kwargs,
):
"""
Save the pipeline's model and tokenizer.
Args:
save_directory (`str` or `os.PathLike`):
A path to the directory w... |
Save the pipeline's model and tokenizer.
Args:
save_directory (`str` or `os.PathLike`):
A path to the directory where to saved. It will be created if it doesn't exist.
safe_serialization (`str`):
Whether to save the model using `safetensors` or t... | save_pretrained | python | huggingface/transformers | src/transformers/pipelines/base.py | https://github.com/huggingface/transformers/blob/master/src/transformers/pipelines/base.py | Apache-2.0 |
def __call__(self, inputs: Union[str, List[str], "Image.Image", List["Image.Image"]] = None, **kwargs):
"""
Predict the depth(s) of the image(s) passed as inputs.
Args:
inputs (`str`, `List[str]`, `PIL.Image` or `List[PIL.Image]`):
The pipeline handles three types of... |
Predict the depth(s) of the image(s) passed as inputs.
Args:
inputs (`str`, `List[str]`, `PIL.Image` or `List[PIL.Image]`):
The pipeline handles three types of images:
- A string containing a http link pointing to an image
- A string contain... | __call__ | python | huggingface/transformers | src/transformers/pipelines/depth_estimation.py | https://github.com/huggingface/transformers/blob/master/src/transformers/pipelines/depth_estimation.py | Apache-2.0 |
def __call__(self, inputs: Union[str, List[str], "Image.Image", List["Image.Image"]] = None, **kwargs):
"""
Assign labels to the image(s) passed as inputs.
Args:
inputs (`str`, `List[str]`, `PIL.Image` or `List[PIL.Image]`):
The pipeline handles three types of images... |
Assign labels to the image(s) passed as inputs.
Args:
inputs (`str`, `List[str]`, `PIL.Image` or `List[PIL.Image]`):
The pipeline handles three types of images:
- A string containing a http link pointing to an image
- A string containing a l... | __call__ | python | huggingface/transformers | src/transformers/pipelines/image_classification.py | https://github.com/huggingface/transformers/blob/master/src/transformers/pipelines/image_classification.py | Apache-2.0 |
def __call__(self, inputs=None, **kwargs) -> Union[Predictions, List[Prediction]]:
"""
Perform segmentation (detect masks & classes) in the image(s) passed as inputs.
Args:
inputs (`str`, `List[str]`, `PIL.Image` or `List[PIL.Image]`):
The pipeline handles three type... |
Perform segmentation (detect masks & classes) in the image(s) passed as inputs.
Args:
inputs (`str`, `List[str]`, `PIL.Image` or `List[PIL.Image]`):
The pipeline handles three types of images:
- A string containing an HTTP(S) link pointing to an image
... | __call__ | python | huggingface/transformers | src/transformers/pipelines/image_segmentation.py | https://github.com/huggingface/transformers/blob/master/src/transformers/pipelines/image_segmentation.py | Apache-2.0 |
def add_images_to_messages(
messages: dict, images: Optional[Union[str, List[str], "Image.Image", List["Image.Image"]]]
):
"""
Retrieve and combine images from the chat and the images passed as input.
"""
if images is None:
images = []
elif not isinstance(images, Iterable) or isinstance(... |
Retrieve and combine images from the chat and the images passed as input.
| add_images_to_messages | python | huggingface/transformers | src/transformers/pipelines/image_text_to_text.py | https://github.com/huggingface/transformers/blob/master/src/transformers/pipelines/image_text_to_text.py | Apache-2.0 |
def __call__(self, inputs: Union[str, List[str], "Image.Image", List["Image.Image"]] = None, **kwargs):
"""
Assign labels to the image(s) passed as inputs.
Args:
inputs (`str`, `List[str]`, `PIL.Image` or `List[PIL.Image]`):
The pipeline handles three types of images... |
Assign labels to the image(s) passed as inputs.
Args:
inputs (`str`, `List[str]`, `PIL.Image` or `List[PIL.Image]`):
The pipeline handles three types of images:
- A string containing a HTTP(s) link pointing to an image
- A string containing ... | __call__ | python | huggingface/transformers | src/transformers/pipelines/image_to_text.py | https://github.com/huggingface/transformers/blob/master/src/transformers/pipelines/image_to_text.py | Apache-2.0 |
def __call__(self, *args, **kwargs) -> Union[Predictions, List[Prediction]]:
"""
Detect objects (bounding boxes & classes) in the image(s) passed as inputs.
Args:
inputs (`str`, `List[str]`, `PIL.Image` or `List[PIL.Image]`):
The pipeline handles three types of image... |
Detect objects (bounding boxes & classes) in the image(s) passed as inputs.
Args:
inputs (`str`, `List[str]`, `PIL.Image` or `List[PIL.Image]`):
The pipeline handles three types of images:
- A string containing an HTTP(S) link pointing to an image
... | __call__ | python | huggingface/transformers | src/transformers/pipelines/object_detection.py | https://github.com/huggingface/transformers/blob/master/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 `Iterable`):
... |
Roughly equivalent to
```
for item in loader:
yield infer(item, **params)
```
Arguments:
loader (`torch.utils.data.DataLoader` or `Iterable`):
The iterator that will be used to apply `infer` on.
... | __init__ | python | huggingface/transformers | src/transformers/pipelines/pt_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/pipelines/pt_utils.py | Apache-2.0 |
def __call__(self, *args, **kwargs):
"""
Answer the question(s) given as inputs by using the context(s).
Args:
question (`str` or `List[str]`):
One or several question(s) (must be used in conjunction with the `context` argument).
context (`str` or `List[s... |
Answer the question(s) given as inputs by using the context(s).
Args:
question (`str` or `List[str]`):
One or several question(s) (must be used in conjunction with the `context` argument).
context (`str` or `List[str]`):
One or several context(s)... | __call__ | python | huggingface/transformers | src/transformers/pipelines/question_answering.py | https://github.com/huggingface/transformers/blob/master/src/transformers/pipelines/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 | huggingface/transformers | src/transformers/pipelines/text2text_generation.py | https://github.com/huggingface/transformers/blob/master/src/transformers/pipelines/text2text_generation.py | Apache-2.0 |
def __call__(self, inputs, **kwargs):
"""
Classify the text(s) given as inputs.
Args:
inputs (`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:
inputs (`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
dictionary containing `{"text", "text_pair"}`... | __call__ | python | huggingface/transformers | src/transformers/pipelines/text_classification.py | https://github.com/huggingface/transformers/blob/master/src/transformers/pipelines/text_classification.py | Apache-2.0 |
def __call__(self, inputs: Optional[Union[str, List[str]]] = None, **kwargs):
"""
Assign labels to the video(s) passed as inputs.
Args:
inputs (`str`, `List[str]`):
The pipeline handles three types of videos:
- A string containing a http link pointin... |
Assign labels to the video(s) passed as inputs.
Args:
inputs (`str`, `List[str]`):
The pipeline handles three types of videos:
- A string containing a http link pointing to a video
- A string containing a local path to a video
... | __call__ | python | huggingface/transformers | src/transformers/pipelines/video_classification.py | https://github.com/huggingface/transformers/blob/master/src/transformers/pipelines/video_classification.py | Apache-2.0 |
def __call__(
self,
image: Union["Image.Image", str, List["Image.Image"], List[str], "KeyDataset"],
question: Optional[Union[str, List[str]]] = None,
**kwargs,
):
r"""
Answers open-ended questions about images. The pipeline accepts several types of inputs which are de... |
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 | huggingface/transformers | src/transformers/pipelines/visual_question_answering.py | https://github.com/huggingface/transformers/blob/master/src/transformers/pipelines/visual_question_answering.py | Apache-2.0 |
def __call__(self, image: Union[str, List[str], "Image", List["Image"]] = None, **kwargs):
"""
Assign labels to the image(s) passed as inputs.
Args:
image (`str`, `List[str]`, `PIL.Image` or `List[PIL.Image]`):
The pipeline handles three types of images:
... |
Assign labels to the image(s) passed as inputs.
Args:
image (`str`, `List[str]`, `PIL.Image` or `List[PIL.Image]`):
The pipeline handles three types of images:
- A string containing a http link pointing to an image
- A string containing a lo... | __call__ | python | huggingface/transformers | src/transformers/pipelines/zero_shot_image_classification.py | https://github.com/huggingface/transformers/blob/master/src/transformers/pipelines/zero_shot_image_classification.py | Apache-2.0 |
def merge_quantization_configs(
cls,
quantization_config: Union[dict, QuantizationConfigMixin],
quantization_config_from_args: Optional[QuantizationConfigMixin],
):
"""
handles situations where both quantization_config from args and quantization_config from model config are p... |
handles situations where both quantization_config from args and quantization_config from model config are present.
| merge_quantization_configs | python | huggingface/transformers | src/transformers/quantizers/auto.py | https://github.com/huggingface/transformers/blob/master/src/transformers/quantizers/auto.py | Apache-2.0 |
def get_special_dtypes_update(self, model, torch_dtype: "torch.dtype") -> Dict[str, "torch.dtype"]:
"""
returns dtypes for modules that are not quantized - used for the computation of the device_map in case
one passes a str as a device_map. The method will use the `modules_to_not_convert` that i... |
returns dtypes for modules that are not quantized - used for the computation of the device_map in case
one passes a str as a device_map. The method will use the `modules_to_not_convert` that is modified
in `_process_model_before_weight_loading`.
Args:
model (`~transformers.... | get_special_dtypes_update | python | huggingface/transformers | src/transformers/quantizers/base.py | https://github.com/huggingface/transformers/blob/master/src/transformers/quantizers/base.py | Apache-2.0 |
def check_quantized_param(
self,
model: "PreTrainedModel",
param_value: "torch.Tensor",
param_name: str,
state_dict: Dict[str, Any],
**kwargs,
) -> bool:
"""
checks if a loaded state_dict component is part of quantized param + some validation; only def... |
checks if a loaded state_dict component is part of quantized param + some validation; only defined if
requires_parameters_quantization == True for quantization methods that require to create a new parameters
for quantization.
| check_quantized_param | python | huggingface/transformers | src/transformers/quantizers/base.py | https://github.com/huggingface/transformers/blob/master/src/transformers/quantizers/base.py | Apache-2.0 |
def create_quantized_param(self, *args, **kwargs) -> "torch.nn.Parameter":
"""
takes needed components from state_dict and creates quantized param; only applicable if
requires_parameters_quantization == True
"""
if not self.requires_parameters_quantization:
raise Attr... |
takes needed components from state_dict and creates quantized param; only applicable if
requires_parameters_quantization == True
| create_quantized_param | python | huggingface/transformers | src/transformers/quantizers/base.py | https://github.com/huggingface/transformers/blob/master/src/transformers/quantizers/base.py | Apache-2.0 |
def preprocess_model(self, model: "PreTrainedModel", **kwargs):
"""
Setting model attributes and/or converting model before weights loading. At this point
the model should be initialized on the meta device so you can freely manipulate the skeleton
of the model in order to replace modules... |
Setting model attributes and/or converting model before weights loading. At this point
the model should be initialized on the meta device so you can freely manipulate the skeleton
of the model in order to replace modules in-place. Make sure to override the abstract method `_process_model_before... | preprocess_model | python | huggingface/transformers | src/transformers/quantizers/base.py | https://github.com/huggingface/transformers/blob/master/src/transformers/quantizers/base.py | Apache-2.0 |
def dequantize(self, model):
"""
Potentially dequantize the model to retrieve the original model, with some loss in accuracy / performance.
Note not all quantization schemes support this.
"""
model = self._dequantize(model)
# Delete quantizer and quantization config
... |
Potentially dequantize the model to retrieve the original model, with some loss in accuracy / performance.
Note not all quantization schemes support this.
| dequantize | python | huggingface/transformers | src/transformers/quantizers/base.py | https://github.com/huggingface/transformers/blob/master/src/transformers/quantizers/base.py | Apache-2.0 |
def get_cuda_warm_up_factor(self):
"""
The factor to be used in `caching_allocator_warmup` to get the number of bytes to pre-allocate to warm up cuda.
A factor of 2 means we allocate all bytes in the empty model (since we allocate in fp16), a factor of 4 means
we allocate half the memory... |
The factor to be used in `caching_allocator_warmup` to get the number of bytes to pre-allocate to warm up cuda.
A factor of 2 means we allocate all bytes in the empty model (since we allocate in fp16), a factor of 4 means
we allocate half the memory of the weights residing in the empty model, e... | get_cuda_warm_up_factor | python | huggingface/transformers | src/transformers/quantizers/base.py | https://github.com/huggingface/transformers/blob/master/src/transformers/quantizers/base.py | Apache-2.0 |
def is_qat_trainable(self) -> bool:
"""Flag indicating whether the quantized model can carry out quantization aware training"""
return (
self.quantization_config.linear_class == "autobitlinear"
and self.quantization_config.quantization_mode == "online"
) | Flag indicating whether the quantized model can carry out quantization aware training | is_qat_trainable | python | huggingface/transformers | src/transformers/quantizers/quantizer_bitnet.py | https://github.com/huggingface/transformers/blob/master/src/transformers/quantizers/quantizer_bitnet.py | Apache-2.0 |
def create_quantized_param(
self,
model: "PreTrainedModel",
param_value: "torch.Tensor",
param_name: str,
target_device: "torch.device",
state_dict: Dict[str, Any],
unexpected_keys: Optional[List[str]] = None,
):
"""
combines logic from _load_s... |
combines logic from _load_state_dict_into_meta_model and .integrations.bitsandbytes.py::set_module_quantized_tensor_to_device()
| create_quantized_param | python | huggingface/transformers | src/transformers/quantizers/quantizer_bnb_4bit.py | https://github.com/huggingface/transformers/blob/master/src/transformers/quantizers/quantizer_bnb_4bit.py | Apache-2.0 |
def create_quantized_param(
self,
model: "PreTrainedModel",
param_value: "torch.Tensor",
param_name: str,
target_device: "torch.device",
state_dict: Dict[str, Any],
unexpected_keys: Optional[List[str]] = None,
):
"""
combines logic from _load_s... |
combines logic from _load_state_dict_into_meta_model and .integrations.bitsandbytes.py::set_module_quantized_tensor_to_device()
needs aux items from state dicts, if found - removes them from unexpected_keys
| create_quantized_param | python | huggingface/transformers | src/transformers/quantizers/quantizer_bnb_8bit.py | https://github.com/huggingface/transformers/blob/master/src/transformers/quantizers/quantizer_bnb_8bit.py | Apache-2.0 |
def update_missing_keys_after_loading(self, model, missing_keys: List[str], prefix: str) -> List[str]:
"""
Update missing keys after loading the model. This is necessary for compressed tensors
to load the model correctly. We expect weights to be present in missing keys.
The weight's are ... |
Update missing keys after loading the model. This is necessary for compressed tensors
to load the model correctly. We expect weights to be present in missing keys.
The weight's are re-constructed by ModelCompressor in _process_model_after_weight_loading
This function cleans up expected... | update_missing_keys_after_loading | python | huggingface/transformers | src/transformers/quantizers/quantizer_compressed_tensors.py | https://github.com/huggingface/transformers/blob/master/src/transformers/quantizers/quantizer_compressed_tensors.py | Apache-2.0 |
def update_unexpected_keys(self, model, unexpected_keys: List[str], prefix: str) -> List[str]:
"""
Override this method if you want to adjust the `unexpected_keys`.
Args:
unexpected_keys (`List[str]`, *optional*):
The list of unexpected keys in the checkpoint compare... |
Override this method if you want to adjust the `unexpected_keys`.
Args:
unexpected_keys (`List[str]`, *optional*):
The list of unexpected keys in the checkpoint compared to the state dict of the model
| update_unexpected_keys | python | huggingface/transformers | src/transformers/quantizers/quantizer_compressed_tensors.py | https://github.com/huggingface/transformers/blob/master/src/transformers/quantizers/quantizer_compressed_tensors.py | Apache-2.0 |
def _process_model_after_weight_loading(self, model, **kwargs):
"""Decompress loaded model if necessary - need for qat"""
if (
self.quantization_config.is_quantization_compressed and not self.run_compressed
) or self.quantization_config.is_sparsification_compressed:
conf... | Decompress loaded model if necessary - need for qat | _process_model_after_weight_loading | python | huggingface/transformers | src/transformers/quantizers/quantizer_compressed_tensors.py | https://github.com/huggingface/transformers/blob/master/src/transformers/quantizers/quantizer_compressed_tensors.py | Apache-2.0 |
def is_qat_trainable(self) -> bool:
"""Loaded Models can carry out quantization aware training"""
# models need to be decompressed carry out qat
return not self.run_compressed or not self.quantization_config.is_quantization_compressed | Loaded Models can carry out quantization aware training | is_qat_trainable | python | huggingface/transformers | src/transformers/quantizers/quantizer_compressed_tensors.py | https://github.com/huggingface/transformers/blob/master/src/transformers/quantizers/quantizer_compressed_tensors.py | Apache-2.0 |
def create_quantized_param(
self,
model: "PreTrainedModel",
param_value: "torch.Tensor",
param_name: str,
target_device: "torch.device",
state_dict: Dict[str, Any],
unexpected_keys: Optional[List[str]] = None,
):
"""
Quantizes weights to FP8 fo... |
Quantizes weights to FP8 format using Block-wise quantization
| create_quantized_param | python | huggingface/transformers | src/transformers/quantizers/quantizer_finegrained_fp8.py | https://github.com/huggingface/transformers/blob/master/src/transformers/quantizers/quantizer_finegrained_fp8.py | Apache-2.0 |
def create_quantized_param(
self,
model: "PreTrainedModel",
param_value: "torch.Tensor",
param_name: str,
target_device: "torch.device",
state_dict: Dict[str, Any],
unexpected_keys: List[str],
):
"""
Each nn.Linear layer is processed here.
... |
Each nn.Linear layer is processed here.
We first check if the corresponding module state_dict contains already HQQ quantized parameters.
If not, we create a temp linear layer with the module state_dict params and use it for quantization
| create_quantized_param | python | huggingface/transformers | src/transformers/quantizers/quantizer_hqq.py | https://github.com/huggingface/transformers/blob/master/src/transformers/quantizers/quantizer_hqq.py | Apache-2.0 |
def check_quantized_param(
self,
model: "PreTrainedModel",
param_value: "torch.Tensor",
param_name: str,
state_dict: Dict[str, Any],
**kwargs,
) -> bool:
"""
Check if a parameter needs to be quantized.
"""
if is_optimum_quanto_available... |
Check if a parameter needs to be quantized.
| check_quantized_param | python | huggingface/transformers | src/transformers/quantizers/quantizer_quanto.py | https://github.com/huggingface/transformers/blob/master/src/transformers/quantizers/quantizer_quanto.py | Apache-2.0 |
def fuzzy_match_size(config_name: str) -> Optional[str]:
"""
Extract the size digit from strings like "4weight", "8weight".
Returns the digit as an integer if found, otherwise None.
"""
config_name = config_name.lower()
str_match = re.search(r"(\d)weight", config_name)
if str_match:
... |
Extract the size digit from strings like "4weight", "8weight".
Returns the digit as an integer if found, otherwise None.
| fuzzy_match_size | python | huggingface/transformers | src/transformers/quantizers/quantizer_torchao.py | https://github.com/huggingface/transformers/blob/master/src/transformers/quantizers/quantizer_torchao.py | Apache-2.0 |
def create_quantized_param(
self,
model: "PreTrainedModel",
param_value: "torch.Tensor",
param_name: str,
target_device: "torch.device",
state_dict: Dict[str, Any],
unexpected_keys: List[str],
):
"""
Each nn.Linear layer that needs to be quanti... |
Each nn.Linear layer that needs to be quantized is processed here.
First, we set the value the weight tensor, then we move it to the target device. Finally, we quantize the module.
| create_quantized_param | python | huggingface/transformers | src/transformers/quantizers/quantizer_torchao.py | https://github.com/huggingface/transformers/blob/master/src/transformers/quantizers/quantizer_torchao.py | Apache-2.0 |
def _process_model_after_weight_loading(self, model, **kwargs):
"""No process required for torchao quantized model"""
if self.quantization_config.quant_type == "autoquant":
from torchao import autoquant
from torchao.quantization import ALL_AUTOQUANT_CLASS_LIST
model ... | No process required for torchao quantized model | _process_model_after_weight_loading | python | huggingface/transformers | src/transformers/quantizers/quantizer_torchao.py | https://github.com/huggingface/transformers/blob/master/src/transformers/quantizers/quantizer_torchao.py | Apache-2.0 |
def get_cuda_warm_up_factor(self):
"""
This factor is used in caching_allocator_warmup to determine how many bytes to pre-allocate for CUDA warmup.
- A factor of 2 means we pre-allocate the full memory footprint of the model.
- A factor of 4 means we pre-allocate half of that, and so on
... |
This factor is used in caching_allocator_warmup to determine how many bytes to pre-allocate for CUDA warmup.
- A factor of 2 means we pre-allocate the full memory footprint of the model.
- A factor of 4 means we pre-allocate half of that, and so on
However, when using TorchAO, calculat... | get_cuda_warm_up_factor | python | huggingface/transformers | src/transformers/quantizers/quantizer_torchao.py | https://github.com/huggingface/transformers/blob/master/src/transformers/quantizers/quantizer_torchao.py | Apache-2.0 |
def _process_model_before_weight_loading(
self,
model: "PreTrainedModel",
keep_in_fp32_modules: Optional[List[str]] = None,
**kwargs,
):
"""
we don't have param like modules_to_not_convert to indicate which layers should not be quantized
because `quantization_... |
we don't have param like modules_to_not_convert to indicate which layers should not be quantized
because `quantization_config` include the layers that should be quantized
| _process_model_before_weight_loading | python | huggingface/transformers | src/transformers/quantizers/quantizer_vptq.py | https://github.com/huggingface/transformers/blob/master/src/transformers/quantizers/quantizer_vptq.py | Apache-2.0 |
def equalize_indent(docstring, indent_level):
"""
Adjust the indentation of a docstring to match the specified indent level.
"""
# fully dedent the docstring
docstring = "\n".join([line.lstrip() for line in docstring.splitlines()])
return textwrap.indent(docstring, " " * indent_level) |
Adjust the indentation of a docstring to match the specified indent level.
| equalize_indent | python | huggingface/transformers | src/transformers/utils/args_doc.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/args_doc.py | Apache-2.0 |
def parse_docstring(docstring, max_indent_level=0):
"""
Parse the docstring to extract the Args section and return it as a dictionary.
The docstring is expected to be in the format:
Args:
arg1 (type): Description of arg1.
arg2 (type): Description of arg2.
# This function will also r... |
Parse the docstring to extract the Args section and return it as a dictionary.
The docstring is expected to be in the format:
Args:
arg1 (type): Description of arg1.
arg2 (type): Description of arg2.
# This function will also return the remaining part of the docstring after the Args se... | parse_docstring | python | huggingface/transformers | src/transformers/utils/args_doc.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/args_doc.py | Apache-2.0 |
def contains_type(type_hint, target_type) -> Tuple[bool, Optional[object]]:
"""
Check if a "nested" type hint contains a specific target type,
return the first-level type containing the target_type if found.
"""
args = get_args(type_hint)
if args == ():
try:
return issubclass... |
Check if a "nested" type hint contains a specific target type,
return the first-level type containing the target_type if found.
| contains_type | python | huggingface/transformers | src/transformers/utils/args_doc.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/args_doc.py | Apache-2.0 |
def get_placeholders_dict(placeholders: List, model_name: str) -> dict:
"""
Get the dictionary of placeholders for the given model name.
"""
# import here to avoid circular import
from transformers.models import auto as auto_module
placeholders_dict = {}
for placeholder in placeholders:
... |
Get the dictionary of placeholders for the given model name.
| get_placeholders_dict | python | huggingface/transformers | src/transformers/utils/args_doc.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/args_doc.py | Apache-2.0 |
def format_args_docstring(args, model_name):
"""
Replaces placeholders such as {image_processor_class} in the docstring with the actual values,
deducted from the model name and the auto modules.
"""
# first check if there are any placeholders in the args, if not return them as is
placeholders = ... |
Replaces placeholders such as {image_processor_class} in the docstring with the actual values,
deducted from the model name and the auto modules.
| format_args_docstring | python | huggingface/transformers | src/transformers/utils/args_doc.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/args_doc.py | Apache-2.0 |
def _get_parameter_info(param_name, documented_params, source_args_dict, param_type, optional):
"""
Get parameter documentation details from the appropriate source.
Tensor shape, optional status and description are taken from the custom docstring in priority if available.
Type is taken from the function... |
Get parameter documentation details from the appropriate source.
Tensor shape, optional status and description are taken from the custom docstring in priority if available.
Type is taken from the function signature first, then from the custom docstring if missing from the signature
Args:
param... | _get_parameter_info | python | huggingface/transformers | src/transformers/utils/args_doc.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/args_doc.py | Apache-2.0 |
def _process_parameters_section(
func_documentation, sig, func, class_name, model_name_lowercase, parent_class, indent_level
):
"""
Process the parameters section of the docstring.
Args:
func_documentation (`str`): Existing function documentation (manually specified in the docstring)
si... |
Process the parameters section of the docstring.
Args:
func_documentation (`str`): Existing function documentation (manually specified in the docstring)
sig (`inspect.Signature`): Function signature
func (`function`): Function the parameters belong to
class_name (`str`): Name o... | _process_parameters_section | python | huggingface/transformers | src/transformers/utils/args_doc.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/args_doc.py | Apache-2.0 |
def _process_returns_section(func_documentation, sig, config_class, indent_level):
"""
Process the returns section of the docstring.
Args:
func_documentation (`str`): Existing function documentation (manually specified in the docstring)
sig (`inspect.Signature`): Function signature
... |
Process the returns section of the docstring.
Args:
func_documentation (`str`): Existing function documentation (manually specified in the docstring)
sig (`inspect.Signature`): Function signature
config_class (`str`): Config class for the model
indent_level (`int`): Indentation... | _process_returns_section | python | huggingface/transformers | src/transformers/utils/args_doc.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/args_doc.py | Apache-2.0 |
def auto_class_docstring(cls, custom_intro=None, custom_args=None, checkpoint=None):
"""
Wrapper that automatically generates a docstring for classes based on their attributes and methods.
"""
# import here to avoid circular import
from transformers.models import auto as auto_module
docstring_i... |
Wrapper that automatically generates a docstring for classes based on their attributes and methods.
| auto_class_docstring | python | huggingface/transformers | src/transformers/utils/args_doc.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/args_doc.py | Apache-2.0 |
def auto_docstring(obj=None, *, custom_intro=None, custom_args=None, checkpoint=None):
"""
Automatically generates docstrings for classes and methods in the Transformers library.
This decorator can be used in the following forms:
@auto_docstring
def my_function(...):
...
or
@auto_do... |
Automatically generates docstrings for classes and methods in the Transformers library.
This decorator can be used in the following forms:
@auto_docstring
def my_function(...):
...
or
@auto_docstring()
def my_function(...):
...
or
@auto_docstring(custom_intro="Custo... | auto_docstring | python | huggingface/transformers | src/transformers/utils/args_doc.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/args_doc.py | Apache-2.0 |
def generate_attention_matrix_from_mask(
words, mask, img_token="<img>", sliding_window=None, token_type_ids=None, image_seq_length=None
):
"""
Generates an attention matrix from a given attention mask.
Optionally applies a sliding window mask (e.g., for Gemma2/3) and
marks regions where image toke... |
Generates an attention matrix from a given attention mask.
Optionally applies a sliding window mask (e.g., for Gemma2/3) and
marks regions where image tokens occur based on the specified `img_token`.
| generate_attention_matrix_from_mask | python | huggingface/transformers | src/transformers/utils/attention_visualizer.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/attention_visualizer.py | Apache-2.0 |
def load_backbone(config):
"""
Loads the backbone model from a config object.
If the config is from the backbone model itself, then we return a backbone model with randomly initialized
weights.
If the config is from the parent model of the backbone model itself, then we load the pretrained backbon... |
Loads the backbone model from a config object.
If the config is from the backbone model itself, then we return a backbone model with randomly initialized
weights.
If the config is from the parent model of the backbone model itself, then we load the pretrained backbone weights
if specified.
| load_backbone | python | huggingface/transformers | src/transformers/utils/backbone_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/backbone_utils.py | Apache-2.0 |
def verify_backbone_config_arguments(
use_timm_backbone: bool,
use_pretrained_backbone: bool,
backbone: Optional[str],
backbone_config: Optional[Union[dict, "PretrainedConfig"]],
backbone_kwargs: Optional[dict],
):
"""
Verify that the config arguments to be passed to load_backbone are valid
... |
Verify that the config arguments to be passed to load_backbone are valid
| verify_backbone_config_arguments | python | huggingface/transformers | src/transformers/utils/backbone_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/backbone_utils.py | Apache-2.0 |
def deprecate_kwarg(
old_name: str,
version: str,
new_name: Optional[str] = None,
warn_if_greater_or_equal_version: bool = False,
raise_if_greater_or_equal_version: bool = False,
raise_if_both_names: bool = False,
additional_message: Optional[str] = None,
):
"""
Function or method de... |
Function or method decorator to notify users about deprecated keyword arguments, replacing them with a new name if specified.
Note that is decorator is `torch.compile`-safe, i.e. it will not cause graph breaks (but no warning will be displayed if compiling).
This decorator allows you to:
- Notify user... | deprecate_kwarg | python | huggingface/transformers | src/transformers/utils/deprecation.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/deprecation.py | Apache-2.0 |
def get_docstring_indentation_level(func):
"""Return the indentation level of the start of the docstring of a class or function (or method)."""
# We assume classes are always defined in the global scope
if inspect.isclass(func):
return 4
source = inspect.getsource(func)
first_line = source.s... | Return the indentation level of the start of the docstring of a class or function (or method). | get_docstring_indentation_level | python | huggingface/transformers | src/transformers/utils/doc.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/doc.py | Apache-2.0 |
def gen_constructor_wrapper(target: Callable) -> tuple[Callable, Callable]:
"""
Wraps `target` to be proxyable. Used for tensor creators like `torch.ones`, `torch.arange` and so on.
"""
wrapper = create_wrapper(target, "call_function")
return wrapper, target |
Wraps `target` to be proxyable. Used for tensor creators like `torch.ones`, `torch.arange` and so on.
| gen_constructor_wrapper | python | huggingface/transformers | src/transformers/utils/fx.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/fx.py | Apache-2.0 |
def is_tensor(x):
"""
Tests if `x` is a `torch.Tensor`, `tf.Tensor`, `jaxlib.xla_extension.DeviceArray`, `np.ndarray` or `mlx.array`
in the order defined by `infer_framework_from_repr`
"""
# This gives us a smart order to test the frameworks with the corresponding tests.
framework_to_test_func =... |
Tests if `x` is a `torch.Tensor`, `tf.Tensor`, `jaxlib.xla_extension.DeviceArray`, `np.ndarray` or `mlx.array`
in the order defined by `infer_framework_from_repr`
| is_tensor | python | huggingface/transformers | src/transformers/utils/generic.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/generic.py | Apache-2.0 |
def torch_int(x):
"""
Casts an input to a torch int64 tensor if we are in a tracing context, otherwise to a Python int.
"""
if not is_torch_available():
return int(x)
import torch
return x.to(torch.int64) if torch.jit.is_tracing() and isinstance(x, torch.Tensor) else int(x) |
Casts an input to a torch int64 tensor if we are in a tracing context, otherwise to a Python int.
| torch_int | python | huggingface/transformers | src/transformers/utils/generic.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/generic.py | Apache-2.0 |
def torch_float(x):
"""
Casts an input to a torch float32 tensor if we are in a tracing context, otherwise to a Python float.
"""
if not is_torch_available():
return int(x)
import torch
return x.to(torch.float32) if torch.jit.is_tracing() and isinstance(x, torch.Tensor) else int(x) |
Casts an input to a torch float32 tensor if we are in a tracing context, otherwise to a Python float.
| torch_float | python | huggingface/transformers | src/transformers/utils/generic.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/generic.py | Apache-2.0 |
def filter_out_non_signature_kwargs(extra: Optional[list] = None):
"""
Decorator to filter out named arguments that are not in the function signature.
This decorator ensures that only the keyword arguments that match the function's signature, or are specified in the
`extra` list, are passed to the func... |
Decorator to filter out named arguments that are not in the function signature.
This decorator ensures that only the keyword arguments that match the function's signature, or are specified in the
`extra` list, are passed to the function. Any additional keyword arguments are filtered out and a warning is i... | filter_out_non_signature_kwargs | python | huggingface/transformers | src/transformers/utils/generic.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/generic.py | Apache-2.0 |
def is_timm_local_checkpoint(pretrained_model_path: str) -> bool:
"""
Checks whether a checkpoint is a timm model checkpoint.
"""
if pretrained_model_path is None:
return False
# in case it's Path, not str
pretrained_model_path = str(pretrained_model_path)
is_file = os.path.isfile(... |
Checks whether a checkpoint is a timm model checkpoint.
| is_timm_local_checkpoint | python | huggingface/transformers | src/transformers/utils/generic.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/generic.py | Apache-2.0 |
def set_attribute_for_modules(module: "torch.nn.Module", key: str, value: Any):
"""
Set a value to a module and all submodules.
"""
setattr(module, key, value)
for submodule in module.children():
set_attribute_for_modules(submodule, key, value) |
Set a value to a module and all submodules.
| set_attribute_for_modules | python | huggingface/transformers | src/transformers/utils/generic.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/generic.py | Apache-2.0 |
def del_attribute_from_modules(module: "torch.nn.Module", key: str):
"""
Delete a value from a module and all submodules.
"""
# because we might remove it previously in case it's a shared module, e.g. activation function
if hasattr(module, key):
delattr(module, key)
for submodule in mod... |
Delete a value from a module and all submodules.
| del_attribute_from_modules | python | huggingface/transformers | src/transformers/utils/generic.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/generic.py | Apache-2.0 |
def can_return_tuple(func):
"""
Decorator to wrap model method, to call output.to_tuple() if return_dict=False passed as a kwarg or
use_return_dict=False is set in the config.
Note:
output.to_tuple() convert output to tuple skipping all `None` values.
"""
@wraps(func)
def wrapper(s... |
Decorator to wrap model method, to call output.to_tuple() if return_dict=False passed as a kwarg or
use_return_dict=False is set in the config.
Note:
output.to_tuple() convert output to tuple skipping all `None` values.
| can_return_tuple | python | huggingface/transformers | src/transformers/utils/generic.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/generic.py | Apache-2.0 |
def list_repo_templates(
repo_id: str,
*,
local_files_only: bool,
revision: Optional[str] = None,
cache_dir: Optional[str] = None,
) -> list[str]:
"""List template files from a repo.
A template is a jinja file located under the `additional_chat_templates/` folder.
If working in offline ... | List template files from a repo.
A template is a jinja file located under the `additional_chat_templates/` folder.
If working in offline mode or if internet is down, the method will list jinja template from the local cache - if any.
| list_repo_templates | python | huggingface/transformers | src/transformers/utils/hub.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/hub.py | Apache-2.0 |
def has_file(
path_or_repo: Union[str, os.PathLike],
filename: str,
revision: Optional[str] = None,
proxies: Optional[dict[str, str]] = None,
token: Optional[Union[bool, str]] = None,
*,
local_files_only: bool = False,
cache_dir: Union[str, Path, None] = None,
repo_type: Optional[str... |
Checks if a repo contains a given file without downloading it. Works for remote repos and local folders.
If offline mode is enabled, checks if the file exists in the cache.
<Tip warning={false}>
This function will raise an error if the repository `path_or_repo` is not valid or if `revision` does not... | has_file | python | huggingface/transformers | src/transformers/utils/hub.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/hub.py | Apache-2.0 |
def is_torch_deterministic():
"""
Check whether pytorch uses deterministic algorithms by looking if torch.set_deterministic_debug_mode() is set to 1 or 2"
"""
if is_torch_available():
import torch
if torch.get_deterministic_debug_mode() == 0:
return False
else:
... |
Check whether pytorch uses deterministic algorithms by looking if torch.set_deterministic_debug_mode() is set to 1 or 2"
| is_torch_deterministic | python | huggingface/transformers | src/transformers/utils/import_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/import_utils.py | Apache-2.0 |
def is_torch_hpu_available():
"Checks if `torch.hpu` is available and potentially if a HPU is in the environment"
if (
not _torch_available
or importlib.util.find_spec("habana_frameworks") is None
or importlib.util.find_spec("habana_frameworks.torch") is None
):
return False
... | Checks if `torch.hpu` is available and potentially if a HPU is in the environment | is_torch_hpu_available | python | huggingface/transformers | src/transformers/utils/import_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/import_utils.py | Apache-2.0 |
def is_torch_xpu_available(check_device=False):
"""
Checks if XPU acceleration is available either via native PyTorch (>=2.6),
`intel_extension_for_pytorch` or via stock PyTorch (>=2.4) and potentially
if a XPU is in the environment.
"""
if not is_torch_available():
return False
tor... |
Checks if XPU acceleration is available either via native PyTorch (>=2.6),
`intel_extension_for_pytorch` or via stock PyTorch (>=2.4) and potentially
if a XPU is in the environment.
| is_torch_xpu_available | python | huggingface/transformers | src/transformers/utils/import_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/import_utils.py | Apache-2.0 |
def is_torch_greater_or_equal(library_version: str, accept_dev: bool = False):
"""
Accepts a library version and returns True if the current version of the library is greater than or equal to the
given version. If `accept_dev` is True, it will also accept development versions (e.g. 2.7.0.dev20250320 matches... |
Accepts a library version and returns True if the current version of the library is greater than or equal to the
given version. If `accept_dev` is True, it will also accept development versions (e.g. 2.7.0.dev20250320 matches
2.7.0).
| is_torch_greater_or_equal | python | huggingface/transformers | src/transformers/utils/import_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/import_utils.py | Apache-2.0 |
def direct_transformers_import(path: str, file="__init__.py") -> ModuleType:
"""Imports transformers directly
Args:
path (`str`): The path to the source file
file (`str`, *optional*): The file to join with the path. Defaults to "__init__.py".
Returns:
`ModuleType`: The resulting im... | Imports transformers directly
Args:
path (`str`): The path to the source file
file (`str`, *optional*): The file to join with the path. Defaults to "__init__.py".
Returns:
`ModuleType`: The resulting imported module
| direct_transformers_import | python | huggingface/transformers | src/transformers/utils/import_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/import_utils.py | Apache-2.0 |
def requires(*, backends=()):
"""
This decorator enables two things:
- Attaching a `__backends` tuple to an object to see what are the necessary backends for it
to execute correctly without instantiating it
- The '@requires' string is used to dynamically import objects
"""
if not isinstan... |
This decorator enables two things:
- Attaching a `__backends` tuple to an object to see what are the necessary backends for it
to execute correctly without instantiating it
- The '@requires' string is used to dynamically import objects
| requires | python | huggingface/transformers | src/transformers/utils/import_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/import_utils.py | Apache-2.0 |
def fetch__all__(file_content):
"""
Returns the content of the __all__ variable in the file content.
Returns None if not defined, otherwise returns a list of strings.
"""
if "__all__" not in file_content:
return []
start_index = None
lines = file_content.splitlines()
for index,... |
Returns the content of the __all__ variable in the file content.
Returns None if not defined, otherwise returns a list of strings.
| fetch__all__ | python | huggingface/transformers | src/transformers/utils/import_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/import_utils.py | Apache-2.0 |
def create_import_structure_from_path(module_path):
"""
This method takes the path to a file/a folder and returns the import structure.
If a file is given, it will return the import structure of the parent folder.
Import structures are designed to be digestible by `_LazyModule` objects. They are
cr... |
This method takes the path to a file/a folder and returns the import structure.
If a file is given, it will return the import structure of the parent folder.
Import structures are designed to be digestible by `_LazyModule` objects. They are
created from the __all__ definitions in each files as well as... | create_import_structure_from_path | python | huggingface/transformers | src/transformers/utils/import_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/import_utils.py | Apache-2.0 |
def spread_import_structure(nested_import_structure):
"""
This method takes as input an unordered import structure and brings the required backends at the top-level,
aggregating modules and objects under their required backends.
Here's an example of an input import structure at the src.transformers.mod... |
This method takes as input an unordered import structure and brings the required backends at the top-level,
aggregating modules and objects under their required backends.
Here's an example of an input import structure at the src.transformers.models level:
{
'albert': {
frozenset()... | spread_import_structure | python | huggingface/transformers | src/transformers/utils/import_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/import_utils.py | Apache-2.0 |
def define_import_structure(module_path: str, prefix: Optional[str] = None) -> IMPORT_STRUCTURE_T:
"""
This method takes a module_path as input and creates an import structure digestible by a _LazyModule.
Here's an example of an output import structure at the src.transformers.models level:
{
f... |
This method takes a module_path as input and creates an import structure digestible by a _LazyModule.
Here's an example of an output import structure at the src.transformers.models level:
{
frozenset({'tokenizers'}): {
'albert.tokenization_albert_fast': {'AlbertTokenizerFast'}
... | define_import_structure | python | huggingface/transformers | src/transformers/utils/import_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/import_utils.py | Apache-2.0 |
def clear_import_cache():
"""
Clear cached Transformers modules to allow reloading modified code.
This is useful when actively developing/modifying Transformers code.
"""
# Get all transformers modules
transformers_modules = [mod_name for mod_name in sys.modules if mod_name.startswith("transfor... |
Clear cached Transformers modules to allow reloading modified code.
This is useful when actively developing/modifying Transformers code.
| clear_import_cache | python | huggingface/transformers | src/transformers/utils/import_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/import_utils.py | Apache-2.0 |
def attach_tracer(tracer_name_template=None):
"""
Decorator that attaches a tracer to a class.
This decorator should be applied to classes that need OpenTelemetry tracing.
It adds a tracer attribute to the class instance that can be used by the traced decorator.
Args:
tracer_name_template:... |
Decorator that attaches a tracer to a class.
This decorator should be applied to classes that need OpenTelemetry tracing.
It adds a tracer attribute to the class instance that can be used by the traced decorator.
Args:
tracer_name_template: Optional template string for the tracer name.
... | attach_tracer | python | huggingface/transformers | src/transformers/utils/metrics.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/metrics.py | Apache-2.0 |
def traced(
func=None,
*,
span_name=None,
standalone=False,
additional_attributes: Optional[List[Tuple[str, str, Union[Any, Callable[[Any], Any]]]]] = None,
):
"""
Decorator to trace function calls with OpenTelemetry.
Can be used as @traced or @traced(span_name="custom_name")
Args:... |
Decorator to trace function calls with OpenTelemetry.
Can be used as @traced or @traced(span_name="custom_name")
Args:
func: The function to trace
span_name: Optional custom name for the span (defaults to function name)
standalone: If True, creates a parentless span
additi... | traced | python | huggingface/transformers | src/transformers/utils/metrics.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/metrics.py | Apache-2.0 |
def _setup_metrics(self):
"""Initialize OpenTelemetry metrics and tracing if the library is available."""
if not _has_opentelemetry:
logger.info("OpenTelemetry is not installed. Metrics and tracing will not be recorded.")
return
self.meter = metrics.get_meter("transform... | Initialize OpenTelemetry metrics and tracing if the library is available. | _setup_metrics | python | huggingface/transformers | src/transformers/utils/metrics.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/metrics.py | Apache-2.0 |
def record_ttft_metric(self, created_time: float, request_id: str) -> None:
"""Record Time to First Token (TTFT).
Args:
created_time: The time the request was created
request_id: The ID of the request
"""
if not _has_opentelemetry:
return
ttf... | Record Time to First Token (TTFT).
Args:
created_time: The time the request was created
request_id: The ID of the request
| record_ttft_metric | python | huggingface/transformers | src/transformers/utils/metrics.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/metrics.py | Apache-2.0 |
def record_batch_metrics(self, requests_in_batch: List) -> None:
"""Record metrics about the batch composition including decode/prefill ratio and batch fill percentage.
Args:
requests_in_batch: List of request states in the current batch
"""
if not _has_opentelemetry or not ... | Record metrics about the batch composition including decode/prefill ratio and batch fill percentage.
Args:
requests_in_batch: List of request states in the current batch
| record_batch_metrics | python | huggingface/transformers | src/transformers/utils/metrics.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/metrics.py | Apache-2.0 |
def record_kv_cache_memory_metrics(self, cache) -> None:
"""Record memory usage of the PagedAttentionCache without GPU synchronization.
This calculates the theoretical memory usage based on cache configuration
and the number of blocks currently in use.
Args:
cache: The Page... | Record memory usage of the PagedAttentionCache without GPU synchronization.
This calculates the theoretical memory usage based on cache configuration
and the number of blocks currently in use.
Args:
cache: The PagedAttentionCache object to measure
| record_kv_cache_memory_metrics | python | huggingface/transformers | src/transformers/utils/metrics.py | https://github.com/huggingface/transformers/blob/master/src/transformers/utils/metrics.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.