text stringlengths 1 1.02k | class_index int64 0 10.8k | source stringlengths 85 188 |
|---|---|---|
class DetaImageProcessor(BaseImageProcessor):
r"""
Constructs a Deformable DETR image processor. | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
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 `si... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
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 t... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
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 ... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
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 ... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
provided for preprocessing. If `pad_size` is not provided, images will be padded to the largest
height and width in the batch.
""" | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
model_input_names = ["pixel_values", "pixel_mask"]
def __init__(
self,
format: Union[str, AnnotationFormat] = AnnotationFormat.COCO_DETECTION,
do_resize: bool = True,
size: Dict[str, int] = None,
resample: PILImageResampling = PILImageResampling.BILINEAR,
do_rescale:... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
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_fa... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
def prepare_annotation(
self,
image: np.ndarray,
target: Dict,
format: Optional[AnnotationFormat] = None,
return_segmentation_masks: bool = None,
masks_path: Optional[Union[str, pathlib.Path]] = None,
input_data_format: Optional[Union[str, ChannelDimension]] = Non... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
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
... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
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:
... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
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 `(heigh... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
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 t... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
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(
"Size must contain 'height' and 'widt... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
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 nu... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
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 dime... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
- `"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) | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
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.
"""... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
for key, value in annotation.items():
if key == "masks":
masks = value
masks = pad(
masks,
padding,
mode=PaddingMode.CONSTANT,
constant_values=0,
input_data_format=ChannelDimen... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
new_annotation["size"] = output_image_size
else:
new_annotation[key] = value
return new_annotation | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
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, ChannelDi... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
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=dat... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
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_fo... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
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]`, *opt... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
- `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`, *o... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
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["widt... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
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,
... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
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 | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
def preprocess(
self,
images: ImageInput,
annotations: Optional[Union[List[Dict], List[List[Dict]]]] = None,
return_segmentation_masks: bool = None,
masks_path: Optional[Union[str, pathlib.Path]] = None,
do_resize: Optional[bool] = None,
size: Optional[Dict[str, i... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
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. | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
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[Lis... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
- "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*, def... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
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 ... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
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... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
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.
for... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
- `"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... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
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 = kwa... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
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... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
# Here, the pad() method pads to the maximum of (width, height). It does not need to be validated.
validate_preprocess_arguments(
do_rescale=do_rescale,
rescale_factor=rescale_factor,
do_normalize=do_normalize,
image_mean=image_mean,
image_std=image_s... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
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, st... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
if input_data_format is None:
# We assume that all images have the same channel dimension format.
input_data_format = infer_channel_dimension_format(images[0])
# prepare (COCO annotations as a list of Dict -> DETR target as a single Dict per image)
if annotations is not None:
... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
# transformations
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.re... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
self.resize(image, size=size, resample=resample, input_data_format=input_data_format)
for image in images
] | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
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
]
... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
if do_pad:
# Pads images and returns their mask: {'pixel_values': ..., 'pixel_mask': ...}
encoded_inputs = self.pad(
images,
annotations=annotations,
return_pixel_mask=True,
data_format=data_format,
input_data_format... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
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 b... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
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*):
... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
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... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
# and from relative [0, 1] to absolute [0, height] coordinates
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... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
# apply NMS
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],
"labe... | 10,425 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/deta/image_processing_deta.py |
class RetriBertTokenizer(PreTrainedTokenizer):
r"""
Constructs a RetriBERT tokenizer.
[`RetriBertTokenizer`] is identical to [`BertTokenizer`] and runs end-to-end tokenization: punctuation splitting
and wordpiece.
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main... | 10,426 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/tokenization_retribert.py |
Args:
vocab_file (`str`):
File containing the vocabulary.
do_lower_case (`bool`, *optional*, defaults to `True`):
Whether or not to lowercase the input when tokenizing.
do_basic_tokenize (`bool`, *optional*, defaults to `True`):
Whether or not to do basic toke... | 10,426 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/tokenization_retribert.py |
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.
pad_token (`str`, *optional*, defaults to `"[PAD]"`):
The token used for padding, for example when batching sequences of different lengt... | 10,426 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/tokenization_retribert.py |
Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see this
[issue](https://github.com/huggingface/transformers/issues/328)).
strip_accents (`bool`, *optional*):
Whether or not to strip all accents. If this option is not specified, then it will... | 10,426 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/tokenization_retribert.py |
vocab_files_names = VOCAB_FILES_NAMES
model_input_names = ["input_ids", "attention_mask"] | 10,426 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/tokenization_retribert.py |
def __init__(
self,
vocab_file,
do_lower_case=True,
do_basic_tokenize=True,
never_split=None,
unk_token="[UNK]",
sep_token="[SEP]",
pad_token="[PAD]",
cls_token="[CLS]",
mask_token="[MASK]",
tokenize_chinese_chars=True,
stri... | 10,426 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/tokenization_retribert.py |
never_split=never_split,
tokenize_chinese_chars=tokenize_chinese_chars,
strip_accents=strip_accents,
) | 10,426 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/tokenization_retribert.py |
self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=str(unk_token))
super().__init__(
do_lower_case=do_lower_case,
do_basic_tokenize=do_basic_tokenize,
never_split=never_split,
unk_token=unk_token,
sep_token=sep_token,
... | 10,426 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/tokenization_retribert.py |
def _tokenize(self, text, split_special_tokens=False):
split_tokens = []
if self.do_basic_tokenize:
for token in self.basic_tokenizer.tokenize(
text, never_split=self.all_special_tokens if not split_special_tokens else None
):
# If the token is par... | 10,426 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/tokenization_retribert.py |
def convert_tokens_to_string(self, tokens):
"""Converts a sequence of tokens (string) in a single string."""
out_string = " ".join(tokens).replace(" ##", "").strip()
return out_string
def build_inputs_with_special_tokens(
self, token_ids_0: List[int], token_ids_1: Optional[List[int]... | 10,426 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/tokenization_retribert.py |
Returns:
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
"""
if token_ids_1 is None:
return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
cls = [self.cls_token_id]
sep = [self.sep_token_id]
return cls ... | 10,426 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/tokenization_retribert.py |
Args:
token_ids_0 (`List[int]`):
List of IDs.
token_ids_1 (`List[int]`, *optional*):
Optional second list of IDs for sequence pairs.
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
Whether or not the token list is ... | 10,426 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/tokenization_retribert.py |
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. A BERT sequence
pair mask has the following format:
... | 10,426 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/tokenization_retribert.py |
Returns:
`List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
"""
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_... | 10,426 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/tokenization_retribert.py |
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
index = 0
if os.path.isdir(save_directory):
vocab_file = os.path.join(
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
... | 10,426 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/tokenization_retribert.py |
class BasicTokenizer:
"""
Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).
Args:
do_lower_case (`bool`, *optional*, defaults to `True`):
Whether or not to lowercase the input when tokenizing.
never_split (`Iterable`, *opti... | 10,427 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/tokenization_retribert.py |
This should likely be deactivated for Japanese (see this
[issue](https://github.com/huggingface/transformers/issues/328)).
strip_accents (`bool`, *optional*):
Whether or not to strip all accents. If this option is not specified, then it will be determined by the
value for `lo... | 10,427 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/tokenization_retribert.py |
def __init__(
self,
do_lower_case=True,
never_split=None,
tokenize_chinese_chars=True,
strip_accents=None,
do_split_on_punc=True,
):
if never_split is None:
never_split = []
self.do_lower_case = do_lower_case
self.never_split = set(... | 10,427 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/tokenization_retribert.py |
Args:
never_split (`List[str]`, *optional*)
Kept for backward compatibility purposes. Now implemented directly at the base class level (see
[`PreTrainedTokenizer.tokenize`]) List of token not to split.
"""
# union() returns a new set by concatenating the two s... | 10,427 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/tokenization_retribert.py |
# This was added on November 1st, 2018 for the multilingual and Chinese
# models. This is also applied to the English models now, but it doesn't
# matter since the English models were not trained on any Chinese data
# and generally don't have any Chinese data in them (there are Chinese
#... | 10,427 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/tokenization_retribert.py |
token = self._run_strip_accents(token)
elif self.strip_accents:
token = self._run_strip_accents(token)
split_tokens.extend(self._run_split_on_punc(token, never_split)) | 10,427 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/tokenization_retribert.py |
output_tokens = whitespace_tokenize(" ".join(split_tokens))
return output_tokens
def _run_strip_accents(self, text):
"""Strips accents from a piece of text."""
text = unicodedata.normalize("NFD", text)
output = []
for char in text:
cat = unicodedata.category(char... | 10,427 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/tokenization_retribert.py |
def _run_split_on_punc(self, text, never_split=None):
"""Splits punctuation on a piece of text."""
if not self.do_split_on_punc or (never_split is not None and text in never_split):
return [text]
chars = list(text)
i = 0
start_new_word = True
output = []
... | 10,427 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/tokenization_retribert.py |
def _tokenize_chinese_chars(self, text):
"""Adds whitespace around any CJK character."""
output = []
for char in text:
cp = ord(char)
if self._is_chinese_char(cp):
output.append(" ")
output.append(char)
output.append(" ")
... | 10,427 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/tokenization_retribert.py |
def _is_chinese_char(self, cp):
"""Checks whether CP is the codepoint of a CJK character."""
# This defines a "chinese character" as anything in the CJK Unicode block:
# https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
#
# Note that the CJK Unicode block is ... | 10,427 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/tokenization_retribert.py |
or (cp >= 0x2F800 and cp <= 0x2FA1F) #
): #
return True | 10,427 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/tokenization_retribert.py |
return False
def _clean_text(self, text):
"""Performs invalid character removal and whitespace cleanup on text."""
output = []
for char in text:
cp = ord(char)
if cp == 0 or cp == 0xFFFD or _is_control(char):
continue
if _is_whitespace(cha... | 10,427 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/tokenization_retribert.py |
class WordpieceTokenizer:
"""Runs WordPiece tokenization."""
def __init__(self, vocab, unk_token, max_input_chars_per_word=100):
self.vocab = vocab
self.unk_token = unk_token
self.max_input_chars_per_word = max_input_chars_per_word
def tokenize(self, text):
"""
Toke... | 10,428 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/tokenization_retribert.py |
output_tokens = []
for token in whitespace_tokenize(text):
chars = list(token)
if len(chars) > self.max_input_chars_per_word:
output_tokens.append(self.unk_token)
continue
is_bad = False
start = 0
sub_tokens = []
... | 10,428 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/tokenization_retribert.py |
if is_bad:
output_tokens.append(self.unk_token)
else:
output_tokens.extend(sub_tokens)
return output_tokens | 10,428 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/tokenization_retribert.py |
class RetriBertTokenizerFast(PreTrainedTokenizerFast):
r"""
Construct a "fast" RetriBERT tokenizer (backed by HuggingFace's *tokenizers* library).
[`RetriBertTokenizerFast`] is identical to [`BertTokenizerFast`] and runs end-to-end tokenization: punctuation
splitting and wordpiece.
This tokenizer ... | 10,429 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/tokenization_retribert_fast.py |
Args:
vocab_file (`str`):
File containing the vocabulary.
do_lower_case (`bool`, *optional*, defaults to `True`):
Whether or not to lowercase the input when tokenizing.
unk_token (`str`, *optional*, defaults to `"[UNK]"`):
The unknown token. A token that is no... | 10,429 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/tokenization_retribert_fast.py |
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.
mask_token (`str`, *optional*, defaults to `"[MASK]"`):
The token used f... | 10,429 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/tokenization_retribert_fast.py |
strip_accents (`bool`, *optional*):
Whether or not to strip all accents. If this option is not specified, then it will be determined by the
value for `lowercase` (as in the original BERT).
wordpieces_prefix (`str`, *optional*, defaults to `"##"`):
The prefix for subwords.
... | 10,429 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/tokenization_retribert_fast.py |
vocab_files_names = VOCAB_FILES_NAMES
slow_tokenizer_class = RetriBertTokenizer
model_input_names = ["input_ids", "attention_mask"]
def __init__(
self,
vocab_file=None,
tokenizer_file=None,
do_lower_case=True,
unk_token="[UNK]",
sep_token="[SEP]",
pad... | 10,429 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/tokenization_retribert_fast.py |
normalizer_state = json.loads(self.backend_tokenizer.normalizer.__getstate__())
if (
normalizer_state.get("lowercase", do_lower_case) != do_lower_case
or normalizer_state.get("strip_accents", strip_accents) != strip_accents
or normalizer_state.get("handle_chinese_chars", toke... | 10,429 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/tokenization_retribert_fast.py |
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
"""
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
adding special tokens. A BERT sequence has the following format:
- single sequence: `[CLS] X [SE... | 10,429 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/tokenization_retribert_fast.py |
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. A BERT sequence
pair mask has the following format:
... | 10,429 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/tokenization_retribert_fast.py |
Returns:
`List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
"""
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_... | 10,429 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/tokenization_retribert_fast.py |
class RetriBertConfig(PretrainedConfig):
r"""
This is the configuration class to store the configuration of a [`RetriBertModel`]. It is used to instantiate a
RetriBertModel model according to the specified arguments, defining the model architecture. Instantiating a
configuration with the defaults will y... | 10,430 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/configuration_retribert.py |
Args:
vocab_size (`int`, *optional*, defaults to 30522):
Vocabulary size of the RetriBERT model. Defines the number of different tokens that can be represented by
the `inputs_ids` passed when calling [`RetriBertModel`]
hidden_size (`int`, *optional*, defaults to 768):
... | 10,430 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/configuration_retribert.py |
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
`"relu"`, `"silu"` and `"gelu_new"` are supported.
hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
The dropout probability for all fully connected layers in the embeddings,... | 10,430 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/configuration_retribert.py |
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
The epsilon used by the layer normalization layers.
share_encoders (`bool`, *optional*, defaults to `True`):
Whether or not to... | 10,430 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/configuration_retribert.py |
model_type = "retribert"
def __init__(
self,
vocab_size=30522,
hidden_size=768,
num_hidden_layers=8,
num_attention_heads=12,
intermediate_size=3072,
hidden_act="gelu",
hidden_dropout_prob=0.1,
attention_probs_dropout_prob=0.1,
max_posi... | 10,430 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/configuration_retribert.py |
self.vocab_size = vocab_size
self.hidden_size = hidden_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.hidden_act = hidden_act
self.intermediate_size = intermediate_size
self.hidden_dropout_prob = hidden_dropout_prob
... | 10,430 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/configuration_retribert.py |
class RetriBertPreTrainedModel(PreTrainedModel):
"""
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
models.
"""
config_class = RetriBertConfig
load_tf_weights = None
base_model_prefix = "retribert"
def _init_weights(self... | 10,431 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/modeling_retribert.py |
class RetriBertModel(RetriBertPreTrainedModel):
def __init__(self, config: RetriBertConfig) -> None:
super().__init__(config)
self.projection_dim = config.projection_dim
self.bert_query = BertModel(config)
self.bert_doc = None if config.share_encoders else BertModel(config)
... | 10,432 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/modeling_retribert.py |
def embed_sentences_checkpointed(
self,
input_ids,
attention_mask,
sent_encoder,
checkpoint_batch_size=-1,
):
# reproduces BERT forward pass with checkpointing
if checkpoint_batch_size < 0 or input_ids.shape[0] < checkpoint_batch_size:
return sent_... | 10,432 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/modeling_retribert.py |
# define function for checkpointing
def partial_encode(*inputs):
encoder_outputs = sent_encoder.encoder(
inputs[0],
attention_mask=inputs[1],
head_mask=head_mask,
)
sequence_output = encoder_outputs[0... | 10,432 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/modeling_retribert.py |
# run embedding layer on everything at once
embedding_output = sent_encoder.embeddings(
input_ids=input_ids, position_ids=None, token_type_ids=token_type_ids, inputs_embeds=None
)
# run encoding and pooling on one mini-batch at a time
pooled_output_list = ... | 10,432 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/deprecated/retribert/modeling_retribert.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.