text
stringlengths
1
1.02k
class_index
int64
0
10.8k
source
stringlengths
85
188
class Pipeline(_ScikitCompat, PushToHubMixin): """ The Pipeline class is the class from which all pipelines inherit. Refer to this class for methods shared across different pipelines. Base class implementing pipelined operations. Pipeline workflow is defined as a sequence of the following operation...
457
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
# Historically we have pipelines working with `tokenizer`, `feature_extractor`, and `image_processor` # as separate processing components. While we have `processor` class that combines them, some pipelines # might still operate with these components separately. # With the addition of `processor` to `pipelin...
457
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
# and all the rest flags to `False` to avoid unnecessary loading of the components. _load_processor = False _load_image_processor = True _load_feature_extractor = True _load_tokenizer = True
457
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
default_input_names = None def __init__( self, model: Union["PreTrainedModel", "TFPreTrainedModel"], tokenizer: Optional[PreTrainedTokenizer] = None, feature_extractor: Optional[PreTrainedFeatureExtractor] = None, image_processor: Optional[BaseImageProcessor] = None, ...
457
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
self.task = task self.model = model self.tokenizer = tokenizer self.feature_extractor = feature_extractor self.image_processor = image_processor self.processor = processor self.modelcard = modelcard self.framework = framework # `accelerate` device map ...
457
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
if is_torch_available() and self.framework == "pt": if device == -1 and self.model.device is not None: device = self.model.device if isinstance(device, torch.device): if device.type == "xpu" and not is_torch_xpu_available(check_device=True): ra...
457
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
elif is_torch_cuda_available(): self.device = torch.device(f"cuda:{device}") elif is_torch_npu_available(): self.device = torch.device(f"npu:{device}") elif is_torch_xpu_available(check_device=True): self.device = torch.device(f"xpu:{device}") ...
457
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
logger.warning(f"Device set to use {self.device}") self.binary_output = binary_output # We shouldn't call `model.to()` for models loaded with accelerate as well as the case that model is already on device if ( self.framework == "pt" and self.model.device != self.device ...
457
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
# If the model can generate: # 1 - create a local generation config. This is done to avoid side-effects on the model as we apply local # tweaks to the generation config. # 2 - load the assistant model if it is passed. self.assistant_model, self.assistant_tokenizer = load_assistant_model(...
457
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
this_task_params = task_specific_params.get(task) if "prefix" in this_task_params: self.prefix = this_task_params.pop("prefix") self.generation_config.update(**this_task_params) # If the tokenizer has a pad token but the model doesn't, set it so that `gene...
457
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
self.call_count = 0 self._batch_size = kwargs.pop("batch_size", None) self._num_workers = kwargs.pop("num_workers", None) self._preprocess_params, self._forward_params, self._postprocess_params = self._sanitize_parameters(**kwargs) # In processor only mode, we can get the modality proce...
457
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
if self.image_processor is None and self.feature_extractor is not None: if isinstance(self.feature_extractor, BaseImageProcessor): # Backward compatible change, if users called # ImageSegmentationPipeline(.., feature_extractor=MyFeatureExtractor()) # then we s...
457
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
Args: save_directory (`str` or `os.PathLike`): A path to the directory where to saved. It will be created if it doesn't exist. safe_serialization (`str`): Whether to save the model using `safetensors` or the traditional way for PyTorch or Tensorflow. k...
457
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
if use_auth_token is not None: warnings.warn( "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.", FutureWarning, ) if kwargs.get("token", None) is not None: raise ValueEr...
457
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
info = info.copy() module_name = info["impl"].__module__ last_module = module_name.split(".")[-1] # Change classes into their names/full names info["impl"] = f"{last_module}.{info['impl'].__name__}" info["pt"] = tuple(c.__name__ for c in in...
457
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
if self.image_processor is not None: self.image_processor.save_pretrained(save_directory, **kwargs) if self.modelcard is not None: self.modelcard.save_pretrained(save_directory) def transform(self, X): """ Scikit / Keras interface to transformers' pipelines. This me...
457
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
Examples: ```python # Explicitly ask for tensor allocation on CUDA device :0 pipe = pipeline(..., device=0) with pipe.device_placement(): # Every framework specific tensor allocation will be done on the request device output = pipe(...) ```""" if ...
457
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
Args: inputs (keyword arguments that should be `torch.Tensor`, the rest is ignored): The tensors to place on `self.device`. Recursive on lists **only**. Return: `Dict[str, torch.Tensor]`: The same as `inputs` but on the proper device. """ retu...
457
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
def _ensure_tensor_on_device(self, inputs, device): if isinstance(inputs, ModelOutput): return ModelOutput( {name: self._ensure_tensor_on_device(tensor, device) for name, tensor in inputs.items()} ) elif isinstance(inputs, dict): return {name: self._en...
457
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
def check_model_type(self, supported_models: Union[List[str], dict]): """ Check if the model class is in supported by the pipeline.
457
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
Args: supported_models (`List[str]` or `dict`): The list of models supported by the pipeline, or a dictionary with model class values. """ if not isinstance(supported_models, list): # Create from a model mapping supported_models_names = [] for _, mode...
457
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
supported_models_names.append(model.__name__) supported_models = supported_models_names if self.model.__class__.__name__ not in supported_models: logger.error( f"The model '{self.model.__class__.__name__}' is not supported for {self.task}. Supported models are" ...
457
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
@abstractmethod def _sanitize_parameters(self, **pipeline_parameters): """ _sanitize_parameters will be called with any excessive named arguments from either `__init__` or `__call__` methods. It should return 3 dictionaries of the resolved parameters used by the various `preprocess`, ...
457
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
@abstractmethod def preprocess(self, input_: Any, **preprocess_parameters: Dict) -> Dict[str, GenericTensor]: """ Preprocess will take the `input_` of a specific pipeline and return a dictionary of everything necessary for `_forward` to run properly. It should contain at least one tensor, bu...
457
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
It is not meant to be called directly, `forward` is preferred. It is basically the same but contains additional code surrounding `_forward` making sure tensors and models are on the same device, disabling the training part of the code (leading to faster inference). """ raise NotImplement...
457
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
def forward(self, model_inputs, **forward_params): with self.device_placement(): if self.framework == "tf": model_inputs["training"] = False model_outputs = self._forward(model_inputs, **forward_params) elif self.framework == "pt": inferenc...
457
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
def get_iterator( self, inputs, num_workers: int, batch_size: int, preprocess_params, forward_params, postprocess_params ): if isinstance(inputs, collections.abc.Sized): dataset = PipelineDataset(inputs, self.preprocess, preprocess_params) else: if num_workers > 1: ...
457
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
feature_extractor = self.feature_extractor if self.feature_extractor is not None else self.image_processor collate_fn = no_collate_fn if batch_size == 1 else pad_collate_fn(self.tokenizer, feature_extractor) dataloader = DataLoader(dataset, num_workers=num_workers, batch_size=batch_size, collate_fn=coll...
457
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
def __call__(self, inputs, *args, num_workers=None, batch_size=None, **kwargs): if args: logger.warning(f"Ignoring args : {args}") if num_workers is None: if self._num_workers is None: num_workers = 0 else: num_workers = self._num_work...
457
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
self.call_count += 1 if self.call_count > 10 and self.framework == "pt" and self.device.type == "cuda": logger.warning_once( "You seem to be using the pipelines sequentially on GPU. In order to maximize efficiency please use a" " dataset", ) is_da...
457
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
if is_list: if can_use_iterator: final_iterator = self.get_iterator( inputs, num_workers, batch_size, preprocess_params, forward_params, postprocess_params ) outputs = list(final_iterator) return outputs else: ...
457
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
) ) ) else: return self.run_single(inputs, preprocess_params, forward_params, postprocess_params)
457
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
def run_multi(self, inputs, preprocess_params, forward_params, postprocess_params): return [self.run_single(item, preprocess_params, forward_params, postprocess_params) for item in inputs] def run_single(self, inputs, preprocess_params, forward_params, postprocess_params): model_inputs = self.prepr...
457
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
class ChunkPipeline(Pipeline): def run_single(self, inputs, preprocess_params, forward_params, postprocess_params): all_outputs = [] for model_inputs in self.preprocess(inputs, **preprocess_params): model_outputs = self.forward(model_inputs, **forward_params) all_outputs.appe...
458
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
def get_iterator( self, inputs, num_workers: int, batch_size: int, preprocess_params, forward_params, postprocess_params ): if "TOKENIZERS_PARALLELISM" not in os.environ: logger.info("Disabling tokenizer parallelism, we're using DataLoader multithreading already") os.environ[...
458
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
# TODO hack by collating feature_extractor and image_processor feature_extractor = self.feature_extractor if self.feature_extractor is not None else self.image_processor collate_fn = no_collate_fn if batch_size == 1 else pad_collate_fn(self.tokenizer, feature_extractor) dataloader = DataLoader(d...
458
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
class PipelineRegistry: def __init__(self, supported_tasks: Dict[str, Any], task_aliases: Dict[str, str]) -> None: self.supported_tasks = supported_tasks self.task_aliases = task_aliases def get_supported_tasks(self) -> List[str]: supported_task = list(self.supported_tasks.keys()) + lis...
459
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
if task.startswith("translation"): tokens = task.split("_") if len(tokens) == 4 and tokens[0] == "translation" and tokens[2] == "to": targeted_task = self.supported_tasks["translation"] task = "translation" return task, targeted_task, (tokens[1], t...
459
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
def register_pipeline( self, task: str, pipeline_class: type, pt_model: Optional[Union[type, Tuple[type]]] = None, tf_model: Optional[Union[type, Tuple[type]]] = None, default: Optional[Dict] = None, type: Optional[str] = None, ) -> None: if task in se...
459
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
if type is not None: task_impl["type"] = type self.supported_tasks[task] = task_impl pipeline_class._registered_impl = {task: task_impl} def to_dict(self): return self.supported_tasks
459
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/base.py
class TokenClassificationArgumentHandler(ArgumentHandler): """ Handles arguments for token classification. """ def __call__(self, inputs: Union[str, List[str]], **kwargs): if inputs is not None and isinstance(inputs, (list, tuple)) and len(inputs) > 0: inputs = list(inputs) ...
460
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/token_classification.py
offset_mapping = kwargs.get("offset_mapping") if offset_mapping: if isinstance(offset_mapping, list) and isinstance(offset_mapping[0], tuple): offset_mapping = [offset_mapping] if len(offset_mapping) != batch_size: raise ValueError("offset_mapping should h...
460
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/token_classification.py
class AggregationStrategy(ExplicitEnum): """All the valid aggregation strategies for TokenClassificationPipeline""" NONE = "none" SIMPLE = "simple" FIRST = "first" AVERAGE = "average" MAX = "max"
461
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/token_classification.py
class TokenClassificationPipeline(ChunkPipeline): """ Named Entity Recognition pipeline using any `ModelForTokenClassification`. See the [named entity recognition examples](../task_summary#named-entity-recognition) for more information. Example: ```python >>> from transformers import pipeline ...
462
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/token_classification.py
>>> # Some models use the same idea to do part of speech. >>> syntaxer = pipeline(model="vblagoje/bert-english-uncased-finetuned-pos", aggregation_strategy="simple") >>> syntaxer("My name is Sarah and I live in London") [{'entity_group': 'PRON', 'score': 0.999, 'word': 'my', 'start': 0, 'end': 2}, {'entity_...
462
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/token_classification.py
Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial) This token recognition pipeline can currently be loaded from [`pipeline`] using the following task identifier: `"ner"` (for predicting the classes of tokens in a sequence: person, organisation, location or miscella...
462
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/token_classification.py
self._basic_tokenizer = BasicTokenizer(do_lower_case=False) self._args_parser = args_parser def _sanitize_parameters( self, ignore_labels=None, grouped_entities: Optional[bool] = None, ignore_subwords: Optional[bool] = None, aggregation_strategy: Optional[Aggregation...
462
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/token_classification.py
if grouped_entities is not None: warnings.warn( "`grouped_entities` is deprecated and will be removed in version v5.0.0, defaulted to" f' `aggregation_strategy="{aggregation_strategy}"` instead.' ) if ignore_subwords is not None: ...
462
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/token_classification.py
if aggregation_strategy is not None: if isinstance(aggregation_strategy, str): aggregation_strategy = AggregationStrategy[aggregation_strategy.upper()] if ( aggregation_strategy in {AggregationStrategy.FIRST, AggregationStrategy.MAX, AggregationStr...
462
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/token_classification.py
"`stride` must be less than `tokenizer.model_max_length` (or even lower if the tokenizer adds special tokens)" ) if aggregation_strategy == AggregationStrategy.NONE: raise ValueError( "`stride` was provided to process all the text but `aggregation_strategy...
462
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/token_classification.py
) return preprocess_params, {}, postprocess_params
462
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/token_classification.py
def __call__(self, inputs: Union[str, List[str]], **kwargs): """ Classify each token of the text(s) given as inputs. Args: inputs (`str` or `List[str]`): One or several texts (or one list of texts) for token classification. Return: A list or a li...
462
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/token_classification.py
- **word** (`str`) -- The token/word classified. This is obtained by decoding the selected tokens. If you want to have the exact string in the original sentence, use `start` and `end`. - **score** (`float`) -- The corresponding probability for `entity`. - **entity** (`str`) -- The ...
462
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/token_classification.py
_inputs, offset_mapping = self._args_parser(inputs, **kwargs) if offset_mapping: kwargs["offset_mapping"] = offset_mapping return super().__call__(inputs, **kwargs) def preprocess(self, sentence, offset_mapping=None, **preprocess_params): tokenizer_params = preprocess_params.po...
462
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/token_classification.py
for i in range(num_chunks): if self.framework == "tf": model_inputs = {k: tf.expand_dims(v[i], 0) for k, v in inputs.items()} else: model_inputs = {k: v[i].unsqueeze(0) for k, v in inputs.items()} if offset_mapping is not None: model_in...
462
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/token_classification.py
def _forward(self, model_inputs): # Forward special_tokens_mask = model_inputs.pop("special_tokens_mask") offset_mapping = model_inputs.pop("offset_mapping", None) sentence = model_inputs.pop("sentence") is_last = model_inputs.pop("is_last") if self.framework == "tf": ...
462
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/token_classification.py
def postprocess(self, all_outputs, aggregation_strategy=AggregationStrategy.NONE, ignore_labels=None): if ignore_labels is None: ignore_labels = ["O"] all_entities = [] for model_outputs in all_outputs: if self.framework == "pt" and model_outputs["logits"][0].dtype in (to...
462
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/token_classification.py
maxes = np.max(logits, axis=-1, keepdims=True) shifted_exp = np.exp(logits - maxes) scores = shifted_exp / shifted_exp.sum(axis=-1, keepdims=True) if self.framework == "tf": input_ids = input_ids.numpy() offset_mapping = offset_mapping.numpy() if offs...
462
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/token_classification.py
pre_entities = self.gather_pre_entities( sentence, input_ids, scores, offset_mapping, special_tokens_mask, aggregation_strategy ) grouped_entities = self.aggregate(pre_entities, aggregation_strategy) # Filter anything that is in self.ignore_labels entities...
462
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/token_classification.py
def aggregate_overlapping_entities(self, entities): if len(entities) == 0: return entities entities = sorted(entities, key=lambda x: x["start"]) aggregated_entities = [] previous_entity = entities[0] for entity in entities: if previous_entity["start"] <= e...
462
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/token_classification.py
def gather_pre_entities( self, sentence: str, input_ids: np.ndarray, scores: np.ndarray, offset_mapping: Optional[List[Tuple[int, int]]], special_tokens_mask: np.ndarray, aggregation_strategy: AggregationStrategy, ) -> List[dict]: """Fuse various numpy...
462
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/token_classification.py
word = self.tokenizer.convert_ids_to_tokens(int(input_ids[idx])) if offset_mapping is not None: start_ind, end_ind = offset_mapping[idx] if not isinstance(start_ind, int): if self.framework == "pt": start_ind = start_ind.item() ...
462
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/token_classification.py
# This is a fallback heuristic. This will fail most likely on any kind of text + punctuation mixtures that will be considered "words". Non word aware models cannot do better than this unfortunately. if aggregation_strategy in { AggregationStrategy.FIRST, ...
462
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/token_classification.py
if int(input_ids[idx]) == self.tokenizer.unk_token_id: word = word_ref is_subword = False else: start_ind = None end_ind = None is_subword = False pre_entity = { "word": word, ...
462
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/token_classification.py
def aggregate(self, pre_entities: List[dict], aggregation_strategy: AggregationStrategy) -> List[dict]: if aggregation_strategy in {AggregationStrategy.NONE, AggregationStrategy.SIMPLE}: entities = [] for pre_entity in pre_entities: entity_idx = pre_entity["scores"].argma...
462
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/token_classification.py
def aggregate_word(self, entities: List[dict], aggregation_strategy: AggregationStrategy) -> dict: word = self.tokenizer.convert_tokens_to_string([entity["word"] for entity in entities]) if aggregation_strategy == AggregationStrategy.FIRST: scores = entities[0]["scores"] idx = sc...
462
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/token_classification.py
entity = self.model.config.id2label[entity_idx] score = average_scores[entity_idx] else: raise ValueError("Invalid aggregation_strategy") new_entity = { "entity": entity, "score": score, "word": word, "start": entities[0]["start"], ...
462
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/token_classification.py
def aggregate_words(self, entities: List[dict], aggregation_strategy: AggregationStrategy) -> List[dict]: """ Override tokens from a given word that disagree to force agreement on word boundaries. Example: micro|soft| com|pany| B-ENT I-NAME I-ENT I-ENT will be rewritten with first strategy as m...
462
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/token_classification.py
word_entities = [] word_group = None for entity in entities: if word_group is None: word_group = [entity] elif entity["is_subword"]: word_group.append(entity) else: word_entities.append(self.aggregate_word(word_group, ag...
462
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/token_classification.py
Args: entities (`dict`): The entities predicted by the pipeline. """ # Get the first entity in the entity group entity = entities[0]["entity"].split("-", 1)[-1] scores = np.nanmean([entity["score"] for entity in entities]) tokens = [entity["word"] for entity in entiti...
462
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/token_classification.py
def get_tag(self, entity_name: str) -> Tuple[str, str]: if entity_name.startswith("B-"): bi = "B" tag = entity_name[2:] elif entity_name.startswith("I-"): bi = "I" tag = entity_name[2:] else: # It's not in B-, I- format # De...
462
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/token_classification.py
# If the current entity is similar and adjacent to the previous entity, # append it to the disaggregated entity group # The split is meant to account for the "B" and "I" prefixes # Shouldn't merge if both entities are B-type bi, tag = self.get_tag(entity["entity"]) ...
462
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/token_classification.py
return entity_groups
462
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/pipelines/token_classification.py
class TrialShortNamer: PREFIX = "hp" DEFAULTS = {} NAMING_INFO = None @classmethod def set_defaults(cls, prefix, defaults): cls.PREFIX = prefix cls.DEFAULTS = defaults cls.build_naming_info() @staticmethod def shortname_for_word(info, word): if len(word) == ...
463
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/utils/hp_naming.py
if short_word is None: # Paranoid fallback def int_to_alphabetic(integer): s = "" while integer != 0: s = chr(ord("A") + integer % 10) + s integer //= 10 return s i = 0 while True: ...
463
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/utils/hp_naming.py
# We try to create a separatorless short name, but if there is a collision we have to fallback # to a separated short name separators = ["", "_"] for separator in separators: shortname = separator.join(shortname_parts) if shortname not in info["reverse_short_param"]: ...
463
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/utils/hp_naming.py
info = { "short_word": {}, "reverse_short_word": {}, "short_param": {}, "reverse_short_param": {}, } field_keys = list(cls.DEFAULTS.keys()) for k in field_keys: cls.add_new_param_name(info, k) cls.NAMING_INFO = info @cla...
463
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/utils/hp_naming.py
sep = "" if isinstance(v, (int, float)) else "-" e = f"{key}{sep}{v}" name.append(e) return "_".join(name) @classmethod def parse_repr(cls, repr): repr = repr[len(cls.PREFIX) + 1 :] if repr == "": values = [] else: values = repr.s...
463
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/utils/hp_naming.py
class EmptyTqdm: """Dummy tqdm which doesn't do anything.""" def __init__(self, *args, **kwargs): # pylint: disable=unused-argument self._iterator = args[0] if args else None def __iter__(self): return iter(self._iterator) def __getattr__(self, _): """Return empty function.""...
464
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/utils/logging.py
class _tqdm_cls: def __call__(self, *args, **kwargs): if _tqdm_active: return tqdm_lib.tqdm(*args, **kwargs) else: return EmptyTqdm(*args, **kwargs) def set_lock(self, *args, **kwargs): self._lock = None if _tqdm_active: return tqdm_lib.tqdm.s...
465
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/utils/logging.py
class Pop2PianoFeatureExtractor(metaclass=DummyObject): _backends = ["essentia", "librosa", "pretty_midi", "scipy", "torch"] def __init__(self, *args, **kwargs): requires_backends(self, ["essentia", "librosa", "pretty_midi", "scipy", "torch"])
466
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/utils/dummy_essentia_and_librosa_and_pretty_midi_and_scipy_and_torch_objects.py
class Pop2PianoTokenizer(metaclass=DummyObject): _backends = ["essentia", "librosa", "pretty_midi", "scipy", "torch"] def __init__(self, *args, **kwargs): requires_backends(self, ["essentia", "librosa", "pretty_midi", "scipy", "torch"])
467
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/utils/dummy_essentia_and_librosa_and_pretty_midi_and_scipy_and_torch_objects.py
class Pop2PianoProcessor(metaclass=DummyObject): _backends = ["essentia", "librosa", "pretty_midi", "scipy", "torch"] def __init__(self, *args, **kwargs): requires_backends(self, ["essentia", "librosa", "pretty_midi", "scipy", "torch"])
468
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/utils/dummy_essentia_and_librosa_and_pretty_midi_and_scipy_and_torch_objects.py
class LayoutLMv2Model: def __init__(self, *args, **kwargs): requires_backends(self, ["detectron2"]) @classmethod def from_pretrained(cls, *args, **kwargs): requires_backends(cls, ["detectron2"])
469
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/utils/dummy_detectron2_objects.py
class Action(ExplicitEnum): NONE = "none" NOTIFY = "notify" NOTIFY_ALWAYS = "notify_always" RAISE = "raise"
470
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/utils/deprecation.py
class PyTorchBenchmark(metaclass=DummyObject): _backends = ["torch"] def __init__(self, *args, **kwargs): requires_backends(self, ["torch"])
471
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/utils/dummy_pt_objects.py
class PyTorchBenchmarkArguments(metaclass=DummyObject): _backends = ["torch"] def __init__(self, *args, **kwargs): requires_backends(self, ["torch"])
472
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/utils/dummy_pt_objects.py
class Cache(metaclass=DummyObject): _backends = ["torch"] def __init__(self, *args, **kwargs): requires_backends(self, ["torch"])
473
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/utils/dummy_pt_objects.py
class CacheConfig(metaclass=DummyObject): _backends = ["torch"] def __init__(self, *args, **kwargs): requires_backends(self, ["torch"])
474
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/utils/dummy_pt_objects.py
class DynamicCache(metaclass=DummyObject): _backends = ["torch"] def __init__(self, *args, **kwargs): requires_backends(self, ["torch"])
475
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/utils/dummy_pt_objects.py
class EncoderDecoderCache(metaclass=DummyObject): _backends = ["torch"] def __init__(self, *args, **kwargs): requires_backends(self, ["torch"])
476
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/utils/dummy_pt_objects.py
class HQQQuantizedCache(metaclass=DummyObject): _backends = ["torch"] def __init__(self, *args, **kwargs): requires_backends(self, ["torch"])
477
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/utils/dummy_pt_objects.py
class HybridCache(metaclass=DummyObject): _backends = ["torch"] def __init__(self, *args, **kwargs): requires_backends(self, ["torch"])
478
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/utils/dummy_pt_objects.py
class MambaCache(metaclass=DummyObject): _backends = ["torch"] def __init__(self, *args, **kwargs): requires_backends(self, ["torch"])
479
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/utils/dummy_pt_objects.py
class OffloadedCache(metaclass=DummyObject): _backends = ["torch"] def __init__(self, *args, **kwargs): requires_backends(self, ["torch"])
480
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/utils/dummy_pt_objects.py
class OffloadedStaticCache(metaclass=DummyObject): _backends = ["torch"] def __init__(self, *args, **kwargs): requires_backends(self, ["torch"])
481
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/utils/dummy_pt_objects.py
class QuantizedCache(metaclass=DummyObject): _backends = ["torch"] def __init__(self, *args, **kwargs): requires_backends(self, ["torch"])
482
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/utils/dummy_pt_objects.py
class QuantizedCacheConfig(metaclass=DummyObject): _backends = ["torch"] def __init__(self, *args, **kwargs): requires_backends(self, ["torch"])
483
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/utils/dummy_pt_objects.py
class QuantoQuantizedCache(metaclass=DummyObject): _backends = ["torch"] def __init__(self, *args, **kwargs): requires_backends(self, ["torch"])
484
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/utils/dummy_pt_objects.py
class SinkCache(metaclass=DummyObject): _backends = ["torch"] def __init__(self, *args, **kwargs): requires_backends(self, ["torch"])
485
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/utils/dummy_pt_objects.py