class RelativePositionBiasBase(nn.Module, ABC):

    def __init__(self, num_heads=None, relative_attention_num_buckets=32, bidirectional=True, scaling_factor=1, max_distance=128, level='tokens', augmentation=False, prefix_bucket=False, expand=False):
        super(RelativePositionBiasBase, self).__init__()
        self.prefix_bucket = prefix_bucket
        self.augmentation = augmentation
        self.level = level
        self.max_distance = max_distance
        self.scaling_factor = scaling_factor
        self.bidirectional = bidirectional
        self.num_heads = num_heads
        self.expand = expand
        self.relative_attention_num_buckets = relative_attention_num_buckets
        extra_head = 2 if prefix_bucket and (not self.expand) else 0
        self.relative_attention_bias = nn.Embedding(self.relative_attention_num_buckets + extra_head, self.num_heads)

    @abstractmethod
    def prepare_input(self, attention_mask: Optional[Tensor]=None, bbox: Optional[Dict[str, Any]]=None) -> Tensor:
        pass

    def get_bucket(self, attention_mask: Optional[Tensor]=None, bbox: Optional[Dict[str, Any]]=None) -> Tensor:
        relative_position = self.prepare_input(attention_mask, bbox)
        rp_bucket: Tensor = get_relative_position_bucket(relative_position, bidirectional=self.bidirectional, num_buckets=self.relative_attention_num_buckets, max_distance=self.max_distance)
        return rp_bucket

    def get_relative_position(self, positions):
        context_position = positions[:, :, None]
        memory_position = positions[:, None, :]
        relative_position = memory_position - context_position
        if self.augmentation and self.training:
            relative_position *= random.uniform(*AUGMENTATION_RANGE)
        relative_position *= self.scaling_factor
        return relative_position.to(torch.long)

    def forward(self, attention_mask: Optional[Tensor]=None, bbox: Optional[Dict[str, Any]]=None) -> Tensor:
        if self.expand and self.prefix_bucket:
            new_bias = nn.Embedding(self.relative_attention_num_buckets + 2, self.num_heads)
            new_bias.weight.data[:self.relative_attention_num_buckets] = self.relative_attention_bias.weight.data
            new_bias.weight.data[self.relative_attention_num_buckets:] = 0.1
            self.relative_attention_bias = new_bias
            self.expand = False
        rp_bucket = self.get_bucket(attention_mask, bbox)
        if self.prefix_bucket:
            if rp_bucket.size(0) == 1 and attention_mask.size(0) > 1:
                rp_bucket = rp_bucket.repeat(attention_mask.size(0), 1, 1)
            is_prefix = bbox[:, :, 1] < 0
            num_prefix = is_prefix.sum(-1)
            for idx, num_prefix_row in enumerate(num_prefix.cpu().numpy()):
                rp_bucket[idx, :num_prefix_row, num_prefix_row:] = self.relative_attention_num_buckets
                rp_bucket[idx, num_prefix_row:, :num_prefix_row] = self.relative_attention_num_buckets + 1
        values: Tensor = self.relative_attention_bias(rp_bucket)
        if values.dim() != 4:
            raise ValueError('Wrong dimension of values tensor')
        values = values.permute([0, 3, 1, 2])
        return values

Base class of relative biases.

Args:
    num_heads (`int`):
        Number of attention heads in the model, it will create embeddings of size `num_heads`, which will be added to the scores of each token pair.
    relative_attention_num_buckets (`int`, *optional*, defaults to 32):
        Pair token metric (distance in the sequence, distance in pixels etc.) will be bucketed, parameter is defining number of such
        buckets.
    bidirectional (`bool`, *optional*, defaults to `True`):
        Whether the distance should be bidirectional for a pair of tokens. If `False`, then distance(tok1, tok2) == distance(tok2, tok1).
    scaling_factor (`int`, *optional*, defaults to 1):
        Defining factor which will be used to scale relative distance.
    max_distance (`int`, *optional*, defaults to 128):
        All distances above this value will end up in the one/same bucket.
    augmentation (`bool`, *optional*, defaults to `False`):
        Whether to multiply relative distances by a random scalar.
    expand (`bool`, *optional*, defaults to `False`):
        Whether to expand an existing pretrained model with subsequent additions of prefix_bucket.


def get_image_features(self, pixel_values=None, output_attentions=None, output_hidden_states=None, return_dict=None):
    vision_outputs = self.vision_model(pixel_values=pixel_values, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
    pooled_output = vision_outputs[1]
    image_features = self.visual_projection(pooled_output)
    return image_features

Returns:
    image_features (`tf.Tensor` of shape `(batch_size, output_dim`): The image embeddings obtained by applying
    the projection layer to the pooled output of [`TFCLIPVisionModel`].

Examples:

```python
>>> from PIL import Image
>>> import requests
>>> from transformers import TFVisionTextDualEncoderModel, AutoImageProcessor

>>> model = TFVisionTextDualEncoderModel.from_pretrained("clip-italian/clip-italian", from_pt=True)
>>> image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224")

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)

>>> inputs = image_processor(images=image, return_tensors="np")

>>> image_features = model.get_image_features(**inputs)
```


def list_pytype_files(suffix):
    assert not suffix.endswith('/')
    loader = globals().get('__loader__', None)
    try:
        filenames = loader.get_zipfile().namelist()
    except AttributeError:
        yield from list_files(get_full_path(suffix))
    else:
        for filename in filenames:
            directory = 'pytype/' + suffix + '/'
            try:
                i = filename.rindex(directory)
            except ValueError:
                pass
            else:
                yield filename[i + len(directory):]

Recursively get the contents of a directory in the pytype installation.

This reports files in said directory as well as all subdirectories of it.

Arguments:
  suffix: the path, relative to "pytype/"

Yields:
  The filenames, relative to pytype/{suffix}
Raises:
  NoSuchDirectory: if the directory doesn't exist.


def forward(self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor]=None, layer_head_mask: Optional[torch.Tensor]=None, past_key_value: Optional[Tuple[torch.Tensor]]=None, output_attentions: Optional[bool]=False, use_cache: Optional[bool]=False, position_ids: Optional[torch.LongTensor]=None, cache_position: Optional[torch.Tensor]=None, **kwargs: Unpack[FlashAttentionKwargs]) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
    residual = hidden_states
    if self.do_layer_norm_before:
        hidden_states = self.self_attn_layer_norm(hidden_states)
    hidden_states, self_attn_weights, present_key_value = self.self_attn(hidden_states=hidden_states, past_key_value=past_key_value, position_ids=position_ids, attention_mask=attention_mask, layer_head_mask=layer_head_mask, output_attentions=output_attentions, cache_position=cache_position, **kwargs)
    hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
    hidden_states = residual + hidden_states
    if not self.do_layer_norm_before:
        hidden_states = self.self_attn_layer_norm(hidden_states)
    hidden_states_shape = hidden_states.shape
    hidden_states = hidden_states.reshape(-1, hidden_states.size(-1))
    residual = hidden_states
    if self.do_layer_norm_before:
        hidden_states = self.final_layer_norm(hidden_states)
    hidden_states = self.fc1(hidden_states)
    hidden_states = self.activation_fn(hidden_states)
    hidden_states = self.fc2(hidden_states)
    hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
    hidden_states = (residual + hidden_states).view(hidden_states_shape)
    if not self.do_layer_norm_before:
        hidden_states = self.final_layer_norm(hidden_states)
    outputs = (hidden_states,)
    if output_attentions:
        outputs += (self_attn_weights,)
    if use_cache:
        outputs += (present_key_value,)
    return outputs

