Upload folder using huggingface_hub
Browse filesFiles changed (12)
- augmentors.py+3-6
- image_operators.py+12
- inference.py+1381-426
- llm_as_judge.py+14-2
- loaders.py+9-9
- metrics.py+7
- operators.py+15-8
- settings_utils.py+1-1
- standard.py+6-9
- task.py+23-19
- text_utils.py+2-1
- version.py+1-1
48 unmodified lines4950515253545527 unmodified lines83848586878889909192939448 unmodified linesaugmented_type = Textclass NullAugmentor(Augmentor):"""Does not change the input string."""def process_value(self, value: Any) -> Any:27 unmodified linesr"""Augments the input by prepending and appending randomly selected (typically, whitespace) patterns.Args:prefixes, suffixes (list or dict) : the potential (typically, whitespace) patterns to select from.The dictionary version allows the specification relative weights for the different patterns.prefix_len, suffix_len (positive int) : The added prefix or suffix will be of a certain length.remove_existing_whitespaces : Clean any existing leading and trailing whitespaces.The strings made of repetitions of the selected pattern(s) are then prepended and/or appended to the potentiallytrimmed input.If only either just prefixes or just suffixes are needed, set the other to None.Examples:48 unmodified lines4950515253545527 unmodified lines83848586878889909148 unmodified linesaugmented_type = Textclass NullAugmentor(TaskInputsAugmentor):"""Does not change the input string."""def process_value(self, value: Any) -> Any:27 unmodified linesr"""Augments the input by prepending and appending randomly selected (typically, whitespace) patterns.Args:prefixes, suffixes (list or dict) : the potential patterns (typically, whitespace) to select from. The dictionary version allows the specification relative weights for the different patterns.prefix_len, suffix_len (positive int) : The added prefix or suffix will be of a certain length.remove_existing_whitespaces : Clean any existing leading and trailing whitespaces. The strings made of repetitions of the selected pattern(s) are then prepended and/or appended to the potentially trimmed input.If only either just prefixes or just suffixes are needed, set the other to None.Examples:
92 unmodified lines93949596979892 unmodified linesreturn imagesclass DecodeImage(FieldOperator, PillowMixin):def process_value(self, value: str) -> Any:image_data = base64.b64decode(value)92 unmodified lines9394959697989910010110210310410510610710810911092 unmodified linesreturn imagesclass EncodeImageToString(FieldOperator):image_format: str = "JPEG"def encode_image_to_base64(self, image):buffer = io.BytesIO()image.save(buffer, format=self.image_format)return base64.b64encode(buffer.getvalue()).decode("utf-8")def process_value(self, value: Any) -> Any:return {"image": self.encode_image_to_base64(value)}class DecodeImage(FieldOperator, PillowMixin):def process_value(self, value: str) -> Any:image_data = base64.b64decode(value)
8 unmodified lines91011121314153 unmodified lines192021222324252627282937 unmodified lines6768697071721 unmodified line74757677787972 unmodified lines15215315415515615758 unmodified lines21621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347477 unmodified lines5525535545555565575585595605615625632 unmodified lines5665675685695705715725735741 unmodified line5765775785795805815825835845855865875885895905915925935945955965973 unmodified lines60160260360460560660712 unmodified lines62062162262362462562662762862963020 unmodified lines651652653654655656657658659313 unmodified lines97397497597697797829 unmodified lines1008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410859 unmodified lines109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126025 unmodified lines128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413954 unmodified lines140014011402140314041405140640 unmodified lines14471448144914501451145214538 unmodified linesimport timeimport uuidfrom collections import Counterfrom typing import Any, Dict, List, Literal, Optional, Unionfrom datasets import DatasetDictfrom tqdm import tqdm, trange3 unmodified linesfrom .dataclass import InternalField, NonPositionalFieldfrom .deprecation_utils import deprecationfrom .error_utils import UnitxtErrorfrom .image_operators import data_url_to_image, extract_imagesfrom .logging_utils import get_loggerfrom .operator import PackageRequirementsMixinfrom .operators import ArtifactFetcherMixinfrom .settings_utils import get_constants, get_settingsconstants = get_constants()settings = get_settings()37 unmodified linesinput_tokens (int) : number of input tokens to the model.output_tokens (int) : number of output tokens to the model.model_name (str): the model_name as kept in the InferenceEngine.inference_type (str): The label stating the type of the InferenceEngine."""1 unmodified lineprediction: Union[str, List[Dict[str, Any]]]input_tokens: Optional[int] = Noneoutput_tokens: Optional[int] = Nonemodel_name: Optional[str] = Noneinference_type: Optional[str] = None72 unmodified linesif param_inst_val is None:setattr(self, param, param_dict_val)def verify_not_chat_api(self, dataset):if isinstance(dataset[0]["source"], list):raise NotImplementedError(58 unmodified linespassclass HFPipelineBasedInferenceEngine(InferenceEngine, PackageRequirementsMixin, LazyLoadMixin):model_name: strmax_new_tokens: intuse_fp16: bool = Truebatch_size: int = 1top_k: Optional[int] = None_requirements_list = {"transformers": "Install huggingface package using 'pip install --upgrade transformers"}def get_engine_id(self):return get_model_and_label_id(self.model_name, "hf_pipeline")def _get_task(self):from transformers import AutoConfigreturn ("text2text-generation"if AutoConfig.from_pretrained(self.model_name, trust_remote_code=True).is_encoder_decoderelse "text-generation")def _prepare_pipeline(self):import torchfrom transformers import pipelinemodel_args: Dict[str, Any] = ({"torch_dtype": torch.float16} if self.use_fp16 else {})model_args.update({"max_new_tokens": self.max_new_tokens})device = torch.device("mps"if torch.backends.mps.is_available()else 0if torch.cuda.is_available()else "cpu")# We do this, because in some cases, using device:auto will offload some weights to the cpu# (even though the model might *just* fit to a single gpu), even if there is a gpu available, and this will# cause an error because the data is always on the gpuif torch.cuda.device_count() > 1:assert device == torch.device(0)model_args.update({"device_map": "auto"})else:model_args.update({"device": device})task = self._get_task()if task == "text-generation":model_args.update({"return_full_text": False})self.model = pipeline(model=self.model_name, trust_remote_code=True, **model_args)def prepare_engine(self):if not self.lazy_load:self._prepare_pipeline()def _is_loaded(self):return hasattr(self, "model") and self.model is not Nonedef _infer(self,dataset: Union[List[Dict[str, Any]], DatasetDict],return_meta_data: bool = False,) -> Union[List[str], List[TextGenerationInferenceOutput]]:if self._get_task() == "text2text-generation":self.verify_not_chat_api(dataset)if not self._is_loaded():self._prepare_pipeline()outputs = []for output in self.model([instance["source"] for instance in dataset],batch_size=self.batch_size,top_k=self.top_k,):if isinstance(output, list):output = output[0]outputs.append(output["generated_text"])return outputsclass MockInferenceEngine(InferenceEngine):model_name: strdefault_inference_value: str = "[[10]]"def get_engine_id(self):return get_model_and_label_id(self.model_name, "mock")def prepare_engine(self):returndef _mock_infer(self,dataset: Union[List[Dict[str, Any]], DatasetDict],) -> Union[List[str], List[TextGenerationInferenceOutput]]:return [self.default_inference_value for _ in dataset]def _infer(self,dataset: Union[List[Dict[str, Any]], DatasetDict],return_meta_data: bool = False,) -> Union[List[str], List[TextGenerationInferenceOutput]]:return self._mock_infer(dataset)class MockModeMixin(Artifact):mock_mode: bool = Falseclass IbmGenAiInferenceEngineParamsMixin(Artifact):beam_width: Optional[int] = Nonedecoding_method: Optional[Literal["greedy", "sample"]] = Noneinclude_stop_sequence: Optional[bool] = Nonelength_penalty: Any = Nonemax_new_tokens: Optional[int] = Nonemin_new_tokens: Optional[int] = Nonerandom_seed: Optional[int] = Nonerepetition_penalty: Optional[float] = Nonereturn_options: Any = Nonestop_sequences: Optional[List[str]] = Nonetemperature: Optional[float] = Nonetime_limit: Optional[int] = Nonetop_k: Optional[int] = Nonetop_p: Optional[float] = Nonetruncate_input_tokens: Optional[int] = Nonetypical_p: Optional[float] = None@deprecation(version="2.0.0", alternative=IbmGenAiInferenceEngineParamsMixin)class IbmGenAiInferenceEngineParams(Artifact):beam_width: Optional[int] = Nonedecoding_method: Optional[Literal["greedy", "sample"]] = Noneinclude_stop_sequence: Optional[bool] = Nonelength_penalty: Any = Nonemax_new_tokens: Optional[int] = Nonemin_new_tokens: Optional[int] = Nonerandom_seed: Optional[int] = Nonerepetition_penalty: Optional[float] = Nonereturn_options: Any = Nonestop_sequences: Optional[List[str]] = Nonetemperature: Optional[float] = Nonetime_limit: Optional[int] = Nonetop_k: Optional[int] = Nonetop_p: Optional[float] = Nonetruncate_input_tokens: Optional[int] = Nonetypical_p: Optional[float] = Noneclass GenericInferenceEngine(InferenceEngine, ArtifactFetcherMixin):default: Optional[str] = Nonedef prepare_engine(self):if "UNITXT_INFERENCE_ENGINE" in os.environ:engine_reference = os.environ["UNITXT_INFERENCE_ENGINE"]else:assert self.default is not None, ("GenericInferenceEngine could not be initialized"'\nThis is since both the "UNITXT_INFERENCE_ENGINE" environmental variable is not set and no default engine was not inputted.'"\nFor example, you can fix it by setting""\nexport UNITXT_INFERENCE_ENGINE=engines.ibm_gen_ai.llama_3_70b_instruct""\nto your ~/.bashrc""\nor passing a similar required engine in the default argument")engine_reference = self.defaultself.engine = self.get_artifact(engine_reference)def get_engine_id(self):return "generic_inference_engine"def _infer(self,dataset: Union[List[Dict[str, Any]], DatasetDict],return_meta_data: bool = False,) -> Union[List[str], List[TextGenerationInferenceOutput]]:return self.engine._infer(dataset)class OllamaInferenceEngine(InferenceEngine, StandardAPIParamsMixin, PackageRequirementsMixin):label: str = "ollama"_requirements_list = {"ollama": "Install ollama package using 'pip install --upgrade ollama"}data_classification_policy = ["public", "proprietary"]def get_engine_id(self):return get_model_and_label_id(self.model, self.label)def prepare_engine(self):passdef _infer(self,dataset: Union[List[Dict[str, Any]], DatasetDict],return_meta_data: bool = False,) -> Union[List[str], List[TextGenerationInferenceOutput]]:import ollamaargs = self.to_dict([StandardAPIParamsMixin])results = []for instance in dataset:messages = self.to_messages(instance)response = ollama.chat(model=self.model,messages=messages,**args,)results.append(response)return [element["message"]["content"] for element in results]class OptionSelectingByLogProbsInferenceEngine:"""OptionSelectingByLogProbsInferenceEngine inference engine is used to select an option based on the logprobs of an options list conditioned by a prompt.The inference engines that inherit from this class must implement `get_token_count` and `get_options_log_probs`."""@abc.abstractmethoddef get_token_count(self, dataset):"""Get the token count of the source key of each dict of the dataset. Add to each instance in the data a "token_count" field.Args:dataset (List[Dict[str, Any]]): A list of dictionaries, each representing a data instance.Returns:List[int]: The token count of the texts"""@abc.abstractmethoddef get_options_log_probs(self, dataset):"""Get the token logprobs of the options of the key task_data.options of each dict of the dataset.Add to each instance in the data a "options_log_prob" field, which is a dict with str as key and a list of {text: str, logprob:float}.Args:dataset (List[Dict[str, Any]]): A list of dictionaries, each representing a data instance.Returns:List[int]: The token count of the texts"""def select(self, dataset: List[Dict[str, Any]]) -> List[Dict[str, Any]]:77 unmodified lines}data_classification_policy = ["public", "proprietary"]parameters: Optional[IbmGenAiInferenceEngineParams] = Nonedef get_engine_id(self):return get_model_and_label_id(self.model_name, self.label)def prepare_engine(self):from genai import Client, Credentialsapi_key_env_var_name = "GENAI_KEY"api_key = os.environ.get(api_key_env_var_name)2 unmodified linesf"Error while trying to run IbmGenAiInferenceEngine."f" Please set the environment param '{api_key_env_var_name}'.")credentials = Credentials(api_key=api_key)self.client = Client(credentials=credentials)self._set_inference_parameters()def _infer(1 unmodified linedataset: Union[List[Dict[str, Any]], DatasetDict],return_meta_data: bool = False,) -> Union[List[str], List[TextGenerationInferenceOutput]]:from genai.schema import TextGenerationParametersgenai_params = TextGenerationParameters(**self.to_dict([IbmGenAiInferenceEngineParamsMixin]))results = []responses = self.client.text.generation.create(model_id=self.model_name,inputs=[instance["source"] for instance in dataset],parameters=genai_params,)for response in responses:generated_text = response.results[0].generated_textresult = self.get_return_object(generated_text, response.results[0], return_meta_data)results.append(result)return results3 unmodified linesdataset: Union[List[Dict[str, Any]], DatasetDict],return_meta_data: bool = False,) -> Union[List[Dict], List[TextGenerationInferenceOutput]]:from genai.schema import TextGenerationParameterslogprobs_return_options = {"generated_tokens": True,12 unmodified linesmodel_id=self.model_name,inputs=[instance["source"] for instance in dataset],parameters=genai_params,)predict_results = []for prediction in predictions:result = prediction.results[0]assert isinstance(result.generated_tokens, list), "result.generated_tokens should be a list"20 unmodified linesoutput_tokens=result.generated_token_count,model_name=self.model_name,inference_type=self.label,)return predict_resultdef get_token_count(self, dataset):texts = [instance["source"] for instance in dataset]token_counts = list(313 unmodified linesreturn OpenAI(api_key=api_key, base_url=api_url)class WMLInferenceEngineParamsMixin(Artifact):decoding_method: Optional[Literal["greedy", "sample"]] = Nonelength_penalty: Optional[Dict[str, Union[int, float]]] = None29 unmodified linesreturn_options: Optional[Dict[str, bool]] = Noneclass WMLInferenceEngine(InferenceEngine,WMLInferenceEngineParamsMixin,PackageRequirementsMixin,LogProbInferenceEngine,OptionSelectingByLogProbsInferenceEngine,):"""Runs inference using ibm-watsonx-ai.Attributes:credentials (Dict[str, str], optional): By default, it is created by a classinstance which tries to retrieve proper environment variables("WML_URL", "WML_PROJECT_ID", "WML_APIKEY"). However, a dictionary withthe following keys: "url", "apikey", "project_id" can be directly providedinstead.model_name (str, optional): ID of a model to be used for inference. Mutuallyexclusive with 'deployment_id'.deployment_id (str, optional): Deployment ID of a tuned model to be used forinference. Mutually exclusive with 'model_name'.parameters (WMLInferenceEngineParams, optional): Instance of WMLInferenceEngineParamswhich defines inference parameters and their values. Deprecated attribute, pleasepass respective parameters directly to the WMLInferenceEngine class instead.concurrency_limit (int): number of requests that will be sent in parallel, max is 10.Examples:from .api import load_datasetwml_credentials = {"url": "some_url", "project_id": "some_id", "api_key": "some_key"}model_name = "google/flan-t5-xxl"wml_inference = WMLInferenceEngine(credentials=wml_credentials,model_name=model_name,data_classification_policy=["public"],top_p=0.5,random_seed=123,)dataset = load_dataset(dataset_query="card=cards.argument_topic,template_card_index=0,loader_limit=5")results = wml_inference.infer(dataset["test"])"""credentials: Optional[Dict[Literal["url", "apikey", "project_id"], str]] = Nonemodel_name: Optional[str] = Nonedeployment_id: Optional[str] = Nonelabel: str = "wml"_requirements_list = {"ibm-watsonx-ai==1.1.14": "Install ibm-watsonx-ai package using 'pip install --upgrade ibm-watsonx-ai'. ""It is advised to have Python version >=3.10 installed, as at lower version this package ""may cause conflicts with other installed packages."}data_classification_policy = ["public", "proprietary"]parameters: Optional[WMLInferenceEngineParams] = Noneconcurrency_limit: int = 10_client: Any = InternalField(default=None, name="WML client")def get_engine_id(self):return get_model_and_label_id(self.model_name, self.label)def verify(self):super().verify()if self.credentials is not None:for key in self.credentials:if key not in ["url", "apikey", "project_id", "space_id"]:raise ValueError(f'Illegal credential key: {key}, use only ["url", "apikey", "project_id", "space_id"]')assert (self.model_nameor self.deployment_id9 unmodified linesdata["credentials"][key] = valuereturn data@staticmethoddef _read_wml_credentials_from_env() -> (Dict[Literal["url", "apikey", "project_id", "space_id"], str]):credentials = {}project_or_deployment_var_name = ("WML_SPACE_ID" if "WML_SPACE_ID" in os.environ else "WML_PROJECT_ID")for env_var_name in ["WML_URL", project_or_deployment_var_name, "WML_APIKEY"]:env_var = os.environ.get(env_var_name)assert env_var, (f"Error while trying to run 'WMLInferenceEngine'. "f"Please set the env variable: '{env_var_name}', or "f"directly provide an instance of ibm-watsonx-ai 'Credentials' "f"to the engine.")name = env_var_name.lower().replace("wml_", "")credentials[name] = env_varreturn credentialsdef _initialize_wml_client(self):from ibm_watsonx_ai.client import APIClientif self.credentials is None:self.credentials = self._read_wml_credentials_from_env()client = APIClient(credentials=self.credentials)if "space_id" in self.credentials:client.set.default_space(self.credentials["space_id"])else:client.set.default_project(self.credentials["project_id"])return clientdef prepare_engine(self):self._client = self._initialize_wml_client()self._set_inference_parameters()def _load_model_and_params(self):from ibm_watsonx_ai.foundation_models import ModelInferencemodel = ModelInference(model_id=self.model_name,deployment_id=self.deployment_id,api_client=self._client,)params = self.to_dict([WMLInferenceEngineParamsMixin], keep_empty=False)return model, paramsdef _infer(self,dataset: Union[List[Dict[str, Any]], DatasetDict],return_meta_data: bool = False,) -> Union[List[str], List[TextGenerationInferenceOutput]]:self.verify_not_chat_api(dataset)model, params = self._load_model_and_params()result = []for source in dataset["source"]:instance_result = model.generate(prompt=source,params=self.to_dict([WMLInferenceEngineParamsMixin], keep_empty=False),)prediction = instance_result["results"][0]["generated_text"]instance_final_results = self.get_return_object(prediction, instance_result, return_meta_data)result.append(instance_final_results)return resultdef _infer_log_probs(self,dataset: Union[List[Dict[str, Any]], DatasetDict],return_meta_data: bool = False,) -> Union[List[Dict], List[TextGenerationInferenceOutput]]:self.verify_not_chat_api(dataset)model, params = self._load_model_and_params()user_return_options = params.pop("return_options", {})# currently this is the only configuration that returns generated logprobs and behaves as expectedlogprobs_return_options = {"input_tokens": True,"generated_tokens": True,"token_logprobs": True,"top_n_tokens": user_return_options.get("top_n_tokens", 5),}for key, value in logprobs_return_options.items():if key in user_return_options and user_return_options[key] != value:raise ValueError(f"'{key}={user_return_options[key]}' is not supported for the 'infer_log_probs' "f"method of {self.__class__.__name__}. For obtaining the logprobs of generated tokens "f"please use '{key}={value}'.")params = {**params,"return_options": logprobs_return_options,}results = model.generate(prompt=[instance["source"] for instance in dataset],params=params,)final_results = []for result in results:generated_tokens = result["results"][0]["generated_tokens"]final_results.append(self.get_return_object(generated_tokens, result, return_meta_data))return final_resultsdef get_return_object(self, predict_result, result, return_meta_data):if return_meta_data:return TextGenerationInferenceOutput(prediction=predict_result,input_tokens=result["results"][0]["input_token_count"],output_tokens=result["results"][0]["generated_token_count"],model_name=self.model_name,inference_type=self.label,)return predict_resultdef get_token_count(self, dataset):from ibm_watsonx_ai.foundation_models import ModelInferencetexts = [instance["source"] for instance in dataset]model = ModelInference(model_id=self.model_name,deployment_id=self.deployment_id,api_client=self._client,)for i in trange(len(texts), desc="Tokenizing"):response = model.tokenize(prompt=texts[i], return_tokens=True)["result"]dataset[i]["token_count"] = response["token_count"]return datasetdef get_options_log_probs(self, dataset):"""Add to each instance in the data a "options_log_prob" field, which is a dict with str as key and a list of {text: str, logprob:float}."""from ibm_watsonx_ai.foundation_models import ModelInferencemodel = ModelInference(model_id=self.model_name,deployment_id=self.deployment_id,api_client=self._client,)texts = [x["source"] for x in dataset]responses = list(tqdm(model.generate(prompt=texts,params={"decoding_method": "greedy",25 unmodified linesreturn datasetdef get_images_without_text(instance):return extract_images(instance["source"], instance)def get_text_without_images(instance, image_token="<image>"):regex = r"<" + f"{constants.image_tag}" + r'\s+src=["\'](.*?)["\']\s*/?>'return re.sub(regex, image_token, instance["source"])class HFLlavaInferenceEngine(InferenceEngine, LazyLoadMixin):model_name: strmax_new_tokens: intlazy_load = Trueimage_token = "<image>"_requirements_list = {"transformers": "Install huggingface package using 'pip install --upgrade transformers","torch": "Install torch, go on PyTorch website for mode details.","accelerate": "pip install accelerate",}def get_engine_id(self):return get_model_and_label_id(self.model_name, "hf_lava")def _prepare_engine(self):import torchfrom transformers import AutoProcessor, LlavaForConditionalGenerationself.device = torch.device("mps"if torch.backends.mps.is_available()else 0if torch.cuda.is_available()else "cpu")self.model = LlavaForConditionalGeneration.from_pretrained(self.model_name,torch_dtype=torch.float16,low_cpu_mem_usage=True,).to(self.device)self.processor = AutoProcessor.from_pretrained(self.model_name)def prepare_engine(self):if not self.lazy_load:self._prepare_engine()def _is_loaded(self):return hasattr(self, "model") and self.model is not Nonedef _get_input(self, instance):assert isinstance(instance["source"], list), "Must use format=formats.chat_api"images = []conversation = []for turn in instance["source"]:if isinstance(turn["content"], list):for content in turn["content"]:if content["type"] == "image_url":content["type"] = "image"image_url = content.pop("image_url")["url"]image = data_url_to_image(image_url)images.append(image)conversation.append(turn)return conversation, imagesdef _infer(self,dataset: Union[List[Dict[str, Any]], DatasetDict],return_meta_data: bool = False,) -> Union[List[str], List[TextGenerationInferenceOutput]]:if not self._is_loaded():self._prepare_engine()import torchresults = []for instance in tqdm(dataset):conversation, images = self._get_input(instance)if len(images) == 1:images = images[0]text = self.processor.apply_chat_template(conversation, add_generation_prompt=True)inputs = self.processor(images=images, text=text, return_tensors="pt").to(self.device, torch.float16)input_len = len(inputs["input_ids"][0])output = self.model.generate(**inputs,max_new_tokens=self.max_new_tokens,do_sample=False,pad_token_id=self.processor.tokenizer.eos_token_id,)result = self.processor.decode(output[0][input_len:], skip_special_tokens=True)results.append(result)return resultsclass LMMSEvalBaseInferenceEngine(4 unmodified linesbatch_size: int = 1image_token = "<image>"_requirements_list = ["lmms-eval==0.2.4"]def prepare_engine(self):if not self.lazy_load:40 unmodified linesdataset: Union[List[Dict[str, Any]], DatasetDict],return_meta_data: bool = False,) -> Union[List[str], List[TextGenerationInferenceOutput]]:self.verify_not_chat_api(dataset)if not self._is_loaded():self._prepare_engine()8 unmodified lines910111213141516171819202122232425263 unmodified lines30313233343536373839404137 unmodified lines7980818283848586871 unmodified line89909192939495969772 unmodified lines17017117217317417517617717817958 unmodified lines238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113577 unmodified lines121312141215121612171218121912201221122212231224122512262 unmodified lines12291230123112321233123412351236123712381239124012411242124312441245124612471248124912501 unmodified line125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612773 unmodified lines12811282128312841285128612871288128912 unmodified lines13021303130413051306130713081309131013111312131320 unmodified lines1334133513361337133813391340134113421343134413451346134713481349135013511352135313541355313 unmodified lines166916701671167216731674167516761677167829 unmodified lines1708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317949 unmodified lines18041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198925 unmodified lines201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823494 unmodified lines23542355235623572358235923602361236240 unmodified lines2403240424052406240724088 unmodified linesimport timeimport uuidfrom collections import Counterfrom typing import (Any,Dict,Iterable,List,Literal,Mapping,Optional,Sequence,Tuple,Union,)from datasets import DatasetDictfrom tqdm import tqdm, trange3 unmodified linesfrom .dataclass import InternalField, NonPositionalFieldfrom .deprecation_utils import deprecationfrom .error_utils import UnitxtErrorfrom .image_operators import EncodeImageToString, data_url_to_image, extract_imagesfrom .logging_utils import get_loggerfrom .operator import PackageRequirementsMixinfrom .operators import ArtifactFetcherMixinfrom .settings_utils import get_constants, get_settingsfrom .type_utils import isoftypeconstants = get_constants()settings = get_settings()37 unmodified linesinput_tokens (int) : number of input tokens to the model.output_tokens (int) : number of output tokens to the model.stop_reason (str): stop reason for text generation, for example "eos" (end of string).seed (int): seed used by the model during generation.input_text (str): input to the model.model_name (str): the model_name as kept in the InferenceEngine.inference_type (str): The label stating the type of the InferenceEngine."""1 unmodified lineprediction: Union[str, List[Dict[str, Any]]]input_tokens: Optional[int] = Noneoutput_tokens: Optional[int] = Nonestop_reason: Optional[str] = Noneseed: Optional[int] = Noneinput_text: Optional[str] = Nonemodel_name: Optional[str] = Noneinference_type: Optional[str] = None72 unmodified linesif param_inst_val is None:setattr(self, param, param_dict_val)def get_model_details(self) -> Dict:"""Might not be possible to implement for all inference engines. Returns an empty dict by default."""return {}def verify_not_chat_api(self, dataset):if isinstance(dataset[0]["source"], list):raise NotImplementedError(58 unmodified linespassclass HFGenerationParamsMixin(Artifact):max_new_tokens: intdo_sample: bool = Falsetemperature: Optional[float] = Nonetop_p: Optional[float] = Nonetop_k: Optional[int] = Nonenum_beams: Optional[int] = Nonerepetition_penalty: Optional[float] = Nonepad_token_id: Optional[int] = Noneeos_token_id: Optional[int] = Noneclass HFInferenceEngineBase(InferenceEngine,LogProbInferenceEngine,PackageRequirementsMixin,LazyLoadMixin,HFGenerationParamsMixin,):model_name: strlabel: strn_top_tokens: int = 5device: Any = Nonedevice_map: Any = Noneuse_fast_tokenizer: bool = Truelow_cpu_mem_usage: bool = Truetorch_dtype: str = "torch.float16"model: Any = InternalField(default=None, name="Inference object")processor: Any = InternalField(default=None, name="Input processor (tokenizer)")_requirements_list = {"transformers": "Install huggingface package using 'pip install --upgrade transformers","torch": "Install torch, go on PyTorch website for mode details.","accelerate": "pip install accelerate",}def _is_loaded(self):return hasattr(self, "model") and self.model is not Nonedef _set_inference_device(self):if self.device is not None and self.device_map is not None:raise ValueError(f"You must specify either 'device' or 'device_map', however both "f"were given: 'device={self.device}', 'device_map={self.device_map}'.")if self.device is None and self.device_map is None:import torchself.device = torch.device("mps"if torch.backends.mps.is_available()else 0if torch.cuda.is_available()else "cpu")@abc.abstractmethoddef _init_processor(self):raise NotImplementedError@abc.abstractmethoddef _init_model(self):raise NotImplementedErrordef _get_torch_dtype(self):import torchif not isinstance(self.torch_dtype, str) or not self.torch_dtype.startswith("torch."):raise ValueError(f"'torch_dtype' must be a string representing torch data "f"type used for inference. The name should be an absolute "f"import, for example: 'torch.float16'. However, "f"'{self.torch_dtype}' was given instead.")try:dtype = eval(self.torch_dtype)except (AttributeError, TypeError) as e:raise ValueError(f"Incorrect value of 'torch_dtype' was given: '{self.torch_dtype}'.") from eif not isinstance(dtype, torch.dtype):raise ValueError(f"'torch_dtype' must be an instance of 'torch.dtype', however, "f"'{dtype}' is an instance of '{type(dtype)}'.")return dtypedef _prepare_engine(self):self._set_inference_device()self._init_processor()self._init_model()def prepare_engine(self):if not self.lazy_load:self._prepare_engine()def get_engine_id(self):return get_model_and_label_id(self.model_name, self.label)def decode_tokens(self, tokens: Sequence, inp_length: int) -> List[str]:return [self.processor.decode(token, skip_special_tokens=True)for token in tokens[inp_length:]]@staticmethoddef create_string_from_tokens(string_tokens: List[str]) -> str:return "".join(token for token in string_tokens)def make_predictions(self, prepared_inputs: Mapping) -> Mapping:return self.model.generate(**prepared_inputs,**self.to_dict([HFGenerationParamsMixin], keep_empty=False),output_scores=True,return_dict_in_generate=True,)def compute_transition_scores(self, sequences: Sequence, scores: Sequence, beam_indices: Optional[int]) -> Sequence:# Some models may not support computing scores in this form by default, so a possible# child class should have its own implementation of this method if necessary.return self.model.compute_transition_scores(sequences,scores,normalize_logits=True,beam_indices=beam_indices,)def get_logprobs(self, predictions: Mapping, string_tokens: List[List[str]]) -> List[List[Dict[str, Any]]]:beam_indices = (predictions.beam_indicesif self.num_beams is not None and self.num_beams > 1else None)transition_scores = self.compute_transition_scores(sequences=predictions.sequences,scores=predictions.scores,beam_indices=beam_indices,)logprobs: List[List[Dict[str, Any]]] = []for sample_no, sample_scores in enumerate(transition_scores.detach().cpu()):sample_logprobs: List[Dict[str, Any]] = []for n, score in enumerate(sample_scores):sample_logprobs.append({"text": string_tokens[sample_no][n],"logprob": float(score.cpu()),"top_tokens": [{"text": self.processor.decode(idx),"logprob": float(predictions.scores[n][sample_no][idx].cpu()),}for idx in predictions.scores[n][sample_no].argsort(dim=0, descending=True)[: self.n_top_tokens]],})logprobs.append(sample_logprobs)return logprobs@abc.abstractmethoddef prepare_inputs(self, data: Iterable) -> Mapping:raise NotImplementedErrordef get_return_object(self,output: Union[str, List[Dict[str, Any]]],output_tokens: Optional[int],inp: Optional[str],inp_tokens: Optional[int],return_meta_data: bool,) -> Union[str, List[Dict[str, Any]], TextGenerationInferenceOutput]:if return_meta_data:return TextGenerationInferenceOutput(prediction=output,output_tokens=output_tokens if output_tokens is not None else None,input_text=inp,input_tokens=inp_tokens if inp_tokens is not None else None,model_name=self.model_name,inference_type=self.label,)return outputdef infer(self,dataset: Union[List[Dict[str, Any]], DatasetDict],return_meta_data: bool = False,) -> Union[List[str], List[TextGenerationInferenceOutput]]:if not self._is_loaded():self._prepare_engine()return super().infer(dataset, return_meta_data)@abc.abstractmethoddef _infer(self,dataset: Union[List[Dict[str, Any]], DatasetDict],return_meta_data: bool = False,) -> Union[List[str], List[TextGenerationInferenceOutput]]:raise NotImplementedErrordef infer_log_probs(self,dataset: Union[List[Dict[str, Any]], DatasetDict],return_meta_data: bool = False,) -> Union[List[Dict], List[TextGenerationInferenceOutput]]:if not self._is_loaded():self._prepare_engine()return super().infer_log_probs(dataset, return_meta_data)@abc.abstractmethoddef _infer_log_probs(self,dataset: Union[List[Dict[str, Any]], DatasetDict],return_meta_data: bool = False,) -> Union[List[Dict], List[TextGenerationInferenceOutput]]:raise NotImplementedErrorclass HFAutoModelInferenceEngine(HFInferenceEngineBase):label: str = "hf_auto_model"def _init_processor(self):from transformers import AutoTokenizerself.processor = AutoTokenizer.from_pretrained(pretrained_model_name_or_path=self.model_name,use_fast=self.use_fast_tokenizer,padding=True,truncation=True,)def _init_model(self):from transformers import (AutoConfig,AutoModelForCausalLM,AutoModelForSeq2SeqLM,)model_class = (AutoModelForSeq2SeqLMif AutoConfig.from_pretrained(self.model_name).is_encoder_decoderelse AutoModelForCausalLM)self.model = model_class.from_pretrained(pretrained_model_name_or_path=self.model_name,trust_remote_code=True,device_map=self.device_map,torch_dtype=self._get_torch_dtype(),)if self.device_map is None:self.model.to(self.device)def prepare_inputs(self, data: Iterable) -> Mapping:return self.processor(data,padding=True,truncation=True,return_tensors="pt",).to(self.device or self.device_map)def _infer_fn(self,dataset: Union[List[Dict[str, Any]], DatasetDict],return_meta_data: bool,return_logprobs: bool,) -> Union[List[str], List[Dict], List[TextGenerationInferenceOutput]]:tokenized_inputs = self.prepare_inputs([instance["source"] for instance in dataset])input_length = (1if self.model.config.is_encoder_decoderelse tokenized_inputs.input_ids.shape[1])predictions = self.make_predictions(tokenized_inputs)sequences = predictions.sequencesstring_tokens = [self.decode_tokens(sequence, input_length) for sequence in sequences]final_outputs = (self.get_logprobs(predictions, string_tokens)if return_logprobselse [self.create_string_from_tokens(strings) for strings in string_tokens])return [self.get_return_object(output=final_outputs[i],output_tokens=len(string_tokens[i]),inp=dataset[i]["source"],inp_tokens=len(tokenized_inputs.encodings[i].tokens)if tokenized_inputs.encodings is not Noneelse None,return_meta_data=return_meta_data,)for i in range(len(sequences))]def _infer(self,dataset: Union[List[Dict[str, Any]], DatasetDict],return_meta_data: bool = False,) -> Union[List[str], List[TextGenerationInferenceOutput]]:self.verify_not_chat_api(dataset)return self._infer_fn(dataset, return_meta_data, False)def _infer_log_probs(self,dataset: Union[List[Dict[str, Any]], DatasetDict],return_meta_data: bool = False,) -> Union[List[Dict], List[TextGenerationInferenceOutput]]:self.verify_not_chat_api(dataset)return self._infer_fn(dataset, return_meta_data, True)class HFLlavaInferenceEngine(HFInferenceEngineBase):lazy_load: bool = Truelabel: str = "hf_lava"image_token: str = "<image>"def compute_transition_scores(self, sequences: Sequence, scores: Sequence, beam_indices: Optional[int]) -> Sequence:if not hasattr(self.model.config, "vocab_size"):self.model.config.vocab_size = self.model.vocab_sizereturn super().compute_transition_scores(sequences, scores, beam_indices)def _init_processor(self):from transformers import AutoProcessorself.processor = AutoProcessor.from_pretrained(self.model_name)if not self.pad_token_id and hasattr(self.processor, "eos_token_id"):self.pad_token_id = self.processor.eos_token_iddef _init_model(self):from transformers import LlavaForConditionalGenerationself.model = LlavaForConditionalGeneration.from_pretrained(self.model_name,torch_dtype=self._get_torch_dtype(),low_cpu_mem_usage=self.low_cpu_mem_usage,device_map=self.device_map,)if self.device_map is None:self.model.to(self.device)@staticmethoddef _get_input(instance):assert isinstance(instance["source"], list), "Must use format=formats.chat_api"images = []conversation = []for turn in instance["source"]:if isinstance(turn["content"], list):for content in turn["content"]:if content["type"] == "image_url":content["type"] = "image"image_url = content.pop("image_url")["url"]image = data_url_to_image(image_url)images.append(image)conversation.append(turn)return conversation, imagesdef prepare_inputs(self, data: Iterable) -> Mapping:conversation, images = self._get_input(data)if len(images) == 1:images = images[0]text = self.processor.apply_chat_template(conversation, add_generation_prompt=True)inputs: Mapping = self.processor(images=images, text=text, return_tensors="pt").to(self.device or self.device_map, self._get_torch_dtype())return inputsdef _infer_fn(self,dataset: Union[List[Dict[str, Any]], DatasetDict],return_meta_data: bool,return_logprobs: bool,) -> Union[List[str], List[Dict], List[TextGenerationInferenceOutput]]:results = []for instance in tqdm(dataset):processed_inputs = self.prepare_inputs(instance)input_len = len(processed_inputs["input_ids"][0])predictions = self.make_predictions(processed_inputs)string_tokens = self.decode_tokens(predictions.sequences[0], input_len)final_outputs = (self.get_logprobs(predictions, [string_tokens])[0]if return_logprobselse self.create_string_from_tokens(string_tokens))results.append(self.get_return_object(output=final_outputs,output_tokens=len(string_tokens),inp=instance["source"],inp_tokens=None,return_meta_data=return_meta_data,))return resultsdef _infer(self,dataset: Union[List[Dict[str, Any]], DatasetDict],return_meta_data: bool = False,) -> Union[List[str], List[TextGenerationInferenceOutput]]:return self._infer_fn(dataset, return_meta_data, False)def _infer_log_probs(self,dataset: Union[List[Dict[str, Any]], DatasetDict],return_meta_data: bool = False,) -> Union[List[Dict], List[TextGenerationInferenceOutput]]:return self._infer_fn(dataset, return_meta_data, True)class HFPeftInferenceEngine(HFAutoModelInferenceEngine):label: str = "hf_peft_auto_model"peft_config: Any = InternalField(default=None,name="PEFT config read from the directory or the Hub repository ""id specified in the 'model_name'.",)_requirements_list = {"transformers": "Install huggingface package using 'pip install --upgrade transformers","torch": "Install torch, go on PyTorch website for mode details.","accelerate": "pip install accelerate","peft": "Install 'peft' package using: 'pip install peft'.",}def _prepare_engine(self):self._read_peft_config()super()._prepare_engine()def _read_peft_config(self):from peft import PeftConfigtry:config = PeftConfig.from_pretrained(self.model_name)assert isinstance(config.base_model_name_or_path, str)self.peft_config = configexcept ValueError as e:if "Can't find" in str(e):raise ValueError(f"Specified model '{self.model_name}' is not the PEFT model. "f"Use a regular instance of the `HFAutoModelInferenceEngine` "f"instead.") from eraise edef _init_processor(self):from transformers import AutoTokenizerself.processor = AutoTokenizer.from_pretrained(self.peft_config.base_model_name_or_path)def _init_model(self):from peft import AutoPeftModelForCausalLM, AutoPeftModelForSeq2SeqLMfrom transformers import AutoConfigmodel_class = (AutoPeftModelForSeq2SeqLMif AutoConfig.from_pretrained(self.model_name).is_encoder_decoderelse AutoPeftModelForCausalLM)self.model = model_class.from_pretrained(pretrained_model_name_or_path=self.peft_config.base_model_name_or_path,trust_remote_code=True,device_map=self.device_map,low_cpu_mem_usage=self.low_cpu_mem_usage,torch_dtype=self._get_torch_dtype(),)if self.device_map is None:self.model.to(self.device)@deprecation(version="2.0.0", msg=" Use non-pipeline-based 'HFInferenceEngine' instead.")class HFPipelineBasedInferenceEngine(InferenceEngine, PackageRequirementsMixin, LazyLoadMixin, HFGenerationParamsMixin):model_name: strlabel: str = "hf_pipeline_inference_engine"use_fast_tokenizer: bool = Trueuse_fp16: bool = Trueload_in_8bit: bool = Falsetask: Optional[str] = Nonedevice: Any = Nonedevice_map: Any = Nonepipe: Any = InternalField(default=None)_requirements_list = {"transformers": "Install huggingface package using 'pip install --upgrade transformers","torch": "Install torch, go on PyTorch website for mode details.","accelerate": "pip install accelerate",}def _is_loaded(self):return hasattr(self, "model") and self.model is not Nonedef get_engine_id(self):return get_model_and_label_id(self.model_name, "hf_pipeline")def _define_task(self):from transformers import AutoConfigself.task = ("text2text-generation"if AutoConfig.from_pretrained(self.model_name, trust_remote_code=True).is_encoder_decoderelse "text-generation")def _get_model_args(self) -> Dict[str, Any]:import torchfrom transformers import BitsAndBytesConfigargs = {}if self.load_in_8bit:quantization_config = BitsAndBytesConfig(load_in_8bit=self.load_in_8bit)args["quantization_config"] = quantization_configelif self.use_fp16:if self.device == torch.device("mps"):args["torch_dtype"] = torch.float16else:args["torch_dtype"] = torch.bfloat16# We do this, because in some cases, using device:auto will offload some weights to the cpu# (even though the model might *just* fit to a single gpu), even if there is a gpu available, and this will# cause an error because the data is always on the gpuif torch.cuda.device_count() > 1:assert self.device == torch.device(0)args["device_map"] = "auto"else:if not self.load_in_8bit:args["device"] = self.deviceif self.task == "text-generation":args["return_full_text"] = Falsereturn argsdef _create_pipeline(self, model_args: Dict[str, Any]):from transformers import pipelineself.model = pipeline(model=self.model_name,task=self.task,use_fast=self.use_fast_tokenizer,trust_remote_code=True,**model_args,**self.to_dict([HFGenerationParamsMixin],keep_empty=False,),)def _set_inference_device(self):if self.device is not None and self.device_map is not None:raise ValueError(f"You must specify either 'device' or 'device_map', however both "f"were given: 'device={self.device}', 'device_map={self.device_map}'.")if self.device is None and self.device_map is None:import torchself.device = torch.device("mps"if torch.backends.mps.is_available()else 0if torch.cuda.is_available()else "cpu")def _prepare_engine(self):self._set_inference_device()if self.task is None:self._define_task()model_args = self._get_model_args()self._create_pipeline(model_args)def prepare_engine(self):if not self.lazy_load:self._prepare_engine()def _infer(self,dataset: Union[List[Dict[str, Any]], DatasetDict],return_meta_data: bool = False,) -> Union[List[str], List[TextGenerationInferenceOutput]]:if not self._is_loaded():self._prepare_engine()outputs = self.model([instance["source"] for instance in dataset])return [self.get_return_object(output[0], instance["source"], return_meta_data)if isinstance(output, list)else self.get_return_object(output, instance["source"], return_meta_data)for output, instance in zip(outputs, dataset)]def get_return_object(self, output, inp, return_meta_data):if return_meta_data:return TextGenerationInferenceOutput(prediction=output["generated_text"],model_name=self.model_name,inference_type=self.label,input_text=inp,)return output["generated_text"]def mock_logprobs_default_value_factory() -> List[Dict[str, Any]]:return [{"logprob": -1,"text": "[[10]]","top_tokens": [{"logprob": -1, "text": "[[10]]"},],}]class MockInferenceEngine(InferenceEngine, LogProbInferenceEngine):model_name: strdefault_inference_value: str = "[[10]]"default_inference_value_logprob: List[Dict[str, Any]] = dataclasses.field(default_factory=mock_logprobs_default_value_factory,)label: str = "mock_inference_engine"def get_engine_id(self):return get_model_and_label_id(self.model_name, "mock")def prepare_engine(self):returndef _mock_infer(self,dataset: Union[List[Dict[str, Any]], DatasetDict],) -> Union[List[str], List[TextGenerationInferenceOutput]]:return [self.default_inference_value for _ in dataset]def _infer(self,dataset: Union[List[Dict[str, Any]], DatasetDict],return_meta_data: bool = False,) -> Union[List[str], List[TextGenerationInferenceOutput]]:return [self.get_return_object(self.default_inference_value, instance, return_meta_data)for instance in dataset]def _infer_log_probs(self,dataset: Union[List[Dict[str, Any]], DatasetDict],return_meta_data: bool = False,) -> Union[List[Dict], List[TextGenerationInferenceOutput]]:return [self.get_return_object(self.default_inference_value_logprob, instance, return_meta_data)for instance in dataset]def get_return_object(self, predict_result, instance, return_meta_data):if return_meta_data:return TextGenerationInferenceOutput(prediction=predict_result,input_tokens=len(instance["source"]),output_tokens=len(predict_result),model_name=self.model_name,inference_type=self.label,input_text=instance["source"],seed=111,stop_reason="",)return predict_resultclass MockModeMixin(Artifact):mock_mode: bool = Falseclass IbmGenAiInferenceEngineParamsMixin(Artifact):beam_width: Optional[int] = Nonedecoding_method: Optional[Literal["greedy", "sample"]] = Noneinclude_stop_sequence: Optional[bool] = Nonelength_penalty: Any = Nonemax_new_tokens: Optional[int] = Nonemin_new_tokens: Optional[int] = Nonerandom_seed: Optional[int] = Nonerepetition_penalty: Optional[float] = Nonereturn_options: Any = Nonestop_sequences: Optional[List[str]] = Nonetemperature: Optional[float] = Nonetime_limit: Optional[int] = Nonetop_k: Optional[int] = Nonetop_p: Optional[float] = Nonetruncate_input_tokens: Optional[int] = Nonetypical_p: Optional[float] = None@deprecation(version="2.0.0", alternative=IbmGenAiInferenceEngineParamsMixin)class IbmGenAiInferenceEngineParams(Artifact):beam_width: Optional[int] = Nonedecoding_method: Optional[Literal["greedy", "sample"]] = Noneinclude_stop_sequence: Optional[bool] = Nonelength_penalty: Any = Nonemax_new_tokens: Optional[int] = Nonemin_new_tokens: Optional[int] = Nonerandom_seed: Optional[int] = Nonerepetition_penalty: Optional[float] = Nonereturn_options: Any = Nonestop_sequences: Optional[List[str]] = Nonetemperature: Optional[float] = Nonetime_limit: Optional[int] = Nonetop_k: Optional[int] = Nonetop_p: Optional[float] = Nonetruncate_input_tokens: Optional[int] = Nonetypical_p: Optional[float] = Noneclass GenericInferenceEngine(InferenceEngine, ArtifactFetcherMixin, LogProbInferenceEngine):default: Optional[str] = Nonedef prepare_engine(self):if "UNITXT_INFERENCE_ENGINE" in os.environ:engine_reference = os.environ["UNITXT_INFERENCE_ENGINE"]else:assert self.default is not None, ("GenericInferenceEngine could not be initialized"'\nThis is since both the "UNITXT_INFERENCE_ENGINE" environmental variable is not set and no default engine was not inputted.'"\nFor example, you can fix it by setting""\nexport UNITXT_INFERENCE_ENGINE=engines.ibm_gen_ai.llama_3_70b_instruct""\nto your ~/.bashrc""\nor passing a similar required engine in the default argument")engine_reference = self.defaultself.engine = self.get_artifact(engine_reference)def get_engine_id(self):# If mock_inference_mode is set, no engine is prepared.if hasattr(self, "engine"):return f"generic_{self.engine.get_engine_id()}"return "generic_inference_engine"def _infer(self,dataset: Union[List[Dict[str, Any]], DatasetDict],return_meta_data: bool = False,) -> Union[List[str], List[TextGenerationInferenceOutput]]:return self.engine._infer(dataset)def _infer_log_probs(self,dataset: Union[List[Dict[str, Any]], DatasetDict],return_meta_data: bool = False,) -> Union[List[str], List[TextGenerationInferenceOutput]]:if not isinstance(self.engine, LogProbInferenceEngine):raise NotImplementedError(f"Error in infer: inference engine used by the GenericInferenceEngine"f"({self.engine.__class__.__name__}) does not support logprobs.")return self.engine._infer_log_probs(dataset)class OllamaInferenceEngine(InferenceEngine, StandardAPIParamsMixin, PackageRequirementsMixin):label: str = "ollama"_requirements_list = {"ollama": "Install ollama package using 'pip install --upgrade ollama"}data_classification_policy = ["public", "proprietary"]def get_engine_id(self):return get_model_and_label_id(self.model, self.label)def prepare_engine(self):passdef _infer(self,dataset: Union[List[Dict[str, Any]], DatasetDict],return_meta_data: bool = False,) -> Union[List[str], List[TextGenerationInferenceOutput]]:import ollamaargs = self.to_dict([StandardAPIParamsMixin])results = []for instance in dataset:messages = self.to_messages(instance)response = ollama.chat(model=self.model,messages=messages,**args,)results.append(response)return [element["message"]["content"] for element in results]class OptionSelectingByLogProbsInferenceEngine:"""OptionSelectingByLogProbsInferenceEngine inference engine is used to select an option based on the logprobs of an options list conditioned by a prompt.The inference engines that inherit from this class must implement `get_token_count` and `get_options_log_probs`."""@abc.abstractmethoddef get_token_count(self, dataset):"""Get the token count of the source key of each dict of the dataset. Add to each instance in the data a "token_count" field.Args:dataset (List[Dict[str, Any]]): A list of dictionaries, each representing a data instance.Returns:List[int]: The token count of the texts"""@abc.abstractmethoddef get_options_log_probs(self, dataset):"""Get the token logprobs of the options of the key task_data.options of each dict of the dataset.Add to each instance in the data a "options_log_prob" field, which is a dict with str as key and a list of {text: str, logprob:float}.Args:dataset (List[Dict[str, Any]]): A list of dictionaries, each representing a data instance.Returns:List[int]: The token count of the texts"""def select(self, dataset: List[Dict[str, Any]]) -> List[Dict[str, Any]]:77 unmodified lines}data_classification_policy = ["public", "proprietary"]parameters: Optional[IbmGenAiInferenceEngineParams] = Nonerate_limit: int = 10def get_engine_id(self):return get_model_and_label_id(self.model_name, self.label)@staticmethoddef _get_credentials():from genai import Credentialsapi_key_env_var_name = "GENAI_KEY"api_key = os.environ.get(api_key_env_var_name)2 unmodified linesf"Error while trying to run IbmGenAiInferenceEngine."f" Please set the environment param '{api_key_env_var_name}'.")return Credentials(api_key=api_key)def prepare_engine(self):self.check_missing_requirements()from genai import Clientfrom genai.text.generation import CreateExecutionOptionscredentials = self._get_credentials()self.client = Client(credentials=credentials)self.execution_options = CreateExecutionOptions(concurrency_limit=self.rate_limit)self._set_inference_parameters()def _infer(1 unmodified linedataset: Union[List[Dict[str, Any]], DatasetDict],return_meta_data: bool = False,) -> Union[List[str], List[TextGenerationInferenceOutput]]:from genai.schema import TextGenerationParameters, TextGenerationResultself.verify_not_chat_api(dataset)genai_params = TextGenerationParameters(**self.to_dict([IbmGenAiInferenceEngineParamsMixin]))responses = self.client.text.generation.create(model_id=self.model_name,inputs=[instance["source"] for instance in dataset],parameters=genai_params,execution_options=self.execution_options,)results = []for response in responses:generation_result: TextGenerationResult = response.results[0]result = self.get_return_object(generation_result.generated_text, generation_result, return_meta_data)results.append(result)return results3 unmodified linesdataset: Union[List[Dict[str, Any]], DatasetDict],return_meta_data: bool = False,) -> Union[List[Dict], List[TextGenerationInferenceOutput]]:from genai.schema import TextGenerationParameters, TextGenerationResultself.verify_not_chat_api(dataset)logprobs_return_options = {"generated_tokens": True,12 unmodified linesmodel_id=self.model_name,inputs=[instance["source"] for instance in dataset],parameters=genai_params,execution_options=self.execution_options,)predict_results = []for prediction in predictions:result: TextGenerationResult = prediction.results[0]assert isinstance(result.generated_tokens, list), "result.generated_tokens should be a list"20 unmodified linesoutput_tokens=result.generated_token_count,model_name=self.model_name,inference_type=self.label,input_text=result.input_text,seed=self.random_seed,stop_reason=result.stop_reason,)return predict_resultdef get_model_details(self) -> Dict:from genai import ApiClientfrom genai.model import ModelServiceapi_client = ApiClient(credentials=self._get_credentials())model_info = (ModelService(api_client=api_client).retrieve(id=self.model_name).result)return model_info.dict()def get_token_count(self, dataset):texts = [instance["source"] for instance in dataset]token_counts = list(313 unmodified linesreturn OpenAI(api_key=api_key, base_url=api_url)@deprecation(version="2.0.0",msg=" You can specify inference parameters directly when initializing an inference engine.",)class WMLInferenceEngineParamsMixin(Artifact):decoding_method: Optional[Literal["greedy", "sample"]] = Nonelength_penalty: Optional[Dict[str, Union[int, float]]] = None29 unmodified linesreturn_options: Optional[Dict[str, bool]] = Noneclass WMLGenerationParamsMixin(Artifact):decoding_method: Optional[Literal["greedy", "sample"]] = Nonelength_penalty: Optional[Dict[str, Union[int, float]]] = Nonetemperature: Optional[float] = Nonetop_p: Optional[float] = Nonetop_k: Optional[int] = Nonerandom_seed: Optional[int] = Nonerepetition_penalty: Optional[float] = Nonemin_new_tokens: Optional[int] = Nonemax_new_tokens: Optional[int] = Nonestop_sequences: Optional[List[str]] = Nonetime_limit: Optional[int] = Nonetruncate_input_tokens: Optional[int] = Noneprompt_variables: Optional[Dict[str, Any]] = Nonereturn_options: Optional[Dict[str, bool]] = Noneclass WMLChatParamsMixin(Artifact):frequency_penalty: Optional[float] = Nonetop_logprobs: Optional[int] = 5presence_penalty: Optional[float] = Noneresponse_format: Optional[Dict[str, Any]] = Nonetemperature: Optional[float] = Nonemax_tokens: Optional[int] = Nonetime_limit: Optional[int] = Nonetop_p: Optional[float] = Nonen: Optional[int] = NoneCredentialsWML = Dict[Literal["url", "username", "password", "apikey", "project_id", "space_id"], str]class WMLInferenceEngineBase(InferenceEngine,PackageRequirementsMixin,LogProbInferenceEngine,OptionSelectingByLogProbsInferenceEngine,):"""Base for classes running inference using ibm-watsonx-ai.Attributes:credentials (Dict[str, str], optional): By default, it is created by a classinstance which tries to retrieve proper environment variables("WML_URL", "WML_PROJECT_ID", "WML_SPACE_ID", "WML_APIKEY", "WML_USERNAME", "WML_PASSWORD").However, a dictionary with the following keys: "url", "apikey", "project_id", "space_id","username", "password".can be directly provided instead.model_name (str, optional): ID of a model to be used for inference. Mutuallyexclusive with 'deployment_id'.deployment_id (str, optional): Deployment ID of a tuned model to be used forinference. Mutually exclusive with 'model_name'.parameters (Union[WMLInferenceEngineParams, WMLGenerationParamsMixin, WMLChatParamsMixin], optional):Defines inference parameters and their values. Deprecated attribute, please pass respectiveparameters directly to the respective class instead."""credentials: Optional[CredentialsWML] = Nonemodel_name: Optional[str] = Nonedeployment_id: Optional[str] = Nonelabel: str = "wml"_requirements_list = {"ibm_watsonx_ai": "Install ibm-watsonx-ai package using 'pip install --upgrade ibm-watsonx-ai'. ""It is advised to have Python version >=3.10 installed, as at lower version this package ""may cause conflicts with other installed packages."}data_classification_policy = ["public", "proprietary"]parameters: Optional[Union[WMLInferenceEngineParams, WMLGenerationParamsMixin, WMLChatParamsMixin]] = None_client: Any = InternalField(default=None, name="WML client")_model: Any = InternalField(default=None, name="WML model")def get_engine_id(self):return get_model_and_label_id(self.model_name or self.deployment_id, self.label)def verify(self):super().verify()assert (self.model_nameor self.deployment_id9 unmodified linesdata["credentials"][key] = valuereturn datadef _initialize_wml_client(self):from ibm_watsonx_ai.client import APIClientif self.credentials is None:self.credentials = self._read_wml_credentials_from_env()self._verify_wml_credentials(self.credentials)client = APIClient(credentials=self.credentials)if "space_id" in self.credentials:client.set.default_space(self.credentials["space_id"])else:client.set.default_project(self.credentials["project_id"])return client@staticmethoddef _read_wml_credentials_from_env() -> CredentialsWML:credentials: CredentialsWML = {}url = os.environ.get("WML_URL")assert url, ("Error while trying to run 'WMLInferenceEngine'. ""Please set the env variable: 'WML_URL'")credentials["url"] = urlspace_id = os.environ.get("WML_SPACE_ID")project_id = os.environ.get("WML_PROJECT_ID")if space_id and project_id:get_logger().warning("Either 'WML_SPACE_ID' or 'WML_PROJECT_ID' need to be ""specified, however, both were found. 'WMLInferenceEngine' ""will use space by default. If it is not desired, then have ""only one of those defined in the env.")credentials["space_id"] = space_idelif project_id:credentials["project_id"] = project_idelse:raise AssertionError("Error while trying to run 'WMLInferenceEngine'. ""Please set either 'WML_SPACE_ID' or 'WML_PROJECT_ID' env ""variable.")apikey = os.environ.get("WML_APIKEY")username = os.environ.get("WML_USERNAME")password = os.environ.get("WML_PASSWORD")if apikey and username and password:get_logger().warning("Either 'WML_APIKEY' or both 'WML_USERNAME' and 'WML_PASSWORD' ""need to be specified, however, all of them were found. ""'WMLInferenceEngine' will use api key only by default. If it is not ""desired, then have only one of those options defined in the env.")if apikey:credentials["apikey"] = apikeyelif username and password:credentials["username"] = usernamecredentials["password"] = passwordelse:raise AssertionError("Error while trying to run 'WMLInferenceEngine'. ""Please set either 'WML_APIKEY' or both 'WML_USERNAME' and ""'WML_PASSWORD' env variables.")return credentials@staticmethoddef _verify_wml_credentials(credentials: CredentialsWML) -> None:assert isoftype(credentials, CredentialsWML), ("WML credentials object must be a dictionary which may ""contain only the following keys: ""['url', 'apikey', 'username', 'password'].")assert credentials.get("url"), "'url' is a mandatory key for WML credentials dict."assert "space_id" in credentials or "project_id" in credentials, ("Either 'space_id' or 'project_id' must be provided ""as keys for WML credentials dict.")assert "apikey" in credentials or ("username" in credentials and "password" in credentials), ("Either 'apikey' or both 'username' and 'password' must be provided ""as keys for WML credentials dict.")def prepare_engine(self):self.check_missing_requirements()self._client = self._initialize_wml_client()self._set_inference_parameters()def _load_model(self):from ibm_watsonx_ai.foundation_models.inference import ModelInferenceself._model = ModelInference(model_id=self.model_name,deployment_id=self.deployment_id,api_client=self._client,)@abc.abstractmethoddef _send_requests(self,dataset: Union[List[Dict[str, Any]], DatasetDict],return_logprobs: bool,return_meta_data: bool,) -> Union[List[str], List[Dict], List[TextGenerationInferenceOutput]]:raise NotImplementedError(f"The class '{self.get_pretty_print_name()}' is an abstract class. "f"Please used either 'WMLInferenceEngineGeneration' or "f"'WMLInferenceEngineChat' instead, depending on your task.")def _infer(self,dataset: Union[List[Dict[str, Any]], DatasetDict],return_meta_data: bool = False,) -> Union[List[str], List[TextGenerationInferenceOutput]]:if self._model is None:self._load_model()return self._send_requests(dataset=dataset,return_logprobs=False,return_meta_data=return_meta_data,)def _infer_log_probs(self,dataset: Union[List[Dict[str, Any]], DatasetDict],return_meta_data: bool = False,) -> Union[List[Dict], List[TextGenerationInferenceOutput]]:if self._model is None:self._load_model()return self._send_requests(dataset=dataset,return_logprobs=True,return_meta_data=return_meta_data,)@abc.abstractmethoddef get_return_object(self, predict_result, result, input_text, return_meta_data):raise NotImplementedErrordef get_model_details(self) -> Dict:return self._model.get_details()def get_token_count(self, dataset):if self._model is None:self._load_model()texts = [instance["source"] for instance in dataset]for i in trange(len(texts), desc="Tokenizing"):response = self._model.tokenize(prompt=texts[i], return_tokens=True)["result"]dataset[i]["token_count"] = response["token_count"]return datasetdef get_options_log_probs(self, dataset):"""Add to each instance in the data a "options_log_prob" field, which is a dict with str as key and a list of {text: str, logprob:float}."""if self._model is None:self._load_model()texts = [x["source"] for x in dataset]responses = list(tqdm(self._model.generate(prompt=texts,params={"decoding_method": "greedy",25 unmodified linesreturn datasetclass WMLInferenceEngineGeneration(WMLInferenceEngineBase, WMLGenerationParamsMixin):"""Generates text for textual inputs.If you want to include images in your input, please use 'WMLInferenceEngineChat' instead.Attributes:concurrency_limit (int): Number of concurrent requests sent to a model. Default is 10,which is also the maximum value.Examples:from .api import load_datasetwml_credentials = {"url": "some_url", "project_id": "some_id", "api_key": "some_key"}model_name = "google/flan-t5-xxl"wml_inference = WMLInferenceEngineGeneration(credentials=wml_credentials,model_name=model_name,data_classification_policy=["public"],top_p=0.5,random_seed=123,)dataset = load_dataset(dataset_query="card=cards.argument_topic,template_card_index=0,loader_limit=5")results = wml_inference.infer(dataset["test"])"""concurrency_limit: int = 10def verify(self):super().verify()assert (isinstance(self.concurrency_limit, int)and 1 <= self.concurrency_limit <= 10), (f"'concurrency_limit' must be a positive integer not greater than 10. "f"However, '{self.concurrency_limit}' was given.")def _set_logprobs_params(self, params: Dict[str, Any]) -> Dict[str, Any]:user_return_options = params.pop("return_options", {})# currently this is the only configuration that returns generated# logprobs and behaves as expectedlogprobs_return_options = {"input_tokens": True,"generated_tokens": True,"token_logprobs": True,"top_n_tokens": user_return_options.get("top_n_tokens", 5),}for key, value in logprobs_return_options.items():if key in user_return_options and user_return_options[key] != value:raise ValueError(f"'{key}={user_return_options[key]}' is not supported for the 'infer_log_probs' "f"method of {self.__class__.__name__}. For obtaining the logprobs of generated tokens "f"please use '{key}={value}'.")return {**params,"return_options": logprobs_return_options,}def _send_requests(self,dataset: Union[List[Dict[str, Any]], DatasetDict],return_logprobs: bool,return_meta_data: bool,) -> Union[List[str], List[Dict], List[TextGenerationInferenceOutput]]:self.verify_not_chat_api(dataset)params = self.to_dict([WMLGenerationParamsMixin], keep_empty=False)if return_logprobs:generation_type = "generated_tokens"params = self._set_logprobs_params(params)else:generation_type = "generated_text"inputs: List[str] = [instance["source"] for instance in dataset]results = self._model.generate(prompt=inputs,params=params,concurrency_limit=self.concurrency_limit,)final_results = []for result, inp in zip(results, inputs):result_metadata = result["results"][0]generated_content = result_metadata[generation_type]final_results.append(self.get_return_object(generated_content, result_metadata, inp, return_meta_data))return final_resultsdef get_return_object(self, predict_result, result, input_text, return_meta_data):if return_meta_data:return TextGenerationInferenceOutput(prediction=predict_result,input_tokens=result["input_token_count"],output_tokens=result["generated_token_count"],model_name=self.model_name or self.deployment_id,inference_type=self.label,stop_reason=result["stop_reason"],seed=self.random_seed,input_text=input_text,)return predict_resultclass WMLInferenceEngineChat(WMLInferenceEngineBase, WMLChatParamsMixin):"""Creates chat session and returns a model's response.You can also include images in your inputs. If you use only textual input, it isrecommended to use 'WMLInferenceEngineGeneration' instead as it is faster, and allowsmore parameters for text generation.You can provide either already formatted messages, or a raw dataset as an input.In case of the former, all passed images should be base64-encoded strings given asan 'image_url' within a message. Moreover, only one image per a list of messagesmay be sent.As for the latter, if there are multiple images per one instance, they will be sentseparately with the same query. If that could possibly affect expected responses,concatenate images within an instance into a single image and adjust your queryaccordingly (if necessary).Attributes:image_encoder (EncodeImageToString, optional): operator which encodes images ingiven format to base64 strings required by service. You should specify it whenyou are using images in your inputs.Example:from .api import load_datasetfrom .image_operatorsimage_encoder = EncodeImageToString(image_format="JPEG")wml_credentials = {"url": "some_url", "project_id": "some_id", "api_key": "some_key"}model_name = "meta-llama/llama-3-2-11b-vision-instruct"wml_inference = WMLInferenceEngineChat(credentials=wml_credentials,model_name=model_name,image_encoder=image_encoder,data_classification_policy=["public"],max_tokens=1024,)dataset = load_dataset(dataset_query="card=cards.doc_vqa.en,template=templates.qa.with_context.with_type,loader_limit=30")results = wml_inference.infer(dataset["test"])"""image_encoder: Optional[EncodeImageToString] = None@staticmethoddef _extract_queries(instance: Dict[str, Any]) -> Tuple[Optional[str], List]:task_data = instance["task_data"]if isinstance(task_data, str):task_data = json.loads(task_data)question = task_data.get("question")images = [None]if "images" in instance["media"]:images = extract_images(instance["source"], instance)return question or instance["source"], imagesdef _create_messages_from_instance(self, instance: Dict[str, Any]) -> List[List[Dict[str, Any]]]:"""Method creates chat messages to be sent to a watsonx.ai model based on a given instance from a dataset."""text, images = self._extract_queries(instance)messages: List[List[Dict[str, Any]]] = []base_message = {"role": "user","content": [{"type": "text","text": text,}],}# Iteration over all possible images to create a separate message for# every single image, since SDK allows only one image per request.for image in images:message = base_message.copy()if image is not None:encoded_image = imageif not isinstance(encoded_image, str):if self.image_encoder is None:raise ValueError("If sending image queries as well, and they are not ""already encoded to base64 strings, you must specify ""the 'image_encoder' to be used.")encoded_image = self.image_encoder.encode_image_to_base64(image)message["content"].append({"type": "image_url","image_url": {"url": "data:image/jpeg;base64," + encoded_image,},})messages.append([message])return messages@staticmethoddef verify_messages(messages: List[Dict[str, Any]]):"""Method verifies if externally provided messages containing images are compatible with the format required by ibm-watsonx-ai."""n_images = 0for message in messages:if isinstance(message["content"], str):continuefor content in message["content"]:if isinstance(content, dict):if "image" in content["type"] and content["type"] != "image_url":raise ValueError(f"ibm-watsonx-ai only supports sending images as base64-encoded "f"strings, which should be given as 'image_url' in a message. "f"However, '{content['type']}' was given.")if content["type"] == "image_url":n_images += 1if n_images > 1:raise ValueError("ibm-watsonx-ai only supports sending one image per a list ""of messages.")def to_messages(self, instance: Union[Dict, List]) -> List[List[Dict[str, Any]]]:if isinstance(instance["source"], str) and "media" in instance:return self._create_messages_from_instance(instance)messages = super().to_messages(instance)self.verify_messages(messages)# This is done to be compatible with inputs containing# images as SDK allows sending only one image per message.return [messages]def _send_requests(self,dataset: Union[List[Dict[str, Any]], DatasetDict],return_logprobs: bool,return_meta_data: bool,) -> Union[List[str], List[Dict], List[TextGenerationInferenceOutput]]:params = self.to_dict([WMLChatParamsMixin], keep_empty=False)if return_logprobs:output_type = "logprobs"params["logprobs"] = Trueelse:output_type = "message"params["logprobs"] = Falsefinal_results = []for instance in dataset:messages = self.to_messages(instance)for message in messages:result = self._model.chat(messages=message,params=params,)final_results.append(self.get_return_object(result["choices"][0][output_type]["content"],result,instance["source"],return_meta_data,))return final_resultsdef get_return_object(self, predict_result, result, input_text, return_meta_data):if return_meta_data:return TextGenerationInferenceOutput(prediction=predict_result,input_tokens=result["usage"]["prompt_tokens"],output_tokens=len(predict_result)if isinstance(predict_result, list)else None,model_name=self.model_name or self.deployment_id,inference_type=self.label,stop_reason=result["choices"][0]["finish_reason"],input_text=input_text,)return predict_result@deprecation(version="2.0.0",msg=" Please use either 'WMLInferenceEngineGeneration' or 'WMLInferenceEngineChat'"" depending on your task.",)class WMLInferenceEngine(WMLInferenceEngineGeneration):def prepare_engine(self):super().prepare_engine()get_logger().warning("'WMLInferenceEngine' is deprecated")def get_images_without_text(instance):return extract_images(instance["source"], instance)def get_text_without_images(instance, image_token="<image>"):regex = r"<" + f"{constants.image_tag}" + r'\s+src=["\'](.*?)["\']\s*/?>'return re.sub(regex, image_token, instance["source"])class LMMSEvalBaseInferenceEngine(4 unmodified linesbatch_size: int = 1image_token = "<image>"_requirements_list = {"lmms_eval": "Install llms-eval package using 'pip install lmms-eval==0.2.4'",}def prepare_engine(self):if not self.lazy_load:40 unmodified linesdataset: Union[List[Dict[str, Any]], DatasetDict],return_meta_data: bool = False,) -> Union[List[str], List[TextGenerationInferenceOutput]]:if not self._is_loaded():self._prepare_engine()
12319 unmodified lines2324252627282992 unmodified lines122123124125126127128242 unmodified lines371372373374375376from abc import abstractmethodfrom typing import Any, Dict, List, Literal, Optional19 unmodified linesreturn json.loads(task_data) if isinstance(task_data, str) else task_dataclass LLMAsJudgeBase(BulkInstanceMetric):"""LLM-as-judge-base metric class for evaluating correctness of generated predictions.Attributes:92 unmodified linespassclass LLMAsJudge(LLMAsJudgeBase, ArtifactFetcherMixin):"""LLM-as-judge-based metric class for evaluating correctness of generated predictions.This class uses the source prompt given to the generator and the generator's predictions to evaluate242 unmodified linessuper().prepare()self.reduction_map = {"mean": [self.main_score]}self.score_prefix = f"{self.inference_model.get_engine_id()}_"def get_full_task_name(self):return self.task123419 unmodified lines2425262728293092 unmodified lines123124125126127128129242 unmodified lines372373374375376377378379380381382383384385386387388import refrom abc import abstractmethodfrom typing import Any, Dict, List, Literal, Optional19 unmodified linesreturn json.loads(task_data) if isinstance(task_data, str) else task_dataclass LLMAsJudgeBase(BulkInstanceMetric, ArtifactFetcherMixin):"""LLM-as-judge-base metric class for evaluating correctness of generated predictions.Attributes:92 unmodified linespassclass LLMAsJudge(LLMAsJudgeBase):"""LLM-as-judge-based metric class for evaluating correctness of generated predictions.This class uses the source prompt given to the generator and the generator's predictions to evaluate242 unmodified linessuper().prepare()self.reduction_map = {"mean": [self.main_score]}self.score_prefix = f"{self.inference_model.get_engine_id()}_"if not self.format:self.set_format_for_inference_engine()# if format is not directly set in constructor, choose according to the inference modeldef set_format_for_inference_engine(self):model_name = self.inference_model.get_engine_id()if re.search("llama.?3.*instruct", model_name):format_name = "formats.llama3_instruct"else:format_name = "formats.empty"self.format = self.get_artifact(format_name)def get_full_task_name(self):return self.task
12345678 unmodified lines1617181920212223242526272829"""This section describes unitxt loaders.Loaders: Generators of Unitxt Multistreams from existing date sources==============================================================Unitxt is all about readily preparing of any given data source for feeding into any given language model, and then,post-processing the model's output, preparing it for any given evaluator.8 unmodified linesstraightforward.Available Loaders Overview:- :ref:`LoadHF <unitxt.loaders.LoadHF>` - Loads data from HuggingFace Datasets.- :ref:`LoadCSV <unitxt.loaders.LoadCSV>` - Imports data from CSV (Comma-Separated Values) files.- :ref:`LoadFromKaggle <unitxt.loaders.LoadFromKaggle>` - Retrieves datasets from the Kaggle community site.- :ref:`LoadFromIBMCloud <unitxt.loaders.LoadFromIBMCloud>` - Fetches datasets hosted on IBM Cloud.- :ref:`LoadFromSklearn <unitxt.loaders.LoadFromSklearn>` - Loads datasets available through the sklearn library.- :ref:`MultipleSourceLoader <unitxt.loaders.MultipleSourceLoader>` - Combines data from multiple different sources.- :ref:`LoadFromDictionary <unitxt.loaders.LoadFromDictionary>` - Loads data from a user-defined Python dictionary.- :ref:`LoadFromHFSpace <unitxt.loaders.LoadFromHFSpace>` - Downloads and loads data from HuggingFace Spaces.12345678 unmodified lines1617181920212223242526272829"""This section describes unitxt loaders.Loaders: Generators of Unitxt Multistreams from existing date sources=====================================================================Unitxt is all about readily preparing of any given data source for feeding into any given language model, and then,post-processing the model's output, preparing it for any given evaluator.8 unmodified linesstraightforward.Available Loaders Overview:- :class:`LoadHF <unitxt.loaders.LoadHF>` - Loads data from HuggingFace Datasets.- :class:`LoadCSV <unitxt.loaders.LoadCSV>` - Imports data from CSV (Comma-Separated Values) files.- :class:`LoadFromKaggle <unitxt.loaders.LoadFromKaggle>` - Retrieves datasets from the Kaggle community site.- :class:`LoadFromIBMCloud <unitxt.loaders.LoadFromIBMCloud>` - Fetches datasets hosted on IBM Cloud.- :class:`LoadFromSklearn <unitxt.loaders.LoadFromSklearn>` - Loads datasets available through the sklearn library.- :class:`MultipleSourceLoader <unitxt.loaders.MultipleSourceLoader>` - Combines data from multiple different sources.- :class:`LoadFromDictionary <unitxt.loaders.LoadFromDictionary>` - Loads data from a user-defined Python dictionary.- :class:`LoadFromHFSpace <unitxt.loaders.LoadFromHFSpace>` - Downloads and loads data from HuggingFace Spaces.
17 unmodified lines18192021222326 unmodified lines50515253545517 unmodified linesfrom scipy.stats._warnings_errors import DegenerateDataWarningfrom .artifact import Artifactfrom .dataclass import (AbstractField,InternalField,26 unmodified lineswarnings.filterwarnings("ignore", category=DegenerateDataWarning)def abstract_factory():return {}17 unmodified lines1819202122232426 unmodified lines51525354555657585960616217 unmodified linesfrom scipy.stats._warnings_errors import DegenerateDataWarningfrom .artifact import Artifactfrom .collections import ListCollectionfrom .dataclass import (AbstractField,InternalField,26 unmodified lineswarnings.filterwarnings("ignore", category=DegenerateDataWarning)class MetricsList(ListCollection):def verify(self):for metric in self.items:assert isinstance(metric, Metric)def abstract_factory():return {}
1616 unmodified lines161716181619162016211622162322 unmodified lines1646164716481649165016511652165316541655165616571658165916601661166216631616 unmodified linescalc_confidence_intervals: booldef process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:from .metrics import Metric# Number of instances in input stream is assumed to be small. This is why# each metric consumes all of them and lays them in its main memory, and even generates22 unmodified linesif isinstance(metric_names, str):metric_names = [metric_names]# Each metric operator computes its score and then sets the main score, overwriting# the previous main score value (if any). So, we need to reverse the order of the listed metrics.# This will cause the first listed metric to run last, and the main score will be set# by the first listed metric (as desired).metric_names = list(reversed(metric_names))for metric_name in metric_names:metric = self.get_artifact(metric_name)assert isinstance(metric, Metric), f"Operator {metric_name} must be a Metric"if not self.calc_confidence_intervals:metric.disable_confidence_interval_calculation()multi_stream = MultiStream(1616 unmodified lines161716181619162016211622162322 unmodified lines16461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701616 unmodified linescalc_confidence_intervals: booldef process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:from .metrics import Metric, MetricsList# Number of instances in input stream is assumed to be small. This is why# each metric consumes all of them and lays them in its main memory, and even generates22 unmodified linesif isinstance(metric_names, str):metric_names = [metric_names]metrics_list = []for metric_name in metric_names:metric = self.get_artifact(metric_name)if isinstance(metric, MetricsList):metrics_list.extend(list(metric.items))elif isinstance(metric, Metric):metrics_list.append(metric)else:raise ValueError(f"Operator {metric_name} must be a Metric or MetricsList")# Each metric operator computes its score and then sets the main score, overwriting# the previous main score value (if any). So, we need to reverse the order of the listed metrics.# This will cause the first listed metric to run last, and the main score will be set# by the first listed metric (as desired).metrics_list = list(reversed(metrics_list))for metric in metrics_list:if not self.calc_confidence_intervals:metric.disable_confidence_interval_calculation()multi_stream = MultiStream(
160 unmodified lines161162163164165166167168160 unmodified linesconstants.metric_file = os.path.join(os.path.dirname(__file__), "metric.py")constants.local_catalog_path = os.path.join(os.path.dirname(__file__), "catalog")unitxt_pkg = importlib.util.find_spec("unitxt")constants.package_dir = os.path.dirname(unitxt_pkg.origin)if unitxt_pkg and unitxt_pkg.origin:constants.default_catalog_path = os.path.join(constants.package_dir, "catalog")else:constants.default_catalog_path = constants.local_catalog_path160 unmodified lines161162163164165166167168160 unmodified linesconstants.metric_file = os.path.join(os.path.dirname(__file__), "metric.py")constants.local_catalog_path = os.path.join(os.path.dirname(__file__), "catalog")unitxt_pkg = importlib.util.find_spec("unitxt")if unitxt_pkg and unitxt_pkg.origin:constants.package_dir = os.path.dirname(unitxt_pkg.origin)constants.default_catalog_path = os.path.join(constants.package_dir, "catalog")else:constants.default_catalog_path = constants.local_catalog_path
12345678911 unmodified lines212223242526278 unmodified lines305306307308309310311172 unmodified lines484485486487488489490491492493494495496497from typing import List, Optional, Unionfrom .artifact import fetch_artifactfrom .augmentors import (Augmentor,)from .card import TaskCardfrom .collections_operators import GetLengthfrom .dataclass import Field, InternalField, NonPositionalField, OptionalField11 unmodified linesfrom .system_prompts import EmptySystemPrompt, SystemPromptfrom .task import Taskfrom .templates import ApplyRandomTemplate, ApplySingleTemplate, Template, TemplatesListfrom .utils import LRUCacheconstants = get_constants()278 unmodified linesself.processing.steps.append(self.task)if self.augmentor is not None:if (self.card.task.augmentable_inputs is Noneor len(self.task.augmentable_inputs) == 0172 unmodified linessampler (Sampler, optional): The Sampler used to select the demonstrations when num_demos > 0.steps (List[StreamingOperator], optional): List of StreamingOperator objects to be used in the recipe.augmentor (Augmentor) : Augmentor to be used to pseudo randomly augment the source textinstruction_card_index (int, optional): Index of instruction card to be usedfor preparing the recipe.template_card_index (int, optional): Index of template card to be used forpreparing the recipe.Methods:prepare(): This overridden method is used for preparing the recipeby arranging all the steps, refiners, and renderers in a sequential manner.Raises:AssertionError: If both template and template_card_index are specified at the same time.123456711 unmodified lines19202122232425278 unmodified lines304305306307308309310172 unmodified lines483484485486487488489490491492493494from typing import List, Optional, Unionfrom .artifact import fetch_artifactfrom .augmentors import Augmentor, NullAugmentorfrom .card import TaskCardfrom .collections_operators import GetLengthfrom .dataclass import Field, InternalField, NonPositionalField, OptionalField11 unmodified linesfrom .system_prompts import EmptySystemPrompt, SystemPromptfrom .task import Taskfrom .templates import ApplyRandomTemplate, ApplySingleTemplate, Template, TemplatesListfrom .type_utils import isoftypefrom .utils import LRUCacheconstants = get_constants()278 unmodified linesself.processing.steps.append(self.task)if self.augmentor is not None and not isoftype(self.augmentor, NullAugmentor):if (self.card.task.augmentable_inputs is Noneor len(self.task.augmentable_inputs) == 0172 unmodified linessampler (Sampler, optional): The Sampler used to select the demonstrations when num_demos > 0.steps (List[StreamingOperator], optional): List of StreamingOperator objects to be used in the recipe.augmentor (Augmentor) : Augmentor to be used to pseudo randomly augment the source textinstruction_card_index (int, optional): Index of instruction card to be used for preparing the recipe.template_card_index (int, optional): Index of template card to be used for preparing the recipe.Methods:prepare(): This overridden method is used for preparing the recipeby arranging all the steps, refiners, and renderers in a sequential manner.Raises:AssertionError: If both template and template_card_index are specified at the same time.
4 unmodified lines5678910175 unmodified lines1861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152164 unmodified linesfrom .deprecation_utils import deprecationfrom .error_utils import Documentation, UnitxtError, UnitxtWarningfrom .logging_utils import get_loggerfrom .operator import InstanceOperatorfrom .operators import ArtifactFetcherMixinfrom .settings_utils import get_constants175 unmodified lines@classmethod@lru_cache(maxsize=None)def get_metric_prediction_type(cls, metric_id: str):metric = cls.get_artifact(metric_id)return metric.prediction_typedef check_metrics_type(self) -> None:prediction_type = self.prediction_typefor metric_id in self.metrics:metric_prediction_type = Task.get_metric_prediction_type(metric_id)if (prediction_type == metric_prediction_typeor prediction_type == Anyor metric_prediction_type == Anyor (get_origin(metric_prediction_type) is Unionand prediction_type in get_args(metric_prediction_type))):continueraise UnitxtError(f"The task's prediction type ({prediction_type}) and '{metric_id}' "f"metric's prediction type ({metric_prediction_type}) are different.",Documentation.ADDING_TASK,)def verify_defaults(self):if self.defaults:4 unmodified lines567891011175 unmodified lines1871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192204 unmodified linesfrom .deprecation_utils import deprecationfrom .error_utils import Documentation, UnitxtError, UnitxtWarningfrom .logging_utils import get_loggerfrom .metrics import MetricsListfrom .operator import InstanceOperatorfrom .operators import ArtifactFetcherMixinfrom .settings_utils import get_constants175 unmodified lines@classmethod@lru_cache(maxsize=None)def get_metrics_artifacts(cls, metric_id: str):metric = cls.get_artifact(metric_id)if isinstance(metric, MetricsList):return metric.itemsreturn [metric]def check_metrics_type(self) -> None:prediction_type = self.prediction_typefor metric_id in self.metrics:metric_artifacts_list = Task.get_metrics_artifacts(metric_id)for metric_artifact in metric_artifacts_list:metric_prediction_type = metric_artifact.prediction_typeif (prediction_type == metric_prediction_typeor prediction_type == Anyor metric_prediction_type == Anyor (get_origin(metric_prediction_type) is Unionand prediction_type in get_args(metric_prediction_type))):continueraise UnitxtError(f"The task's prediction type ({prediction_type}) and '{metric_id}' "f"metric's prediction type ({metric_prediction_type}) are different.",Documentation.ADDING_TASK,)def verify_defaults(self):if self.defaults:
136 unmodified lines137138139140141142143136 unmodified linesif len(d) == 0:return ["{}"]for key, val in d.items():res.append(key + ": ")yaml_for_val = construct_dict_as_yaml_lines(val, indent_delta=indent_delta)assert len(yaml_for_val) > 0if is_simple(val):136 unmodified lines137138139140141142143144136 unmodified linesif len(d) == 0:return ["{}"]for key, val in d.items():printable_key = f'"{key}"' if (" " in key) or (key == "") else keyres.append(printable_key + ": ")yaml_for_val = construct_dict_as_yaml_lines(val, indent_delta=indent_delta)assert len(yaml_for_val) > 0if is_simple(val):
1version = "1.15.6"1version = "1.15.7"
augmentors.py+3-6
image_operators.py+12
inference.py+1381-426
llm_as_judge.py+14-2
loaders.py+9-9
metrics.py+7
operators.py+15-8
settings_utils.py+1-1
standard.py+6-9
task.py+23-19
text_utils.py+2-1
version.py+1-1