code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def from_dict(cls, video_processor_dict: Dict[str, Any], **kwargs): """ Instantiates a type of [`~video_processing_utils.VideoProcessorBase`] from a Python dictionary of parameters. Args: video_processor_dict (`Dict[str, Any]`): Dictionary that will be used to instan...
Instantiates a type of [`~video_processing_utils.VideoProcessorBase`] from a Python dictionary of parameters. Args: video_processor_dict (`Dict[str, Any]`): Dictionary that will be used to instantiate the video processor object. Such a dictionary can be retr...
from_dict
python
huggingface/transformers
src/transformers/video_processing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/video_processing_utils.py
Apache-2.0
def to_dict(self) -> Dict[str, Any]: """ Serializes this instance to a Python dictionary. Returns: `Dict[str, Any]`: Dictionary of all the attributes that make up this video processor instance. """ output = copy.deepcopy(self.__dict__) output["video_processor...
Serializes this instance to a Python dictionary. Returns: `Dict[str, Any]`: Dictionary of all the attributes that make up this video processor instance.
to_dict
python
huggingface/transformers
src/transformers/video_processing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/video_processing_utils.py
Apache-2.0
def from_json_file(cls, json_file: Union[str, os.PathLike]): """ Instantiates a video processor of type [`~video_processing_utils.VideoProcessorBase`] from the path to a JSON file of parameters. Args: json_file (`str` or `os.PathLike`): Path to the JSON file ...
Instantiates a video processor of type [`~video_processing_utils.VideoProcessorBase`] from the path to a JSON file of parameters. Args: json_file (`str` or `os.PathLike`): Path to the JSON file containing the parameters. Returns: A video process...
from_json_file
python
huggingface/transformers
src/transformers/video_processing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/video_processing_utils.py
Apache-2.0
def register_for_auto_class(cls, auto_class="AutoVideoProcessor"): """ Register this class with a given auto class. This should only be used for custom video processors as the ones in the library are already mapped with `AutoVideoProcessor `. <Tip warning={true}> This API is ex...
Register this class with a given auto class. This should only be used for custom video processors as the ones in the library are already mapped with `AutoVideoProcessor `. <Tip warning={true}> This API is experimental and may have some slight breaking changes in the next releases. ...
register_for_auto_class
python
huggingface/transformers
src/transformers/video_processing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/video_processing_utils.py
Apache-2.0
def fetch_videos(self, video_url_or_urls: Union[str, List[str]]): """ Convert a single or a list of urls into the corresponding `np.array` objects. If a single url is passed, the return value will be a single object. If a list is passed a list of objects is returned. """ ...
Convert a single or a list of urls into the corresponding `np.array` objects. If a single url is passed, the return value will be a single object. If a list is passed a list of objects is returned.
fetch_videos
python
huggingface/transformers
src/transformers/video_processing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/video_processing_utils.py
Apache-2.0
def convert_pil_frames_to_video(videos: List[VideoInput]) -> List[Union["np.ndarray", "torch.Tensor"]]: """ Given a batch of videos, converts each video to a 4D array. If video is already in array type, it is simply returned. We assume that all inputs in the list are in the same format, based on the type of...
Given a batch of videos, converts each video to a 4D array. If video is already in array type, it is simply returned. We assume that all inputs in the list are in the same format, based on the type of the first element. Args: videos (`VideoInput`): Video inputs to turn into a list of v...
convert_pil_frames_to_video
python
huggingface/transformers
src/transformers/video_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/video_utils.py
Apache-2.0
def make_batched_videos(videos) -> List[Union["np.ndarray", "torch.Tensor"]]: """ Ensure that the input is a list of videos. If the input is a single video, it is converted to a list of length 1. If the input is a batch of videos, it is converted to a list of 4D video arrays. Videos passed as list `PIL.Imag...
Ensure that the input is a list of videos. If the input is a single video, it is converted to a list of length 1. If the input is a batch of videos, it is converted to a list of 4D video arrays. Videos passed as list `PIL.Image` frames are converted to 4D arrays. We assume that all inputs in the list ...
make_batched_videos
python
huggingface/transformers
src/transformers/video_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/video_utils.py
Apache-2.0
def get_video_size(video: np.ndarray, channel_dim: ChannelDimension = None) -> Tuple[int, int]: """ Returns the (height, width) dimensions of the video. Args: video (`np.ndarray`): The video to get the dimensions of. channel_dim (`ChannelDimension`, *optional*): Whic...
Returns the (height, width) dimensions of the video. Args: video (`np.ndarray`): The video to get the dimensions of. channel_dim (`ChannelDimension`, *optional*): Which dimension the channel dimension is in. If `None`, will infer the channel dimension from the video. ...
get_video_size
python
huggingface/transformers
src/transformers/video_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/video_utils.py
Apache-2.0
def get_uniform_frame_indices(total_num_frames: int, num_frames: Optional[int] = None): """ Creates a numpy array for uniform sampling of `num_frame` frames from `total_num_frames` when loading a video. Args: total_num_frames (`int`): Total number of frames that a video has. ...
Creates a numpy array for uniform sampling of `num_frame` frames from `total_num_frames` when loading a video. Args: total_num_frames (`int`): Total number of frames that a video has. num_frames (`int`, *optional*): Number of frames to sample uniformly. If not speci...
get_uniform_frame_indices
python
huggingface/transformers
src/transformers/video_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/video_utils.py
Apache-2.0
def default_sample_indices_fn(metadata: VideoMetadata, num_frames=None, fps=None, **kwargs): """ A default sampling function that replicates the logic used in get_uniform_frame_indices, while optionally handling `fps` if `num_frames` is not provided. Args: metadata (`VideoMetadata`): ...
A default sampling function that replicates the logic used in get_uniform_frame_indices, while optionally handling `fps` if `num_frames` is not provided. Args: metadata (`VideoMetadata`): `VideoMetadata` object containing metadata about the video, such as "total_num_frames" or "fps". ...
default_sample_indices_fn
python
huggingface/transformers
src/transformers/video_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/video_utils.py
Apache-2.0
def read_video_opencv( video_path: str, sample_indices_fn: Callable, **kwargs, ): """ Decode a video using the OpenCV backend. Args: video_path (`str`): Path to the video file. sample_indices_fn (`Callable`): A callable function that will return indices a...
Decode a video using the OpenCV backend. Args: video_path (`str`): Path to the video file. sample_indices_fn (`Callable`): A callable function that will return indices at which the video should be sampled. If the video has to be loaded using by a different s...
read_video_opencv
python
huggingface/transformers
src/transformers/video_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/video_utils.py
Apache-2.0
def read_video_decord( video_path: str, sample_indices_fn: Optional[Callable] = None, **kwargs, ): """ Decode a video using the Decord backend. Args: video_path (`str`): Path to the video file. sample_indices_fn (`Callable`, *optional*): A callable functi...
Decode a video using the Decord backend. Args: video_path (`str`): Path to the video file. sample_indices_fn (`Callable`, *optional*): A callable function that will return indices at which the video should be sampled. If the video has to be loaded using by a...
read_video_decord
python
huggingface/transformers
src/transformers/video_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/video_utils.py
Apache-2.0
def read_video_pyav( video_path: str, sample_indices_fn: Callable, **kwargs, ): """ Decode the video with PyAV decoder. Args: video_path (`str`): Path to the video file. sample_indices_fn (`Callable`, *optional*): A callable function that will return indi...
Decode the video with PyAV decoder. Args: video_path (`str`): Path to the video file. sample_indices_fn (`Callable`, *optional*): A callable function that will return indices at which the video should be sampled. If the video has to be loaded using by a diff...
read_video_pyav
python
huggingface/transformers
src/transformers/video_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/video_utils.py
Apache-2.0
def read_video_torchvision( video_path: str, sample_indices_fn: Callable, **kwargs, ): """ Decode the video with torchvision decoder. Args: video_path (`str`): Path to the video file. sample_indices_fn (`Callable`, *optional*): A callable function that wi...
Decode the video with torchvision decoder. Args: video_path (`str`): Path to the video file. sample_indices_fn (`Callable`, *optional*): A callable function that will return indices at which the video should be sampled. If the video has to be loaded using by...
read_video_torchvision
python
huggingface/transformers
src/transformers/video_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/video_utils.py
Apache-2.0
def load_video( video: Union[str, "VideoInput"], num_frames: Optional[int] = None, fps: Optional[int] = None, backend: str = "pyav", sample_indices_fn: Optional[Callable] = None, **kwargs, ) -> np.array: """ Loads `video` to a numpy array. Args: video (`str` or `VideoInput`)...
Loads `video` to a numpy array. Args: video (`str` or `VideoInput`): The video to convert to the numpy array format. Can be a link to video or local path. num_frames (`int`, *optional*): Number of frames to sample uniformly. If not passed, the whole video is loaded. ...
load_video
python
huggingface/transformers
src/transformers/video_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/video_utils.py
Apache-2.0
def convert_to_rgb( video: np.array, data_format: Optional[ChannelDimension] = None, input_data_format: Optional[Union[str, ChannelDimension]] = None, ) -> np.array: """ Convert video to RGB by blending the transparency layer if it's in RGBA format, otherwise simply returns it. Args: vi...
Convert video to RGB by blending the transparency layer if it's in RGBA format, otherwise simply returns it. Args: video (`np.array`): The video to convert. data_format (`ChannelDimension`, *optional*): The channel dimension format of the output video. If unset, will us...
convert_to_rgb
python
huggingface/transformers
src/transformers/video_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/video_utils.py
Apache-2.0
def pad( video: np.ndarray, padding: Union[int, Tuple[int, int], Iterable[Tuple[int, int]]], mode: PaddingMode = PaddingMode.CONSTANT, constant_values: Union[float, Iterable[float]] = 0.0, data_format: Optional[Union[str, ChannelDimension]] = None, input_data_format: Optional[Union[str, ChannelD...
Pads the `video` with the specified (height, width) `padding` and `mode`. Args: video (`np.ndarray`): The video to pad. padding (`int` or `Tuple[int, int]` or `Iterable[Tuple[int, int]]`): Padding to apply to the edges of the height, width axes. Can be one of three form...
pad
python
huggingface/transformers
src/transformers/video_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/video_utils.py
Apache-2.0
def group_videos_by_shape( videos: List["torch.Tensor"], ) -> Tuple[Dict[Tuple[int, int], List["torch.Tensor"]], Dict[int, Tuple[Tuple[int, int], int]]]: """ Groups videos by shape. Returns a dictionary with the shape as key and a list of videos with that shape as value, and a dictionary with the in...
Groups videos by shape. Returns a dictionary with the shape as key and a list of videos with that shape as value, and a dictionary with the index of the video in the original list as key and the shape and index in the grouped list as value.
group_videos_by_shape
python
huggingface/transformers
src/transformers/video_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/video_utils.py
Apache-2.0
def reorder_videos( processed_videos: Dict[Tuple[int, int], "torch.Tensor"], grouped_videos_index: Dict[int, Tuple[int, int]] ) -> List["torch.Tensor"]: """ Reconstructs a list of videos in the original order. """ return [ processed_videos[grouped_videos_index[i][0]][grouped_videos_index[i][...
Reconstructs a list of videos in the original order.
reorder_videos
python
huggingface/transformers
src/transformers/video_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/video_utils.py
Apache-2.0
def add_fast_image_processor_to_model_init( fast_image_processing_module_file: str, fast_image_processor_name, model_name: str ): """ Add the fast image processor to the __init__.py file of the model. """ with open(TRANSFORMERS_PATH / "models" / model_name / "__init__.py", "r", encoding="utf-8") as ...
Add the fast image processor to the __init__.py file of the model.
add_fast_image_processor_to_model_init
python
huggingface/transformers
src/transformers/commands/add_fast_image_processor.py
https://github.com/huggingface/transformers/blob/master/src/transformers/commands/add_fast_image_processor.py
Apache-2.0
def add_fast_image_processor_to_auto(image_processor_name: str, fast_image_processor_name: str): """ Add the fast image processor to the auto module. """ with open(TRANSFORMERS_PATH / "models" / "auto" / "image_processing_auto.py", "r", encoding="utf-8") as f: content = f.read() # get all l...
Add the fast image processor to the auto module.
add_fast_image_processor_to_auto
python
huggingface/transformers
src/transformers/commands/add_fast_image_processor.py
https://github.com/huggingface/transformers/blob/master/src/transformers/commands/add_fast_image_processor.py
Apache-2.0
def add_fast_image_processor_to_doc(fast_image_processor_name: str, model_name: str): """ Add the fast image processor to the model's doc file. """ doc_source = REPO_PATH / "docs" / "source" # find the doc files doc_files = list(doc_source.glob(f"*/model_doc/{model_name}.md")) if not doc_fil...
Add the fast image processor to the model's doc file.
add_fast_image_processor_to_doc
python
huggingface/transformers
src/transformers/commands/add_fast_image_processor.py
https://github.com/huggingface/transformers/blob/master/src/transformers/commands/add_fast_image_processor.py
Apache-2.0
def add_fast_image_processor_to_tests(fast_image_processor_name: str, model_name: str): """ Add the fast image processor to the image processing tests. """ tests_path = REPO_PATH / "tests" / "models" / model_name test_file = tests_path / f"test_image_processing_{model_name}.py" if not os.path.ex...
Add the fast image processor to the image processing tests.
add_fast_image_processor_to_tests
python
huggingface/transformers
src/transformers/commands/add_fast_image_processor.py
https://github.com/huggingface/transformers/blob/master/src/transformers/commands/add_fast_image_processor.py
Apache-2.0
def get_fast_image_processing_content_header(content: str) -> str: """ Get the header of the slow image processor file. """ # get all the commented lines at the beginning of the file content_header = re.search(r"^# coding=utf-8\n(#[^\n]*\n)*", content, re.MULTILINE) if not content_header: ...
Get the header of the slow image processor file.
get_fast_image_processing_content_header
python
huggingface/transformers
src/transformers/commands/add_fast_image_processor.py
https://github.com/huggingface/transformers/blob/master/src/transformers/commands/add_fast_image_processor.py
Apache-2.0
def write_default_fast_image_processor_file( fast_image_processing_module_file: str, fast_image_processor_name: str, content_base_file: str ): """ Write a default fast image processor file. Used when encountering a problem while parsing the slow image processor file. """ imports = "\n\nfrom ...image...
Write a default fast image processor file. Used when encountering a problem while parsing the slow image processor file.
write_default_fast_image_processor_file
python
huggingface/transformers
src/transformers/commands/add_fast_image_processor.py
https://github.com/huggingface/transformers/blob/master/src/transformers/commands/add_fast_image_processor.py
Apache-2.0
def add_fast_image_processor_file( fast_image_processing_module_file: str, fast_image_processor_name: str, content_base_file: str ): """ Add the fast image processor file to the model's folder. """ # if the file already exists, do nothing if os.path.exists(fast_image_processing_module_file): ...
Add the fast image processor file to the model's folder.
add_fast_image_processor_file
python
huggingface/transformers
src/transformers/commands/add_fast_image_processor.py
https://github.com/huggingface/transformers/blob/master/src/transformers/commands/add_fast_image_processor.py
Apache-2.0
def add_fast_image_processor(model_name: str): """ Add the necessary references to the fast image processor in the transformers package, and create the fast image processor file in the model's folder. """ model_module = TRANSFORMERS_PATH / "models" / model_name image_processing_module_file = lis...
Add the necessary references to the fast image processor in the transformers package, and create the fast image processor file in the model's folder.
add_fast_image_processor
python
huggingface/transformers
src/transformers/commands/add_fast_image_processor.py
https://github.com/huggingface/transformers/blob/master/src/transformers/commands/add_fast_image_processor.py
Apache-2.0
def add_model_to_main_init( old_model_patterns: ModelPatterns, new_model_patterns: ModelPatterns, frameworks: Optional[List[str]] = None, with_processing: bool = True, ): """ Add a model to the main init of Transformers. Args: old_model_patterns (`ModelPatterns`): The patterns for t...
Add a model to the main init of Transformers. Args: old_model_patterns (`ModelPatterns`): The patterns for the old model. new_model_patterns (`ModelPatterns`): The patterns for the new model. frameworks (`List[str]`, *optional*): If specified, only the models implemented in...
add_model_to_main_init
python
huggingface/transformers
src/transformers/commands/add_new_model_like.py
https://github.com/huggingface/transformers/blob/master/src/transformers/commands/add_new_model_like.py
Apache-2.0
def get_user_field( question: str, default_value: Optional[str] = None, is_valid_answer: Optional[Callable] = None, convert_to: Optional[Callable] = None, fallback_message: Optional[str] = None, ) -> Any: """ A utility function that asks a question to the user to get an answer, potentially l...
A utility function that asks a question to the user to get an answer, potentially looping until it gets a valid answer. Args: question (`str`): The question to ask the user. default_value (`str`, *optional*): A potential default value that will be used when the answer is empty. is_...
get_user_field
python
huggingface/transformers
src/transformers/commands/add_new_model_like.py
https://github.com/huggingface/transformers/blob/master/src/transformers/commands/add_new_model_like.py
Apache-2.0
def stream_output(self, output_stream: TextIteratorStreamer) -> str: """Stream output from a role, and return the generated text after it's done steaming.""" # This method is originally from the FastChat CLI: # https://github.com/lm-sys/FastChat/blob/main/fastchat/serve/cli.py # Create a...
Stream output from a role, and return the generated text after it's done steaming.
stream_output
python
huggingface/transformers
src/transformers/commands/chat.py
https://github.com/huggingface/transformers/blob/master/src/transformers/commands/chat.py
Apache-2.0
def input(self) -> str: """Gets user input from the console.""" input = self._console.input(f"[bold red]<{self.user_name}>:\n") self._console.print() return input
Gets user input from the console.
input
python
huggingface/transformers
src/transformers/commands/chat.py
https://github.com/huggingface/transformers/blob/master/src/transformers/commands/chat.py
Apache-2.0
def print_status(self, model_name: str, generation_config: GenerationConfig, model_kwargs: dict): """Prints the status of the model and generation settings to the console.""" self._console.print(f"[bold blue]Model: {model_name}\n") if model_kwargs: self._console.print(f"[bold blue]Mo...
Prints the status of the model and generation settings to the console.
print_status
python
huggingface/transformers
src/transformers/commands/chat.py
https://github.com/huggingface/transformers/blob/master/src/transformers/commands/chat.py
Apache-2.0
def _handle_deprecated_args(self, args: ChatArguments) -> ChatArguments: """ Handles deprecated arguments and their deprecation cycle. To be removed after we fully migrated to the new args. """ has_warnings = False # 1. Model as a positional argument args.model_n...
Handles deprecated arguments and their deprecation cycle. To be removed after we fully migrated to the new args.
_handle_deprecated_args
python
huggingface/transformers
src/transformers/commands/chat.py
https://github.com/huggingface/transformers/blob/master/src/transformers/commands/chat.py
Apache-2.0
def get_username() -> str: """Returns the username of the current user.""" if platform.system() == "Windows": return os.getlogin() else: return pwd.getpwuid(os.getuid()).pw_name
Returns the username of the current user.
get_username
python
huggingface/transformers
src/transformers/commands/chat.py
https://github.com/huggingface/transformers/blob/master/src/transformers/commands/chat.py
Apache-2.0
def save_chat(chat, args: ChatArguments, filename: Optional[str] = None) -> str: """Saves the chat history to a file.""" output_dict = {} output_dict["settings"] = vars(args) output_dict["chat_history"] = chat folder = args.save_folder if filename is None: t...
Saves the chat history to a file.
save_chat
python
huggingface/transformers
src/transformers/commands/chat.py
https://github.com/huggingface/transformers/blob/master/src/transformers/commands/chat.py
Apache-2.0
def parse_generate_flags(self, generate_flags: list[str]) -> dict: """Parses the generate flags from the user input into a dictionary of `generate` kwargs.""" if len(generate_flags) == 0: return {} # Assumption: `generate_flags` is a list of strings, each string being a `flag=value`...
Parses the generate flags from the user input into a dictionary of `generate` kwargs.
parse_generate_flags
python
huggingface/transformers
src/transformers/commands/chat.py
https://github.com/huggingface/transformers/blob/master/src/transformers/commands/chat.py
Apache-2.0
def get_generation_parameterization( self, args: ChatArguments, tokenizer: AutoTokenizer, model: PreTrainedModel ) -> tuple[GenerationConfig, dict]: """ Returns a GenerationConfig object holding the generation parameters for the CLI command. """ # No generation config arg pro...
Returns a GenerationConfig object holding the generation parameters for the CLI command.
get_generation_parameterization
python
huggingface/transformers
src/transformers/commands/chat.py
https://github.com/huggingface/transformers/blob/master/src/transformers/commands/chat.py
Apache-2.0
def parse_eos_tokens( tokenizer: PreTrainedTokenizer, generation_config: GenerationConfig, eos_tokens: Optional[str], eos_token_ids: Optional[str], ) -> tuple[int, list[int]]: """Retrieves the pad token ID and all possible EOS token IDs.""" if generation_config.pad_to...
Retrieves the pad token ID and all possible EOS token IDs.
parse_eos_tokens
python
huggingface/transformers
src/transformers/commands/chat.py
https://github.com/huggingface/transformers/blob/master/src/transformers/commands/chat.py
Apache-2.0
def handle_non_exit_user_commands( self, user_input: str, args: ChatArguments, interface: RichInterface, examples: dict[str, dict[str, str]], generation_config: GenerationConfig, model_kwargs: dict, chat: list[dict], ) -> tuple[list[dict], GenerationCo...
Handles all user commands except for `!exit`. May update the chat history (e.g. reset it) or the generation config (e.g. set a new flag).
handle_non_exit_user_commands
python
huggingface/transformers
src/transformers/commands/chat.py
https://github.com/huggingface/transformers/blob/master/src/transformers/commands/chat.py
Apache-2.0
def pad_without_fast_tokenizer_warning(tokenizer, *pad_args, **pad_kwargs): """ Pads without triggering the warning about how using the pad function is sub-optimal when using a fast tokenizer. """ # To avoid errors when using Feature extractors if not hasattr(tokenizer, "deprecation_warnings"): ...
Pads without triggering the warning about how using the pad function is sub-optimal when using a fast tokenizer.
pad_without_fast_tokenizer_warning
python
huggingface/transformers
src/transformers/data/data_collator.py
https://github.com/huggingface/transformers/blob/master/src/transformers/data/data_collator.py
Apache-2.0
def advance(self): """ When called, returns the token(s) that would take this constraint one step closer to being fulfilled. Return: token_ids (Union[int, List[int], None]): - A single token ID (int) that advances the constraint, or - A list of token ...
When called, returns the token(s) that would take this constraint one step closer to being fulfilled. Return: token_ids (Union[int, List[int], None]): - A single token ID (int) that advances the constraint, or - A list of token IDs that could advance the con...
advance
python
huggingface/transformers
src/transformers/generation/beam_constraints.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/beam_constraints.py
Apache-2.0
def get_candidates(self, input_ids: torch.LongTensor) -> Tuple[torch.LongTensor, Optional[torch.FloatTensor]]: """ Fetches the candidates to be tried for the current input. Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of inpu...
Fetches the candidates to be tried for the current input. Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids) Return: `torch.Long...
get_candidates
python
huggingface/transformers
src/transformers/generation/candidate_generator.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/candidate_generator.py
Apache-2.0
def update_candidate_strategy(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, num_matches: int): """ Updates the candidate generation strategy based on the outcomes. Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices ...
Updates the candidate generation strategy based on the outcomes. Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids) scores (`torch.FloatT...
update_candidate_strategy
python
huggingface/transformers
src/transformers/generation/candidate_generator.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/candidate_generator.py
Apache-2.0
def get_candidates(self, input_ids: torch.LongTensor) -> Tuple[torch.LongTensor, Optional[torch.FloatTensor]]: """ Fetches the candidates to be tried for the current input. Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of inpu...
Fetches the candidates to be tried for the current input. Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids) Return: `torch.Long...
get_candidates
python
huggingface/transformers
src/transformers/generation/candidate_generator.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/candidate_generator.py
Apache-2.0
def _calculate_new_tokens(self, input_ids: torch.LongTensor) -> Tuple[int, int]: """Calculate the minimum and maximum number of new tokens to generate.""" new_cur_len = input_ids.shape[-1] max_new_tokens = min(int(self.num_assistant_tokens), self.generation_config.max_length - new_cur_len - 1) ...
Calculate the minimum and maximum number of new tokens to generate.
_calculate_new_tokens
python
huggingface/transformers
src/transformers/generation/candidate_generator.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/candidate_generator.py
Apache-2.0
def _update_past_and_masks( self, input_ids: torch.LongTensor, remove_from_pkv: int = 0, num_added_tokens: int = 1 ) -> bool: """Update past key values and attention masks for subsequent generation rounds.""" has_past_key_values = self.assistant_kwargs.get("past_key_values", None) is not Non...
Update past key values and attention masks for subsequent generation rounds.
_update_past_and_masks
python
huggingface/transformers
src/transformers/generation/candidate_generator.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/candidate_generator.py
Apache-2.0
def _prepare_generation_args(self, input_ids: torch.LongTensor, min_new_tokens: int, max_new_tokens: int) -> Dict: """Prepare arguments for the generation call.""" return { self.input_ids_key: input_ids, "min_new_tokens": min_new_tokens, "max_new_tokens": max_new_toke...
Prepare arguments for the generation call.
_prepare_generation_args
python
huggingface/transformers
src/transformers/generation/candidate_generator.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/candidate_generator.py
Apache-2.0
def _generate_candidates(self, generation_args: Dict) -> Tuple[torch.LongTensor, Optional[torch.FloatTensor]]: """Generate candidate sequences using the assistant model.""" assistant_output = self.assistant_model.generate(**generation_args, **self.assistant_kwargs) self.assistant_kwargs["past_ke...
Generate candidate sequences using the assistant model.
_generate_candidates
python
huggingface/transformers
src/transformers/generation/candidate_generator.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/candidate_generator.py
Apache-2.0
def _get_longest_diag_dict(input_matrix, nonzero_idx): """ Calculates the length of the longest diagonal sequence in a given matrix. Args: input_matrix (torch.Tensor): The input matrix. nonzero_idx (torch.Tensor): The indices of the non-zero elements in the matrix. ...
Calculates the length of the longest diagonal sequence in a given matrix. Args: input_matrix (torch.Tensor): The input matrix. nonzero_idx (torch.Tensor): The indices of the non-zero elements in the matrix. Returns: dict: A dictionary where the keys are the i...
_get_longest_diag_dict
python
huggingface/transformers
src/transformers/generation/candidate_generator.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/candidate_generator.py
Apache-2.0
def _get_longest_diag_index(input_matrix): """ Returns the start index and length of the longest diagonal in the given input. Args: input_matrix (numpy.ndarray): The input matrix. Returns: tuple: A tuple containing the start index and length of the longest diagona...
Returns the start index and length of the longest diagonal in the given input. Args: input_matrix (numpy.ndarray): The input matrix. Returns: tuple: A tuple containing the start index and length of the longest diagonal.
_get_longest_diag_index
python
huggingface/transformers
src/transformers/generation/candidate_generator.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/candidate_generator.py
Apache-2.0
def _get_tokens_diag(prompt, prompt_plus_new_tokens): """ Input: prompt: 2D array of shape (batch_size, prompt_length), represents the original prompt tokens prompt_plus_new_tokens: 2D array of shape (batch_size, prompt_length), represents the suffix of the original prompt, with ...
Input: prompt: 2D array of shape (batch_size, prompt_length), represents the original prompt tokens prompt_plus_new_tokens: 2D array of shape (batch_size, prompt_length), represents the suffix of the original prompt, with additional new tokens. Output: discrepancy_le...
_get_tokens_diag
python
huggingface/transformers
src/transformers/generation/candidate_generator.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/candidate_generator.py
Apache-2.0
def convert_source_tokens_to_target_tokens( self, input_ids, source_tokenizer, destination_tokenizer, ): """ Convert token IDs from one tokenizer to another. Args: input_ids: The input token IDs. source_tokenizer: The source tokenizer. ...
Convert token IDs from one tokenizer to another. Args: input_ids: The input token IDs. source_tokenizer: The source tokenizer. destination_tokenizer: The destination tokenizer. Returns: The converted token IDs.
convert_source_tokens_to_target_tokens
python
huggingface/transformers
src/transformers/generation/candidate_generator.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/candidate_generator.py
Apache-2.0
def _prepare_assistant_input_ids(self, input_ids: torch.LongTensor) -> Tuple[torch.LongTensor, int]: """Converts target input IDs to assistant input IDs, handling discrepancies.""" convert_kwargs = { "source_tokenizer": self.target_tokenizer, "destination_tokenizer": self.assista...
Converts target input IDs to assistant input IDs, handling discrepancies.
_prepare_assistant_input_ids
python
huggingface/transformers
src/transformers/generation/candidate_generator.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/candidate_generator.py
Apache-2.0
def _process_assistant_outputs( self, input_ids: torch.LongTensor, assistant_sequences: torch.LongTensor, assistant_input_ids: torch.LongTensor ) -> torch.LongTensor: """Processes assistant outputs to obtain target input IDs.""" num_prev_assistant = self.prev_assistant_ids.shape[1] s...
Processes assistant outputs to obtain target input IDs.
_process_assistant_outputs
python
huggingface/transformers
src/transformers/generation/candidate_generator.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/candidate_generator.py
Apache-2.0
def __init__(self, original_embedding: nn.Embedding, assistant_overlap_token_ids): """ Wraps an existing embedding layer and remaps token IDs before lookup. Args: original_embedding (nn.Embedding): Pre-trained or existing embedding layer. assistant_overlap_token_ids (dic...
Wraps an existing embedding layer and remaps token IDs before lookup. Args: original_embedding (nn.Embedding): Pre-trained or existing embedding layer. assistant_overlap_token_ids (dict): Mapping from original token IDs to new token IDs. Example: {old_...
__init__
python
huggingface/transformers
src/transformers/generation/candidate_generator.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/candidate_generator.py
Apache-2.0
def forward(self, input_ids: torch.LongTensor) -> torch.FloatTensor: """ Args: input_ids (torch.LongTensor): Tensor of token IDs (batch_size, seq_len). Returns: torch.FloatTensor: Corresponding input embeddings. """ if self.map: # Get the last...
Args: input_ids (torch.LongTensor): Tensor of token IDs (batch_size, seq_len). Returns: torch.FloatTensor: Corresponding input embeddings.
forward
python
huggingface/transformers
src/transformers/generation/candidate_generator.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/candidate_generator.py
Apache-2.0
def unmap_input_ids(self): """ Disables the mapping of input ids despite the assistant pruning for the language model head being enabled. This method is required for the first forward pass of `_MapInputEmbedding` where input ids are already in the assistant vocabulary space. By disabling the ma...
Disables the mapping of input ids despite the assistant pruning for the language model head being enabled. This method is required for the first forward pass of `_MapInputEmbedding` where input ids are already in the assistant vocabulary space. By disabling the mapping, it ensures that the input ids a...
unmap_input_ids
python
huggingface/transformers
src/transformers/generation/candidate_generator.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/candidate_generator.py
Apache-2.0
def get_target_ids( self, assistant_input_ids, target_input_ids, assistant_candidate_ids: torch.LongTensor ) -> torch.LongTensor: """ Return the target candidate ids that correspond to the assistant candidate ids. Note that we have already the target ids for the prompt and we only ne...
Return the target candidate ids that correspond to the assistant candidate ids. Note that we have already the target ids for the prompt and we only need to find the target ids for the new tokens. Moreover, assistant ids of the original prompt does not necessarily appear in _assistant_to_target_...
get_target_ids
python
huggingface/transformers
src/transformers/generation/candidate_generator.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/candidate_generator.py
Apache-2.0
def get_target_logits(self, assistant_logits: torch.FloatTensor) -> torch.FloatTensor: """ Return the target logits that correspond to the assistant logits. """ target_shape: tuple[int, ...] = (*assistant_logits.shape[:-1], self.target_vocab_size) target_logits: torch.FloatTenso...
Return the target logits that correspond to the assistant logits.
get_target_logits
python
huggingface/transformers
src/transformers/generation/candidate_generator.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/candidate_generator.py
Apache-2.0
def cleanup(cls): """ Clean up dead references in the cache. This removes entries where either the target_tokenizer or assistant_tokenizer has been garbage collected. """ # Remove entries from the outer cache where the target_tokenizer is no longer alive dead_keys...
Clean up dead references in the cache. This removes entries where either the target_tokenizer or assistant_tokenizer has been garbage collected.
cleanup
python
huggingface/transformers
src/transformers/generation/candidate_generator.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/candidate_generator.py
Apache-2.0
def get_candidates(self, input_ids: torch.LongTensor) -> Tuple[torch.LongTensor, Optional[torch.FloatTensor]]: """ Simplified version of get_candidates that uses the translator cache for token conversion. """ target_input_ids = input_ids.to(self.assistant_model.device) assistant_...
Simplified version of get_candidates that uses the translator cache for token conversion.
get_candidates
python
huggingface/transformers
src/transformers/generation/candidate_generator.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/candidate_generator.py
Apache-2.0
def _prepare_assistant_input_ids(self, target_input_ids: torch.LongTensor) -> torch.LongTensor: """ Simplified token conversion that only processes new tokens. """ # Calculate new tokens since last call target_seq_len = target_input_ids.shape[-1] if self._target_seq_len_w...
Simplified token conversion that only processes new tokens.
_prepare_assistant_input_ids
python
huggingface/transformers
src/transformers/generation/candidate_generator.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/candidate_generator.py
Apache-2.0
def get_candidates(self, input_ids: torch.LongTensor) -> Tuple[torch.LongTensor, Optional[torch.FloatTensor]]: """ Fetches the candidates to be tried for the current input. Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of inpu...
Fetches the candidates to be tried for the current input. Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids) Return: `torch.Long...
get_candidates
python
huggingface/transformers
src/transformers/generation/candidate_generator.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/candidate_generator.py
Apache-2.0
def _prepare_attention_mask(model_kwargs: Dict[str, Any], new_length: int, is_encoder_decoder: bool) -> Dict[str, Any]: """Expands or crops the model's mask for decoding purposes, to the defined length""" mask_key = "decoder_attention_mask" if is_encoder_decoder else "attention_mask" if mask_key not in mod...
Expands or crops the model's mask for decoding purposes, to the defined length
_prepare_attention_mask
python
huggingface/transformers
src/transformers/generation/candidate_generator.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/candidate_generator.py
Apache-2.0
def _prepare_token_type_ids(model_kwargs: Dict[str, Any], new_length: int) -> Dict[str, Any]: """Expands or crops the model's token_type_ids for decoding purposes, to the defined length""" if "token_type_ids" not in model_kwargs or model_kwargs["token_type_ids"] is None: return model_kwargs token_t...
Expands or crops the model's token_type_ids for decoding purposes, to the defined length
_prepare_token_type_ids
python
huggingface/transformers
src/transformers/generation/candidate_generator.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/candidate_generator.py
Apache-2.0
def get_generation_mode(self, assistant_model: Optional["PreTrainedModel"] = None) -> GenerationMode: """ Returns the generation mode triggered by the [`GenerationConfig`] instance. Arg: assistant_model (`PreTrainedModel`, *optional*): The assistant model to be used ...
Returns the generation mode triggered by the [`GenerationConfig`] instance. Arg: assistant_model (`PreTrainedModel`, *optional*): The assistant model to be used for assisted generation. If set, the generation mode will be assisted generation. Return...
get_generation_mode
python
huggingface/transformers
src/transformers/generation/configuration_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/configuration_utils.py
Apache-2.0
def validate(self, strict=False): """ Validates the values of the attributes of the [`GenerationConfig`] instance. Raises exceptions in the presence of parameterization that can be detected as incorrect from the configuration instance alone. Note that some parameters not validated here ...
Validates the values of the attributes of the [`GenerationConfig`] instance. Raises exceptions in the presence of parameterization that can be detected as incorrect from the configuration instance alone. Note that some parameters not validated here are best validated at generate runtime, as th...
validate
python
huggingface/transformers
src/transformers/generation/configuration_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/configuration_utils.py
Apache-2.0
def from_dict(cls, config_dict, **kwargs): """ Constructs a BaseWatermarkingConfig instance from a dictionary of parameters. Args: config_dict (Dict[str, Any]): Dictionary containing configuration parameters. **kwargs: Additional keyword arguments to override dictionary ...
Constructs a BaseWatermarkingConfig instance from a dictionary of parameters. Args: config_dict (Dict[str, Any]): Dictionary containing configuration parameters. **kwargs: Additional keyword arguments to override dictionary values. Returns: BaseWatermarking...
from_dict
python
huggingface/transformers
src/transformers/generation/configuration_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/configuration_utils.py
Apache-2.0
def to_json_file(self, json_file_path: Union[str, os.PathLike]): """ Save this instance to a JSON file. Args: json_file_path (Union[str, os.PathLike]): Path to the JSON file in which this configuration instance's parameters will be saved. """ with open(json_file_path...
Save this instance to a JSON file. Args: json_file_path (Union[str, os.PathLike]): Path to the JSON file in which this configuration instance's parameters will be saved.
to_json_file
python
huggingface/transformers
src/transformers/generation/configuration_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/configuration_utils.py
Apache-2.0
def update(self, **kwargs): """ Update the configuration attributes with new values. Args: **kwargs: Keyword arguments representing configuration attributes and their new values. """ for key, value in kwargs.items(): if hasattr(self, key): ...
Update the configuration attributes with new values. Args: **kwargs: Keyword arguments representing configuration attributes and their new values.
update
python
huggingface/transformers
src/transformers/generation/configuration_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/configuration_utils.py
Apache-2.0
def update_with_token(self, token_id: int) -> bool: """Update the request with a newly generated token and check for completion. Args: token_id: The token ID to add to the output sequence Returns: bool: True if the request is now complete, False otherwise """ ...
Update the request with a newly generated token and check for completion. Args: token_id: The token ID to add to the output sequence Returns: bool: True if the request is now complete, False otherwise
update_with_token
python
huggingface/transformers
src/transformers/generation/continuous_batching.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/continuous_batching.py
Apache-2.0
def to_generation_output(self): """Convert the request state to a GenerationOutput object.""" return GenerationOutput( request_id=self.request_id, prompt_ids=self.full_prompt_ids, status=self.status, generated_tokens=self.static_outputs, logpro...
Convert the request state to a GenerationOutput object.
to_generation_output
python
huggingface/transformers
src/transformers/generation/continuous_batching.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/continuous_batching.py
Apache-2.0
def __init__( self, config: PretrainedConfig, generation_config: GenerationConfig, device: torch.device, dtype: torch.dtype = torch.float16, layer_device_map: Optional[Dict[int, Union[str, torch.device, int]]] = None, initial_prompt_shapes: Optional[List[List[int]...
Initialize a paged attention cache for efficient memory usage. Args: config: Model configuration generation_config: Generation configuration containing cache parameters device: Device for the cache tensors dtype: Data type for the cache tensors layer_...
__init__
python
huggingface/transformers
src/transformers/generation/continuous_batching.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/continuous_batching.py
Apache-2.0
def _get_physical_indices(self, state: RequestState, logical_indices: List[int]) -> List[int]: """ Maps logical sequence indices to physical cache indices using the block table, using PyTorch. Args: request_id: The request ID. logical_indices: A list of logical indices. ...
Maps logical sequence indices to physical cache indices using the block table, using PyTorch. Args: request_id: The request ID. logical_indices: A list of logical indices. Returns: A list of physical indices. Raises: ValueError: If no b...
_get_physical_indices
python
huggingface/transformers
src/transformers/generation/continuous_batching.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/continuous_batching.py
Apache-2.0
def _prepare_request_for_processing( self, state: RequestState, token_budget: int, request_ids_to_remove_from_waiting: Set[str] ): """Prepare a request for processing in the current batch.""" request_tokens = ( state.remaining_prompt_ids if state.status == RequestStatus.SPLIT_PEN...
Prepare a request for processing in the current batch.
_prepare_request_for_processing
python
huggingface/transformers
src/transformers/generation/continuous_batching.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/continuous_batching.py
Apache-2.0
def add_waiting_request(self, state: RequestState): """Add a request to the waiting list.""" if self.retain_cache_on_finish and state.request_id in self.active_requests: old_state = self.active_requests.pop(state.request_id) state.prompt_ids = state.prompt_ids[len(old_state.full_...
Add a request to the waiting list.
add_waiting_request
python
huggingface/transformers
src/transformers/generation/continuous_batching.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/continuous_batching.py
Apache-2.0
def compute_optimal_blocks( device: torch.device, config: PretrainedConfig, generation_config: GenerationConfig, inputs: List[List[int]], dtype: torch.dtype = torch.bfloat16, safety_margin: float = 0.9, median_prefill_length: Optional[int] = None, ): """Calculate optimal number and size ...
Calculate optimal number and size of blocks for the KV cache. Args: device: The device where the model runs config: The model configuration generation_config: The generation configuration inputs: Sample input sequences to estimate memory requirements dtype: Data type for cac...
compute_optimal_blocks
python
huggingface/transformers
src/transformers/generation/continuous_batching.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/continuous_batching.py
Apache-2.0
def __init__( self, cache: PagedAttentionCache, config: PretrainedConfig, generation_config: GenerationConfig, input_queue: queue.Queue, output_queue: queue.Queue, stop_event: threading.Event, model_device: torch.device, model_dtype: torch.dtype, ...
Initialize the continuous batch processor. Args: cache: The paged attention cache to use generation_config: The generation configuration input_queue: Queue for incoming requests output_queue: Queue for outgoing results stop_event: Event to signal proc...
__init__
python
huggingface/transformers
src/transformers/generation/continuous_batching.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/continuous_batching.py
Apache-2.0
def reset_static_tensors(self): """Reset static tensors for the next batch.""" self.input_ids.zero_() self.position_ids.zero_() self.attention_mask.fill_(torch.finfo(self.model_dtype).min) self.cumulative_seqlens_q.zero_() self.cumulative_seqlens_k.zero_() self.wr...
Reset static tensors for the next batch.
reset_static_tensors
python
huggingface/transformers
src/transformers/generation/continuous_batching.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/continuous_batching.py
Apache-2.0
def get_model_kwargs(self) -> PagedAttentionArgs: """Get model keyword arguments for the current batch.""" # torch.set_printoptions(threshold=100000,linewidth=10000) return { "input_ids": self.input_ids, "position_ids": self.position_ids, "attention_mask": sel...
Get model keyword arguments for the current batch.
get_model_kwargs
python
huggingface/transformers
src/transformers/generation/continuous_batching.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/continuous_batching.py
Apache-2.0
def _configure_batch_parameters(self): """Set up batch processing parameters based on generation config.""" # Calculate total cache capacity total_cache_tokens = self.cache.num_blocks * self.cache.block_size # Get or calculate max tokens per batch user_batch_tokens = getattr(sel...
Set up batch processing parameters based on generation config.
_configure_batch_parameters
python
huggingface/transformers
src/transformers/generation/continuous_batching.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/continuous_batching.py
Apache-2.0
def _get_new_requests(self): """Pull new requests from the input queue and add to waiting list.""" while not self.input_queue.empty(): try: state = self.input_queue.get_nowait() if state is None: # Sentinel value continue s...
Pull new requests from the input queue and add to waiting list.
_get_new_requests
python
huggingface/transformers
src/transformers/generation/continuous_batching.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/continuous_batching.py
Apache-2.0
def prepare_next_batch(self): """Prepare tensors and metadata for the next model forward pass.""" # Get new requests from the queue self._get_new_requests() if not self.scheduler.has_pending_requests(): return None self.metrics.record_queue_metrics(len(self.scheduler...
Prepare tensors and metadata for the next model forward pass.
prepare_next_batch
python
huggingface/transformers
src/transformers/generation/continuous_batching.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/continuous_batching.py
Apache-2.0
def _maybe_send_output(self, state: RequestState, token: int): """Send output to the queue based on streaming mode and request state.""" if self.streaming: state.next_token = token self.output_queue.put(state.to_generation_output()) elif state.status == RequestStatus.FINI...
Send output to the queue based on streaming mode and request state.
_maybe_send_output
python
huggingface/transformers
src/transformers/generation/continuous_batching.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/continuous_batching.py
Apache-2.0
def update_batch(self): """Update request states based on generated tokens.""" out_tokens = self._sync() finished_request_ids = [] for i, state in enumerate(self.requests_in_batch): req_id = state.request_id if len(state.remaining_prompt_ids) == 0: ...
Update request states based on generated tokens.
update_batch
python
huggingface/transformers
src/transformers/generation/continuous_batching.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/continuous_batching.py
Apache-2.0
def fail_all_requests(self, error): """Fail all active requests with the given error. Args: error: The error to report in the failure message """ for state in self.scheduler.active_requests.values(): self._handle_request_error(error, state) self.sched...
Fail all active requests with the given error. Args: error: The error to report in the failure message
fail_all_requests
python
huggingface/transformers
src/transformers/generation/continuous_batching.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/continuous_batching.py
Apache-2.0
def stop(self, block: bool = False, timeout: Optional[float] = None): """Signal the background thread to stop. Args: block: Whether to wait for the thread to stop timeout: Maximum time to wait for the thread to stop """ if self._generation_thread is None: ...
Signal the background thread to stop. Args: block: Whether to wait for the thread to stop timeout: Maximum time to wait for the thread to stop
stop
python
huggingface/transformers
src/transformers/generation/continuous_batching.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/continuous_batching.py
Apache-2.0
def join(self, timeout: Optional[float] = None): """Wait for the background thread to finish. Args: timeout: Maximum time to wait for the thread to stop """ if self._generation_thread is not None: self._generation_thread.join(timeout=timeout) if self....
Wait for the background thread to finish. Args: timeout: Maximum time to wait for the thread to stop
join
python
huggingface/transformers
src/transformers/generation/continuous_batching.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/continuous_batching.py
Apache-2.0
def add_request( self, input_ids: List[int], request_id: Optional[str] = None, max_new_tokens: Optional[int] = None ) -> str: """Add a new generation request to the queue. Args: input_ids: Input token IDs to use as prompt request_id: Optional custom request ID (auto-...
Add a new generation request to the queue. Args: input_ids: Input token IDs to use as prompt request_id: Optional custom request ID (auto-generated if None) **kwargs: Additional generation parameters Returns: str: The request ID
add_request
python
huggingface/transformers
src/transformers/generation/continuous_batching.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/continuous_batching.py
Apache-2.0
def get_result(self, timeout=None) -> Optional[GenerationOutput]: """Retrieve one result from the output queue. Args: timeout: Maximum time to wait for a result Returns: Optional[Dict]: The result data or None if timeout """ if self._generation_thread is...
Retrieve one result from the output queue. Args: timeout: Maximum time to wait for a result Returns: Optional[Dict]: The result data or None if timeout
get_result
python
huggingface/transformers
src/transformers/generation/continuous_batching.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/continuous_batching.py
Apache-2.0
def __iter__(self): """Iterate over results as they become available.""" while ( self._generation_thread is not None and self._generation_thread.is_alive() or not self.output_queue.empty() ): result = self.get_result(timeout=0.1) # allow the model to run for 10 seconds ...
Iterate over results as they become available.
__iter__
python
huggingface/transformers
src/transformers/generation/continuous_batching.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/continuous_batching.py
Apache-2.0
def _generation_step(self, batch_processor: ContinuousBatchProcessor): """Perform a single generation step. This is cuda graphed""" batch_data = batch_processor.get_model_kwargs() with torch.no_grad(): logits = self._model_forward(batch_data) if self.log_prob_generation: ...
Perform a single generation step. This is cuda graphed
_generation_step
python
huggingface/transformers
src/transformers/generation/continuous_batching.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/continuous_batching.py
Apache-2.0
def _run_generation_loop(self): """Main processing loop running in the background thread.""" batch_processor = None try: paged_attention_cache = PagedAttentionCache( self.model.config, self.generation_config, self.model.device, ...
Main processing loop running in the background thread.
_run_generation_loop
python
huggingface/transformers
src/transformers/generation/continuous_batching.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/continuous_batching.py
Apache-2.0
def _handle_critical_error(self, error, batch_processor: Optional[ContinuousBatchProcessor]): """Handle critical errors that terminate the generation loop.""" # Signal stop self.stop_event.set() # Fail pending requests in input queue try: while True: ...
Handle critical errors that terminate the generation loop.
_handle_critical_error
python
huggingface/transformers
src/transformers/generation/continuous_batching.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/continuous_batching.py
Apache-2.0
def evict_request_from_cache(self, request_id: str): """Evict a request from the cache. It is assumed that the request is already finished.""" if not self.manual_eviction: raise RuntimeError("Manual eviction is not enabled for this manager.") if self.batch_processor is not None: ...
Evict a request from the cache. It is assumed that the request is already finished.
evict_request_from_cache
python
huggingface/transformers
src/transformers/generation/continuous_batching.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/continuous_batching.py
Apache-2.0
def init_continuous_batching( self, generation_config: Optional[GenerationConfig] = None, manual_eviction: bool = False, max_queue_size: int = 0, streaming: bool = False, ) -> ContinuousBatchingManager: """Initialize a manager for continuous batching inference. ...
Initialize a manager for continuous batching inference. Args: generation_config: Custom generation configuration max_queue_size: Maximum size of the input request queue streaming: Whether to stream tokens as they are generated Returns: `ContinuousBatchin...
init_continuous_batching
python
huggingface/transformers
src/transformers/generation/continuous_batching.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/continuous_batching.py
Apache-2.0
def generate_batch( self, inputs: List[List[int]], generation_config: Optional[GenerationConfig] = None, progress_bar: bool = True, **kwargs, ) -> List[List[int]]: """Generate sequences for a batch of prompts using continuous batching. Args: input...
Generate sequences for a batch of prompts using continuous batching. Args: inputs: List of input token sequences (prompts) generation_config: Optional generation configuration **kwargs: Additional generation parameters Returns: `List[List[int]]`: A list ...
generate_batch
python
huggingface/transformers
src/transformers/generation/continuous_batching.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/continuous_batching.py
Apache-2.0
def get_previous_ngrams(self, input_ids: jnp.ndarray, vocab_size: int, cur_len: int): """ get a matrix of size (batch_size,) + (vocab_size,)*n (for n-grams) that represent the n-grams that occurred previously. The BCOO representation allow to store only the few non-zero entries, instead ...
get a matrix of size (batch_size,) + (vocab_size,)*n (for n-grams) that represent the n-grams that occurred previously. The BCOO representation allow to store only the few non-zero entries, instead of the full (huge) matrix
get_previous_ngrams
python
huggingface/transformers
src/transformers/generation/flax_logits_process.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/flax_logits_process.py
Apache-2.0
def get_banned_tokens_mask(self, latest_tokens: jnp.ndarray, previous_ngrams) -> jnp.ndarray: """ Determines which tokens must be banned given latest tokens and the previously seen ngrams. """ @sparse.sparsify @jax.vmap def inner_fn(latest_tokens, previous_ngrams...
Determines which tokens must be banned given latest tokens and the previously seen ngrams.
get_banned_tokens_mask
python
huggingface/transformers
src/transformers/generation/flax_logits_process.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/flax_logits_process.py
Apache-2.0
def _convert_list_arguments_into_dict(self): """BC: we used to accept `dict{tuple of tokens: float}` directly, now we expect a list""" if isinstance(self.sequence_bias, list): temp_sequence = self.sequence_bias self.sequence_bias = {tuple(sublist[0]): sublist[1] for sublist in te...
BC: we used to accept `dict{tuple of tokens: float}` directly, now we expect a list
_convert_list_arguments_into_dict
python
huggingface/transformers
src/transformers/generation/logits_process.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/logits_process.py
Apache-2.0