libs/partners/huggingface/langchain_huggingface/llms/huggingface_pipeline.py PYTHON 420 lines View on github.com → Search inside
1from __future__ import annotations  # type: ignore[import-not-found]23import importlib.util4import logging5import warnings6from collections.abc import Iterator, Mapping7from typing import Any, Self89from langchain_core.callbacks import CallbackManagerForLLMRun10from langchain_core.language_models.llms import BaseLLM11from langchain_core.outputs import Generation, GenerationChunk, LLMResult12from pydantic import ConfigDict, model_validator1314from langchain_huggingface._version import __version__15from langchain_huggingface.utils.import_utils import (16    IMPORT_ERROR,17    is_openvino_available,18    is_optimum_intel_available,19    is_optimum_intel_version,20)2122DEFAULT_MODEL_ID = "gpt2"23DEFAULT_TASK = "text-generation"24VALID_TASKS = (25    "text2text-generation",26    "text-generation",27    "image-text-to-text",28    "summarization",29    "translation",30)31DEFAULT_BATCH_SIZE = 432_MIN_OPTIMUM_VERSION = "1.21"333435logger = logging.getLogger(__name__)363738class HuggingFacePipeline(BaseLLM):39    """HuggingFace Pipeline API.4041    To use, you should have the `transformers` python package installed.4243    Only supports `text-generation`, `text2text-generation`, `image-text-to-text`,44    `summarization` and `translation`  for now.4546    Example using from_model_id:47        ```python48        from langchain_huggingface import HuggingFacePipeline4950        hf = HuggingFacePipeline.from_model_id(51            model_id="gpt2",52            task="text-generation",53            pipeline_kwargs={"max_new_tokens": 10},54        )55        ```5657    Example passing pipeline in directly:58        ```python59        from langchain_huggingface import HuggingFacePipeline60        from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline6162        model_id = "gpt2"63        tokenizer = AutoTokenizer.from_pretrained(model_id)64        model = AutoModelForCausalLM.from_pretrained(model_id)65        pipe = pipeline(66            "text-generation",67            model=model,68            tokenizer=tokenizer,69            max_new_tokens=10,70        )71        hf = HuggingFacePipeline(pipeline=pipe)72        ```73    """7475    pipeline: Any = None7677    model_id: str | None = None78    """The model name. If not set explicitly by the user,79    it will be inferred from the provided pipeline (if available).80    If neither is provided, the DEFAULT_MODEL_ID will be used."""8182    model_kwargs: dict | None = None83    """Keyword arguments passed to the model."""8485    pipeline_kwargs: dict | None = None86    """Keyword arguments passed to the pipeline."""8788    batch_size: int = DEFAULT_BATCH_SIZE89    """Batch size to use when passing multiple documents to generate."""9091    model_config = ConfigDict(92        extra="forbid",93    )9495    @model_validator(mode="after")96    def _set_huggingface_version(self) -> Self:97        """Set package version in metadata."""98        self._add_version("langchain-huggingface", __version__)99        return self100101    @model_validator(mode="before")102    @classmethod103    def pre_init_validator(cls, values: dict[str, Any]) -> dict[str, Any]:104        """Ensure model_id is set either by pipeline or user input."""105        if "model_id" not in values:106            if values.get("pipeline"):107                values["model_id"] = values["pipeline"].model.name_or_path108            else:109                values["model_id"] = DEFAULT_MODEL_ID110        return values111112    @classmethod113    def from_model_id(114        cls,115        model_id: str,116        task: str,117        backend: str = "default",118        device: int | None = None,119        device_map: str | None = None,120        model_kwargs: dict | None = None,121        pipeline_kwargs: dict | None = None,122        batch_size: int = DEFAULT_BATCH_SIZE,123        **kwargs: Any,124    ) -> HuggingFacePipeline:125        """Construct the pipeline object from model_id and task."""126        try:127            from transformers import (  # type: ignore[import]128                AutoModelForCausalLM,129                AutoModelForSeq2SeqLM,130                AutoTokenizer,131            )132            from transformers import pipeline as hf_pipeline  # type: ignore[import]133134        except ImportError as e:135            msg = (136                "Could not import transformers python package. "137                "Please install it with `pip install transformers`."138            )139            raise ValueError(msg) from e140141        _model_kwargs = model_kwargs.copy() if model_kwargs else {}142        if device_map is not None:143            if device is not None:144                msg = (145                    "Both `device` and `device_map` are specified. "146                    "`device` will override `device_map`. "147                    "You will most likely encounter unexpected behavior."148                    "Please remove `device` and keep "149                    "`device_map`."150                )151                raise ValueError(msg)152153            if "device_map" in _model_kwargs:154                msg = "`device_map` is already specified in `model_kwargs`."155                raise ValueError(msg)156157            _model_kwargs["device_map"] = device_map158        tokenizer = AutoTokenizer.from_pretrained(model_id, **_model_kwargs)159160        if backend == "ipex":161            msg = (162                "`backend='ipex'` is no longer supported; the default "163                "`transformers` backend will be used instead. Intel GPU acceleration "164                "is natively supported in PyTorch 2.5 and later."165            )166            warnings.warn(msg, UserWarning, stacklevel=2)167            backend = "default"168169        if backend == "openvino":170            if task not in VALID_TASKS:171                msg = (172                    f"Got invalid task {task}, "173                    f"currently only {VALID_TASKS} are supported"174                )175                raise ValueError(msg)176177            err_msg = f"Backend: {backend} {IMPORT_ERROR.format(f'optimum[{backend}]')}"178            if not is_optimum_intel_available():179                raise ImportError(err_msg)180181            if is_optimum_intel_version("<", _MIN_OPTIMUM_VERSION):182                msg = (183                    f"Backend: {backend} requires optimum-intel>="184                    f"{_MIN_OPTIMUM_VERSION}. You can install it with pip: "185                    "`pip install --upgrade --upgrade-strategy eager "186                    f"`optimum[{backend}]`."187                )188                raise ImportError(msg)189190            if not is_openvino_available():191                raise ImportError(err_msg)192193            from optimum.intel import (  # type: ignore[import]194                OVModelForCausalLM,195                OVModelForSeq2SeqLM,196            )197198            model_cls = (199                OVModelForCausalLM if task == "text-generation" else OVModelForSeq2SeqLM200            )201202        else:203            model_cls = (204                AutoModelForCausalLM205                if task == "text-generation"206                else AutoModelForSeq2SeqLM207            )208209        model = model_cls.from_pretrained(model_id, **_model_kwargs)210211        if tokenizer.pad_token is None:212            if model.config.pad_token_id is not None:213                tokenizer.pad_token_id = model.config.pad_token_id214            elif model.config.eos_token_id is not None and isinstance(215                model.config.eos_token_id, int216            ):217                tokenizer.pad_token_id = model.config.eos_token_id218            elif tokenizer.eos_token_id is not None:219                tokenizer.pad_token_id = tokenizer.eos_token_id220            else:221                tokenizer.add_special_tokens({"pad_token": "[PAD]"})222223        if (224            (225                getattr(model, "is_loaded_in_4bit", False)226                or getattr(model, "is_loaded_in_8bit", False)227            )228            and device is not None229            and backend == "default"230        ):231            logger.warning(232                f"Setting the `device` argument to None from {device} to avoid "233                "the error caused by attempting to move the model that was already "234                "loaded on the GPU using the Accelerate module to the same or "235                "another device."236            )237            device = None238239        if (240            device is not None241            and importlib.util.find_spec("torch") is not None242            and backend == "default"243        ):244            import torch245246            # `torch.accelerator` (added in PyTorch 2.6) is device-agnostic and247            # detects CUDA, XPU, and other accelerator backends.248            if hasattr(torch, "accelerator"):249                accelerator_device_count = torch.accelerator.device_count()250            else:251                accelerator_device_count = torch.cuda.device_count()252            if device < -1 or (device >= accelerator_device_count):253                msg = (254                    f"Got device=={device}, "255                    f"device is required to be within [-1, {accelerator_device_count})"256                )257                raise ValueError(msg)258            if device_map is not None and device < 0:259                device = None260            if device is not None and device < 0 and accelerator_device_count > 0:261                logger.warning(262                    "Device has %d accelerator(s) available. "263                    "Provide device={deviceId} to `from_model_id` to use available"264                    "accelerators for execution. deviceId is -1 (default) for CPU "265                    "and can be a positive integer associated with the accelerator "266                    "device id.",267                    accelerator_device_count,268                )269        if device is not None and device_map is not None and backend == "openvino":270            logger.warning("Please set device for OpenVINO through: `model_kwargs`")271        if "trust_remote_code" in _model_kwargs:272            _model_kwargs = {273                k: v for k, v in _model_kwargs.items() if k != "trust_remote_code"274            }275        _pipeline_kwargs = pipeline_kwargs or {}276        pipeline = hf_pipeline(  # type: ignore[call-overload]277            task=task,278            model=model,279            tokenizer=tokenizer,280            device=device,281            batch_size=batch_size,282            model_kwargs=_model_kwargs,283            **_pipeline_kwargs,284        )285        if pipeline.task not in VALID_TASKS:286            msg = (287                f"Got invalid task {pipeline.task}, "288                f"currently only {VALID_TASKS} are supported"289            )290            raise ValueError(msg)291        return cls(292            pipeline=pipeline,293            model_id=model_id,294            model_kwargs=_model_kwargs,295            pipeline_kwargs=_pipeline_kwargs,296            batch_size=batch_size,297            **kwargs,298        )299300    @property301    def _identifying_params(self) -> Mapping[str, Any]:302        """Get the identifying parameters."""303        return {304            "model_id": self.model_id,305            "model_kwargs": self.model_kwargs,306            "pipeline_kwargs": self.pipeline_kwargs,307        }308309    @property310    def _llm_type(self) -> str:311        return "huggingface_pipeline"312313    def _generate(314        self,315        prompts: list[str],316        stop: list[str] | None = None,317        run_manager: CallbackManagerForLLMRun | None = None,318        **kwargs: Any,319    ) -> LLMResult:320        # List to hold all results321        text_generations: list[str] = []322        pipeline_kwargs = kwargs.get("pipeline_kwargs", {})323        skip_prompt = kwargs.get("skip_prompt", False)324325        for i in range(0, len(prompts), self.batch_size):326            batch_prompts = prompts[i : i + self.batch_size]327328            # Process batch of prompts329            responses = self.pipeline(330                batch_prompts,331                **pipeline_kwargs,332            )333334            # Process each response in the batch335            for j, response in enumerate(responses):336                if isinstance(response, list):337                    # if model returns multiple generations, pick the top one338                    response = response[0]339340                if (341                    self.pipeline.task == "text-generation"342                    or self.pipeline.task == "text2text-generation"343                    or self.pipeline.task == "image-text-to-text"344                ):345                    text = response["generated_text"]346                elif self.pipeline.task == "summarization":347                    text = response["summary_text"]348                elif self.pipeline.task in "translation":349                    text = response["translation_text"]350                else:351                    msg = (352                        f"Got invalid task {self.pipeline.task}, "353                        f"currently only {VALID_TASKS} are supported"354                    )355                    raise ValueError(msg)356                if skip_prompt:357                    text = text[len(batch_prompts[j]) :]358                # Append the processed text to results359                text_generations.append(text)360361        return LLMResult(362            generations=[[Generation(text=text)] for text in text_generations]363        )364365    def _stream(366        self,367        prompt: str,368        stop: list[str] | None = None,369        run_manager: CallbackManagerForLLMRun | None = None,370        **kwargs: Any,371    ) -> Iterator[GenerationChunk]:372        from threading import Thread373374        import torch375        from transformers import (376            StoppingCriteria,377            StoppingCriteriaList,378            TextIteratorStreamer,379        )380381        pipeline_kwargs = kwargs.get("pipeline_kwargs", {})382        skip_prompt = kwargs.get("skip_prompt", True)383384        if stop is not None:385            stop = self.pipeline.tokenizer.convert_tokens_to_ids(stop)386        stopping_ids_list = stop or []387388        class StopOnTokens(StoppingCriteria):389            def __call__(390                self,391                input_ids: torch.LongTensor,392                scores: torch.FloatTensor,393                **kwargs: Any,394            ) -> bool:395                return any(input_ids[0][-1] == stop_id for stop_id in stopping_ids_list)396397        stopping_criteria = StoppingCriteriaList([StopOnTokens()])398399        streamer = TextIteratorStreamer(400            self.pipeline.tokenizer,401            timeout=60.0,402            skip_prompt=skip_prompt,403            skip_special_tokens=True,404        )405        generation_kwargs = dict(406            text_inputs=prompt,407            streamer=streamer,408            stopping_criteria=stopping_criteria,409            **pipeline_kwargs,410        )411        t1 = Thread(target=self.pipeline, kwargs=generation_kwargs)412        t1.start()413414        for char in streamer:415            chunk = GenerationChunk(text=char)416            if run_manager:417                run_manager.on_llm_new_token(chunk.text, chunk=chunk)418419            yield chunk

Findings

✓ No findings reported for this file.

Get this view in your editor

Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.

Generated by searchcode.com · powered by code_get_file + code_get_findings