libs/partners/huggingface/langchain_huggingface/llms/huggingface_pipeline.py PYTHON 421 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 Any89from langchain_core.callbacks import CallbackManagerForLLMRun10from langchain_core.language_models.llms import BaseLLM11from langchain_core.outputs import Generation, GenerationChunk, LLMResult12from pydantic import ConfigDict, model_validator13from typing_extensions import Self1415from langchain_huggingface._version import __version__16from langchain_huggingface.utils.import_utils import (17    IMPORT_ERROR,18    is_openvino_available,19    is_optimum_intel_available,20    is_optimum_intel_version,21)2223DEFAULT_MODEL_ID = "gpt2"24DEFAULT_TASK = "text-generation"25VALID_TASKS = (26    "text2text-generation",27    "text-generation",28    "image-text-to-text",29    "summarization",30    "translation",31)32DEFAULT_BATCH_SIZE = 433_MIN_OPTIMUM_VERSION = "1.21"343536logger = logging.getLogger(__name__)373839class HuggingFacePipeline(BaseLLM):40    """HuggingFace Pipeline API.4142    To use, you should have the `transformers` python package installed.4344    Only supports `text-generation`, `text2text-generation`, `image-text-to-text`,45    `summarization` and `translation`  for now.4647    Example using from_model_id:48        ```python49        from langchain_huggingface import HuggingFacePipeline5051        hf = HuggingFacePipeline.from_model_id(52            model_id="gpt2",53            task="text-generation",54            pipeline_kwargs={"max_new_tokens": 10},55        )56        ```5758    Example passing pipeline in directly:59        ```python60        from langchain_huggingface import HuggingFacePipeline61        from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline6263        model_id = "gpt2"64        tokenizer = AutoTokenizer.from_pretrained(model_id)65        model = AutoModelForCausalLM.from_pretrained(model_id)66        pipe = pipeline(67            "text-generation",68            model=model,69            tokenizer=tokenizer,70            max_new_tokens=10,71        )72        hf = HuggingFacePipeline(pipeline=pipe)73        ```74    """7576    pipeline: Any = None7778    model_id: str | None = None79    """The model name. If not set explicitly by the user,80    it will be inferred from the provided pipeline (if available).81    If neither is provided, the DEFAULT_MODEL_ID will be used."""8283    model_kwargs: dict | None = None84    """Keyword arguments passed to the model."""8586    pipeline_kwargs: dict | None = None87    """Keyword arguments passed to the pipeline."""8889    batch_size: int = DEFAULT_BATCH_SIZE90    """Batch size to use when passing multiple documents to generate."""9192    model_config = ConfigDict(93        extra="forbid",94    )9596    @model_validator(mode="after")97    def _set_huggingface_version(self) -> Self:98        """Set package version in metadata."""99        self._add_version("langchain-huggingface", __version__)100        return self101102    @model_validator(mode="before")103    @classmethod104    def pre_init_validator(cls, values: dict[str, Any]) -> dict[str, Any]:105        """Ensure model_id is set either by pipeline or user input."""106        if "model_id" not in values:107            if values.get("pipeline"):108                values["model_id"] = values["pipeline"].model.name_or_path109            else:110                values["model_id"] = DEFAULT_MODEL_ID111        return values112113    @classmethod114    def from_model_id(115        cls,116        model_id: str,117        task: str,118        backend: str = "default",119        device: int | None = None,120        device_map: str | None = None,121        model_kwargs: dict | None = None,122        pipeline_kwargs: dict | None = None,123        batch_size: int = DEFAULT_BATCH_SIZE,124        **kwargs: Any,125    ) -> HuggingFacePipeline:126        """Construct the pipeline object from model_id and task."""127        try:128            from transformers import (  # type: ignore[import]129                AutoModelForCausalLM,130                AutoModelForSeq2SeqLM,131                AutoTokenizer,132            )133            from transformers import pipeline as hf_pipeline  # type: ignore[import]134135        except ImportError as e:136            msg = (137                "Could not import transformers python package. "138                "Please install it with `pip install transformers`."139            )140            raise ValueError(msg) from e141142        _model_kwargs = model_kwargs.copy() if model_kwargs else {}143        if device_map is not None:144            if device is not None:145                msg = (146                    "Both `device` and `device_map` are specified. "147                    "`device` will override `device_map`. "148                    "You will most likely encounter unexpected behavior."149                    "Please remove `device` and keep "150                    "`device_map`."151                )152                raise ValueError(msg)153154            if "device_map" in _model_kwargs:155                msg = "`device_map` is already specified in `model_kwargs`."156                raise ValueError(msg)157158            _model_kwargs["device_map"] = device_map159        tokenizer = AutoTokenizer.from_pretrained(model_id, **_model_kwargs)160161        if backend == "ipex":162            msg = (163                "`backend='ipex'` is no longer supported; the default "164                "`transformers` backend will be used instead. Intel GPU acceleration "165                "is natively supported in PyTorch 2.5 and later."166            )167            warnings.warn(msg, UserWarning, stacklevel=2)168            backend = "default"169170        if backend == "openvino":171            if task not in VALID_TASKS:172                msg = (173                    f"Got invalid task {task}, "174                    f"currently only {VALID_TASKS} are supported"175                )176                raise ValueError(msg)177178            err_msg = f"Backend: {backend} {IMPORT_ERROR.format(f'optimum[{backend}]')}"179            if not is_optimum_intel_available():180                raise ImportError(err_msg)181182            if is_optimum_intel_version("<", _MIN_OPTIMUM_VERSION):183                msg = (184                    f"Backend: {backend} requires optimum-intel>="185                    f"{_MIN_OPTIMUM_VERSION}. You can install it with pip: "186                    "`pip install --upgrade --upgrade-strategy eager "187                    f"`optimum[{backend}]`."188                )189                raise ImportError(msg)190191            if not is_openvino_available():192                raise ImportError(err_msg)193194            from optimum.intel import (  # type: ignore[import]195                OVModelForCausalLM,196                OVModelForSeq2SeqLM,197            )198199            model_cls = (200                OVModelForCausalLM if task == "text-generation" else OVModelForSeq2SeqLM201            )202203        else:204            model_cls = (205                AutoModelForCausalLM206                if task == "text-generation"207                else AutoModelForSeq2SeqLM208            )209210        model = model_cls.from_pretrained(model_id, **_model_kwargs)211212        if tokenizer.pad_token is None:213            if model.config.pad_token_id is not None:214                tokenizer.pad_token_id = model.config.pad_token_id215            elif model.config.eos_token_id is not None and isinstance(216                model.config.eos_token_id, int217            ):218                tokenizer.pad_token_id = model.config.eos_token_id219            elif tokenizer.eos_token_id is not None:220                tokenizer.pad_token_id = tokenizer.eos_token_id221            else:222                tokenizer.add_special_tokens({"pad_token": "[PAD]"})223224        if (225            (226                getattr(model, "is_loaded_in_4bit", False)227                or getattr(model, "is_loaded_in_8bit", False)228            )229            and device is not None230            and backend == "default"231        ):232            logger.warning(233                f"Setting the `device` argument to None from {device} to avoid "234                "the error caused by attempting to move the model that was already "235                "loaded on the GPU using the Accelerate module to the same or "236                "another device."237            )238            device = None239240        if (241            device is not None242            and importlib.util.find_spec("torch") is not None243            and backend == "default"244        ):245            import torch246247            # `torch.accelerator` (added in PyTorch 2.6) is device-agnostic and248            # detects CUDA, XPU, and other accelerator backends.249            if hasattr(torch, "accelerator"):250                accelerator_device_count = torch.accelerator.device_count()251            else:252                accelerator_device_count = torch.cuda.device_count()253            if device < -1 or (device >= accelerator_device_count):254                msg = (255                    f"Got device=={device}, "256                    f"device is required to be within [-1, {accelerator_device_count})"257                )258                raise ValueError(msg)259            if device_map is not None and device < 0:260                device = None261            if device is not None and device < 0 and accelerator_device_count > 0:262                logger.warning(263                    "Device has %d accelerator(s) available. "264                    "Provide device={deviceId} to `from_model_id` to use available"265                    "accelerators for execution. deviceId is -1 (default) for CPU "266                    "and can be a positive integer associated with the accelerator "267                    "device id.",268                    accelerator_device_count,269                )270        if device is not None and device_map is not None and backend == "openvino":271            logger.warning("Please set device for OpenVINO through: `model_kwargs`")272        if "trust_remote_code" in _model_kwargs:273            _model_kwargs = {274                k: v for k, v in _model_kwargs.items() if k != "trust_remote_code"275            }276        _pipeline_kwargs = pipeline_kwargs or {}277        pipeline = hf_pipeline(  # type: ignore[call-overload]278            task=task,279            model=model,280            tokenizer=tokenizer,281            device=device,282            batch_size=batch_size,283            model_kwargs=_model_kwargs,284            **_pipeline_kwargs,285        )286        if pipeline.task not in VALID_TASKS:287            msg = (288                f"Got invalid task {pipeline.task}, "289                f"currently only {VALID_TASKS} are supported"290            )291            raise ValueError(msg)292        return cls(293            pipeline=pipeline,294            model_id=model_id,295            model_kwargs=_model_kwargs,296            pipeline_kwargs=_pipeline_kwargs,297            batch_size=batch_size,298            **kwargs,299        )300301    @property302    def _identifying_params(self) -> Mapping[str, Any]:303        """Get the identifying parameters."""304        return {305            "model_id": self.model_id,306            "model_kwargs": self.model_kwargs,307            "pipeline_kwargs": self.pipeline_kwargs,308        }309310    @property311    def _llm_type(self) -> str:312        return "huggingface_pipeline"313314    def _generate(315        self,316        prompts: list[str],317        stop: list[str] | None = None,318        run_manager: CallbackManagerForLLMRun | None = None,319        **kwargs: Any,320    ) -> LLMResult:321        # List to hold all results322        text_generations: list[str] = []323        pipeline_kwargs = kwargs.get("pipeline_kwargs", {})324        skip_prompt = kwargs.get("skip_prompt", False)325326        for i in range(0, len(prompts), self.batch_size):327            batch_prompts = prompts[i : i + self.batch_size]328329            # Process batch of prompts330            responses = self.pipeline(331                batch_prompts,332                **pipeline_kwargs,333            )334335            # Process each response in the batch336            for j, response in enumerate(responses):337                if isinstance(response, list):338                    # if model returns multiple generations, pick the top one339                    response = response[0]340341                if (342                    self.pipeline.task == "text-generation"343                    or self.pipeline.task == "text2text-generation"344                    or self.pipeline.task == "image-text-to-text"345                ):346                    text = response["generated_text"]347                elif self.pipeline.task == "summarization":348                    text = response["summary_text"]349                elif self.pipeline.task in "translation":350                    text = response["translation_text"]351                else:352                    msg = (353                        f"Got invalid task {self.pipeline.task}, "354                        f"currently only {VALID_TASKS} are supported"355                    )356                    raise ValueError(msg)357                if skip_prompt:358                    text = text[len(batch_prompts[j]) :]359                # Append the processed text to results360                text_generations.append(text)361362        return LLMResult(363            generations=[[Generation(text=text)] for text in text_generations]364        )365366    def _stream(367        self,368        prompt: str,369        stop: list[str] | None = None,370        run_manager: CallbackManagerForLLMRun | None = None,371        **kwargs: Any,372    ) -> Iterator[GenerationChunk]:373        from threading import Thread374375        import torch376        from transformers import (377            StoppingCriteria,378            StoppingCriteriaList,379            TextIteratorStreamer,380        )381382        pipeline_kwargs = kwargs.get("pipeline_kwargs", {})383        skip_prompt = kwargs.get("skip_prompt", True)384385        if stop is not None:386            stop = self.pipeline.tokenizer.convert_tokens_to_ids(stop)387        stopping_ids_list = stop or []388389        class StopOnTokens(StoppingCriteria):390            def __call__(391                self,392                input_ids: torch.LongTensor,393                scores: torch.FloatTensor,394                **kwargs: Any,395            ) -> bool:396                return any(input_ids[0][-1] == stop_id for stop_id in stopping_ids_list)397398        stopping_criteria = StoppingCriteriaList([StopOnTokens()])399400        streamer = TextIteratorStreamer(401            self.pipeline.tokenizer,402            timeout=60.0,403            skip_prompt=skip_prompt,404            skip_special_tokens=True,405        )406        generation_kwargs = dict(407            text_inputs=prompt,408            streamer=streamer,409            stopping_criteria=stopping_criteria,410            **pipeline_kwargs,411        )412        t1 = Thread(target=self.pipeline, kwargs=generation_kwargs)413        t1.start()414415        for char in streamer:416            chunk = GenerationChunk(text=char)417            if run_manager:418                run_manager.on_llm_new_token(chunk.text, chunk=chunk)419420            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