Args:
    hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
    attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
        `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
    layer_head_mask (`torch.FloatTensor`, *optional*): mask for attention heads in a given layer of size
        `(encoder_attention_heads,)`.
    output_attentions (`bool`, *optional*):
        Whether or not to return the attentions tensors of all attention layers. See `attentions` under
        returned tensors for more detail.
    use_cache (`bool`, *optional*):
        If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
        (see `past_key_values`).
    past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
    cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
        Indices depicting the position of the input sequence tokens in the sequence..


def master(self, task_type=None, task_id=None, rpc_layer=None):
    task_type = task_type if task_type is not None else self.task_type
    task_id = task_id if task_id is not None else self.task_id
    if task_type is not None and task_id is not None:
        return format_master_url(self.cluster_spec().task_address(task_type, task_id), rpc_layer or self.rpc_layer)
    return ''

Returns the master string for connecting to a TensorFlow master.

Args:
  task_type: (Optional) Overrides the default auto-selected task type.
  task_id: (Optional) Overrides the default auto-selected task index.
  rpc_layer: (Optional) Overrides the default RPC protocol TensorFlow uses
    to communicate across nodes.

Returns:
  A connection string for connecting to a TensorFlow master.


class DetaImageProcessor(BaseImageProcessor):
    model_input_names = ['pixel_values', 'pixel_mask']

    def __init__(self, format: Union[str, AnnotationFormat]=AnnotationFormat.COCO_DETECTION, do_resize: bool=True, size: Optional[Dict[str, int]]=None, resample: PILImageResampling=PILImageResampling.BILINEAR, do_rescale: bool=True, rescale_factor: Union[int, float]=1 / 255, do_normalize: bool=True, image_mean: Optional[Union[float, List[float]]]=None, image_std: Optional[Union[float, List[float]]]=None, do_convert_annotations: bool=True, do_pad: bool=True, pad_size: Optional[Dict[str, int]]=None, **kwargs) -> None:
        if 'pad_and_return_pixel_mask' in kwargs:
            do_pad = kwargs.pop('pad_and_return_pixel_mask')
        size = size if size is not None else {'shortest_edge': 800, 'longest_edge': 1333}
        size = get_size_dict(size, default_to_square=False)
        if do_convert_annotations is None:
            do_convert_annotations = do_normalize
        super().__init__(**kwargs)
        self.format = format
        self.do_resize = do_resize
        self.size = size
        self.resample = resample
        self.do_rescale = do_rescale
        self.rescale_factor = rescale_factor
        self.do_normalize = do_normalize
        self.do_convert_annotations = do_convert_annotations
        self.image_mean = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
        self.image_std = image_std if image_std is not None else IMAGENET_DEFAULT_STD
        self.do_pad = do_pad
        self.pad_size = pad_size

    def prepare_annotation(self, image: np.ndarray, target: Dict, format: Optional[AnnotationFormat]=None, return_segmentation_masks: Optional[bool]=None, masks_path: Optional[Union[str, pathlib.Path]]=None, input_data_format: Optional[Union[str, ChannelDimension]]=None) -> Dict:
        """
        Prepare an annotation for feeding into DETA model.
        """
        format = format if format is not None else self.format
        if format == AnnotationFormat.COCO_DETECTION:
            return_segmentation_masks = False if return_segmentation_masks is None else return_segmentation_masks
            target = prepare_coco_detection_annotation(image, target, return_segmentation_masks, input_data_format=input_data_format)
        elif format == AnnotationFormat.COCO_PANOPTIC:
            return_segmentation_masks = True if return_segmentation_masks is None else return_segmentation_masks
            target = prepare_coco_panoptic_annotation(image, target, masks_path=masks_path, return_masks=return_segmentation_masks, input_data_format=input_data_format)
        else:
            raise ValueError(f'Format {format} is not supported.')
        return target

    def resize(self, image: np.ndarray, size: Dict[str, int], resample: PILImageResampling=PILImageResampling.BILINEAR, data_format: Optional[ChannelDimension]=None, input_data_format: Optional[Union[str, ChannelDimension]]=None, **kwargs) -> np.ndarray:
        """
        Resize the image to the given size. Size can be `min_size` (scalar) or `(height, width)` tuple. If size is an
        int, smaller edge of the image will be matched to this number.

        Args:
            image (`np.ndarray`):
                Image to resize.
            size (`Dict[str, int]`):
                Size of the image's `(height, width)` dimensions after resizing. Available options are:
                    - `{"height": int, "width": int}`: The image will be resized to the exact size `(height, width)`.
                        Do NOT keep the aspect ratio.
                    - `{"shortest_edge": int, "longest_edge": int}`: The image will be resized to a maximum size respecting
                        the aspect ratio and keeping the shortest edge less or equal to `shortest_edge` and the longest edge
                        less or equal to `longest_edge`.
                    - `{"max_height": int, "max_width": int}`: The image will be resized to the maximum size respecting the
                        aspect ratio and keeping the height less or equal to `max_height` and the width less or equal to
                        `max_width`.
            resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
                Resampling filter to use if resizing the image.
            data_format (`ChannelDimension`, *optional*):
                The channel dimension format for the output image. If unset, the channel dimension format of the input
                image is used.
            input_data_format (`ChannelDimension` or `str`, *optional*):
                The channel dimension format of the input image. If not provided, it will be inferred from the input
                image.
        """
        size = get_size_dict(size, default_to_square=False)
        if 'shortest_edge' in size and 'longest_edge' in size:
            new_size = get_resize_output_image_size(image, size['shortest_edge'], size['longest_edge'], input_data_format=input_data_format)
        elif 'height' in size and 'width' in size:
            new_size = (size['height'], size['width'])
        elif 'max_height' in size and 'max_width' in size:
            new_size = get_image_size_for_max_height_width(image, size['max_height'], size['max_width'], input_data_format=input_data_format)
        else:
            raise ValueError(f"Size must contain 'height' and 'width' keys or 'shortest_edge' and 'longest_edge' keys. Got {size.keys()}.")
        image = resize(image, size=new_size, resample=resample, data_format=data_format, input_data_format=input_data_format)
        return image

    def resize_annotation(self, annotation, orig_size, size, resample: PILImageResampling=PILImageResampling.NEAREST) -> Dict:
        """
        Resize the annotation to match the resized image. If size is an int, smaller edge of the mask will be matched
        to this number.
        """
        return resize_annotation(annotation, orig_size=orig_size, target_size=size, resample=resample)

    def rescale(self, image: np.ndarray, rescale_factor: float, data_format: Optional[Union[str, ChannelDimension]]=None, input_data_format: Optional[Union[str, ChannelDimension]]=None) -> np.ndarray:
        """
        Rescale the image by the given factor. image = image * rescale_factor.

        Args:
            image (`np.ndarray`):
                Image to rescale.
            rescale_factor (`float`):
                The value to use for rescaling.
            data_format (`str` or `ChannelDimension`, *optional*):
                The channel dimension format for the output image. If unset, the channel dimension format of the input
                image is used. Can be one of:
                - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
                - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
            input_data_format (`str` or `ChannelDimension`, *optional*):
                The channel dimension format for the input image. If unset, is inferred from the input image. Can be
                one of:
                - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
                - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
        """
        return rescale(image, rescale_factor, data_format=data_format, input_data_format=input_data_format)

    def normalize_annotation(self, annotation: Dict, image_size: Tuple[int, int]) -> Dict:
        """
        Normalize the boxes in the annotation from `[top_left_x, top_left_y, bottom_right_x, bottom_right_y]` to
        `[center_x, center_y, width, height]` format and from absolute to relative pixel values.
        """
        return normalize_annotation(annotation, image_size=image_size)

    def _update_annotation_for_padded_image(self, annotation: Dict, input_image_size: Tuple[int, int], output_image_size: Tuple[int, int], padding, update_bboxes) -> Dict:
        """
        Update the annotation for a padded image.
        """
        new_annotation = {}
        new_annotation['size'] = output_image_size
        for key, value in annotation.items():
            if key == 'masks':
                masks = value
                masks = pad(masks, padding, mode=PaddingMode.CONSTANT, constant_values=0, input_data_format=ChannelDimension.FIRST)
                masks = safe_squeeze(masks, 1)
                new_annotation['masks'] = masks
            elif key == 'boxes' and update_bboxes:
                boxes = value
                boxes *= np.asarray([input_image_size[1] / output_image_size[1], input_image_size[0] / output_image_size[0], input_image_size[1] / output_image_size[1], input_image_size[0] / output_image_size[0]])
                new_annotation['boxes'] = boxes
            elif key == 'size':
                new_annotation['size'] = output_image_size
            else:
                new_annotation[key] = value
        return new_annotation

    def _pad_image(self, image: np.ndarray, output_size: Tuple[int, int], annotation: Optional[Dict[str, Any]]=None, constant_values: Union[float, Iterable[float]]=0, data_format: Optional[ChannelDimension]=None, input_data_format: Optional[Union[str, ChannelDimension]]=None, update_bboxes: bool=True) -> np.ndarray:
        """
        Pad an image with zeros to the given size.
        """
        input_height, input_width = get_image_size(image, channel_dim=input_data_format)
        output_height, output_width = output_size
        pad_bottom = output_height - input_height
        pad_right = output_width - input_width
        padding = ((0, pad_bottom), (0, pad_right))
        padded_image = pad(image, padding, mode=PaddingMode.CONSTANT, constant_values=constant_values, data_format=data_format, input_data_format=input_data_format)
        if annotation is not None:
            annotation = self._update_annotation_for_padded_image(annotation, (input_height, input_width), (output_height, output_width), padding, update_bboxes)
        return (padded_image, annotation)

    def pad(self, images: List[np.ndarray], annotations: Optional[Union[AnnotationType, List[AnnotationType]]]=None, constant_values: Union[float, Iterable[float]]=0, return_pixel_mask: bool=True, return_tensors: Optional[Union[str, TensorType]]=None, data_format: Optional[ChannelDimension]=None, input_data_format: Optional[Union[str, ChannelDimension]]=None, update_bboxes: bool=True, pad_size: Optional[Dict[str, int]]=None) -> BatchFeature:
        """
        Pads a batch of images to the bottom and right of the image with zeros to the size of largest height and width
        in the batch and optionally returns their corresponding pixel mask.

        Args:
            images (List[`np.ndarray`]):
                Images to pad.
            annotations (`AnnotationType` or `List[AnnotationType]`, *optional*):
                Annotations to transform according to the padding that is applied to the images.
            constant_values (`float` or `Iterable[float]`, *optional*):
                The value to use for the padding if `mode` is `"constant"`.
            return_pixel_mask (`bool`, *optional*, defaults to `True`):
                Whether to return a pixel mask.
            return_tensors (`str` or `TensorType`, *optional*):
                The type of tensors to return. Can be one of:
                    - Unset: Return a list of `np.ndarray`.
                    - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
                    - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
                    - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
                    - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
            data_format (`str` or `ChannelDimension`, *optional*):
                The channel dimension format of the image. If not provided, it will be the same as the input image.
            input_data_format (`ChannelDimension` or `str`, *optional*):
                The channel dimension format of the input image. If not provided, it will be inferred.
            update_bboxes (`bool`, *optional*, defaults to `True`):
                Whether to update the bounding boxes in the annotations to match the padded images. If the
                bounding boxes have not been converted to relative coordinates and `(centre_x, centre_y, width, height)`
                format, the bounding boxes will not be updated.
            pad_size (`Dict[str, int]`, *optional*):
                The size `{"height": int, "width" int}` to pad the images to. Must be larger than any image size
                provided for preprocessing. If `pad_size` is not provided, images will be padded to the largest
                height and width in the batch.
        """
        pad_size = pad_size if pad_size is not None else self.pad_size
        if pad_size is not None:
            padded_size = (pad_size['height'], pad_size['width'])
        else:
            padded_size = get_max_height_width(images, input_data_format=input_data_format)
        annotation_list = annotations if annotations is not None else [None] * len(images)
        padded_images = []
        padded_annotations = []
        for image, annotation in zip(images, annotation_list):
            padded_image, padded_annotation = self._pad_image(image, padded_size, annotation, constant_values=constant_values, data_format=data_format, input_data_format=input_data_format, update_bboxes=update_bboxes)
            padded_images.append(padded_image)
            padded_annotations.append(padded_annotation)
        data = {'pixel_values': padded_images}
        if return_pixel_mask:
            masks = [make_pixel_mask(image=image, output_size=padded_size, input_data_format=input_data_format) for image in images]
            data['pixel_mask'] = masks
        encoded_inputs = BatchFeature(data=data, tensor_type=return_tensors)
        if annotations is not None:
            encoded_inputs['labels'] = [BatchFeature(annotation, tensor_type=return_tensors) for annotation in padded_annotations]
        return encoded_inputs

    def preprocess(self, images: ImageInput, annotations: Optional[Union[List[Dict], List[List[Dict]]]]=None, return_segmentation_masks: Optional[bool]=None, masks_path: Optional[Union[str, pathlib.Path]]=None, do_resize: Optional[bool]=None, size: Optional[Dict[str, int]]=None, resample=None, do_rescale: Optional[bool]=None, rescale_factor: Optional[Union[int, float]]=None, do_normalize: Optional[bool]=None, image_mean: Optional[Union[float, List[float]]]=None, image_std: Optional[Union[float, List[float]]]=None, do_convert_annotations: Optional[bool]=None, do_pad: Optional[bool]=None, format: Optional[Union[str, AnnotationFormat]]=None, return_tensors: Optional[Union[TensorType, str]]=None, data_format: Union[str, ChannelDimension]=ChannelDimension.FIRST, input_data_format: Optional[Union[str, ChannelDimension]]=None, pad_size: Optional[Dict[str, int]]=None, **kwargs) -> BatchFeature:
        """
        Preprocess an image or a batch of images so that it can be used by the model.

        Args:
            images (`ImageInput`):
                Image or batch of images to preprocess. Expects a single or batch of images with pixel values ranging
                from 0 to 255. If passing in images with pixel values between 0 and 1, set `do_rescale=False`.
            annotations (`List[Dict]` or `List[List[Dict]]`, *optional*):
                List of annotations associated with the image or batch of images. If annotation is for object
                detection, the annotations should be a dictionary with the following keys:
                - "image_id" (`int`): The image id.
                - "annotations" (`List[Dict]`): List of annotations for an image. Each annotation should be a
                  dictionary. An image can have no annotations, in which case the list should be empty.
                If annotation is for segmentation, the annotations should be a dictionary with the following keys:
                - "image_id" (`int`): The image id.
                - "segments_info" (`List[Dict]`): List of segments for an image. Each segment should be a dictionary.
                  An image can have no segments, in which case the list should be empty.
                - "file_name" (`str`): The file name of the image.
            return_segmentation_masks (`bool`, *optional*, defaults to self.return_segmentation_masks):
                Whether to return segmentation masks.
            masks_path (`str` or `pathlib.Path`, *optional*):
                Path to the directory containing the segmentation masks.
            do_resize (`bool`, *optional*, defaults to self.do_resize):
                Whether to resize the image.
            size (`Dict[str, int]`, *optional*, defaults to self.size):
                Size of the image's `(height, width)` dimensions after resizing. Available options are:
                    - `{"height": int, "width": int}`: The image will be resized to the exact size `(height, width)`.
                        Do NOT keep the aspect ratio.
                    - `{"shortest_edge": int, "longest_edge": int}`: The image will be resized to a maximum size respecting
                        the aspect ratio and keeping the shortest edge less or equal to `shortest_edge` and the longest edge
                        less or equal to `longest_edge`.
                    - `{"max_height": int, "max_width": int}`: The image will be resized to the maximum size respecting the
                        aspect ratio and keeping the height less or equal to `max_height` and the width less or equal to
                        `max_width`.
            resample (`PILImageResampling`, *optional*, defaults to self.resample):
                Resampling filter to use when resizing the image.
            do_rescale (`bool`, *optional*, defaults to self.do_rescale):
                Whether to rescale the image.
            rescale_factor (`float`, *optional*, defaults to self.rescale_factor):
                Rescale factor to use when rescaling the image.
            do_normalize (`bool`, *optional*, defaults to self.do_normalize):
                Whether to normalize the image.
            image_mean (`float` or `List[float]`, *optional*, defaults to self.image_mean):
                Mean to use when normalizing the image.
            image_std (`float` or `List[float]`, *optional*, defaults to self.image_std):
                Standard deviation to use when normalizing the image.
            do_convert_annotations (`bool`, *optional*, defaults to self.do_convert_annotations):
                Whether to convert the annotations to the format expected by the model. Converts the bounding
                boxes from the format `(top_left_x, top_left_y, width, height)` to `(center_x, center_y, width, height)`
                and in relative coordinates.
            do_pad (`bool`, *optional*, defaults to self.do_pad):
                Whether to pad the image. If `True`, padding will be applied to the bottom and right of
                the image with zeros. If `pad_size` is provided, the image will be padded to the specified
                dimensions. Otherwise, the image will be padded to the maximum height and width of the batch.
            format (`str` or `AnnotationFormat`, *optional*, defaults to self.format):
                Format of the annotations.
            return_tensors (`str` or `TensorType`, *optional*, defaults to self.return_tensors):
                Type of tensors to return. If `None`, will return the list of images.
            data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
                The channel dimension format for the output image. Can be one of:
                - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
                - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
                - Unset: Use the channel dimension format of the input image.
            input_data_format (`ChannelDimension` or `str`, *optional*):
                The channel dimension format for the input image. If unset, the channel dimension format is inferred
                from the input image. Can be one of:
                - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
                - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
                - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
            pad_size (`Dict[str, int]`, *optional*):
                The size `{"height": int, "width" int}` to pad the images to. Must be larger than any image size
                provided for preprocessing. If `pad_size` is not provided, images will be padded to the largest
                height and width in the batch.
        """
        if 'pad_and_return_pixel_mask' in kwargs:
            logger.warning_once('The `pad_and_return_pixel_mask` argument is deprecated and will be removed in a future version, use `do_pad` instead.')
            do_pad = kwargs.pop('pad_and_return_pixel_mask')
        do_resize = self.do_resize if do_resize is None else do_resize
        size = self.size if size is None else size
        size = get_size_dict(size=size, default_to_square=False)
        resample = self.resample if resample is None else resample
        do_rescale = self.do_rescale if do_rescale is None else do_rescale
        rescale_factor = self.rescale_factor if rescale_factor is None else rescale_factor
        do_normalize = self.do_normalize if do_normalize is None else do_normalize
        image_mean = self.image_mean if image_mean is None else image_mean
        image_std = self.image_std if image_std is None else image_std
        do_convert_annotations = self.do_convert_annotations if do_convert_annotations is None else do_convert_annotations
        do_pad = self.do_pad if do_pad is None else do_pad
        pad_size = self.pad_size if pad_size is None else pad_size
        format = self.format if format is None else format
        validate_preprocess_arguments(do_rescale=do_rescale, rescale_factor=rescale_factor, do_normalize=do_normalize, image_mean=image_mean, image_std=image_std, do_resize=do_resize, size=size, resample=resample)
        if not is_batched(images):
            images = [images]
            annotations = [annotations] if annotations is not None else None
        if not valid_images(images):
            raise ValueError('Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, torch.Tensor, tf.Tensor or jax.ndarray.')
        if annotations is not None and len(images) != len(annotations):
            raise ValueError(f'The number of images ({len(images)}) and annotations ({len(annotations)}) do not match.')
        format = AnnotationFormat(format)
        if annotations is not None:
            validate_annotations(format, SUPPORTED_ANNOTATION_FORMATS, annotations)
        if masks_path is not None and format == AnnotationFormat.COCO_PANOPTIC and (not isinstance(masks_path, (pathlib.Path, str))):
            raise ValueError(f'The path to the directory containing the mask PNG files should be provided as a `pathlib.Path` or string object, but is {type(masks_path)} instead.')
        images = [to_numpy_array(image) for image in images]
        if do_rescale and is_scaled_image(images[0]):
            logger.warning_once('It looks like you are trying to rescale already rescaled images. If the input images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again.')
        if input_data_format is None:
            input_data_format = infer_channel_dimension_format(images[0])
        if annotations is not None:
            prepared_images = []
            prepared_annotations = []
            for image, target in zip(images, annotations):
                target = self.prepare_annotation(image, target, format, return_segmentation_masks=return_segmentation_masks, masks_path=masks_path, input_data_format=input_data_format)
                prepared_images.append(image)
                prepared_annotations.append(target)
            images = prepared_images
            annotations = prepared_annotations
            del prepared_images, prepared_annotations
        if do_resize:
            if annotations is not None:
                resized_images, resized_annotations = ([], [])
                for image, target in zip(images, annotations):
                    orig_size = get_image_size(image, input_data_format)
                    resized_image = self.resize(image, size=size, resample=resample, input_data_format=input_data_format)
                    resized_annotation = self.resize_annotation(target, orig_size, get_image_size(resized_image, input_data_format))
                    resized_images.append(resized_image)
                    resized_annotations.append(resized_annotation)
                images = resized_images
                annotations = resized_annotations
                del resized_images, resized_annotations
            else:
                images = [self.resize(image, size=size, resample=resample, input_data_format=input_data_format) for image in images]
        if do_rescale:
            images = [self.rescale(image, rescale_factor, input_data_format=input_data_format) for image in images]
        if do_normalize:
            images = [self.normalize(image, image_mean, image_std, input_data_format=input_data_format) for image in images]
        if do_convert_annotations and annotations is not None:
            annotations = [self.normalize_annotation(annotation, get_image_size(image, input_data_format)) for annotation, image in zip(annotations, images)]
        if do_pad:
            encoded_inputs = self.pad(images, annotations=annotations, return_pixel_mask=True, data_format=data_format, input_data_format=input_data_format, return_tensors=return_tensors, update_bboxes=do_convert_annotations, pad_size=pad_size)
        else:
            images = [to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images]
            encoded_inputs = BatchFeature(data={'pixel_values': images}, tensor_type=return_tensors)
            if annotations is not None:
                encoded_inputs['labels'] = [BatchFeature(annotation, tensor_type=return_tensors) for annotation in annotations]
        return encoded_inputs

    def post_process_object_detection(self, outputs, threshold: float=0.5, target_sizes: Union[TensorType, List[Tuple]]=None, nms_threshold: float=0.7):
        """
        Converts the output of [`DetaForObjectDetection`] into final bounding boxes in (top_left_x, top_left_y,
        bottom_right_x, bottom_right_y) format. Only supports PyTorch.

        Args:
            outputs ([`DetrObjectDetectionOutput`]):
                Raw outputs of the model.
            threshold (`float`, *optional*, defaults to 0.5):
                Score threshold to keep object detection predictions.
            target_sizes (`torch.Tensor` or `List[Tuple[int, int]]`, *optional*):
                Tensor of shape `(batch_size, 2)` or list of tuples (`Tuple[int, int]`) containing the target size
                (height, width) of each image in the batch. If left to None, predictions will not be resized.
            nms_threshold (`float`, *optional*, defaults to 0.7):
                NMS threshold.

        Returns:
            `List[Dict]`: A list of dictionaries, each dictionary containing the scores, labels and boxes for an image
            in the batch as predicted by the model.
        """
        out_logits, out_bbox = (outputs.logits, outputs.pred_boxes)
        batch_size, num_queries, num_labels = out_logits.shape
        if target_sizes is not None:
            if len(out_logits) != len(target_sizes):
                raise ValueError('Make sure that you pass in as many target sizes as the batch dimension of the logits')
        prob = out_logits.sigmoid()
        all_scores = prob.view(batch_size, num_queries * num_labels).to(out_logits.device)
        all_indexes = torch.arange(num_queries * num_labels)[None].repeat(batch_size, 1).to(out_logits.device)
        all_boxes = torch.div(all_indexes, out_logits.shape[2], rounding_mode='floor')
        all_labels = all_indexes % out_logits.shape[2]
        boxes = center_to_corners_format(out_bbox)
        boxes = torch.gather(boxes, 1, all_boxes.unsqueeze(-1).repeat(1, 1, 4))
        if target_sizes is not None:
            if isinstance(target_sizes, List):
                img_h = torch.Tensor([i[0] for i in target_sizes])
                img_w = torch.Tensor([i[1] for i in target_sizes])
            else:
                img_h, img_w = target_sizes.unbind(1)
            scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1).to(boxes.device)
            boxes = boxes * scale_fct[:, None, :]
        results = []
        for b in range(batch_size):
            box = boxes[b]
            score = all_scores[b]
            lbls = all_labels[b]
            pre_topk = score.topk(min(10000, num_queries * num_labels)).indices
            box = box[pre_topk]
            score = score[pre_topk]
            lbls = lbls[pre_topk]
            keep_inds = batched_nms(box, score, lbls, nms_threshold)[:100]
            score = score[keep_inds]
            lbls = lbls[keep_inds]
            box = box[keep_inds]
            results.append({'scores': score[score > threshold], 'labels': lbls[score > threshold], 'boxes': box[score > threshold]})
        return results

Constructs a Deformable DETR image processor.

Args:
    format (`str`, *optional*, defaults to `"coco_detection"`):
        Data format of the annotations. One of "coco_detection" or "coco_panoptic".
    do_resize (`bool`, *optional*, defaults to `True`):
        Controls whether to resize the image's (height, width) dimensions to the specified `size`. Can be
        overridden by the `do_resize` parameter in the `preprocess` method.
    size (`Dict[str, int]` *optional*, defaults to `{"shortest_edge": 800, "longest_edge": 1333}`):
        Size of the image's `(height, width)` dimensions after resizing. Can be overridden by the `size` parameter
        in the `preprocess` method. Available options are:
            - `{"height": int, "width": int}`: The image will be resized to the exact size `(height, width)`.
                Do NOT keep the aspect ratio.
            - `{"shortest_edge": int, "longest_edge": int}`: The image will be resized to a maximum size respecting
                the aspect ratio and keeping the shortest edge less or equal to `shortest_edge` and the longest edge
                less or equal to `longest_edge`.
            - `{"max_height": int, "max_width": int}`: The image will be resized to the maximum size respecting the
                aspect ratio and keeping the height less or equal to `max_height` and the width less or equal to
                `max_width`.
    resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
        Resampling filter to use if resizing the image.
    do_rescale (`bool`, *optional*, defaults to `True`):
        Controls whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the
        `do_rescale` parameter in the `preprocess` method.
    rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
        Scale factor to use if rescaling the image. Can be overridden by the `rescale_factor` parameter in the
        `preprocess` method.
    do_normalize:
        Controls whether to normalize the image. Can be overridden by the `do_normalize` parameter in the
        `preprocess` method.
    image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_DEFAULT_MEAN`):
        Mean values to use when normalizing the image. Can be a single value or a list of values, one for each
        channel. Can be overridden by the `image_mean` parameter in the `preprocess` method.
    image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_DEFAULT_STD`):
        Standard deviation values to use when normalizing the image. Can be a single value or a list of values, one
        for each channel. Can be overridden by the `image_std` parameter in the `preprocess` method.
    do_convert_annotations (`bool`, *optional*, defaults to `True`):
        Controls whether to convert the annotations to the format expected by the DETR model. Converts the
        bounding boxes to the format `(center_x, center_y, width, height)` and in the range `[0, 1]`.
        Can be overridden by the `do_convert_annotations` parameter in the `preprocess` method.
    do_pad (`bool`, *optional*, defaults to `True`):
        Controls whether to pad the image. Can be overridden by the `do_pad` parameter in the `preprocess`
        method. If `True`, padding will be applied to the bottom and right of the image with zeros.
        If `pad_size` is provided, the image will be padded to the specified dimensions.
        Otherwise, the image will be padded to the maximum height and width of the batch.
    pad_size (`Dict[str, int]`, *optional*):
        The size `{"height": int, "width" int}` to pad the images to. Must be larger than any image size
        provided for preprocessing. If `pad_size` is not provided, images will be padded to the largest
        height and width in the batch.


def _process_file_infos(file_infos):
    files = []
    num_elements = 0
    offsets = np.int64([])
    offset_sum = 0
    thresholds = np.int64([])
    threshold_sum = 0
    adjustment_needed = False
    for file_info in file_infos:
        files.append(file_info['path'])
        skip = 0
        if 'skip' in file_info:
            if file_info['skip'] < -1:
                raise ValueError('`skip` should be greater than `-1` but got {}'.format(file_info['skip']))
            if file_info['skip'] == -1:
                skip = file_info['num_elements']
            else:
                skip = min(file_info['skip'], file_info['num_elements'])
        take = file_info['num_elements'] - skip
        if 'take' in file_info:
            if file_info['take'] < -1:
                raise ValueError('`take` should be greater than `-1` but got {}'.format(file_info['take']))
            if file_info['take'] != -1:
                take = min(file_info['take'], take)
        remainder = file_info['num_elements'] - skip - take
        if take != file_info['num_elements']:
            adjustment_needed = True
        num_elements += take
        offsets = np.append(offsets, offset_sum + skip)
        offset_sum += skip + remainder
        thresholds = np.append(thresholds, threshold_sum)
        threshold_sum += take
    result = {'files': files, 'num_elements': num_elements}
    if adjustment_needed:
        result['offsets'] = offsets
        result['thresholds'] = thresholds
    return result

Computes aggregate information about files to read.

The method collects information about the files to read, the total number of
elements, and arrays that can be used to account for elements to be skipped,
which can be specified via the "skip" and "take" keys.

To account for elements to skip, the range of each file can be divided into
three regions:
- S (elements to skip)
- T (elements to read)
- R (remainder of elements that will also be skipped)

The `thresholds` and `offsets` arrays are initialized as follows:
`thresholds = [0, T_1, T_1 + T_2, ...]` and
`offsets = [S_1, S_1 + R_1 + S_2, S_1 + R_1 + S_2 + R_2 + S_3, ...]`

This makes it possible to map an index from a contiguous range
`(0...num_elements_to_read)` to an index in the range of all elements,
skipping over elements as per the "skip" and "take" keys values. In
particular, for a given input index `X`, we find the greatest `thresholds`
value that is smaller or equal to `X`. Let `t(X)` denotes such index in the
`thresholds` array. The output index is computed as `X + offsets[t(X)]`.

Args:
  file_infos: See `file_infos` argument of `index_shuffle` for details.

Returns:
  A dictionary containing the following keys:
    - `files`, the vector of pathnames of files to read
    - `num_elements`, an integer identifying the total number of elements
    - `offsets`, the vector of offsets to use for index adjustment (in case
      any elements should be skipped)
    - `thresholds`, the vector of thresholds to use for index adjustment (in
      case any elements should be skipped)


class LlavaOnevisionCausalLMOutputWithPast(ModelOutput):
    loss: Optional[torch.FloatTensor] = None
    logits: Optional[torch.FloatTensor] = None
    past_key_values: Optional[List[torch.FloatTensor]] = None
    hidden_states: Optional[Tuple[torch.FloatTensor]] = None
    attentions: Optional[Tuple[torch.FloatTensor]] = None
    image_hidden_states: Optional[torch.FloatTensor] = None
    video_hidden_states: Optional[torch.FloatTensor] = None

Base class for LlavaOnevision causal language model (or autoregressive) outputs.

Args:
    loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
        Language modeling loss (for next-token prediction).
    logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
        Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
    past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
        Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
        `(batch_size, num_heads, sequence_length, embed_size_per_head)`)

        Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
        `past_key_values` input) to speed up sequential decoding.
    hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
        Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
        one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.

        Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
    attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
        Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
        sequence_length)`.

        Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
        heads.
    image_hidden_states (`torch.FloatTensor`, *optional*):
        A `torch.FloatTensor` of size (batch_size * num_patches, num_images, sequence_length, hidden_size)`.
        image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.

    video_hidden_states (`torch.FloatTensor`, *optional*):
        A `torch.FloatTensor`  of size `(batch_size * num_frames, num_videos, sequence_length, hidden_size)`.
        video_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.


def index_of(self, value_str):
    if value_str is None:
        value_str = ''
    if value_str in self._string_to_index:
        return self._string_to_index[value_str]
    index = len(self._string_table)
    self._string_table.append(value_str)
    self._string_to_index[value_str] = index
    return index

Get index of value_str in the string table.

If value_str is not in the string table, we will add it at the end
and then return the new index.
Args:
  value_str: (string) Value to lookup/add in/to the string table.

Returns:
  Index of value_str in the string table.


def _get_raw_feature_as_tensor(self, key):
    raw_feature = self._features[key]
    feature_tensor = sparse_tensor_lib.convert_to_tensor_or_sparse_tensor(raw_feature)

    def expand_dims(input_tensor):
        if isinstance(input_tensor, sparse_tensor_lib.SparseTensor):
            return sparse_ops.sparse_reshape(input_tensor, [array_ops.shape(input_tensor)[0], 1])
        else:
            return array_ops.expand_dims(input_tensor, -1)
    rank = feature_tensor.get_shape().ndims
    if rank is not None:
        if rank == 0:
            raise ValueError('Feature (key: {}) cannot have rank 0. Given: {}'.format(key, feature_tensor))
        return feature_tensor if rank != 1 else expand_dims(feature_tensor)
    with ops.control_dependencies([check_ops.assert_positive(array_ops.rank(feature_tensor), message='Feature (key: {}) cannot have rank 0. Given: {}'.format(key, feature_tensor))]):
        return cond.cond(math_ops.equal(1, array_ops.rank(feature_tensor)), lambda: expand_dims(feature_tensor), lambda: feature_tensor)

Gets the raw_feature (keyed by `key`) as `tensor`.

The raw feature is converted to (sparse) tensor and maybe expand dim.

For both `Tensor` and `SparseTensor`, the rank will be expanded (to 2) if
the rank is 1. This supports dynamic rank also. For rank 0 raw feature, will
error out as it is not supported.

Args:
  key: A `str` key to access the raw feature.

Returns:
  A `Tensor` or `SparseTensor`.

Raises:
  ValueError: if the raw feature has rank 0.


def restore(self, sess, save_path):
    start_time = time.time()
    if self._is_empty:
        return
    if save_path is None:
        raise ValueError("Can't load save_path when it is None.")
    checkpoint_prefix = compat.as_text(save_path)
    if not checkpoint_management.checkpoint_exists_internal(checkpoint_prefix):
        raise ValueError('The passed save_path is not a valid checkpoint: ' + checkpoint_prefix)
    logging.info('Restoring parameters from %s', checkpoint_prefix)
    try:
        if context.executing_eagerly():
            self._build_eager(save_path, build_save=False, build_restore=True)
        else:
            sess.run(self.saver_def.restore_op_name, {self.saver_def.filename_tensor_name: save_path})
    except errors.NotFoundError as err:
        try:
            names_to_keys = object_graph_key_mapping(save_path)
        except errors.NotFoundError:
            raise _wrap_restore_error_with_msg(err, 'a Variable name or other graph key that is missing')
        logging.warning('Restoring an object-based checkpoint using a name-based saver. This may be somewhat fragile, and will re-build the Saver. Instead, consider loading object-based checkpoints using tf.train.Checkpoint().')
        self._object_restore_saver = saver_from_object_based_checkpoint(checkpoint_path=save_path, var_list=self._var_list, builder=self._builder, names_to_keys=names_to_keys, cached_saver=self._object_restore_saver)
        self._object_restore_saver.restore(sess=sess, save_path=save_path)
    except errors.InvalidArgumentError as err:
        raise _wrap_restore_error_with_msg(err, 'a mismatch between the current graph and the graph')
    metrics.AddCheckpointReadDuration(api_label=_SAVER_LABEL, microseconds=_get_duration_microseconds(start_time, time.time()))

Restores previously saved variables.

This method runs the ops added by the constructor for restoring variables.
It requires a session in which the graph was launched.  The variables to
restore do not have to have been initialized, as restoring is itself a way
to initialize variables.

The `save_path` argument is typically a value previously returned from a
`save()` call, or a call to `latest_checkpoint()`.

Args:
  sess: A `Session` to use to restore the parameters. None in eager mode.
  save_path: Path where parameters were previously saved.

Raises:
  ValueError: If save_path is None or not a valid checkpoint.


def _get_object_type(filename, filepath):
    filename_no_ext = os.path.splitext(filename)[0].lower()
    if filename_no_ext.endswith(PrecompiledExampleType.test_ends):
        object_type = PRECOMPILED_OBJECT_TYPE_UNIT_TEST
    elif PrecompiledExampleType.katas in filepath.split(os.sep):
        object_type = PRECOMPILED_OBJECT_TYPE_KATA
    elif PrecompiledExampleType.examples in filepath.split(os.sep):
        object_type = PRECOMPILED_OBJECT_TYPE_EXAMPLE
    else:
        object_type = PRECOMPILED_OBJECT_TYPE_UNSPECIFIED
    return object_type

Get type of an object based on it filename/filepath

Args:
    filename: object's filename
    filepath: object's filepath

Returns: type of the object (example, kata, unit-test)


class RobertaTokenizerFast(PreTrainedTokenizerFast):
    vocab_files_names = VOCAB_FILES_NAMES
    model_input_names = ['input_ids', 'attention_mask']
    slow_tokenizer_class = RobertaTokenizer

    def __init__(self, vocab_file=None, merges_file=None, tokenizer_file=None, errors='replace', bos_token='<s>', eos_token='</s>', sep_token='</s>', cls_token='<s>', unk_token='<unk>', pad_token='<pad>', mask_token='<mask>', add_prefix_space=False, trim_offsets=True, **kwargs):
        mask_token = AddedToken(mask_token, lstrip=True, rstrip=False, normalized=False) if isinstance(mask_token, str) else mask_token
        super().__init__(vocab_file, merges_file, tokenizer_file=tokenizer_file, errors=errors, bos_token=bos_token, eos_token=eos_token, sep_token=sep_token, cls_token=cls_token, unk_token=unk_token, pad_token=pad_token, mask_token=mask_token, add_prefix_space=add_prefix_space, trim_offsets=trim_offsets, **kwargs)
        tokenizer_component = 'post_processor'
        tokenizer_component_instance = getattr(self.backend_tokenizer, tokenizer_component, None)
        if tokenizer_component_instance:
            state = json.loads(tokenizer_component_instance.__getstate__())
            if 'sep' in state:
                state['sep'] = tuple(state['sep'])
            if 'cls' in state:
                state['cls'] = tuple(state['cls'])
            changes_to_apply = False
            if state.get('add_prefix_space', add_prefix_space) != add_prefix_space:
                state['add_prefix_space'] = add_prefix_space
                changes_to_apply = True
            if state.get('trim_offsets', trim_offsets) != trim_offsets:
                state['trim_offsets'] = trim_offsets
                changes_to_apply = True
            if changes_to_apply:
                component_class = getattr(processors, state.pop('type'))
                new_value = component_class(**state)
                setattr(self.backend_tokenizer, tokenizer_component, new_value)

    @property
    def mask_token(self) -> str:
        """
        `str`: Mask token, to use when training a model with masked-language modeling. Log an error if used while not
        having been set.

        Roberta tokenizer has a special mask token to be usable in the fill-mask pipeline. The mask token will greedily
        comprise the space before the *<mask>*.
        """
        if self._mask_token is None:
            if self.verbose:
                logger.error('Using mask_token, but it is not set yet.')
            return None
        return str(self._mask_token)

    @mask_token.setter
    def mask_token(self, value):
        """
        Overriding the default behavior of the mask token to have it eat the space before it.

        This is needed to preserve backward compatibility with all the previously used models based on Roberta.
        """
        value = AddedToken(value, lstrip=True, rstrip=False) if isinstance(value, str) else value
        self._mask_token = value

    def _batch_encode_plus(self, *args, **kwargs) -> BatchEncoding:
        is_split_into_words = kwargs.get('is_split_into_words', False)
        assert self.add_prefix_space or not is_split_into_words, f'You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with pretokenized inputs.'
        return super()._batch_encode_plus(*args, **kwargs)

    def _encode_plus(self, *args, **kwargs) -> BatchEncoding:
        is_split_into_words = kwargs.get('is_split_into_words', False)
        assert self.add_prefix_space or not is_split_into_words, f'You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with pretokenized inputs.'
        return super()._encode_plus(*args, **kwargs)

    def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str]=None) -> Tuple[str]:
        files = self._tokenizer.model.save(save_directory, name=filename_prefix)
        return tuple(files)

    def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
        output = [self.bos_token_id] + token_ids_0 + [self.eos_token_id]
        if token_ids_1 is None:
            return output
        return output + [self.eos_token_id] + token_ids_1 + [self.eos_token_id]

    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. RoBERTa 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]`, *optional*):
                Optional second list of IDs for sequence pairs.

        Returns:
            `List[int]`: List of zeros.
        """
        sep = [self.sep_token_id]
        cls = [self.cls_token_id]
        if token_ids_1 is None:
            return len(cls + token_ids_0 + sep) * [0]
        return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]

Construct a "fast" RoBERTa tokenizer (backed by HuggingFace's *tokenizers* library), derived from the GPT-2
tokenizer, using byte-level Byte-Pair-Encoding.

This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
be encoded differently whether it is at the beginning of the sentence (without space) or not:

```python
>>> from transformers import RobertaTokenizerFast

>>> tokenizer = RobertaTokenizerFast.from_pretrained("FacebookAI/roberta-base")
>>> tokenizer("Hello world")["input_ids"]
[0, 31414, 232, 2]

>>> tokenizer(" Hello world")["input_ids"]
[0, 20920, 232, 2]
```

You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.

<Tip>

When used with `is_split_into_words=True`, this tokenizer needs to be instantiated with `add_prefix_space=True`.

</Tip>

This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
refer to this superclass for more information regarding those methods.

Args:
    vocab_file (`str`):
        Path to the vocabulary file.
    merges_file (`str`):
        Path to the merges file.
    errors (`str`, *optional*, defaults to `"replace"`):
        Paradigm to follow when decoding bytes to UTF-8. See
        [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
    bos_token (`str`, *optional*, defaults to `"<s>"`):
        The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.

        <Tip>

        When building a sequence using special tokens, this is not the token that is used for the beginning of
        sequence. The token used is the `cls_token`.

        </Tip>

    eos_token (`str`, *optional*, defaults to `"</s>"`):
        The end of sequence token.

        <Tip>

        When building a sequence using special tokens, this is not the token that is used for the end of sequence.
        The token used is the `sep_token`.

        </Tip>

    sep_token (`str`, *optional*, defaults to `"</s>"`):
        The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
        sequence classification or for a text and a question for question answering. It is also used as the last
        token of a sequence built with special tokens.
    cls_token (`str`, *optional*, defaults to `"<s>"`):
        The classifier token which is used when doing sequence classification (classification of the whole sequence
        instead of per-token classification). It is the first token of the sequence when built with special tokens.
    unk_token (`str`, *optional*, defaults to `"<unk>"`):
        The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
        token instead.
    pad_token (`str`, *optional*, defaults to `"<pad>"`):
        The token used for padding, for example when batching sequences of different lengths.
    mask_token (`str`, *optional*, defaults to `"<mask>"`):
        The token used for masking values. This is the token used when training this model with masked language
        modeling. This is the token which the model will try to predict.
    add_prefix_space (`bool`, *optional*, defaults to `False`):
        Whether or not to add an initial space to the input. This allows to treat the leading word just as any
        other word. (RoBERTa tokenizer detect beginning of words by the preceding space).
    trim_offsets (`bool`, *optional*, defaults to `True`):
        Whether the post processing step should trim offsets to avoid including whitespaces.


class SquaredHinge(reduction_metrics.MeanMetricWrapper):

    def __init__(self, name='squared_hinge', dtype=None):
        super().__init__(fn=squared_hinge, name=name, dtype=dtype)
        self._direction = 'down'

    def get_config(self):
        return {'name': self.name, 'dtype': self.dtype}

Computes the hinge metric between `y_true` and `y_pred`.

`y_true` values are expected to be -1 or 1. If binary (0 or 1) labels are
provided we will convert them to -1 or 1.

Args:
    name: (Optional) string name of the metric instance.
    dtype: (Optional) data type of the metric result.

Example:

>>> m = keras.metrics.SquaredHinge()
>>> m.update_state([[0, 1], [0, 0]], [[0.6, 0.4], [0.4, 0.6]])
>>> m.result()
1.86
>>> m.reset_state()
>>> m.update_state([[0, 1], [0, 0]], [[0.6, 0.4], [0.4, 0.6]],
...                sample_weight=[1, 0])
>>> m.result()
1.46


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.Tensor]=None, input_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.Tensor]=None, inputs_embeds: Optional[torch.Tensor]=None, labels: Optional[torch.Tensor]=None, use_mems: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, **kwargs) -> Union[Tuple, XLNetLMHeadModelOutput]:
    return_dict = return_dict if return_dict is not None else self.config.use_return_dict
    transformer_outputs = self.transformer(input_ids, attention_mask=attention_mask, mems=mems, perm_mask=perm_mask, target_mapping=target_mapping, token_type_ids=token_type_ids, input_mask=input_mask, head_mask=head_mask, inputs_embeds=inputs_embeds, use_mems=use_mems, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, **kwargs)
    logits = self.lm_loss(transformer_outputs[0])
    loss = None
    if labels is not None:
        loss_fct = CrossEntropyLoss()
        loss = loss_fct(logits.view(-1, logits.size(-1)), labels.view(-1))
    if not return_dict:
        output = (logits,) + transformer_outputs[1:]
        return (loss,) + output if loss is not None else output
    return XLNetLMHeadModelOutput(loss=loss, logits=logits, mems=transformer_outputs.mems, hidden_states=transformer_outputs.hidden_states, attentions=transformer_outputs.attentions)

mems (`List[torch.FloatTensor]` of length `config.n_layers`):
    Contains pre-computed hidden-states (see `mems` output below) . Can be used to speed up sequential
    decoding. The token ids which have their past given to this model should not be passed as `input_ids` as
    they have already been computed.

    `use_mems` has to be set to `True` to make use of `mems`.
perm_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length, sequence_length)`, *optional*):
    Mask to indicate the attention pattern for each input token with values selected in `[0, 1]`:

    - if `perm_mask[k, i, j] = 0`, i attend to j in batch k;
    - if `perm_mask[k, i, j] = 1`, i does not attend to j in batch k.

    If not set, each token attends to all the others (full bidirectional attention). Only used during
    pretraining (to define factorization order) or for sequential decoding (generation).
target_mapping (`torch.FloatTensor` of shape `(batch_size, num_predict, sequence_length)`, *optional*):
    Mask to indicate the output tokens to use. If `target_mapping[k, i, j] = 1`, the i-th predict in batch k is
    on the j-th token. Only used during pretraining for partial prediction or for sequential decoding
    (generation).
input_mask (`torch.FloatTensor` of shape `batch_size, sequence_length`, *optional*):
    Mask to avoid performing attention on padding token indices. Negative of `attention_mask`, i.e. with 0 for
    real tokens and 1 for padding which is kept for compatibility with the original code base.

    Mask values selected in `[0, 1]`:

    - 1 for tokens that are **masked**,
    - 0 for tokens that are **not masked**.

    You can only uses one of `input_mask` and `attention_mask`.
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 correspond to the masked input words that should be predicted and depends on
    `target_mapping`. Note in order to perform standard auto-regressive language modeling a *<mask>* token has
    to be added to the `input_ids` (see the `prepare_inputs_for_generation` function and examples below)

    Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100` are ignored, the loss
    is only computed for labels in `[0, ..., config.vocab_size]`
use_mems (`bool`, *optional*):
    Whether to use memory states to speed up sequential decoding. If set to `True`, the model will use the hidden
    states from previous forward passes to compute attention, which can significantly improve performance for
    sequential decoding tasks.

Examples:

```python
>>> from transformers import AutoTokenizer, XLNetLMHeadModel
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("xlnet/xlnet-large-cased")
>>> model = XLNetLMHeadModel.from_pretrained("xlnet/xlnet-large-cased")

>>> # We show how to setup inputs to predict a next token using a bi-directional context.
>>> input_ids = torch.tensor(
...     tokenizer.encode("Hello, my dog is very <mask>", add_special_tokens=False)
... ).unsqueeze(
...     0
... )  # We will predict the masked token
>>> perm_mask = torch.zeros((1, input_ids.shape[1], input_ids.shape[1]), dtype=torch.float)
>>> perm_mask[:, :, -1] = 1.0  # Previous tokens don't see last token
>>> target_mapping = torch.zeros(
...     (1, 1, input_ids.shape[1]), dtype=torch.float
... )  # Shape [1, 1, seq_length] => let's predict one token
>>> target_mapping[
...     0, 0, -1
... ] = 1.0  # Our first (and only) prediction will be the last token of the sequence (the masked token)

>>> outputs = model(input_ids, perm_mask=perm_mask, target_mapping=target_mapping)
>>> next_token_logits = outputs[
...     0
... ]  # Output has shape [target_mapping.size(0), target_mapping.size(1), config.vocab_size]

>>> # The same way can the XLNetLMHeadModel be used to be trained by standard auto-regressive language modeling.
>>> input_ids = torch.tensor(
...     tokenizer.encode("Hello, my dog is very <mask>", add_special_tokens=False)
... ).unsqueeze(
...     0
... )  # We will predict the masked token
>>> labels = torch.tensor(tokenizer.encode("cute", add_special_tokens=False)).unsqueeze(0)
>>> assert labels.shape[0] == 1, "only one word will be predicted"
>>> perm_mask = torch.zeros((1, input_ids.shape[1], input_ids.shape[1]), dtype=torch.float)
>>> perm_mask[
...     :, :, -1
... ] = 1.0  # Previous tokens don't see last token as is done in standard auto-regressive lm training
>>> target_mapping = torch.zeros(
...     (1, 1, input_ids.shape[1]), dtype=torch.float
... )  # Shape [1, 1, seq_length] => let's predict one token
>>> target_mapping[
...     0, 0, -1
... ] = 1.0  # Our first (and only) prediction will be the last token of the sequence (the masked token)

>>> outputs = model(input_ids, perm_mask=perm_mask, target_mapping=target_mapping, labels=labels)
>>> loss = outputs.loss
>>> next_token_logits = (
...     outputs.logits
... )  # Logits have shape [target_mapping.size(0), target_mapping.size(1), config.vocab_size]
```


def class_from_typename(cls, type_name: str) -> Optional[Type['JSONConvertible']]:
    return cls._TYPE_REGISTRY.class_from_typename(type_name)

Gets the class for a registered type name.

Args:
  type_name: A string as the global unique type identifier for requested
    class.

Returns:
  A type object if registered, otherwise None.


def _tf_data_pack_sequence_as(structure, flat_sequence):
    if not (_tf_data_is_nested(flat_sequence) or isinstance(flat_sequence, list)):
        raise TypeError(f"Argument `flat_sequence` must be a sequence. Got '{type(flat_sequence).__name__}'.")
    if not _tf_data_is_nested(structure):
        if len(flat_sequence) != 1:
            raise ValueError(f'Argument `structure` is a scalar but `len(flat_sequence)`={len(flat_sequence)} > 1')
        return flat_sequence[0]
    flat_structure = _tf_data_flatten(structure)
    if len(flat_structure) != len(flat_sequence):
        raise ValueError(f'Could not pack sequence. Argument `structure` had {len(flat_structure)} elements, but argument `flat_sequence` had {len(flat_sequence)} elements. Received structure: {structure}, flat_sequence: {flat_sequence}.')
    _, packed = _tf_data_packed_nest_with_indices(structure, flat_sequence, 0)
    return sequence_like(structure, packed)

Returns a given flattened sequence packed into a nest.

If `structure` is a scalar, `flat_sequence` must be a single-element list;
in this case the return value is `flat_sequence[0]`.

Args:
  structure: tuple or list constructed of scalars and/or other tuples/lists,
    or a scalar.  Note: numpy arrays are considered scalars.
  flat_sequence: flat sequence to pack.

Returns:
  packed: `flat_sequence` converted to have the same recursive structure as
    `structure`.

Raises:
  ValueError: If nest and structure have different element counts.


def post_process_depth_estimation(self, outputs: 'DepthEstimatorOutput', target_sizes: Optional[Union[TensorType, List[Tuple[int, int]], None]]=None) -> List[Dict[str, TensorType]]:
    requires_backends(self, 'torch')
    predicted_depth = outputs.predicted_depth
    if target_sizes is not None and len(predicted_depth) != len(target_sizes):
        raise ValueError('Make sure that you pass in as many target sizes as the batch dimension of the predicted depth')
    results = []
    target_sizes = [None] * len(predicted_depth) if target_sizes is None else target_sizes
    for depth, target_size in zip(predicted_depth, target_sizes):
        if target_size is not None:
            depth = depth[None, None, ...]
            depth = torch.nn.functional.interpolate(depth, size=target_size, mode='bicubic', align_corners=False)
            depth = depth.squeeze()
        results.append({'predicted_depth': depth})
    return results

Converts the raw output of [`DepthEstimatorOutput`] into final depth predictions and depth PIL images.
Only supports PyTorch.

Args:
    outputs ([`DepthEstimatorOutput`]):
        Raw outputs of the model.
    target_sizes (`TensorType` or `List[Tuple[int, int]]`, *optional*):
        Tensor of shape `(batch_size, 2)` or list of tuples (`Tuple[int, int]`) containing the target size
        (height, width) of each image in the batch. If left to None, predictions will not be resized.

Returns:
    `List[Dict[str, TensorType]]`: A list of dictionaries of tensors representing the processed depth
    predictions.


def sequence_categorical_column_with_vocabulary_file(key, vocabulary_file, vocabulary_size=None, num_oov_buckets=0, default_value=None, dtype=dtypes.string):
    return fc.SequenceCategoricalColumn(fc.categorical_column_with_vocabulary_file(key=key, vocabulary_file=vocabulary_file, vocabulary_size=vocabulary_size, num_oov_buckets=num_oov_buckets, default_value=default_value, dtype=dtype))

A sequence of categorical terms where ids use a vocabulary file.

Pass this to `embedding_column` or `indicator_column` to convert sequence
categorical data into dense representation for input to sequence NN, such as
RNN.

Example:

```python
states = sequence_categorical_column_with_vocabulary_file(
    key='states', vocabulary_file='/us/states.txt', vocabulary_size=50,
    num_oov_buckets=5)
states_embedding = embedding_column(states, dimension=10)
columns = [states_embedding]

features = tf.io.parse_example(..., features=make_parse_example_spec(columns))
sequence_feature_layer = SequenceFeatures(columns)
sequence_input, sequence_length = sequence_feature_layer(features)
sequence_length_mask = tf.sequence_mask(sequence_length)

rnn_cell = tf.keras.layers.SimpleRNNCell(hidden_size)
rnn_layer = tf.keras.layers.RNN(rnn_cell)
outputs, state = rnn_layer(sequence_input, mask=sequence_length_mask)
```

Args:
  key: A unique string identifying the input feature.
  vocabulary_file: The vocabulary file name.
  vocabulary_size: Number of the elements in the vocabulary. This must be no
    greater than length of `vocabulary_file`, if less than length, later
    values are ignored. If None, it is set to the length of `vocabulary_file`.
  num_oov_buckets: Non-negative integer, the number of out-of-vocabulary
    buckets. All out-of-vocabulary inputs will be assigned IDs in the range
    `[vocabulary_size, vocabulary_size+num_oov_buckets)` based on a hash of
    the input value. A positive `num_oov_buckets` can not be specified with
    `default_value`.
  default_value: The integer ID value to return for out-of-vocabulary feature
    values, defaults to `-1`. This can not be specified with a positive
    `num_oov_buckets`.
  dtype: The type of features. Only string and integer types are supported.

Returns:
  A `SequenceCategoricalColumn`.

Raises:
  ValueError: `vocabulary_file` is missing or cannot be opened.
  ValueError: `vocabulary_size` is missing or < 1.
  ValueError: `num_oov_buckets` is a negative integer.
  ValueError: `num_oov_buckets` and `default_value` are both specified.
  ValueError: `dtype` is neither string nor integer.


def _parallel_part_processors(part_processors: Sequence[PartProcessorWithMatchFn]) -> PartProcessorFn:

    async def part_processor(content: ProcessorPart) -> AsyncIterable[ProcessorPart]:
        output_queue = asyncio.Queue()
        processors = []
        match_fns = []
        passthrough_fallback = False
        passthrough_always = False
        for p in part_processors:
            if p is PASSTHROUGH_FALLBACK:
                passthrough_fallback = True
                continue
            if p is PASSTHROUGH_ALWAYS:
                passthrough_always = True
                continue
            processors.append(_CaptureReservedSubstreams(output_queue, p))
            match_fns.append(p.match)
        parallel_processor = _CaptureReservedSubstreams(output_queue, map_processor.parallel_part_functions(processors, match_fns, with_default_output=passthrough_fallback, with_always_output=passthrough_always))
        content = parallel_processor(content)
        create_task(_enqueue_content(content, output_queue))
        while (part := (await output_queue.get())) is not None:
            yield part
            output_queue.task_done()
    return part_processor

Combine **part processors** in parallel.

Adds debug and status streams to the output.

NOTE: Substreams debug and status are yielded immediately instead of passing
      them to the next processor.

Args:
  part_processors: sequence of part processors to compute concurrently.

Returns:
  Part processor that computes the output of the provided sequence of part
  processors concurrently.


def Insert(self, request, global_params=None):
    config = self.GetMethodConfig('Insert')
    return self._RunMethod(config, request, global_params=global_params)

Creates a new empty dataset.

Args:
  request: (BigqueryDatasetsInsertRequest) input message
  global_params: (StandardQueryParameters, default: None) global arguments
Returns:
  (Dataset) The response message.


def preprocess(self, images: ImageInput, do_resize: Optional[bool]=None, size: Optional[Dict[str, int]]=None, resample: PILImageResampling=None, do_rescale: Optional[bool]=None, rescale_factor: Optional[float]=None, do_normalize: Optional[bool]=None, image_mean: Optional[Union[float, List[float]]]=None, image_std: Optional[Union[float, List[float]]]=None, return_tensors: Optional[Union[str, TensorType]]=None, data_format: Union[str, ChannelDimension]=ChannelDimension.FIRST, input_data_format: Optional[Union[str, ChannelDimension]]=None):
    do_resize = do_resize if do_resize is not None else self.do_resize
    do_rescale = do_rescale if do_rescale is not None else self.do_rescale
    do_normalize = do_normalize if do_normalize is not None else self.do_normalize
    resample = resample if resample is not None else self.resample
    rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
    image_mean = image_mean if image_mean is not None else self.image_mean
    image_std = image_std if image_std is not None else self.image_std
    size = size if size is not None else self.size
    size_dict = get_size_dict(size)
    images = make_list_of_images(images)
    if not valid_images(images):
        raise ValueError('Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, torch.Tensor, tf.Tensor or jax.ndarray.')
    validate_preprocess_arguments(do_rescale=do_rescale, rescale_factor=rescale_factor, do_normalize=do_normalize, image_mean=image_mean, image_std=image_std, do_resize=do_resize, size=size, resample=resample)
    images = [to_numpy_array(image) for image in images]
    if do_rescale and is_scaled_image(images[0]):
        logger.warning_once('It looks like you are trying to rescale already rescaled images. If the input images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again.')
    if input_data_format is None:
        input_data_format = infer_channel_dimension_format(images[0])
    if do_resize:
        images = [self.resize(image=image, size=size_dict, resample=resample, input_data_format=input_data_format) for image in images]
    if do_rescale:
        images = [self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format) for image in images]
    if do_normalize:
        images = [self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format) for image in images]
    images = [to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images]
    data = {'pixel_values': images}
    return BatchFeature(data=data, tensor_type=return_tensors)

Preprocess an image or batch of images.

Args:
    images (`ImageInput`):
        Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
        passing in images with pixel values between 0 and 1, set `do_rescale=False`.
    do_resize (`bool`, *optional*, defaults to `self.do_resize`):
        Whether to resize the image.
    size (`Dict[str, int]`, *optional*, defaults to `self.size`):
        Dictionary in the format `{"height": h, "width": w}` specifying the size of the output image after
        resizing.
    resample (`PILImageResampling` filter, *optional*, defaults to `self.resample`):
        `PILImageResampling` filter to use if resizing the image e.g. `PILImageResampling.BILINEAR`. Only has
        an effect if `do_resize` is set to `True`.
    do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
        Whether to rescale the image values between [0 - 1].
    rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
        Rescale factor to rescale the image by if `do_rescale` is set to `True`.
    do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
        Whether to normalize the image.
    image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
        Image mean to use if `do_normalize` is set to `True`.
    image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
        Image standard deviation to use if `do_normalize` is set to `True`.
    return_tensors (`str` or `TensorType`, *optional*):
        The type of tensors to return. Can be one of:
        - Unset: Return a list of `np.ndarray`.
        - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
        - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
        - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
        - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
    data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
        The channel dimension format for the output image. Can be one of:
        - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
        - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
        - Unset: Use the channel dimension format of the input image.
    input_data_format (`ChannelDimension` or `str`, *optional*):
        The channel dimension format for the input image. If unset, the channel dimension format is inferred
        from the input image. Can be one of:
        - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
        - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
        - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.


def __call__(self, input_tensor: core.Tensor) -> Mapping[str, core.Tensor]:
    out = math_ops.matmul(input_tensor, self.filters)
    return {'output': out}

Performs a matrix multiplication.

Args:
  input_tensor: Input tensor to matmul with the filter.

Returns:
  A map of: output key -> output result.


class Callback:

    def __init__(self):
        self.validation_data = None
        self.model = None
        self._chief_worker_only = None
        self._supports_tf_logs = False

    def set_params(self, params):
        self.params = params

    def set_model(self, model):
        self.model = model

    @doc_controls.for_subclass_implementers
    @generic_utils.default
    def on_batch_begin(self, batch, logs=None):
        """A backwards compatibility alias for `on_train_batch_begin`."""

    @doc_controls.for_subclass_implementers
    @generic_utils.default
    def on_batch_end(self, batch, logs=None):
        """A backwards compatibility alias for `on_train_batch_end`."""

    @doc_controls.for_subclass_implementers
    def on_epoch_begin(self, epoch, logs=None):
        """Called at the start of an epoch.

    Subclasses should override for any actions to run. This function should only
    be called during TRAIN mode.

    Args:
        epoch: Integer, index of epoch.
        logs: Dict. Currently no data is passed to this argument for this method
          but that may change in the future.
    """

    @doc_controls.for_subclass_implementers
    def on_epoch_end(self, epoch, logs=None):
        """Called at the end of an epoch.

    Subclasses should override for any actions to run. This function should only
    be called during TRAIN mode.

    Args:
        epoch: Integer, index of epoch.
        logs: Dict, metric results for this training epoch, and for the
          validation epoch if validation is performed. Validation result keys
          are prefixed with `val_`. For training epoch, the values of the
         `Model`'s metrics are returned. Example : `{'loss': 0.2, 'accuracy':
           0.7}`.
    """

    @doc_controls.for_subclass_implementers
    @generic_utils.default
    def on_train_batch_begin(self, batch, logs=None):
        """Called at the beginning of a training batch in `fit` methods.

    Subclasses should override for any actions to run.

    Note that if the `steps_per_execution` argument to `compile` in
    `tf.keras.Model` is set to `N`, this method will only be called every `N`
    batches.

    Args:
        batch: Integer, index of batch within the current epoch.
        logs: Dict, contains the return value of `model.train_step`. Typically,
          the values of the `Model`'s metrics are returned.  Example:
          `{'loss': 0.2, 'accuracy': 0.7}`.
    """
        self.on_batch_begin(batch, logs=logs)

    @doc_controls.for_subclass_implementers
    @generic_utils.default
    def on_train_batch_end(self, batch, logs=None):
        """Called at the end of a training batch in `fit` methods.

    Subclasses should override for any actions to run.

    Note that if the `steps_per_execution` argument to `compile` in
    `tf.keras.Model` is set to `N`, this method will only be called every `N`
    batches.

    Args:
        batch: Integer, index of batch within the current epoch.
        logs: Dict. Aggregated metric results up until this batch.
    """
        self.on_batch_end(batch, logs=logs)

    @doc_controls.for_subclass_implementers
    @generic_utils.default
    def on_test_batch_begin(self, batch, logs=None):
        """Called at the beginning of a batch in `evaluate` methods.

    Also called at the beginning of a validation batch in the `fit`
    methods, if validation data is provided.

    Subclasses should override for any actions to run.

    Note that if the `steps_per_execution` argument to `compile` in
    `tf.keras.Model` is set to `N`, this method will only be called every `N`
    batches.

    Args:
        batch: Integer, index of batch within the current epoch.
        logs: Dict, contains the return value of `model.test_step`. Typically,
          the values of the `Model`'s metrics are returned.  Example:
          `{'loss': 0.2, 'accuracy': 0.7}`.
    """

    @doc_controls.for_subclass_implementers
    @generic_utils.default
    def on_test_batch_end(self, batch, logs=None):
        """Called at the end of a batch in `evaluate` methods.

    Also called at the end of a validation batch in the `fit`
    methods, if validation data is provided.

    Subclasses should override for any actions to run.

    Note that if the `steps_per_execution` argument to `compile` in
    `tf.keras.Model` is set to `N`, this method will only be called every `N`
    batches.

    Args:
        batch: Integer, index of batch within the current epoch.
        logs: Dict. Aggregated metric results up until this batch.
    """

    @doc_controls.for_subclass_implementers
    @generic_utils.default
    def on_predict_batch_begin(self, batch, logs=None):
        """Called at the beginning of a batch in `predict` methods.

    Subclasses should override for any actions to run.

    Note that if the `steps_per_execution` argument to `compile` in
    `tf.keras.Model` is set to `N`, this method will only be called every `N`
    batches.

    Args:
        batch: Integer, index of batch within the current epoch.
        logs: Dict, contains the return value of `model.predict_step`,
          it typically returns a dict with a key 'outputs' containing
          the model's outputs.
    """

    @doc_controls.for_subclass_implementers
    @generic_utils.default
    def on_predict_batch_end(self, batch, logs=None):
        """Called at the end of a batch in `predict` methods.

    Subclasses should override for any actions to run.

    Note that if the `steps_per_execution` argument to `compile` in
    `tf.keras.Model` is set to `N`, this method will only be called every `N`
    batches.

    Args:
        batch: Integer, index of batch within the current epoch.
        logs: Dict. Aggregated metric results up until this batch.
    """

    @doc_controls.for_subclass_implementers
    def on_train_begin(self, logs=None):
        """Called at the beginning of training.

    Subclasses should override for any actions to run.

    Args:
        logs: Dict. Currently no data is passed to this argument for this method
          but that may change in the future.
    """

    @doc_controls.for_subclass_implementers
    def on_train_end(self, logs=None):
        """Called at the end of training.

    Subclasses should override for any actions to run.

    Args:
        logs: Dict. Currently the output of the last call to `on_epoch_end()`
          is passed to this argument for this method but that may change in
          the future.
    """

    @doc_controls.for_subclass_implementers
    def on_test_begin(self, logs=None):
        """Called at the beginning of evaluation or validation.

    Subclasses should override for any actions to run.

    Args:
        logs: Dict. Currently no data is passed to this argument for this method
          but that may change in the future.
    """

    @doc_controls.for_subclass_implementers
    def on_test_end(self, logs=None):
        """Called at the end of evaluation or validation.

    Subclasses should override for any actions to run.

    Args:
        logs: Dict. Currently the output of the last call to
          `on_test_batch_end()` is passed to this argument for this method
          but that may change in the future.
    """

    @doc_controls.for_subclass_implementers
    def on_predict_begin(self, logs=None):
        """Called at the beginning of prediction.

    Subclasses should override for any actions to run.

    Args:
        logs: Dict. Currently no data is passed to this argument for this method
          but that may change in the future.
    """

    @doc_controls.for_subclass_implementers
    def on_predict_end(self, logs=None):
        """Called at the end of prediction.

    Subclasses should override for any actions to run.

    Args:
        logs: Dict. Currently no data is passed to this argument for this method
          but that may change in the future.
    """

    def _implements_train_batch_hooks(self):
        """Determines if this Callback should be called for each train batch."""
        return not generic_utils.is_default(self.on_batch_begin) or not generic_utils.is_default(self.on_batch_end) or (not generic_utils.is_default(self.on_train_batch_begin)) or (not generic_utils.is_default(self.on_train_batch_end))

    def _implements_test_batch_hooks(self):
        """Determines if this Callback should be called for each test batch."""
        return not generic_utils.is_default(self.on_test_batch_begin) or not generic_utils.is_default(self.on_test_batch_end)

    def _implements_predict_batch_hooks(self):
        """Determines if this Callback should be called for each predict batch."""
        return not generic_utils.is_default(self.on_predict_batch_begin) or not generic_utils.is_default(self.on_predict_batch_end)

Abstract base class used to build new callbacks.

Callbacks can be passed to keras methods such as `fit`, `evaluate`, and
`predict` in order to hook into the various stages of the model training and
inference lifecycle.

To create a custom callback, subclass `keras.callbacks.Callback` and override
the method associated with the stage of interest. See
https://www.tensorflow.org/guide/keras/custom_callback for more information.

Example:

>>> training_finished = False
>>> class MyCallback(tf.keras.callbacks.Callback):
...   def on_train_end(self, logs=None):
...     global training_finished
...     training_finished = True
>>> model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
>>> model.compile(loss='mean_squared_error')
>>> model.fit(tf.constant([[1.0]]), tf.constant([[1.0]]),
...           callbacks=[MyCallback()])
>>> assert training_finished == True

If you want to use `Callback` objects in a custom training loop:

1. You should pack all your callbacks into a single `callbacks.CallbackList`
   so they can all be called together.
2. You will need to manually call all the `on_*` methods at the appropriate
   locations in your loop. Like this:

   ```
   callbacks =  tf.keras.callbacks.CallbackList([...])
   callbacks.append(...)

   callbacks.on_train_begin(...)
   for epoch in range(EPOCHS):
     callbacks.on_epoch_begin(epoch)
     for i, data in dataset.enumerate():
       callbacks.on_train_batch_begin(i)
       batch_logs = model.train_step(data)
       callbacks.on_train_batch_end(i, batch_logs)
     epoch_logs = ...
     callbacks.on_epoch_end(epoch, epoch_logs)
   final_logs=...
   callbacks.on_train_end(final_logs)
   ```

Attributes:
    params: Dict. Training parameters (eg. verbosity, batch size, number of
      epochs...).
    model: Instance of `keras.models.Model`. Reference of the model being
      trained.

The `logs` dictionary that callback methods
take as argument will contain keys for quantities relevant to
the current batch or epoch (see method-specific docstrings).


def start_server_on_separate_thread(dump_to_filesystem=True, server_start_delay_sec=0.0, poll_server=False, blocking=True, toggle_watch_on_core_metadata=None):
    server_port = portpicker.pick_unused_port()
    debug_server_url = 'grpc://localhost:%d' % server_port
    server_dump_dir = tempfile.mkdtemp() if dump_to_filesystem else None
    server = EventListenerTestServicer(server_port=server_port, dump_dir=server_dump_dir, toggle_watch_on_core_metadata=toggle_watch_on_core_metadata)

    def delay_then_run_server():
        time.sleep(server_start_delay_sec)
        server.run_server(blocking=blocking)
    server_thread = threading.Thread(target=delay_then_run_server)
    server_thread.start()
    if poll_server:
        if not _poll_server_till_success(50, 0.2, debug_server_url, server_dump_dir, server, gpu_memory_fraction=0.1):
            raise ValueError('Failed to start test gRPC debug server at port %d' % server_port)
        server.clear_data()
    return (server_port, debug_server_url, server_dump_dir, server_thread, server)

Create a test gRPC debug server and run on a separate thread.

Args:
  dump_to_filesystem: (bool) whether the debug server will dump debug data
    to the filesystem.
  server_start_delay_sec: (float) amount of time (in sec) to delay the server
    start up for.
  poll_server: (bool) whether the server will be polled till success on
    startup.
  blocking: (bool) whether the server should be started in a blocking mode.
  toggle_watch_on_core_metadata: A list of
      (node_name, output_slot, debug_op) tuples to toggle the
      watchpoint status during the on_core_metadata calls (optional).

Returns:
  server_port: (int) Port on which the server runs.
  debug_server_url: (str) grpc:// URL to the server.
  server_dump_dir: (str) The debug server's dump directory.
  server_thread: The server Thread object.
  server: The `EventListenerTestServicer` object.

Raises:
  ValueError: If polling the server process for ready state is not successful
    within maximum polling count.