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 decode(self, input, *args, **kwargs ) -> Union[str, List[str]]: """ Perform decoding process of the tokenizer. Parameters ------------ inputs : list. The token sequence. args : Optional. Positional arguments. kwargs : Optional. ...
Perform decoding process of the tokenizer. Parameters ------------ inputs : list. The token sequence. args : Optional. Positional arguments. kwargs : Optional. Keyword arguments. Returns ------------ outputs...
decode
python
OptimalScale/LMFlow
src/lmflow/models/hf_encoder_decoder_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_encoder_decoder_model.py
Apache-2.0
def inference(self, inputs, *args, **kwargs): """ Perform generation process of the model. Parameters ------------ inputs : The sequence used as a prompt for the generation or as model inputs to the model. args : Optional. Positional arguments. ...
Perform generation process of the model. Parameters ------------ inputs : The sequence used as a prompt for the generation or as model inputs to the model. args : Optional. Positional arguments. kwargs : Optional. Keyword arguments....
inference
python
OptimalScale/LMFlow
src/lmflow/models/hf_encoder_decoder_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_encoder_decoder_model.py
Apache-2.0
def save(self, dir, save_full_model=False, *args, **kwargs): """ Perform generation process of the model. Parameters ------------ dir : The directory to save model and tokenizer save_full_model : Optional. Whether to save full model. kwa...
Perform generation process of the model. Parameters ------------ dir : The directory to save model and tokenizer save_full_model : Optional. Whether to save full model. kwargs : Optional. Keyword arguments. Returns ...
save
python
OptimalScale/LMFlow
src/lmflow/models/hf_encoder_decoder_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_encoder_decoder_model.py
Apache-2.0
def get_max_length(self): """ Return max acceptable input length in terms of tokens. """ if "tokenizer" not in self.tokenizer.__dict__: return self.tokenizer.model_max_length else: # for the multi-modality processor, # the max length is stored ...
Return max acceptable input length in terms of tokens.
get_max_length
python
OptimalScale/LMFlow
src/lmflow/models/hf_encoder_decoder_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_encoder_decoder_model.py
Apache-2.0
def __init__( self, model_args: ModelArguments, do_train: bool, ds_config=None, device: Optional[str]="gpu", use_accelerator: bool=False, hf_auto_model_additional_args: Optional[Dict]=None, *args, **kwargs ): """Initializes a HFModel in...
Initializes a HFModel instance. Parameters ---------- model_args : Dictionary with model arguments such as model name, path, revision, etc. do_train : bool To prepare the model for training or inference. ds_config : optional Deepspeed configu...
__init__
python
OptimalScale/LMFlow
src/lmflow/models/hf_model_mixin.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_model_mixin.py
Apache-2.0
def __prepare_model_config( self, model_args: ModelArguments, hf_auto_model_additional_args: Optional[Dict]=None, ): """Prepare model configuration for hf auto register, Parameters ---------- model_args : ModelArguments LMFlow model arguments. ...
Prepare model configuration for hf auto register, Parameters ---------- model_args : ModelArguments LMFlow model arguments. hf_auto_model_additional_args : Optional[Dict], optional Special configurations such as `num_labels` in `AutoModelForSequenceClassification`...
__prepare_model_config
python
OptimalScale/LMFlow
src/lmflow/models/hf_model_mixin.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_model_mixin.py
Apache-2.0
def __model_module_inject( self, model_args: ModelArguments, ) -> None: """Override some model modules with custom implementations. Current implementations: - Position interpolation (model_args.do_rope_scaling): replace llama embeddings with condense emb...
Override some model modules with custom implementations. Current implementations: - Position interpolation (model_args.do_rope_scaling): replace llama embeddings with condense embeddings.
__model_module_inject
python
OptimalScale/LMFlow
src/lmflow/models/hf_model_mixin.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_model_mixin.py
Apache-2.0
def deactivate_model_for_inference( self, use_vllm: bool=False, ): """Deactivate the model and release the resources. NOTE: Currently, VLLM doesn't have an official way to do this, and the implementation below cannot release all gpu resources by our observation. ...
Deactivate the model and release the resources. NOTE: Currently, VLLM doesn't have an official way to do this, and the implementation below cannot release all gpu resources by our observation. Thus this method is just a placeholder for future implementation. See: [Github issue]...
deactivate_model_for_inference
python
OptimalScale/LMFlow
src/lmflow/models/hf_model_mixin.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_model_mixin.py
Apache-2.0
def __init__( self, model_args: ModelArguments, tune_strategy: str='normal', ds_config=None, device="gpu", use_accelerator=False, *args, **kwargs ): """ Initializes a HFTextRegressionModel instance. :param model_args: dictionary...
Initializes a HFTextRegressionModel instance. :param model_args: dictionary with model arguments such as model name, path, revision, etc. :param tune_strategy: tuning strategy: normal, none, lora or adapter :param ds_config: deepspeed configuration for distributed training
__init__
python
OptimalScale/LMFlow
src/lmflow/models/hf_text_regression_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_text_regression_model.py
Apache-2.0
def tokenize( self, dataset: Dataset, add_special_tokens=True, *args, **kwargs ): """ Tokenize the full dataset. Parameters ------------ dataset : lmflow.datasets.Dataset. args : Optional. Positional argume...
Tokenize the full dataset. Parameters ------------ dataset : lmflow.datasets.Dataset. args : Optional. Positional arguments. kwargs : Optional. Keyword arguments. Returns ------------ tokenized_d...
tokenize
python
OptimalScale/LMFlow
src/lmflow/models/hf_text_regression_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_text_regression_model.py
Apache-2.0
def inference( self, inputs, release_gpu: bool = False, use_vllm: bool = False, **kwargs ) -> Union[List[float], SequenceClassifierOutputWithPast]: """ Perform generation process of the model. Parameters ------------ inputs : ...
Perform generation process of the model. Parameters ------------ inputs : The sequence used as a prompt for the generation or as model inputs to the model. When using vllm inference, this should be a string or a list of strings. When using normal...
inference
python
OptimalScale/LMFlow
src/lmflow/models/hf_text_regression_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_text_regression_model.py
Apache-2.0
def __inference( self, inputs, **kwargs ): """ Perform generation process of the model. Parameters ------------ inputs : The **tokenized** sequence used as a prompt for the generation or as model inputs to the model. kwargs :...
Perform generation process of the model. Parameters ------------ inputs : The **tokenized** sequence used as a prompt for the generation or as model inputs to the model. kwargs : Optional. Keyword arguments. Returns -----...
__inference
python
OptimalScale/LMFlow
src/lmflow/models/hf_text_regression_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_text_regression_model.py
Apache-2.0
def __vllm_inference( self, inputs: Union[str, List[str]], sampling_params: Optional['SamplingParams'] = None, **kwargs, ) -> Union[List[List[str]], List[List[List[int]]]]: """Perform VLLM inference process of the model. Parameters ---------- inputs ...
Perform VLLM inference process of the model. Parameters ---------- inputs : Union[str, List[str]] Prompt(s), string or a list of strings. sampling_params : Optional[SamplingParams], optional vllm SamplingParams object, by default None. Returns --...
__vllm_inference
python
OptimalScale/LMFlow
src/lmflow/models/hf_text_regression_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_text_regression_model.py
Apache-2.0
def __init__( self, model_args, *args, **kwargs ): """ Initializes a TextRegressionModel instance. :param model_args: dictionary with model arguments such as model name, path, revision, etc. """ self.inference_func = None
Initializes a TextRegressionModel instance. :param model_args: dictionary with model arguments such as model name, path, revision, etc.
__init__
python
OptimalScale/LMFlow
src/lmflow/models/text_regression_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/text_regression_model.py
Apache-2.0
def inference(self, inputs: Dataset): """ Gets regression results of a given dataset. :inputs: Dataset object, only accept type "text_only". """ if self.inference_func is not None: return self.inference_func(inputs) else: pass
Gets regression results of a given dataset. :inputs: Dataset object, only accept type "text_only".
inference
python
OptimalScale/LMFlow
src/lmflow/models/text_regression_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/text_regression_model.py
Apache-2.0
def __init__(self, config: Blip2Config, image_encoder_name_or_path=None, qformer_name_or_path=None, language_model_name_or_path=None, low_resource=False,): ''' TODO update the docs Args: config: ...
TODO update the docs Args: config: # the below varaible are used to overwrite the model in config image_encoder_name_or_path: qformer_name_or_path: language_model_name_or_path: Returns:
__init__
python
OptimalScale/LMFlow
src/lmflow/models/vision2seq_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/vision2seq_model.py
Apache-2.0
def register_prompt_cache(self, prompt_ids, prompt_keys_values): """ Udpate the prompt id and embedding for reuse in the future Args: prompt_ids (torch.LongTensor): The id of the prompt. prompt_keys_values (torch.FloatTensor): The embedding of the prompt. Return...
Udpate the prompt id and embedding for reuse in the future Args: prompt_ids (torch.LongTensor): The id of the prompt. prompt_keys_values (torch.FloatTensor): The embedding of the prompt. Returns: None
register_prompt_cache
python
OptimalScale/LMFlow
src/lmflow/models/vision2seq_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/vision2seq_model.py
Apache-2.0
def save_prompt_cache(self, path): """ Save prompt embedding and id. Args: path: The path to save the prompt embedding and id. Returns: None """ torch.save( dict( prompt_ids=self.prompt_ids, prompt_key...
Save prompt embedding and id. Args: path: The path to save the prompt embedding and id. Returns: None
save_prompt_cache
python
OptimalScale/LMFlow
src/lmflow/models/vision2seq_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/vision2seq_model.py
Apache-2.0
def generate( self, pixel_values: torch.FloatTensor, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.LongTensor] = None, image_token_indexes: Optional[List] = [0], one_sample_multiple_images: Optional[bool] = False, images: Optional[to...
Overrides `generate` function to be able to use the model as a conditional generator. Args: pixel_values (`torch.FloatTensor` of shape (batch_size, num_channels, height, width)): Input images to be processed. input_ids (`torch.LongTensor` of shape (batch_size, s...
generate
python
OptimalScale/LMFlow
src/lmflow/models/vision2seq_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/vision2seq_model.py
Apache-2.0
def prepare_inputs_labels_for_multimodal( self, input_ids, attention_mask, past_key_values, labels, images, language_projection=None, language_model=None, **kwargs ): ''' Copy from the LLAVA code base. Should be polished. ''' vision_tower = sel...
Copy from the LLAVA code base. Should be polished.
prepare_inputs_labels_for_multimodal
python
OptimalScale/LMFlow
src/lmflow/models/vision_encoder/clip_encoder.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/vision_encoder/clip_encoder.py
Apache-2.0
def step(self, closure=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() for ...
Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss.
step
python
OptimalScale/LMFlow
src/lmflow/optim/adabelief.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/optim/adabelief.py
Apache-2.0
def step(self, closure = None): r"""Performs a single optimization step. Arguments: closure: A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() for group, base_lr in zip(self.param_...
Performs a single optimization step. Arguments: closure: A closure that reevaluates the model and returns the loss.
step
python
OptimalScale/LMFlow
src/lmflow/optim/adabound.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/optim/adabound.py
Apache-2.0
def step(self, closure = None): r"""Performs a single optimization step. Arguments: closure: A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() for group in self.param_groups: ...
Performs a single optimization step. Arguments: closure: A closure that reevaluates the model and returns the loss.
step
python
OptimalScale/LMFlow
src/lmflow/optim/adamp.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/optim/adamp.py
Apache-2.0
def step(self, closure=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() ...
Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss.
step
python
OptimalScale/LMFlow
src/lmflow/optim/adamw_schedule_free.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/optim/adamw_schedule_free.py
Apache-2.0
def step(self, closure: Callable=None): """ Performs a single optimization step. Arguments: closure (:obj:`Callable`, `optional`): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() ...
Performs a single optimization step. Arguments: closure (:obj:`Callable`, `optional`): A closure that reevaluates the model and returns the loss.
step
python
OptimalScale/LMFlow
src/lmflow/optim/dummy.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/optim/dummy.py
Apache-2.0
def step(self, closure = None): r"""Performs a single optimization step. Arguments: closure: A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() for group in self.param_groups: ...
Performs a single optimization step. Arguments: closure: A closure that reevaluates the model and returns the loss.
step
python
OptimalScale/LMFlow
src/lmflow/optim/lamb.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/optim/lamb.py
Apache-2.0
def step(self, closure = None): r"""Performs a single optimization step. Arguments: closure: A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: with torch.enable_grad(): loss = closure() ...
Performs a single optimization step. Arguments: closure: A closure that reevaluates the model and returns the loss.
step
python
OptimalScale/LMFlow
src/lmflow/optim/lars.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/optim/lars.py
Apache-2.0
def zeropower_via_newtonschulz5(G: Tensor, steps: int) -> Tensor: """ Newton-Schulz iteration to compute the zeroth power / orthogonalization of G. We opt to use a quintic iteration whose coefficients are selected to maximize the slope at zero. For the purpose of minimizing steps, it turns out to be emp...
Newton-Schulz iteration to compute the zeroth power / orthogonalization of G. We opt to use a quintic iteration whose coefficients are selected to maximize the slope at zero. For the purpose of minimizing steps, it turns out to be empirically effective to keep increasing the slope at zero even beyond t...
zeropower_via_newtonschulz5
python
OptimalScale/LMFlow
src/lmflow/optim/muon.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/optim/muon.py
Apache-2.0
def step(self, closure=None): """ Performs a single optimization step. Args: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() ...
Performs a single optimization step. Args: closure (callable, optional): A closure that reevaluates the model and returns the loss.
step
python
OptimalScale/LMFlow
src/lmflow/optim/muon.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/optim/muon.py
Apache-2.0
def step(self, closure = None): r"""Performs a single optimization step. Arguments: closure: A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() for group in self.param_groups: ...
Performs a single optimization step. Arguments: closure: A closure that reevaluates the model and returns the loss.
step
python
OptimalScale/LMFlow
src/lmflow/optim/radam.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/optim/radam.py
Apache-2.0
def step(self, closure = None): r"""Performs a single optimization step. Arguments: closure: A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() for group in self.param_groups: ...
Performs a single optimization step. Arguments: closure: A closure that reevaluates the model and returns the loss.
step
python
OptimalScale/LMFlow
src/lmflow/optim/sgdp.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/optim/sgdp.py
Apache-2.0
def step(self, closure=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() ...
Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss.
step
python
OptimalScale/LMFlow
src/lmflow/optim/sgd_schedule_free.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/optim/sgd_schedule_free.py
Apache-2.0
def step(self, closure = None): r"""Performs a single optimization step. Arguments: closure: A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() for group in self.param_groups: ...
Performs a single optimization step. Arguments: closure: A closure that reevaluates the model and returns the loss.
step
python
OptimalScale/LMFlow
src/lmflow/optim/yogi.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/optim/yogi.py
Apache-2.0
def convert_to_paired_dataset( self, source_dataset: Dataset, sampling_paired_method: str="random", length_penalty: float=0.0, margin_scale: float=1.0, use_fast: bool=False, ) -> Dataset: """Convert a scored one to multiple (text_to_scored_textlist) to a paire...
Convert a scored one to multiple (text_to_scored_textlist) to a paired dataset by rejection sampling.
convert_to_paired_dataset
python
OptimalScale/LMFlow
src/lmflow/pipeline/dpov2_aligner.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/dpov2_aligner.py
Apache-2.0
def _calc_reward_with_length_penalty( self, rewards: List[float], lengths: List[int], length_penalty: float, ) -> List[float]: """When length_penalty > 0, penalize the longer sequence by subtracting length_penalty * length from the reward. Vice versa when length_pe...
When length_penalty > 0, penalize the longer sequence by subtracting length_penalty * length from the reward. Vice versa when length_penalty < 0.
_calc_reward_with_length_penalty
python
OptimalScale/LMFlow
src/lmflow/pipeline/dpov2_aligner.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/dpov2_aligner.py
Apache-2.0
def sampling_paired_idx_from_rewards( self, rewards: List[float], sampling_paired_method: str="random", use_fast: bool=False, ) -> Tuple[int, int]: """Prepare the dataset for DPO training by rejection sampling. We implement different strategies to select pairs, includ...
Prepare the dataset for DPO training by rejection sampling. We implement different strategies to select pairs, including random: randomly select two instances max_min: best v.s. worst max_max: best v.s. second best max_random: best v.s. random from the remaining
sampling_paired_idx_from_rewards
python
OptimalScale/LMFlow
src/lmflow/pipeline/dpov2_aligner.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/dpov2_aligner.py
Apache-2.0
def get_paired_dataset( data_root: str, data_dir: str, sanity_check: bool = False, cache_dir: Optional[str] = None, num_proc=24, ) -> Dataset: """Load dataset and convert it to the necessary format. The dataset is converted to a dictionary with the following structure: ...
Load dataset and convert it to the necessary format. The dataset is converted to a dictionary with the following structure: { 'prompt': List[str], 'chosen': List[str], 'rejected': List[str], } Prompts are structured as follows: "Question: " + <prompt> + " Answer: "
get_paired_dataset
python
OptimalScale/LMFlow
src/lmflow/pipeline/dpo_aligner.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/dpo_aligner.py
Apache-2.0
def evaluate( self, model, dataset: Dataset, metric = "accuracy", verbose=True, ): """ Perform Evaluation for a model Parameters ------------ model : TunableModel object. TunableModel to perform inference dataset :...
Perform Evaluation for a model Parameters ------------ model : TunableModel object. TunableModel to perform inference dataset : Dataset object.
evaluate
python
OptimalScale/LMFlow
src/lmflow/pipeline/evaluator.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/evaluator.py
Apache-2.0
def _evaluate_nll( self, model, dataset: Dataset, verbose=True, ): """ Evaluates negative log likelihood of the model over a dataset. NLL = -1/N sum_{i=1}^N sum_{j=1}^|w_i| ln(p(w_{i,j}|context_window)), where N is the number of data samples, w_{i,j}...
Evaluates negative log likelihood of the model over a dataset. NLL = -1/N sum_{i=1}^N sum_{j=1}^|w_i| ln(p(w_{i,j}|context_window)), where N is the number of data samples, w_{i,j} is the j-th token in i-th sample. Here "context_window" = p(w_{i,start}, w_{i,start+1}, ..., p_{i...
_evaluate_nll
python
OptimalScale/LMFlow
src/lmflow/pipeline/evaluator.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/evaluator.py
Apache-2.0
def group_text(self, tokenized_datasets, model_max_length): """ Groups texts together to form blocks of maximum length `model_max_length` and returns the processed data as a dictionary. """ data_args = self.data_args finetuner_args = self.finetuner_args if data_a...
Groups texts together to form blocks of maximum length `model_max_length` and returns the processed data as a dictionary.
group_text
python
OptimalScale/LMFlow
src/lmflow/pipeline/finetuner.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/finetuner.py
Apache-2.0
def tune(self, model: Union[HFDecoderModel, HFTextRegressionModel, HFEncoderDecoderModel], dataset: Dataset, transform_dataset_in_place=True, data_collator=None): """ Perform tuning for a model Parameters ------------ model : T...
Perform tuning for a model Parameters ------------ model : TunableModel object. TunableModel to perform tuning. dataset: dataset to train model.
tune
python
OptimalScale/LMFlow
src/lmflow/pipeline/finetuner.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/finetuner.py
Apache-2.0
def create_dataloader(self, dataset: Dataset): r"""Batchlize dataset and format it to dataloader. Args: dataset (Dataset): the dataset object Output: dataloader (batchlize): the dataloader object dataset_size (int): the length of the dataset """ ...
Batchlize dataset and format it to dataloader. Args: dataset (Dataset): the dataset object Output: dataloader (batchlize): the dataloader object dataset_size (int): the length of the dataset
create_dataloader
python
OptimalScale/LMFlow
src/lmflow/pipeline/inferencer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/inferencer.py
Apache-2.0
def inference( self, model, dataset: Dataset, max_new_tokens: int=100, temperature: float=0.0, prompt_structure: str='{input}', remove_image_flag: bool=False, chatbot_type: str="mini_gpt", ): """ Perform inference for a model P...
Perform inference for a model Parameters ------------ model : TunableModel object. TunableModel to perform inference dataset : Dataset object. Returns: output_dataset: Dataset object.
inference
python
OptimalScale/LMFlow
src/lmflow/pipeline/inferencer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/inferencer.py
Apache-2.0
def score_to_prob(scores: torch.Tensor, temperature: float = 0., top_p: float = 1.,) -> torch.Tensor: """Convert scores (NOT softmaxed tensor) to probabilities with support for temperature, top-p sampling, and argmax. Parameters ---------- sc...
Convert scores (NOT softmaxed tensor) to probabilities with support for temperature, top-p sampling, and argmax. Parameters ---------- scores : torch.Tensor Input scores. temperature : float, optional Temperature parameter for controlling randomness. Higher value...
score_to_prob
python
OptimalScale/LMFlow
src/lmflow/pipeline/inferencer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/inferencer.py
Apache-2.0
def predict_next_token(model: HFDecoderModel, input_ids: torch.Tensor, num_new_tokens: int = 1): """Predict the next token given the input_ids. """ output = model.inference(input_ids, use_accelerator=True, max_new_tokens=num_new...
Predict the next token given the input_ids.
predict_next_token
python
OptimalScale/LMFlow
src/lmflow/pipeline/inferencer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/inferencer.py
Apache-2.0
def autoregressive_sampling(self, input_ids: torch.Tensor, model: HFDecoderModel, temperature: float = 0., num_new_tokens: int = 5) -> Dict: """Ref: [arXiv:2211.17192v2](https://ar...
Ref: [arXiv:2211.17192v2](https://arxiv.org/abs/2211.17192) Section 2.2
autoregressive_sampling
python
OptimalScale/LMFlow
src/lmflow/pipeline/inferencer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/inferencer.py
Apache-2.0
def inference( self, model: HFDecoderModel, input: str, max_new_tokens: int=1024, ): """ Perform inference for a model Parameters ------------ model : HFDecoderModel object. TunableModel to perform inference input : str. ...
Perform inference for a model Parameters ------------ model : HFDecoderModel object. TunableModel to perform inference input : str. The input text (i.e., the prompt) for the model. max_new_tokens : int. The maximum numb...
inference
python
OptimalScale/LMFlow
src/lmflow/pipeline/inferencer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/inferencer.py
Apache-2.0
def _initialize_trainer(self, model, tokenizer, training_args): """ This function takes the model and tokenizer as the input and initialize the trainer. """ trainer = RaftTrainer( model=model, args=training_args, train_dataset=Dataset.from_dict({"text"...
This function takes the model and tokenizer as the input and initialize the trainer.
_initialize_trainer
python
OptimalScale/LMFlow
src/lmflow/pipeline/raft_aligner.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/raft_aligner.py
Apache-2.0
def _load_dataset( self, selected_dataset, model, tokenizer, model_args, data_args, training_args, ): ''' This function prepares the dataset for every iteration. ''' raw_datasets = selected_dataset if training_args.do_t...
This function prepares the dataset for every iteration.
_load_dataset
python
OptimalScale/LMFlow
src/lmflow/pipeline/raft_aligner.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/raft_aligner.py
Apache-2.0
def _load_input_dataset(self, dataset, tokenizer): """ Load input dataset (i.e. prompt/question dataset) for training. Args: dataset: A Dataset object. The dataset to be loaded. Returns: dataloader (`torch.utils.data.DataLoader`): ...
Load input dataset (i.e. prompt/question dataset) for training. Args: dataset: A Dataset object. The dataset to be loaded. Returns: dataloader (`torch.utils.data.DataLoader`): The dataloader for the dataset.
_load_input_dataset
python
OptimalScale/LMFlow
src/lmflow/pipeline/raft_aligner.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/raft_aligner.py
Apache-2.0
def align(self, model, dataset, reward_model): """ Perform alignment for a model Parameters ------------ model : BaseModel object. dataset: Dataset object. Input dataset for model to generate outputs. The input and output will then be feed int...
Perform alignment for a model Parameters ------------ model : BaseModel object. dataset: Dataset object. Input dataset for model to generate outputs. The input and output will then be feed into reward model to get the reward for align...
align
python
OptimalScale/LMFlow
src/lmflow/pipeline/raft_aligner.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/raft_aligner.py
Apache-2.0
def __call__(self, batch: Dict[str, np.ndarray]): """batch: Dict[str, np.ndarray] Example (batch size=2): {'input': array(['...','...'], dtype=object), 'output': array([array(["...", "..."], dtype=object), array(['...','...'], dtype=object)], dtype=object...
batch: Dict[str, np.ndarray] Example (batch size=2): {'input': array(['...','...'], dtype=object), 'output': array([array(["...", "..."], dtype=object), array(['...','...'], dtype=object)], dtype=object), 'input_ids': array([[[128000, 128006, 882, ......
__call__
python
OptimalScale/LMFlow
src/lmflow/pipeline/rm_inferencer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/rm_inferencer.py
Apache-2.0
def inference( self, model: HFDecoderModel, dataset: Dataset, enable_decode_inference_result: bool = True, release_gpu: bool = False, inference_args: Optional[InferencerArguments] = None, enable_distributed_inference: bool = False, **kwargs, ) -> Lis...
Perform inference using the provided model and dataset. Will save inference results if `save_results` is set to True in `inferencer_args`. Parameters ---------- model : HFDecoderModel LMFlow HFDecoderModel object dataset : Dataset LMFlow Dataset object ...
inference
python
OptimalScale/LMFlow
src/lmflow/pipeline/vllm_inferencer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/vllm_inferencer.py
Apache-2.0
def __call__(self, batch: Dict[str, np.ndarray]): """batch: Dict[str, np.ndarray], {"item": array(['...', '...', '...', ...])} """ batched_inference_res = self.model.inference( inputs=batch['item'], sampling_params=self.sampling_par...
batch: Dict[str, np.ndarray], {"item": array(['...', '...', '...', ...])}
__call__
python
OptimalScale/LMFlow
src/lmflow/pipeline/vllm_inferencer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/vllm_inferencer.py
Apache-2.0
def tokenize_batch_element( self, prompt: str, chosen: str, rejected: str, ) -> Dict: """Tokenize a single batch element. At this stage, we don't convert to PyTorch tensors yet; we just handle the truncation in case the prompt + chosen or prompt + rejecte...
Tokenize a single batch element. At this stage, we don't convert to PyTorch tensors yet; we just handle the truncation in case the prompt + chosen or prompt + rejected responses is/are too long. First we truncate the prompt; if we're still too long, we truncate the chosen/rejected. ...
tokenize_batch_element
python
OptimalScale/LMFlow
src/lmflow/pipeline/utils/dpov2_dataprocessor.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/utils/dpov2_dataprocessor.py
Apache-2.0
def dpo_loss( self, policy_chosen_logps: torch.FloatTensor, policy_rejected_logps: torch.FloatTensor, reference_chosen_logps: torch.FloatTensor, reference_rejected_logps: torch.FloatTensor, reference_free: bool = False, margin: Optional[torch.FloatTensor] = None, ...
Compute the DPO loss for a batch of policy and reference model log probabilities. Args: policy_chosen_logps: Log probabilities of the policy model for the chosen responses. Shape: (batch_size,) policy_rejected_logps: Log probabilities of the policy model for the rejected responses. Shap...
dpo_loss
python
OptimalScale/LMFlow
src/lmflow/pipeline/utils/dpov2_trainer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/utils/dpov2_trainer.py
Apache-2.0
def get_batch_metrics( self, model, batch: Dict[str, Union[List, torch.LongTensor]], train_eval: Literal["train", "eval"] = "train", ): """Compute the DPO loss and other metrics for the given batch of inputs for train or test.""" metrics = {} ( pol...
Compute the DPO loss and other metrics for the given batch of inputs for train or test.
get_batch_metrics
python
OptimalScale/LMFlow
src/lmflow/pipeline/utils/dpov2_trainer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/utils/dpov2_trainer.py
Apache-2.0
def _save_checkpoint(self, _, trial, metrics=None): """ Don't save base model, optimizer etc. but create checkpoint folder (needed for saving adapter) """ checkpoint_folder = f"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}" run_dir = self._get_output_dir(trial=trial) outp...
Don't save base model, optimizer etc. but create checkpoint folder (needed for saving adapter)
_save_checkpoint
python
OptimalScale/LMFlow
src/lmflow/pipeline/utils/peft_trainer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/utils/peft_trainer.py
Apache-2.0
def on_epoch_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): """ Save intermediate model adapters in case of interrupted training """ folder = os.path.join(args.output_dir, f"{PREFIX_CHECKPOINT_DIR}-{state.global_step}") self._save(kwargs['...
Save intermediate model adapters in case of interrupted training
on_epoch_end
python
OptimalScale/LMFlow
src/lmflow/pipeline/utils/peft_trainer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/utils/peft_trainer.py
Apache-2.0
def _get_collator_with_removed_columns( self, data_collator: Callable, description: Optional[str] = None ) -> Callable: """Wrap the data collator in a callable removing unused columns.""" if not self.args.remove_unused_columns: return data_collator self._set_signature_col...
Wrap the data collator in a callable removing unused columns.
_get_collator_with_removed_columns
python
OptimalScale/LMFlow
src/lmflow/pipeline/utils/raft_trainer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/utils/raft_trainer.py
Apache-2.0
def get_train_dataloader(self) -> DataLoader: """ Returns the training [`~torch.utils.data.DataLoader`]. Will use no sampler if `train_dataset` does not implement `__len__`, a random sampler (adapted to distributed training if necessary) otherwise. Subclass and override this meth...
Returns the training [`~torch.utils.data.DataLoader`]. Will use no sampler if `train_dataset` does not implement `__len__`, a random sampler (adapted to distributed training if necessary) otherwise. Subclass and override this method if you want to inject some custom behavior.
get_train_dataloader
python
OptimalScale/LMFlow
src/lmflow/pipeline/utils/raft_trainer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/utils/raft_trainer.py
Apache-2.0
def get_eval_dataloader(self, eval_dataset: Optional[Dataset] = None) -> DataLoader: """ Returns the evaluation [`~torch.utils.data.DataLoader`]. Subclass and override this method if you want to inject some custom behavior. Args: eval_dataset (`torch.utils.data.Dataset`, *opt...
Returns the evaluation [`~torch.utils.data.DataLoader`]. Subclass and override this method if you want to inject some custom behavior. Args: eval_dataset (`torch.utils.data.Dataset`, *optional*): If provided, will override `self.eval_dataset`. If it is a [`~datasets....
get_eval_dataloader
python
OptimalScale/LMFlow
src/lmflow/pipeline/utils/raft_trainer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/utils/raft_trainer.py
Apache-2.0
def get_test_dataloader(self, test_dataset: Dataset) -> DataLoader: """ Returns the test [`~torch.utils.data.DataLoader`]. Subclass and override this method if you want to inject some custom behavior. Args: test_dataset (`torch.utils.data.Dataset`, *optional*): ...
Returns the test [`~torch.utils.data.DataLoader`]. Subclass and override this method if you want to inject some custom behavior. Args: test_dataset (`torch.utils.data.Dataset`, *optional*): The test dataset to use. If it is a [`~datasets.Dataset`], columns not accept...
get_test_dataloader
python
OptimalScale/LMFlow
src/lmflow/pipeline/utils/raft_trainer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/utils/raft_trainer.py
Apache-2.0
def create_optimizer_and_scheduler(self, num_training_steps: int): """ Setup the optimizer and the learning rate scheduler. We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the Trainer's init through `optimizers`, or subclass and...
Setup the optimizer and the learning rate scheduler. We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the Trainer's init through `optimizers`, or subclass and override this method (or `create_optimizer` and/or `create_scheduler`...
create_optimizer_and_scheduler
python
OptimalScale/LMFlow
src/lmflow/pipeline/utils/raft_trainer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/utils/raft_trainer.py
Apache-2.0
def create_optimizer(self): """ Setup the optimizer. We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the Trainer's init through `optimizers`, or subclass and override this method in a subclass. """ opt_model = se...
Setup the optimizer. We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the Trainer's init through `optimizers`, or subclass and override this method in a subclass.
create_optimizer
python
OptimalScale/LMFlow
src/lmflow/pipeline/utils/raft_trainer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/utils/raft_trainer.py
Apache-2.0
def get_optimizer_cls_and_kwargs(args: TrainingArguments) -> Tuple[Any, Any]: """ Returns the optimizer class and optimizer parameters based on the training arguments. Args: args (`transformers.training_args.TrainingArguments`): The training arguments for the training...
Returns the optimizer class and optimizer parameters based on the training arguments. Args: args (`transformers.training_args.TrainingArguments`): The training arguments for the training session.
get_optimizer_cls_and_kwargs
python
OptimalScale/LMFlow
src/lmflow/pipeline/utils/raft_trainer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/utils/raft_trainer.py
Apache-2.0
def create_scheduler(self, num_training_steps: int, optimizer: torch.optim.Optimizer = None): """ Setup the scheduler. The optimizer of the trainer must have been set up either before this method is called or passed as an argument. Args: num_training_steps (int): The number o...
Setup the scheduler. The optimizer of the trainer must have been set up either before this method is called or passed as an argument. Args: num_training_steps (int): The number of training steps to do.
create_scheduler
python
OptimalScale/LMFlow
src/lmflow/pipeline/utils/raft_trainer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/utils/raft_trainer.py
Apache-2.0
def num_examples(self, dataloader: DataLoader) -> int: """ Helper to get number of samples in a [`~torch.utils.data.DataLoader`] by accessing its dataset. When dataloader.dataset does not exist or has no length, estimates as best it can """ try: dataset = dataloader.d...
Helper to get number of samples in a [`~torch.utils.data.DataLoader`] by accessing its dataset. When dataloader.dataset does not exist or has no length, estimates as best it can
num_examples
python
OptimalScale/LMFlow
src/lmflow/pipeline/utils/raft_trainer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/utils/raft_trainer.py
Apache-2.0
def train( self, resume_from_checkpoint: Optional[Union[str, bool]] = None, trial: Union["optuna.Trial", Dict[str, Any]] = None, ignore_keys_for_eval: Optional[List[str]] = None, is_first_time = False, **kwargs, ): """ Main training entry point. ...
Main training entry point. Args: resume_from_checkpoint (`str` or `bool`, *optional*): If a `str`, local path to a saved checkpoint as saved by a previous instance of [`Trainer`]. If a `bool` and equals `True`, load the last checkpoint in *args.output_dir* as...
train
python
OptimalScale/LMFlow
src/lmflow/pipeline/utils/raft_trainer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/utils/raft_trainer.py
Apache-2.0
def _inner_training_loop( self, batch_size=None, args=None, resume_from_checkpoint=None, trial=None, ignore_keys_for_eval=None ): ''' 0 This function serves to train one time 1 Update the self.train_dataset before calling this function ''' # 1 Get dataloader s...
0 This function serves to train one time 1 Update the self.train_dataset before calling this function
_inner_training_loop
python
OptimalScale/LMFlow
src/lmflow/pipeline/utils/raft_trainer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/utils/raft_trainer.py
Apache-2.0
def _load_optimizer_and_scheduler(self, checkpoint): """If optimizer and scheduler states exist, load them.""" if checkpoint is None: return if self.deepspeed: # deepspeed loads optimizer/lr_scheduler together with the model in deepspeed_init return ...
If optimizer and scheduler states exist, load them.
_load_optimizer_and_scheduler
python
OptimalScale/LMFlow
src/lmflow/pipeline/utils/raft_trainer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/utils/raft_trainer.py
Apache-2.0
def hyperparameter_search( self, hp_space: Optional[Callable[["optuna.Trial"], Dict[str, float]]] = None, compute_objective: Optional[Callable[[Dict[str, float]], float]] = None, n_trials: int = 20, direction: str = "minimize", backend: Optional[Union["str", HPSearchBacke...
Launch an hyperparameter search using `optuna` or `Ray Tune` or `SigOpt`. The optimized quantity is determined by `compute_objective`, which defaults to a function returning the evaluation loss when no metric is provided, the sum of all metrics otherwise. <Tip warning={true}> To...
hyperparameter_search
python
OptimalScale/LMFlow
src/lmflow/pipeline/utils/raft_trainer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/utils/raft_trainer.py
Apache-2.0
def log(self, logs: Dict[str, float]) -> None: """ Log `logs` on the various objects watching training. Subclass and override this method to inject custom behavior. Args: logs (`Dict[str, float]`): The values to log. """ if self.state.epoch is ...
Log `logs` on the various objects watching training. Subclass and override this method to inject custom behavior. Args: logs (`Dict[str, float]`): The values to log.
log
python
OptimalScale/LMFlow
src/lmflow/pipeline/utils/raft_trainer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/utils/raft_trainer.py
Apache-2.0
def _prepare_input(self, data: Union[torch.Tensor, Any]) -> Union[torch.Tensor, Any]: """ Prepares one `data` before feeding it to the model, be it a tensor or a nested list/dictionary of tensors. """ if isinstance(data, Mapping): return type(data)({k: self._prepare_input(v) ...
Prepares one `data` before feeding it to the model, be it a tensor or a nested list/dictionary of tensors.
_prepare_input
python
OptimalScale/LMFlow
src/lmflow/pipeline/utils/raft_trainer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/utils/raft_trainer.py
Apache-2.0
def _prepare_inputs(self, inputs: Dict[str, Union[torch.Tensor, Any]]) -> Dict[str, Union[torch.Tensor, Any]]: """ Prepare `inputs` before feeding them to the model, converting them to tensors if they are not already and handling potential state. """ inputs = self._prepare_input(...
Prepare `inputs` before feeding them to the model, converting them to tensors if they are not already and handling potential state.
_prepare_inputs
python
OptimalScale/LMFlow
src/lmflow/pipeline/utils/raft_trainer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/utils/raft_trainer.py
Apache-2.0
def autocast_smart_context_manager(self, cache_enabled: Optional[bool] = True): """ A helper wrapper that creates an appropriate context manager for `autocast` while feeding it the desired arguments, depending on the situation. """ if self.use_cuda_amp or self.use_cpu_amp: ...
A helper wrapper that creates an appropriate context manager for `autocast` while feeding it the desired arguments, depending on the situation.
autocast_smart_context_manager
python
OptimalScale/LMFlow
src/lmflow/pipeline/utils/raft_trainer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/utils/raft_trainer.py
Apache-2.0
def training_step(self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]]) -> torch.Tensor: """ Perform a training step on a batch of inputs. Subclass and override to inject custom behavior. Args: model (`nn.Module`): The model to train. ...
Perform a training step on a batch of inputs. Subclass and override to inject custom behavior. Args: model (`nn.Module`): The model to train. inputs (`Dict[str, Union[torch.Tensor, Any]]`): The inputs and targets of the model. ...
training_step
python
OptimalScale/LMFlow
src/lmflow/pipeline/utils/raft_trainer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/utils/raft_trainer.py
Apache-2.0
def compute_loss(self, model, inputs, return_outputs=False): """ How the loss is computed by Trainer. By default, all models return the loss in the first element. Subclass and override for custom behavior. """ if self.label_smoother is not None and "labels" in inputs: ...
How the loss is computed by Trainer. By default, all models return the loss in the first element. Subclass and override for custom behavior.
compute_loss
python
OptimalScale/LMFlow
src/lmflow/pipeline/utils/raft_trainer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/utils/raft_trainer.py
Apache-2.0
def is_world_process_zero(self) -> bool: """ Whether or not this process is the global main process (when training in a distributed fashion on several machines, this is only going to be `True` for one process). """ # Special case for SageMaker ModelParallel since there process_in...
Whether or not this process is the global main process (when training in a distributed fashion on several machines, this is only going to be `True` for one process).
is_world_process_zero
python
OptimalScale/LMFlow
src/lmflow/pipeline/utils/raft_trainer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/utils/raft_trainer.py
Apache-2.0
def save_model(self, output_dir: Optional[str] = None, _internal_call: bool = False): """ Will save the model, so you can reload it using `from_pretrained()`. Will only save from the main process. """ if output_dir is None: output_dir = self.args.output_dir ...
Will save the model, so you can reload it using `from_pretrained()`. Will only save from the main process.
save_model
python
OptimalScale/LMFlow
src/lmflow/pipeline/utils/raft_trainer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/utils/raft_trainer.py
Apache-2.0
def evaluate( self, eval_dataset: Optional[Dataset] = None, ignore_keys: Optional[List[str]] = None, metric_key_prefix: str = "eval", ) -> Dict[str, float]: """ Run evaluation and returns metrics. The calling script will be responsible for providing a method t...
Run evaluation and returns metrics. The calling script will be responsible for providing a method to compute metrics, as they are task-dependent (pass it to the init `compute_metrics` argument). You can also subclass and override this method to inject custom behavior. Args: ...
evaluate
python
OptimalScale/LMFlow
src/lmflow/pipeline/utils/raft_trainer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/utils/raft_trainer.py
Apache-2.0
def predict( self, test_dataset: Dataset, ignore_keys: Optional[List[str]] = None, metric_key_prefix: str = "test" ) -> PredictionOutput: """ Run prediction and returns predictions and potential metrics. Depending on the dataset and your use case, your test dataset may contain labels...
Run prediction and returns predictions and potential metrics. Depending on the dataset and your use case, your test dataset may contain labels. In that case, this method will also return metrics, like in `evaluate()`. Args: test_dataset (`Dataset`): Dataset t...
predict
python
OptimalScale/LMFlow
src/lmflow/pipeline/utils/raft_trainer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/utils/raft_trainer.py
Apache-2.0
def evaluation_loop( self, dataloader: DataLoader, description: str, prediction_loss_only: Optional[bool] = None, ignore_keys: Optional[List[str]] = None, metric_key_prefix: str = "eval", ) -> EvalLoopOutput: """ Prediction/evaluation loop, shared by `...
Prediction/evaluation loop, shared by `Trainer.evaluate()` and `Trainer.predict()`. Works both with or without labels.
evaluation_loop
python
OptimalScale/LMFlow
src/lmflow/pipeline/utils/raft_trainer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/utils/raft_trainer.py
Apache-2.0
def _nested_gather(self, tensors, name=None): """ Gather value of `tensors` (tensor or list/tuple of nested tensors) and convert them to numpy before concatenating them to `gathered` """ if tensors is None: return if is_torch_tpu_available(): if na...
Gather value of `tensors` (tensor or list/tuple of nested tensors) and convert them to numpy before concatenating them to `gathered`
_nested_gather
python
OptimalScale/LMFlow
src/lmflow/pipeline/utils/raft_trainer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/utils/raft_trainer.py
Apache-2.0
def _pad_across_processes(self, tensor, pad_index=-100): """ Recursively pad the tensors in a nested list/tuple/dictionary of tensors from all devices to the same size so they can safely be gathered. """ if isinstance(tensor, (list, tuple)): return type(tensor)(self._...
Recursively pad the tensors in a nested list/tuple/dictionary of tensors from all devices to the same size so they can safely be gathered.
_pad_across_processes
python
OptimalScale/LMFlow
src/lmflow/pipeline/utils/raft_trainer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/utils/raft_trainer.py
Apache-2.0
def prediction_step( self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]], prediction_loss_only: bool, ignore_keys: Optional[List[str]] = None, ) -> Tuple[Optional[torch.Tensor], Optional[torch.Tensor], Optional[torch.Tensor]]: """ Perform an ev...
Perform an evaluation step on `model` using `inputs`. Subclass and override to inject custom behavior. Args: model (`nn.Module`): The model to evaluate. inputs (`Dict[str, Union[torch.Tensor, Any]]`): The inputs and targets of the model. ...
prediction_step
python
OptimalScale/LMFlow
src/lmflow/pipeline/utils/raft_trainer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/utils/raft_trainer.py
Apache-2.0
def floating_point_ops(self, inputs: Dict[str, Union[torch.Tensor, Any]]): """ For models that inherit from [`PreTrainedModel`], uses that method to compute the number of floating point operations for every backward + forward pass. If using another model, either implement such a method in the ...
For models that inherit from [`PreTrainedModel`], uses that method to compute the number of floating point operations for every backward + forward pass. If using another model, either implement such a method in the model or subclass and override this method. Args: inputs (`D...
floating_point_ops
python
OptimalScale/LMFlow
src/lmflow/pipeline/utils/raft_trainer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/utils/raft_trainer.py
Apache-2.0
def init_git_repo(self, at_init: bool = False): """ Initializes a git repo in `self.args.hub_model_id`. Args: at_init (`bool`, *optional*, defaults to `False`): Whether this function is called before any training or not. If `self.args.overwrite_output_dir` is ...
Initializes a git repo in `self.args.hub_model_id`. Args: at_init (`bool`, *optional*, defaults to `False`): Whether this function is called before any training or not. If `self.args.overwrite_output_dir` is `True` and `at_init` is `True`, the path to the rep...
init_git_repo
python
OptimalScale/LMFlow
src/lmflow/pipeline/utils/raft_trainer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/utils/raft_trainer.py
Apache-2.0
def prediction_loop( self, dataloader: DataLoader, description: str, prediction_loss_only: Optional[bool] = None, ignore_keys: Optional[List[str]] = None, metric_key_prefix: str = "eval", ) -> EvalLoopOutput: """ Prediction/evaluation loop, shared by `...
Prediction/evaluation loop, shared by `Trainer.evaluate()` and `Trainer.predict()`. Works both with or without labels.
prediction_loop
python
OptimalScale/LMFlow
src/lmflow/pipeline/utils/raft_trainer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/utils/raft_trainer.py
Apache-2.0
def _gather_and_numpify(self, tensors, name): """ Gather value of `tensors` (tensor or list/tuple of nested tensors) and convert them to numpy before concatenating them to `gathered` """ if tensors is None: return if is_torch_tpu_available(): tenso...
Gather value of `tensors` (tensor or list/tuple of nested tensors) and convert them to numpy before concatenating them to `gathered`
_gather_and_numpify
python
OptimalScale/LMFlow
src/lmflow/pipeline/utils/raft_trainer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/utils/raft_trainer.py
Apache-2.0
def _add_sm_patterns_to_gitignore(self) -> None: """Add SageMaker Checkpointing patterns to .gitignore file.""" # Make sure we only do this on the main process if not self.is_world_process_zero(): return patterns = ["*.sagemaker-uploading", "*.sagemaker-uploaded"] #...
Add SageMaker Checkpointing patterns to .gitignore file.
_add_sm_patterns_to_gitignore
python
OptimalScale/LMFlow
src/lmflow/pipeline/utils/raft_trainer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/utils/raft_trainer.py
Apache-2.0
def text_to_textlist_tokenize_function( examples, data_args: DatasetArguments, tokenizer: Union[PreTrainedTokenizer, PreTrainedTokenizerFast], column_names, add_special_tokens, use_truncation, ) -> Dict: """For rm inference, and don't need attn mask and labels. NOTE: input_ids here refe...
For rm inference, and don't need attn mask and labels. NOTE: input_ids here refers to the tokenized input_ids of the input **and** output
text_to_textlist_tokenize_function
python
OptimalScale/LMFlow
src/lmflow/tokenization/hf_text_regression_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/tokenization/hf_text_regression_model.py
Apache-2.0
def make_shell_args_from_dataclass( dataclass_objects: List, format: str="subprocess", skip_default: bool=True, ignored_args_list: Optional[List[str]]=None, ) -> Union[str, List[str]]: """Return a string or a list of strings that can be used as shell arguments. Parameters ---------- da...
Return a string or a list of strings that can be used as shell arguments. Parameters ---------- dataclass_objects : List A list of dataclass objects. format : str, optional Return format, can be "shell" or "subprocess", by default "subprocess". skip_default : bool, optional ...
make_shell_args_from_dataclass
python
OptimalScale/LMFlow
src/lmflow/utils/common.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/utils/common.py
Apache-2.0
def create_copied_dataclass( original_dataclass, field_prefix: str, class_prefix: str, new_default: Dict=None ): """Create a copied dataclass with new field names and default values. Parameters ---------- original_dataclass : dataclass field_prefix : str The prefix to add...
Create a copied dataclass with new field names and default values. Parameters ---------- original_dataclass : dataclass field_prefix : str The prefix to add to the **field** names of the copied dataclass. class_prefix : str The prefix to add to the **class** name of the copied datac...
create_copied_dataclass
python
OptimalScale/LMFlow
src/lmflow/utils/common.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/utils/common.py
Apache-2.0
def remove_dataclass_attr_prefix(data_instance, prefix: str) -> Dict: """Remove the prefix from the attribute names of a dataclass instance. Parameters ---------- data_instance : dataclass prefix : str The prefix to remove from the attribute names of the dataclass instance. Returns ...
Remove the prefix from the attribute names of a dataclass instance. Parameters ---------- data_instance : dataclass prefix : str The prefix to remove from the attribute names of the dataclass instance. Returns ------- Dict
remove_dataclass_attr_prefix
python
OptimalScale/LMFlow
src/lmflow/utils/common.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/utils/common.py
Apache-2.0
def add_dataclass_attr_prefix(data_instance, prefix: str) -> Dict: """Add the prefix to the attribute names of a dataclass instance. Parameters ---------- data_instance : dataclass prefix : str The prefix to add to the attribute names of the dataclass instance. Returns ------- ...
Add the prefix to the attribute names of a dataclass instance. Parameters ---------- data_instance : dataclass prefix : str The prefix to add to the attribute names of the dataclass instance. Returns ------- Dict
add_dataclass_attr_prefix
python
OptimalScale/LMFlow
src/lmflow/utils/common.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/utils/common.py
Apache-2.0
def set_random_seed(seed: int): """ Set the random seed for `random`, `numpy`, `torch`, `torch.cuda`. Parameters ------------ seed : int The default seed. """ random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) if torch.cuda.is_available(): to...
Set the random seed for `random`, `numpy`, `torch`, `torch.cuda`. Parameters ------------ seed : int The default seed.
set_random_seed
python
OptimalScale/LMFlow
src/lmflow/utils/data_utils.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/utils/data_utils.py
Apache-2.0
def load_data(file_name: str): """ Load data with file name. Parameters ------------ file_name : str. The dataset file name. Returns ------------ inputs : list. The input texts of the dataset. outputs : list. The output texts file datasets. len :...
Load data with file name. Parameters ------------ file_name : str. The dataset file name. Returns ------------ inputs : list. The input texts of the dataset. outputs : list. The output texts file datasets. len : int. The length of the datase...
load_data
python
OptimalScale/LMFlow
src/lmflow/utils/data_utils.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/utils/data_utils.py
Apache-2.0
def batchlize(examples: list, batch_size: int, random_shuffle: bool): """ Convert examples to a dataloader. Parameters ------------ examples : list. Data list. batch_size : int. random_shuffle : bool If true, the dataloader shuffle the training data. Returns --...
Convert examples to a dataloader. Parameters ------------ examples : list. Data list. batch_size : int. random_shuffle : bool If true, the dataloader shuffle the training data. Returns ------------ dataloader: Dataloader with batch generator.
batchlize
python
OptimalScale/LMFlow
src/lmflow/utils/data_utils.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/utils/data_utils.py
Apache-2.0
def preview_file(file_path: str, chars: int = 100): """ Returns the first and last specified number of characters from a file without loading the entire file into memory, working with any file type. Args: file_path (str): Path to the file to be previewed chars (int, optional): Numbe...
Returns the first and last specified number of characters from a file without loading the entire file into memory, working with any file type. Args: file_path (str): Path to the file to be previewed chars (int, optional): Number of characters to show from start and end. Defaults to 100...
preview_file
python
OptimalScale/LMFlow
src/lmflow/utils/data_utils.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/utils/data_utils.py
Apache-2.0