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 __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 _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 |
def get_dataset_type_fast(file_path: str, max_chars: int = 100) -> Union[str, None]:
'''Get the type values from the first and last n lines of a large json dataset.
'''
file_content_preview = []
dataset_type = None
dataset_type_pattern = re.compile(r'[\"\']type[\"\']:\s*[\'\"]([^"]+)[\'\"]')
fil... | Get the type values from the first and last n lines of a large json dataset.
| get_dataset_type_fast | 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 check_dataset_instances_key_fast(file_path: str, instances_key: str, max_lines: int = 100) -> bool:
'''Check if the dataset instances key matches the instance_key.
'''
file_content_preview = []
instance_key_pattern = re.compile(r'[\"\']' + instances_key + r'[\"\']')
file_content_preview.extend(p... | Check if the dataset instances key matches the instance_key.
| check_dataset_instances_key_fast | 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 answer_extraction(response, answer_type=None): #use this funtion to extract answers from generated text
"""
Use this funtion to extract answers from generated text
Parameters
------------
args :
Arguments.
response : str
plain string response.
Returns
---------... |
Use this funtion to extract answers from generated text
Parameters
------------
args :
Arguments.
response : str
plain string response.
Returns
------------
answer:
Decoded answer (such as A, B, C, D, E for mutiple-choice QA).
| answer_extraction | 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 format(self, **kwargs) -> list:
"""Format the string components with the provided keyword arguments.
Mostly used for formatting system prompt, user and assistant messages.
Parameters
----------
**kwargs : dict
Keyword arguments containing values to replace in th... | Format the string components with the provided keyword arguments.
Mostly used for formatting system prompt, user and assistant messages.
Parameters
----------
**kwargs : dict
Keyword arguments containing values to replace in the template components.
Returns
... | format | python | OptimalScale/LMFlow | src/lmflow/utils/conversation_template/base.py | https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/utils/conversation_template/base.py | Apache-2.0 |
def encode_conversation(
self,
tokenizer: PreTrainedTokenizer,
messages: List[Dict[str, str]],
system: Optional[str] = None,
tools: Optional[List[str]] = None,
**kwargs
) -> Sequence[Tuple[List[int], List[int]]]:
r'''
Messages here should be guaranteed... |
Messages here should be guaranteed to be in pairs, with the first message being the user message and the second message being the system message.
Data example:
```json
{
"conversation_id": 2,
"system": "sysinfo1",
"tools": ["tool_1_desc"],
... | encode_conversation | python | OptimalScale/LMFlow | src/lmflow/utils/conversation_template/base.py | https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/utils/conversation_template/base.py | Apache-2.0 |
def _encode_template(
self,
template: List[TemplateComponent],
tokenizer: PreTrainedTokenizer,
**kwargs
) -> List[int]:
"""Encode template components into token ids.
Parameters
----------
template : List[TemplateComponent]
Formatted templ... | Encode template components into token ids.
Parameters
----------
template : List[TemplateComponent]
Formatted template components.
tokenizer : PreTrainedTokenizer
Tokenizer to convert tokens into token ids.
Returns
-------
List[int]
... | _encode_template | python | OptimalScale/LMFlow | src/lmflow/utils/conversation_template/base.py | https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/utils/conversation_template/base.py | Apache-2.0 |
def _ensure_id_list(self, obj: Union[int, List[int]]) -> List[int]:
'''Make sure the object is a list of integers. Useful for handling token ids.
'''
if isinstance(obj, int):
return [obj]
elif isinstance(obj, list):
return obj
else:
raise Value... | Make sure the object is a list of integers. Useful for handling token ids.
| _ensure_id_list | python | OptimalScale/LMFlow | src/lmflow/utils/conversation_template/base.py | https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/utils/conversation_template/base.py | Apache-2.0 |
def forward(ctx, qkv, bias=None, causal=False, softmax_scale=None):
"""
qkv: (batch, seqlen, 3, nheads, headdim)
bias: optional, shape broadcastible to (batch, nheads, seqlen, seqlen).
For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen).
... |
qkv: (batch, seqlen, 3, nheads, headdim)
bias: optional, shape broadcastible to (batch, nheads, seqlen, seqlen).
For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen).
ALiBi mask for non-causal would have shape (1, nheads, seqlen, seqlen)
... | forward | python | OptimalScale/LMFlow | src/lmflow/utils/flash_attention/triton_flash_attention.py | https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/utils/flash_attention/triton_flash_attention.py | Apache-2.0 |
def forward(ctx, q, kv, bias=None, causal=False, softmax_scale=None):
"""
q: (batch, seqlen_q, nheads, headdim)
kv: (batch, seqlen_k, 2, nheads, headdim)
bias: optional, shape broadcastible to (batch, nheads, seqlen_q, seqlen_k).
For example, ALiBi mask for ca... |
q: (batch, seqlen_q, nheads, headdim)
kv: (batch, seqlen_k, 2, nheads, headdim)
bias: optional, shape broadcastible to (batch, nheads, seqlen_q, seqlen_k).
For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen_k).
ALiBi mask for no... | forward | python | OptimalScale/LMFlow | src/lmflow/utils/flash_attention/triton_flash_attention.py | https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/utils/flash_attention/triton_flash_attention.py | Apache-2.0 |
def forward(ctx, q, k, v, bias=None, causal=False, softmax_scale=None):
"""
q: (batch_size, seqlen_q, nheads, headdim)
k, v: (batch_size, seqlen_k, nheads, headdim)
bias: optional, shape broadcastible to (batch, nheads, seqlen_q, seqlen_k).
For example, ALiBi ... |
q: (batch_size, seqlen_q, nheads, headdim)
k, v: (batch_size, seqlen_k, nheads, headdim)
bias: optional, shape broadcastible to (batch, nheads, seqlen_q, seqlen_k).
For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen_k).
ALiBi ma... | forward | python | OptimalScale/LMFlow | src/lmflow/utils/flash_attention/triton_flash_attention.py | https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/utils/flash_attention/triton_flash_attention.py | Apache-2.0 |
def find_abbreviation(
long_form_candidate: Span, short_form_candidate: Span
) -> Tuple[Span, Optional[Span]]:
"""
Implements the abbreviation detection algorithm in "A simple algorithm
for identifying abbreviation definitions in biomedical text.", (Schwartz & Hearst, 2003).
The algorithm works by ... |
Implements the abbreviation detection algorithm in "A simple algorithm
for identifying abbreviation definitions in biomedical text.", (Schwartz & Hearst, 2003).
The algorithm works by enumerating the characters in the short form of the abbreviation,
checking that they can be matched against characters... | find_abbreviation | python | allenai/scispacy | scispacy/abbreviation.py | https://github.com/allenai/scispacy/blob/master/scispacy/abbreviation.py | Apache-2.0 |
def find(self, span: Span, doc: Doc) -> Tuple[Span, Set[Span]]:
"""
Functional version of calling the matcher for a single span.
This method is helpful if you already have an abbreviation which
you want to find a definition for.
"""
dummy_matches = [(-1, int(span.start), ... |
Functional version of calling the matcher for a single span.
This method is helpful if you already have an abbreviation which
you want to find a definition for.
| find | python | allenai/scispacy | scispacy/abbreviation.py | https://github.com/allenai/scispacy/blob/master/scispacy/abbreviation.py | Apache-2.0 |
def make_short_form_serializable(self, abbreviation: Span):
"""
Converts the abbreviations into a short form that is serializable to enable multiprocessing
Parameters
----------
abbreviation: Span
The abbreviation span identified by the detector
"""
l... |
Converts the abbreviations into a short form that is serializable to enable multiprocessing
Parameters
----------
abbreviation: Span
The abbreviation span identified by the detector
| make_short_form_serializable | python | allenai/scispacy | scispacy/abbreviation.py | https://github.com/allenai/scispacy/blob/master/scispacy/abbreviation.py | Apache-2.0 |
def load_approximate_nearest_neighbours_index(
linker_paths: LinkerPaths,
ef_search: int = 200,
) -> FloatIndex:
"""
Load an approximate nearest neighbours index from disk.
Parameters
----------
linker_paths: LinkerPaths, required.
Contains the paths to the data required for the ent... |
Load an approximate nearest neighbours index from disk.
Parameters
----------
linker_paths: LinkerPaths, required.
Contains the paths to the data required for the entity linker.
ef_search: int, optional (default = 200)
Controls speed performance at query time. Max value is 2000,
... | load_approximate_nearest_neighbours_index | python | allenai/scispacy | scispacy/candidate_generation.py | https://github.com/allenai/scispacy/blob/master/scispacy/candidate_generation.py | Apache-2.0 |
def nmslib_knn_with_zero_vectors(
self, vectors: numpy.ndarray, k: int
) -> Tuple[numpy.ndarray, numpy.ndarray]:
"""
ann_index.knnQueryBatch crashes if any of the vectors is all zeros.
This function is a wrapper around `ann_index.knnQueryBatch` that solves this problem. It works as f... |
ann_index.knnQueryBatch crashes if any of the vectors is all zeros.
This function is a wrapper around `ann_index.knnQueryBatch` that solves this problem. It works as follows:
- remove empty vectors from `vectors`.
- call `ann_index.knnQueryBatch` with the non-empty vectors only. This re... | nmslib_knn_with_zero_vectors | python | allenai/scispacy | scispacy/candidate_generation.py | https://github.com/allenai/scispacy/blob/master/scispacy/candidate_generation.py | Apache-2.0 |
def __call__(
self, mention_texts: List[str], k: int
) -> List[List[MentionCandidate]]:
"""
Given a list of mention texts, returns a list of candidate neighbors.
NOTE: Because we include canonical name aliases in the ann index, the list
of candidates returned will not necess... |
Given a list of mention texts, returns a list of candidate neighbors.
NOTE: Because we include canonical name aliases in the ann index, the list
of candidates returned will not necessarily be of length k for each candidate,
because we then map these to canonical ids only.
NOTE... | __call__ | python | allenai/scispacy | scispacy/candidate_generation.py | https://github.com/allenai/scispacy/blob/master/scispacy/candidate_generation.py | Apache-2.0 |
def create_tfidf_ann_index(
out_path: str, kb: Optional[KnowledgeBase] = None
) -> Tuple[List[str], TfidfVectorizer, FloatIndex]:
"""
Build tfidf vectorizer and ann index.
Parameters
----------
out_path: str, required.
The path where the various model pieces will be saved.
kb : Know... |
Build tfidf vectorizer and ann index.
Parameters
----------
out_path: str, required.
The path where the various model pieces will be saved.
kb : KnowledgeBase, optional.
The kb items to generate the index and vectors for.
| create_tfidf_ann_index | python | allenai/scispacy | scispacy/candidate_generation.py | https://github.com/allenai/scispacy/blob/master/scispacy/candidate_generation.py | Apache-2.0 |
def pysbd_sentencizer(doc: Doc) -> Doc:
"""Adds sentence boundaries to a Doc.
Intended to be used as a pipe in a spaCy pipeline.
Uses https://github.com/nipunsadvilkar/pySBD to get proper sentence and
respective char_spans
Handle special cases:
New lines cannot be end of sentence tokens.
Ne... | Adds sentence boundaries to a Doc.
Intended to be used as a pipe in a spaCy pipeline.
Uses https://github.com/nipunsadvilkar/pySBD to get proper sentence and
respective char_spans
Handle special cases:
New lines cannot be end of sentence tokens.
New lines that separate sentences will be added t... | pysbd_sentencizer | python | allenai/scispacy | scispacy/custom_sentence_segmenter.py | https://github.com/allenai/scispacy/blob/master/scispacy/custom_sentence_segmenter.py | Apache-2.0 |
def remove_new_lines(text: str) -> str:
"""Used to preprocess away new lines in the middle of words. This function
is intended to be called on a raw string before it is passed through a
spaCy pipeline
@param text: a string of text to be processed
"""
text = text.replace("-\n\n", "")
t... | Used to preprocess away new lines in the middle of words. This function
is intended to be called on a raw string before it is passed through a
spaCy pipeline
@param text: a string of text to be processed
| remove_new_lines | python | allenai/scispacy | scispacy/custom_tokenizer.py | https://github.com/allenai/scispacy/blob/master/scispacy/custom_tokenizer.py | Apache-2.0 |
def process_example(lines: List[str]) -> MedMentionExample:
"""
Processes the text lines of a file corresponding to a single MedMention abstract,
extracts the title, abstract, pubmed id and entities. The lines of the file should
have the following format:
PMID | t | Title text
PMID | a | Abstrac... |
Processes the text lines of a file corresponding to a single MedMention abstract,
extracts the title, abstract, pubmed id and entities. The lines of the file should
have the following format:
PMID | t | Title text
PMID | a | Abstract text
PMID TAB StartIndex TAB EndIndex TAB MentionTextSegment ... | process_example | python | allenai/scispacy | scispacy/data_util.py | https://github.com/allenai/scispacy/blob/master/scispacy/data_util.py | Apache-2.0 |
def med_mentions_example_iterator(filename: str) -> Iterator[MedMentionExample]:
"""
Iterates over a Med Mentions file, yielding examples.
"""
with open(filename, "r", encoding="utf-8") as med_mentions_file:
lines = []
for line in med_mentions_file:
line = line.strip()
... |
Iterates over a Med Mentions file, yielding examples.
| med_mentions_example_iterator | python | allenai/scispacy | scispacy/data_util.py | https://github.com/allenai/scispacy/blob/master/scispacy/data_util.py | Apache-2.0 |
def select_subset_of_overlapping_chain(
chain: List[Tuple[int, int, str]]
) -> List[Tuple[int, int, str]]:
"""
Select the subset of entities in an overlapping chain to return by greedily choosing the
longest entity in the chain until there are no entities remaining
"""
sorted_chain = sorted(chai... |
Select the subset of entities in an overlapping chain to return by greedily choosing the
longest entity in the chain until there are no entities remaining
| select_subset_of_overlapping_chain | python | allenai/scispacy | scispacy/data_util.py | https://github.com/allenai/scispacy/blob/master/scispacy/data_util.py | Apache-2.0 |
def remove_overlapping_entities(
sorted_spacy_format_entities: List[Tuple[int, int, str]]
) -> List[Tuple[int, int, str]]:
"""
Removes overlapping entities from the entity set, by greedilytaking the longest
entity from each overlapping chain. The input list of entities should be sorted
and follow th... |
Removes overlapping entities from the entity set, by greedilytaking the longest
entity from each overlapping chain. The input list of entities should be sorted
and follow the spacy format.
| remove_overlapping_entities | python | allenai/scispacy | scispacy/data_util.py | https://github.com/allenai/scispacy/blob/master/scispacy/data_util.py | Apache-2.0 |
def _handle_sentence(examples: List[Tuple[str, str]]) -> SpacyNerExample:
"""
Processes a single sentence by building it up as a space separated string
with its corresponding typed entity spans.
"""
start_index = -1
current_index = 0
in_entity = False
entity_type: str = ""
sent = ""
... |
Processes a single sentence by building it up as a space separated string
with its corresponding typed entity spans.
| _handle_sentence | python | allenai/scispacy | scispacy/data_util.py | https://github.com/allenai/scispacy/blob/master/scispacy/data_util.py | Apache-2.0 |
def read_ner_from_tsv(filename: str) -> List[SpacyNerExample]:
"""
Reads BIO formatted NER data from a TSV file, such as the
NER data found here:
https://github.com/cambridgeltl/MTL-Bioinformatics-2016
Data is expected to be 2 tab seperated tokens per line, with
sentences denoted by empty lines... |
Reads BIO formatted NER data from a TSV file, such as the
NER data found here:
https://github.com/cambridgeltl/MTL-Bioinformatics-2016
Data is expected to be 2 tab seperated tokens per line, with
sentences denoted by empty lines. Sentences read by this
function will be already tokenized, but r... | read_ner_from_tsv | python | allenai/scispacy | scispacy/data_util.py | https://github.com/allenai/scispacy/blob/master/scispacy/data_util.py | Apache-2.0 |
def filename_to_url(filename: str, cache_dir: Optional[str] = None) -> Tuple[str, str]:
"""
Return the url and etag (which may be ``None``) stored for `filename`.
Raise ``FileNotFoundError`` if `filename` or its stored metadata do not exist.
"""
if cache_dir is None:
cache_dir = DATASET_CACH... |
Return the url and etag (which may be ``None``) stored for `filename`.
Raise ``FileNotFoundError`` if `filename` or its stored metadata do not exist.
| filename_to_url | python | allenai/scispacy | scispacy/file_cache.py | https://github.com/allenai/scispacy/blob/master/scispacy/file_cache.py | Apache-2.0 |
def expand_to_noun_compound(self, token: Token, doc: Doc):
"""
Expand a token to it's noun phrase based
on a simple POS tag heuristic.
"""
start = token.i
while True:
if start - 1 < 0:
break
previous_token = doc[start - 1]
... |
Expand a token to it's noun phrase based
on a simple POS tag heuristic.
| expand_to_noun_compound | python | allenai/scispacy | scispacy/hyponym_detector.py | https://github.com/allenai/scispacy/blob/master/scispacy/hyponym_detector.py | Apache-2.0 |
def __call__(self, doc: Doc):
"""
Runs the matcher on the Doc object and sets token and
doc level attributes for hypernym and hyponym relations.
"""
# Find matches in doc
matches = self.matcher(doc)
# If none are found then return None
if not matches:
... |
Runs the matcher on the Doc object and sets token and
doc level attributes for hypernym and hyponym relations.
| __call__ | python | allenai/scispacy | scispacy/hyponym_detector.py | https://github.com/allenai/scispacy/blob/master/scispacy/hyponym_detector.py | Apache-2.0 |
def get_metric(self, reset: bool = False):
"""
Returns
-------
A Dict per label containing following the span based metrics:
precision : float
recall : float
f1-measure : float
Additionally, an ``overall`` key is included, which provides the precision,
... |
Returns
-------
A Dict per label containing following the span based metrics:
precision : float
recall : float
f1-measure : float
Additionally, an ``overall`` key is included, which provides the precision,
recall and f1-measure for all spans.
| get_metric | python | allenai/scispacy | scispacy/per_class_scorer.py | https://github.com/allenai/scispacy/blob/master/scispacy/per_class_scorer.py | Apache-2.0 |
def get_children(self, node: SemanticTypeNode) -> List[SemanticTypeNode]:
"""
Recursively build up a flat list of all a node's children.
"""
children = []
for child in node.children:
children.append(child)
children.extend(self.get_children(child))
... |
Recursively build up a flat list of all a node's children.
| get_children | python | allenai/scispacy | scispacy/umls_semantic_type_tree.py | https://github.com/allenai/scispacy/blob/master/scispacy/umls_semantic_type_tree.py | Apache-2.0 |
def get_parent(self, node: SemanticTypeNode) -> Optional[SemanticTypeNode]:
"""
Returns the parent of the input node, returning None if the input node is the root of the tree
"""
current_depth = node.level
possible_parents = self.get_nodes_at_depth(current_depth - 1)
for... |
Returns the parent of the input node, returning None if the input node is the root of the tree
| get_parent | python | allenai/scispacy | scispacy/umls_semantic_type_tree.py | https://github.com/allenai/scispacy/blob/master/scispacy/umls_semantic_type_tree.py | Apache-2.0 |
def get_collapsed_type_id_map_at_level(self, level: int) -> Dict[str, str]:
"""
Constructs a label mapping from the original tree labels to a tree of a fixed depth,
collapsing labels greater than the depth specified to the closest parent which is
still present in the new fixed depth tree... |
Constructs a label mapping from the original tree labels to a tree of a fixed depth,
collapsing labels greater than the depth specified to the closest parent which is
still present in the new fixed depth tree. This is effectively mapping to a _coarser_
label space.
| get_collapsed_type_id_map_at_level | python | allenai/scispacy | scispacy/umls_semantic_type_tree.py | https://github.com/allenai/scispacy/blob/master/scispacy/umls_semantic_type_tree.py | Apache-2.0 |
def construct_umls_tree_from_tsv(filepath: str) -> UmlsSemanticTypeTree:
"""
Reads in a tsv file which is formatted as a depth first traversal of
a hierarchy tree, where nodes are of the format:
Name TAB UMLS Semantic Type TAB Tree Depth
Event T051 1
Activity T052 2
Behav... |
Reads in a tsv file which is formatted as a depth first traversal of
a hierarchy tree, where nodes are of the format:
Name TAB UMLS Semantic Type TAB Tree Depth
Event T051 1
Activity T052 2
Behavior T053 3
Social Behavior T054 4
Individual Beh... | construct_umls_tree_from_tsv | python | allenai/scispacy | scispacy/umls_semantic_type_tree.py | https://github.com/allenai/scispacy/blob/master/scispacy/umls_semantic_type_tree.py | Apache-2.0 |
def read_umls_file_headers(meta_path: str, filename: str) -> List[str]:
"""
Read the file descriptor MRFILES.RRF from a UMLS release and get column headers (names)
for the given file
MRFILES.RRF file format: a pipe-separated values
Useful columns:
column 0: name of one of the files in the M... |
Read the file descriptor MRFILES.RRF from a UMLS release and get column headers (names)
for the given file
MRFILES.RRF file format: a pipe-separated values
Useful columns:
column 0: name of one of the files in the META directory
column 2: column names of that file
Args:
me... | read_umls_file_headers | python | allenai/scispacy | scispacy/umls_utils.py | https://github.com/allenai/scispacy/blob/master/scispacy/umls_utils.py | Apache-2.0 |
def read_umls_concepts(
meta_path: str,
concept_details: Dict,
source: Optional[str] = None,
lang: str = "ENG",
non_suppressed: bool = True,
):
"""
Read the concepts file MRCONSO.RRF from a UMLS release and store it in
concept_details dictionary. Each concept is represented with
- co... |
Read the concepts file MRCONSO.RRF from a UMLS release and store it in
concept_details dictionary. Each concept is represented with
- concept_id
- canonical_name
- aliases
- types
- definition
This function fills the first three. If a canonical name is not found, it is left empty.
... | read_umls_concepts | python | allenai/scispacy | scispacy/umls_utils.py | https://github.com/allenai/scispacy/blob/master/scispacy/umls_utils.py | Apache-2.0 |
def read_umls_types(meta_path: str, concept_details: Dict):
"""
Read the types file MRSTY.RRF from a UMLS release and store it in
concept_details dictionary. This function adds the `types` field
to the information of each concept
MRSTY.RRF file format: a pipe-separated values
Useful columns: CU... |
Read the types file MRSTY.RRF from a UMLS release and store it in
concept_details dictionary. This function adds the `types` field
to the information of each concept
MRSTY.RRF file format: a pipe-separated values
Useful columns: CUI, TUI
Args:
meta_path: path to the META directory of ... | read_umls_types | python | allenai/scispacy | scispacy/umls_utils.py | https://github.com/allenai/scispacy/blob/master/scispacy/umls_utils.py | Apache-2.0 |
def read_umls_definitions(meta_path: str, concept_details: Dict):
"""
Read the types file MRDEF.RRF from a UMLS release and store it in
concept_details dictionary. This function adds the `definition` field
to the information of each concept
MRDEF.RRF file format: a pipe-separated values
Useful ... |
Read the types file MRDEF.RRF from a UMLS release and store it in
concept_details dictionary. This function adds the `definition` field
to the information of each concept
MRDEF.RRF file format: a pipe-separated values
Useful columns: CUI, SAB, SUPPRESS, DEF
Args:
meta_path: path to th... | read_umls_definitions | python | allenai/scispacy | scispacy/umls_utils.py | https://github.com/allenai/scispacy/blob/master/scispacy/umls_utils.py | Apache-2.0 |
def count_frequencies(language_class: Language, input_path: Path):
"""
Given a file containing single documents per line
(for scispacy, these are Pubmed abstracts), split the text
using a science specific tokenizer and compute word and
document frequencies for all words.
"""
print(f"Processi... |
Given a file containing single documents per line
(for scispacy, these are Pubmed abstracts), split the text
using a science specific tokenizer and compute word and
document frequencies for all words.
| count_frequencies | python | allenai/scispacy | scripts/count_word_frequencies.py | https://github.com/allenai/scispacy/blob/master/scripts/count_word_frequencies.py | Apache-2.0 |
def merge_counts(frequencies: List[Tuple[Counter, Counter]], output_path: str):
"""
Merge a number of frequency counts generated from `count_frequencies`
into a single file, written to `output_path`.
"""
counts = Counter()
doc_counts = Counter()
for word_count, doc_count in frequencies:
... |
Merge a number of frequency counts generated from `count_frequencies`
into a single file, written to `output_path`.
| merge_counts | python | allenai/scispacy | scripts/count_word_frequencies.py | https://github.com/allenai/scispacy/blob/master/scripts/count_word_frequencies.py | Apache-2.0 |
def get_spacy_model(
spacy_model_name: str,
pos_tags: bool,
parse: bool,
ner: bool,
with_custom_tokenizer: bool = False,
with_sentence_segmenter: bool = False,
with_serializable_abbreviation_detector: Optional[bool] = None,
) -> SpacyModelType:
"""
In order to avoid loading spacy mod... |
In order to avoid loading spacy models repeatedly,
we'll save references to them, keyed by the options
we used to create the spacy model, so any particular
configuration only gets loaded once.
| get_spacy_model | python | allenai/scispacy | tests/conftest.py | https://github.com/allenai/scispacy/blob/master/tests/conftest.py | Apache-2.0 |
def __call__(self, position: Position, rng_key: Optional[PRNGKey]) -> State:
"""Initialize the algorithm's state.
Parameters
----------
position
A chain position.
Returns
-------
The kernel state that corresponds to the position.
""" | Initialize the algorithm's state.
Parameters
----------
position
A chain position.
Returns
-------
The kernel state that corresponds to the position.
| __call__ | python | blackjax-devs/blackjax | blackjax/base.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/base.py | Apache-2.0 |
def __call__(self, rng_key: PRNGKey, state: State) -> tuple[State, Info]:
"""Update the current state using the sampling algorithm.
Parameters
----------
rng_key:
The random state used by JAX's random numbers generator.
state:
The current kernel state. Th... | Update the current state using the sampling algorithm.
Parameters
----------
rng_key:
The random state used by JAX's random numbers generator.
state:
The current kernel state. The kernel state contains the current
chain position as well as other infor... | __call__ | python | blackjax-devs/blackjax | blackjax/base.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/base.py | Apache-2.0 |
def potential_scale_reduction(
input_array: ArrayLike, chain_axis: int = 0, sample_axis: int = 1
) -> Array:
"""Gelman and Rubin (1992)'s potential scale reduction for computing multiple MCMC chain convergence.
Parameters
----------
input_array:
An array representing multiple chains of MCMC... | Gelman and Rubin (1992)'s potential scale reduction for computing multiple MCMC chain convergence.
Parameters
----------
input_array:
An array representing multiple chains of MCMC samples. The array must
contains a chain dimension and a sample dimension.
chain_axis
The axis indi... | potential_scale_reduction | python | blackjax-devs/blackjax | blackjax/diagnostics.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/diagnostics.py | Apache-2.0 |
def effective_sample_size(
input_array: ArrayLike, chain_axis: int = 0, sample_axis: int = 1
) -> Array:
"""Compute estimate of the effective sample size (ess).
Parameters
----------
input_array:
An array representing multiple chains of MCMC samples. The array must
contains a chain ... | Compute estimate of the effective sample size (ess).
Parameters
----------
input_array:
An array representing multiple chains of MCMC samples. The array must
contains a chain dimension and a sample dimension.
chain_axis
The axis indicating the multiple chains. Default to 0.
... | effective_sample_size | python | blackjax-devs/blackjax | blackjax/diagnostics.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/diagnostics.py | Apache-2.0 |
def _update_progress_bar(iter_num, chain_id):
"Updates progress bar of a JAX scan or loop"
chain_id = lax.cond(
# update every multiple of `print_rate` except at the end
(iter_num % print_rate == 0) | (iter_num == (num_samples - 1)),
lambda _: io_callback(_update_bar... | Updates progress bar of a JAX scan or loop | _update_progress_bar | python | blackjax-devs/blackjax | blackjax/progress_bar.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/progress_bar.py | Apache-2.0 |
def _progress_bar_scan(func):
"""Decorator that adds a progress bar to `body_fun` used in `lax.scan`.
Note that `body_fun` must either be looping over `np.arange(num_samples)`,
or be looping over a tuple who's first element is `np.arange(num_samples)`
This means that `iter_num` is the cu... | Decorator that adds a progress bar to `body_fun` used in `lax.scan`.
Note that `body_fun` must either be looping over `np.arange(num_samples)`,
or be looping over a tuple who's first element is `np.arange(num_samples)`
This means that `iter_num` is the current iteration number
| _progress_bar_scan | python | blackjax-devs/blackjax | blackjax/progress_bar.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/progress_bar.py | Apache-2.0 |
def linear_map(diag_or_dense_a, b, *, precision="highest"):
"""Perform a linear map of the form y = Ax.
Dispatch matrix multiplication to either jnp.dot or jnp.multiply.
Unlike jax.numpy.dot, this function output an Array that match the dtype
and shape of the 2nd input:
- diag_or_dense_a is a scal... | Perform a linear map of the form y = Ax.
Dispatch matrix multiplication to either jnp.dot or jnp.multiply.
Unlike jax.numpy.dot, this function output an Array that match the dtype
and shape of the 2nd input:
- diag_or_dense_a is a scalar or 1d vector, `diag_or_dense_a * b` is returned
- diag_or_de... | linear_map | python | blackjax-devs/blackjax | blackjax/util.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/util.py | Apache-2.0 |
def generate_gaussian_noise(
rng_key: PRNGKey,
position: ArrayLikeTree,
mu: Union[float, Array] = 0.0,
sigma: Union[float, Array] = 1.0,
) -> ArrayTree:
"""Generate N(mu, sigma) noise with output structure that match a given PyTree.
Parameters
----------
rng_key:
The pseudo-rand... | Generate N(mu, sigma) noise with output structure that match a given PyTree.
Parameters
----------
rng_key:
The pseudo-random number generator key used to generate random numbers.
position:
PyTree that the structure the output should to match.
mu:
The mean of the Gaussian di... | generate_gaussian_noise | python | blackjax-devs/blackjax | blackjax/util.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/util.py | Apache-2.0 |
def generate_unit_vector(
rng_key: PRNGKey,
position: ArrayLikeTree,
) -> Array:
"""Generate a random unit vector with output structure that match a given PyTree.
Parameters
----------
rng_key:
The pseudo-random number generator key used to generate random numbers.
position:
... | Generate a random unit vector with output structure that match a given PyTree.
Parameters
----------
rng_key:
The pseudo-random number generator key used to generate random numbers.
position:
PyTree that the structure the output should to match.
Returns
-------
Random unit ... | generate_unit_vector | python | blackjax-devs/blackjax | blackjax/util.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/util.py | Apache-2.0 |
def index_pytree(input_pytree: ArrayLikeTree) -> ArrayTree:
"""Builds a PyTree with elements indicating its corresponding index on a flat array.
Various algorithms in BlackJAX take as input a 1 or 2 dimensional array which somehow
affects the sampling or approximation of a PyTree. For instance, in HMC a 1 ... | Builds a PyTree with elements indicating its corresponding index on a flat array.
Various algorithms in BlackJAX take as input a 1 or 2 dimensional array which somehow
affects the sampling or approximation of a PyTree. For instance, in HMC a 1 or 2
dimensional inverse mass matrix is used when simulating Ha... | index_pytree | python | blackjax-devs/blackjax | blackjax/util.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/util.py | Apache-2.0 |
def run_inference_algorithm(
rng_key: PRNGKey,
inference_algorithm: Union[SamplingAlgorithm, VIAlgorithm],
num_steps: int,
initial_state: ArrayLikeTree = None,
initial_position: ArrayLikeTree = None,
progress_bar: bool = False,
transform: Callable = lambda state, info: (state, info),
) -> tu... | Wrapper to run an inference algorithm.
Note that this utility function does not work for Stochastic Gradient MCMC samplers
like sghmc, as SG-MCMC samplers require additional control flow for batches of data
to be passed in during each sample.
Parameters
----------
rng_key
The random st... | run_inference_algorithm | python | blackjax-devs/blackjax | blackjax/util.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/util.py | Apache-2.0 |
def store_only_expectation_values(
sampling_algorithm,
state_transform=lambda x: x,
incremental_value_transform=lambda x: x,
burn_in=0,
):
"""Takes a sampling algorithm and constructs from it a new sampling algorithm object. The new sampling algorithm has the same
kernel but only stores the str... | Takes a sampling algorithm and constructs from it a new sampling algorithm object. The new sampling algorithm has the same
kernel but only stores the streaming expectation values of some observables, not the full states; to save memory.
It saves incremental_value_transform(E[state_transform(x)]) at each step ... | store_only_expectation_values | python | blackjax-devs/blackjax | blackjax/util.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/util.py | Apache-2.0 |
def incremental_value_update(
expectation, incremental_val, weight=1.0, zero_prevention=0.0
):
"""Compute the streaming average of a function O(x) using a weight.
Parameters:
----------
expectation
the value of the expectation at the current timestep
incremental_val
... | Compute the streaming average of a function O(x) using a weight.
Parameters:
----------
expectation
the value of the expectation at the current timestep
incremental_val
tuple of (total, average) where total is the sum of weights and average is the current average
... | incremental_value_update | python | blackjax-devs/blackjax | blackjax/util.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/util.py | Apache-2.0 |
def adjusted_mclmc_find_L_and_step_size(
mclmc_kernel,
num_steps,
state,
rng_key,
target,
frac_tune1=0.1,
frac_tune2=0.1,
frac_tune3=0.0,
diagonal_preconditioning=True,
params=None,
max="avg",
num_windows=1,
tuning_factor=1.3,
):
"""
Finds the optimal value of... |
Finds the optimal value of the parameters for the MH-MCHMC algorithm.
Parameters
----------
mclmc_kernel
The kernel function used for the MCMC algorithm.
num_steps
The number of MCMC steps that will subsequently be run, after tuning.
state
The initial state of the MCMC ... | adjusted_mclmc_find_L_and_step_size | python | blackjax-devs/blackjax | blackjax/adaptation/adjusted_mclmc_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/adjusted_mclmc_adaptation.py | Apache-2.0 |
def adjusted_mclmc_make_L_step_size_adaptation(
kernel,
dim,
frac_tune1,
frac_tune2,
target,
diagonal_preconditioning,
fix_L_first_da=False,
max="avg",
tuning_factor=1.0,
):
"""Adapts the stepsize and L of the MCLMC kernel. Designed for adjusted MCLMC"""
def dual_avg_step(fi... | Adapts the stepsize and L of the MCLMC kernel. Designed for adjusted MCLMC | adjusted_mclmc_make_L_step_size_adaptation | python | blackjax-devs/blackjax | blackjax/adaptation/adjusted_mclmc_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/adjusted_mclmc_adaptation.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.