/usr/local/lib/python3.6/site-packages/transformers/pipelines/__pycache__
NameSizeModeActions
audio_classification.cpython-36.pyc55060644editdlrm
audio_utils.cpython-36.pyc60620644editdlrm
automatic_speech_recognition.cpython-36.pyc125590644editdlrm
base.cpython-36.pyc380650644editdlrm
conversational.cpython-36.pyc114930644editdlrm
feature_extraction.cpython-36.pyc38660644editdlrm
fill_mask.cpython-36.pyc78090644editdlrm
image_classification.cpython-36.pyc48610644editdlrm
image_segmentation.cpython-36.pyc69080644editdlrm
object_detection.cpython-36.pyc57610644editdlrm
pt_utils.cpython-36.pyc83440644editdlrm
question_answering.cpython-36.pyc176830644editdlrm
table_question_answering.cpython-36.pyc136530644editdlrm
text2text_generation.cpython-36.pyc142640644editdlrm
text_classification.cpython-36.pyc69220644editdlrm
text_generation.cpython-36.pyc87080644editdlrm
token_classification.cpython-36.pyc152480644editdlrm
zero_shot_classification.cpython-36.pyc99080644editdlrm
zero_shot_image_classification.cpython-36.pyc53630644editdlrm
__init__.cpython-36.pyc206210644editdlrm
Edit: /usr/local/lib/python3.6/site-packages/transformers/pipelines/__pycache__/base.cpython-36.pyc (38065B)
3 Eg@sddlZddlZddlZddlZddlZddlZddlZddlZddlZddl m Z m Z ddlm Z ddl mZddlmZmZddlmZmZmZmZmZmZmZddlmZdd lmZdd lmZdd l m!Z!dd l"m#Z#dd l$m%Z%m&Z&m'Z'm(Z(m)Z)eedddfZ*e'r*ddl+Z,ddl-m.Z.e(rdddl/Z/ddl0m1Z1m2Z2ddl3m4Z4ddl5m6Z6ndZ2dZ6erddl7m8Z8ddl9m:Z:e)j;e<Z=ddZ>ddZ?ddZ@d>e!eeeAeeBfeeAeeAddd ZCd?eeeAeeBfeeAeeAd!d"d#ZDd@eeAd$d%d&ZEeeeAeeeAd'd(d)ZFGd*d+d+eGZHGd,d-d-e ZIGd.d/d/ZJGd0d1d1eJZKGd2d3d3eJZLGd4d5d5eJZMGd6d7d7e ZNd8ZOe(rdd9lPmQZQmRZRmSZSmTZTe&eOGd:d;d;eNZUGdQsz_pad..)dimc3s|]}|jdVqdS)rN)shape)r*r+)r,r&r' Rsz_pad..r)dtyperleftcsg|] }|qSr&r&)r*r+)r,r&r'r-gs) r# isinstancetorchTensorr/catmaxr1Zzeros enumerateclone) r%r, padding_value padding_side batch_sizer/r. max_lengthr1tensorir+r&)r,r'_padHs.  ,* 22rBcsd}d}|dkr |dkr td|dk rH|jdkrrE>rFrHrG>rIrJ>rLrK)setkeysr$rB)r%rNr+Zpaddedr,Z_padding_value)f_padding_valuer=t_padding_valuer&r'inners$   zpad_collate_fn..inner)r$Z pad_token_idr=getattr) tokenizerfeature_extractorZt_padding_sideZf_padding_siderQr&)rOr=rPr'pad_collate_fnjs.   rU)config model_classestask frameworkc Kst rt rtdt|tr||d<f}to<|dk}toJ|dk}|r||rf||jdtf}|r|||jdtf}|jrg} xb|jD]X} t j d} |rt | | d} | dk r| j | |rt | d| d} | dk r| j | qW|t | }t|dkrtd |x|D]} |j}|dkrN|jd rNd |d <tjd n(|dkrv|jdrvd |d<tjdy(| j|f|}t|dr|j}PWnttfk rwYnXqWt|trtd|d|d|jjjdrdnd}||fS)a Select framework (TensorFlow or PyTorch) to use from the `model` passed. Returns a tuple (framework, model). If `model` is instantiated, this function will just infer the framework from the model class. Otherwise `model` is actually a checkpoint name and this method will try to instantiate it using `model_classes`. Since we don't want to instantiate the model twice, this model is returned for use by the pipeline. If both frameworks are installed and available for `model`, PyTorch is selected. Args: model (`str`, [`PreTrainedModel`] or [`TFPreTrainedModel`]): The model to infer the framework from. If `str`, a checkpoint name. The model to infer the framewrok from. config ([`AutoConfig`]): The config associated with the model to help using the correct class model_classes (dictionary `str` to `type`, *optional*): A mapping framework to class. task (`str`): The task defining which pipeline will be returned. model_kwargs: Additional dictionary of keyword arguments passed along to the model's `from_pretrained(..., **model_kwargs)` function. Returns: `Tuple`: A tuple framework, model. zAt least one of TensorFlow 2.0 or PyTorch should be installed. To install TensorFlow 2.0, read the instructions at https://www.tensorflow.org/install/ To install PyTorch, read the instructions at https://pytorch.org/._from_pipelineptNtfZ transformersTFrz2Pipeline cannot infer suitable model classes from z.h5TZfrom_tfz}Model might be a TensorFlow model (ending with `.h5`) but TensorFlow is not available. Trying to load the model with PyTorch.z.binZfrom_ptz{Model might be a PyTorch model (ending with `.bin`) but PyTorch is not available. Trying to load the model with Tensorflow.evalzCould not load model z$ with any of the following classes: .>r[N>r\N)rr RuntimeErrorr5strgetrrZ architectures importlib import_modulerRappendtupler#r$copyendswithloggerwarningfrom_pretrainedhasattrr^OSError __class____name__ startswith)modelrVrWrXrY model_kwargsZ class_tupleZlook_ptZlook_tfclasses architectureZtransformers_module_classZ model_classkwargsr&r&r'infer_framework_load_modelsb!         rw)rWrXrYcKsDt|tr"tj|fd|i|}n|j}t||f||||d|S)ar Select framework (TensorFlow or PyTorch) to use from the `model` passed. Returns a tuple (framework, model). If `model` is instantiated, this function will just infer the framework from the model class. Otherwise `model` is actually a checkpoint name and this method will try to instantiate it using `model_classes`. Since we don't want to instantiate the model twice, this model is returned for use by the pipeline. If both frameworks are installed and available for `model`, PyTorch is selected. Args: model (`str`, [`PreTrainedModel`] or [`TFPreTrainedModel`]): The model to infer the framework from. If `str`, a checkpoint name. The model to infer the framewrok from. model_classes (dictionary `str` to `type`, *optional*): A mapping framework to class. task (`str`): The task defining which pipeline will be returned. model_kwargs: Additional dictionary of keyword arguments passed along to the model's `from_pretrained(..., **model_kwargs)` function. Returns: `Tuple`: A tuple framework, model. rZ)rWrZrXrY)r5rarrkrVrw)rqrWrXrYrrrVr&r&r'infer_framework_from_models  rx)revisionc Cstjdtt r$t r$tdt|trtrLt rLtj ||d}nTtrjt rjt j ||d}n6ytj ||d}Wn"t k rt j ||d}YnX|j j jdrdnd}|S)a[ Select framework (TensorFlow or PyTorch) to use. Args: model (`str`, [`PreTrainedModel`] or [`TFPreTrainedModel`]): If both frameworks are installed, picks the one corresponding to the model passed (either a model class or the model name). If no specific model is provided, defaults to using PyTorch. zb`get_framework` is deprecated and will be removed in v5, use `infer_framework_from_model` instead.zAt least one of TensorFlow 2.0 or PyTorch should be installed. To install TensorFlow 2.0, read the instructions at https://www.tensorflow.org/install/ To install PyTorch, read the instructions at https://pytorch.org/.)ryr]r\r[)warningswarn FutureWarningrrr`r5rarrkrrmrnrorp)rqryrYr&r&r' get_framework,s"  r}) targeted_taskrY task_optionsreturncCstrt rd}ntr&t r&d}|d}|rV||krHtd|||d}nd|krl|dd}ntd|dkrd}||S)a Select a default model to use for a given task. Defaults to pytorch if ambiguous. Args: targeted_task (`Dict` ): Dictionary representing the given task, that should contain default models framework (`str`, None) "pt", "tf" or None, representing a specific framework if it was specified, or None if we don't know yet. task_options (`Any`, None) Any further value required by the task to get fully specified, for instance (SRC, TGT) languages for translation task. Returns `str` The model string representing the default model for this pipeline r[r\defaultz9The task does not provide any default models for options rqzXThe task defaults can't be correctly selected. You probably meant "translation_XX_to_YY"N)rrr$)r~rYrdefaultsZdefault_modelsr&r&r'get_default_modelNsrcs*eZdZdZeeedfdd ZZS)PipelineExceptionz Raised by a [`Pipeline`] when handling __call__. Args: task (`str`): The task of the pipeline. model (`str`): The model used by the pipeline. reason (`str`): The error message to display. )rXrqreasoncstj|||_||_dS)N)super__init__rXrq)selfrXrqr)rnr&r'rs zPipelineException.__init__)ro __module__ __qualname____doc__rar __classcell__r&r&)rnr'rxsrc@seZdZdZeddZdS)ArgumentHandlerzQ Base interface for handling arguments for each [`~pipelines.Pipeline`]. cOs tdS)N)NotImplementedError)rargsrvr&r&r'__call__szArgumentHandler.__call__N)rorrrrrr&r&r&r'rsrc@seZdZdZdddgZdeeeeeeedddZe d d Z e e e e e fd d d Ze e e e fedddZedeeeeeeeddddZdS)PipelineDataFormata Base class for all the pipeline supported data format both for reading and writing. Supported data formats currently includes: - JSON - CSV - stdin/stdout (pipe) `PipelineDataFormat` also includes some utilities to work with multi-columns like mapping from datasets columns to pipelines keyword arguments through the `dataset_kwarg_1=dataset_column_1` format. Args: output_path (`str`, *optional*): Where to save the outgoing data. input_path (`str`, *optional*): Where to look for the input data. column (`str`, *optional*): The column to read. overwrite (`bool`, *optional*, defaults to `False`): Whether or not to overwrite the `output_path`. jsoncsvpipeF) output_path input_pathcolumn overwritecCs||_||_|dk r|jdndg|_t|jdk|_|jrNdd|jD|_|dk rz| rztt|jrzt|jd|dk rtt|jst|jddS)N,rcSs*g|]"}d|krt|jdn||fqS)=)rfsplit)r*cr&r&r'r-sz/PipelineDataFormat.__init__..z already exists on diskz doesnt exist on disk) rrrrr#is_multi_columnsrrrm)rrrrrr&r&r'rszPipelineDataFormat.__init__cCs tdS)N)r)rr&r&r'__iter__szPipelineDataFormat.__iter__)datacCs tdS)z Save the provided data object with the representation for the current [`~pipelines.PipelineDataFormat`]. Args: data (`dict` or list of `dict`): The data to store. N)r)rrr&r&r'saveszPipelineDataFormat.save)rrc CsJtjj|j\}}tjjj|df}t|d}tj||WdQRX|S)z Save the provided data object as a pickle-formatted binary data on the disk. Args: data (`dict` or list of `dict`): The data to store. Returns: `str`: Path where the data has been saved. picklezwb+N) ospathsplitextrextsepjoinopenrdump)rrr_Z binary_pathZf_outputr&r&r' save_binarys  zPipelineDataFormat.save_binary)formatrrrrcCs\|dkrt||||dS|dkr0t||||dS|dkrHt||||dStd|ddS)a Creates an instance of the right subclass of [`~pipelines.PipelineDataFormat`] depending on `format`. Args: format: (`str`): The format of the desired pipeline. Acceptable values are `"json"`, `"csv"` or `"pipe"`. output_path (`str`, *optional*): Where to save the outgoing data. input_path (`str`, *optional*): Where to look for the input data. column (`str`, *optional*): The column to read. overwrite (`bool`, *optional*, defaults to `False`): Whether or not to overwrite the `output_path`. Returns: [`~pipelines.PipelineDataFormat`]: The proper data format. r)rrrzUnknown reader z% (Available reader are json/csv/pipe)N)JsonPipelineDataFormatCsvPipelineDataFormatPipedPipelineDataFormatKeyError)rrrrrr&r&r'from_strszPipelineDataFormat.from_strN)F)F)rorrrZSUPPORTED_FORMATSr raboolrrrrdictr rr staticmethodrr&r&r&r'rs "  rcsReZdZdZd eeeeeedfdd ZddZee dd d Z Z S) ra Support for pipelines using CSV data format. Args: output_path (`str`, *optional*): Where to save the outgoing data. input_path (`str`, *optional*): Where to look for the input data. column (`str`, *optional*): The column to read. overwrite (`bool`, *optional*, defaults to `False`): Whether or not to overwrite the `output_path`. F)rrrcstj||||ddS)N)r)rr)rrrrr)rnr&r'rszCsvPipelineDataFormat.__init__c #sbt|jdL}tj|}x:|D]2|jr@fdd|jDVq|jdVqWWdQRXdS)Nrcsi|]\}}||qSr&r&)r*kr)rowr&r' sz2CsvPipelineDataFormat.__iter__..r)rrr DictReaderrr)rfreaderr&)rr'rs   zCsvPipelineDataFormat.__iter__)rc CsRt|jd<}t|dkrDtj|t|dj}|j|j|WdQRXdS)z Save the provided data object with the representation for the current [`~pipelines.PipelineDataFormat`]. Args: data (`List[dict]`): The data to store. wrN) rrr#r DictWriterlistrN writeheader writerows)rrrwriterr&r&r'r"s  zCsvPipelineDataFormat.save)F) rorrrr rarrr rrrr&r&)rnr'rs $ rcsNeZdZdZd eeeeeedfdd ZddZedd d Z Z S) ra Support for pipelines using JSON file format. Args: output_path (`str`, *optional*): Where to save the outgoing data. input_path (`str`, *optional*): Where to look for the input data. column (`str`, *optional*): The column to read. overwrite (`bool`, *optional*, defaults to `False`): Whether or not to overwrite the `output_path`. F)rrrc s:tj||||dt|d}tj||_WdQRXdS)N)rr)rrrrload_entries)rrrrrr)rnr&r'r<s zJsonPipelineDataFormat.__init__c#sBx<|jD]2|jr*fdd|jDVq|jdVqWdS)Ncsi|]\}}||qSr&r&)r*rr)entryr&r'rKsz3JsonPipelineDataFormat.__iter__..r)rrr)rr&)rr'rHs zJsonPipelineDataFormat.__iter__)rc Cs(t|jd}tj||WdQRXdS)z| Save the provided data object in a json file. Args: data (`dict`): The data to store. rN)rrrr)rrrr&r&r'rOszJsonPipelineDataFormat.save)F) rorrrr rarrrrrr&r&)rnr'r0s $rcsJeZdZdZddZedddZeeeefe dfdd Z Z S) ra Read data from piped input to the python process. For multi columns data, columns should separated by If columns are provided, then the output will be a dictionary with {column_x: value_x} Args: output_path (`str`, *optional*): Where to save the outgoing data. input_path (`str`, *optional*): Where to look for the input data. column (`str`, *optional*): The column to read. overwrite (`bool`, *optional*, defaults to `False`): Whether or not to overwrite the `output_path`. ccsXxRtjD]H}d|krJ|jd}|jr>ddt|j|DVqPt|Vq|VqWdS)N cSsi|]\\}}}||qSr&r&)r*rvrlr&r&r'rpsz4PipedPipelineDataFormat.__iter__..)sysstdinrrziprf)rliner&r&r'rhs   z PipedPipelineDataFormat.__iter__)rcCs t|dS)z^ Print the data. Args: data (`dict`): The data to store. N)print)rrr&r&r'rxszPipedPipelineDataFormat.save)rrcs|jdkrtdtj|S)NzWhen using piped input on pipeline outputting large object requires an output file path. Please provide such output path through --output argument.)rrrr)rr)rnr&r'rs z#PipedPipelineDataFormat.save_binary) rorrrrrrrr rarrr&r&)rnr'rZs  rc@s(eZdZdZeddZeddZdS) _ScikitCompatzA Interface layer for the Scikit and Keras compatibility. cCs tdS)N)r)rXr&r&r' transformsz_ScikitCompat.transformcCs tdS)N)r)rrr&r&r'predictsz_ScikitCompat.predictN)rorrrrrrr&r&r&r'rs ra Arguments: model ([`PreTrainedModel`] or [`TFPreTrainedModel`]): The model that will be used by the pipeline to make predictions. This needs to be a model inheriting from [`PreTrainedModel`] for PyTorch and [`TFPreTrainedModel`] for TensorFlow. tokenizer ([`PreTrainedTokenizer`]): The tokenizer that will be used by the pipeline to encode data for the model. This object inherits from [`PreTrainedTokenizer`]. modelcard (`str` or [`ModelCard`], *optional*): Model card attributed to the model for this pipeline. framework (`str`, *optional*): The framework to use, either `"pt"` for PyTorch or `"tf"` for TensorFlow. The specified framework must be installed. If no framework is specified, will default to the one currently installed. If no framework is specified and both frameworks are installed, will default to the framework of the `model`, or to PyTorch if no model is provided. task (`str`, defaults to `""`): A task-identifier for the pipeline. num_workers (`int`, *optional*, defaults to 8): When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used. batch_size (`int`, *optional*, defaults to 1): When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read [Batching with pipelines](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching) . args_parser ([`~pipelines.ArgumentHandler`], *optional*): Reference to the object in charge of parsing supplied pipeline parameters. device (`int`, *optional*, defaults to -1): Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. binary_output (`bool`, *optional*, defaults to `False`): Flag indicating if the output the pipeline should happen in a binary format (i.e., pickle) or as raw text. )PipelineChunkIteratorPipelineDatasetPipelineIteratorPipelinePackIteratorc @sBeZdZdZdZd6ed7eeeeee ee e e e e d d d Ze d d d ZddZddZeddZddZddZeee efdddZeddZeeeee efdddZeee efeed d!d"Z eeeed#d$d%Z!d&d'Z"d(d)Z#e e d*d+d,Z$ddd*d-d.Z%d/d0Z&d1d2Z'd3d4Z(dS)8Pipelinea 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 operations: Input -> Tokenization -> Model Inference -> Post-Processing (task dependent) -> Output Pipeline supports running on CPU or GPU through the device argument (see below). Some pipeline, like for instance [`FeatureExtractionPipeline`] (`'feature-extraction'`) output large tensor object as nested-lists. In order to avoid dumping such large structure as textual data we provide the `binary_output` constructor argument. If set to `True`, the output will be stored in the pickle format. NrrFr"r!) rqrSrT modelcardrYrX args_parserdevice binary_outputc Ks|dkrt||jd\}}||_||_||_||_||_||_|dkrJ|ntj |dkrZdnd||_ | |_ |jdkr|j j dkr|jj |j |_|jjj } | dk r|| kr|jjj| j|d|_| jdd|_| jd d|_|jf| \|_|_|_dS) N)rVr\rcpuzcuda:r[cudar> num_workers)rwrVrXrqrSrTrrYr6rrtypetotask_specific_paramsupdaterb call_countpop _batch_size _num_workers_sanitize_parameters_preprocess_params_forward_params_postprocess_params) rrqrSrTrrYrXrrrrvrr&r&r'rs&* zPipeline.__init__)save_directorycCstjj|r"tjd|ddStj|dd|jj||jdk rR|jj||j dk rh|j j||j dk r~|j j|dS)z Save the pipeline's model and tokenizer. Args: save_directory (`str`): A path to the directory where to saved. It will be created if it doesn't exist. zProvided path (z#) should be a directory, not a fileNT)exist_ok) rrisfilerierrormakedirsrqsave_pretrainedrSrTr)rrr&r&r'rs       zPipeline.save_pretrainedcCs ||dS)zn Scikit / Keras interface to transformers' pipelines. This method will forward to __call__(). )rr&)rrr&r&r'rszPipeline.transformcCs ||dS)zn Scikit / Keras interface to transformers' pipelines. This method will forward to __call__(). )rr&)rrr&r&r'rszPipeline.predictc csb|jdkr>tj|jdkrdn d|j dVWdQRXn |jjdkrXtjj|jdVdS)a Context Manager allowing tensor allocation on the user-specified device in framework agnostic way. Returns: Context manager Examples: ```python # Explicitly ask for tensor allocation on CUDA device :0 pipe = pipeline(..., device=0) with pipe.device_placement(): # Every framework specific tensor allocation will be done on the request device output = pipe(...) ```r\rz/CPU:0z /device:GPU:Nrr4)rYr\rrr6rZ set_device)rr&r&r'device_placement%s  " zPipeline.device_placementcKs|j||jS)av Ensure PyTorch tensors are on the specified device. 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. )_ensure_tensor_on_devicer)rinputsr&r&r'ensure_tensor_on_device?s z Pipeline.ensure_tensor_on_devicecst|tr&tfdd|jDSt|trHfdd|jDSt|trntfdd|jDSt|trfdd|DSt|trtfdd|DSt|tjr|j S|SdS)Ncsi|]\}}j||qSr&)r)r*namer@)rrr&r'rPsz5Pipeline._ensure_tensor_on_device..csi|]\}}j||qSr&)r)r*rr@)rrr&r'rSscsi|]\}}j||qSr&)r)r*rr@)rrr&r'rUscsg|]}j|qSr&)r)r*r+)rrr&r'r-Wsz5Pipeline._ensure_tensor_on_device..csg|]}j|qSr&)r)r*r+)rrr&r'r-Ys) r5rr%rrrrfr6r7r)rrrr&)rrr'rMs       z!Pipeline._ensure_tensor_on_device)supported_modelscCst|tsTg}x@|jD]4\}}t|tr@|jdd|Dq|j|jqW|}|jjj|krt j d|jjjd|j d|ddS)z Check if the model class is in supported by the pipeline. Args: supported_models (`List[str]` or `dict`): The list of models supported by the pipeline, or a dictionary with model class values. cSsg|] }|jqSr&)ro)r*_modelr&r&r'r-lsz-Pipeline.check_model_type..z The model 'z' is not supported for z. Supported models are r_N) r5rr%rfextendrerorqrnrirrX)rrZsupported_models_namesrVrqr&r&r'check_model_type_s  zPipeline.check_model_typecKs tddS)aG _sanitize_parameters will be called with any excessive named arguments from either `__init__` or `__call__` methods. It should return 3 dictionnaries of the resolved parameters used by the various `preprocess`, `forward` and `postprocess` methods. Do not fill dictionnaries if the caller didn't specify a kwargs. This let's you keep defaults in function signatures, which is more "natural". It is not meant to be called directly, it will be automatically called and the final parameters resolved by `__init__` and `__call__` z$_sanitize_parameters not implementedN)r)rZpipeline_parametersr&r&r'rus zPipeline._sanitize_parameters)input_preprocess_parametersrcKs tddS)z Preprocess will take the `input_` of a specific pipeline and return a dictionnary of everything necessary for `_forward` to run properly. It should contain at least one tensor, but might have arbitrary other items. zpreprocess not implementedN)r)rrrr&r&r' preprocessszPipeline.preprocess) input_tensorsforward_parametersrcKs tddS)a _forward will receive the prepared dictionnary from `preprocess` and run it on the model. This method might involve the GPU or the CPU and should be agnostic to it. Isolating this function is the reason for `preprocess` and `postprocess` to exist, so that the hot path, this method generally can run as fast as possible. 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). z_forward not implementedN)r)rrrr&r&r'_forwards zPipeline._forward) model_outputspostprocess_parametersrcKs tddS)a Postprocess will receive the raw outputs of the `_forward` method, generally tensors, and reformat them into something more friendly. Generally it will output a list or a dict or results (containing just strings and numbers). zpostprocess not implementedN)r)rrrr&r&r' postprocessszPipeline.postprocesscCs&tjtjtjdkrtjntj}|S)Nz1.9.0)rparser6 __version__Zinference_modeZno_grad)rinference_contextr&r&r'get_inference_contexts"zPipeline.get_inference_contextcKs|j|jdkr,d|d<|j|f|}nj|jdkr|j}|8|j||jd}|j|f|}|j|tjdd}WdQRXntd|jdWdQRX|S) Nr\FZtrainingr[)rrz Framework z is not supported)rrYrrrrr6r$)r model_inputsforward_paramsrrr&r&r'forwards    zPipeline.forward)rr>c Cst|tjjrt||j|}n$|dkr4tjdd}t||j|}dt j kr`tj ddt j d<|dkrlt n t |j|j}t||||d} t| |j||d} t| |j|} | S)NrzFor iterable dataset using num_workers>1 is likely to result in errors since everything is iterable, setting `num_workers=1` to guarantee correctness.TOKENIZERS_PARALLELISMzNDisabling tokenizer parallelism, we're using DataLoader multithreading alreadyfalse)rr> collate_fn)loader_batch_size)r5 collectionsabcSizedrrrirjrrenvironinfor(rUrSrTrrr) rrrr>preprocess_paramsrpostprocess_paramsdatasetr  dataloadermodel_iteratorfinal_iteratorr&r&r' get_iterators   zPipeline.get_iteratorcOs|rtjd||dkr2|jdkr,d}n|j}|dkrP|jdkrJd}n|j}|jf|\}}}|j|}|j|}|j|}|jd7_|jdkr|j dkr|j j dkrt j dttdk ot|t} t|tj} t|t} | p| p| } |j dko| p| p| } | rN| r<|j||||||}dd |D}|S|j||||Sn@| rh|j||||||S| r~|j||||S|j||||SdS) NzIgnoring args : rr r[rzlYou seem to be using the pipelines sequentially on GPU. In order to maximize efficiency please use a datasetcSsg|]}|qSr&r&)r*outputr&r&r'r-sz%Pipeline.__call__..)rirjrrrrrrrrYrrrzr{ UserWarningrr5types GeneratorTyperr run_multiiterate run_single)rrrr>rrvrrrZ is_datasetZ is_generatorZis_list is_iterableZcan_use_iteratorroutputsr&r&r'rsJ         zPipeline.__call__csfdd|DS)Ncsg|]}j|qSr&)r)r*r+)rrrrr&r'r-sz&Pipeline.run_multi..r&)rrrrrr&)rrrrr'rszPipeline.run_multicCs.|j|f|}|j|f|}|j|f|}|S)N)rrr)rrrrrrrr r&r&r'rszPipeline.run_singleccs$x|D]}|j||||VqWdS)N)r)rrrrrrr&r&r'r s zPipeline.iterater4)NNNNrNr4F)r"r!))rorrrZdefault_input_namesrr rrrrarintrrrrrrrrrr rrrrr r rrrrrrrrrrrrr&r&r&r'rs>4   8rc@s$eZdZddZeedddZdS) ChunkPipelinec CsFg}x.|j|f|D]}|j|f|}|j|qW|j|f|}|S)N)rrrer) rrrrrZ all_outputsrrr r&r&r'rs zChunkPipeline.run_single)rr>c Csdtjkrtjddtjd<|dkr4tjdd}t||j|}|dkrNtn t|j |j }t ||||d} t | |j ||d} t| |j|} | S)NrzNDisabling tokenizer parallelism, we're using DataLoader multithreading alreadyrrzFor ChunkPipeline using num_workers>0 is likely to result in errors since everything is iterable, setting `num_workers=1` to guarantee correctness.)rr>r )r )rrrirrjrrr(rUrSrTrrrrr) rrrr>rrrrr rrrr&r&r'rs   zChunkPipeline.get_iteratorN)rorrrr!rr&r&r&r'r"s r")NNN)NNN)N)Wr rrcrrrrrrzr rrr contextlibros.pathrrtypingrr r r r r r packagingrZfeature_extraction_utilsrrrZmodels.auto.configuration_autorZtokenization_utilsrutilsrrrrrrZ tensorflowr\Zmodels.auto.modeling_tf_autorr6Ztorch.utils.datarrZmodels.auto.modeling_autorZpt_utilsr Zmodeling_tf_utilsr!Zmodeling_utilsr" get_loggerrorir(rBrUrarrwrxr}r ExceptionrrrrrrrZPIPELINE_INIT_ARGSZtransformers.pipelines.pt_utilsrrrrrr"r&r&r&r'sx  $          "=.^,#"* q,*1/P