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 ndgrid(*tensors) -> Tuple[torch.Tensor, ...]: """generate N-D grid in dimension order. The ndgrid function is like meshgrid except that the order of the first two input arguments are switched. That is, the statement [X1,X2,X3] = ndgrid(x1,x2,x3) produces the same result as [X2,X1,X3] = m...
generate N-D grid in dimension order. The ndgrid function is like meshgrid except that the order of the first two input arguments are switched. That is, the statement [X1,X2,X3] = ndgrid(x1,x2,x3) produces the same result as [X2,X1,X3] = meshgrid(x2,x1,x3) This naming is based on MATLAB, th...
ndgrid
python
NVlabs/VILA
llava/model/multimodal_encoder/intern/modeling_intern_vit.py
https://github.com/NVlabs/VILA/blob/master/llava/model/multimodal_encoder/intern/modeling_intern_vit.py
Apache-2.0
def drop_block_2d( x, drop_prob: float = 0.1, block_size: int = 7, gamma_scale: float = 1.0, with_noise: bool = False, inplace: bool = False, batchwise: bool = False, ): """DropBlock. See https://arxiv.org/pdf/1810.12890.pdf DropBlock with an experimental gaussian noise option. This...
DropBlock. See https://arxiv.org/pdf/1810.12890.pdf DropBlock with an experimental gaussian noise option. This layer has been tested on a few training runs with success, but needs further validation and possibly optimization for lower runtime impact.
drop_block_2d
python
NVlabs/VILA
llava/model/multimodal_encoder/intern/modeling_intern_vit.py
https://github.com/NVlabs/VILA/blob/master/llava/model/multimodal_encoder/intern/modeling_intern_vit.py
Apache-2.0
def drop_block_fast_2d( x: torch.Tensor, drop_prob: float = 0.1, block_size: int = 7, gamma_scale: float = 1.0, with_noise: bool = False, inplace: bool = False, ): """DropBlock. See https://arxiv.org/pdf/1810.12890.pdf DropBlock with an experimental gaussian noise option. Simplied from ...
DropBlock. See https://arxiv.org/pdf/1810.12890.pdf DropBlock with an experimental gaussian noise option. Simplied from above without concern for valid block mask at edges.
drop_block_fast_2d
python
NVlabs/VILA
llava/model/multimodal_encoder/intern/modeling_intern_vit.py
https://github.com/NVlabs/VILA/blob/master/llava/model/multimodal_encoder/intern/modeling_intern_vit.py
Apache-2.0
def drop_path(x, drop_prob: float = 0.0, training: bool = False, scale_by_keep: bool = True): """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). This is the same as the DropConnect impl I created for EfficientNet, etc networks, however, the original name is misleadi...
Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). This is the same as the DropConnect impl I created for EfficientNet, etc networks, however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper... See discussion: https:...
drop_path
python
NVlabs/VILA
llava/model/multimodal_encoder/intern/modeling_intern_vit.py
https://github.com/NVlabs/VILA/blob/master/llava/model/multimodal_encoder/intern/modeling_intern_vit.py
Apache-2.0
def forward( self, hidden_states: torch.Tensor, ) -> Tuple[torch.FloatTensor, Optional[torch.FloatTensor], Optional[Tuple[torch.FloatTensor]]]: """ Args: hidden_states (`Tuple[torch.FloatTensor, Optional[torch.FloatTensor]]`): input to the layer of shape `(batch, seq_len,...
Args: hidden_states (`Tuple[torch.FloatTensor, Optional[torch.FloatTensor]]`): input to the layer of shape `(batch, seq_len, embed_dim)`
forward
python
NVlabs/VILA
llava/model/multimodal_encoder/intern/modeling_intern_vit.py
https://github.com/NVlabs/VILA/blob/master/llava/model/multimodal_encoder/intern/modeling_intern_vit.py
Apache-2.0
def forward( self, inputs_embeds, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, BaseModelOutput]: r""" Args: inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): ...
Args: inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): Embedded representation of the inputs. Should be float, not int tokens. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states ...
forward
python
NVlabs/VILA
llava/model/multimodal_encoder/intern/modeling_intern_vit.py
https://github.com/NVlabs/VILA/blob/master/llava/model/multimodal_encoder/intern/modeling_intern_vit.py
Apache-2.0
def trunc_normal_tf_( tensor: torch.Tensor, mean: float = 0.0, std: float = 1.0, a: float = -2.0, b: float = 2.0 ) -> torch.Tensor: """Fills the input Tensor with values drawn from a truncated normal distribution. The values are effectively drawn from the normal distribution :math:`\\mathcal{N}(\text{me...
Fills the input Tensor with values drawn from a truncated normal distribution. The values are effectively drawn from the normal distribution :math:`\mathcal{N}( ext{mean}, ext{std}^2)` with values outside :math:`[a, b]` redrawn until they are within the bounds. The method used for generating the random...
trunc_normal_tf_
python
NVlabs/VILA
llava/model/multimodal_encoder/siglip/modeling_siglip.py
https://github.com/NVlabs/VILA/blob/master/llava/model/multimodal_encoder/siglip/modeling_siglip.py
Apache-2.0
def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor: """ This method is an adapted method for SigLIP (due to SigLIP not having class embedding unlike other ViTs) that allows the model to interpolate the pre-trained position encodings such that it...
This method is an adapted method for SigLIP (due to SigLIP not having class embedding unlike other ViTs) that allows the model to interpolate the pre-trained position encodings such that it can be usable on higher resolution images. Source: https://github.com/facebookresearch/d...
interpolate_pos_encoding
python
NVlabs/VILA
llava/model/multimodal_encoder/siglip/modeling_siglip.py
https://github.com/NVlabs/VILA/blob/master/llava/model/multimodal_encoder/siglip/modeling_siglip.py
Apache-2.0
def forward( self, hidden_states: torch.Tensor, attention_mask: torch.Tensor, output_attentions: Optional[bool] = False, ) -> Tuple[torch.FloatTensor]: """ Args: hidden_states (`torch.FloatTensor`): Input to the layer of shape `(batch, seq_...
Args: hidden_states (`torch.FloatTensor`): Input to the layer of shape `(batch, seq_len, embed_dim)`. attention_mask (`torch.FloatTensor`): Attention mask of shape `(batch, 1, q_len, k_v_seq_len)` where padding elements are indicated by very large negativ...
forward
python
NVlabs/VILA
llava/model/multimodal_encoder/siglip/modeling_siglip.py
https://github.com/NVlabs/VILA/blob/master/llava/model/multimodal_encoder/siglip/modeling_siglip.py
Apache-2.0
def forward( self, inputs_embeds, attention_mask: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, BaseModelOutput]: r""" Args: ...
Args: inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_...
forward
python
NVlabs/VILA
llava/model/multimodal_encoder/siglip/modeling_siglip.py
https://github.com/NVlabs/VILA/blob/master/llava/model/multimodal_encoder/siglip/modeling_siglip.py
Apache-2.0
def forward( self, input_ids: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bo...
Returns: Examples: ```python >>> from transformers import AutoTokenizer, SiglipTextModel >>> model = SiglipTextModel.from_pretrained("google/siglip-base-patch16-224") >>> tokenizer = AutoTokenizer.from_pretrained("google/siglip-base-patch16-224") >>> # import...
forward
python
NVlabs/VILA
llava/model/multimodal_encoder/siglip/modeling_siglip.py
https://github.com/NVlabs/VILA/blob/master/llava/model/multimodal_encoder/siglip/modeling_siglip.py
Apache-2.0
def forward( self, pixel_values, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, interpolate_pos_encoding: bool = False, ) -> Union[Tuple, BaseModelOutputWithPooling]: r""" Retu...
Returns: Examples: ```python >>> from PIL import Image >>> import requests >>> from transformers import AutoProcessor, SiglipVisionModel >>> model = SiglipVisionModel.from_pretrained("google/siglip-base-patch16-224") >>> processor = AutoProcessor.from_...
forward
python
NVlabs/VILA
llava/model/multimodal_encoder/siglip/modeling_siglip.py
https://github.com/NVlabs/VILA/blob/master/llava/model/multimodal_encoder/siglip/modeling_siglip.py
Apache-2.0
def get_text_features( self, input_ids: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: O...
Returns: text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by applying the projection layer to the pooled output of [`SiglipTextModel`]. Examples: ```python >>> from transformers import AutoTokenizer, AutoModel...
get_text_features
python
NVlabs/VILA
llava/model/multimodal_encoder/siglip/modeling_siglip.py
https://github.com/NVlabs/VILA/blob/master/llava/model/multimodal_encoder/siglip/modeling_siglip.py
Apache-2.0
def get_image_features( self, pixel_values: Optional[torch.FloatTensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, interpolate_pos_encoding: bool = False, ) -> torch.FloatTensor: ...
Returns: image_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by applying the projection layer to the pooled output of [`SiglipVisionModel`]. Examples: ```python >>> from PIL import Image >>> import requ...
get_image_features
python
NVlabs/VILA
llava/model/multimodal_encoder/siglip/modeling_siglip.py
https://github.com/NVlabs/VILA/blob/master/llava/model/multimodal_encoder/siglip/modeling_siglip.py
Apache-2.0
def forward( self, input_ids: Optional[torch.LongTensor] = None, pixel_values: Optional[torch.FloatTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, return_loss: Optional[bool] = None, output_attentions...
Returns: Examples: ```python >>> from PIL import Image >>> import requests >>> from transformers import AutoProcessor, AutoModel >>> import torch >>> model = AutoModel.from_pretrained("google/siglip-base-patch16-224") >>> processor = AutoProces...
forward
python
NVlabs/VILA
llava/model/multimodal_encoder/siglip/modeling_siglip.py
https://github.com/NVlabs/VILA/blob/master/llava/model/multimodal_encoder/siglip/modeling_siglip.py
Apache-2.0
def forward( self, pixel_values: Optional[torch.Tensor] = None, labels: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, interpolate_pos_encoding: bool = False...
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for computing the image classification/regression loss. Indices should be in `[0, ..., config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If `config.n...
forward
python
NVlabs/VILA
llava/model/multimodal_encoder/siglip/modeling_siglip.py
https://github.com/NVlabs/VILA/blob/master/llava/model/multimodal_encoder/siglip/modeling_siglip.py
Apache-2.0
def is_mm_model(model_path): """ Check if the model at the given path is a visual language model. Args: model_path (str): The path to the model. Returns: bool: True if the model is an MM model, False otherwise. """ config = AutoConfig.from_pretrained(model_path) architectur...
Check if the model at the given path is a visual language model. Args: model_path (str): The path to the model. Returns: bool: True if the model is an MM model, False otherwise.
is_mm_model
python
NVlabs/VILA
llava/model/utils/utils.py
https://github.com/NVlabs/VILA/blob/master/llava/model/utils/utils.py
Apache-2.0
def process_vision_info( conversations: list[dict] | list[list[dict]], return_video_kwargs: bool = False, ) -> tuple[list[PIL.Image.Image] | None, list[torch.Tensor | list[PIL.Image.Image]] | None, Optional[dict]]: """ referernce from qwen_vl_utils NVILA does not depend on th...
referernce from qwen_vl_utils NVILA does not depend on the function, but the interface is the same.
process_vision_info
python
NVlabs/VILA
llava/remote_code/auto_processor.py
https://github.com/NVlabs/VILA/blob/master/llava/remote_code/auto_processor.py
Apache-2.0
def __call__( self, conversation=None, **kwargs: Unpack[VILAProcessorKwargs], ) -> BatchFeature: """ The `conv` will be look like [ { 'from': 'human', 'value': [ <transformers_modules.NVILA-Lite-2B-hf-pre...
The `conv` will be look like [ { 'from': 'human', 'value': [ <transformers_modules.NVILA-Lite-2B-hf-preview.media.Image object at 0x154e68e4c460>, 'What are the common elements in these pictures?' ] ...
__call__
python
NVlabs/VILA
llava/remote_code/auto_processor.py
https://github.com/NVlabs/VILA/blob/master/llava/remote_code/auto_processor.py
Apache-2.0
def post_process_image_text_to_text(self, generated_outputs): """ Post-process the output of the model to decode the text. Args: generated_outputs (`torch.Tensor` or `np.ndarray`): The output of the model `generate` function. The output is expected to be a tensor of ...
Post-process the output of the model to decode the text. Args: generated_outputs (`torch.Tensor` or `np.ndarray`): The output of the model `generate` function. The output is expected to be a tensor of shape `(batch_size, sequence_length)` or `(sequence_lengt...
post_process_image_text_to_text
python
NVlabs/VILA
llava/remote_code/auto_processor.py
https://github.com/NVlabs/VILA/blob/master/llava/remote_code/auto_processor.py
Apache-2.0
def check_dot_in_model_path(model_path: str): """Check if the model path contains dot, which will affect the remote code loading.""" if osp.isdir(model_path): # local model if "." in osp.abspath(model_path): return True else: # remote model if "." in model_path: ret...
Check if the model path contains dot, which will affect the remote code loading.
check_dot_in_model_path
python
NVlabs/VILA
llava/remote_code/modeling_vila.py
https://github.com/NVlabs/VILA/blob/master/llava/remote_code/modeling_vila.py
Apache-2.0
def generate( self, input_ids: Optional[torch.FloatTensor] = None, media: Optional[Dict[str, List[torch.Tensor]]] = None, media_config: Dict[str, Dict[str, Any]] = None, attention_mask: Optional[torch.LongTensor] = None, return_output_ids_only: bool = False, **gen...
input_tokens: <image> describe the image media: [Tensor(1, 3, 384, 384), ] -----------> input_tokens: 36000 001 002 003 004 input_emds: <media emd> 001 002 003 004
generate
python
NVlabs/VILA
llava/remote_code/modeling_vila.py
https://github.com/NVlabs/VILA/blob/master/llava/remote_code/modeling_vila.py
Apache-2.0
def split_to_even_chunks(indices, lengths, num_chunks): """ Split a list of indices into `chunks` chunks of roughly equal lengths. """ if len(indices) % num_chunks != 0: return [indices[i::num_chunks] for i in range(num_chunks)] num_indices_per_chunk = len(indices) // num_chunks chunk...
Split a list of indices into `chunks` chunks of roughly equal lengths.
split_to_even_chunks
python
NVlabs/VILA
llava/train/llava_trainer.py
https://github.com/NVlabs/VILA/blob/master/llava/train/llava_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. """ if is_sagemak...
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
NVlabs/VILA
llava/train/llava_trainer.py
https://github.com/NVlabs/VILA/blob/master/llava/train/llava_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 i...
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
NVlabs/VILA
llava/train/llava_trainer.py
https://github.com/NVlabs/VILA/blob/master/llava/train/llava_trainer.py
Apache-2.0
def dice_loss( inputs: torch.Tensor, targets: torch.Tensor, scale=100, # 100000.0, eps=1e-6, ): """ Compute the DICE loss, similar to generalized IOU for masks Args: inputs: A float tensor of arbitrary shape. The predictions fo...
Compute the DICE loss, similar to generalized IOU for masks Args: inputs: A float tensor of arbitrary shape. The predictions for each example. targets: A float tensor with the same shape as inputs. Stores the binary classification label fo...
dice_loss
python
NVlabs/VILA
llava/train/llava_trainer.py
https://github.com/NVlabs/VILA/blob/master/llava/train/llava_trainer.py
Apache-2.0
def get_nb_trainable_parameters(model) -> tuple[int, int]: r""" Returns the number of trainable parameters and the number of all parameters in the model. """ trainable_params = 0 all_param = 0 for _, param in model.named_parameters(): num_params = param.numel() # if using DS Zero...
Returns the number of trainable parameters and the number of all parameters in the model.
get_nb_trainable_parameters
python
NVlabs/VILA
llava/train/train.py
https://github.com/NVlabs/VILA/blob/master/llava/train/train.py
Apache-2.0
def __getitem__(self, i) -> Dict[str, torch.Tensor]: """ { 'prompt': 'Is there a snowman wearing a green scarf and hat in the background?', 'chosen': 'No, there is no snowman wearing a green scarf and hat in the background of the image. The image features a person ...', ...
{ 'prompt': 'Is there a snowman wearing a green scarf and hat in the background?', 'chosen': 'No, there is no snowman wearing a green scarf and hat in the background of the image. The image features a person ...', 'rejected': 'No, there is no snowman in the background.', ...
__getitem__
python
NVlabs/VILA
llava/train/train.py
https://github.com/NVlabs/VILA/blob/master/llava/train/train.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 method if you want to ...
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
NVlabs/VILA
llava/train/train_llm_to_long.py
https://github.com/NVlabs/VILA/blob/master/llava/train/train_llm_to_long.py
Apache-2.0
def patched_normalize( image: np.ndarray, mean: Union[float, Iterable[float]], std: Union[float, Iterable[float]], data_format: Optional[ChannelDimension] = None, input_data_format: Optional[Union[str, ChannelDimension]] = None, ) -> np.ndarray: """ Normalizes `image` using the mean and stan...
Normalizes `image` using the mean and standard deviation specified by `mean` and `std`. image = (image - mean) / std Args: image (`np.ndarray`): The image to normalize. mean (`float` or `Iterable[float]`): The mean to use for normalization. std (`float` or ...
patched_normalize
python
NVlabs/VILA
llava/train/transformer_normalize_monkey_patch.py
https://github.com/NVlabs/VILA/blob/master/llava/train/transformer_normalize_monkey_patch.py
Apache-2.0
def training_step( self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]], num_items_in_batch=None ) -> 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. The dictionary will be unpac...
training_step
python
NVlabs/VILA
llava/train/transformer_normalize_monkey_patch.py
https://github.com/NVlabs/VILA/blob/master/llava/train/transformer_normalize_monkey_patch.py
Apache-2.0
def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None): """ 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 or self.compute_loss_func is ...
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
NVlabs/VILA
llava/train/transformer_normalize_monkey_patch.py
https://github.com/NVlabs/VILA/blob/master/llava/train/transformer_normalize_monkey_patch.py
Apache-2.0
def __init__( self, module=None, data_parallel_group=None, mem_efficient_linear=True, remote_device=None, pin_memory=False, config_dict_or_path=None, config=None, enabled=True, dtype=None, mpu=None, ): """A context manag...
A context manager to partition the model parameters during the model construction with MiCS partition strategy. Model states are partitioned to the number of devices specified via ``mics_shard_size`` field in the deepspeed config json file. The context manager also introduces hierarchica...
__init__
python
NVlabs/VILA
llava/train/deepspeed_replace/runtime/zero/mics.py
https://github.com/NVlabs/VILA/blob/master/llava/train/deepspeed_replace/runtime/zero/mics.py
Apache-2.0
def _convert_to_zero_parameters(self, ds_config, module, mpu): """overload the parent class function for convert the parameters""" log_dist(f"Convert to zero parameters from MiCS Offload manager", ranks=[0]) non_zero_params = [p for p in module.parameters() if not is_zero_param(p)] if no...
overload the parent class function for convert the parameters
_convert_to_zero_parameters
python
NVlabs/VILA
llava/train/deepspeed_replace/runtime/zero/mics.py
https://github.com/NVlabs/VILA/blob/master/llava/train/deepspeed_replace/runtime/zero/mics.py
Apache-2.0
def load_state_dict( self, state_dict_list, load_optimizer_states=True, load_from_fp32_weights=False, checkpoint_folder=None ): r"""Loading the ZeRO-3/MiCS partitioned checkpoints Because the self.dp_process_group is replaced with the communicator for partition group we can call the ...
Loading the ZeRO-3/MiCS partitioned checkpoints Because the self.dp_process_group is replaced with the communicator for partition group we can call the load_state_dict logic from ZeRO-3.
load_state_dict
python
NVlabs/VILA
llava/train/deepspeed_replace/runtime/zero/mics.py
https://github.com/NVlabs/VILA/blob/master/llava/train/deepspeed_replace/runtime/zero/mics.py
Apache-2.0
def all_to_all_4D(input: torch.tensor, scatter_idx: int = 2, gather_idx: int = 1, group=None) -> torch.tensor: """ all-to-all for QKV Args: input (torch.tensor): a tensor sharded along dim scatter dim scatter_idx (int): default 1 gather_idx (int): default 2 group : torch pro...
all-to-all for QKV Args: input (torch.tensor): a tensor sharded along dim scatter dim scatter_idx (int): default 1 gather_idx (int): default 2 group : torch process group Returns: torch.tensor: resharded tensor (bs, seqlen/P, hc, hs)
all_to_all_4D
python
NVlabs/VILA
llava/train/sequence_parallel/all_to_all.py
https://github.com/NVlabs/VILA/blob/master/llava/train/sequence_parallel/all_to_all.py
Apache-2.0
def all_to_all_5D(input: torch.tensor, scatter_idx: int = 3, gather_idx: int = 1, group=None) -> torch.tensor: """ all-to-all for QKV forward (bs, seqlen/N, 3, hc, hs) -> (bs, seqlen, 3, hc/N, hs) Args: input (torch.tensor): a tensor sharded along dim scatter dim scatter_idx (int): defa...
all-to-all for QKV forward (bs, seqlen/N, 3, hc, hs) -> (bs, seqlen, 3, hc/N, hs) Args: input (torch.tensor): a tensor sharded along dim scatter dim scatter_idx (int): default 1 gather_idx (int): default 2 group : torch process group Returns: torch.tensor: resh...
all_to_all_5D
python
NVlabs/VILA
llava/train/sequence_parallel/all_to_all.py
https://github.com/NVlabs/VILA/blob/master/llava/train/sequence_parallel/all_to_all.py
Apache-2.0
def set_pg_manager(sp_degree, sp_ring_degree=1, use_ulysses_low=True, ring_type=None): """ Set the process group manager for sequence parallelism. sp_degree = sp_ring_degree x sp_ulysses_degree """ # first check torch distributed group init and set device accordingly; # (DL) TODO: Whether this ...
Set the process group manager for sequence parallelism. sp_degree = sp_ring_degree x sp_ulysses_degree
set_pg_manager
python
NVlabs/VILA
llava/train/sequence_parallel/globals.py
https://github.com/NVlabs/VILA/blob/master/llava/train/sequence_parallel/globals.py
Apache-2.0
def forward( self, query: Tensor, key: Tensor, value: Tensor, *args: Any, attention_mask=None, dropout_p=0.0, softmax_scale=None, seqlens_in_batch=None, causal=False, window_size=(-1, -1), alibi_slopes=None, determin...
forward Arguments: query (Tensor): query input to the layer key (Tensor): key input to the layer value (Tensor): value input to the layer args: other args Returns: * output (Tensor): context output
forward
python
NVlabs/VILA
llava/train/sequence_parallel/hybrid_attn.py
https://github.com/NVlabs/VILA/blob/master/llava/train/sequence_parallel/hybrid_attn.py
Apache-2.0
def forward( self, query: Tensor, key: Tensor, value: Tensor, dropout_p=0.0, softmax_scale=None, causal=False, window_size=(-1, -1), alibi_slopes=None, deterministic=False, return_attn_probs=False, *args: Any, ) -> Tenso...
forward Arguments: query (Tensor): query input to the layer (bs, seqlen/P, hc, hs) key (Tensor): key input to the layer (bs, seqlen/P, hc_kv, hs) value (Tensor): value input to the layer (bs, seqlen/P, hc_kv, hs) args: other args Returns: * o...
forward
python
NVlabs/VILA
llava/train/sequence_parallel/hybrid_attn.py
https://github.com/NVlabs/VILA/blob/master/llava/train/sequence_parallel/hybrid_attn.py
Apache-2.0
def _flash_attention_forward( query_states: torch.Tensor, key_states: torch.Tensor, value_states: torch.Tensor, attention_mask: torch.Tensor, query_length: int, is_causal: bool, dropout: float = 0.0, position_ids: Optional[torch.Tensor] = None, softmax_scale: Optional[float] = None, ...
Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token first unpad the input, then computes the attention scores and pad the final attention scores. Args: query_states (`torch.Tensor`): Input query states to be passed to Flash Attent...
_flash_attention_forward
python
NVlabs/VILA
llava/train/sequence_parallel/monkey_patch.py
https://github.com/NVlabs/VILA/blob/master/llava/train/sequence_parallel/monkey_patch.py
Apache-2.0
def backward(ctx, grad_output_k, grad_output_v): """ For backward, we sum the copy head inside a query group. """ num_head_dim = ctx.num_head_dim num_heads_kv = ctx.num_heads_kv # we split the grad into query groups splits. grad_output_k_splits = torch.chunk(gra...
For backward, we sum the copy head inside a query group.
backward
python
NVlabs/VILA
llava/train/sequence_parallel/ulysses_attn.py
https://github.com/NVlabs/VILA/blob/master/llava/train/sequence_parallel/ulysses_attn.py
Apache-2.0
def unflatten_varlen_lse(lse, cu_seqlens, max_seqlen: int): """ Arguments: lse: (total_seqlen, nheads, 1) cu_seqlens: (batch_size + 1,) max_seqlen: int Return: unflatten_lse: (batch_size, nheads, max_seqlen) """ lse = lse.unsqueeze(dim=-1) batch_size = len(cu_seql...
Arguments: lse: (total_seqlen, nheads, 1) cu_seqlens: (batch_size + 1,) max_seqlen: int Return: unflatten_lse: (batch_size, nheads, max_seqlen)
unflatten_varlen_lse
python
NVlabs/VILA
llava/train/sequence_parallel/ring/triton_utils.py
https://github.com/NVlabs/VILA/blob/master/llava/train/sequence_parallel/ring/triton_utils.py
Apache-2.0
def top_k_top_p_filtering( logits: torch.FloatTensor, top_k: int = 0, top_p: float = 1.0, filter_value: float = -float("Inf"), min_tokens_to_keep: int = 1, ) -> torch.FloatTensor: """ Filter a distribution of logits using top-k and/or nucleus (top-p) filtering. Args: logits: log...
Filter a distribution of logits using top-k and/or nucleus (top-p) filtering. Args: logits: logits distribution shape (batch size, vocabulary size) top_k (`int`, *optional*, defaults to 0): If > 0, only keep the top k tokens with highest probability (top-k filtering) top_p ...
top_k_top_p_filtering
python
NVlabs/VILA
llava/trl/core.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/core.py
Apache-2.0
def flatten_dict(nested: Dict, sep: str = "/") -> Dict: """Flatten dictionary and concatenate nested keys with separator.""" def recurse(nest: Dict, prefix: str, into: Dict) -> None: for k, v in nest.items(): if sep in k: raise ValueError(f"separator '{sep}' not allowed to b...
Flatten dictionary and concatenate nested keys with separator.
flatten_dict
python
NVlabs/VILA
llava/trl/core.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/core.py
Apache-2.0
def convert_to_scalar(stats: Dict) -> Dict: """ Converts the stats from a flattened dict to single scalar dicts """ tensorboard_stats = {} for k, v in stats.items(): # for tensorboard compatibility - arrays and tensors are ignored with tensorboard # therefore we convert single elemen...
Converts the stats from a flattened dict to single scalar dicts
convert_to_scalar
python
NVlabs/VILA
llava/trl/core.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/core.py
Apache-2.0
def logprobs_from_logits(logits: torch.Tensor, labels: torch.Tensor, gather: bool = True) -> torch.Tensor: """ See: https://github.com/pytorch/pytorch/issues/563#issuecomment-330103591 """ logp = F.log_softmax(logits, dim=2) if not gather: return logp logpy = torch.gather(logp, 2, label...
See: https://github.com/pytorch/pytorch/issues/563#issuecomment-330103591
logprobs_from_logits
python
NVlabs/VILA
llava/trl/core.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/core.py
Apache-2.0
def masked_mean(values: torch.Tensor, mask: torch.Tensor, axis: Optional[bool] = None) -> torch.Tensor: """Compute mean of tensor with a masked values.""" if axis is not None: return (values * mask).sum(axis=axis) / mask.sum(axis=axis) else: return (values * mask).sum() / mask.sum()
Compute mean of tensor with a masked values.
masked_mean
python
NVlabs/VILA
llava/trl/core.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/core.py
Apache-2.0
def masked_var(values: torch.Tensor, mask: torch.Tensor, unbiased: bool = True) -> torch.Tensor: """Compute variance of tensor with masked values.""" mean = masked_mean(values, mask) centered_values = values - mean variance = masked_mean(centered_values**2, mask) if unbiased: mask_sum = mask...
Compute variance of tensor with masked values.
masked_var
python
NVlabs/VILA
llava/trl/core.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/core.py
Apache-2.0
def average_torch_dicts(list_of_dicts: List[Dict]) -> Dict: """Average values of a list of dicts with torch tensors.""" average_dict = dict() for key in list_of_dicts[0].keys(): average_dict[key] = torch.mean(torch.stack([d[key] for d in list_of_dicts]), axis=0) return average_dict
Average values of a list of dicts with torch tensors.
average_torch_dicts
python
NVlabs/VILA
llava/trl/core.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/core.py
Apache-2.0
def stats_to_np(stats_dict: Dict) -> Dict: """Cast all torch.tensors in dict to numpy arrays.""" new_dict = dict() for k, v in stats_dict.items(): if isinstance(v, torch.Tensor): new_dict[k] = v.detach().cpu() if new_dict[k].dtype == torch.bfloat16: new_dict[k...
Cast all torch.tensors in dict to numpy arrays.
stats_to_np
python
NVlabs/VILA
llava/trl/core.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/core.py
Apache-2.0
def set_seed(seed: int) -> None: """ Helper function for reproducible behavior to set the seed in `random`, `numpy`, and `torch`. Args: seed (`int`): The seed to set. """ random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) if is_xpu_available(): torch.xpu.manu...
Helper function for reproducible behavior to set the seed in `random`, `numpy`, and `torch`. Args: seed (`int`): The seed to set.
set_seed
python
NVlabs/VILA
llava/trl/core.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/core.py
Apache-2.0
def randn_tensor( shape: Union[Tuple, List], generator: Optional[Union[List[torch.Generator], torch.Generator]] = None, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None, layout: Optional[torch.layout] = None, ) -> torch.Tensor: """A helper function to create random tens...
A helper function to create random tensors on the desired `device` with the desired `dtype`. When passing a list of generators, you can seed each batch size individually. If CPU generators are passed, the tensor is always created on the CPU.
randn_tensor
python
NVlabs/VILA
llava/trl/core.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/core.py
Apache-2.0
def is_npu_available() -> bool: """Checks if `torch_npu` is installed and potentially if a NPU is in the environment""" if importlib.util.find_spec("torch") is None or importlib.util.find_spec("torch_npu") is None: return False import torch import torch_npu # noqa: F401 return hasattr(tor...
Checks if `torch_npu` is installed and potentially if a NPU is in the environment
is_npu_available
python
NVlabs/VILA
llava/trl/import_utils.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/import_utils.py
Apache-2.0
def __call__(self, input_ids, scores, **kwargs): """Returns true if all generated sequences contain any of the stop strings.""" if self.first_call: self.generated_tokens = [1 for _ in range(input_ids.shape[0])] self.start_length = input_ids.shape[-1] - 1 self.first_ca...
Returns true if all generated sequences contain any of the stop strings.
__call__
python
NVlabs/VILA
llava/trl/environment/base_environment.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/environment/base_environment.py
Apache-2.0
def __init__(self, text, tokens, system=True): """ Initialize TextHistory. args: text (`str`): The text of the first segment. tokens (`torch.LongTensor`): The tokens of the first segment. system (`bool`, *optional*): Whether the first segment is a system or u...
Initialize TextHistory. args: text (`str`): The text of the first segment. tokens (`torch.LongTensor`): The tokens of the first segment. system (`bool`, *optional*): Whether the first segment is a system or user segment.
__init__
python
NVlabs/VILA
llava/trl/environment/base_environment.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/environment/base_environment.py
Apache-2.0
def append_segment(self, text, tokens, system=True): """ Append a new segment to the history. args: text (`str`): The text of the new segment. tokens (`torch.LongTensor`): The tokens of the new segment. system (`bool`, *optional*): Whether the new segment is ...
Append a new segment to the history. args: text (`str`): The text of the new segment. tokens (`torch.LongTensor`): The tokens of the new segment. system (`bool`, *optional*): Whether the new segment is a system or user segment.
append_segment
python
NVlabs/VILA
llava/trl/environment/base_environment.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/environment/base_environment.py
Apache-2.0
def split_query_response_tokens(self): """ Split the tokens into query and response tokens. """ split_index = self.token_spans[0][1] query = self.tokens[:split_index] response = self.tokens[split_index:] mask = self.token_masks[split_index:] return query,...
Split the tokens into query and response tokens.
split_query_response_tokens
python
NVlabs/VILA
llava/trl/environment/base_environment.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/environment/base_environment.py
Apache-2.0
def __init__( self, model=None, tokenizer=None, tools=None, reward_fn=None, prompt=None, max_turns=4, max_tool_reponse=100, max_length=None, generation_kwargs=None, ): """ Initialize TextEnvironment. Args: ...
Initialize TextEnvironment. Args: model (`PreTrainedModelWrapper`): The model to use for generation. tokenizer (`transformers.PreTrainedTokenizer`): The tokenizer to use for generation. tools (list): A list of tools to use for interaction. reward_fn (fun...
__init__
python
NVlabs/VILA
llava/trl/environment/base_environment.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/environment/base_environment.py
Apache-2.0
def run(self, queries, **rewards_kwargs): """ Run the environment on a list of queries. Args: queries (list[str]): A list of queries to run the model in the environment on. """ turns = 0 queries = [self.prompt + task for task in queries] queries_toke...
Run the environment on a list of queries. Args: queries (list[str]): A list of queries to run the model in the environment on.
run
python
NVlabs/VILA
llava/trl/environment/base_environment.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/environment/base_environment.py
Apache-2.0
def step(self, history): """ Step the environment forward one turn. Args: history (`TextHistory`): The history to step forward. """ truncated, ended = self.task_end_check(history) if ended: history.complete(truncated=truncated) if history....
Step the environment forward one turn. Args: history (`TextHistory`): The history to step forward.
step
python
NVlabs/VILA
llava/trl/environment/base_environment.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/environment/base_environment.py
Apache-2.0
def parse_tool_call(self, text): """ Parse request string. Expected format: <request><tool_name>query<call> """ result = re.search(f"(?<={self.request_token}).*?(?={self.call_token})", text, re.DOTALL) # if we can't find a <request>/<call> span we return none if result i...
Parse request string. Expected format: <request><tool_name>query<call>
parse_tool_call
python
NVlabs/VILA
llava/trl/environment/base_environment.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/environment/base_environment.py
Apache-2.0
def compute_reward(self, histories, **reward_kwargs): """ Compute the reward for a list of histories. """ rewards = self.reward_fn([history.last_text_segment for history in histories], **reward_kwargs) for history, reward in zip(histories, rewards): history.reward = r...
Compute the reward for a list of histories.
compute_reward
python
NVlabs/VILA
llava/trl/environment/base_environment.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/environment/base_environment.py
Apache-2.0
def generate(self, histories): """ Generate responses for a list of histories. """ active_histories = [i for i, history in enumerate(histories) if not history.completed] query_tensors = [histories[i].tokens for i in active_histories] response_tensors = self._generate_bat...
Generate responses for a list of histories.
generate
python
NVlabs/VILA
llava/trl/environment/base_environment.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/environment/base_environment.py
Apache-2.0
def tasks_end_check(self, histories, model_turn=True): """ Check if the current generation sequences have finished. """ for history in histories: if not history.completed: truncated, ended = self.task_end_check(history, model_turn=model_turn) i...
Check if the current generation sequences have finished.
tasks_end_check
python
NVlabs/VILA
llava/trl/environment/base_environment.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/environment/base_environment.py
Apache-2.0
def task_end_check(self, history, model_turn=True): """ Check if the current generation sequence has finished. """ truncated = False ended = False if history.completed: return truncated, ended if self.max_length is not None and len(self.tokenizer(histo...
Check if the current generation sequence has finished.
task_end_check
python
NVlabs/VILA
llava/trl/environment/base_environment.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/environment/base_environment.py
Apache-2.0
def _generate_batched( self, query_tensors, batch_size: int = 16, pad_to_multiple_of: int = None, ): """ Generate responses for a list of query tensors. args: query_tensors (list[torch.Tensor]): A list of query tensors to generate responses for. ...
Generate responses for a list of query tensors. args: query_tensors (list[torch.Tensor]): A list of query tensors to generate responses for. batch_size (int): The batch size to use for generation. pad_to_multiple_of (int): The padding length to use for generation. ...
_generate_batched
python
NVlabs/VILA
llava/trl/environment/base_environment.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/environment/base_environment.py
Apache-2.0
def __init__( self, model: PreTrainedModelWrapper, tokenizer: Union[PreTrainedTokenizer, PreTrainedTokenizerFast], queries_to_scores: Callable[[List[str]], List[float]], length_sampler: Any, sample_size: int = 4, seed: Optional[int] = None, n_candidates: i...
Initialize the sampler for best-of-n generation Args: model (`PreTrainedModelWrapper`): The pretrained model to use for generation tokenizer (`PreTrainedTokenizer` or `PreTrainedTokenizerFast`): Tokenizer associated with the pretrained model ...
__init__
python
NVlabs/VILA
llava/trl/extras/best_of_n_sampler.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/extras/best_of_n_sampler.py
Apache-2.0
def generate( self, tokenized_query: Union[List[int], torch.Tensor, List[torch.Tensor], List[List[int]]], skip_special_tokens: bool = True, device: Optional[Union[str, torch.device]] = None, **generation_kwargs, ) -> List[List[str]]: r""" Generate the best of ...
Generate the best of n samples for input queries Args: tokenized_query (`List[int]` or `torch.Tensor` or `List[torch.Tensor]` or `List[int]`): represents either a single tokenized query (a single tensor or a list of integers) or a batch of tokenized queries (a list of tenso...
generate
python
NVlabs/VILA
llava/trl/extras/best_of_n_sampler.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/extras/best_of_n_sampler.py
Apache-2.0
def conversations_formatting_function(tokenizer: AutoTokenizer, messages_field: Literal["messages", "conversations"]): r""" return a callable function that takes in a "messages" dataset and returns a formatted dataset, based on the tokenizer apply chat template to the dataset """ def format_dataset...
return a callable function that takes in a "messages" dataset and returns a formatted dataset, based on the tokenizer apply chat template to the dataset
conversations_formatting_function
python
NVlabs/VILA
llava/trl/extras/dataset_formatting.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/extras/dataset_formatting.py
Apache-2.0
def instructions_formatting_function(tokenizer: AutoTokenizer): r""" return a callable function that takes in an "instructions" dataset and returns a formatted dataset, based on the tokenizer apply chat template to the dataset """ def format_dataset(examples): if isinstance(examples["prompt...
return a callable function that takes in an "instructions" dataset and returns a formatted dataset, based on the tokenizer apply chat template to the dataset
instructions_formatting_function
python
NVlabs/VILA
llava/trl/extras/dataset_formatting.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/extras/dataset_formatting.py
Apache-2.0
def get_formatting_func_from_dataset( dataset: Union[Dataset, ConstantLengthDataset], tokenizer: AutoTokenizer ) -> Optional[Callable]: r""" Finds the correct formatting function based on the dataset structure. Currently supported datasets are: - `ChatML` with [{"role": str, "content": str}] - `inst...
Finds the correct formatting function based on the dataset structure. Currently supported datasets are: - `ChatML` with [{"role": str, "content": str}] - `instruction` with [{"prompt": str, "completion": str}] Args: dataset (Dataset): User dataset tokenizer (AutoTokenizer): Tokenizer u...
get_formatting_func_from_dataset
python
NVlabs/VILA
llava/trl/extras/dataset_formatting.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/extras/dataset_formatting.py
Apache-2.0
def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): r""" Instantiates a new model from a pretrained model from `transformers`. The pretrained model is loaded using the `from_pretrained` method of the `transformers.PreTrainedModel` class. The arguments that are...
Instantiates a new model from a pretrained model from `transformers`. The pretrained model is loaded using the `from_pretrained` method of the `transformers.PreTrainedModel` class. The arguments that are specific to the `transformers.PreTrainedModel` class are passed along this method a...
from_pretrained
python
NVlabs/VILA
llava/trl/models/modeling_base.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/models/modeling_base.py
Apache-2.0
def _get_current_device(cls): r""" Get the current device. For GPU, we return the local process index using the `accelerate.PartialState` object to handle corner cases when running scripts in distributed environments. Returns: current_device (`Union[int, str]`): ...
Get the current device. For GPU, we return the local process index using the `accelerate.PartialState` object to handle corner cases when running scripts in distributed environments. Returns: current_device (`Union[int, str]`): The current device.
_get_current_device
python
NVlabs/VILA
llava/trl/models/modeling_base.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/models/modeling_base.py
Apache-2.0
def _split_kwargs(cls, kwargs): """ Separate the kwargs from the arguments that we support inside `supported_args` and the ones that we don't. """ check_peft_kwargs = False if is_peft_available(): from peft import prepare_model_for_kbit_training ...
Separate the kwargs from the arguments that we support inside `supported_args` and the ones that we don't.
_split_kwargs
python
NVlabs/VILA
llava/trl/models/modeling_base.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/models/modeling_base.py
Apache-2.0
def add_and_load_reward_modeling_adapter( cls, pretrained_model, adapter_model_id, adapter_name="reward_model_adapter", token=None ): r""" Add and load a reward modeling adapter. This method can only be used if the model is a `PeftModel` and if you have initialized the model with the...
Add and load a reward modeling adapter. This method can only be used if the model is a `PeftModel` and if you have initialized the model with the `reward_modeling_adapter_id` argument, pointing to the id of the reward modeling adapter. The latest needs also to contain the score head in ...
add_and_load_reward_modeling_adapter
python
NVlabs/VILA
llava/trl/models/modeling_base.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/models/modeling_base.py
Apache-2.0
def save_pretrained(self, *args, **kwargs): r""" Save the pretrained model to a directory. This method is a wrapper around `transformers.PreTrainedModel.save_pretrained`. Please refer to the documentation of `transformers.PreTrainedModel.save_pretrained` for more information. Ar...
Save the pretrained model to a directory. This method is a wrapper around `transformers.PreTrainedModel.save_pretrained`. Please refer to the documentation of `transformers.PreTrainedModel.save_pretrained` for more information. Args: *args (`list`, *optional*): ...
save_pretrained
python
NVlabs/VILA
llava/trl/models/modeling_base.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/models/modeling_base.py
Apache-2.0
def compute_reward_score(self, input_ids, attention_mask=None, **kwargs): r""" Computes the reward score for a given input. The method has first to enable the adapter and then compute the reward score. After that the model disables the reward modeling adapter and enables the default ppo ...
Computes the reward score for a given input. The method has first to enable the adapter and then compute the reward score. After that the model disables the reward modeling adapter and enables the default ppo adapter again.
compute_reward_score
python
NVlabs/VILA
llava/trl/models/modeling_base.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/models/modeling_base.py
Apache-2.0
def create_reference_model( model: PreTrainedModelWrapper, num_shared_layers: int = None, pattern: str = None ) -> PreTrainedModelWrapper: """ Creates a static reference copy of a model. Note that model will be in `.eval()` mode. Args: model (`PreTrainedModelWrapper`): The model to be copied. ...
Creates a static reference copy of a model. Note that model will be in `.eval()` mode. Args: model (`PreTrainedModelWrapper`): The model to be copied. num_shared_layers (`int`, *optional*): The number of initial layers that are shared between both models and kept frozen. pattern (`str`...
create_reference_model
python
NVlabs/VILA
llava/trl/models/modeling_base.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/models/modeling_base.py
Apache-2.0
def _left_broadcast(input_tensor, shape): """ As opposed to the default direction of broadcasting (right to left), this function broadcasts from left to right Args: input_tensor (`torch.FloatTensor`): is the tensor to broadcast shape (`Tuple[int]`): is the shape to broadcast ...
As opposed to the default direction of broadcasting (right to left), this function broadcasts from left to right Args: input_tensor (`torch.FloatTensor`): is the tensor to broadcast shape (`Tuple[int]`): is the shape to broadcast to
_left_broadcast
python
NVlabs/VILA
llava/trl/models/modeling_sd_base.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/models/modeling_sd_base.py
Apache-2.0
def __init__(self, pretrained_model, **kwargs): r""" Initializes the model. Args: pretrained_model (`transformers.PreTrainedModel`): The model to wrap. It should be a causal language model such as GPT2. or any model mapped inside the `AutoModelForCaus...
Initializes the model. Args: pretrained_model (`transformers.PreTrainedModel`): The model to wrap. It should be a causal language model such as GPT2. or any model mapped inside the `AutoModelForCausalLM` class. kwargs (`dict`, `optional`): ...
__init__
python
NVlabs/VILA
llava/trl/models/modeling_value_head.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/models/modeling_value_head.py
Apache-2.0
def _init_weights(self, **kwargs): r""" Initializes the weights of the value head. The default initialization strategy is random. Users can pass a different initialization strategy by passing the `v_head_init_strategy` argument when calling `.from_pretrained`. Supported strategies are: ...
Initializes the weights of the value head. The default initialization strategy is random. Users can pass a different initialization strategy by passing the `v_head_init_strategy` argument when calling `.from_pretrained`. Supported strategies are: - `normal`: initializes the weights with...
_init_weights
python
NVlabs/VILA
llava/trl/models/modeling_value_head.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/models/modeling_value_head.py
Apache-2.0
def forward( self, input_ids=None, past_key_values=None, attention_mask=None, **kwargs, ): r""" Applies a forward pass to the wrapped model and returns the logits of the value head. Args: input_ids (`torch.LongTensor` of shape `(batch_size...
Applies a forward pass to the wrapped model and returns the logits of the value head. Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. past_key_values (`tuple(tuple(torch.FloatTens...
forward
python
NVlabs/VILA
llava/trl/models/modeling_value_head.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/models/modeling_value_head.py
Apache-2.0
def state_dict(self, *args, **kwargs): r""" Returns the state dictionary of the model. We add the state dictionary of the value head to the state dictionary of the wrapped model by prepending the key with `v_head.`. """ if not self.is_peft_model: pretrained_model_stat...
Returns the state dictionary of the model. We add the state dictionary of the value head to the state dictionary of the wrapped model by prepending the key with `v_head.`.
state_dict
python
NVlabs/VILA
llava/trl/models/modeling_value_head.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/models/modeling_value_head.py
Apache-2.0
def post_init(self, state_dict): r""" We add the state dictionary of the value head to the state dictionary of the wrapped model by prepending the key with `v_head.`. This function removes the `v_head.` prefix from the keys of the value head state dictionary. """ for k in...
We add the state dictionary of the value head to the state dictionary of the wrapped model by prepending the key with `v_head.`. This function removes the `v_head.` prefix from the keys of the value head state dictionary.
post_init
python
NVlabs/VILA
llava/trl/models/modeling_value_head.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/models/modeling_value_head.py
Apache-2.0
def set_device_hook(module, input, outputs): r""" A hook that sets the device of the output of the model to the device of the first parameter of the model. Args: module (`nn.Module`): The module to which the hoo...
A hook that sets the device of the output of the model to the device of the first parameter of the model. Args: module (`nn.Module`): The module to which the hook is attached. input (`tuple`): ...
set_device_hook
python
NVlabs/VILA
llava/trl/models/modeling_value_head.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/models/modeling_value_head.py
Apache-2.0
def _init_weights(self, **kwargs): r""" We initialize the weights of the value head. """ initializer_range = kwargs.pop("v_head_initializer_range", 0.2) # random init by default init_strategy = kwargs.pop("v_head_init_strategy", None) if init_strategy is None: ...
We initialize the weights of the value head.
_init_weights
python
NVlabs/VILA
llava/trl/models/modeling_value_head.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/models/modeling_value_head.py
Apache-2.0
def setup_chat_format( model: PreTrainedModel, tokenizer: PreTrainedTokenizer, format: Optional[Literal["chatml"]] = "chatml", resize_to_multiple_of: Optional[int] = None, ) -> Tuple[PreTrainedModel, PreTrainedTokenizer]: """ Setup chat format by adding special tokens to the tokenizer, setting t...
Setup chat format by adding special tokens to the tokenizer, setting the correct format, and extending the embedding layer of the model based on the new special tokens. Args: model (`~transformers.PreTrainedModel`): The model to be modified. tokenizer (`~transformers.PreTrainedTokenizer`): The tok...
setup_chat_format
python
NVlabs/VILA
llava/trl/models/utils.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/models/utils.py
Apache-2.0
def step(self, epoch: int, global_step: int): """ Perform a single step of training. Args: epoch (int): The current epoch. global_step (int): The current global step. Side Effects: - Model weights are updated - Logs the statistics to the ...
Perform a single step of training. Args: epoch (int): The current epoch. global_step (int): The current global step. Side Effects: - Model weights are updated - Logs the statistics to the accelerator trackers. - If `self.image_sample...
step
python
NVlabs/VILA
llava/trl/trainer/ddpo_trainer.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/trainer/ddpo_trainer.py
Apache-2.0
def calculate_loss(self, latents, timesteps, next_latents, log_probs, advantages, embeds): """ Calculate the loss for a batch of an unpacked sample Args: latents (torch.Tensor): The latents sampled from the diffusion model, shape: [batch_size, num_channels_latents, h...
Calculate the loss for a batch of an unpacked sample Args: latents (torch.Tensor): The latents sampled from the diffusion model, shape: [batch_size, num_channels_latents, height, width] timesteps (torch.Tensor): The timesteps sampled from the dif...
calculate_loss
python
NVlabs/VILA
llava/trl/trainer/ddpo_trainer.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/trainer/ddpo_trainer.py
Apache-2.0
def _generate_samples(self, iterations, batch_size): """ Generate samples from the model Args: iterations (int): Number of iterations to generate samples for batch_size (int): Batch size to use for sampling Returns: samples (List[Dict[str, torch.Tens...
Generate samples from the model Args: iterations (int): Number of iterations to generate samples for batch_size (int): Batch size to use for sampling Returns: samples (List[Dict[str, torch.Tensor]]), prompt_image_pairs (List[List[Any]])
_generate_samples
python
NVlabs/VILA
llava/trl/trainer/ddpo_trainer.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/trainer/ddpo_trainer.py
Apache-2.0
def _train_batched_samples(self, inner_epoch, epoch, global_step, batched_samples): """ Train on a batch of samples. Main training segment Args: inner_epoch (int): The current inner epoch epoch (int): The current epoch global_step (int): The current global st...
Train on a batch of samples. Main training segment Args: inner_epoch (int): The current inner epoch epoch (int): The current epoch global_step (int): The current global step batched_samples (List[Dict[str, torch.Tensor]]): The batched samples to train on...
_train_batched_samples
python
NVlabs/VILA
llava/trl/trainer/ddpo_trainer.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/trainer/ddpo_trainer.py
Apache-2.0
def train(self, epochs: Optional[int] = None): """ Train the model for a given number of epochs """ global_step = 0 if epochs is None: epochs = self.config.num_epochs for epoch in range(self.first_epoch, epochs): global_step = self.step(epoch, glob...
Train the model for a given number of epochs
train
python
NVlabs/VILA
llava/trl/trainer/ddpo_trainer.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/trainer/ddpo_trainer.py
Apache-2.0
def create_model_card(self, path: str, model_name: Optional[str] = "TRL DDPO 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 DDPO M...
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 DDPO Model`.
create_model_card
python
NVlabs/VILA
llava/trl/trainer/ddpo_trainer.py
https://github.com/NVlabs/VILA/blob/master/llava/trl/trainer/ddpo_trainer.py
Apache-2.0
def get_train_dataloader(self) -> DataLoader: """ Returns the training [`~torch.utils.data.DataLoader`]. Subclass of transformers.src.transformers.trainer.get_train_dataloader to precompute `ref_log_probs`. """ if self.precompute_ref_log_probs and not self._precomputed_train_re...
Returns the training [`~torch.utils.data.DataLoader`]. Subclass of transformers.src.transformers.trainer.get_train_dataloader to precompute `ref_log_probs`.
get_train_dataloader
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_eval_dataloader(self, eval_dataset: Optional[Dataset] = None) -> DataLoader: """ Returns the evaluation [`~torch.utils.data.DataLoader`]. Subclass of transformers.src.transformers.trainer.get_eval_dataloader to precompute `ref_log_probs`. Args: eval_dataset (`torch....
Returns the evaluation [`~torch.utils.data.DataLoader`]. Subclass of transformers.src.transformers.trainer.get_eval_dataloader to precompute `ref_log_probs`. Args: eval_dataset (`torch.utils.data.Dataset`, *optional*): If provided, will override `self.eval_dataset`...
get_eval_dataloader
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 build_tokenized_answer(self, prompt, answer): """ Llama tokenizer does satisfy `enc(a + b) = enc(a) + enc(b)`. It does ensure `enc(a + b) = enc(a) + enc(a + b)[len(enc(a)):]`. Reference: https://github.com/EleutherAI/lm-evaluation-harness/pull/531#issuecomment-1595586257 ...
Llama tokenizer does satisfy `enc(a + b) = enc(a) + enc(b)`. It does ensure `enc(a + b) = enc(a) + enc(a + b)[len(enc(a)):]`. Reference: https://github.com/EleutherAI/lm-evaluation-harness/pull/531#issuecomment-1595586257
build_tokenized_answer
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 tokenize_row(self, feature, model: Optional[Union[PreTrainedModel, nn.Module]] = None) -> Dict: """Tokenize a single row from a DPO specific dataset. At this stage, we don't convert to PyTorch tensors yet; we just handle the truncation in case the prompt + chosen or prompt + rejected respon...
Tokenize a single row from a DPO specific dataset. 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/...
tokenize_row
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 null_ref_context(self): """Context manager for handling null reference model (that is, peft adapter manipulation).""" with ( self.accelerator.unwrap_model(self.model).disable_adapter() if self.is_peft_model and not self.ref_adapter_name else nullcontext() ...
Context manager for handling null reference model (that is, peft adapter manipulation).
null_ref_context
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 compute_reference_log_probs(self, padded_batch: Dict) -> Dict: """Computes log probabilities of the reference model for a single padded batch of a DPO specific dataset.""" compte_ref_context_manager = torch.cuda.amp.autocast if self._peft_has_been_casted_to_bf16 else nullcontext # compute r...
Computes log probabilities of the reference model for a single padded batch of a DPO specific dataset.
compute_reference_log_probs
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