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 clear(self):
"""
Clears the attention bank of all reader attention modules.
This method is used when the `reference_attn` attribute is set to `True`.
It clears the attention bank of all reader attention modules inside the UNet
model based on the selected `fusion_blocks` mode... |
Clears the attention bank of all reader attention modules.
This method is used when the `reference_attn` attribute is set to `True`.
It clears the attention bank of all reader attention modules inside the UNet
model based on the selected `fusion_blocks` mode.
If `fusion_blocks... | clear | python | fudan-generative-vision/hallo | hallo/models/mutual_self_attention.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/models/mutual_self_attention.py | MIT |
def forward(self, x):
"""
Forward pass of the InflatedConv3d layer.
Args:
x (torch.Tensor): Input tensor to the layer.
Returns:
torch.Tensor: Output tensor after applying the InflatedConv3d layer.
"""
video_length = x.shape[2]
x = rearra... |
Forward pass of the InflatedConv3d layer.
Args:
x (torch.Tensor): Input tensor to the layer.
Returns:
torch.Tensor: Output tensor after applying the InflatedConv3d layer.
| forward | python | fudan-generative-vision/hallo | hallo/models/resnet.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/models/resnet.py | MIT |
def forward(self, x):
"""
Performs a forward pass through the CustomClassName.
:param x: Input tensor of shape (batch_size, channels, video_length, height, width).
:return: Output tensor of shape (batch_size, channels, video_length, height, width).
"""
video_leng... |
Performs a forward pass through the CustomClassName.
:param x: Input tensor of shape (batch_size, channels, video_length, height, width).
:return: Output tensor of shape (batch_size, channels, video_length, height, width).
| forward | python | fudan-generative-vision/hallo | hallo/models/resnet.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/models/resnet.py | MIT |
def forward(self, hidden_states, output_size=None):
"""
Forward pass of the Upsample3D class.
Args:
hidden_states (torch.Tensor): Input tensor to be upsampled.
output_size (tuple, optional): Desired output size of the upsampled tensor.
Returns:
torch... |
Forward pass of the Upsample3D class.
Args:
hidden_states (torch.Tensor): Input tensor to be upsampled.
output_size (tuple, optional): Desired output size of the upsampled tensor.
Returns:
torch.Tensor: Upsampled tensor.
Raises:
Asserti... | forward | python | fudan-generative-vision/hallo | hallo/models/resnet.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/models/resnet.py | MIT |
def __init__(
self, channels, use_conv=False, out_channels=None, padding=1, name="conv"
):
"""
Downsamples the given input in the 3D space.
Args:
channels: The number of input channels.
use_conv: Whether to use a convolutional layer for downsampling.
... |
Downsamples the given input in the 3D space.
Args:
channels: The number of input channels.
use_conv: Whether to use a convolutional layer for downsampling.
out_channels: The number of output channels. If None, the input channels are used.
padding: The am... | __init__ | python | fudan-generative-vision/hallo | hallo/models/resnet.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/models/resnet.py | MIT |
def forward(self, hidden_states):
"""
Forward pass for the Downsample3D class.
Args:
hidden_states (torch.Tensor): Input tensor to be downsampled.
Returns:
torch.Tensor: Downsampled tensor.
Raises:
AssertionError: If the number of channels i... |
Forward pass for the Downsample3D class.
Args:
hidden_states (torch.Tensor): Input tensor to be downsampled.
Returns:
torch.Tensor: Downsampled tensor.
Raises:
AssertionError: If the number of channels in the input tensor does not match the expecte... | forward | python | fudan-generative-vision/hallo | hallo/models/resnet.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/models/resnet.py | MIT |
def forward(self, input_tensor, temb):
"""
Forward pass for the ResnetBlock3D class.
Args:
input_tensor (torch.Tensor): Input tensor to the ResnetBlock3D layer.
temb (torch.Tensor): Token embedding tensor.
Returns:
torch.Tensor: Output tensor after p... |
Forward pass for the ResnetBlock3D class.
Args:
input_tensor (torch.Tensor): Input tensor to the ResnetBlock3D layer.
temb (torch.Tensor): Token embedding tensor.
Returns:
torch.Tensor: Output tensor after passing through the ResnetBlock3D layer.
| forward | python | fudan-generative-vision/hallo | hallo/models/resnet.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/models/resnet.py | MIT |
def forward(
self,
hidden_states: torch.Tensor,
encoder_hidden_states: Optional[torch.Tensor] = None,
timestep: Optional[torch.LongTensor] = None,
_added_cond_kwargs: Dict[str, torch.Tensor] = None,
class_labels: Optional[torch.LongTensor] = None,
cross_attention_... |
The [`Transformer2DModel`] forward method.
Args:
hidden_states (`torch.LongTensor` of shape `(batch size, num latent pixels)` if discrete,
`torch.FloatTensor` of shape `(batch size, channel, height, width)` if continuous):
Input `hidden_states`.
enc... | forward | python | fudan-generative-vision/hallo | hallo/models/transformer_2d.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/models/transformer_2d.py | MIT |
def forward(
self,
hidden_states,
encoder_hidden_states=None,
attention_mask=None,
full_mask=None,
face_mask=None,
lip_mask=None,
motion_scale=None,
timestep=None,
return_dict: bool = True,
):
"""
Forward pass for the Tr... |
Forward pass for the Transformer3DModel.
Args:
hidden_states (torch.Tensor): The input hidden states.
encoder_hidden_states (torch.Tensor, optional): The input encoder hidden states.
attention_mask (torch.Tensor, optional): The attention mask.
full_mask ... | forward | python | fudan-generative-vision/hallo | hallo/models/transformer_3d.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/models/transformer_3d.py | MIT |
def get_down_block(
down_block_type: str,
num_layers: int,
in_channels: int,
out_channels: int,
temb_channels: int,
add_downsample: bool,
resnet_eps: float,
resnet_act_fn: str,
transformer_layers_per_block: int = 1,
num_attention_heads: Optional[int] = None,
resnet_groups: Op... | This function creates and returns a UpBlock2D or CrossAttnUpBlock2D object based on the given up_block_type.
Args:
up_block_type (str): The type of up block to create. Must be either "UpBlock2D" or "CrossAttnUpBlock2D".
num_layers (int): The number of layers in the ResNet block.
in_channel... | get_down_block | python | fudan-generative-vision/hallo | hallo/models/unet_2d_blocks.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/models/unet_2d_blocks.py | MIT |
def forward(
self, hidden_states: torch.FloatTensor, temb: Optional[torch.FloatTensor] = None
) -> torch.FloatTensor:
"""
Forward pass of the UNetMidBlock2D class.
Args:
hidden_states (torch.FloatTensor): The input tensor to the UNetMidBlock2D.
temb (Optional... |
Forward pass of the UNetMidBlock2D class.
Args:
hidden_states (torch.FloatTensor): The input tensor to the UNetMidBlock2D.
temb (Optional[torch.FloatTensor], optional): The token embedding tensor. Defaults to None.
Returns:
torch.FloatTensor: The output ten... | forward | python | fudan-generative-vision/hallo | hallo/models/unet_2d_blocks.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/models/unet_2d_blocks.py | MIT |
def forward(
self,
hidden_states: torch.FloatTensor,
temb: Optional[torch.FloatTensor] = None,
encoder_hidden_states: Optional[torch.FloatTensor] = None,
attention_mask: Optional[torch.FloatTensor] = None,
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
e... |
Forward pass for the UNetMidBlock2DCrossAttn class.
Args:
hidden_states (torch.FloatTensor): The input hidden states tensor.
temb (Optional[torch.FloatTensor], optional): The optional tensor for time embeddings.
encoder_hidden_states (Optional[torch.FloatTensor], op... | forward | python | fudan-generative-vision/hallo | hallo/models/unet_2d_blocks.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/models/unet_2d_blocks.py | MIT |
def forward(
self,
hidden_states: torch.FloatTensor,
temb: Optional[torch.FloatTensor] = None,
encoder_hidden_states: Optional[torch.FloatTensor] = None,
attention_mask: Optional[torch.FloatTensor] = None,
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
e... |
Forward pass for the CrossAttnDownBlock2D class.
Args:
hidden_states (torch.FloatTensor): The input hidden states.
temb (Optional[torch.FloatTensor], optional): The token embeddings. Defaults to None.
encoder_hidden_states (Optional[torch.FloatTensor], optional): Th... | forward | python | fudan-generative-vision/hallo | hallo/models/unet_2d_blocks.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/models/unet_2d_blocks.py | MIT |
def forward(
self,
hidden_states: torch.FloatTensor,
temb: Optional[torch.FloatTensor] = None,
scale: float = 1.0,
) -> Tuple[torch.FloatTensor, Tuple[torch.FloatTensor, ...]]:
"""
Forward pass of the DownBlock2D class.
Args:
hidden_states (torch.... |
Forward pass of the DownBlock2D class.
Args:
hidden_states (torch.FloatTensor): The input tensor to the DownBlock2D layer.
temb (Optional[torch.FloatTensor], optional): The token embedding tensor. Defaults to None.
scale (float, optional): The scale factor for the i... | forward | python | fudan-generative-vision/hallo | hallo/models/unet_2d_blocks.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/models/unet_2d_blocks.py | MIT |
def forward(
self,
hidden_states: torch.FloatTensor,
res_hidden_states_tuple: Tuple[torch.FloatTensor, ...],
temb: Optional[torch.FloatTensor] = None,
encoder_hidden_states: Optional[torch.FloatTensor] = None,
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
... |
Forward pass for the CrossAttnUpBlock2D class.
Args:
self (CrossAttnUpBlock2D): An instance of the CrossAttnUpBlock2D class.
hidden_states (torch.FloatTensor): The input hidden states tensor.
res_hidden_states_tuple (Tuple[torch.FloatTensor, ...]): A tuple of residu... | forward | python | fudan-generative-vision/hallo | hallo/models/unet_2d_blocks.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/models/unet_2d_blocks.py | MIT |
def forward(
self,
hidden_states: torch.FloatTensor,
res_hidden_states_tuple: Tuple[torch.FloatTensor, ...],
temb: Optional[torch.FloatTensor] = None,
upsample_size: Optional[int] = None,
scale: float = 1.0,
) -> torch.FloatTensor:
"""
Forward pass fo... |
Forward pass for the UpBlock2D class.
Args:
self (UpBlock2D): An instance of the UpBlock2D class.
hidden_states (torch.FloatTensor): The input tensor to the block.
res_hidden_states_tuple (Tuple[torch.FloatTensor, ...]): A tuple of residual hidden states.
... | forward | python | fudan-generative-vision/hallo | hallo/models/unet_2d_blocks.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/models/unet_2d_blocks.py | MIT |
def attn_processors(self) -> Dict[str, AttentionProcessor]:
r"""
Returns:
`dict` of attention processors: A dictionary containing all attention processors used in the model with
indexed by its weight name.
"""
# set recursively
processors = {}
def... |
Returns:
`dict` of attention processors: A dictionary containing all attention processors used in the model with
indexed by its weight name.
| attn_processors | python | fudan-generative-vision/hallo | hallo/models/unet_2d_condition.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/models/unet_2d_condition.py | MIT |
def set_attn_processor(
self,
processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]],
_remove_lora=False,
):
r"""
Sets the attention processor to use to compute attention.
Parameters:
processor (`dict` of `AttentionProcessor` or only `Attenti... |
Sets the attention processor to use to compute attention.
Parameters:
processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
The instantiated processor class or a dictionary of processor classes that will be set as the processor
for **all**... | set_attn_processor | python | fudan-generative-vision/hallo | hallo/models/unet_2d_condition.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/models/unet_2d_condition.py | MIT |
def set_default_attn_processor(self):
"""
Disables custom attention processors and sets the default attention implementation.
"""
if all(
proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS
for proc in self.attn_processors.values()
):
processor = A... |
Disables custom attention processors and sets the default attention implementation.
| set_default_attn_processor | python | fudan-generative-vision/hallo | hallo/models/unet_2d_condition.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/models/unet_2d_condition.py | MIT |
def set_attention_slice(self, slice_size):
r"""
Enable sliced attention computation.
When this option is enabled, the attention module splits the input tensor in slices to compute attention in
several steps. This is useful for saving some memory in exchange for a small decrease in speed... |
Enable sliced attention computation.
When this option is enabled, the attention module splits the input tensor in slices to compute attention in
several steps. This is useful for saving some memory in exchange for a small decrease in speed.
Args:
slice_size (`str` or `int`... | set_attention_slice | python | fudan-generative-vision/hallo | hallo/models/unet_2d_condition.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/models/unet_2d_condition.py | MIT |
def forward(
self,
sample: torch.FloatTensor,
timestep: Union[torch.Tensor, float, int],
encoder_hidden_states: torch.Tensor,
cond_tensor: torch.FloatTensor=None,
class_labels: Optional[torch.Tensor] = None,
timestep_cond: Optional[torch.Tensor] = None,
at... |
The [`UNet2DConditionModel`] forward method.
Args:
sample (`torch.FloatTensor`):
The noisy input tensor with the following shape `(batch, channel, height, width)`.
timestep (`torch.FloatTensor` or `float` or `int`): The number of timesteps to denoise an input.
... | forward | python | fudan-generative-vision/hallo | hallo/models/unet_2d_condition.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/models/unet_2d_condition.py | MIT |
def load_change_cross_attention_dim(
cls,
pretrained_model_path: PathLike,
subfolder=None,
# unet_additional_kwargs=None,
):
"""
Load or change the cross-attention dimension of a pre-trained model.
Parameters:
pretrained_model_name_or_path (:class... |
Load or change the cross-attention dimension of a pre-trained model.
Parameters:
pretrained_model_name_or_path (:class:`~typing.Union[str, :class:`~pathlib.Path`]`):
The identifier of the pre-trained model or the path to the local folder containing the model.
fo... | load_change_cross_attention_dim | python | fudan-generative-vision/hallo | hallo/models/unet_2d_condition.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/models/unet_2d_condition.py | MIT |
def attn_processors(self) -> Dict[str, AttentionProcessor]:
r"""
Returns:
`dict` of attention processors: A dictionary containing all attention processors used in the model with
indexed by its weight name.
"""
# set recursively
processors = {}
def... |
Returns:
`dict` of attention processors: A dictionary containing all attention processors used in the model with
indexed by its weight name.
| attn_processors | python | fudan-generative-vision/hallo | hallo/models/unet_3d.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/models/unet_3d.py | MIT |
def set_attention_slice(self, slice_size):
r"""
Enable sliced attention computation.
When this option is enabled, the attention module will split the input tensor in slices, to compute attention
in several steps. This is useful to save some memory in exchange for a small speed decrease.... |
Enable sliced attention computation.
When this option is enabled, the attention module will split the input tensor in slices, to compute attention
in several steps. This is useful to save some memory in exchange for a small speed decrease.
Args:
slice_size (`str` or `int` ... | set_attention_slice | python | fudan-generative-vision/hallo | hallo/models/unet_3d.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/models/unet_3d.py | MIT |
def set_attn_processor(
self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]
):
r"""
Sets the attention processor to use to compute attention.
Parameters:
processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
The in... |
Sets the attention processor to use to compute attention.
Parameters:
processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
The instantiated processor class or a dictionary of processor classes that will be set as the processor
for **all**... | set_attn_processor | python | fudan-generative-vision/hallo | hallo/models/unet_3d.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/models/unet_3d.py | MIT |
def forward(
self,
sample: torch.FloatTensor,
timestep: Union[torch.Tensor, float, int],
encoder_hidden_states: torch.Tensor,
audio_embedding: Optional[torch.Tensor] = None,
class_labels: Optional[torch.Tensor] = None,
mask_cond_fea: Optional[torch.Tensor] = None,... |
Args:
sample (`torch.FloatTensor`): (batch, channel, height, width) noisy inputs tensor
timestep (`torch.FloatTensor` or `float` or `int`): (batch) timesteps
encoder_hidden_states (`torch.FloatTensor`): (batch, sequence_length, feature_dim) encoder hidden states
... | forward | python | fudan-generative-vision/hallo | hallo/models/unet_3d.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/models/unet_3d.py | MIT |
def from_pretrained_2d(
cls,
pretrained_model_path: PathLike,
motion_module_path: PathLike,
subfolder=None,
unet_additional_kwargs=None,
mm_zero_proj_out=False,
use_landmark=True,
):
"""
Load a pre-trained 2D UNet model from a given directory.
... |
Load a pre-trained 2D UNet model from a given directory.
Parameters:
pretrained_model_path (`str` or `PathLike`):
Path to the directory containing a pre-trained 2D UNet model.
dtype (`torch.dtype`, *optional*):
The data type of the loaded model. ... | from_pretrained_2d | python | fudan-generative-vision/hallo | hallo/models/unet_3d.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/models/unet_3d.py | MIT |
def get_down_block(
down_block_type,
num_layers,
in_channels,
out_channels,
temb_channels,
add_downsample,
resnet_eps,
resnet_act_fn,
attn_num_head_channels,
resnet_groups=None,
cross_attention_dim=None,
audio_attention_dim=None,
downsample_padding=None,
dual_cros... |
Factory function to instantiate a down-block module for the 3D UNet architecture.
Down blocks are used in the downsampling part of the U-Net to reduce the spatial dimensions
of the feature maps while increasing the depth. This function can create blocks with or without
cross attention based on the... | get_down_block | python | fudan-generative-vision/hallo | hallo/models/unet_3d_blocks.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/models/unet_3d_blocks.py | MIT |
def get_up_block(
up_block_type,
num_layers,
in_channels,
out_channels,
prev_output_channel,
temb_channels,
add_upsample,
resnet_eps,
resnet_act_fn,
attn_num_head_channels,
resnet_groups=None,
cross_attention_dim=None,
audio_attention_dim=None,
dual_cross_attentio... |
Factory function to instantiate an up-block module for the 3D UNet architecture.
Up blocks are used in the upsampling part of the U-Net to increase the spatial dimensions
of the feature maps while decreasing the depth. This function can create blocks with or without
cross attention based on the specif... | get_up_block | python | fudan-generative-vision/hallo | hallo/models/unet_3d_blocks.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/models/unet_3d_blocks.py | MIT |
def forward(
self,
hidden_states,
temb=None,
encoder_hidden_states=None,
attention_mask=None,
full_mask=None,
face_mask=None,
lip_mask=None,
audio_embedding=None,
motion_scale=None,
):
"""
Forward pass for the UNetMidBlo... |
Forward pass for the UNetMidBlock3DCrossAttn class.
Args:
self (UNetMidBlock3DCrossAttn): An instance of the UNetMidBlock3DCrossAttn class.
hidden_states (Tensor): The input hidden states tensor.
temb (Tensor, optional): The input temporal embedding tensor. Defaults... | forward | python | fudan-generative-vision/hallo | hallo/models/unet_3d_blocks.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/models/unet_3d_blocks.py | MIT |
def forward(
self,
hidden_states,
temb=None,
encoder_hidden_states=None,
attention_mask=None,
full_mask=None,
face_mask=None,
lip_mask=None,
audio_embedding=None,
motion_scale=None,
):
"""
Defines the forward pass for th... |
Defines the forward pass for the CrossAttnDownBlock3D class.
Parameters:
- hidden_states : torch.Tensor
The input tensor to the block.
temb : torch.Tensor, optional
The token embeddings from the previous block.
encoder_hidden_states : torch.T... | forward | python | fudan-generative-vision/hallo | hallo/models/unet_3d_blocks.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/models/unet_3d_blocks.py | MIT |
def forward(
self,
hidden_states,
temb=None,
encoder_hidden_states=None,
):
"""
forward method for the DownBlock3D class.
Args:
hidden_states (Tensor): The input tensor to the DownBlock3D layer.
temb (Tensor, optional): The tok... |
forward method for the DownBlock3D class.
Args:
hidden_states (Tensor): The input tensor to the DownBlock3D layer.
temb (Tensor, optional): The token embeddings, if using transformer.
encoder_hidden_states (Tensor, optional): The hidden states from the encod... | forward | python | fudan-generative-vision/hallo | hallo/models/unet_3d_blocks.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/models/unet_3d_blocks.py | MIT |
def forward(
self,
hidden_states,
res_hidden_states_tuple,
temb=None,
encoder_hidden_states=None,
upsample_size=None,
attention_mask=None,
full_mask=None,
face_mask=None,
lip_mask=None,
audio_embedding=None,
motion_scale=Non... |
Forward pass for the CrossAttnUpBlock3D class.
Args:
self (CrossAttnUpBlock3D): An instance of the CrossAttnUpBlock3D class.
hidden_states (Tensor): The input hidden states tensor.
res_hidden_states_tuple (Tuple[Tensor]): A tuple of residual hidden states tensors.
... | forward | python | fudan-generative-vision/hallo | hallo/models/unet_3d_blocks.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/models/unet_3d_blocks.py | MIT |
def forward(
self,
hidden_states,
res_hidden_states_tuple,
temb=None,
upsample_size=None,
encoder_hidden_states=None,
):
"""
Forward pass for the UpBlock3D class.
Args:
self (UpBlock3D): An instance of the UpBlock3D class.
... |
Forward pass for the UpBlock3D class.
Args:
self (UpBlock3D): An instance of the UpBlock3D class.
hidden_states (Tensor): The input hidden states tensor.
res_hidden_states_tuple (Tuple[Tensor]): A tuple of residual hidden states tensors.
temb (Tensor, op... | forward | python | fudan-generative-vision/hallo | hallo/models/unet_3d_blocks.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/models/unet_3d_blocks.py | MIT |
def forward(
self,
input_values,
seq_len,
attention_mask=None,
mask_time_indices=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
):
"""
Forward pass of the Wav2Vec model.
Args:
self: The i... |
Forward pass of the Wav2Vec model.
Args:
self: The instance of the model.
input_values: The input values (waveform) to the model.
seq_len: The sequence length of the input values.
attention_mask: Attention mask to be used for the model.
mask_... | forward | python | fudan-generative-vision/hallo | hallo/models/wav2vec.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/models/wav2vec.py | MIT |
def feature_extract(
self,
input_values,
seq_len,
):
"""
Extracts features from the input values and returns the extracted features.
Parameters:
input_values (torch.Tensor): The input values to be processed.
seq_len (torch.Tensor): The sequence length... |
Extracts features from the input values and returns the extracted features.
Parameters:
input_values (torch.Tensor): The input values to be processed.
seq_len (torch.Tensor): The sequence lengths of the input values.
Returns:
extracted_features (torch.Tensor): The extr... | feature_extract | python | fudan-generative-vision/hallo | hallo/models/wav2vec.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/models/wav2vec.py | MIT |
def encode(
self,
extract_features,
attention_mask=None,
mask_time_indices=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
):
"""
Encodes the input features into the output space.
Args:
extract_fe... |
Encodes the input features into the output space.
Args:
extract_features (torch.Tensor): The extracted features from the audio signal.
attention_mask (torch.Tensor, optional): Attention mask to be used for padding.
mask_time_indices (torch.Tensor, optional): Masked ... | encode | python | fudan-generative-vision/hallo | hallo/models/wav2vec.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/models/wav2vec.py | MIT |
def linear_interpolation(features, seq_len):
"""
Transpose the features to interpolate linearly.
Args:
features (torch.Tensor): The extracted features to be interpolated.
seq_len (torch.Tensor): The sequence lengths of the features.
Returns:
torch.Tensor: The interpolated featu... |
Transpose the features to interpolate linearly.
Args:
features (torch.Tensor): The extracted features to be interpolated.
seq_len (torch.Tensor): The sequence lengths of the features.
Returns:
torch.Tensor: The interpolated features.
| linear_interpolation | python | fudan-generative-vision/hallo | hallo/models/wav2vec.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/models/wav2vec.py | MIT |
def filter_non_none(dict_obj: Dict):
"""
Filters out key-value pairs from the given dictionary where the value is None.
Args:
dict_obj (Dict): The dictionary to be filtered.
Returns:
Dict: The dictionary with key-value pairs removed where the value was None.
This function creates ... |
Filters out key-value pairs from the given dictionary where the value is None.
Args:
dict_obj (Dict): The dictionary to be filtered.
Returns:
Dict: The dictionary with key-value pairs removed where the value was None.
This function creates a new dictionary containing only the key-val... | filter_non_none | python | fudan-generative-vision/hallo | hallo/utils/config.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/utils/config.py | MIT |
def seed_everything(seed):
"""
Seeds all random number generators to ensure reproducibility.
Args:
seed (int): The seed value to set for all random number generators.
"""
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed % (2**32))
random.seed(seed) |
Seeds all random number generators to ensure reproducibility.
Args:
seed (int): The seed value to set for all random number generators.
| seed_everything | python | fudan-generative-vision/hallo | hallo/utils/util.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/utils/util.py | MIT |
def import_filename(filename):
"""
Import a module from a given file location.
Args:
filename (str): The path to the file containing the module to be imported.
Returns:
module: The imported module.
Raises:
ImportError: If the module cannot be imported.
Example:
... |
Import a module from a given file location.
Args:
filename (str): The path to the file containing the module to be imported.
Returns:
module: The imported module.
Raises:
ImportError: If the module cannot be imported.
Example:
>>> imported_module = import_filenam... | import_filename | python | fudan-generative-vision/hallo | hallo/utils/util.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/utils/util.py | MIT |
def delete_additional_ckpt(base_path, num_keep):
"""
Deletes additional checkpoint files in the given directory.
Args:
base_path (str): The path to the directory containing the checkpoint files.
num_keep (int): The number of most recent checkpoint files to keep.
Returns:
None
... |
Deletes additional checkpoint files in the given directory.
Args:
base_path (str): The path to the directory containing the checkpoint files.
num_keep (int): The number of most recent checkpoint files to keep.
Returns:
None
Raises:
FileNotFoundError: If the base_path ... | delete_additional_ckpt | python | fudan-generative-vision/hallo | hallo/utils/util.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/utils/util.py | MIT |
def save_videos_from_pil(pil_images, path, fps=8):
"""
Save a sequence of images as a video using the Pillow library.
Args:
pil_images (List[PIL.Image]): A list of PIL.Image objects representing the frames of the video.
path (str): The output file path for the video.
fps (int, optio... |
Save a sequence of images as a video using the Pillow library.
Args:
pil_images (List[PIL.Image]): A list of PIL.Image objects representing the frames of the video.
path (str): The output file path for the video.
fps (int, optional): The frames per second rate of the video. Defaults to... | save_videos_from_pil | python | fudan-generative-vision/hallo | hallo/utils/util.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/utils/util.py | MIT |
def save_videos_grid(videos: torch.Tensor, path: str, rescale=False, n_rows=6, fps=8):
"""
Save a grid of videos as an animation or video.
Args:
videos (torch.Tensor): A tensor of shape (batch_size, channels, time, height, width)
containing the videos to save.
path (str): The pa... |
Save a grid of videos as an animation or video.
Args:
videos (torch.Tensor): A tensor of shape (batch_size, channels, time, height, width)
containing the videos to save.
path (str): The path to save the video grid. Supported formats are .mp4, .avi, and .gif.
rescale (bool, ... | save_videos_grid | python | fudan-generative-vision/hallo | hallo/utils/util.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/utils/util.py | MIT |
def read_frames(video_path):
"""
Reads video frames from a given video file.
Args:
video_path (str): The path to the video file.
Returns:
container (av.container.InputContainer): The input container object
containing the video stream.
... |
Reads video frames from a given video file.
Args:
video_path (str): The path to the video file.
Returns:
container (av.container.InputContainer): The input container object
containing the video stream.
Raises:
FileNotFoundErr... | read_frames | python | fudan-generative-vision/hallo | hallo/utils/util.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/utils/util.py | MIT |
def get_fps(video_path):
"""
Get the frame rate (FPS) of a video file.
Args:
video_path (str): The path to the video file.
Returns:
int: The frame rate (FPS) of the video file.
"""
container = av.open(video_path)
video_stream = next(s for s in container.streams if s.type ==... |
Get the frame rate (FPS) of a video file.
Args:
video_path (str): The path to the video file.
Returns:
int: The frame rate (FPS) of the video file.
| get_fps | python | fudan-generative-vision/hallo | hallo/utils/util.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/utils/util.py | MIT |
def tensor_to_video(tensor, output_video_file, audio_source, fps=25):
"""
Converts a Tensor with shape [c, f, h, w] into a video and adds an audio track from the specified audio file.
Args:
tensor (Tensor): The Tensor to be converted, shaped [c, f, h, w].
output_video_file (str): The file p... |
Converts a Tensor with shape [c, f, h, w] into a video and adds an audio track from the specified audio file.
Args:
tensor (Tensor): The Tensor to be converted, shaped [c, f, h, w].
output_video_file (str): The file path where the output video will be saved.
audio_source (str): The pat... | tensor_to_video | python | fudan-generative-vision/hallo | hallo/utils/util.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/utils/util.py | MIT |
def compute_face_landmarks(detection_result, h, w):
"""
Compute face landmarks from a detection result.
Args:
detection_result (mediapipe.solutions.face_mesh.FaceMesh): The detection result containing face landmarks.
h (int): The height of the video frame.
w (int): The width of the ... |
Compute face landmarks from a detection result.
Args:
detection_result (mediapipe.solutions.face_mesh.FaceMesh): The detection result containing face landmarks.
h (int): The height of the video frame.
w (int): The width of the video frame.
Returns:
face_landmarks_list (lis... | compute_face_landmarks | python | fudan-generative-vision/hallo | hallo/utils/util.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/utils/util.py | MIT |
def get_landmark(file):
"""
This function takes a file as input and returns the facial landmarks detected in the file.
Args:
file (str): The path to the file containing the video or image to be processed.
Returns:
Tuple[List[float], List[float]]: A tuple containing two lists of floats ... |
This function takes a file as input and returns the facial landmarks detected in the file.
Args:
file (str): The path to the file containing the video or image to be processed.
Returns:
Tuple[List[float], List[float]]: A tuple containing two lists of floats representing the x and y coordi... | get_landmark | python | fudan-generative-vision/hallo | hallo/utils/util.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/utils/util.py | MIT |
def get_landmark_overframes(landmark_model, frames_path):
"""
This function iterate frames and returns the facial landmarks detected in each frame.
Args:
landmark_model: mediapipe landmark model instance
frames_path (str): The path to the video frames.
Returns:
List[List[float]... |
This function iterate frames and returns the facial landmarks detected in each frame.
Args:
landmark_model: mediapipe landmark model instance
frames_path (str): The path to the video frames.
Returns:
List[List[float], float, float]: A List containing two lists of floats representi... | get_landmark_overframes | python | fudan-generative-vision/hallo | hallo/utils/util.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/utils/util.py | MIT |
def get_lip_mask(landmarks, height, width, out_path=None, expand_ratio=2.0):
"""
Extracts the lip region from the given landmarks and saves it as an image.
Parameters:
landmarks (numpy.ndarray): Array of facial landmarks.
height (int): Height of the output lip mask image.
width (int... |
Extracts the lip region from the given landmarks and saves it as an image.
Parameters:
landmarks (numpy.ndarray): Array of facial landmarks.
height (int): Height of the output lip mask image.
width (int): Width of the output lip mask image.
out_path (pathlib.Path): Path to save... | get_lip_mask | python | fudan-generative-vision/hallo | hallo/utils/util.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/utils/util.py | MIT |
def get_union_lip_mask(landmarks, height, width, expand_ratio=1):
"""
Extracts the lip region from the given landmarks and saves it as an image.
Parameters:
landmarks (numpy.ndarray): Array of facial landmarks.
height (int): Height of the output lip mask image.
width (int): Width of... |
Extracts the lip region from the given landmarks and saves it as an image.
Parameters:
landmarks (numpy.ndarray): Array of facial landmarks.
height (int): Height of the output lip mask image.
width (int): Width of the output lip mask image.
expand_ratio (float): Expand ratio of... | get_union_lip_mask | python | fudan-generative-vision/hallo | hallo/utils/util.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/utils/util.py | MIT |
def get_face_mask(landmarks, height, width, out_path=None, expand_ratio=1.2):
"""
Generate a face mask based on the given landmarks.
Args:
landmarks (numpy.ndarray): The landmarks of the face.
height (int): The height of the output face mask image.
width (int): The width of the outp... |
Generate a face mask based on the given landmarks.
Args:
landmarks (numpy.ndarray): The landmarks of the face.
height (int): The height of the output face mask image.
width (int): The width of the output face mask image.
out_path (pathlib.Path): The path to save the face mask i... | get_face_mask | python | fudan-generative-vision/hallo | hallo/utils/util.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/utils/util.py | MIT |
def get_union_face_mask(landmarks, height, width, expand_ratio=1):
"""
Generate a face mask based on the given landmarks.
Args:
landmarks (numpy.ndarray): The landmarks of the face.
height (int): The height of the output face mask image.
width (int): The width of the output face mas... |
Generate a face mask based on the given landmarks.
Args:
landmarks (numpy.ndarray): The landmarks of the face.
height (int): The height of the output face mask image.
width (int): The width of the output face mask image.
expand_ratio (float): Expand ratio of mask.
Returns:
... | get_union_face_mask | python | fudan-generative-vision/hallo | hallo/utils/util.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/utils/util.py | MIT |
def get_mask(file, cache_dir, face_expand_raio):
"""
Generate a face mask based on the given landmarks and save it to the specified cache directory.
Args:
file (str): The path to the file containing the landmarks.
cache_dir (str): The directory to save the generated face mask.
Returns:... |
Generate a face mask based on the given landmarks and save it to the specified cache directory.
Args:
file (str): The path to the file containing the landmarks.
cache_dir (str): The directory to save the generated face mask.
Returns:
None
| get_mask | python | fudan-generative-vision/hallo | hallo/utils/util.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/utils/util.py | MIT |
def expand_region(region, image_w, image_h, expand_ratio=1.0):
"""
Expand the given region by a specified ratio.
Args:
region (tuple): A tuple containing the coordinates (min_x, max_x, min_y, max_y) of the region.
image_w (int): The width of the image.
image_h (int): The height of th... |
Expand the given region by a specified ratio.
Args:
region (tuple): A tuple containing the coordinates (min_x, max_x, min_y, max_y) of the region.
image_w (int): The width of the image.
image_h (int): The height of the image.
expand_ratio (float, optional): The ratio by which th... | expand_region | python | fudan-generative-vision/hallo | hallo/utils/util.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/utils/util.py | MIT |
def get_blur_mask(file_path, output_file_path, resize_dim=(64, 64), kernel_size=(101, 101)):
"""
Read, resize, blur, normalize, and save an image.
Parameters:
file_path (str): Path to the input image file.
output_dir (str): Path to the output directory to save blurred images.
resize_dim (tuple)... |
Read, resize, blur, normalize, and save an image.
Parameters:
file_path (str): Path to the input image file.
output_dir (str): Path to the output directory to save blurred images.
resize_dim (tuple): Dimensions to resize the images to.
kernel_size (tuple): Size of the kernel to use for Gaussia... | get_blur_mask | python | fudan-generative-vision/hallo | hallo/utils/util.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/utils/util.py | MIT |
def blur_mask(mask, resize_dim=(64, 64), kernel_size=(51, 51)):
"""
Read, resize, blur, normalize, and save an image.
Parameters:
file_path (str): Path to the input image file.
resize_dim (tuple): Dimensions to resize the images to.
kernel_size (tuple): Size of the kernel to use for Gaussian bl... |
Read, resize, blur, normalize, and save an image.
Parameters:
file_path (str): Path to the input image file.
resize_dim (tuple): Dimensions to resize the images to.
kernel_size (tuple): Size of the kernel to use for Gaussian blur.
| blur_mask | python | fudan-generative-vision/hallo | hallo/utils/util.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/utils/util.py | MIT |
def get_background_mask(file_path, output_file_path):
"""
Read an image, invert its values, and save the result.
Parameters:
file_path (str): Path to the input image file.
output_dir (str): Path to the output directory to save the inverted image.
"""
# Read the image
image = cv2.imread(... |
Read an image, invert its values, and save the result.
Parameters:
file_path (str): Path to the input image file.
output_dir (str): Path to the output directory to save the inverted image.
| get_background_mask | python | fudan-generative-vision/hallo | hallo/utils/util.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/utils/util.py | MIT |
def get_sep_face_mask(file_path1, file_path2, output_file_path):
"""
Read two images, subtract the second one from the first, and save the result.
Parameters:
output_dir (str): Path to the output directory to save the subtracted image.
"""
# Read the images
mask1 = cv2.imread(file_path1, c... |
Read two images, subtract the second one from the first, and save the result.
Parameters:
output_dir (str): Path to the output directory to save the subtracted image.
| get_sep_face_mask | python | fudan-generative-vision/hallo | hallo/utils/util.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/utils/util.py | MIT |
def load_checkpoint(cfg, save_dir, accelerator):
"""
Load the most recent checkpoint from the specified directory.
This function loads the latest checkpoint from the `save_dir` if the `resume_from_checkpoint` parameter is set to "latest".
If a specific checkpoint is provided in `resume_from_checkpoint`... |
Load the most recent checkpoint from the specified directory.
This function loads the latest checkpoint from the `save_dir` if the `resume_from_checkpoint` parameter is set to "latest".
If a specific checkpoint is provided in `resume_from_checkpoint`, it loads that checkpoint. If no checkpoint is found,
... | load_checkpoint | python | fudan-generative-vision/hallo | hallo/utils/util.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/utils/util.py | MIT |
def compute_snr(noise_scheduler, timesteps):
"""
Computes SNR as per
https://github.com/TiankaiHang/Min-SNR-Diffusion-Training/blob/
521b624bd70c67cee4bdf49225915f5945a872e3/guided_diffusion/gaussian_diffusion.py#L847-L849
"""
alphas_cumprod = noise_scheduler.alphas_cumprod
sqrt_alph... |
Computes SNR as per
https://github.com/TiankaiHang/Min-SNR-Diffusion-Training/blob/
521b624bd70c67cee4bdf49225915f5945a872e3/guided_diffusion/gaussian_diffusion.py#L847-L849
| compute_snr | python | fudan-generative-vision/hallo | hallo/utils/util.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/utils/util.py | MIT |
def extract_audio_from_videos(video_path: Path, audio_output_path: Path) -> Path:
"""
Extract audio from a video file and save it as a WAV file.
This function uses ffmpeg to extract the audio stream from a given video file and saves it as a WAV file
in the specified output directory.
Args:
... |
Extract audio from a video file and save it as a WAV file.
This function uses ffmpeg to extract the audio stream from a given video file and saves it as a WAV file
in the specified output directory.
Args:
video_path (Path): The path to the input video file.
output_dir (Path): The dire... | extract_audio_from_videos | python | fudan-generative-vision/hallo | hallo/utils/util.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/utils/util.py | MIT |
def convert_video_to_images(video_path: Path, output_dir: Path) -> Path:
"""
Convert a video file into a sequence of images.
This function uses ffmpeg to convert each frame of the given video file into an image. The images are saved
in a directory named after the video file stem under the specified out... |
Convert a video file into a sequence of images.
This function uses ffmpeg to convert each frame of the given video file into an image. The images are saved
in a directory named after the video file stem under the specified output directory.
Args:
video_path (Path): The path to the input video... | convert_video_to_images | python | fudan-generative-vision/hallo | hallo/utils/util.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/utils/util.py | MIT |
def get_union_mask(masks):
"""
Compute the union of a list of masks.
This function takes a list of masks and computes their union by taking the maximum value at each pixel location.
Additionally, it finds the bounding box of the non-zero regions in the mask and sets the bounding box area to white.
... |
Compute the union of a list of masks.
This function takes a list of masks and computes their union by taking the maximum value at each pixel location.
Additionally, it finds the bounding box of the non-zero regions in the mask and sets the bounding box area to white.
Args:
masks (list of np.n... | get_union_mask | python | fudan-generative-vision/hallo | hallo/utils/util.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/utils/util.py | MIT |
def move_final_checkpoint(save_dir, module_dir, prefix):
"""
Move the final checkpoint file to the save directory.
This function identifies the latest checkpoint file based on the given prefix and moves it to the specified save directory.
Args:
save_dir (str): The directory where the final che... |
Move the final checkpoint file to the save directory.
This function identifies the latest checkpoint file based on the given prefix and moves it to the specified save directory.
Args:
save_dir (str): The directory where the final checkpoint file should be saved.
module_dir (str): The dire... | move_final_checkpoint | python | fudan-generative-vision/hallo | hallo/utils/util.py | https://github.com/fudan-generative-vision/hallo/blob/master/hallo/utils/util.py | MIT |
def predict(image, audio, pose_weight, face_weight, lip_weight, face_expand_ratio, progress=gr.Progress(track_tqdm=True)):
"""
Create a gradio interface with the configs.
"""
_ = progress
config = {
'source_image': image,
'driving_audio': audio,
'pose_weight': pose_weight,
... |
Create a gradio interface with the configs.
| predict | python | fudan-generative-vision/hallo | scripts/app.py | https://github.com/fudan-generative-vision/hallo/blob/master/scripts/app.py | MIT |
def setup_directories(video_path: Path) -> dict:
"""
Setup directories for storing processed files.
Args:
video_path (Path): Path to the video file.
Returns:
dict: A dictionary containing paths for various directories.
"""
base_dir = video_path.parent.parent
dirs = {
... |
Setup directories for storing processed files.
Args:
video_path (Path): Path to the video file.
Returns:
dict: A dictionary containing paths for various directories.
| setup_directories | python | fudan-generative-vision/hallo | scripts/data_preprocess.py | https://github.com/fudan-generative-vision/hallo/blob/master/scripts/data_preprocess.py | MIT |
def process_single_video(video_path: Path,
output_dir: Path,
image_processor: ImageProcessorForDataProcessing,
audio_processor: AudioProcessor,
step: int) -> None:
"""
Process a single video file.
Args:
... |
Process a single video file.
Args:
video_path (Path): Path to the video file.
output_dir (Path): Directory to save the output.
image_processor (ImageProcessorForDataProcessing): Image processor object.
audio_processor (AudioProcessor): Audio processor object.
gpu_status... | process_single_video | python | fudan-generative-vision/hallo | scripts/data_preprocess.py | https://github.com/fudan-generative-vision/hallo/blob/master/scripts/data_preprocess.py | MIT |
def process_all_videos(input_video_list: List[Path], output_dir: Path, step: int) -> None:
"""
Process all videos in the input list.
Args:
input_video_list (List[Path]): List of video paths to process.
output_dir (Path): Directory to save the output.
gpu_status (bool): Whether to us... |
Process all videos in the input list.
Args:
input_video_list (List[Path]): List of video paths to process.
output_dir (Path): Directory to save the output.
gpu_status (bool): Whether to use GPU for processing.
| process_all_videos | python | fudan-generative-vision/hallo | scripts/data_preprocess.py | https://github.com/fudan-generative-vision/hallo/blob/master/scripts/data_preprocess.py | MIT |
def get_video_paths(source_dir: Path, parallelism: int, rank: int) -> List[Path]:
"""
Get paths of videos to process, partitioned for parallel processing.
Args:
source_dir (Path): Source directory containing videos.
parallelism (int): Level of parallelism.
rank (int): Rank for distr... |
Get paths of videos to process, partitioned for parallel processing.
Args:
source_dir (Path): Source directory containing videos.
parallelism (int): Level of parallelism.
rank (int): Rank for distributed processing.
Returns:
List[Path]: List of video paths to process.
| get_video_paths | python | fudan-generative-vision/hallo | scripts/data_preprocess.py | https://github.com/fudan-generative-vision/hallo/blob/master/scripts/data_preprocess.py | MIT |
def construct_meta_info(frames_dir_path: Path) -> dict:
"""
Construct meta information for a given frames directory.
Args:
frames_dir_path (Path): The path to the frames directory.
Returns:
dict: A dictionary containing the meta information for the frames directory, or None if the requ... |
Construct meta information for a given frames directory.
Args:
frames_dir_path (Path): The path to the frames directory.
Returns:
dict: A dictionary containing the meta information for the frames directory, or None if the required files do not exist.
| construct_meta_info | python | fudan-generative-vision/hallo | scripts/extract_meta_info_stage1.py | https://github.com/fudan-generative-vision/hallo/blob/master/scripts/extract_meta_info_stage1.py | MIT |
def main():
"""
Main function to extract meta info for training.
"""
parser = argparse.ArgumentParser()
parser.add_argument("-r", "--root_path", type=str,
required=True, help="Root path of the video directories")
parser.add_argument("-n", "--dataset_name", type=str,
... |
Main function to extract meta info for training.
| main | python | fudan-generative-vision/hallo | scripts/extract_meta_info_stage1.py | https://github.com/fudan-generative-vision/hallo/blob/master/scripts/extract_meta_info_stage1.py | MIT |
def extract_meta_info(video_path: str) -> dict:
"""
Extract meta information for a given video file.
Args:
video_path (str): The path to the video file.
Returns:
dict: A dictionary containing the meta information for the video.
"""
mask_path = construct_paths(
video_pat... |
Extract meta information for a given video file.
Args:
video_path (str): The path to the video file.
Returns:
dict: A dictionary containing the meta information for the video.
| extract_meta_info | python | fudan-generative-vision/hallo | scripts/extract_meta_info_stage2.py | https://github.com/fudan-generative-vision/hallo/blob/master/scripts/extract_meta_info_stage2.py | MIT |
def main():
"""
Main function to extract meta info for training.
"""
parser = argparse.ArgumentParser()
parser.add_argument("-r", "--root_path", type=str,
required=True, help="Root path of the video files")
parser.add_argument("-n", "--dataset_name", type=str,
... |
Main function to extract meta info for training.
| main | python | fudan-generative-vision/hallo | scripts/extract_meta_info_stage2.py | https://github.com/fudan-generative-vision/hallo/blob/master/scripts/extract_meta_info_stage2.py | MIT |
def forward(self,):
"""
empty function to override abstract function of nn Module
""" |
empty function to override abstract function of nn Module
| forward | python | fudan-generative-vision/hallo | scripts/inference.py | https://github.com/fudan-generative-vision/hallo/blob/master/scripts/inference.py | MIT |
def get_modules(self):
"""
Simple method to avoid too-few-public-methods pylint error
"""
return {
"reference_unet": self.reference_unet,
"denoising_unet": self.denoising_unet,
"face_locator": self.face_locator,
"imageproj": self.imageproj,... |
Simple method to avoid too-few-public-methods pylint error
| get_modules | python | fudan-generative-vision/hallo | scripts/inference.py | https://github.com/fudan-generative-vision/hallo/blob/master/scripts/inference.py | MIT |
def process_audio_emb(audio_emb):
"""
Process the audio embedding to concatenate with other tensors.
Parameters:
audio_emb (torch.Tensor): The audio embedding tensor to process.
Returns:
concatenated_tensors (List[torch.Tensor]): The concatenated tensor list.
"""
concatenated_t... |
Process the audio embedding to concatenate with other tensors.
Parameters:
audio_emb (torch.Tensor): The audio embedding tensor to process.
Returns:
concatenated_tensors (List[torch.Tensor]): The concatenated tensor list.
| process_audio_emb | python | fudan-generative-vision/hallo | scripts/inference.py | https://github.com/fudan-generative-vision/hallo/blob/master/scripts/inference.py | MIT |
def inference_process(args: argparse.Namespace):
"""
Perform inference processing.
Args:
args (argparse.Namespace): Command-line arguments.
This function initializes the configuration for the inference process. It sets up the necessary
modules and variables to prepare for the upcoming infe... |
Perform inference processing.
Args:
args (argparse.Namespace): Command-line arguments.
This function initializes the configuration for the inference process. It sets up the necessary
modules and variables to prepare for the upcoming inference steps.
| inference_process | python | fudan-generative-vision/hallo | scripts/inference.py | https://github.com/fudan-generative-vision/hallo/blob/master/scripts/inference.py | MIT |
def forward(
self,
noisy_latents,
timesteps,
ref_image_latents,
face_emb,
face_mask,
uncond_fwd: bool = False,
):
"""
Forward pass of the model.
Args:
self (Net): The model instance.
noisy_latents (torch.Tensor):... |
Forward pass of the model.
Args:
self (Net): The model instance.
noisy_latents (torch.Tensor): Noisy latents.
timesteps (torch.Tensor): Timesteps.
ref_image_latents (torch.Tensor): Reference image latents.
face_emb (torch.Tensor): Face embeddi... | forward | python | fudan-generative-vision/hallo | scripts/train_stage1.py | https://github.com/fudan-generative-vision/hallo/blob/master/scripts/train_stage1.py | MIT |
def get_noise_scheduler(cfg: argparse.Namespace):
"""
Create noise scheduler for training
Args:
cfg (omegaconf.dictconfig.DictConfig): Configuration object.
Returns:
train noise scheduler and val noise scheduler
"""
sched_kwargs = OmegaConf.to_container(cfg.noise_scheduler_kwar... |
Create noise scheduler for training
Args:
cfg (omegaconf.dictconfig.DictConfig): Configuration object.
Returns:
train noise scheduler and val noise scheduler
| get_noise_scheduler | python | fudan-generative-vision/hallo | scripts/train_stage1.py | https://github.com/fudan-generative-vision/hallo/blob/master/scripts/train_stage1.py | MIT |
def log_validation(
vae,
net,
scheduler,
accelerator,
width,
height,
imageproj,
cfg,
save_dir,
global_step,
face_analysis_model_path,
):
"""
Log validation generation image.
Args:
vae (nn.Module): Variational Autoencoder model.
net (Net): Main mod... |
Log validation generation image.
Args:
vae (nn.Module): Variational Autoencoder model.
net (Net): Main model.
scheduler (diffusers.SchedulerMixin): Noise scheduler.
accelerator (accelerate.Accelerator): Accelerator for training.
width (int): Width of the input images.
... | log_validation | python | fudan-generative-vision/hallo | scripts/train_stage1.py | https://github.com/fudan-generative-vision/hallo/blob/master/scripts/train_stage1.py | MIT |
def train_stage1_process(cfg: argparse.Namespace) -> None:
"""
Trains the model using the given configuration (cfg).
Args:
cfg (dict): The configuration dictionary containing the parameters for training.
Notes:
- This function trains the model using the given configuration.
- I... |
Trains the model using the given configuration (cfg).
Args:
cfg (dict): The configuration dictionary containing the parameters for training.
Notes:
- This function trains the model using the given configuration.
- It initializes the necessary components for training, such as the p... | train_stage1_process | python | fudan-generative-vision/hallo | scripts/train_stage1.py | https://github.com/fudan-generative-vision/hallo/blob/master/scripts/train_stage1.py | MIT |
def load_config(config_path: str) -> dict:
"""
Loads the configuration file.
Args:
config_path (str): Path to the configuration file.
Returns:
dict: The configuration dictionary.
"""
if config_path.endswith(".yaml"):
return OmegaConf.load(config_path)
if config_pat... |
Loads the configuration file.
Args:
config_path (str): Path to the configuration file.
Returns:
dict: The configuration dictionary.
| load_config | python | fudan-generative-vision/hallo | scripts/train_stage1.py | https://github.com/fudan-generative-vision/hallo/blob/master/scripts/train_stage1.py | MIT |
def forward(
self,
noisy_latents: torch.Tensor,
timesteps: torch.Tensor,
ref_image_latents: torch.Tensor,
face_emb: torch.Tensor,
audio_emb: torch.Tensor,
mask: torch.Tensor,
full_mask: torch.Tensor,
face_mask: torch.Tensor,
lip_mask: torch... |
simple docstring to prevent pylint error
| forward | python | fudan-generative-vision/hallo | scripts/train_stage2.py | https://github.com/fudan-generative-vision/hallo/blob/master/scripts/train_stage2.py | MIT |
def get_attention_mask(mask: torch.Tensor, weight_dtype: torch.dtype) -> torch.Tensor:
"""
Rearrange the mask tensors to the required format.
Args:
mask (torch.Tensor): The input mask tensor.
weight_dtype (torch.dtype): The data type for the mask tensor.
Returns:
torch.Tensor: ... |
Rearrange the mask tensors to the required format.
Args:
mask (torch.Tensor): The input mask tensor.
weight_dtype (torch.dtype): The data type for the mask tensor.
Returns:
torch.Tensor: The rearranged mask tensor.
| get_attention_mask | python | fudan-generative-vision/hallo | scripts/train_stage2.py | https://github.com/fudan-generative-vision/hallo/blob/master/scripts/train_stage2.py | MIT |
def get_noise_scheduler(cfg: argparse.Namespace) -> Tuple[DDIMScheduler, DDIMScheduler]:
"""
Create noise scheduler for training.
Args:
cfg (argparse.Namespace): Configuration object.
Returns:
Tuple[DDIMScheduler, DDIMScheduler]: Train noise scheduler and validation noise scheduler.
... |
Create noise scheduler for training.
Args:
cfg (argparse.Namespace): Configuration object.
Returns:
Tuple[DDIMScheduler, DDIMScheduler]: Train noise scheduler and validation noise scheduler.
| get_noise_scheduler | python | fudan-generative-vision/hallo | scripts/train_stage2.py | https://github.com/fudan-generative-vision/hallo/blob/master/scripts/train_stage2.py | MIT |
def process_audio_emb(audio_emb: torch.Tensor) -> torch.Tensor:
"""
Process the audio embedding to concatenate with other tensors.
Parameters:
audio_emb (torch.Tensor): The audio embedding tensor to process.
Returns:
concatenated_tensors (List[torch.Tensor]): The concatenated tensor li... |
Process the audio embedding to concatenate with other tensors.
Parameters:
audio_emb (torch.Tensor): The audio embedding tensor to process.
Returns:
concatenated_tensors (List[torch.Tensor]): The concatenated tensor list.
| process_audio_emb | python | fudan-generative-vision/hallo | scripts/train_stage2.py | https://github.com/fudan-generative-vision/hallo/blob/master/scripts/train_stage2.py | MIT |
def log_validation(
accelerator: Accelerator,
vae: AutoencoderKL,
net: Net,
scheduler: DDIMScheduler,
width: int,
height: int,
clip_length: int = 24,
generator: torch.Generator = None,
cfg: dict = None,
save_dir: str = None,
global_step: int = 0,
times: int = None,
fa... |
Log validation video during the training process.
Args:
accelerator (Accelerator): The accelerator for distributed training.
vae (AutoencoderKL): The autoencoder model.
net (Net): The main neural network model.
scheduler (DDIMScheduler): The scheduler for noise.
width (... | log_validation | python | fudan-generative-vision/hallo | scripts/train_stage2.py | https://github.com/fudan-generative-vision/hallo/blob/master/scripts/train_stage2.py | MIT |
def train_stage2_process(cfg: argparse.Namespace) -> None:
"""
Trains the model using the given configuration (cfg).
Args:
cfg (dict): The configuration dictionary containing the parameters for training.
Notes:
- This function trains the model using the given configuration.
- I... |
Trains the model using the given configuration (cfg).
Args:
cfg (dict): The configuration dictionary containing the parameters for training.
Notes:
- This function trains the model using the given configuration.
- It initializes the necessary components for training, such as the p... | train_stage2_process | python | fudan-generative-vision/hallo | scripts/train_stage2.py | https://github.com/fudan-generative-vision/hallo/blob/master/scripts/train_stage2.py | MIT |
def load_config(config_path: str) -> dict:
"""
Loads the configuration file.
Args:
config_path (str): Path to the configuration file.
Returns:
dict: The configuration dictionary.
"""
if config_path.endswith(".yaml"):
return OmegaConf.load(config_path)
if config_pat... |
Loads the configuration file.
Args:
config_path (str): Path to the configuration file.
Returns:
dict: The configuration dictionary.
| load_config | python | fudan-generative-vision/hallo | scripts/train_stage2.py | https://github.com/fudan-generative-vision/hallo/blob/master/scripts/train_stage2.py | MIT |
def make_tfrecord_loaders(args):
"""Load train/val/test dataset from shuffled TFRecords"""
import data_utils.tf_dl
data_set_args = {'batch_size': args.batch_size,
'max_seq_len': args.seq_length,
'max_preds_per_seq': args.max_preds_per_seq,
'tra... | Load train/val/test dataset from shuffled TFRecords | make_tfrecord_loaders | python | THUDM/GLM | configure_data.py | https://github.com/THUDM/GLM/blob/master/configure_data.py | MIT |
def get_split(args):
"""
Get dataset splits from comma separated string list
"""
splits = []
if args.split.find(',') != -1:
splits = [float(s) for s in args.split.split(',')]
elif args.split.find('/') != -1:
splits = [float(s) for s in args.split.split('/')]
else:
spl... |
Get dataset splits from comma separated string list
| get_split | python | THUDM/GLM | configure_data.py | https://github.com/THUDM/GLM/blob/master/configure_data.py | MIT |
def configure_data():
"""add cmdline flags for configuring datasets"""
# These are options that are used by data_utils, but are either
# deprecated or not meant to be exposed to the command line user.
# These options are intneded to be set in code by specific scripts.
defaults = {
'world_siz... | add cmdline flags for configuring datasets | configure_data | python | THUDM/GLM | configure_data.py | https://github.com/THUDM/GLM/blob/master/configure_data.py | MIT |
def process_batch(batch, args):
"""Process batch and produce inputs for the model."""
keys = ["text", "label"]
if args.pretrained_bert:
keys += ["padding_mask", "types"]
else:
keys += ["mask", "position"]
if args.cloze_eval:
if args.fast_decode:
keys +... | Process batch and produce inputs for the model. | process_batch | python | THUDM/GLM | finetune_glm.py | https://github.com/THUDM/GLM/blob/master/finetune_glm.py | MIT |
def finetune_forward_step(batch, model, args, timers, mems):
"""Simple forward step with cross-entropy loss."""
# Get the batch.
timers('batch generator').start()
try:
batch_ = next(batch)
except BaseException:
batch_ = batch
data = process_batch(batch_, args)
timers('batch ... | Simple forward step with cross-entropy loss. | finetune_forward_step | python | THUDM/GLM | finetune_glm.py | https://github.com/THUDM/GLM/blob/master/finetune_glm.py | MIT |
def _build_infinite_size_dataloader(dataloader):
"""Build a looped dataloader with infinite size."""
iterator = dataloader.__iter__()
while True:
try:
yield iterator.__next__()
except StopIteration:
iterator = dataloader.__iter__() | Build a looped dataloader with infinite size. | _build_infinite_size_dataloader | python | THUDM/GLM | finetune_glm.py | https://github.com/THUDM/GLM/blob/master/finetune_glm.py | MIT |
def finetune(args, train_valid_datasets_provider, model_kwargs, forward_step=finetune_forward_step,
end_of_epoch_callback_provider=None):
"""Main finetune function used across all tasks."""
global tokenizer
timers = Timers()
tokenizer = prepare_tokenizer(args)
pretrain_glm.tokenizer = t... | Main finetune function used across all tasks. | finetune | python | THUDM/GLM | finetune_glm.py | https://github.com/THUDM/GLM/blob/master/finetune_glm.py | MIT |
def add(self, hyp: torch.LongTensor, sum_logprobs: float, mems=None):
"""
Add a new hypothesis to the list.
"""
score = sum_logprobs / (max(hyp.shape[-1], 1) ** self.length_penalty)
if len(self) < self.num_beams or score > self.worst_score:
self.beams.append((score, h... |
Add a new hypothesis to the list.
| add | python | THUDM/GLM | generation_utils.py | https://github.com/THUDM/GLM/blob/master/generation_utils.py | MIT |
def is_done(self, best_sum_logprobs: float, cur_len: int) -> bool:
"""
If there are enough hypotheses and that none of the hypotheses being generated can become better than the worst
one in the heap, then we are done with this sentence.
"""
if len(self) < self.num_beams:
... |
If there are enough hypotheses and that none of the hypotheses being generated can become better than the worst
one in the heap, then we are done with this sentence.
| is_done | python | THUDM/GLM | generation_utils.py | https://github.com/THUDM/GLM/blob/master/generation_utils.py | MIT |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves Python code examples from Django repository that contain 'django' in the code, which helps identify Django-specific code snippets but provides limited analytical insights beyond basic filtering.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.