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 concatenated_inputs( batch: Dict[str, Union[List, torch.LongTensor]], is_encoder_decoder: bool = False, label_pad_token_id: int = -100, padding_value: int = 0, device: Optional[torch.device] = None, ) -> Dict[str, torch.LongTensor]: """Concatenate the chosen and r...
Concatenate the chosen and rejected inputs into a single tensor. Args: batch: A batch of data. Must contain the keys 'chosen_input_ids' and 'rejected_input_ids', which are tensors of shape (batch_size, sequence_length). is_encoder_decoder: Whether the model is an encoder-decoder model. ...
concatenated_inputs
python
NVlabs/VILA
llava/trl/trainer/dpo_trainer.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/trainer/dpo_trainer.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, ) -> Tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]: """Comput...
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
NVlabs/VILA
llava/trl/trainer/dpo_trainer.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/trainer/dpo_trainer.py
Apache-2.0
def get_batch_logps( logits: torch.FloatTensor, labels: torch.LongTensor, average_log_prob: bool = False, label_pad_token_id: int = -100, is_encoder_decoder: bool = False, ) -> torch.FloatTensor: """Compute the log probabilities of the given labels under the given log...
Compute the log probabilities of the given labels under the given logits. Args: logits: Logits of the model (unnormalized). Shape: (batch_size, sequence_length, vocab_size) labels: Labels for which to compute the log probabilities. Label tokens with a value of label_pad_token_id are ign...
get_batch_logps
python
NVlabs/VILA
llava/trl/trainer/dpo_trainer.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/trainer/dpo_trainer.py
Apache-2.0
def concatenated_forward( self, model: nn.Module, batch: Dict[str, Union[List, torch.LongTensor]] ) -> Tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]: """Run the given model on the given batch of inputs, concatenating the chosen and rejected inputs together. ...
Run the given model on the given batch of inputs, concatenating the chosen and rejected inputs together. We do this to avoid doing two forward passes, because it's faster for FSDP.
concatenated_forward
python
NVlabs/VILA
llava/trl/trainer/dpo_trainer.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/trainer/dpo_trainer.py
Apache-2.0
def get_batch_loss_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. CHANGE: 1. add sft loss 2. a...
Compute the DPO loss and other metrics for the given batch of inputs for train or test. CHANGE: 1. add sft loss 2. all gather metrics
get_batch_loss_metrics
python
NVlabs/VILA
llava/trl/trainer/dpo_trainer.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/trainer/dpo_trainer.py
Apache-2.0
def get_batch_samples(self, model, batch: Dict[str, torch.LongTensor]) -> Tuple[str, str]: """Generate samples from the model and reference model for the given batch of inputs.""" # If one uses `generate_during_eval` with peft + bf16, we need to explictly call generate with # the torch cuda amp...
Generate samples from the model and reference model for the given batch of inputs.
get_batch_samples
python
NVlabs/VILA
llava/trl/trainer/dpo_trainer.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/trainer/dpo_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: """ Overriding built-in evaluation loop to ...
Overriding built-in evaluation loop to store metrics for each batch. Prediction/evaluation loop, shared by `Trainer.evaluate()` and `Trainer.predict()`. Works both with or without labels.
evaluation_loop
python
NVlabs/VILA
llava/trl/trainer/dpo_trainer.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/trainer/dpo_trainer.py
Apache-2.0
def log(self, logs: Dict[str, float]) -> None: """ Log `logs` on the various objects watching training, including stored metrics. Args: logs (`Dict[str, float]`): The values to log. """ # logs either has 'loss' or 'eval_loss' train_eval = "tra...
Log `logs` on the various objects watching training, including stored metrics. Args: logs (`Dict[str, float]`): The values to log.
log
python
NVlabs/VILA
llava/trl/trainer/dpo_trainer.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/trainer/dpo_trainer.py
Apache-2.0
def push_to_hub(self, commit_message: Optional[str] = "End of training", blocking: bool = True, **kwargs) -> str: """ Overwrite the `push_to_hub` method in order to force-add the tag "sft" when pushing the model on the Hub. Please refer to `~transformers.Trainer.push_to_hub` for more details. ...
Overwrite the `push_to_hub` method in order to force-add the tag "sft" when pushing the model on the Hub. Please refer to `~transformers.Trainer.push_to_hub` for more details.
push_to_hub
python
NVlabs/VILA
llava/trl/trainer/dpo_trainer.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/trainer/dpo_trainer.py
Apache-2.0
def _step_safety_checker( input_ids: List[torch.LongTensor], attention_mask: List[torch.LongTensor], labels: List[torch.LongTensor], texts: List[str], texts_labels: List[str], ): """ Check if the input data is valid for training. Args: inp...
Check if the input data is valid for training. Args: input_ids (List[`torch.LongTensor`]): List of tensors containing the input_ids attention_mask (List[`torch.LongTensor`]): List of tensors containing the attention_mask labels (List[...
_step_safety_checker
python
NVlabs/VILA
llava/trl/trainer/iterative_sft_trainer.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/trainer/iterative_sft_trainer.py
Apache-2.0
def step( self, input_ids: Optional[List[torch.LongTensor]] = None, attention_mask: Optional[List[torch.LongTensor]] = None, labels: Optional[List[torch.LongTensor]] = None, texts: Optional[List[str]] = None, texts_labels: Optional[List[str]] = None, ): """ ...
Run an optimisation step given a list of input_ids, attention_mask, and labels or a list of text and text_labels. Args: input_ids (List[`torch.LongTensor`]): List of tensors containing the input_ids (if not provided, text will be used) attention_mask (List[`torch...
step
python
NVlabs/VILA
llava/trl/trainer/iterative_sft_trainer.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/trainer/iterative_sft_trainer.py
Apache-2.0
def __init__( self, config: PPOConfig = None, model: PreTrainedModelWrapper = None, ref_model: Optional[PreTrainedModelWrapper] = None, tokenizer: PreTrainedTokenizerBase = None, dataset: Optional[Union[torch.utils.data.Dataset, Dataset]] = None, optimizer: Option...
Initialize PPOTrainer. Args: config (`PPOConfig`): Configuration object for PPOTrainer. Check the documentation of `PPOConfig` for more details. model (`PreTrainedModelWrapper`): Hugging Face transformer model with a value head. ref_m...
__init__
python
NVlabs/VILA
llava/trl/trainer/ppo_trainer.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/trainer/ppo_trainer.py
Apache-2.0
def prepare_dataloader(self, dataset: Union[torch.utils.data.Dataset, Dataset], data_collator=None): """ Prepare the dataloader for training. Args: dataset (Union[`torch.utils.data.Dataset`, `datasets.Dataset`]): PyTorch dataset or Hugging Face dataset. If a Hugging ...
Prepare the dataloader for training. Args: dataset (Union[`torch.utils.data.Dataset`, `datasets.Dataset`]): PyTorch dataset or Hugging Face dataset. If a Hugging Face dataset is passed, the dataset will be preprocessed by removing the columns that are not us...
prepare_dataloader
python
NVlabs/VILA
llava/trl/trainer/ppo_trainer.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/trainer/ppo_trainer.py
Apache-2.0
def generate( self, query_tensor: Union[torch.Tensor, List[torch.Tensor]], length_sampler: Callable = None, batch_size: int = 4, return_prompt: bool = True, generate_ref_response: bool = False, **generation_kwargs, ): """ Generate response with...
Generate response with the model given the query tensor. call the `generate` method of the model. Args: query_tensor (`torch.LongTensor`): A tensor of shape (`seq_len`) containing query tokens or a list of tensors of shape (`seq_len`). length_sampler (`C...
generate
python
NVlabs/VILA
llava/trl/trainer/ppo_trainer.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/trainer/ppo_trainer.py
Apache-2.0
def _step_safety_checker( self, batch_size: int, queries: List[torch.LongTensor], responses: List[torch.LongTensor], scores: List[torch.FloatTensor], masks: Optional[List[torch.LongTensor]] = None, ): """ Check if the input data is valid for training. ...
Check if the input data is valid for training. Args: batch_size (int): Batch size from the config file. queries (List[`torch.LongTensor`]): List of tensors containing the encoded queries of shape (`query_length`) responses (List[`torc...
_step_safety_checker
python
NVlabs/VILA
llava/trl/trainer/ppo_trainer.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/trainer/ppo_trainer.py
Apache-2.0
def step( self, queries: List[torch.LongTensor], responses: List[torch.LongTensor], scores: List[torch.FloatTensor], response_masks: Optional[List[torch.LongTensor]] = None, ): """ Run a PPO optimisation step given a list of queries, model responses, and rewar...
Run a PPO optimisation step given a list of queries, model responses, and rewards. Args: queries (List[`torch.LongTensor`]): List of tensors containing the encoded queries of shape (`query_length`) responses (List[`torch.LongTensor`]): List of te...
step
python
NVlabs/VILA
llava/trl/trainer/ppo_trainer.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/trainer/ppo_trainer.py
Apache-2.0
def _early_stop(self, policykl): r""" Handles the early stopping logic. If the policy KL is greater than the target KL, then the gradient is zeroed and the optimization step is skipped. This also handles the multi-gpu case where the policy KL is averaged across all processes. Ar...
Handles the early stopping logic. If the policy KL is greater than the target KL, then the gradient is zeroed and the optimization step is skipped. This also handles the multi-gpu case where the policy KL is averaged across all processes. Args: policy_kl (torch.Tensor): ...
_early_stop
python
NVlabs/VILA
llava/trl/trainer/ppo_trainer.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/trainer/ppo_trainer.py
Apache-2.0
def gather_stats(self, stats): """ Gather stats from all processes. Useful in the context of distributed training. Args: stats (dict[str, Any]): a dictionary of stats to be gathered. The stats should contain torch tensors. Returns: `dict[str, Any]`: ...
Gather stats from all processes. Useful in the context of distributed training. Args: stats (dict[str, Any]): a dictionary of stats to be gathered. The stats should contain torch tensors. Returns: `dict[str, Any]`: A dictionary of stats with the tensors gat...
gather_stats
python
NVlabs/VILA
llava/trl/trainer/ppo_trainer.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/trainer/ppo_trainer.py
Apache-2.0
def batched_forward_pass( self, model: PreTrainedModelWrapper, queries: torch.Tensor, responses: torch.Tensor, model_inputs: dict, return_logits: bool = False, response_masks: Optional[torch.Tensor] = None, ): """ Calculate model outputs in mul...
Calculate model outputs in multiple batches. Args: queries (`torch.LongTensor`): List of tensors containing the encoded queries, shape (`batch_size`, `query_length`) responses (`torch.LongTensor`): List of tensors containing the encoded responses...
batched_forward_pass
python
NVlabs/VILA
llava/trl/trainer/ppo_trainer.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/trainer/ppo_trainer.py
Apache-2.0
def train_minibatch( self, old_logprobs: torch.FloatTensor, values: torch.FloatTensor, logprobs: torch.FloatTensor, logits: torch.FloatTensor, vpreds: torch.FloatTensor, mask: torch.LongTensor, advantages: torch.FloatTensor, returns: torch.FloatTen...
Train one PPO minibatch Args: logprobs (`torch.FloatTensor`): Log probabilities of the model, shape [mini_batch_size, response_length] values (`torch.FloatTensor`): Values of the value head, shape [mini_batch_size, response_length] qu...
train_minibatch
python
NVlabs/VILA
llava/trl/trainer/ppo_trainer.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/trainer/ppo_trainer.py
Apache-2.0
def compute_rewards( self, scores: torch.FloatTensor, logprobs: torch.FloatTensor, ref_logprobs: torch.FloatTensor, masks: torch.LongTensor, ): """ Compute per token rewards from scores and KL-penalty. Args: scores (`torch.FloatTensor`): ...
Compute per token rewards from scores and KL-penalty. Args: scores (`torch.FloatTensor`): Scores from the reward model, shape (`batch_size`) logprobs (`torch.FloatTensor`): Log probabilities of the model, shape (`batch_size`, `response_length`) ...
compute_rewards
python
NVlabs/VILA
llava/trl/trainer/ppo_trainer.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/trainer/ppo_trainer.py
Apache-2.0
def loss( self, old_logprobs: torch.FloatTensor, values: torch.FloatTensor, logits: torch.FloatTensor, vpreds: torch.FloatTensor, logprobs: torch.FloatTensor, mask: torch.LongTensor, advantages: torch.FloatTensor, returns: torch.FloatTensor, ):...
Calculate policy and value losses. Args: old_logprobs (`torch.FloatTensor`): Log probabilities of the model, shape (`batch_size`, `response_length`) values (`torch.FloatTensor`): Values of the value head, shape (`batch_size`, `response_length`) ...
loss
python
NVlabs/VILA
llava/trl/trainer/ppo_trainer.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/trainer/ppo_trainer.py
Apache-2.0
def record_step_stats(self, kl_coef: float, **data): """ Record training step statistics. Args: kl_coef (`float`): KL coefficient data (`dict`): Dictionary of training step data Returns: stats (`dict`): ...
Record training step statistics. Args: kl_coef (`float`): KL coefficient data (`dict`): Dictionary of training step data Returns: stats (`dict`): Dictionary of training step statistics
record_step_stats
python
NVlabs/VILA
llava/trl/trainer/ppo_trainer.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/trainer/ppo_trainer.py
Apache-2.0
def log_stats( self, stats: dict, batch: dict, rewards: List[torch.FloatTensor], columns_to_log: List[str] = ["query", "response"], ): """ A function that logs all the training stats. Call it at the end of each epoch. Args: stats (dict[str...
A function that logs all the training stats. Call it at the end of each epoch. Args: stats (dict[str, Any]): A dictionary of training stats. batch (dict[str, Any]): A dictionary of batch data, this contains the queries and responses. ...
log_stats
python
NVlabs/VILA
llava/trl/trainer/ppo_trainer.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/trainer/ppo_trainer.py
Apache-2.0
def create_model_card(self, path: str, model_name: Optional[str] = "TRL Model") -> None: """Creates and saves a model card for a TRL model. Args: path (`str`): The path to save the model card to. model_name (`str`, *optional*): The name of the model, defaults to `TRL Model`. ...
Creates and saves a model card for a TRL model. Args: path (`str`): The path to save the model card to. model_name (`str`, *optional*): The name of the model, defaults to `TRL Model`.
create_model_card
python
NVlabs/VILA
llava/trl/trainer/ppo_trainer.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/trainer/ppo_trainer.py
Apache-2.0
def __init__( self, model: Union[PreTrainedModel, nn.Module] = None, args: Optional[RewardConfig] = None, data_collator: Optional[DataCollator] = None, train_dataset: Optional[Dataset] = None, eval_dataset: Optional[Union[Dataset, Dict[str, Dataset]]] = None, toke...
Initialize RewardTrainer. Args: model (`transformers.PreTrainedModel`): The model to train, preferably an `AutoModelForSequenceClassification`. args (`RewardConfig`): The arguments to use for training. data_collator (`transformers.Dat...
__init__
python
NVlabs/VILA
llava/trl/trainer/reward_trainer.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/trainer/reward_trainer.py
Apache-2.0
def _trl_activate_neftune(self, model): r""" Activates the neftune as presented in this code: https://github.com/neelsjain/NEFTune and paper: https://arxiv.org/abs/2310.05914 Since in transformers Trainer we do have an `_activate_neftune` method, we need to rename this method to avoid conflicts....
Activates the neftune as presented in this code: https://github.com/neelsjain/NEFTune and paper: https://arxiv.org/abs/2310.05914 Since in transformers Trainer we do have an `_activate_neftune` method, we need to rename this method to avoid conflicts.
_trl_activate_neftune
python
NVlabs/VILA
llava/trl/trainer/sft_trainer.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/trainer/sft_trainer.py
Apache-2.0
def __init__(self, accelerator): """ Calculates the running mean and standard deviation of a data stream. Reference: https://github.com/OpenLMLab/MOSS-RLHF/blob/40b91eb2f2b71b16919addede0341d2bef70825d/utils.py#L75 """ self.mean = 0 self.std = 1 self.var = 1 ...
Calculates the running mean and standard deviation of a data stream. Reference: https://github.com/OpenLMLab/MOSS-RLHF/blob/40b91eb2f2b71b16919addede0341d2bef70825d/utils.py#L75
__init__
python
NVlabs/VILA
llava/trl/trainer/utils.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/trainer/utils.py
Apache-2.0
def update(self, xs: torch.Tensor) -> Tuple[float, float]: """ Updates running moments from batch's moments computed across ranks """ if self.accelerator.use_distributed: xs_mean, xs_var, xs_count = get_global_statistics(self.accelerator, xs) else: xs_coun...
Updates running moments from batch's moments computed across ranks
update
python
NVlabs/VILA
llava/trl/trainer/utils.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/trainer/utils.py
Apache-2.0
def get_global_statistics(accelerator, xs: torch.Tensor, mask=None, device="cpu") -> Tuple[float, float, int]: """ Computes element-wise mean and variance of the tensor across processes. Reference: https://github.com/OpenLMLab/MOSS-RLHF/blob/40b91eb2f2b71b16919addede0341d2bef70825d/utils.py#L57C1-L73C75 ...
Computes element-wise mean and variance of the tensor across processes. Reference: https://github.com/OpenLMLab/MOSS-RLHF/blob/40b91eb2f2b71b16919addede0341d2bef70825d/utils.py#L57C1-L73C75
get_global_statistics
python
NVlabs/VILA
llava/trl/trainer/utils.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/trainer/utils.py
Apache-2.0
def neftune_post_forward_hook(module, input, output): """ Implements the NEFTune forward pass for the model using forward hooks. Note this works only for torch.nn.Embedding layers. This method is slightly adapted from the original source code that can be found here: https://github.com/neelsjain/NEFTune ...
Implements the NEFTune forward pass for the model using forward hooks. Note this works only for torch.nn.Embedding layers. This method is slightly adapted from the original source code that can be found here: https://github.com/neelsjain/NEFTune Simply add it to your model as follows: ```python ...
neftune_post_forward_hook
python
NVlabs/VILA
llava/trl/trainer/utils.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/trainer/utils.py
Apache-2.0
def compute_file_md5sum(fname: Union[str, BinaryIO], chunksize: int = 1000000) -> str: """Compute the md5sum of a file in chunks. Parameters ---------- fname : Union[str, BinaryIO] Filename or file object chunksize : int, optional Chunk size in bytes, by default 1000000 Returns...
Compute the md5sum of a file in chunks. Parameters ---------- fname : Union[str, BinaryIO] Filename or file object chunksize : int, optional Chunk size in bytes, by default 1000000 Returns ------- str MD5 sum of the file Examples -------- >>> compute_fi...
compute_file_md5sum
python
NVlabs/VILA
llava/wids/wids.py
https://github.com/NVlabs/VILA/blob/master/llava/wids/wids.py
Apache-2.0
def compute_file_md5sum(fname: Union[str, BinaryIO], chunksize: int = 1000000) -> str: """Compute the md5sum of a file in chunks.""" md5 = hashlib.md5() if isinstance(fname, str): with open(fname, "rb") as f: for chunk in iter(lambda: f.read(chunksize), b""): md5.update(c...
Compute the md5sum of a file in chunks.
compute_file_md5sum
python
NVlabs/VILA
llava/wids/wids.py
https://github.com/NVlabs/VILA/blob/master/llava/wids/wids.py
Apache-2.0
def splitname(fname): """Returns the basename and extension of a filename""" assert "." in fname, "Filename must have an extension" # basename, extension = re.match(r"^((?:.*/)?.*?)(\..*)$", fname).groups() # wids v1: # basename, extension = os.path.splitext(fname) # wids v2: # fit MMDU mu...
Returns the basename and extension of a filename
splitname
python
NVlabs/VILA
llava/wids/wids.py
https://github.com/NVlabs/VILA/blob/master/llava/wids/wids.py
Apache-2.0
def group_by_key(names): """Group the file names by key. Args: names: A list of file names. Returns: A list of lists of indices, where each sublist contains indices of files with the same key. """ groups = [] kmaps = {} for i, fname in enumerate(names): # Ig...
Group the file names by key. Args: names: A list of file names. Returns: A list of lists of indices, where each sublist contains indices of files with the same key.
group_by_key
python
NVlabs/VILA
llava/wids/wids.py
https://github.com/NVlabs/VILA/blob/master/llava/wids/wids.py
Apache-2.0
def default_decoder(sample: Dict[str, Any], format: Optional[Union[bool, str]] = True): """A default decoder for webdataset. This handles common file extensions: .txt, .cls, .cls2, .jpg, .png, .json, .npy, .mp, .pt, .pth, .pickle, .pkl. These are the most common extensions used in webdataset. F...
A default decoder for webdataset. This handles common file extensions: .txt, .cls, .cls2, .jpg, .png, .json, .npy, .mp, .pt, .pth, .pickle, .pkl. These are the most common extensions used in webdataset. For other extensions, users can provide their own decoder. Args: sample: sample, mo...
default_decoder
python
NVlabs/VILA
llava/wids/wids.py
https://github.com/NVlabs/VILA/blob/master/llava/wids/wids.py
Apache-2.0
def f(shard): """Given a URL, return a local name for the shard.""" if shard.startswith("pipe:"): # uuencode the entire URL string hex32 = base64.urlsafe_b64encode(hashlib.sha256(shard.encode()).digest())[:32].decode() return os.path.join(dldir, "pipe__" + hex32) ...
Given a URL, return a local name for the shard.
f
python
NVlabs/VILA
llava/wids/wids.py
https://github.com/NVlabs/VILA/blob/master/llava/wids/wids.py
Apache-2.0
def interpret_transformations(transformations): """Interpret the transformations argument. This takes care of transformations specified as string shortcuts and returns a list of callables. """ if not isinstance(transformations, list): transformations = [transformations] result = [] ...
Interpret the transformations argument. This takes care of transformations specified as string shortcuts and returns a list of callables.
interpret_transformations
python
NVlabs/VILA
llava/wids/wids.py
https://github.com/NVlabs/VILA/blob/master/llava/wids/wids.py
Apache-2.0
def hash_dataset_name(input_string): """Compute a hash of the input string and return the first 16 characters of the hash.""" # Compute SHA256 hash of the input string hash_object = hashlib.sha256(input_string.encode()) hash_digest = hash_object.digest() # Encode the hash in base64 base64_encod...
Compute a hash of the input string and return the first 16 characters of the hash.
hash_dataset_name
python
NVlabs/VILA
llava/wids/wids.py
https://github.com/NVlabs/VILA/blob/master/llava/wids/wids.py
Apache-2.0
def __init__( self, shards, *, cache_size=int(1e12), cache_dir=None, lru_size=10, dataset_name=None, localname=None, transformations="PIL", keep=False, base=None, options=None, ): """Create a ShardListDataset. ...
Create a ShardListDataset. Args: shards: a list of (filename, length) pairs or a URL pointing to a JSON descriptor file cache_size: the number of shards to keep in the cache lru_size: the number of shards to keep in the LRU cache localname: a function that maps U...
__init__
python
NVlabs/VILA
llava/wids/wids.py
https://github.com/NVlabs/VILA/blob/master/llava/wids/wids.py
Apache-2.0
def check_cache_misses(self): """Check if the cache miss rate is too high.""" accesses, misses = self.get_stats() if accesses > 100 and misses / accesses > 0.3: # output a warning only once self.check_cache_misses = lambda: None print(f"Warning: ShardListDatas...
Check if the cache miss rate is too high.
check_cache_misses
python
NVlabs/VILA
llava/wids/wids.py
https://github.com/NVlabs/VILA/blob/master/llava/wids/wids.py
Apache-2.0
def get_shard(self, index): """Get the shard and index within the shard corresponding to the given index.""" # Find the shard corresponding to the given index. shard_idx = np.searchsorted(self.cum_lengths, index, side="right") # Figure out which index within the shard corresponds to the...
Get the shard and index within the shard corresponding to the given index.
get_shard
python
NVlabs/VILA
llava/wids/wids.py
https://github.com/NVlabs/VILA/blob/master/llava/wids/wids.py
Apache-2.0
def __getitem__(self, index): """Return the sample corresponding to the given index.""" shard, inner_idx, desc = self.get_shard(index) sample = shard[inner_idx] # Check if we're missing the cache too often. self.check_cache_misses() sample["__dataset__"] = desc.get("dat...
Return the sample corresponding to the given index.
__getitem__
python
NVlabs/VILA
llava/wids/wids.py
https://github.com/NVlabs/VILA/blob/master/llava/wids/wids.py
Apache-2.0
def lengths_to_ranges(lengths): """Convert a list of lengths to a list of ranges.""" ranges = [] start = 0 for length in lengths: ranges.append((start, start + length)) start += length return ranges
Convert a list of lengths to a list of ranges.
lengths_to_ranges
python
NVlabs/VILA
llava/wids/wids.py
https://github.com/NVlabs/VILA/blob/master/llava/wids/wids.py
Apache-2.0
def intersect_range(a, b): """Return the intersection of the two half-open integer intervals.""" result = max(a[0], b[0]), min(a[1], b[1]) if result[0] >= result[1]: return None return result
Return the intersection of the two half-open integer intervals.
intersect_range
python
NVlabs/VILA
llava/wids/wids.py
https://github.com/NVlabs/VILA/blob/master/llava/wids/wids.py
Apache-2.0
def intersect_ranges(rangelist, r): """Return the intersection of the half-open integer interval r with the list of half-open integer intervals.""" result = [] for a in rangelist: x = intersect_range(a, r) if x is not None: result.append(x) return result
Return the intersection of the half-open integer interval r with the list of half-open integer intervals.
intersect_ranges
python
NVlabs/VILA
llava/wids/wids.py
https://github.com/NVlabs/VILA/blob/master/llava/wids/wids.py
Apache-2.0
def iterate_ranges(ranges, rng, indexshuffle=True, shardshuffle=True): """Iterate over the ranges in a random order.""" shard_indexes = list(range(len(ranges))) if shardshuffle: rng.shuffle(shard_indexes) for i in shard_indexes: lo, hi = ranges[i] sample_indexes = list(range(lo, ...
Iterate over the ranges in a random order.
iterate_ranges
python
NVlabs/VILA
llava/wids/wids.py
https://github.com/NVlabs/VILA/blob/master/llava/wids/wids.py
Apache-2.0
def DistributedChunkedSampler( dataset: Dataset, *, num_replicas: Optional[int] = None, num_samples: Optional[int] = None, rank: Optional[int] = None, shuffle: bool = True, shufflefirst: bool = False, seed: int = 0, drop_last: bool = None, chunksize: int = 1000000, ) -> ChunkedSa...
Return a ChunkedSampler for the current worker in distributed training. Reverts to a simple ChunkedSampler if not running in distributed mode. Since the split among workers takes place before the chunk shuffle, workers end up with a fixed set of shards they need to download. The more workers, the fewe...
DistributedChunkedSampler
python
NVlabs/VILA
llava/wids/wids.py
https://github.com/NVlabs/VILA/blob/master/llava/wids/wids.py
Apache-2.0
def keep_most_recent_files(pattern, maxsize=int(1e12), maxfiles=1000, debug=False): """Keep the most recent files in a directory, deleting the rest. The maxsize is the maximum size of the directory in bytes. The maxfiles is the maximum number of files to keep. The files are sorted by modification time,...
Keep the most recent files in a directory, deleting the rest. The maxsize is the maximum size of the directory in bytes. The maxfiles is the maximum number of files to keep. The files are sorted by modification time, and the most recent files are kept. If the directory is already smaller than maxsize, ...
keep_most_recent_files
python
NVlabs/VILA
llava/wids/wids_cleanup.py
https://github.com/NVlabs/VILA/blob/master/llava/wids/wids_cleanup.py
Apache-2.0
def create_cleanup_background_process(pattern, maxsize=int(1e12), maxfiles=1000, every=60): """Create a background process that keeps a directory below a certain size.""" def cleanup_worker(every): # use a lock file to ensure that only one cleanup worker is running lockfile = os.path.join(os.pa...
Create a background process that keeps a directory below a certain size.
create_cleanup_background_process
python
NVlabs/VILA
llava/wids/wids_cleanup.py
https://github.com/NVlabs/VILA/blob/master/llava/wids/wids_cleanup.py
Apache-2.0
def download_file_no_log(remote, local, handlers=default_cmds): """Download a file from a remote url to a local path. The remote url can be a pipe: url, in which case the remainder of the url is treated as a command template that is executed to perform the download. """ if remote.startswith("pipe:"...
Download a file from a remote url to a local path. The remote url can be a pipe: url, in which case the remainder of the url is treated as a command template that is executed to perform the download.
download_file_no_log
python
NVlabs/VILA
llava/wids/wids_dl.py
https://github.com/NVlabs/VILA/blob/master/llava/wids/wids_dl.py
Apache-2.0
def urldir(url): """Return the directory part of a url.""" parsed_url = urlparse(url) path = parsed_url.path directory = os.path.dirname(path) return parsed_url._replace(path=directory).geturl()
Return the directory part of a url.
urldir
python
NVlabs/VILA
llava/wids/wids_index.py
https://github.com/NVlabs/VILA/blob/master/llava/wids/wids_index.py
Apache-2.0
def urlfile(url): """Return the file part of a url.""" parsed_url = urlparse(url) path = parsed_url.path filename = os.path.basename(path) return filename
Return the file part of a url.
urlfile
python
NVlabs/VILA
llava/wids/wids_index.py
https://github.com/NVlabs/VILA/blob/master/llava/wids/wids_index.py
Apache-2.0
def main_create(args): """Create a full shard index for a list of files.""" # set default output file name if args.output is None: args.output = "shardindex.json" if args.name is None: first = os.path.splitext(args.files[0])[0] args.name = shorten_name(first) print("sett...
Create a full shard index for a list of files.
main_create
python
NVlabs/VILA
llava/wids/wids_index.py
https://github.com/NVlabs/VILA/blob/master/llava/wids/wids_index.py
Apache-2.0
def main_info(args): """Show info about an index file.""" if args.table: print("file\tname\tnbytes\tnsamples\tbase\tlast\tdatasets") for filename in args.filenames: data = load_remote_dsdesc_raw(filename) print( filename, data.get("name"), ...
Show info about an index file.
main_info
python
NVlabs/VILA
llava/wids/wids_index.py
https://github.com/NVlabs/VILA/blob/master/llava/wids/wids_index.py
Apache-2.0
def main(): """Commands for manipulating the shard index.""" # Create the top-level parser parser = argparse.ArgumentParser(description="Command line tool with subcommands for file operations.") subparsers = parser.add_subparsers(dest="command", required=True, help="Subcommands") # Create the parse...
Commands for manipulating the shard index.
main
python
NVlabs/VILA
llava/wids/wids_index.py
https://github.com/NVlabs/VILA/blob/master/llava/wids/wids_index.py
Apache-2.0
def __init__(self, capacity: int, release_handler=None): """Initialize a new LRU cache with the given capacity.""" self.capacity = capacity self.cache = OrderedDict() self.release_handler = release_handler
Initialize a new LRU cache with the given capacity.
__init__
python
NVlabs/VILA
llava/wids/wids_lru.py
https://github.com/NVlabs/VILA/blob/master/llava/wids/wids_lru.py
Apache-2.0
def __getitem__(self, key): """Return the value associated with the given key, or None.""" if key not in self.cache: return None self.cache.move_to_end(key) return self.cache[key]
Return the value associated with the given key, or None.
__getitem__
python
NVlabs/VILA
llava/wids/wids_lru.py
https://github.com/NVlabs/VILA/blob/master/llava/wids/wids_lru.py
Apache-2.0
def __setitem__(self, key, value): """Associate the given value with the given key.""" if key in self.cache: self.cache.move_to_end(key) self.cache[key] = value if len(self.cache) > self.capacity: key, value = self.cache.popitem(last=False) if self.rel...
Associate the given value with the given key.
__setitem__
python
NVlabs/VILA
llava/wids/wids_lru.py
https://github.com/NVlabs/VILA/blob/master/llava/wids/wids_lru.py
Apache-2.0
def __delitem__(self, key): """Remove the given key from the cache.""" if key in self.cache: if self.release_handler is not None: value = self.cache[key] self.release_handler(key, value) del self.cache[key]
Remove the given key from the cache.
__delitem__
python
NVlabs/VILA
llava/wids/wids_lru.py
https://github.com/NVlabs/VILA/blob/master/llava/wids/wids_lru.py
Apache-2.0
def keep_while_reading(fname, fd, phase, delay=0.0): """This is a possible cleanup callback for cleanup_callback of MIndexedTar. It assumes that as long as there are some readers for a file, more readers may be trying to open it. Note that on Linux, unlinking the file doesn't matter after it has b...
This is a possible cleanup callback for cleanup_callback of MIndexedTar. It assumes that as long as there are some readers for a file, more readers may be trying to open it. Note that on Linux, unlinking the file doesn't matter after it has been mmapped. The contents will only be deleted when all ...
keep_while_reading
python
NVlabs/VILA
llava/wids/wids_mmtar.py
https://github.com/NVlabs/VILA/blob/master/llava/wids/wids_mmtar.py
Apache-2.0
def urlmerge(base, url): """Merge a base URL and a relative URL. The function fills in any missing part of the url from the base, except for params, query, and fragment, which are taken only from the 'url'. For the pathname component, it merges the paths like os.path.join: an absolute path in 'url'...
Merge a base URL and a relative URL. The function fills in any missing part of the url from the base, except for params, query, and fragment, which are taken only from the 'url'. For the pathname component, it merges the paths like os.path.join: an absolute path in 'url' overrides the base path, otherw...
urlmerge
python
NVlabs/VILA
llava/wids/wids_specs.py
https://github.com/NVlabs/VILA/blob/master/llava/wids/wids_specs.py
Apache-2.0
def check_shards(l): """Check that a list of shards is well-formed. This checks that the list is a list of dictionaries, and that each dictionary has a "url" and a "nsamples" key. """ assert isinstance(l, list) for shard in l: assert isinstance(shard, dict) assert "url" in shard...
Check that a list of shards is well-formed. This checks that the list is a list of dictionaries, and that each dictionary has a "url" and a "nsamples" key.
check_shards
python
NVlabs/VILA
llava/wids/wids_specs.py
https://github.com/NVlabs/VILA/blob/master/llava/wids/wids_specs.py
Apache-2.0
def set_all(l, k, v): """Set a key to a value in a list of dictionaries.""" if v is None: return for x in l: if k not in x: x[k] = v
Set a key to a value in a list of dictionaries.
set_all
python
NVlabs/VILA
llava/wids/wids_specs.py
https://github.com/NVlabs/VILA/blob/master/llava/wids/wids_specs.py
Apache-2.0
def load_remote_dsdesc_raw(source): """Load a remote or local dataset description in JSON format.""" if isinstance(source, str): with tempfile.TemporaryDirectory() as tmpdir: dlname = os.path.join(tmpdir, "dataset.json") with download_and_open(source, dlname) as f: ...
Load a remote or local dataset description in JSON format.
load_remote_dsdesc_raw
python
NVlabs/VILA
llava/wids/wids_specs.py
https://github.com/NVlabs/VILA/blob/master/llava/wids/wids_specs.py
Apache-2.0
def resolve_dsdesc(dsdesc, *, options=None, base=None): """Resolve a dataset description. This rebases the shards as necessary and loads any remote references. Dataset descriptions are JSON files. They must have the following format; { "wids_version": 1, # optional immediate shardlist...
Resolve a dataset description. This rebases the shards as necessary and loads any remote references. Dataset descriptions are JSON files. They must have the following format; { "wids_version": 1, # optional immediate shardlist "shardlist": [ {"url": "http://example.com...
resolve_dsdesc
python
NVlabs/VILA
llava/wids/wids_specs.py
https://github.com/NVlabs/VILA/blob/master/llava/wids/wids_specs.py
Apache-2.0
def quantize_module_config(module_name): """ Generate quantization config to apply W8A8 quantization for specified module. Rest of the model is kept in FP32 precision. """ config = LinearQuantizerConfig( global_config=ModuleLinearQuantizerConfig( milestones=[0, 1000, 1000, 0], ...
Generate quantization config to apply W8A8 quantization for specified module. Rest of the model is kept in FP32 precision.
quantize_module_config
python
apple/ml-stable-diffusion
python_coreml_stable_diffusion/activation_quantization.py
https://github.com/apple/ml-stable-diffusion/blob/master/python_coreml_stable_diffusion/activation_quantization.py
MIT
def quantize_cumulative_config(skip_conv_layers, skip_einsum_layers): """ Generate quantization config to apply W8A8 quantization. Skipped layers are kept in W8A32 precision. """ logger.info(f"Skipping {len(skip_conv_layers)} conv layers and {len(skip_einsum_layers)} einsum layers") w8config = M...
Generate quantization config to apply W8A8 quantization. Skipped layers are kept in W8A32 precision.
quantize_cumulative_config
python
apple/ml-stable-diffusion
python_coreml_stable_diffusion/activation_quantization.py
https://github.com/apple/ml-stable-diffusion/blob/master/python_coreml_stable_diffusion/activation_quantization.py
MIT
def quantize(model, config, calibration_data): """ Apply post training activation quantization to specified model, using calibration data """ submodules = dict(model.named_modules(remove_duplicate=True)) layer_norm_modules = [key for key, val in submodules.items() if isinstance(val, LayerNormANE)] ...
Apply post training activation quantization to specified model, using calibration data
quantize
python
apple/ml-stable-diffusion
python_coreml_stable_diffusion/activation_quantization.py
https://github.com/apple/ml-stable-diffusion/blob/master/python_coreml_stable_diffusion/activation_quantization.py
MIT
def recipe_overrides_for_inference_speedup(conv_layers, skipped_conv): """ Quantize the slowest conv layers, even if in skipped set based on PSNR, for good inference speedup """ for layer in conv_layers: if "up_blocks" in layer and "resnets" in layer and "conv1" in layer: if layer in...
Quantize the slowest conv layers, even if in skipped set based on PSNR, for good inference speedup
recipe_overrides_for_inference_speedup
python
apple/ml-stable-diffusion
python_coreml_stable_diffusion/activation_quantization.py
https://github.com/apple/ml-stable-diffusion/blob/master/python_coreml_stable_diffusion/activation_quantization.py
MIT
def recipe_overrides_for_quality(conv_layers, skipped_conv): """ Do not quantize out projection layers to avoid quantizing outputs of preceding concat layers. Quantizing output of concat layers can lead to quality degradation, due to sharing of scales across concat inputs, which can have varied ranges. ...
Do not quantize out projection layers to avoid quantizing outputs of preceding concat layers. Quantizing output of concat layers can lead to quality degradation, due to sharing of scales across concat inputs, which can have varied ranges. Since this is a constraint enforced during model conversion, it ...
recipe_overrides_for_quality
python
apple/ml-stable-diffusion
python_coreml_stable_diffusion/activation_quantization.py
https://github.com/apple/ml-stable-diffusion/blob/master/python_coreml_stable_diffusion/activation_quantization.py
MIT
def register_input_log_hook(unet, inputs): """ Register forward pre hook to save model inputs """ def hook(_, input): input_copy = deepcopy(input) input_copy = tuple(i.to('cpu') for i in input_copy) inputs.append(input_copy) # Return inputs unmodified return inp...
Register forward pre hook to save model inputs
register_input_log_hook
python
apple/ml-stable-diffusion
python_coreml_stable_diffusion/activation_quantization.py
https://github.com/apple/ml-stable-diffusion/blob/master/python_coreml_stable_diffusion/activation_quantization.py
MIT
def register_input_preprocessing_hook(pipe): """ Register forward pre hook to convert UNet inputs from HuggingFace StableDiffusionPipeline to match expected model inputs in UNet2DConditionModel defined in unet.py """ def hook(_, args, kwargs): sample = args[0] timestep = args[1] ...
Register forward pre hook to convert UNet inputs from HuggingFace StableDiffusionPipeline to match expected model inputs in UNet2DConditionModel defined in unet.py
register_input_preprocessing_hook
python
apple/ml-stable-diffusion
python_coreml_stable_diffusion/activation_quantization.py
https://github.com/apple/ml-stable-diffusion/blob/master/python_coreml_stable_diffusion/activation_quantization.py
MIT
def prepare_pipe(pipe, unet): """ Create a new pipeline from `pipe` with `unet` as the noise predictor """ new_pipe = deepcopy(pipe) unet.to(new_pipe.unet.device) new_pipe.unet = unet pre_hook_handle = register_input_preprocessing_hook(new_pipe) return new_pipe, pre_hook_handle
Create a new pipeline from `pipe` with `unet` as the noise predictor
prepare_pipe
python
apple/ml-stable-diffusion
python_coreml_stable_diffusion/activation_quantization.py
https://github.com/apple/ml-stable-diffusion/blob/master/python_coreml_stable_diffusion/activation_quantization.py
MIT
def split_einsum(q, k, v, mask, heads, dim_head): """ Attention Implementation backing AttentionImplementations.SPLIT_EINSUM - Implements https://machinelearning.apple.com/research/neural-engine-transformers - Recommended for ANE - Marginally slower on GPU """ mh_q = [ q[:, head_idx * d...
Attention Implementation backing AttentionImplementations.SPLIT_EINSUM - Implements https://machinelearning.apple.com/research/neural-engine-transformers - Recommended for ANE - Marginally slower on GPU
split_einsum
python
apple/ml-stable-diffusion
python_coreml_stable_diffusion/attention.py
https://github.com/apple/ml-stable-diffusion/blob/master/python_coreml_stable_diffusion/attention.py
MIT
def split_einsum_v2(q, k, v, mask, heads, dim_head): """ Attention Implementation backing AttentionImplementations.SPLIT_EINSUM_V2 - Implements https://machinelearning.apple.com/research/neural-engine-transformers - Recommended for ANE - Marginally slower on GPU - Chunks the query sequence to avoid...
Attention Implementation backing AttentionImplementations.SPLIT_EINSUM_V2 - Implements https://machinelearning.apple.com/research/neural-engine-transformers - Recommended for ANE - Marginally slower on GPU - Chunks the query sequence to avoid large intermediate tensors and improves ANE performance ...
split_einsum_v2
python
apple/ml-stable-diffusion
python_coreml_stable_diffusion/attention.py
https://github.com/apple/ml-stable-diffusion/blob/master/python_coreml_stable_diffusion/attention.py
MIT
def original(q, k, v, mask, heads, dim_head): """ Attention Implementation backing AttentionImplementations.ORIGINAL - Not recommended for ANE - Recommended for GPU """ bs = q.size(0) mh_q = q.view(bs, heads, dim_head, -1) mh_k = k.view(bs, heads, dim_head, -1) mh_v = v.view(bs, heads, ...
Attention Implementation backing AttentionImplementations.ORIGINAL - Not recommended for ANE - Recommended for GPU
original
python
apple/ml-stable-diffusion
python_coreml_stable_diffusion/attention.py
https://github.com/apple/ml-stable-diffusion/blob/master/python_coreml_stable_diffusion/attention.py
MIT
def _verify_output_correctness_of_chunks(full_model, first_chunk_model=None, second_chunk_model=None, pipeline_model=None,): """ Verifies the end-to-end output correctness of full (original) mo...
Verifies the end-to-end output correctness of full (original) model versus chunked models
_verify_output_correctness_of_chunks
python
apple/ml-stable-diffusion
python_coreml_stable_diffusion/chunk_mlprogram.py
https://github.com/apple/ml-stable-diffusion/blob/master/python_coreml_stable_diffusion/chunk_mlprogram.py
MIT
def _load_prog_from_mlmodel(model): """ Load MIL Program from an MLModel """ model_spec = model.get_spec() start_ = time.time() logger.info( "Loading MLModel object into a MIL Program object (including the weights).." ) prog = _milproto_to_pymil( model_spec=model_spec, ...
Load MIL Program from an MLModel
_load_prog_from_mlmodel
python
apple/ml-stable-diffusion
python_coreml_stable_diffusion/chunk_mlprogram.py
https://github.com/apple/ml-stable-diffusion/blob/master/python_coreml_stable_diffusion/chunk_mlprogram.py
MIT
def _get_op_idx_split_location(prog: Program): """ Find the op that approximately bisects the graph as measure by weights size on each side """ main_block = prog.functions["main"] main_block.operations = list(main_block.operations) total_size_in_mb = 0 for op in main_block.operations: i...
Find the op that approximately bisects the graph as measure by weights size on each side
_get_op_idx_split_location
python
apple/ml-stable-diffusion
python_coreml_stable_diffusion/chunk_mlprogram.py
https://github.com/apple/ml-stable-diffusion/blob/master/python_coreml_stable_diffusion/chunk_mlprogram.py
MIT
def _make_first_chunk_prog(prog, op_idx): """ Build first chunk by declaring early outputs and removing unused subgraph """ block = prog.functions["main"] boundary_vars = _get_first_chunk_outputs(block, op_idx) # Due to possible numerical issues, cast any fp16 var to fp32 new_boundary_vars = _a...
Build first chunk by declaring early outputs and removing unused subgraph
_make_first_chunk_prog
python
apple/ml-stable-diffusion
python_coreml_stable_diffusion/chunk_mlprogram.py
https://github.com/apple/ml-stable-diffusion/blob/master/python_coreml_stable_diffusion/chunk_mlprogram.py
MIT
def _make_second_chunk_prog(prog, op_idx): """ Build second chunk by rebuilding a pristine MIL Program from MLModel """ block = prog.functions["main"] block.opset_version = ct.target.iOS16 # First chunk outputs are second chunk inputs (e.g. skip connections) boundary_vars = _get_first_chunk_out...
Build second chunk by rebuilding a pristine MIL Program from MLModel
_make_second_chunk_prog
python
apple/ml-stable-diffusion
python_coreml_stable_diffusion/chunk_mlprogram.py
https://github.com/apple/ml-stable-diffusion/blob/master/python_coreml_stable_diffusion/chunk_mlprogram.py
MIT
def _macos_version(): """ Returns macOS version as a tuple of integers. On non-Macs, returns an empty tuple. """ if sys.platform == "darwin": try: ver_str = subprocess.run(["sw_vers", "-productVersion"], stdout=subprocess.PIPE).stdout.decode('utf-8').strip('\n') return tu...
Returns macOS version as a tuple of integers. On non-Macs, returns an empty tuple.
_macos_version
python
apple/ml-stable-diffusion
python_coreml_stable_diffusion/coreml_model.py
https://github.com/apple/ml-stable-diffusion/blob/master/python_coreml_stable_diffusion/coreml_model.py
MIT
def get_resource_type(resources_dir: str) -> str: """ Detect resource type based on filepath extensions. returns: `packages`: for .mlpackage resources 'compiled`: for .mlmodelc resources """ directories = [f for f in os.listdir(resources_dir) if os.path.isdir(os.path....
Detect resource type based on filepath extensions. returns: `packages`: for .mlpackage resources 'compiled`: for .mlmodelc resources
get_resource_type
python
apple/ml-stable-diffusion
python_coreml_stable_diffusion/coreml_model.py
https://github.com/apple/ml-stable-diffusion/blob/master/python_coreml_stable_diffusion/coreml_model.py
MIT
def _load_mlpackage(submodule_name, mlpackages_dir, model_version, compute_unit, sources=None): """ Load Core ML (mlpackage) models from disk (As exported by torch2coreml.py) """ # if sources not provided, attempt to i...
Load Core ML (mlpackage) models from disk (As exported by torch2coreml.py)
_load_mlpackage
python
apple/ml-stable-diffusion
python_coreml_stable_diffusion/coreml_model.py
https://github.com/apple/ml-stable-diffusion/blob/master/python_coreml_stable_diffusion/coreml_model.py
MIT
def _load_mlpackage_controlnet(mlpackages_dir, model_version, compute_unit): """ Load Core ML (mlpackage) models from disk (As exported by torch2coreml.py) """ model_name = model_version.replace("/", "_") logger.info(f"Loading controlnet_{model_name} mlpackage") fname = f"ControlNet_{model_name}.m...
Load Core ML (mlpackage) models from disk (As exported by torch2coreml.py)
_load_mlpackage_controlnet
python
apple/ml-stable-diffusion
python_coreml_stable_diffusion/coreml_model.py
https://github.com/apple/ml-stable-diffusion/blob/master/python_coreml_stable_diffusion/coreml_model.py
MIT
def __init__(self, num_channels, clip_mag=None, eps=1e-5, elementwise_affine=True): """ Args: num_channels: Number of channels (C) where the expected input data format is BC1S. S stands for sequence length. ...
Args: num_channels: Number of channels (C) where the expected input data format is BC1S. S stands for sequence length. clip_mag: Optional float value to use for clamping the input range before layer norm is applied. If specified, helps red...
__init__
python
apple/ml-stable-diffusion
python_coreml_stable_diffusion/layer_norm.py
https://github.com/apple/ml-stable-diffusion/blob/master/python_coreml_stable_diffusion/layer_norm.py
MIT
def _ensure_numerical_range_and_cast(val, low, high, np_dtype): ''' For some cases, the computed quantized data might exceed the data range. For instance, after rounding and addition, we might get `128` for the int8 quantization. This utility function ensures the val in the data range be...
For some cases, the computed quantized data might exceed the data range. For instance, after rounding and addition, we might get `128` for the int8 quantization. This utility function ensures the val in the data range before doing the cast.
_ensure_numerical_range_and_cast
python
apple/ml-stable-diffusion
python_coreml_stable_diffusion/mixed_bit_compression_pre_analysis.py
https://github.com/apple/ml-stable-diffusion/blob/master/python_coreml_stable_diffusion/mixed_bit_compression_pre_analysis.py
MIT
def get_coreml_pipe(pytorch_pipe, mlpackages_dir, model_version, compute_unit, delete_original_pipe=True, scheduler_override=None, controlnet_models=None, force_zeros_for_empty_pro...
Initializes and returns a `CoreMLStableDiffusionPipeline` from an original diffusers PyTorch pipeline sources: 'packages' or 'compiled' forces creation of model from specified sources. sources must be in mlpackages_dir
get_coreml_pipe
python
apple/ml-stable-diffusion
python_coreml_stable_diffusion/pipeline.py
https://github.com/apple/ml-stable-diffusion/blob/master/python_coreml_stable_diffusion/pipeline.py
MIT
def get_image_path(args, **override_kwargs): """ mkdir output folder and encode metadata in the filename """ out_folder = os.path.join(args.o, "_".join(args.prompt.replace("/", "_").rsplit(" "))) os.makedirs(out_folder, exist_ok=True) out_fname = f"randomSeed_{override_kwargs.get('seed', None) or a...
mkdir output folder and encode metadata in the filename
get_image_path
python
apple/ml-stable-diffusion
python_coreml_stable_diffusion/pipeline.py
https://github.com/apple/ml-stable-diffusion/blob/master/python_coreml_stable_diffusion/pipeline.py
MIT
def compute_psnr(a, b): """ Compute Peak-Signal-to-Noise-Ratio across two numpy.ndarray objects """ max_b = np.abs(b).max() sumdeltasq = 0.0 sumdeltasq = ((a - b) * (a - b)).sum() sumdeltasq /= b.size sumdeltasq = np.sqrt(sumdeltasq) eps = 1e-5 eps2 = 1e-10 psnr = 20 * np.log1...
Compute Peak-Signal-to-Noise-Ratio across two numpy.ndarray objects
compute_psnr
python
apple/ml-stable-diffusion
python_coreml_stable_diffusion/torch2coreml.py
https://github.com/apple/ml-stable-diffusion/blob/master/python_coreml_stable_diffusion/torch2coreml.py
MIT
def report_correctness(original_outputs, final_outputs, log_prefix): """ Report PSNR values across two compatible tensors """ original_psnr = compute_psnr(original_outputs, original_outputs) final_psnr = compute_psnr(original_outputs, final_outputs) dB_change = final_psnr - original_psnr logger...
Report PSNR values across two compatible tensors
report_correctness
python
apple/ml-stable-diffusion
python_coreml_stable_diffusion/torch2coreml.py
https://github.com/apple/ml-stable-diffusion/blob/master/python_coreml_stable_diffusion/torch2coreml.py
MIT
def quantize_weights(args): """ Quantize weights to args.quantize_nbits using a palette (look-up table) """ for model_name in ["text_encoder", "text_encoder_2", "unet", "refiner", "control-unet"]: logger.info(f"Quantizing {model_name} to {args.quantize_nbits}-bit precision") out_path = _get_...
Quantize weights to args.quantize_nbits using a palette (look-up table)
quantize_weights
python
apple/ml-stable-diffusion
python_coreml_stable_diffusion/torch2coreml.py
https://github.com/apple/ml-stable-diffusion/blob/master/python_coreml_stable_diffusion/torch2coreml.py
MIT
def _compile_coreml_model(source_model_path, output_dir, final_name): """ Compiles Core ML models using the coremlcompiler utility from Xcode toolchain """ target_path = os.path.join(output_dir, f"{final_name}.mlmodelc") if os.path.exists(target_path): logger.warning( f"Found existin...
Compiles Core ML models using the coremlcompiler utility from Xcode toolchain
_compile_coreml_model
python
apple/ml-stable-diffusion
python_coreml_stable_diffusion/torch2coreml.py
https://github.com/apple/ml-stable-diffusion/blob/master/python_coreml_stable_diffusion/torch2coreml.py
MIT
def bundle_resources_for_swift_cli(args): """ - Compiles Core ML models from mlpackage into mlmodelc format - Download tokenizer resources for the text encoder """ resources_dir = os.path.join(args.o, "Resources") if not os.path.exists(resources_dir): os.makedirs(resources_dir, exist_ok=...
- Compiles Core ML models from mlpackage into mlmodelc format - Download tokenizer resources for the text encoder
bundle_resources_for_swift_cli
python
apple/ml-stable-diffusion
python_coreml_stable_diffusion/torch2coreml.py
https://github.com/apple/ml-stable-diffusion/blob/master/python_coreml_stable_diffusion/torch2coreml.py
MIT
def patched_make_causal_mask(input_ids_shape, dtype, device, past_key_values_length: int = 0): """ Patch to replace torch.finfo(dtype).min with -1e4 """ bsz, tgt_len = input_ids_shape mask = torch.full((tgt_len, tgt_len), torch.tensor(-1e4, device=device), device=device) mask_cond = torch.arange(mas...
Patch to replace torch.finfo(dtype).min with -1e4
patched_make_causal_mask
python
apple/ml-stable-diffusion
python_coreml_stable_diffusion/torch2coreml.py
https://github.com/apple/ml-stable-diffusion/blob/master/python_coreml_stable_diffusion/torch2coreml.py
MIT
def convert_text_encoder(text_encoder, tokenizer, submodule_name, args): """ Converts the text encoder component of Stable Diffusion """ text_encoder = text_encoder.to(dtype=torch.float32) out_path = _get_out_path(args, submodule_name) if os.path.exists(out_path): logger.info( f"...
Converts the text encoder component of Stable Diffusion
convert_text_encoder
python
apple/ml-stable-diffusion
python_coreml_stable_diffusion/torch2coreml.py
https://github.com/apple/ml-stable-diffusion/blob/master/python_coreml_stable_diffusion/torch2coreml.py
MIT
def convert_vae_decoder(pipe, args): """ Converts the VAE Decoder component of Stable Diffusion """ out_path = _get_out_path(args, "vae_decoder") if os.path.exists(out_path): logger.info( f"`vae_decoder` already exists at {out_path}, skipping conversion." ) return ...
Converts the VAE Decoder component of Stable Diffusion
convert_vae_decoder
python
apple/ml-stable-diffusion
python_coreml_stable_diffusion/torch2coreml.py
https://github.com/apple/ml-stable-diffusion/blob/master/python_coreml_stable_diffusion/torch2coreml.py
MIT
def convert_vae_decoder_sd3(args): """ Converts the VAE component of Stable Diffusion 3 """ out_path = _get_out_path(args, "vae_decoder") if os.path.exists(out_path): logger.info( f"`vae_decoder` already exists at {out_path}, skipping conversion." ) return # ...
Converts the VAE component of Stable Diffusion 3
convert_vae_decoder_sd3
python
apple/ml-stable-diffusion
python_coreml_stable_diffusion/torch2coreml.py
https://github.com/apple/ml-stable-diffusion/blob/master/python_coreml_stable_diffusion/torch2coreml.py
MIT
def convert_vae_encoder(pipe, args): """ Converts the VAE Encoder component of Stable Diffusion """ out_path = _get_out_path(args, "vae_encoder") if os.path.exists(out_path): logger.info( f"`vae_encoder` already exists at {out_path}, skipping conversion." ) return ...
Converts the VAE Encoder component of Stable Diffusion
convert_vae_encoder
python
apple/ml-stable-diffusion
python_coreml_stable_diffusion/torch2coreml.py
https://github.com/apple/ml-stable-diffusion/blob/master/python_coreml_stable_diffusion/torch2coreml.py
MIT