index int64 0 50.7k | project_path stringclasses 279
values | completion_path stringlengths 57 199 | signature_postion stringlengths 3 11 | class_position stringlengths 3 11 | function_name stringlengths 1 62 | class_name stringlengths 0 55 | body_position stringlengths 3 11 | body_position_with_comments stringlengths 3 11 | masked_class stringlengths 14 8.32k | masked_class_with_comment stringlengths 14 8.32k | func_body stringlengths 9 6.72k | func_body_with_comment stringlengths 9 6.72k | len_func_body int64 1 643 | len_input int64 10 2.02k | len_output int64 4 1.9k | total int64 20 2.05k | file_code stringlengths 14 442k | file_code_with_comment stringlengths 14 442k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
45,321 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/mdetr/transformer.py | 162,169 | 135,186 | forward | TransformerEncoder | 169,186 | 169,186 | class TransformerEncoder(nn.Module):
"""
A transformer encoder.
Args: encoder_layer (nn.Module): Module for an individual encoder layer.
num_layers (int): Number of encoder layers.
norm (Optional[nn.Module]): Normalization applied after last encoder layer.
Default:... | class TransformerEncoder(nn.Module):
"""
A transformer encoder.
Args: encoder_layer (nn.Module): Module for an individual encoder layer.
num_layers (int): Number of encoder layers.
norm (Optional[nn.Module]): Normalization applied after last encoder layer.
Default:... |
output = src
for layer in self.layers:
output = layer(
output,
src_mask=mask,
src_key_padding_mask=src_key_padding_mask,
pos=pos,
)
if self.norm is not None:
output = self.norm(output)
... |
output = src
for layer in self.layers:
output = layer(
output,
src_mask=mask,
src_key_padding_mask=src_key_padding_mask,
pos=pos,
)
if self.norm is not None:
output = self.norm(output)
... | 25 | 337 | 106 | 443 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Callable, NamedTuple, Optional
import torch
from torch import nn, Tensor
from torchmultimod... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Callable, NamedTuple, Optional
import torch
from torch import nn, Tensor
from torchmultimod... |
45,322 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/mdetr/transformer.py | 326,333 | 264,357 | forward_pre | TransformerEncoderLayer | 333,345 | 333,345 | class TransformerEncoderLayer(nn.Module):
"""
A single layer from a transformer encoder.
Args: d_model (int): Number of features in the input.
num_heads (int): Number of heads in multi-head attention.
dim_feedforward (int): Dimension of feedforward network. Default: 2048
... | class TransformerEncoderLayer(nn.Module):
"""
A single layer from a transformer encoder.
Args: d_model (int): Number of features in the input.
num_heads (int): Number of heads in multi-head attention.
dim_feedforward (int): Dimension of feedforward network. Default: 2048
... | x = src
x = self.norm1(x)
q = k = self.with_pos_embed(x, pos)
self_attention_outputs = self.self_attn(
q, k, value=x, attn_mask=src_mask, key_padding_mask=src_key_padding_mask
)[0]
x = x + self.dropout1(self_attention_outputs)
x = self.norm2(x)
... | x = src
x = self.norm1(x)
q = k = self.with_pos_embed(x, pos)
self_attention_outputs = self.self_attn(
q, k, value=x, attn_mask=src_mask, key_padding_mask=src_key_padding_mask
)[0]
x = x + self.dropout1(self_attention_outputs)
x = self.norm2(x)
... | 39 | 983 | 168 | 1,151 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Callable, NamedTuple, Optional
import torch
from torch import nn, Tensor
from torchmultimod... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Callable, NamedTuple, Optional
import torch
from torch import nn, Tensor
from torchmultimod... |
45,324 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/omnivore.py | 77,78 | 54,86 | forward | Omnivore | 78,86 | 78,86 | class Omnivore(nn.Module):
"""Omnivore is a model that accept multiple vision modality.
Omnivore (https://arxiv.org/abs/2201.08377) is a single model that able to do classification
on images, videos, and single-view 3D data using the same shared parameters of the encoder.
Args:
encoder (nn.Mod... | class Omnivore(nn.Module):
"""Omnivore is a model that accept multiple vision modality.
Omnivore (https://arxiv.org/abs/2201.08377) is a single model that able to do classification
on images, videos, and single-view 3D data using the same shared parameters of the encoder.
Args:
encoder (nn.Mod... | x = self.encoder(x)
assert (
input_type in self.heads
), f"Unsupported input_type: {input_type}, please use one of {list(self.heads.keys())}"
x = self.heads[input_type](x)
return x
| x = self.encoder(x)
assert (
input_type in self.heads
), f"Unsupported input_type: {input_type}, please use one of {list(self.heads.keys())}"
x = self.heads[input_type](x)
return x
| 22 | 324 | 86 | 410 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Callable, List, Optional
import torch
import torchmultimodal.utils.common as common_utils
... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Callable, List, Optional
import torch
import torchmultimodal.utils.common as common_utils
... |
45,325 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/omnivore.py | 119,120 | 86,134 | forward | PatchEmbedOmnivore | 120,134 | 120,134 | class PatchEmbedOmnivore(nn.Module):
"""Patch Embedding strategy for Omnivore model
It will use common PatchEmbed3d for image and video,
for single view depth image it will have separate embedding for the depth channel
and add the embedding result with the RGB channel
reference: https://arxiv.org/ab... | class PatchEmbedOmnivore(nn.Module):
"""Patch Embedding strategy for Omnivore model
It will use common PatchEmbed3d for image and video,
for single view depth image it will have separate embedding for the depth channel
and add the embedding result with the RGB channel
reference: https://arxiv.org/ab... | # x: B C D H W
# Note: D here represent time
assert x.ndim == 5
has_depth = x.shape[1] == 4
if has_depth:
x_rgb = self.patch_embed(x[:, :3, ...])
x_d = self.depth_patch_embed(x[:, 3:, ...])
x = x_rgb + x_d
else:
x = self.pa... | # x: B C D H W
# Note: D here represent time
assert x.ndim == 5
has_depth = x.shape[1] == 4
if has_depth:
x_rgb = self.patch_embed(x[:, :3, ...])
x_d = self.depth_patch_embed(x[:, 3:, ...])
x = x_rgb + x_d
else:
x = self.pa... | 45 | 393 | 142 | 535 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Callable, List, Optional
import torch
import torchmultimodal.utils.common as common_utils
... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Callable, List, Optional
import torch
import torchmultimodal.utils.common as common_utils
... |
45,326 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/two_tower.py | 73,79 | 19,92 | _get_tower_input | TwoTower | 79,92 | 79,92 | class TwoTower(nn.Module):
"""
A two tower architecture with a pair of late fusion models
(for now, can be extended) followed by a fusion for output of each tower.
Args:
tower_id_to_tower (Dict[str, LateFusion]): mapping of tower id
to tower model. Size should be 2, same tower should be ... | class TwoTower(nn.Module):
"""
A two tower architecture with a pair of late fusion models
(for now, can be extended) followed by a fusion for output of each tower.
Args:
tower_id_to_tower (Dict[str, LateFusion]): mapping of tower id
to tower model. Size should be 2, same tower should be ... | tower_input = {}
channel_name_mapping: Dict[str, str] = {}
if self.shared_tower_id_to_channel_mapping is not None:
if self.shared_tower_id_to_channel_mapping.get(tower_id) is not None:
channel_name_mapping = self.shared_tower_id_to_channel_mapping[tower_id]
f... | tower_input = {}
channel_name_mapping: Dict[str, str] = {}
if self.shared_tower_id_to_channel_mapping is not None:
if self.shared_tower_id_to_channel_mapping.get(tower_id) is not None:
channel_name_mapping = self.shared_tower_id_to_channel_mapping[tower_id]
f... | 42 | 809 | 199 | 1,008 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from collections import OrderedDict
from typing import Dict, List, NamedTuple, Optional
from torch import nn, ... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from collections import OrderedDict
from typing import Dict, List, NamedTuple, Optional
from torch import nn, ... |
45,328 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/video_gpt/gpt.py | 424,438 | 385,519 | forward | MultimodalTransformerDecoder | 467,504 | 438,504 | class MultimodalTransformerDecoder(nn.Module):
"""A transformer decoder for two modalities
The token- and position- embedding layers are per modality:
* During training both modalities are fed into the module and concatenated as a single sequence of
tokenized embedding vectors
* Dur... | class MultimodalTransformerDecoder(nn.Module):
"""A transformer decoder for two modalities
The token- and position- embedding layers are per modality:
* During training both modalities are fed into the module and concatenated as a single sequence of
tokenized embedding vectors
* Dur... | if (in_modality is None) and (out_modality is None):
raise ValueError(
"in_modality and out_modality sequences cannot be both empty"
)
# Since generation is based on the previous data point (autoregressive) where
# only one modality is needed at any point... | """
Args:
in_modality (Tensor, optional): Tensor of dimension ``(b, in_seq_len, d_model)`` containing tokenized
embeddings for the input modality. Defaults to ``None``.
out_modality (Tensor, optional): Tensor of dimension ``(b, out_seq_len, d_model')`` containing ... | 153 | 1,451 | 512 | 1,963 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from functools import partial
from typing import Any, Callable, Dict, NamedTuple, Optional, Tuple, Union
impor... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from functools import partial
from typing import Any, Callable, Dict, NamedTuple, Optional, Tuple, Union
impor... |
45,329 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/video_gpt/gpt.py | 760,761 | 740,777 | forward | RightShift | 768,777 | 761,777 | class RightShift(nn.Module):
"""Shifts the embedding vectors along the sequence dimension to the right.
Since the decoder progresses by taking the token it generates in the previous step, before it
has generated anything it needs a token to start with. Hence, the start-of-sentence (SOS) token.
The SOS ... | class RightShift(nn.Module):
"""Shifts the embedding vectors along the sequence dimension to the right.
Since the decoder progresses by taking the token it generates in the previous step, before it
has generated anything it needs a token to start with. Hence, the start-of-sentence (SOS) token.
The SOS ... | x_shape = list(x.shape)
x = x.flatten(start_dim=1, end_dim=-2) # (batch, seq_len, emb)
sos = self.sos.unsqueeze(0).unsqueeze(1).repeat(x_shape[0], 1, 1) # (b, 1, emb)
# Shift one unit to the right along dim ``seq_len``
x = torch.cat(
(sos.data, x[:, :-1, :]), dim=1
... | """
Args:
x (Tensor): An input tensor of shape ``(b, seq_len, emb_dim)``.
Returns;
A tensor of the same shape as that of the input with the ``sos`` token prepended.
"""
x_shape = list(x.shape)
x = x.flatten(start_dim=1, end_dim=-2) # (batch, seq_... | 48 | 360 | 181 | 541 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from functools import partial
from typing import Any, Callable, Dict, NamedTuple, Optional, Tuple, Union
impor... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from functools import partial
from typing import Any, Callable, Dict, NamedTuple, Optional, Tuple, Union
impor... |
45,330 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/video_gpt/gpt.py | 537,547 | 519,609 | forward | TransformerDecoder | 567,609 | 547,609 | class TransformerDecoder(nn.Module):
"""A transformer decoder.
Args:
decoder_layer (nn.Module): The transformer decoder layer.
An instance of :class:`TransformerDecoderLayer`.
num_layers (int): The number of transformer decoder layers to be stacked up.
"""
def __init__(
... | class TransformerDecoder(nn.Module):
"""A transformer decoder.
Args:
decoder_layer (nn.Module): The transformer decoder layer.
An instance of :class:`TransformerDecoderLayer`.
num_layers (int): The number of transformer decoder layers to be stacked up.
"""
def __init__(
... | if attn_mask is not None and attn_mask.dim() == 2:
attn_mask = attn_mask[
None, None, :, :
] # (q_seq_len, k_seq_len) -> (1, 1, q_seq_len, k_seq_len)
if head_mask is not None and head_mask.dim() == 3:
head_mask = head_mask[None, :, :, :]
all... | """
Args:
hidden_states (Tensor): Tensor of the embedding vectors of dimension ``(b, seq_len, emb_dim)``.
attn_mask (Tensor, optional): Tensor of dimension ``(q_seq_len, k_seq_len)`` or
``(b, q_seq_len, k_seq_len)`` where prefixes ``q`` and ``k`` stand for query a... | 122 | 679 | 525 | 1,204 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from functools import partial
from typing import Any, Callable, Dict, NamedTuple, Optional, Tuple, Union
impor... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from functools import partial
from typing import Any, Callable, Dict, NamedTuple, Optional, Tuple, Union
impor... |
45,331 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/video_gpt/gpt.py | 659,668 | 609,740 | forward | TransformerDecoderLayer | 685,716 | 668,716 | class TransformerDecoderLayer(nn.Module):
"""A single layer from a GPT transformer decoder
Layer norm is applied before the attention layer and the feedforward layer so that the gradients are
well-behaved at initialization for training stability. This is also called "Pre-LN Transformer" studied in
`"On... | class TransformerDecoderLayer(nn.Module):
"""A single layer from a GPT transformer decoder
Layer norm is applied before the attention layer and the feedforward layer so that the gradients are
well-behaved at initialization for training stability. This is also called "Pre-LN Transformer" studied in
`"On... | attn_probs = None
past_key_values = None
attn_out = self._attn(
self.norm_attn(x),
attn_mask,
head_mask,
return_attn_weights,
use_cache=use_cache,
causal=causal,
)
if return_attn_weights:
attn_h... | """
Args:
x (Tensor): input embedding vectors.
attn_mask (Tensor, optional): Tensor of dimension ``(b, q_seq_len, k_seq_len)`` where prefixes ``q``
and ``k`` stand for query and key. Contains 1s for positions to attend to and 0s for masked positions.
... | 50 | 1,224 | 304 | 1,528 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from functools import partial
from typing import Any, Callable, Dict, NamedTuple, Optional, Tuple, Union
impor... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from functools import partial
from typing import Any, Callable, Dict, NamedTuple, Optional, Tuple, Union
impor... |
45,334 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/video_gpt/video_vqvae.py | 444,445 | 408,452 | forward | AttentionResidualBlock | 449,452 | 445,452 | class AttentionResidualBlock(nn.Module):
"""Residual block with axial attention.
Implements the component as proposed in `"VideoGPT: Video Generation using VQ-VAE and
Transformers (Yan et al. 2022)"<https://arxiv.org/pdf/2104.10157.pdf>`_.
Code reference:
https://github.com/wilson1yan/VideoGPT... | class AttentionResidualBlock(nn.Module):
"""Residual block with axial attention.
Implements the component as proposed in `"VideoGPT: Video Generation using VQ-VAE and
Transformers (Yan et al. 2022)"<https://arxiv.org/pdf/2104.10157.pdf>`_.
Code reference:
https://github.com/wilson1yan/VideoGPT... | return x + self.block(x)
| """
Args:
x (Tensor): Input of shape ``(b, c, d1, d2, d3)``.
"""
return x + self.block(x)
| 4 | 535 | 16 | 551 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any, cast, List, Optional, Tuple, Union
import torch
from torch import nn, Size, Tensor
f... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any, cast, List, Optional, Tuple, Union
import torch
from torch import nn, Size, Tensor
f... |
45,335 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/video_gpt/video_vqvae.py | 37,45 | 23,87 | forward | AxialAttention | 62,87 | 45,87 | class AxialAttention(nn.Module):
"""Computes attention over a single axis of the input. Other dims are flattened into the batch dimension.
Args:
axial_dim (int): Dimension to compute attention on, indexed by input dimensions
(i.e., ``0`` for first input dimension, ``1`` for second).
... | class AxialAttention(nn.Module):
"""Computes attention over a single axis of the input. Other dims are flattened into the batch dimension.
Args:
axial_dim (int): Dimension to compute attention on, indexed by input dimensions
(i.e., ``0`` for first input dimension, ``1`` for second).
... | # Ensure axial dim is within right dimensions, should be between head dim and embedding dim
if self.axial_dim >= len(q.shape) - 1:
raise ValueError("axial dim does not match input shape")
# flatten all dims into batch dimension except chosen axial dim and channel dim
# b, h,... | """
Args:
q (Tensor): Query input of shape ``(b, h, d1, ..., dn, dim_q)`` where ``h`` is the number of
attention heads, ``(d1, ..., dn)`` are the query latent dimensions and ``dim_q`` is the dimension
of the query embeddings.
k, v (Tensor): Key/val... | 106 | 610 | 385 | 995 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any, cast, List, Optional, Tuple, Union
import torch
from torch import nn, Size, Tensor
f... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any, cast, List, Optional, Tuple, Union
import torch
from torch import nn, Size, Tensor
f... |
45,336 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/video_gpt/video_vqvae.py | 127,128 | 87,143 | forward | AxialAttentionBlock | 128,143 | 128,143 | class AxialAttentionBlock(nn.Module):
"""Computes multihead axial attention across all dims of the input.
Axial attention is an alternative to standard full attention, where instead
of computing attention across the entire flattened input, you compute it for
each dimension. To capture the global contex... | class AxialAttentionBlock(nn.Module):
"""Computes multihead axial attention across all dims of the input.
Axial attention is an alternative to standard full attention, where instead
of computing attention across the entire flattened input, you compute it for
each dimension. To capture the global contex... | n_channel = x.shape[1]
if n_channel != self.qkv_dim:
raise ValueError(
f"Input channel dimension is {n_channel}, expected {self.qkv_dim}"
)
h = shift_dim(x, 1, -1) # (b, c, d1, ..., dn) -> (b, d1, ..., dn, c)
attn_out = torch.zeros_like(h)
... | n_channel = x.shape[1]
if n_channel != self.qkv_dim:
raise ValueError(
f"Input channel dimension is {n_channel}, expected {self.qkv_dim}"
)
h = shift_dim(x, 1, -1) # (b, c, d1, ..., dn) -> (b, d1, ..., dn, c)
attn_out = torch.zeros_like(h)
... | 67 | 577 | 236 | 813 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any, cast, List, Optional, Tuple, Union
import torch
from torch import nn, Size, Tensor
f... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any, cast, List, Optional, Tuple, Union
import torch
from torch import nn, Size, Tensor
f... |
45,337 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/video_gpt/video_vqvae.py | 392,393 | 320,408 | forward | VideoDecoder | 397,408 | 393,408 | class VideoDecoder(nn.Module):
"""Decoder for Video VQVAE.
Takes quantized output from codebook and applies a ``SamePadConv3d`` layer, a stack of
``AttentionResidualBlocks``, followed by a specified number of ``SamePadConvTranspose3d``
layers. The residual blocks use Axial Attention to enhance represen... | class VideoDecoder(nn.Module):
"""Decoder for Video VQVAE.
Takes quantized output from codebook and applies a ``SamePadConv3d`` layer, a stack of
``AttentionResidualBlocks``, followed by a specified number of ``SamePadConvTranspose3d``
layers. The residual blocks use Axial Attention to enhance represen... | in_channel = x.shape[1]
if in_channel != self.conv_in.conv.in_channels:
raise ValueError(
f"expected input channel dim to be {self.conv_in.conv.in_channels}, but got {in_channel}"
)
h = self.conv_in(x)
h = self.res_stack(h)
h = self.convts(... | """
Args:
x (Tensor): Input quantized embeddings with shape ``(b, emb_dim, d1, d2, d3)``.
"""
in_channel = x.shape[1]
if in_channel != self.conv_in.conv.in_channels:
raise ValueError(
f"expected input channel dim to be {self.conv_in.conv.in... | 31 | 996 | 125 | 1,121 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any, cast, List, Optional, Tuple, Union
import torch
from torch import nn, Size, Tensor
f... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any, cast, List, Optional, Tuple, Union
import torch
from torch import nn, Size, Tensor
f... |
45,338 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/video_gpt/video_vqvae.py | 291,292 | 217,320 | get_latent_shape | VideoEncoder | 293,304 | 292,304 | class VideoEncoder(nn.Module):
"""Encoder for Video VQVAE.
Stacks specified number of ``SamePadConv3d`` layers
followed by a stack of ``AttentionResidualBlocks`` and a final ``SamePadConv3d``
layer before the codebook. The residual blocks use Axial Attention to enhance
representations of video data... | class VideoEncoder(nn.Module):
"""Encoder for Video VQVAE.
Stacks specified number of ``SamePadConv3d`` layers
followed by a stack of ``AttentionResidualBlocks`` and a final ``SamePadConv3d``
layer before the codebook. The residual blocks use Axial Attention to enhance
representations of video data... | latent_shape = list(input_shape)
for layer in self.convs: # ignore conv_out since it has a stride of 1
if isinstance(layer, SamePadConv3d):
# SamePadConv should downsample input shape by factor of stride
latent_shape = [
latent_shape[dim] ... | """Return shape of encoder output based on number of downsampling conv layers"""
latent_shape = list(input_shape)
for layer in self.convs: # ignore conv_out since it has a stride of 1
if isinstance(layer, SamePadConv3d):
# SamePadConv should downsample input shape by... | 43 | 1,146 | 133 | 1,279 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any, cast, List, Optional, Tuple, Union
import torch
from torch import nn, Size, Tensor
f... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any, cast, List, Optional, Tuple, Union
import torch
from torch import nn, Size, Tensor
f... |
45,339 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/vqvae.py | 72,75 | 26,119 | encode | VQVAE | 85,93 | 75,93 | class VQVAE(nn.Module):
"""General model for VQVAE that provides codebook layer to link user specified
encoder and decoder.
Vector Quantized Variational Autoencoder is a type of autoencoder that defines
an embedding of discrete vectors as the latent variables in the bottleneck layer
instead of norm... | class VQVAE(nn.Module):
"""General model for VQVAE that provides codebook layer to link user specified
encoder and decoder.
Vector Quantized Variational Autoencoder is a type of autoencoder that defines
an embedding of discrete vectors as the latent variables in the bottleneck layer
instead of norm... | encoded = self.encoder(x)
out = self.codebook(encoded)
indices = out.codebook_indices
quantized = out.quantized
if return_embeddings:
return indices, quantized
return indices
| """Converts input data to token ids
Args:
x (Tensor): Input data of shape ``(b, c, d1, ..., dn)``.
return_embeddings (bool): Flag to return also the quantized embeddings. Defaults to ``False``.
Returns:
* A tensor of token ids: ``(b, d1, ...., dn)``
... | 19 | 1,127 | 71 | 1,198 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import NamedTuple, Tuple, Union
from torch import nn, Size, Tensor
from torchmultimodal.modules.la... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import NamedTuple, Tuple, Union
from torch import nn, Size, Tensor
from torchmultimodal.modules.la... |
45,341 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/encoders/bert_text_encoder.py | 67,77 | 17,123 | forward | BERTTextEncoder | 77,123 | 77,123 | class BERTTextEncoder(nn.Module):
"""
General text transformer encoder with embeddings, following BERT.
Can be constructed with any user-provided embeddings and encoder.
Based on https://github.com/huggingface/transformers/blob/main/src/transformers/models/bert/modeling_bert.py#L870
Attributes:
... | class BERTTextEncoder(nn.Module):
"""
General text transformer encoder with embeddings, following BERT.
Can be constructed with any user-provided embeddings and encoder.
Based on https://github.com/huggingface/transformers/blob/main/src/transformers/models/bert/modeling_bert.py#L870
Attributes:
... | if input_ids is not None:
input_shape = input_ids.size()
device = input_ids.device
elif inputs_embeds is not None:
input_shape = inputs_embeds.size()[:-1]
device = inputs_embeds.device
else:
raise ValueError("input_ids or inputs_embeds ... | if input_ids is not None:
input_shape = input_ids.size()
device = input_ids.device
elif inputs_embeds is not None:
input_shape = inputs_embeds.size()[:-1]
device = inputs_embeds.device
else:
raise ValueError("input_ids or inputs_embeds ... | 108 | 830 | 532 | 1,362 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Callable, Optional
import torch
from torch import nn, Tensor
from torchmultimodal.models.fl... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Callable, Optional
import torch
from torch import nn, Tensor
from torchmultimodal.models.fl... |
45,342 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/encoders/embedding_encoder.py | 48,49 | 14,59 | forward | EmbeddingEncoder | 49,59 | 49,59 | class EmbeddingEncoder(nn.Module):
"""Combine embeddings for tensor representing list of indices based on pooling type
Args:
embedding (nn.Embedding): embedding module
pooling_type (str): pooling function to combine the embeddings like sum. Choose
from pooling_types
pooling_dim ... | class EmbeddingEncoder(nn.Module):
"""Combine embeddings for tensor representing list of indices based on pooling type
Args:
embedding (nn.Embedding): embedding module
pooling_type (str): pooling function to combine the embeddings like sum. Choose
from pooling_types
pooling_dim ... | if self.use_hash:
x = x % (self.embedding.num_embeddings - 1) + 1
out = self.embedding(x)
if self.pooling_type == "sum":
out = torch.sum(out, dim=self.pooling_dim)
elif self.pooling_type == "mean":
out = torch.mean(out, dim=self.pooling_dim)
el... | if self.use_hash:
x = x % (self.embedding.num_embeddings - 1) + 1
out = self.embedding(x)
if self.pooling_type == "sum":
out = torch.sum(out, dim=self.pooling_dim)
elif self.pooling_type == "mean":
out = torch.mean(out, dim=self.pooling_dim)
el... | 37 | 348 | 147 | 495 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import torch
from torch import nn, Tensor
POOLING_TYPES = ["sum", "mean", "max"]
class EmbeddingEncoder(nn.... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import torch
from torch import nn, Tensor
POOLING_TYPES = ["sum", "mean", "max"]
class EmbeddingEncoder(nn.... |
45,343 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/encoders/mil_encoder.py | 85,86 | 17,100 | forward | MILEncoder | 86,100 | 86,100 | class MILEncoder(nn.Module):
"""
Multi instance learning encoder that partitions the input into a set of inputs
and uses a shared encoder followed by deepset
fusion to get a pooled representation of the entire input. Example use is to build a
single representation from embeddings of all images in a ... | class MILEncoder(nn.Module):
"""
Multi instance learning encoder that partitions the input into a set of inputs
and uses a shared encoder followed by deepset
fusion to get a pooled representation of the entire input. Example use is to build a
single representation from embeddings of all images in a ... | idx = 0
input_size = x.size(dim=1)
if input_size != sum(self.partition_sizes):
raise ValueError(
f"partition sizes should sum to the input size {input_size}"
)
partitioned_input = torch.split(x, self.partition_sizes, dim=1)
encoded_input =... | idx = 0
input_size = x.size(dim=1)
if input_size != sum(self.partition_sizes):
raise ValueError(
f"partition sizes should sum to the input size {input_size}"
)
partitioned_input = torch.split(x, self.partition_sizes, dim=1)
encoded_input =... | 43 | 809 | 173 | 982 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Callable, List, Optional, Union
import torch
from torch import nn, Tensor
from torchmultimo... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Callable, List, Optional, Union
import torch
from torch import nn, Tensor
from torchmultimo... |
45,345 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/encoders/vision_transformer.py | 119,120 | 91,133 | forward | GlobalAveragePooler | 127,133 | 120,133 | class GlobalAveragePooler(nn.Module):
"""
Global average pooler that averages the embeddings over all the patches in a sample
and applies layer norm and an optional linear head on top.
Args:
input_dim (int): hidden dim of the transformer last hidden state.
output_dim (Optional[int]): out... | class GlobalAveragePooler(nn.Module):
"""
Global average pooler that averages the embeddings over all the patches in a sample
and applies layer norm and an optional linear head on top.
Args:
input_dim (int): hidden dim of the transformer last hidden state.
output_dim (Optional[int]): out... | out = x[:, 1:, :].mean(dim=1)
out = self.norm(out)
out = self.head(out)
return out
| """
Args:
x (Tensor): Input tensor with shape bsz x len x input_dim. The first entry in assumed to be CLS
and ignored during averaging
Returns:
Tensor: Output tensor with shape bsz x output_dim
"""
out = x[:, 1:, :].mean(dim=1)
out ... | 13 | 418 | 51 | 469 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any, Callable, Optional, Tuple, Union
import torch
from torch import nn, Tensor
from torch... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any, Callable, Optional, Tuple, Union
import torch
from torch import nn, Tensor
from torch... |
45,346 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/encoders/vision_transformer.py | 57,63 | 20,91 | forward | VisionTransformer | 63,91 | 63,91 | class VisionTransformer(nn.Module):
"""
General image transformer encoder with embeddings. Similar to ``VisionTransformer`` in torchvision,
but more composable. Can be constructed with any user-provided embeddings, encoder, and task head.
Attributes:
embeddings (nn.Module): Module that projects... | class VisionTransformer(nn.Module):
"""
General image transformer encoder with embeddings. Similar to ``VisionTransformer`` in torchvision,
but more composable. Can be constructed with any user-provided embeddings, encoder, and task head.
Attributes:
embeddings (nn.Module): Module that projects... |
embedding_output = self.embeddings(
images, image_patches_mask=image_patches_mask
).embeddings
encoder_output = self.encoder(
embedding_output,
attention_mask=attention_mask,
return_hidden_states=True,
)
last_hidden_state = encode... |
embedding_output = self.embeddings(
images, image_patches_mask=image_patches_mask
).embeddings
encoder_output = self.encoder(
embedding_output,
attention_mask=attention_mask,
return_hidden_states=True,
)
last_hidden_state = encode... | 50 | 580 | 259 | 839 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any, Callable, Optional, Tuple, Union
import torch
from torch import nn, Tensor
from torch... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any, Callable, Optional, Tuple, Union
import torch
from torch import nn, Tensor
from torch... |
45,347 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/encoders/weighted_embedding_encoder.py | 40,41 | 13,53 | forward | WeightedEmbeddingEncoder | 41,53 | 41,53 | class WeightedEmbeddingEncoder(nn.Module):
"""Combine weighted embeddings for tensor representing list of indices based on
pooling type.
Args:
embedding (nn.Embedding): embedding module
pooling_function (Callable[[Tensor, int], Union[Tensor, Tuple]]): pooling function to combine the weighte... | class WeightedEmbeddingEncoder(nn.Module):
"""Combine weighted embeddings for tensor representing list of indices based on
pooling type.
Args:
embedding (nn.Embedding): embedding module
pooling_function (Callable[[Tensor, int], Union[Tensor, Tuple]]): pooling function to combine the weighte... | index = torch.arange(0, weights.size(1), dtype=torch.int)
index = index.to(weights.device)
weighted_embeddings = self.embedding(index) * weights.unsqueeze(-1)
pooled_embeddings = self.pooling_function(weighted_embeddings, self.pooling_dim)
if isinstance(pooled_embeddings, Tensor)... | index = torch.arange(0, weights.size(1), dtype=torch.int)
index = index.to(weights.device)
weighted_embeddings = self.embedding(index) * weights.unsqueeze(-1)
pooled_embeddings = self.pooling_function(weighted_embeddings, self.pooling_dim)
if isinstance(pooled_embeddings, Tensor)... | 50 | 326 | 192 | 518 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Callable, Tuple, Union
import torch
from torch import nn, Tensor
class WeightedEmbeddingE... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Callable, Tuple, Union
import torch
from torch import nn, Tensor
class WeightedEmbeddingE... |
45,348 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/fusions/attention_fusion.py | 46,47 | 13,63 | forward | AttentionFusionModule | 47,63 | 47,63 | class AttentionFusionModule(nn.Module):
"""
Fuse embeddings through weighted sum of the corresponding linear projections.
Linear layer for learning the weights.
Args:
channel_to_encoder_dim: mapping of channel name to the encoding dimension
encoding_projection_dim: common dimension to p... | class AttentionFusionModule(nn.Module):
"""
Fuse embeddings through weighted sum of the corresponding linear projections.
Linear layer for learning the weights.
Args:
channel_to_encoder_dim: mapping of channel name to the encoding dimension
encoding_projection_dim: common dimension to p... | concatenated_in = torch.cat(
[embeddings[k] for k in sorted(embeddings.keys())], dim=-1
)
attention_weights = self.attention(concatenated_in)
projected_embeddings: List[Tensor] = []
for channel, projection in self.encoding_projection.items():
projected_emb... | concatenated_in = torch.cat(
[embeddings[k] for k in sorted(embeddings.keys())], dim=-1
)
attention_weights = self.attention(concatenated_in)
projected_embeddings: List[Tensor] = []
for channel, projection in self.encoding_projection.items():
projected_emb... | 44 | 385 | 217 | 602 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Dict, List, Optional
import torch
from torch import nn, Tensor
class AttentionFusionModul... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Dict, List, Optional
import torch
from torch import nn, Tensor
class AttentionFusionModul... |
45,349 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/fusions/concat_fusion.py | 29,30 | 13,34 | forward | ConcatFusionModule | 30,34 | 30,34 | class ConcatFusionModule(nn.Module):
"""Module to fuse modalities via concatenation. Sorted by keys for consistency.
Inputs:
embeddings (Dict[str, Tensor]): A dictionary mapping modalities to their
tensor representations.
"""
def __init__(self, projection: nn.Module = None):
... | class ConcatFusionModule(nn.Module):
"""Module to fuse modalities via concatenation. Sorted by keys for consistency.
Inputs:
embeddings (Dict[str, Tensor]): A dictionary mapping modalities to their
tensor representations.
"""
def __init__(self, projection: nn.Module = None):
... | concatenated_in = torch.cat(
[embeddings[k] for k in sorted(embeddings.keys())], dim=-1
)
return self.projection(concatenated_in)
| concatenated_in = torch.cat(
[embeddings[k] for k in sorted(embeddings.keys())], dim=-1
)
return self.projection(concatenated_in)
| 12 | 162 | 56 | 218 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Dict
import torch
from torch import nn
class ConcatFusionModule(nn.Module):
"""Module... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Dict
import torch
from torch import nn
class ConcatFusionModule(nn.Module):
"""Module... |
45,351 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/fusions/deepset_fusion.py | 130,131 | 14,142 | _pool_features | DeepsetFusionModule | 131,142 | 131,142 | class DeepsetFusionModule(nn.Module):
"""
Fuse embeddings through stacking followed by pooling strategy and MLP
See https://arxiv.org/pdf/2003.01607.pdf
Args:
channel_to_encoder_dim (Dict[str, int]): mapping of channel name to the\
encoding dimension
mlp (nn.Module): MLP with in... | class DeepsetFusionModule(nn.Module):
"""
Fuse embeddings through stacking followed by pooling strategy and MLP
See https://arxiv.org/pdf/2003.01607.pdf
Args:
channel_to_encoder_dim (Dict[str, int]): mapping of channel name to the\
encoding dimension
mlp (nn.Module): MLP with in... | pooled_embeddings = self.pooling_function(embeddings, dim=1)
if torch.jit.isinstance(pooled_embeddings, Tuple[Tensor, Tensor]):
return pooled_embeddings.values
if not isinstance(pooled_embeddings, Tensor):
raise ValueError(
f"Result from pooling function s... | pooled_embeddings = self.pooling_function(embeddings, dim=1)
if torch.jit.isinstance(pooled_embeddings, Tuple[Tensor, Tensor]):
return pooled_embeddings.values
if not isinstance(pooled_embeddings, Tensor):
raise ValueError(
f"Result from pooling function s... | 32 | 1,266 | 135 | 1,401 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Callable, Dict, Optional, Tuple
import torch
import torch.nn.functional as F
from torch imp... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Callable, Dict, Optional, Tuple
import torch
import torch.nn.functional as F
from torch imp... |
45,352 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/fusions/deepset_fusion.py | 165,166 | 142,171 | _pool_features | DeepsetFusionWithTransformer | 166,171 | 166,171 | class DeepsetFusionWithTransformer(DeepsetFusionModule):
def __init__(
self,
channel_to_encoder_dim: Dict[str, int],
mlp: nn.Module,
pooling_function: nn.TransformerEncoder,
apply_attention: bool = False,
attention_dim: Optional[int] = None,
modality_normalize... | class DeepsetFusionWithTransformer(DeepsetFusionModule):
def __init__(
self,
channel_to_encoder_dim: Dict[str, int],
mlp: nn.Module,
pooling_function: nn.TransformerEncoder,
apply_attention: bool = False,
attention_dim: Optional[int] = None,
modality_normalize... | pooled = self.pooling_function(embeddings)
# take representation of the first token as the pooled feature
return pooled[:, 0, :]
| pooled = self.pooling_function(embeddings)
# take representation of the first token as the pooled feature
return pooled[:, 0, :]
| 18 | 232 | 48 | 280 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Callable, Dict, Optional, Tuple
import torch
import torch.nn.functional as F
from torch imp... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Callable, Dict, Optional, Tuple
import torch
import torch.nn.functional as F
from torch imp... |
45,353 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/layers/activation.py | 42,43 | 28,45 | forward | GEGLU | 43,45 | 43,45 | class GEGLU(nn.Module):
"""Gated Linear Unit with GELU activation function
.. math:: \text{GEGLU}(a,b) = a * \text{GELU}(b)
where :math:`a` is the first half of the input matrices and :math:`b` is
the second half, as descibed in the paper:
`"GLU Variants Improve Transformer"<https://arxiv.org/pdf/... | class GEGLU(nn.Module):
"""Gated Linear Unit with GELU activation function
.. math:: \text{GEGLU}(a,b) = a * \text{GELU}(b)
where :math:`a` is the first half of the input matrices and :math:`b` is
the second half, as descibed in the paper:
`"GLU Variants Improve Transformer"<https://arxiv.org/pdf/... | x, gate = x.chunk(2, dim=self.split_dim)
return x * F.gelu(gate)
| x, gate = x.chunk(2, dim=self.split_dim)
return x * F.gelu(gate)
| 9 | 195 | 36 | 231 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import torch
import torch.nn.functional as F
from torch import nn, Tensor
class SiLU(nn.Module):
r"""Sigm... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import torch
import torch.nn.functional as F
from torch import nn, Tensor
class SiLU(nn.Module):
r"""Sigm... |
45,354 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/layers/activation.py | 24,25 | 12,28 | forward | SiLU | 25,28 | 25,28 | class SiLU(nn.Module):
r"""Sigmoid Linear Unit
.. math:: \text{SiLU}(x) = x * \sigma(1.702 * x)
where :math:`\sigma(x)` is the cumulative distribution function for Logistic Distribution.
Approximation of the exact GeLU for greater forward speed. Note that this is different from
``torch.nn.SiLU`` ... | class SiLU(nn.Module):
r"""Sigmoid Linear Unit
.. math:: \text{SiLU}(x) = x * \sigma(1.702 * x)
where :math:`\sigma(x)` is the cumulative distribution function for Logistic Distribution.
Approximation of the exact GeLU for greater forward speed. Note that this is different from
``torch.nn.SiLU`` ... | return torch.sigmoid(1.702 * x) * x
| return torch.sigmoid(1.702 * x) * x
| 6 | 190 | 25 | 215 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import torch
import torch.nn.functional as F
from torch import nn, Tensor
class SiLU(nn.Module):
r"""Sigm... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import torch
import torch.nn.functional as F
from torch import nn, Tensor
class SiLU(nn.Module):
r"""Sigm... |
45,356 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/layers/attention.py | 120,129 | 70,185 | forward | MultiHeadAttention | 144,185 | 129,185 | class MultiHeadAttention(nn.Module):
"""Computes multihead attention with flexible attention mechanism and caching for fast decoding.
Multihead attention linearly projects and divides queries, keys, and values into
multiple 'heads'. This enables the computation of attention multiple times in
parallel, ... | class MultiHeadAttention(nn.Module):
"""Computes multihead attention with flexible attention mechanism and caching for fast decoding.
Multihead attention linearly projects and divides queries, keys, and values into
multiple 'heads'. This enables the computation of attention multiple times in
parallel, ... | # If kv is specified use those inputs for cross-attention, otherwise use q
k = v = q if kv is None else kv
# compute q
q = split_multihead(self.query(q), self.n_head)
# For causal k, v are provided step-wise so we should always compute them
# For non-causal skip computin... | """
Args:
q (Tensor): Query of shape ``(b, d1, ..., dn, dim_q)`` or ``(b, seq_len, dim_q)``
(for autoregressive decoding it's typical to pass in flattened tensors).
kv (Tensor, optional): Key (and value) of shape ``(b, d1', ..., dn', dim_kv)`` or
`... | 197 | 1,084 | 553 | 1,637 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any, Dict, Optional, Tuple, Union
import torch
from torch import nn, Tensor
from torch.nn i... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any, Dict, Optional, Tuple, Union
import torch
from torch import nn, Tensor
from torch.nn i... |
45,357 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/layers/attention.py | 26,34 | 15,70 | forward | SelfAttention | 51,70 | 34,70 | class SelfAttention(nn.Module):
"""Computes attention over the entire n-dimensional input.
Args:
attn_dropout (float, optional): Probability of dropout after softmax. Default is ``0.0``.
"""
def __init__(self, attn_dropout: float = 0.0) -> None:
super().__init__()
self.attn_dro... | class SelfAttention(nn.Module):
"""Computes attention over the entire n-dimensional input.
Args:
attn_dropout (float, optional): Probability of dropout after softmax. Default is ``0.0``.
"""
def __init__(self, attn_dropout: float = 0.0) -> None:
super().__init__()
self.attn_dro... | _, _, *shape, _ = q.shape
# flatten to b, h, (d1, ..., dn), dim_q/dim_kv
q = q.flatten(start_dim=2, end_dim=-2)
k = k.flatten(start_dim=2, end_dim=-2)
v = v.flatten(start_dim=2, end_dim=-2)
out, attn_probs = scaled_dot_product_attention(
q,
k,
... | """
Args:
q (Tensor): Query input of shape ``(b, h, d1, ..., dn, dim_q)`` where ``h`` is the number of
attention heads, ``(d1, ..., dn)`` are the query latent dimensions and ``dim_q`` is the dimension
of the query embeddings.
k, v (Tensor): Key/val... | 46 | 522 | 225 | 747 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any, Dict, Optional, Tuple, Union
import torch
from torch import nn, Tensor
from torch.nn i... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any, Dict, Optional, Tuple, Union
import torch
from torch import nn, Tensor
from torch.nn i... |
45,358 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/layers/attention_pooler.py | 47,48 | 16,71 | forward | AttentionPooler | 55,67 | 48,67 | class AttentionPooler(nn.Module):
"""
Attention pooling layer: pools inputs to sequence length n_queries by performing
cross-attention with learned query embeddings. Originally proposed in
https://arxiv.org/abs/1810.00825. This implementation is based on the one
in open_clip repo: https:... | class AttentionPooler(nn.Module):
"""
Attention pooling layer: pools inputs to sequence length n_queries by performing
cross-attention with learned query embeddings. Originally proposed in
https://arxiv.org/abs/1810.00825. This implementation is based on the one
in open_clip repo: https:... | x = self.ln_k(x)
query = self.ln_q(self.query)
batch_size = x.shape[0]
# (n_queries, output_embed_dim) -> (batch_size, n_queries, output_embed_dim)
query = self._repeat(query, batch_size)
out = self.attn(query, x, x)
assert isinstance(out, Tensor)
out = ... | """
Inputs:
x (Tensor): Input tensor of shape (batch_size, seq_len, input_embed_dim).
Returns:
Attention pooled tensor with shape
(batch_size, n_queries, output_embed_dim).
"""
x = self.ln_k(x)
query = self.ln_q(self.query)
... | 33 | 578 | 142 | 720 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import List
import torch
from torch import nn, Tensor
from torchmultimodal.modules.layers.multi_he... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import List
import torch
from torch import nn, Tensor
from torchmultimodal.modules.layers.multi_he... |
45,359 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/layers/attention_pooler.py | 88,89 | 71,102 | forward | CascadedAttentionPooler | 97,102 | 89,102 | class CascadedAttentionPooler(nn.Module):
"""
Wrapper class to perform cascaded attention pooling given multiple attention
poolers. E.g. in CoCa the contrastive pooler is applied on top of the outputs of
the captioning pooler.
Args:
poolers (List[AttentionPooler]): List of individual attent... | class CascadedAttentionPooler(nn.Module):
"""
Wrapper class to perform cascaded attention pooling given multiple attention
poolers. E.g. in CoCa the contrastive pooler is applied on top of the outputs of
the captioning pooler.
Args:
poolers (List[AttentionPooler]): List of individual attent... | pooler_outs = []
for pooler in self.poolers:
x = pooler(x)
pooler_outs.append(x)
return pooler_outs
| """
Inputs:
x (Tensor): Input tensor of shape (batch_size, seq_len, input_embed_dim).
Returns:
List[Tensor] containing attention pooled tensors with shapes
(batch_size, n_queries, output_embed_dim), where n_queries and
output_embed_dim are ... | 13 | 272 | 51 | 323 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import List
import torch
from torch import nn, Tensor
from torchmultimodal.modules.layers.multi_he... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import List
import torch
from torch import nn, Tensor
from torchmultimodal.modules.layers.multi_he... |
45,362 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/layers/conv.py | 62,63 | 15,75 | forward | SamePadConv3d | 67,75 | 63,75 | class SamePadConv3d(nn.Module):
"""Performs a same padded convolution on a 3D input.
This maintains input shape with unit stride, and divides input dims by non-unit stride.
Code reference:
https://github.com/wilson1yan/VideoGPT/blob/master/videogpt/vqvae.py
Args:
in_channels (int): Nu... | class SamePadConv3d(nn.Module):
"""Performs a same padded convolution on a 3D input.
This maintains input shape with unit stride, and divides input dims by non-unit stride.
Code reference:
https://github.com/wilson1yan/VideoGPT/blob/master/videogpt/vqvae.py
Args:
in_channels (int): Nu... | # Calculate padding needed based on input shape only once to reduce run time
if self.pad_input is None:
self.pad_input = calculate_same_padding(
self.kernel_size, self.stride, x.shape[2:]
)
return self.conv(F.pad(x, self.pad_input))
| """
Args:
x (Tensor): Input of shape ``(b, c, d1, d2, d3)``.
"""
# Calculate padding needed based on input shape only once to reduce run time
if self.pad_input is None:
self.pad_input = calculate_same_padding(
self.kernel_size, self.stride,... | 28 | 579 | 93 | 672 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import warnings
from itertools import repeat
from typing import Any, Tuple, Union
from torch import nn, Size, ... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import warnings
from itertools import repeat
from typing import Any, Tuple, Union
from torch import nn, Size, ... |
45,363 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/layers/conv.py | 117,118 | 75,133 | forward | SamePadConvTranspose3d | 122,133 | 118,133 | class SamePadConvTranspose3d(nn.Module):
"""Performs a same padded transposed convolution on a 3D input.
This ensures output shape in input shape multiplied by stride.
Code reference:
https://github.com/wilson1yan/VideoGPT/blob/master/videogpt/vqvae.py
Args:
in_channels (int): Number ... | class SamePadConvTranspose3d(nn.Module):
"""Performs a same padded transposed convolution on a 3D input.
This ensures output shape in input shape multiplied by stride.
Code reference:
https://github.com/wilson1yan/VideoGPT/blob/master/videogpt/vqvae.py
Args:
in_channels (int): Number ... | # Calculate padding needed based on input shape only once to reduce run time
if self.pad_input is None:
self.pad_input = calculate_same_padding(
self.kernel_size, self.stride, x.shape[2:]
)
self.convt.padding, self.convt.output_padding = calculate_tran... | """
Args:
x (Tensor): Input of shape ``(b, c, d1, d2, d3)``.
"""
# Calculate padding needed based on input shape only once to reduce run time
if self.pad_input is None:
self.pad_input = calculate_same_padding(
self.kernel_size, self.stride,... | 37 | 544 | 155 | 699 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import warnings
from itertools import repeat
from typing import Any, Tuple, Union
from torch import nn, Size, ... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import warnings
from itertools import repeat
from typing import Any, Tuple, Union
from torch import nn, Size, ... |
45,364 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/layers/multi_head_attention.py | 118,128 | 84,182 | forward | MultiHeadAttentionWithCache | 148,182 | 128,182 | class MultiHeadAttentionWithCache(nn.Module):
"""
MultiHeadAttention module for both self-attention(SA) and cross-attention(CA).
This class supports a cache mechanism for decoders to store previous states through
"past_key_value". Key/value states should be only cached for self-attention cases.
q, k... | class MultiHeadAttentionWithCache(nn.Module):
"""
MultiHeadAttention module for both self-attention(SA) and cross-attention(CA).
This class supports a cache mechanism for decoders to store previous states through
"past_key_value". Key/value states should be only cached for self-attention cases.
q, k... | bsz = query.size(0)
embed_dim = query.size(-1)
head_dim = embed_dim // self.num_heads
query = self.q_proj(query)
key = self.k_proj(key)
value = self.v_proj(value)
# bsz x seq_len x embed_dim => bsz x num_heads x seq_len x head_dim
query = query.view(bsz, ... | """
Args:
query (Tensor): input query of shape bsz x target_seq_len x embed_dim
key (Tensor): key of shape bsz x source_seq_len x embed_dim
value (Tensor): value of shape bsz x source_seq_len x embed_dim
attn_mask (optional Tensor): Attention mask of shape... | 163 | 929 | 563 | 1,492 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import NamedTuple, Optional, Tuple, Union
import torch
import torch.nn.functional as F
from torch... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import NamedTuple, Optional, Tuple, Union
import torch
import torch.nn.functional as F
from torch... |
45,365 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/layers/multi_head_attention.py | 40,46 | 20,84 | forward | MultiHeadSelfAttention | 59,84 | 46,84 | class MultiHeadSelfAttention(nn.Module):
"""
Multihead self attention.
Similar to the self attention variant of MHA in attention.py but uses the scaled_dot_product_attention from PyTorch
(which uses flash or memory efficient version for certain conditions).
TODO: merge this into attention.py once ot... | class MultiHeadSelfAttention(nn.Module):
"""
Multihead self attention.
Similar to the self attention variant of MHA in attention.py but uses the scaled_dot_product_attention from PyTorch
(which uses flash or memory efficient version for certain conditions).
TODO: merge this into attention.py once ot... |
bsz = query.size(0)
embed_dim = query.size(-1)
projected_query = self.input_proj(query)
query, key, value = projected_query.chunk(3, dim=-1)
head_dim = embed_dim // self.num_heads
# bsz x seq len x embed_dim => bsz x num_heads x seq len x head_dim
query = query.... | """
Args:
query (Tensor): input query of shape bsz x seq_len x embed_dim
attn_mask (optional Tensor): attention mask of shape bsz x num_heads x seq_len x seq_len.
Note that the num_heads dimension can equal 1 and the mask will be broadcasted to all heads.
... | 99 | 500 | 379 | 879 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import NamedTuple, Optional, Tuple, Union
import torch
import torch.nn.functional as F
from torch... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import NamedTuple, Optional, Tuple, Union
import torch
import torch.nn.functional as F
from torch... |
45,366 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/layers/normalizations.py | 40,41 | 28,51 | forward | Fp32GroupNorm | 41,51 | 41,51 | class Fp32GroupNorm(nn.GroupNorm):
"""
GroupNorm that supports mixed-precision / fp16 training by performing normalization
in fp32 and converting back.
Code ref:
https://github.com/facebookresearch/fairseq/blob/0338cdc3094ca7d29ff4d36d64791f7b4e4b5e6e/fairseq/modules/fp32_group_norm.py#L13
"""
... | class Fp32GroupNorm(nn.GroupNorm):
"""
GroupNorm that supports mixed-precision / fp16 training by performing normalization
in fp32 and converting back.
Code ref:
https://github.com/facebookresearch/fairseq/blob/0338cdc3094ca7d29ff4d36d64791f7b4e4b5e6e/fairseq/modules/fp32_group_norm.py#L13
"""
... | output = nn.functional.group_norm(
x.float(),
self.num_groups,
self.weight.float() if self.weight is not None else None,
self.bias.float() if self.bias is not None else None,
self.eps,
)
return output.type_as(x)
| output = nn.functional.group_norm(
x.float(),
self.num_groups,
self.weight.float() if self.weight is not None else None,
self.bias.float() if self.bias is not None else None,
self.eps,
)
return output.type_as(x)
| 25 | 193 | 98 | 291 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any
import torch
from torch import nn, Tensor
class Fp32LayerNorm(nn.LayerNorm):
def ... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any
import torch
from torch import nn, Tensor
class Fp32LayerNorm(nn.LayerNorm):
def ... |
45,367 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/layers/normalizations.py | 17,18 | 13,28 | forward | Fp32LayerNorm | 18,28 | 18,28 | class Fp32LayerNorm(nn.LayerNorm):
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
def forward(self, x: Tensor) -> Tensor:
FILL_FUNC_BODY | class Fp32LayerNorm(nn.LayerNorm):
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
def forward(self, x: Tensor) -> Tensor:
FILL_FUNC_BODY | output = nn.functional.layer_norm(
x.float(),
self.normalized_shape,
self.weight.float() if self.weight is not None else None,
self.bias.float() if self.bias is not None else None,
self.eps,
)
return output.type_as(x)
| output = nn.functional.layer_norm(
x.float(),
self.normalized_shape,
self.weight.float() if self.weight is not None else None,
self.bias.float() if self.bias is not None else None,
self.eps,
)
return output.type_as(x)
| 25 | 77 | 99 | 176 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any
import torch
from torch import nn, Tensor
class Fp32LayerNorm(nn.LayerNorm):
def ... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any
import torch
from torch import nn, Tensor
class Fp32LayerNorm(nn.LayerNorm):
def ... |
45,368 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/layers/normalizations.py | 69,70 | 51,77 | _norm | RMSNorm | 70,72 | 70,72 | class RMSNorm(nn.Module):
"""Root Mean Square Layer Normalization
as proposed in: https://arxiv.org/abs/1910.07467
Calcs are done in fp32.
original impl: https://github.com/facebookresearch/llama/blob/main/llama/model.py
Args:
dim(int) = model size
eps(float) = epsilon
"""
... | class RMSNorm(nn.Module):
"""Root Mean Square Layer Normalization
as proposed in: https://arxiv.org/abs/1910.07467
Calcs are done in fp32.
original impl: https://github.com/facebookresearch/llama/blob/main/llama/model.py
Args:
dim(int) = model size
eps(float) = epsilon
"""
... | return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
| return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
| 7 | 254 | 34 | 288 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any
import torch
from torch import nn, Tensor
class Fp32LayerNorm(nn.LayerNorm):
def ... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any
import torch
from torch import nn, Tensor
class Fp32LayerNorm(nn.LayerNorm):
def ... |
45,369 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/layers/normalizations.py | 94,95 | 77,97 | forward | SimpleRMSNorm | 95,97 | 95,97 | class SimpleRMSNorm(nn.Module):
"""Simple RMSNorm
SRMSNorm(x) = (x / ∥x∥2) /√d
as proposed in:
Scaling TransNormer to 175 Billion Parameters
https://arxiv.org/abs/2307.14995
Usage: use as drop in replacement for RMSNorm.
"""
def __init__(self, dim: int, eps: float = 1e-12):
s... | class SimpleRMSNorm(nn.Module):
"""Simple RMSNorm
SRMSNorm(x) = (x / ∥x∥2) /√d
as proposed in:
Scaling TransNormer to 175 Billion Parameters
https://arxiv.org/abs/2307.14995
Usage: use as drop in replacement for RMSNorm.
"""
def __init__(self, dim: int, eps: float = 1e-12):
s... | denom = x.norm(p=2, dim=-1, keepdim=True).clamp_min(self.eps).expand_as(x)
return (x / denom) * self.scaling
| denom = x.norm(p=2, dim=-1, keepdim=True).clamp_min(self.eps).expand_as(x)
return (x / denom) * self.scaling
| 11 | 193 | 54 | 247 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any
import torch
from torch import nn, Tensor
class Fp32LayerNorm(nn.LayerNorm):
def ... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any
import torch
from torch import nn, Tensor
class Fp32LayerNorm(nn.LayerNorm):
def ... |
45,370 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/layers/patch_embedding.py | 86,87 | 26,159 | _init_conv_weights | PatchEmbeddings | 87,96 | 87,96 | class PatchEmbeddings(nn.Module):
"""
Construct the CLS token, position and patch embeddings for vision transformer
Args:
image_size (Union[int, Tuple[int, int]]): Size of the input. If set to an int, we assume a square input. Defaults to 224.
patch_size (int): Size of the patch. Defaults to... | class PatchEmbeddings(nn.Module):
"""
Construct the CLS token, position and patch embeddings for vision transformer
Args:
image_size (Union[int, Tuple[int, int]]): Size of the input. If set to an int, we assume a square input. Defaults to 224.
patch_size (int): Size of the patch. Defaults to... | fan_in = (
self.conv_projection.in_channels
* self.conv_projection.kernel_size[0]
* self.conv_projection.kernel_size[1]
)
nn.init.trunc_normal_(self.conv_projection.weight, std=math.sqrt(1 / fan_in))
assert self.conv_projection.bias is not None
... | fan_in = (
self.conv_projection.in_channels
* self.conv_projection.kernel_size[0]
* self.conv_projection.kernel_size[1]
)
nn.init.trunc_normal_(self.conv_projection.weight, std=math.sqrt(1 / fan_in))
assert self.conv_projection.bias is not None
... | 19 | 1,746 | 133 | 1,879 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import math
import warnings
from typing import Iterable, NamedTuple, Optional, Tuple, Union
import torch
from ... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import math
import warnings
from typing import Iterable, NamedTuple, Optional, Tuple, Union
import torch
from ... |
45,371 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/layers/text_embedding.py | 70,77 | 13,105 | forward | BERTTextEmbeddings | 77,105 | 77,105 | class BERTTextEmbeddings(nn.Module):
"""Construct word, position, and token type embeddings following BERT, similar to HuggingFace BertEmbeddings
Attributes:
hidden_size (int): size of embedding space. Default is 768.
vocab_size (int): size of vocabulary. Default is 30522.
pad_token_id ... | class BERTTextEmbeddings(nn.Module):
"""Construct word, position, and token type embeddings following BERT, similar to HuggingFace BertEmbeddings
Attributes:
hidden_size (int): size of embedding space. Default is 768.
vocab_size (int): size of vocabulary. Default is 30522.
pad_token_id ... | if input_ids is not None:
input_shape = input_ids.size()
device = input_ids.device
elif inputs_embeds is not None:
input_shape = inputs_embeds.size()[:-1]
device = inputs_embeds.device
else:
raise ValueError("input_ids or inputs_embeds ... | if input_ids is not None:
input_shape = input_ids.size()
device = input_ids.device
elif inputs_embeds is not None:
input_shape = inputs_embeds.size()[:-1]
device = inputs_embeds.device
else:
raise ValueError("input_ids or inputs_embeds ... | 89 | 988 | 399 | 1,387 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Optional
import torch
from torch import nn, Tensor
class BERTTextEmbeddings(nn.Module):
... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Optional
import torch
from torch import nn, Tensor
class BERTTextEmbeddings(nn.Module):
... |
45,372 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/layers/transformer.py | 592,602 | 529,663 | forward | TransformerDecoder | 627,663 | 602,663 | class TransformerDecoder(nn.Module):
"""
Transformer decoder: n transformer decoder layers and an optional final LN
Args:
n_layer (int): number of transformer decoder layers
d_model (int): size of hidden dimension of input
n_head (int): number of attention heads
dim_feedforw... | class TransformerDecoder(nn.Module):
"""
Transformer decoder: n transformer decoder layers and an optional final LN
Args:
n_layer (int): number of transformer decoder layers
d_model (int): size of hidden dimension of input
n_head (int): number of attention heads
dim_feedforw... |
all_hidden_states = []
current_key_values = torch.jit.annotate(List[Tuple[Tensor, Tensor]], [])
for i, layer_module in enumerate(self.layer):
if return_hidden_states:
all_hidden_states.append(hidden_states)
past_key_value = past_key_values[i] if past_k... | """
Inputs:
hidden_states (Tensor): input query of shape bsz x seq_len x embed_dim
encoder_hidden_states (Optional[Tensor]): input key/values of shape
bsz x seq_len x embed_dim, only used for cross-attention.
Default is None.
attention_... | 62 | 1,193 | 382 | 1,575 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Callable, List, NamedTuple, Optional, Tuple
import torch
from torch import nn, Tensor
fro... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Callable, List, NamedTuple, Optional, Tuple
import torch
from torch import nn, Tensor
fro... |
45,374 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/layers/transformer.py | 214,220 | 158,259 | forward | TransformerEncoder | 233,259 | 220,259 | class TransformerEncoder(nn.Module):
"""
Transformer encoder consisting of n Transformer encoder layers and an optional final LN
Args:
n_layer (int): number of Transformer encoder layers
d_model (int): size of hidden dimension of input
n_head (int): number of attention heads
... | class TransformerEncoder(nn.Module):
"""
Transformer encoder consisting of n Transformer encoder layers and an optional final LN
Args:
n_layer (int): number of Transformer encoder layers
d_model (int): size of hidden dimension of input
n_head (int): number of attention heads
... |
all_hidden_states = []
for layer_module in self.layer:
if return_hidden_states:
all_hidden_states.append(hidden_states)
layer_outputs = layer_module(
hidden_states,
attention_mask=attention_mask,
)
hidden... | """
Args:
hidden_states (Tensor): input to the transformer encoder of shape bsz x seq_len x d_model
attention_mask (Optional[Tensor]): attention mask of shape bsz x seq_len x seq_len.
Same format as MultiHeadSelfAttention class.
return_hidden_states (bool)... | 39 | 922 | 215 | 1,137 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Callable, List, NamedTuple, Optional, Tuple
import torch
from torch import nn, Tensor
fro... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Callable, List, NamedTuple, Optional, Tuple
import torch
from torch import nn, Tensor
fro... |
45,375 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/layers/transformer.py | 81,86 | 32,158 | _attention_block | TransformerEncoderLayer | 86,93 | 86,93 | class TransformerEncoderLayer(nn.Module):
"""Transformer encoder layer: transformer block consisting of multihead self-attention and feedforward blocks,
based on "Attention Is All You Need" (Vaswani et al. 2017).
Args:
d_model (int): size of hidden dimension of input
n_head (int): number of... | class TransformerEncoderLayer(nn.Module):
"""Transformer encoder layer: transformer block consisting of multihead self-attention and feedforward blocks,
based on "Attention Is All You Need" (Vaswani et al. 2017).
Args:
d_model (int): size of hidden dimension of input
n_head (int): number of... | output = self.attention(
hidden_states,
attn_mask=attention_mask,
)
output = self.attention_dropout(output)
return output
| output = self.attention(
hidden_states,
attn_mask=attention_mask,
)
output = self.attention_dropout(output)
return output
| 11 | 1,305 | 53 | 1,358 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Callable, List, NamedTuple, Optional, Tuple
import torch
from torch import nn, Tensor
fro... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Callable, List, NamedTuple, Optional, Tuple
import torch
from torch import nn, Tensor
fro... |
45,376 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/losses/albef.py | 105,112 | 80,139 | forward | CausalLanguageModelingLoss | 112,139 | 112,139 | class CausalLanguageModelingLoss(nn.Module):
"""
Compute the autoregressive masked language modeling loss by predicting the next token, as used in VQA.
Support loss distillation for non-zero alpha. Compute standard mlm loss for zero alpha.
Args:
mask_token_id (int): The token id indicating a ma... | class CausalLanguageModelingLoss(nn.Module):
"""
Compute the autoregressive masked language modeling loss by predicting the next token, as used in VQA.
Support loss distillation for non-zero alpha. Compute standard mlm loss for zero alpha.
Args:
mask_token_id (int): The token id indicating a ma... | batch_size = labels.size(0)
# shift prediction scores and labels by one for next-token predict
prediction_scores = prediction_scores[:, :-1, :].contiguous()
labels = labels[:, 1:].contiguous()
mlm_loss = F.cross_entropy(
prediction_scores.view(-1, prediction_scores.sh... | batch_size = labels.size(0)
# shift prediction scores and labels by one for next-token predict
prediction_scores = prediction_scores[:, :-1, :].contiguous()
labels = labels[:, 1:].contiguous()
mlm_loss = F.cross_entropy(
prediction_scores.view(-1, prediction_scores.sh... | 90 | 383 | 377 | 760 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Optional
import torch
import torch.nn.functional as F
from torch import nn, Tensor
class ... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Optional
import torch
import torch.nn.functional as F
from torch import nn, Tensor
class ... |
45,377 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/losses/albef.py | 36,45 | 14,80 | forward | ImageTextContrastiveLoss | 45,80 | 45,80 | class ImageTextContrastiveLoss(nn.Module):
"""
Compute the image-text contrastive loss from image-text similarity, as used in ALBEF.
Support loss distillation with pseudo-targets for non-zero alpha. Compute standard contrastive loss for zero alpha.
Inputs:
image_to_text_sim (Tensor): Image to t... | class ImageTextContrastiveLoss(nn.Module):
"""
Compute the image-text contrastive loss from image-text similarity, as used in ALBEF.
Support loss distillation with pseudo-targets for non-zero alpha. Compute standard contrastive loss for zero alpha.
Inputs:
image_to_text_sim (Tensor): Image to t... | if sim_targets is None:
sim_targets = torch.zeros(image_to_text_sim.size()).to(
image_to_text_sim.device
)
sim_targets.fill_diagonal_(1)
if alpha != 0:
assert (
image_to_text_sim_m is not None and text_to_image_sim_m is not... | if sim_targets is None:
sim_targets = torch.zeros(image_to_text_sim.size()).to(
image_to_text_sim.device
)
sim_targets.fill_diagonal_(1)
if alpha != 0:
assert (
image_to_text_sim_m is not None and text_to_image_sim_m is not... | 99 | 407 | 463 | 870 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Optional
import torch
import torch.nn.functional as F
from torch import nn, Tensor
class ... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Optional
import torch
import torch.nn.functional as F
from torch import nn, Tensor
class ... |
45,379 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/losses/blip2_losses.py | 292,299 | 257,364 | forward | Blip2Phase1Loss | 309,364 | 299,364 | class Blip2Phase1Loss(nn.Module):
"""
Blip2 phase 1 loss module
Args:
dim_q (int): Dimension of query tensor, this value should be the same as dim_q in qformer.
default value is 768 as in the paper.
enable_itc (bool): enable image-text contrastive loss, default is True
e... | class Blip2Phase1Loss(nn.Module):
"""
Blip2 phase 1 loss module
Args:
dim_q (int): Dimension of query tensor, this value should be the same as dim_q in qformer.
default value is 768 as in the paper.
enable_itc (bool): enable image-text contrastive loss, default is True
e... |
# calculate similarities
assert model_output.text_features is not None
(
sim_i2t,
sim_t2i,
) = compute_image_text_similarity(
model_output.image_features,
model_output.text_features,
temp=self.temp,
)
# calcula... | """
Inputs:
model_output (Blip2Output): model output from BLIP2 (see blip2.py)
blip2 (nn.Module): BLIP2 model with updated params
input_ids (Optional[torch.Tensor]): text input ids of shape [bsz, seq_len].
attention_mask (Optional[torch.Tensor]): text inpu... | 111 | 632 | 677 | 1,309 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from dataclasses import dataclass
from typing import Optional, OrderedDict, Tuple
import torch
from torch impo... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from dataclasses import dataclass
from typing import Optional, OrderedDict, Tuple
import torch
from torch impo... |
45,381 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/losses/contrastive_loss_with_temperature.py | 185,193 | 121,203 | forward | ContrastiveLossWithTemperature | 193,203 | 193,203 | class ContrastiveLossWithTemperature(nn.Module):
"""Contrastive loss with a temperature parameter, as used in CLIP and FLAVA.
CLIP: https://arxiv.org/pdf/2103.00020.pdf
FLAVA: https://arxiv.org/pdf/2112.04482.pdf
A contrastive loss over pairs of input embeddings a and b. For each input_a
embedding... | class ContrastiveLossWithTemperature(nn.Module):
"""Contrastive loss with a temperature parameter, as used in CLIP and FLAVA.
CLIP: https://arxiv.org/pdf/2103.00020.pdf
FLAVA: https://arxiv.org/pdf/2112.04482.pdf
A contrastive loss over pairs of input embeddings a and b. For each input_a
embedding... |
self.logit_scale.data.clamp_(self.logit_scale_min, self.logit_scale_max)
return contrastive_loss_with_temperature(
embeddings_a=embeddings_a,
embeddings_b=embeddings_b,
logit_scale=self.logit_scale,
backprop_type=backprop_type,
cross_entropy_k... |
self.logit_scale.data.clamp_(self.logit_scale_min, self.logit_scale_max)
return contrastive_loss_with_temperature(
embeddings_a=embeddings_a,
embeddings_b=embeddings_b,
logit_scale=self.logit_scale,
backprop_type=backprop_type,
cross_entropy_k... | 11 | 1,065 | 131 | 1,196 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import math
from dataclasses import dataclass
from typing import Any, Dict, Optional, OrderedDict, Tuple, Union... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import math
from dataclasses import dataclass
from typing import Any, Dict, Optional, OrderedDict, Tuple, Union... |
45,383 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/losses/flava.py | 261,267 | 241,297 | forward | FLAVAGlobalContrastiveLoss | 267,297 | 267,297 | class FLAVAGlobalContrastiveLoss(nn.Module):
def __init__(
self,
logit_scale: Union[float, nn.Parameter] = None,
image_embedding_size: int = 768,
text_embedding_size: int = 768,
projection_size: int = 768,
image_embedding_index: int = 0,
text_embedding_index: ... | class FLAVAGlobalContrastiveLoss(nn.Module):
def __init__(
self,
logit_scale: Union[float, nn.Parameter] = None,
image_embedding_size: int = 768,
text_embedding_size: int = 768,
projection_size: int = 768,
image_embedding_index: int = 0,
text_embedding_index: ... |
text_embedding = nn.functional.normalize(text_sequence, dim=-1)
image_embedding = nn.functional.normalize(
image_sequence,
dim=-1,
)
self.logit_scale.data.clamp_(0, 4.6052)
output = contrastive_loss_with_temperature(
embeddings_a=image_embed... |
text_embedding = nn.functional.normalize(text_sequence, dim=-1)
image_embedding = nn.functional.normalize(
image_sequence,
dim=-1,
)
self.logit_scale.data.clamp_(0, 4.6052)
output = contrastive_loss_with_temperature(
embeddings_a=image_embed... | 40 | 293 | 325 | 618 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import math
import warnings
from dataclasses import dataclass, field
from typing import Any, Callable, Optional... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import math
import warnings
from dataclasses import dataclass, field
from typing import Any, Callable, Optional... |
45,385 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/losses/flava.py | 122,127 | 110,143 | forward | ITMLoss | 127,143 | 127,143 | class ITMLoss(nn.Module):
def __init__(
self,
hidden_size: int = 768,
ignore_index: int = -1,
**kwargs: Any,
):
super().__init__()
self.pooler = Pooler(hidden_size=hidden_size)
self.cls = TwoWayHead(hidden_size=hidden_size)
self.ce_loss = nn.CrossE... | class ITMLoss(nn.Module):
def __init__(
self,
hidden_size: int = 768,
ignore_index: int = -1,
**kwargs: Any,
):
super().__init__()
self.pooler = Pooler(hidden_size=hidden_size)
self.cls = TwoWayHead(hidden_size=hidden_size)
self.ce_loss = nn.CrossE... | if self.training:
assert_labels_are_present(labels, "itm labels")
pooled_output = self.pooler(hidden_states)
scores = self.cls(pooled_output)
if labels is None:
loss = pooled_output.sum() * 0
else:
loss = self.ce_loss(
scores.... | if self.training:
assert_labels_are_present(labels, "itm labels")
pooled_output = self.pooler(hidden_states)
scores = self.cls(pooled_output)
if labels is None:
loss = pooled_output.sum() * 0
else:
loss = self.ce_loss(
scores.... | 31 | 170 | 148 | 318 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import math
import warnings
from dataclasses import dataclass, field
from typing import Any, Callable, Optional... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import math
import warnings
from dataclasses import dataclass, field
from typing import Any, Callable, Optional... |
45,386 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/losses/flava.py | 174,175 | 143,182 | forward | MaskedPredictionHead | 175,182 | 175,182 | class MaskedPredictionHead(nn.Module):
def __init__(
self,
hidden_size: int = 768,
vocab_size: int = 30522,
transform_act_fn: Callable[[Tensor], Tensor] = nn.functional.gelu,
layer_norm_eps: float = 1e-5,
use_fp32_layer_norm: bool = True,
**kwargs: Any,
):... | class MaskedPredictionHead(nn.Module):
def __init__(
self,
hidden_size: int = 768,
vocab_size: int = 30522,
transform_act_fn: Callable[[Tensor], Tensor] = nn.functional.gelu,
layer_norm_eps: float = 1e-5,
use_fp32_layer_norm: bool = True,
**kwargs: Any,
):... | hidden_states = self.dense(hidden_states)
hidden_states = self.transform_act_fn(hidden_states)
hidden_states = self.layer_norm(hidden_states)
hidden_states = self.decoder(hidden_states)
return hidden_states
| hidden_states = self.dense(hidden_states)
hidden_states = self.transform_act_fn(hidden_states)
hidden_states = self.layer_norm(hidden_states)
hidden_states = self.decoder(hidden_states)
return hidden_states
| 14 | 406 | 79 | 485 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import math
import warnings
from dataclasses import dataclass, field
from typing import Any, Callable, Optional... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import math
import warnings
from dataclasses import dataclass, field
from typing import Any, Callable, Optional... |
45,387 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/losses/flava.py | 206,209 | 182,241 | forward | MaskedPredictionLoss | 209,241 | 209,241 | class MaskedPredictionLoss(nn.Module):
def __init__(
self,
hidden_size: int = 768,
vocab_size: int = 30522,
transform_act_fn: Callable[[Tensor], Tensor] = nn.functional.gelu,
layer_norm_eps: float = 1e-5,
ignore_index: int = -1,
ignore_nan: bool = False,
... | class MaskedPredictionLoss(nn.Module):
def __init__(
self,
hidden_size: int = 768,
vocab_size: int = 30522,
transform_act_fn: Callable[[Tensor], Tensor] = nn.functional.gelu,
layer_norm_eps: float = 1e-5,
ignore_index: int = -1,
ignore_nan: bool = False,
... | if self.training:
assert_labels_are_present(masked_labels, "masked labels")
if masked_labels is not None:
masked_tokens = masked_labels.ne(self.ignore_index)
masked_labels = masked_labels[masked_tokens]
sequence_output = hidden_states[masked_tokens, :]
... | if self.training:
assert_labels_are_present(masked_labels, "masked labels")
if masked_labels is not None:
masked_tokens = masked_labels.ne(self.ignore_index)
masked_labels = masked_labels[masked_tokens]
sequence_output = hidden_states[masked_tokens, :]
... | 82 | 316 | 369 | 685 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import math
import warnings
from dataclasses import dataclass, field
from typing import Any, Callable, Optional... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import math
import warnings
from dataclasses import dataclass, field
from typing import Any, Callable, Optional... |
45,388 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/losses/flava.py | 91,92 | 84,100 | forward | Pooler | 92,100 | 92,100 | class Pooler(nn.Module):
def __init__(self, hidden_size: int = 768, **kwargs: Any):
super().__init__()
self.dense = nn.Linear(hidden_size, hidden_size)
self.activation = nn.Tanh()
def forward(self, hidden_states: Tensor) -> Tensor:
FILL_FUNC_BODY | class Pooler(nn.Module):
def __init__(self, hidden_size: int = 768, **kwargs: Any):
super().__init__()
self.dense = nn.Linear(hidden_size, hidden_size)
self.activation = nn.Tanh()
def forward(self, hidden_states: Tensor) -> Tensor:
FILL_FUNC_BODY | # We "pool" the model by simply taking the hidden state corresponding
# to the first token.
first_token_tensor = hidden_states[:, 0]
pooled_output = self.dense(first_token_tensor)
pooled_output = self.activation(pooled_output)
return pooled_output
| # We "pool" the model by simply taking the hidden state corresponding
# to the first token.
first_token_tensor = hidden_states[:, 0]
pooled_output = self.dense(first_token_tensor)
pooled_output = self.activation(pooled_output)
return pooled_output
| 29 | 105 | 92 | 197 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import math
import warnings
from dataclasses import dataclass, field
from typing import Any, Callable, Optional... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import math
import warnings
from dataclasses import dataclass, field
from typing import Any, Callable, Optional... |
45,389 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/losses/flava.py | 106,107 | 100,110 | forward | TwoWayHead | 107,110 | 107,110 | class TwoWayHead(nn.Module):
def __init__(self, hidden_size: int = 768, **kwargs: Any):
super().__init__()
self.seq_relationship = nn.Linear(hidden_size, 2)
def forward(self, pooled_output: Tensor) -> Tensor:
FILL_FUNC_BODY | class TwoWayHead(nn.Module):
def __init__(self, hidden_size: int = 768, **kwargs: Any):
super().__init__()
self.seq_relationship = nn.Linear(hidden_size, 2)
def forward(self, pooled_output: Tensor) -> Tensor:
FILL_FUNC_BODY | return self.seq_relationship(pooled_output)
| return self.seq_relationship(pooled_output)
| 2 | 95 | 20 | 115 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import math
import warnings
from dataclasses import dataclass, field
from typing import Any, Callable, Optional... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import math
import warnings
from dataclasses import dataclass, field
from typing import Any, Callable, Optional... |
45,391 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/losses/reconstruction_loss.py | 24,25 | 10,48 | forward | ReconstructionLoss | 34,48 | 25,48 | class ReconstructionLoss(nn.Module):
"""
Reconstruction loss that computed MSE between predicted and target values as described in MAE paper
https://arxiv.org/abs/2111.06377. Loss is averaged only over masked patches.
Args:
normalize_target (bool) : Whether target should be normalized. Defaults... | class ReconstructionLoss(nn.Module):
"""
Reconstruction loss that computed MSE between predicted and target values as described in MAE paper
https://arxiv.org/abs/2111.06377. Loss is averaged only over masked patches.
Args:
normalize_target (bool) : Whether target should be normalized. Defaults... | if mask.sum() == 0:
raise ValueError("At least one patch must be masked")
if self.normalize_target:
mean = target.mean(dim=-1, keepdim=True)
var = target.var(dim=-1, keepdim=True)
# pyre-fixme[58]: `**` is not supported for operand types `Tensor` and
... | """
Args:
pred (Tensor): predicted tensor with shape bsz x num_patches x (patch_size ** 2 * channels)
target (Tensor): patchified input with the same shape as pred
mask (Tensor): Tensor of shape bsz x num_patches indicating which patches are masked.
1 ind... | 74 | 283 | 217 | 500 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from torch import nn, Tensor
class ReconstructionLoss(nn.Module):
"""
Reconstruction loss that comput... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from torch import nn, Tensor
class ReconstructionLoss(nn.Module):
"""
Reconstruction loss that comput... |
45,392 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/losses/vqvae.py | 26,27 | 13,31 | forward | CommitmentLoss | 27,31 | 27,31 | class CommitmentLoss(nn.Module):
"""Commitment loss calculates the mean Euclidean distance between pairs of encoder output vectors
and their corresponding quantized vectors. It encourages an encoder to generate outputs closer to an embedding.
This is the beta in Eq. 3 of Oord et al. 2017 (https://arxiv.org/... | class CommitmentLoss(nn.Module):
"""Commitment loss calculates the mean Euclidean distance between pairs of encoder output vectors
and their corresponding quantized vectors. It encourages an encoder to generate outputs closer to an embedding.
This is the beta in Eq. 3 of Oord et al. 2017 (https://arxiv.org/... | # Quantized vectors must be detached because commitment loss only lets gradient flow through encoder output
loss = F.mse_loss(quantized.detach(), encoded) * self.commitment_cost
return loss
| # Quantized vectors must be detached because commitment loss only lets gradient flow through encoder output
loss = F.mse_loss(quantized.detach(), encoded) * self.commitment_cost
return loss
| 24 | 206 | 55 | 261 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any
from torch import nn, Tensor
from torch.nn import functional as F
class CommitmentLos... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any
from torch import nn, Tensor
from torch.nn import functional as F
class CommitmentLos... |
45,393 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/modules/masking/random_masking.py | 95,101 | 1,110 | _random_masking_1d | 101,110 | 101,110 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import NamedTuple, Tuple
import torch
from torch import Tensor
class RandomMaskingOutput(NamedT... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import NamedTuple, Tuple
import torch
from torch import Tensor
class RandomMaskingOutput(NamedT... | # x shape : bsz x h x w x embed_dim
n, _, _, d = x.shape
len_keep = int(num_patches_h * (1 - mask_ratio))
noise = torch.rand(n, num_patches_h, device=x.device)
ids_shuffle = torch.argsort(noise, dim=1)
ids_keep = ids_shuffle[:, :len_keep]
index = ids_keep.unsqueeze(-1).unsqueeze(-1).repeat(1... | # x shape : bsz x h x w x embed_dim
n, _, _, d = x.shape
len_keep = int(num_patches_h * (1 - mask_ratio))
noise = torch.rand(n, num_patches_h, device=x.device)
ids_shuffle = torch.argsort(noise, dim=1)
ids_keep = ids_shuffle[:, :len_keep]
index = ids_keep.unsqueeze(-1).unsqueeze(-1).repeat(1... | 51 | 1,149 | 194 | 1,343 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import NamedTuple, Tuple
import torch
from torch import Tensor
class RandomMaskingOutput(NamedT... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import NamedTuple, Tuple
import torch
from torch import Tensor
class RandomMaskingOutput(NamedT... | |
45,396 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/transforms/clip_transform.py | 144,145 | 84,205 | bpe | CLIPBPETokenizer | 145,185 | 145,185 | class CLIPBPETokenizer:
"""
Construct a CLIP tokenizer. Based on byte-level Byte-Pair-Encoding.
This implementation is adapted from https://git.io/JDTuJ.
Example usage:
tokenizer = CLIPBPETokenizer()
sentence = "Hello I am using CLIP tokenizer."
tokens = tokenizer.encode(sentence)
token... | class CLIPBPETokenizer:
"""
Construct a CLIP tokenizer. Based on byte-level Byte-Pair-Encoding.
This implementation is adapted from https://git.io/JDTuJ.
Example usage:
tokenizer = CLIPBPETokenizer()
sentence = "Hello I am using CLIP tokenizer."
tokens = tokenizer.encode(sentence)
token... | if token in self.cache:
return self.cache[token]
word = tuple(token[:-1]) + (token[-1] + "</w>",)
pairs = get_pairs(word)
if not pairs:
return token + "</w>"
while True:
bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf"... | if token in self.cache:
return self.cache[token]
word = tuple(token[:-1]) + (token[-1] + "</w>",)
pairs = get_pairs(word)
if not pairs:
return token + "</w>"
while True:
bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf"... | 118 | 1,223 | 402 | 1,625 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import html
from functools import lru_cache
from typing import Callable, Dict, List, Optional, Set, Tuple, Unio... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import html
from functools import lru_cache
from typing import Callable, Dict, List, Optional, Set, Tuple, Unio... |
45,397 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/transforms/clip_transform.py | 236,237 | 205,243 | forward | CLIPBPETransform | 237,243 | 237,243 | class CLIPBPETransform(nn.Module):
"""
nn.Module wrapper around CLIPBPETokenizer. Supports either a single string
or list of strings for tokenization.
Args:
bpe_path (Optional[str]): path to the BPE file.
Defaults to CLIP_DEFAULT_VOCAB_BPE_PATH
bos_token (Optional[str]): beg... | class CLIPBPETransform(nn.Module):
"""
nn.Module wrapper around CLIPBPETokenizer. Supports either a single string
or list of strings for tokenization.
Args:
bpe_path (Optional[str]): path to the BPE file.
Defaults to CLIP_DEFAULT_VOCAB_BPE_PATH
bos_token (Optional[str]): beg... | if isinstance(text, str):
return self.bpe.encode(text)
else:
return [self.bpe.encode(t) for t in text]
| if isinstance(text, str):
return self.bpe.encode(text)
else:
return [self.bpe.encode(t) for t in text]
| 12 | 400 | 52 | 452 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import html
from functools import lru_cache
from typing import Callable, Dict, List, Optional, Set, Tuple, Unio... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import html
from functools import lru_cache
from typing import Callable, Dict, List, Optional, Set, Tuple, Unio... |
45,398 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/transforms/clip_transform.py | 350,351 | 303,357 | forward | CLIPImageTransform | 351,357 | 351,357 | class CLIPImageTransform(nn.Module):
"""CLIP image transform
random resized crop (train mode) or resize and center crop, followed by RGB conversion, tensor conversion, and normalization.
Args:
image_size (Union[int, Tuple[int]): desired output image size.
image_interpolation (torchvision.tr... | class CLIPImageTransform(nn.Module):
"""CLIP image transform
random resized crop (train mode) or resize and center crop, followed by RGB conversion, tensor conversion, and normalization.
Args:
image_size (Union[int, Tuple[int]): desired output image size.
image_interpolation (torchvision.tr... | if isinstance(image, Image):
return self.image_transform(image)
image_result = torch.stack([self.image_transform(x) for x in image])
return image_result
| if isinstance(image, Image):
return self.image_transform(image)
image_result = torch.stack([self.image_transform(x) for x in image])
return image_result
| 14 | 563 | 59 | 622 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import html
from functools import lru_cache
from typing import Callable, Dict, List, Optional, Set, Tuple, Unio... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import html
from functools import lru_cache
from typing import Callable, Dict, List, Optional, Set, Tuple, Unio... |
45,399 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/transforms/clip_transform.py | 297,298 | 243,303 | forward | CLIPTextTransform | 298,303 | 298,303 | class CLIPTextTransform(nn.Module):
"""CLIP text transform
CLIP BPE tokenizer transform, adds start and end tokens, then pads/truncates to text_max_length as necessary.
This transform is torch scriptable.
Args:
text_max_length (int): Maximum length of text token sequences.
text_start_tok... | class CLIPTextTransform(nn.Module):
"""CLIP text transform
CLIP BPE tokenizer transform, adds start and end tokens, then pads/truncates to text_max_length as necessary.
This transform is torch scriptable.
Args:
text_max_length (int): Maximum length of text token sequences.
text_start_tok... | text_result = self.text_transform(text)
assert torch.jit.isinstance(text_result, Tensor)
return text_result
| text_result = self.text_transform(text)
assert torch.jit.isinstance(text_result, Tensor)
return text_result
| 8 | 764 | 46 | 810 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import html
from functools import lru_cache
from typing import Callable, Dict, List, Optional, Set, Tuple, Unio... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import html
from functools import lru_cache
from typing import Callable, Dict, List, Optional, Set, Tuple, Unio... |
45,400 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/transforms/clip_transform.py | 416,419 | 357,420 | forward | CLIPTransform | 419,420 | 419,420 | class CLIPTransform(nn.Module):
"""Image and text transform for CLIP model.
Image transform: either random resized crop (train mode) or resize and center
crop, followed by RGB conversion, tensor conversion, and normalization.
Text transform: applies CLIP's BPE tokenizer transform, adds start and en... | class CLIPTransform(nn.Module):
"""Image and text transform for CLIP model.
Image transform: either random resized crop (train mode) or resize and center
crop, followed by RGB conversion, tensor conversion, and normalization.
Text transform: applies CLIP's BPE tokenizer transform, adds start and en... | return self.image_transform(image), self.text_transform(text)
| return self.image_transform(image), self.text_transform(text)
| 3 | 864 | 20 | 884 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import html
from functools import lru_cache
from typing import Callable, Dict, List, Optional, Set, Tuple, Unio... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import html
from functools import lru_cache
from typing import Callable, Dict, List, Optional, Set, Tuple, Unio... |
45,402 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/transforms/text_transforms.py | 49,50 | 35,58 | forward | AddToken | 54,58 | 50,58 | class AddToken(nn.Module):
"""Add token to beginning or end of sequence
:param token: The token to be added
:type token: Union[int, str]
:param begin: Whether to insert token at start or end or sequence, defaults to True
:type begin: bool, optional
"""
def __init__(self, token: Union[int, ... | class AddToken(nn.Module):
"""Add token to beginning or end of sequence
:param token: The token to be added
:type token: Union[int, str]
:param begin: Whether to insert token at start or end or sequence, defaults to True
:type begin: bool, optional
"""
def __init__(self, token: Union[int, ... |
return add_token(input, self.token, self.begin)
| """
:param input: Input sequence or batch
:type input: Union[List[Union[str, int]], List[List[Union[str, int]]]]
"""
return add_token(input, self.token, self.begin)
| 4 | 197 | 24 | 221 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any, List, Optional, Union
import torch
from torch import nn, Tensor
from torch.nn.utils.rn... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any, List, Optional, Union
import torch
from torch import nn, Tensor
from torch.nn.utils.rn... |
45,403 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/transforms/text_transforms.py | 72,73 | 58,86 | forward | PadTransform | 79,86 | 73,86 | class PadTransform(nn.Module):
"""Pad tensor to a fixed length with given padding value.
:param max_length: Maximum length to pad to
:type max_length: int
:param pad_value: Value to pad the tensor with
:type pad_value: bool
"""
def __init__(self, max_length: int, pad_value: int) -> None:
... | class PadTransform(nn.Module):
"""Pad tensor to a fixed length with given padding value.
:param max_length: Maximum length to pad to
:type max_length: int
:param pad_value: Value to pad the tensor with
:type pad_value: bool
"""
def __init__(self, max_length: int, pad_value: int) -> None:
... | max_encoded_length = x.size(-1)
if max_encoded_length < self.max_length:
pad_amount = self.max_length - max_encoded_length
x = torch.nn.functional.pad(x, (0, pad_amount), value=self.pad_value)
return x
| """
:param x: The tensor to pad
:type x: Tensor
:return: Tensor padded up to max_length with pad_value
:rtype: Tensor
"""
max_encoded_length = x.size(-1)
if max_encoded_length < self.max_length:
pad_amount = self.max_length - max_encoded_length... | 20 | 209 | 93 | 302 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any, List, Optional, Union
import torch
from torch import nn, Tensor
from torch.nn.utils.rn... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any, List, Optional, Union
import torch
from torch import nn, Tensor
from torch.nn.utils.rn... |
45,404 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/transforms/text_transforms.py | 102,103 | 86,111 | forward | ToTensor | 108,111 | 103,111 | class ToTensor(nn.Module):
r"""Convert input to torch tensor
:param padding_value: Pad value to make each input in the batch of length equal to the longest sequence in the batch.
:type padding_value: Optional[int]
:param dtype: :class:`torch.dtype` of output tensor
:type dtype: :class:`torch.dtype`... | class ToTensor(nn.Module):
r"""Convert input to torch tensor
:param padding_value: Pad value to make each input in the batch of length equal to the longest sequence in the batch.
:type padding_value: Optional[int]
:param dtype: :class:`torch.dtype` of output tensor
:type dtype: :class:`torch.dtype`... | return to_tensor(input, padding_value=self.padding_value, dtype=self.dtype)
| """
:param input: Sequence or batch of token ids
:type input: Union[List[int], List[List[int]]]
:rtype: Tensor
"""
return to_tensor(input, padding_value=self.padding_value, dtype=self.dtype)
| 4 | 245 | 32 | 277 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any, List, Optional, Union
import torch
from torch import nn, Tensor
from torch.nn.utils.rn... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any, List, Optional, Union
import torch
from torch import nn, Tensor
from torch.nn.utils.rn... |
45,405 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/transforms/text_transforms.py | 25,26 | 14,35 | forward | Truncate | 32,35 | 26,35 | class Truncate(nn.Module):
r"""Truncate input sequence
:param max_seq_len: The maximum allowable length for input sequence
:type max_seq_len: int
"""
def __init__(self, max_seq_len: int) -> None:
super().__init__()
self.max_seq_len = max_seq_len
def forward(self, x: Any) -> An... | class Truncate(nn.Module):
r"""Truncate input sequence
:param max_seq_len: The maximum allowable length for input sequence
:type max_seq_len: int
"""
def __init__(self, max_seq_len: int) -> None:
super().__init__()
self.max_seq_len = max_seq_len
def forward(self, x: Any) -> An... | return truncate(x, self.max_seq_len)
| """
:param input: Input sequence or batch of sequence to be truncated
:type input: Union[List[Union[str, int]], List[List[Union[str, int]]]]
:return: Truncated sequence
:rtype: Union[List[Union[str, int]], List[List[Union[str, int]]]]
"""
return truncate(x, self.m... | 3 | 213 | 21 | 234 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any, List, Optional, Union
import torch
from torch import nn, Tensor
from torch.nn.utils.rn... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any, List, Optional, Union
import torch
from torch import nn, Tensor
from torch.nn.utils.rn... |
45,406 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/transforms/video_transform.py | 85,86 | 21,97 | normalize | VideoTransform | 87,97 | 86,97 | class VideoTransform:
"""Transform videos for encoding
Args:
time_samples (int): number of frames to sample in the time dimension
mean (Tuple[float, float, float]): sequence of means of each channel
std (Tuple[float, float, float]): sequence of standard deviations of each channel
... | class VideoTransform:
"""Transform videos for encoding
Args:
time_samples (int): number of frames to sample in the time dimension
mean (Tuple[float, float, float]): sequence of means of each channel
std (Tuple[float, float, float]): sequence of standard deviations of each channel
... | b, t, _, _, _ = video.shape
video = video.flatten(start_dim=0, end_dim=1) # "b t h w c -> (b t) h w c"
video = shift_dim(video, -1, 1) # "(b t) h w c -> (b t) c h w"
video = video.float() / 255.0
video = normalize(video, mean=self.mean, std=self.std)
video = video.unf... | """Normalizes video of dims (b, t, h, w, c) to mean 0, std 1"""
b, t, _, _, _ = video.shape
video = video.flatten(start_dim=0, end_dim=1) # "b t h w c -> (b t) h w c"
video = shift_dim(video, -1, 1) # "(b t) h w c -> (b t) c h w"
video = video.float() / 255.0
video = n... | 86 | 899 | 211 | 1,110 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Tuple
import torch
import torch.nn.functional as F
from torchmultimodal.utils.common import... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Tuple
import torch
import torch.nn.functional as F
from torchmultimodal.utils.common import... |
45,407 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/utils/assertion.py | 10,13 | 1,18 | assert_equal_lengths | 13,18 | 13,18 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Sized
def assert_equal_lengths(
*args: Sized, msg: str = "iterable arguments must have... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Sized
def assert_equal_lengths(
*args: Sized, msg: str = "iterable arguments must have... | lengths = set()
for item in args:
lengths.add(len(item))
if len(lengths) != 1:
raise ValueError(msg)
| lengths = set()
for item in args:
lengths.add(len(item))
if len(lengths) != 1:
raise ValueError(msg)
| 14 | 112 | 48 | 160 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Sized
def assert_equal_lengths(
*args: Sized, msg: str = "iterable arguments must have... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Sized
def assert_equal_lengths(
*args: Sized, msg: str = "iterable arguments must have... | |
45,408 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/utils/attention.py | 13,14 | 1,66 | get_extended_attention_mask | 30,56 | 14,56 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Optional
import torch
from torch import Tensor
def get_extended_attention_mask(attention_... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Optional
import torch
from torch import Tensor
def get_extended_attention_mask(attention_... | if attention_mask.dim() == 4:
# Mask has already been broadcasted to the correct shape (either
# [batch_size, num_heads, query_seq_length, key_seq_length] for causal case or
# [batch_size, num_heads, seq_length, seq_length] for padding case)
extended_attention_mask = attention_mask
... | """Makes attention masks broadcastable along head and sequence dimensions.
Accepting two types of attention masks:
- Causal: masks that prevent attending to future positions of dimensions
``(batch_size, query_seq_len, key_seq_len)``
- Padding: masks that prevent attending to token p... | 132 | 410 | 399 | 809 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Optional
import torch
from torch import Tensor
def get_extended_attention_mask(attention_... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Optional
import torch
from torch import Tensor
def get_extended_attention_mask(attention_... | |
45,409 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/utils/distributed.py | 61,66 | 1,91 | concat_gather_all_gpu | 78,86 | 66,86 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from enum import Enum
from typing import List
import torch
from torch import Tensor
from torch.distributed imp... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from enum import Enum
from typing import List
import torch
from torch import Tensor
from torch.distributed imp... | if not torch.distributed.is_available() or not torch.distributed.is_initialized():
return tensor
tensors_all_gpus = gather_tensor(tensor, backprop_type)
return torch.cat(tensors_all_gpus, dim=dim)
| """Gathers a tensor across all GPUs.
Inputs:
tensor (Tensor): Tensors that need to be gathered.
backprop_type (BackpropType): whether to backpropagate gradients to all
workers (GLOBAL), just the local worker (LOCAL), or not at all (NONE).
Default: BackpropType.GLOBAL
... | 15 | 848 | 85 | 933 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from enum import Enum
from typing import List
import torch
from torch import Tensor
from torch.distributed imp... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from enum import Enum
from typing import List
import torch
from torch import Tensor
from torch.distributed imp... | |
45,410 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/utils/file_io.py | 10,11 | 1,21 | _get_path_manager | 11,21 | 11,21 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from iopath.common.file_io import HTTPURLHandler, PathManager
def _get_path_manager() -> PathManager:
FILL_FU... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from iopath.common.file_io import HTTPURLHandler, PathManager
def _get_path_manager() -> PathManager:
FILL_FU... | try:
from torchmultimodal.fb.utils.file_io import FBPathManager, register_handlers
pm = FBPathManager()
register_handlers(pm)
return pm
except ImportError:
pm = PathManager()
pm.register_handler(HTTPURLHandler())
return pm
| try:
from torchmultimodal.fb.utils.file_io import FBPathManager, register_handlers
pm = FBPathManager()
register_handlers(pm)
return pm
except ImportError:
pm = PathManager()
pm.register_handler(HTTPURLHandler())
return pm
| 20 | 102 | 93 | 195 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from iopath.common.file_io import HTTPURLHandler, PathManager
def _get_path_manager() -> PathManager:
FILL_FU... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from iopath.common.file_io import HTTPURLHandler, PathManager
def _get_path_manager() -> PathManager:
FILL_FU... | |
45,415 | /home/hieuvd/dung_repo/raw/stars_03/flow-project_flow/flow | /home/hieuvd/dung_repo/raw/stars_03/flow-project_flow/flow/examples/simulate.py | 16,17 | 1,94 | parse_args | 24,56 | 17,56 | """Runner script for non-RL simulations in flow.
Usage
python simulate.py EXP_CONFIG --no_render
"""
import argparse
import sys
import json
import os
from flow.core.experiment import Experiment
from flow.core.params import AimsunParams
from flow.utils.rllib import FlowParamsEncoder
def parse_args(args):
FILL_FU... | """Runner script for non-RL simulations in flow.
Usage
python simulate.py EXP_CONFIG --no_render
"""
import argparse
import sys
import json
import os
from flow.core.experiment import Experiment
from flow.core.params import AimsunParams
from flow.utils.rllib import FlowParamsEncoder
def parse_args(args):
"""... | parser = argparse.ArgumentParser(
description="Parse argument used when running a Flow simulation.",
epilog="python simulate.py EXP_CONFIG --num_runs INT --no_render")
# required input parameters
parser.add_argument(
'exp_config', type=str,
help='Name of the experiment confi... | """Parse training options user can specify in command line.
Returns
-------
argparse.Namespace
the output parser object
"""
parser = argparse.ArgumentParser(
description="Parse argument used when running a Flow simulation.",
epilog="python simulate.py EXP_CONFIG --num_ru... | 100 | 613 | 356 | 969 | """Runner script for non-RL simulations in flow.
Usage
python simulate.py EXP_CONFIG --no_render
"""
import argparse
import sys
import json
import os
from flow.core.experiment import Experiment
from flow.core.params import AimsunParams
from flow.utils.rllib import FlowParamsEncoder
def parse_args(args):
FILL_FU... | """Runner script for non-RL simulations in flow.
Usage
python simulate.py EXP_CONFIG --no_render
"""
import argparse
import sys
import json
import os
from flow.core.experiment import Experiment
from flow.core.params import AimsunParams
from flow.utils.rllib import FlowParamsEncoder
def parse_args(args):
"""... | |
45,416 | /home/hieuvd/dung_repo/raw/stars_03/flow-project_flow/flow | /home/hieuvd/dung_repo/raw/stars_03/flow-project_flow/flow/flow/controllers/base_lane_changing_controller.py | 63,64 | 6,82 | get_action | BaseLaneChangeController | 78,82 | 64,82 | class BaseLaneChangeController(metaclass=ABCMeta):
"""Base class for lane-changing controllers.
Instantiates a controller and forces the user to pass a
lane_changing duration to the controller.
Usage
-----
>>> from flow.core.params import VehicleParams
>>> from flow.controllers import SimL... | class BaseLaneChangeController(metaclass=ABCMeta):
"""Base class for lane-changing controllers.
Instantiates a controller and forces the user to pass a
lane_changing duration to the controller.
Usage
-----
>>> from flow.core.params import VehicleParams
>>> from flow.controllers import SimL... | lc_action = self.get_lane_change_action(env)
# TODO(ak): add failsafe
return lc_action
| """Return the action of the lane change controller.
Modifies the lane change action to ensure safety, if requested.
Parameters
----------
env : flow.envs.Env
state of the environment at the current time step
Returns
-------
float or int
... | 9 | 553 | 42 | 595 | """Contains the base lane change controller class."""
from abc import ABCMeta, abstractmethod
class BaseLaneChangeController(metaclass=ABCMeta):
"""Base class for lane-changing controllers.
Instantiates a controller and forces the user to pass a
lane_changing duration to the controller.
Usage
-... | """Contains the base lane change controller class."""
from abc import ABCMeta, abstractmethod
class BaseLaneChangeController(metaclass=ABCMeta):
"""Base class for lane-changing controllers.
Instantiates a controller and forces the user to pass a
lane_changing duration to the controller.
Usage
-... |
45,417 | /home/hieuvd/dung_repo/raw/stars_03/flow-project_flow/flow | /home/hieuvd/dung_repo/raw/stars_03/flow-project_flow/flow/flow/controllers/lane_change_controllers.py | 13,14 | 7,18 | get_lane_change_action | SimLaneChangeController | 15,18 | 14,18 | class SimLaneChangeController(BaseLaneChangeController):
"""A controller used to enforce sumo lane-change dynamics on a vehicle.
Usage: See base class for usage example.
"""
def get_lane_change_action(self, env):
FILL_FUNC_BODY | class SimLaneChangeController(BaseLaneChangeController):
"""A controller used to enforce sumo lane-change dynamics on a vehicle.
Usage: See base class for usage example.
"""
def get_lane_change_action(self, env):
"""See parent class."""
FILL_FUNC_BODY | return None
| """See parent class."""
return None
| 2 | 82 | 9 | 91 | """Contains a list of custom lane change controllers."""
from flow.controllers.base_lane_changing_controller import \
BaseLaneChangeController
class SimLaneChangeController(BaseLaneChangeController):
"""A controller used to enforce sumo lane-change dynamics on a vehicle.
Usage: See base class for usage ... | """Contains a list of custom lane change controllers."""
from flow.controllers.base_lane_changing_controller import \
BaseLaneChangeController
class SimLaneChangeController(BaseLaneChangeController):
"""A controller used to enforce sumo lane-change dynamics on a vehicle.
Usage: See base class for usage ... |
45,418 | /home/hieuvd/dung_repo/raw/stars_03/flow-project_flow/flow | /home/hieuvd/dung_repo/raw/stars_03/flow-project_flow/flow/flow/controllers/lane_change_controllers.py | 24,25 | 18,27 | get_lane_change_action | StaticLaneChanger | 26,27 | 25,27 | class StaticLaneChanger(BaseLaneChangeController):
"""A lane-changing model used to keep a vehicle in the same lane.
Usage: See base class for usage example.
"""
def get_lane_change_action(self, env):
FILL_FUNC_BODY | class StaticLaneChanger(BaseLaneChangeController):
"""A lane-changing model used to keep a vehicle in the same lane.
Usage: See base class for usage example.
"""
def get_lane_change_action(self, env):
"""See parent class."""
FILL_FUNC_BODY | return 0
| """See parent class."""
return 0
| 2 | 83 | 6 | 89 | """Contains a list of custom lane change controllers."""
from flow.controllers.base_lane_changing_controller import \
BaseLaneChangeController
class SimLaneChangeController(BaseLaneChangeController):
"""A controller used to enforce sumo lane-change dynamics on a vehicle.
Usage: See base class for usage ... | """Contains a list of custom lane change controllers."""
from flow.controllers.base_lane_changing_controller import \
BaseLaneChangeController
class SimLaneChangeController(BaseLaneChangeController):
"""A controller used to enforce sumo lane-change dynamics on a vehicle.
Usage: See base class for usage ... |
45,419 | /home/hieuvd/dung_repo/raw/stars_03/flow-project_flow/flow | /home/hieuvd/dung_repo/raw/stars_03/flow-project_flow/flow/flow/core/kernel/simulation/aimsun.py | 115,116 | 9,132 | close | AimsunKernelSimulation | 117,132 | 116,132 | class AimsunKernelSimulation(KernelSimulation):
"""Aimsun simulation kernel.
Extends KernelSimulation.
Attributes
----------
master_kernel : flow.core.kernel.Kernel
the higher level kernel (used to call methods from other sub-kernels)
kernel_api : any
an API that may be used to... | class AimsunKernelSimulation(KernelSimulation):
"""Aimsun simulation kernel.
Extends KernelSimulation.
Attributes
----------
master_kernel : flow.core.kernel.Kernel
the higher level kernel (used to call methods from other sub-kernels)
kernel_api : any
an API that may be used to... | # save the emission data to a csv
if self.emission_path is not None:
name = "%s_emission.csv" % self.master_kernel.network.network.name
with open(osp.join(self.emission_path, name), "w") as f:
writer = csv.writer(f, delimiter=',')
writer.writerow(s... | """See parent class."""
# save the emission data to a csv
if self.emission_path is not None:
name = "%s_emission.csv" % self.master_kernel.network.network.name
with open(osp.join(self.emission_path, name), "w") as f:
writer = csv.writer(f, delimiter=',')
... | 54 | 1,023 | 208 | 1,231 | """Script containing the base simulation kernel class."""
from flow.core.kernel.simulation.base import KernelSimulation
from flow.utils.aimsun.api import FlowAimsunAPI
import os.path as osp
import csv
from flow.core.util import ensure_dir
class AimsunKernelSimulation(KernelSimulation):
"""Aimsun simulation kernel... | """Script containing the base simulation kernel class."""
from flow.core.kernel.simulation.base import KernelSimulation
from flow.utils.aimsun.api import FlowAimsunAPI
import os.path as osp
import csv
from flow.core.util import ensure_dir
class AimsunKernelSimulation(KernelSimulation):
"""Aimsun simulation kernel... |
45,420 | /home/hieuvd/dung_repo/raw/stars_03/flow-project_flow/flow | /home/hieuvd/dung_repo/raw/stars_03/flow-project_flow/flow/flow/core/kernel/simulation/base.py | 52,53 | 4,86 | simulation_step | KernelSimulation | 57,59 | 53,59 | class KernelSimulation(object):
"""Base simulation kernel.
The simulation kernel is responsible for generating the simulation and
passing to all other kernel the API that they can use to interact with the
simulation.
The simulation kernel is also responsible for advancing, resetting, and
stori... | class KernelSimulation(object):
"""Base simulation kernel.
The simulation kernel is responsible for generating the simulation and
passing to all other kernel the API that they can use to interact with the
simulation.
The simulation kernel is also responsible for advancing, resetting, and
stori... | raise NotImplementedError
| """Advance the simulation by one step.
This is done in most cases by calling a relevant simulator API method.
"""
raise NotImplementedError
| 2 | 593 | 11 | 604 | """Script containing the base simulation kernel class."""
class KernelSimulation(object):
"""Base simulation kernel.
The simulation kernel is responsible for generating the simulation and
passing to all other kernel the API that they can use to interact with the
simulation.
The simulation kernel... | """Script containing the base simulation kernel class."""
class KernelSimulation(object):
"""Base simulation kernel.
The simulation kernel is responsible for generating the simulation and
passing to all other kernel the API that they can use to interact with the
simulation.
The simulation kernel... |
45,421 | /home/hieuvd/dung_repo/raw/stars_03/flow-project_flow/flow | /home/hieuvd/dung_repo/raw/stars_03/flow-project_flow/flow/flow/core/kernel/traffic_light/aimsun.py | 56,57 | 5,73 | get_state | AimsunKernelTrafficLight | 72,73 | 57,73 | class AimsunKernelTrafficLight(KernelTrafficLight):
"""Aimsun traffic light kernel.
Implements all methods discussed in the base traffic light kernel class.
"""
def __init__(self, master_kernel):
"""Instantiate the sumo traffic light kernel.
Parameters
----------
maste... | class AimsunKernelTrafficLight(KernelTrafficLight):
"""Aimsun traffic light kernel.
Implements all methods discussed in the base traffic light kernel class.
"""
def __init__(self, master_kernel):
"""Instantiate the sumo traffic light kernel.
Parameters
----------
maste... | return self.kernel_api.get_traffic_light_state(meter_aimsun_id)
| """Return the state of the traffic light(s) at the specified node.
Parameters
----------
meter_aimsun_id: int
aimsun id of the meter
Returns
-------
state : int
desired state(s) for the traffic light
0: red
1: gree... | 2 | 522 | 26 | 548 | """Script containing the base traffic light kernel class."""
from flow.core.kernel.traffic_light.base import KernelTrafficLight
class AimsunKernelTrafficLight(KernelTrafficLight):
"""Aimsun traffic light kernel.
Implements all methods discussed in the base traffic light kernel class.
"""
def __init_... | """Script containing the base traffic light kernel class."""
from flow.core.kernel.traffic_light.base import KernelTrafficLight
class AimsunKernelTrafficLight(KernelTrafficLight):
"""Aimsun traffic light kernel.
Implements all methods discussed in the base traffic light kernel class.
"""
def __init_... |
45,422 | /home/hieuvd/dung_repo/raw/stars_03/flow-project_flow/flow | /home/hieuvd/dung_repo/raw/stars_03/flow-project_flow/flow/flow/core/kernel/traffic_light/base.py | 53,54 | 4,101 | update | KernelTrafficLight | 65,67 | 54,67 | class KernelTrafficLight(object):
"""Base traffic light kernel.
This kernel sub-class is used to interact with the simulator with regards
to all traffic light -dependent components. Specifically, this class
contains methods for:
* Interacting with the simulator: This consisting specifying the stat... | class KernelTrafficLight(object):
"""Base traffic light kernel.
This kernel sub-class is used to interact with the simulator with regards
to all traffic light -dependent components. Specifically, this class
contains methods for:
* Interacting with the simulator: This consisting specifying the stat... | raise NotImplementedError
| """Update the states and phases of the traffic lights.
This ensures that the traffic light variables match current traffic
light data.
Parameters
----------
reset : bool
specifies whether the simulator was reset in the last simulation
step
... | 2 | 793 | 11 | 804 | """Script containing the base traffic light kernel class."""
class KernelTrafficLight(object):
"""Base traffic light kernel.
This kernel sub-class is used to interact with the simulator with regards
to all traffic light -dependent components. Specifically, this class
contains methods for:
* Inte... | """Script containing the base traffic light kernel class."""
class KernelTrafficLight(object):
"""Base traffic light kernel.
This kernel sub-class is used to interact with the simulator with regards
to all traffic light -dependent components. Specifically, this class
contains methods for:
* Inte... |
45,424 | /home/hieuvd/dung_repo/raw/stars_03/flow-project_flow/flow | /home/hieuvd/dung_repo/raw/stars_03/flow-project_flow/flow/flow/core/params.py | 678,679 | 629,683 | get_additional_param | EnvParams | 680,683 | 679,683 | class EnvParams:
"""Environment and experiment-specific parameters.
This includes specifying the bounds of the action space and relevant
coefficients to the reward function, as well as specifying how the
positions of vehicles are modified in between rollouts.
Attributes
----------
addition... | class EnvParams:
"""Environment and experiment-specific parameters.
This includes specifying the bounds of the action space and relevant
coefficients to the reward function, as well as specifying how the
positions of vehicles are modified in between rollouts.
Attributes
----------
addition... | return self.additional_params[key]
| """Return a variable from additional_params."""
return self.additional_params[key]
| 2 | 498 | 17 | 515 | """Objects that define the various meta-parameters of an experiment."""
import logging
import collections
from flow.utils.flow_warnings import deprecated_attribute
from flow.controllers.car_following_models import SimCarFollowingController
from flow.controllers.rlcontroller import RLController
from flow.controllers.l... | """Objects that define the various meta-parameters of an experiment."""
import logging
import collections
from flow.utils.flow_warnings import deprecated_attribute
from flow.controllers.car_following_models import SimCarFollowingController
from flow.controllers.rlcontroller import RLController
from flow.controllers.l... |
45,425 | /home/hieuvd/dung_repo/raw/stars_03/flow-project_flow/flow | /home/hieuvd/dung_repo/raw/stars_03/flow-project_flow/flow/flow/core/params.py | 1146,1159 | 1136,1284 | add | InFlows | 1159,1281 | 1159,1281 | class InFlows:
"""Used to add inflows to a network.
Inflows can be specified for any edge that has a specified route or routes.
"""
def __init__(self):
"""Instantiate Inflows."""
self.__flows = []
def add(self,
edge,
veh_type,
vehs_per_hour=None... | class InFlows:
"""Used to add inflows to a network.
Inflows can be specified for any edge that has a specified route or routes.
"""
def __init__(self):
"""Instantiate Inflows."""
self.__flows = []
def add(self,
edge,
veh_type,
vehs_per_hour=None... | r"""Specify a new inflow for a given type of vehicles and edge.
Parameters
----------
edge : str
starting edge for the vehicles in this inflow
veh_type : str
type of the vehicles entering the edge. Must match one of the types
set in the Vehicl... | r"""Specify a new inflow for a given type of vehicles and edge.
Parameters
----------
edge : str
starting edge for the vehicles in this inflow
veh_type : str
type of the vehicles entering the edge. Must match one of the types
set in the Vehicl... | 643 | 198 | 1,519 | 1,717 | """Objects that define the various meta-parameters of an experiment."""
import logging
import collections
from flow.utils.flow_warnings import deprecated_attribute
from flow.controllers.car_following_models import SimCarFollowingController
from flow.controllers.rlcontroller import RLController
from flow.controllers.l... | """Objects that define the various meta-parameters of an experiment."""
import logging
import collections
from flow.utils.flow_warnings import deprecated_attribute
from flow.controllers.car_following_models import SimCarFollowingController
from flow.controllers.rlcontroller import RLController
from flow.controllers.l... |
45,426 | /home/hieuvd/dung_repo/raw/stars_03/flow-project_flow/flow | /home/hieuvd/dung_repo/raw/stars_03/flow-project_flow/flow/flow/core/params.py | 70,81 | 49,219 | add | TrafficLightParams | 135,163 | 81,163 | class TrafficLightParams:
"""Base traffic light.
This class is used to place traffic lights in the network and describe
the state of these traffic lights. In addition, this class supports
modifying the states of certain lights via TraCI.
"""
def __init__(self, baseline=False):
"""Insta... | class TrafficLightParams:
"""Base traffic light.
This class is used to place traffic lights in the network and describe
the state of these traffic lights. In addition, this class supports
modifying the states of certain lights via TraCI.
"""
def __init__(self, baseline=False):
"""Insta... | # prepare the data needed to generate xml files
self.__tls_properties[node_id] = {"id": node_id, "type": tls_type}
if programID:
self.__tls_properties[node_id]["programID"] = programID
if offset:
self.__tls_properties[node_id]["offset"] = offset
if phas... | """Add a traffic light component to the network.
When generating networks using xml files, using this method to add a
traffic light will explicitly place the traffic light in the requested
node of the generated network.
If traffic lights are not added here but are already prese... | 74 | 1,202 | 334 | 1,536 | """Objects that define the various meta-parameters of an experiment."""
import logging
import collections
from flow.utils.flow_warnings import deprecated_attribute
from flow.controllers.car_following_models import SimCarFollowingController
from flow.controllers.rlcontroller import RLController
from flow.controllers.l... | """Objects that define the various meta-parameters of an experiment."""
import logging
import collections
from flow.utils.flow_warnings import deprecated_attribute
from flow.controllers.car_following_models import SimCarFollowingController
from flow.controllers.rlcontroller import RLController
from flow.controllers.l... |
45,427 | /home/hieuvd/dung_repo/raw/stars_03/flow-project_flow/flow | /home/hieuvd/dung_repo/raw/stars_03/flow-project_flow/flow/flow/core/params.py | 256,266 | 219,377 | add | VehicleParams | 293,366 | 266,366 | class VehicleParams:
"""Base vehicle class.
This is used to describe the state of all vehicles in the network.
State information on the vehicles for a given time step can be set or
retrieved from this class.
"""
def __init__(self):
"""Instantiate the base vehicle class."""
self... | class VehicleParams:
"""Base vehicle class.
This is used to describe the state of all vehicles in the network.
State information on the vehicles for a given time step can be set or
retrieved from this class.
"""
def __init__(self):
"""Instantiate the base vehicle class."""
self... | if car_following_params is None:
# FIXME: depends on simulator
car_following_params = SumoCarFollowingParams()
if lane_change_params is None:
# FIXME: depends on simulator
lane_change_params = SumoLaneChangeParams()
type_params = {}
type_... | """Add a sequence of vehicles to the list of vehicles in the network.
Parameters
----------
veh_id : str
base vehicle ID for the vehicles (will be appended by a number)
acceleration_controller : tup, optional
1st element: flow-specified acceleration contr... | 210 | 822 | 780 | 1,602 | """Objects that define the various meta-parameters of an experiment."""
import logging
import collections
from flow.utils.flow_warnings import deprecated_attribute
from flow.controllers.car_following_models import SimCarFollowingController
from flow.controllers.rlcontroller import RLController
from flow.controllers.l... | """Objects that define the various meta-parameters of an experiment."""
import logging
import collections
from flow.utils.flow_warnings import deprecated_attribute
from flow.controllers.car_following_models import SimCarFollowingController
from flow.controllers.rlcontroller import RLController
from flow.controllers.l... |
45,429 | /home/hieuvd/dung_repo/raw/stars_03/flow-project_flow/flow | /home/hieuvd/dung_repo/raw/stars_03/flow-project_flow/flow/flow/networks/bay_bridge_toll.py | 55,56 | 32,98 | specify_routes | BayBridgeTollNetwork | 61,98 | 56,98 | class BayBridgeTollNetwork(Network):
"""A network used to simulate the bottleneck portion of the Bay Bridge.
The bay bridge was originally imported from OpenStreetMap and subsequently
modified to more closely match the network geometry of the actual Bay
Bridge. As opposed to BayBridgeNetwork, this netw... | class BayBridgeTollNetwork(Network):
"""A network used to simulate the bottleneck portion of the Bay Bridge.
The bay bridge was originally imported from OpenStreetMap and subsequently
modified to more closely match the network geometry of the actual Bay
Bridge. As opposed to BayBridgeNetwork, this netw... | rts = {
"11198593": ["11198593", "11198595.0"],
"157598960": ["157598960", "11198595.0"],
"11198595.0": ["11198595.0", "11198595.656.0"],
"11198595.656.0": ["11198595.656.0", "gneE5"],
"gneE5": ["gneE5", "340686911#2.0.13"],
"124952171": ["... | """See parent class.
Routes for vehicles moving through the bay bridge from Oakland to San
Francisco.
"""
rts = {
"11198593": ["11198593", "11198595.0"],
"157598960": ["157598960", "11198595.0"],
"11198595.0": ["11198595.0", "11198595.656.0"],... | 95 | 279 | 1,321 | 1,600 | """Contains the Bay Bridge toll network class."""
from flow.networks.base import Network
# Use this to ensure that vehicles are only placed in the edges of the Bay
# Bridge moving from Oakland to San Francisco.
EDGES_DISTRIBUTION = [
'157598960',
'11198599',
'11198595.0',
'11198595.656.0',
'124952... | """Contains the Bay Bridge toll network class."""
from flow.networks.base import Network
# Use this to ensure that vehicles are only placed in the edges of the Bay
# Bridge moving from Oakland to San Francisco.
EDGES_DISTRIBUTION = [
'157598960',
'11198599',
'11198595.0',
'11198595.656.0',
'124952... |
45,432 | /home/hieuvd/dung_repo/raw/stars_03/flow-project_flow/flow | /home/hieuvd/dung_repo/raw/stars_03/flow-project_flow/flow/flow/utils/flow_warnings.py | 30,31 | 1,106 | deprecated | 36,106 | 31,106 | """Warnings that may be printed by Flow (e.g. deprecation warnings)."""
import functools
import inspect
import warnings
string_types = (type(b''), type(u''))
def deprecated_attribute(obj, dep_from, dep_to):
"""Print a deprecation warning.
Parameters
----------
obj : class
The class with the... | """Warnings that may be printed by Flow (e.g. deprecation warnings)."""
import functools
import inspect
import warnings
string_types = (type(b''), type(u''))
def deprecated_attribute(obj, dep_from, dep_to):
"""Print a deprecation warning.
Parameters
----------
obj : class
The class with the... | # if isinstance(base, string_types):
# The @deprecated is used with a 'reason'.
#
# .. code-block:: python
#
# @deprecated("please, use another function")
# def old_function(x, y):
# pass
def decorator(func1):
if inspect.isclass(func1):
fmt1 = "The c... | """Print a deprecation warning.
This is a decorator which can be used to mark functions as deprecated. It
will result in a warning being emitted when the function is used.
"""
# if isinstance(base, string_types):
# The @deprecated is used with a 'reason'.
#
# .. code-block:: python
... | 182 | 279 | 696 | 975 | """Warnings that may be printed by Flow (e.g. deprecation warnings)."""
import functools
import inspect
import warnings
string_types = (type(b''), type(u''))
def deprecated_attribute(obj, dep_from, dep_to):
"""Print a deprecation warning.
Parameters
----------
obj : class
The class with the... | """Warnings that may be printed by Flow (e.g. deprecation warnings)."""
import functools
import inspect
import warnings
string_types = (type(b''), type(u''))
def deprecated_attribute(obj, dep_from, dep_to):
"""Print a deprecation warning.
Parameters
----------
obj : class
The class with the... | |
45,433 | /home/hieuvd/dung_repo/raw/stars_03/flow-project_flow/flow | /home/hieuvd/dung_repo/raw/stars_03/flow-project_flow/flow/flow/utils/leaderboard/solution.py.template | 13,14 | 1,22 | get_actions | 14,19 | 14,19 | """
A solution should include:
1. Benchmark network;
2. get_actions() method;
3. get_states() method.
"""
# Specify benchmark network below.
BENCHMARK = "" # Benchmark name goes here...
# Specify get_action() method below.
def get_actions(state):
FILL_FUNC_BODYdef get_states(env, **kwargs):
# get_st... | """
A solution should include:
1. Benchmark network;
2. get_actions() method;
3. get_states() method.
"""
# Specify benchmark network below.
BENCHMARK = "" # Benchmark name goes here...
# Specify get_action() method below.
def get_actions(state):
FILL_FUNC_BODYdef get_states(env, **kwargs):
# get_st... | # get_actions() code goes here...
return
# Specify get_state() method below.
| # get_actions() code goes here...
return
# Specify get_state() method below.
| 11 | 121 | 32 | 153 | """
A solution should include:
1. Benchmark network;
2. get_actions() method;
3. get_states() method.
"""
# Specify benchmark network below.
BENCHMARK = "" # Benchmark name goes here...
# Specify get_action() method below.
def get_actions(state):
FILL_FUNC_BODYdef get_states(env, **kwargs):
# get_st... | """
A solution should include:
1. Benchmark network;
2. get_actions() method;
3. get_states() method.
"""
# Specify benchmark network below.
BENCHMARK = "" # Benchmark name goes here...
# Specify get_action() method below.
def get_actions(state):
FILL_FUNC_BODYdef get_states(env, **kwargs):
# get_st... | |
45,434 | /home/hieuvd/dung_repo/raw/stars_03/flow-project_flow/flow | /home/hieuvd/dung_repo/raw/stars_03/flow-project_flow/flow/setup.py | 11,12 | 1,52 | _read_requirements_file | 13,18 | 12,18 | #!/usr/bin/env python3
# flake8: noqa
"""Setup script for the Flow repository."""
from os.path import dirname, realpath
from setuptools import find_packages, setup, Distribution
import setuptools.command.build_ext as _build_ext
import subprocess
from flow.version import __version__
def _read_requirements_file():
FILL... | #!/usr/bin/env python3
# flake8: noqa
"""Setup script for the Flow repository."""
from os.path import dirname, realpath
from setuptools import find_packages, setup, Distribution
import setuptools.command.build_ext as _build_ext
import subprocess
from flow.version import __version__
def _read_requirements_file():
... | req_file_path = '%s/requirements.txt' % dirname(realpath(__file__))
with open(req_file_path) as f:
return [line.strip() for line in f]
| """Return the elements in requirements.txt."""
req_file_path = '%s/requirements.txt' % dirname(realpath(__file__))
with open(req_file_path) as f:
return [line.strip() for line in f]
| 15 | 437 | 60 | 497 | #!/usr/bin/env python3
# flake8: noqa
"""Setup script for the Flow repository."""
from os.path import dirname, realpath
from setuptools import find_packages, setup, Distribution
import setuptools.command.build_ext as _build_ext
import subprocess
from flow.version import __version__
def _read_requirements_file():
FILL... | #!/usr/bin/env python3
# flake8: noqa
"""Setup script for the Flow repository."""
from os.path import dirname, realpath
from setuptools import find_packages, setup, Distribution
import setuptools.command.build_ext as _build_ext
import subprocess
from flow.version import __version__
def _read_requirements_file():
... | |
45,435 | /home/hieuvd/dung_repo/raw/stars_03/flow-project_flow/flow | /home/hieuvd/dung_repo/raw/stars_03/flow-project_flow/flow/setup.py | 32,33 | 29,37 | has_ext_modules | BinaryDistribution | 34,37 | 33,37 | class BinaryDistribution(Distribution):
"""See parent class."""
def has_ext_modules(self):
FILL_FUNC_BODY | class BinaryDistribution(Distribution):
"""See parent class."""
def has_ext_modules(self):
"""Return True for external modules."""
FILL_FUNC_BODY | return True
| """Return True for external modules."""
return True
| 2 | 48 | 9 | 57 | #!/usr/bin/env python3
# flake8: noqa
"""Setup script for the Flow repository."""
from os.path import dirname, realpath
from setuptools import find_packages, setup, Distribution
import setuptools.command.build_ext as _build_ext
import subprocess
from flow.version import __version__
def _read_requirements_file():
... | #!/usr/bin/env python3
# flake8: noqa
"""Setup script for the Flow repository."""
from os.path import dirname, realpath
from setuptools import find_packages, setup, Distribution
import setuptools.command.build_ext as _build_ext
import subprocess
from flow.version import __version__
def _read_requirements_file():
... |
45,436 | /home/hieuvd/dung_repo/raw/stars_03/flow-project_flow/flow | /home/hieuvd/dung_repo/raw/stars_03/flow-project_flow/flow/setup.py | 21,22 | 18,29 | run | build_ext | 23,29 | 22,29 | class build_ext(_build_ext.build_ext):
"""External buid commands."""
def run(self):
FILL_FUNC_BODY | class build_ext(_build_ext.build_ext):
"""External buid commands."""
def run(self):
"""Install traci wheels."""
FILL_FUNC_BODY | subprocess.check_call(
['python3','-m','pip', 'install',
'https://akreidieh.s3.amazonaws.com/sumo/flow-0.4.0/'
'sumotools-0.4.0-py3-none-any.whl'])
| """Install traci wheels."""
subprocess.check_call(
['python3','-m','pip', 'install',
'https://akreidieh.s3.amazonaws.com/sumo/flow-0.4.0/'
'sumotools-0.4.0-py3-none-any.whl'])
| 5 | 48 | 85 | 133 | #!/usr/bin/env python3
# flake8: noqa
"""Setup script for the Flow repository."""
from os.path import dirname, realpath
from setuptools import find_packages, setup, Distribution
import setuptools.command.build_ext as _build_ext
import subprocess
from flow.version import __version__
def _read_requirements_file():
... | #!/usr/bin/env python3
# flake8: noqa
"""Setup script for the Flow repository."""
from os.path import dirname, realpath
from setuptools import find_packages, setup, Distribution
import setuptools.command.build_ext as _build_ext
import subprocess
from flow.version import __version__
def _read_requirements_file():
... |
45,460 | /home/hieuvd/dung_repo/raw/stars_03/fudan-zvg_SETR/SETR | /home/hieuvd/dung_repo/raw/stars_03/fudan-zvg_SETR/SETR/demo/image_demo.py | 7,8 | 1,30 | main | 8,28 | 8,28 | from argparse import ArgumentParser
from mmseg.apis import inference_segmentor, init_segmentor, show_result_pyplot
from mmseg.core.evaluation import get_palette
def main():
FILL_FUNC_BODYif __name__ == '__main__':
main()
| from argparse import ArgumentParser
from mmseg.apis import inference_segmentor, init_segmentor, show_result_pyplot
from mmseg.core.evaluation import get_palette
def main():
FILL_FUNC_BODYif __name__ == '__main__':
main()
| parser = ArgumentParser()
parser.add_argument('img', help='Image file')
parser.add_argument('config', help='Config file')
parser.add_argument('checkpoint', help='Checkpoint file')
parser.add_argument(
'--device', default='cuda:0', help='Device used for inference')
parser.add_argument(
... | parser = ArgumentParser()
parser.add_argument('img', help='Image file')
parser.add_argument('config', help='Config file')
parser.add_argument('checkpoint', help='Checkpoint file')
parser.add_argument(
'--device', default='cuda:0', help='Device used for inference')
parser.add_argument(
... | 65 | 79 | 254 | 333 | from argparse import ArgumentParser
from mmseg.apis import inference_segmentor, init_segmentor, show_result_pyplot
from mmseg.core.evaluation import get_palette
def main():
FILL_FUNC_BODYif __name__ == '__main__':
main()
| from argparse import ArgumentParser
from mmseg.apis import inference_segmentor, init_segmentor, show_result_pyplot
from mmseg.core.evaluation import get_palette
def main():
FILL_FUNC_BODYif __name__ == '__main__':
main()
| |
45,461 | /home/hieuvd/dung_repo/raw/stars_03/fudan-zvg_SETR/SETR | /home/hieuvd/dung_repo/raw/stars_03/fudan-zvg_SETR/SETR/docs/conf.py | 26,27 | 1,80 | get_version | 27,33 | 27,33 | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... | with open(version_file, 'r') as f:
exec(compile(f.read(), version_file, 'exec'))
return locals()['__version__']
# The full version, including alpha/beta/rc tags
| with open(version_file, 'r') as f:
exec(compile(f.read(), version_file, 'exec'))
return locals()['__version__']
# The full version, including alpha/beta/rc tags
| 17 | 692 | 63 | 755 | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... | |
45,462 | /home/hieuvd/dung_repo/raw/stars_03/fudan-zvg_SETR/SETR | /home/hieuvd/dung_repo/raw/stars_03/fudan-zvg_SETR/SETR/hlg-detection/mmdet/core/bbox/coder/distance_point_bbox_coder.py | 41,42 | 7,64 | decode | DistancePointBBoxCoder | 58,64 | 42,64 | @BBOX_CODERS.register_module()
class DistancePointBBoxCoder(BaseBBoxCoder):
"""Distance Point BBox coder.
This coder encodes gt bboxes (x1, y1, x2, y2) into (top, bottom, left,
right) and decode it back to the original.
Args:
clip_border (bool, optional): Whether clip the objects outside the
... | @BBOX_CODERS.register_module()
class DistancePointBBoxCoder(BaseBBoxCoder):
"""Distance Point BBox coder.
This coder encodes gt bboxes (x1, y1, x2, y2) into (top, bottom, left,
right) and decode it back to the original.
Args:
clip_border (bool, optional): Whether clip the objects outside the
... | assert points.size(0) == pred_bboxes.size(0)
assert points.size(-1) == 2
assert pred_bboxes.size(-1) == 4
if self.clip_border is False:
max_shape = None
return distance2bbox(points, pred_bboxes, max_shape)
| """Decode distance prediction to bounding box.
Args:
points (Tensor): Shape (B, N, 2) or (N, 2).
pred_bboxes (Tensor): Distance from the given point to 4
boundaries (left, top, right, bottom). Shape (B, N, 4)
or (N, 4)
max_shape (Seque... | 23 | 668 | 90 | 758 | # Copyright (c) OpenMMLab. All rights reserved.
from ..builder import BBOX_CODERS
from ..transforms import bbox2distance, distance2bbox
from .base_bbox_coder import BaseBBoxCoder
@BBOX_CODERS.register_module()
class DistancePointBBoxCoder(BaseBBoxCoder):
"""Distance Point BBox coder.
This coder encodes gt bb... | # Copyright (c) OpenMMLab. All rights reserved.
from ..builder import BBOX_CODERS
from ..transforms import bbox2distance, distance2bbox
from .base_bbox_coder import BaseBBoxCoder
@BBOX_CODERS.register_module()
class DistancePointBBoxCoder(BaseBBoxCoder):
"""Distance Point BBox coder.
This coder encodes gt bb... |
45,463 | /home/hieuvd/dung_repo/raw/stars_03/fudan-zvg_SETR/SETR | /home/hieuvd/dung_repo/raw/stars_03/fudan-zvg_SETR/SETR/hlg-detection/mmdet/core/bbox/coder/pseudo_bbox_coder.py | 17,18 | 6,20 | decode | PseudoBBoxCoder | 19,20 | 18,20 | @BBOX_CODERS.register_module()
class PseudoBBoxCoder(BaseBBoxCoder):
"""Pseudo bounding box coder."""
def __init__(self, **kwargs):
super(BaseBBoxCoder, self).__init__(**kwargs)
def encode(self, bboxes, gt_bboxes):
"""torch.Tensor: return the given ``bboxes``"""
return gt_bboxes
... | @BBOX_CODERS.register_module()
class PseudoBBoxCoder(BaseBBoxCoder):
"""Pseudo bounding box coder."""
def __init__(self, **kwargs):
super(BaseBBoxCoder, self).__init__(**kwargs)
def encode(self, bboxes, gt_bboxes):
"""torch.Tensor: return the given ``bboxes``"""
return gt_bboxes
... | return pred_bboxes
| """torch.Tensor: return the given ``pred_bboxes``"""
return pred_bboxes
| 2 | 167 | 9 | 176 | # Copyright (c) OpenMMLab. All rights reserved.
from ..builder import BBOX_CODERS
from .base_bbox_coder import BaseBBoxCoder
@BBOX_CODERS.register_module()
class PseudoBBoxCoder(BaseBBoxCoder):
"""Pseudo bounding box coder."""
def __init__(self, **kwargs):
super(BaseBBoxCoder, self).__init__(**kwargs... | # Copyright (c) OpenMMLab. All rights reserved.
from ..builder import BBOX_CODERS
from .base_bbox_coder import BaseBBoxCoder
@BBOX_CODERS.register_module()
class PseudoBBoxCoder(BaseBBoxCoder):
"""Pseudo bounding box coder."""
def __init__(self, **kwargs):
super(BaseBBoxCoder, self).__init__(**kwargs... |
45,464 | /home/hieuvd/dung_repo/raw/stars_03/fudan-zvg_SETR/SETR | /home/hieuvd/dung_repo/raw/stars_03/fudan-zvg_SETR/SETR/hlg-detection/mmdet/core/bbox/samplers/combined_sampler.py | 19,20 | 6,22 | _sample_neg | CombinedSampler | 21,22 | 20,22 | @BBOX_SAMPLERS.register_module()
class CombinedSampler(BaseSampler):
"""A sampler that combines positive sampler and negative sampler."""
def __init__(self, pos_sampler, neg_sampler, **kwargs):
super(CombinedSampler, self).__init__(**kwargs)
self.pos_sampler = build_sampler(pos_sampler, **kwarg... | @BBOX_SAMPLERS.register_module()
class CombinedSampler(BaseSampler):
"""A sampler that combines positive sampler and negative sampler."""
def __init__(self, pos_sampler, neg_sampler, **kwargs):
super(CombinedSampler, self).__init__(**kwargs)
self.pos_sampler = build_sampler(pos_sampler, **kwarg... | raise NotImplementedError
| """Sample negative samples."""
raise NotImplementedError
| 2 | 185 | 9 | 194 | # Copyright (c) OpenMMLab. All rights reserved.
from ..builder import BBOX_SAMPLERS, build_sampler
from .base_sampler import BaseSampler
@BBOX_SAMPLERS.register_module()
class CombinedSampler(BaseSampler):
"""A sampler that combines positive sampler and negative sampler."""
def __init__(self, pos_sampler, ne... | # Copyright (c) OpenMMLab. All rights reserved.
from ..builder import BBOX_SAMPLERS, build_sampler
from .base_sampler import BaseSampler
@BBOX_SAMPLERS.register_module()
class CombinedSampler(BaseSampler):
"""A sampler that combines positive sampler and negative sampler."""
def __init__(self, pos_sampler, ne... |
45,465 | /home/hieuvd/dung_repo/raw/stars_03/fudan-zvg_SETR/SETR | /home/hieuvd/dung_repo/raw/stars_03/fudan-zvg_SETR/SETR/hlg-detection/mmdet/core/evaluation/bbox_overlaps.py | 5,10 | 1,66 | bbox_overlaps | 28,66 | 10,66 | # Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
def bbox_overlaps(bboxes1,
bboxes2,
mode='iou',
eps=1e-6,
use_legacy_coordinate=False):
FILL_FUNC_BODY | # Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
def bbox_overlaps(bboxes1,
bboxes2,
mode='iou',
eps=1e-6,
use_legacy_coordinate=False):
"""Calculate the ious between each bbox of bboxes1 and bboxes2.
Args:
bbox... |
assert mode in ['iou', 'iof']
if not use_legacy_coordinate:
extra_length = 0.
else:
extra_length = 1.
bboxes1 = bboxes1.astype(np.float32)
bboxes2 = bboxes2.astype(np.float32)
rows = bboxes1.shape[0]
cols = bboxes2.shape[0]
ious = np.zeros((rows, cols), dtype=np.float32)... | """Calculate the ious between each bbox of bboxes1 and bboxes2.
Args:
bboxes1 (ndarray): Shape (n, 4)
bboxes2 (ndarray): Shape (k, 4)
mode (str): IOU (intersection over union) or IOF (intersection
over foreground)
use_legacy_coordinate (bool): Whether to use coordina... | 177 | 338 | 655 | 993 | # Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
def bbox_overlaps(bboxes1,
bboxes2,
mode='iou',
eps=1e-6,
use_legacy_coordinate=False):
FILL_FUNC_BODY | # Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
def bbox_overlaps(bboxes1,
bboxes2,
mode='iou',
eps=1e-6,
use_legacy_coordinate=False):
"""Calculate the ious between each bbox of bboxes1 and bboxes2.
Args:
bbox... | |
45,466 | /home/hieuvd/dung_repo/raw/stars_03/fudan-zvg_SETR/SETR | /home/hieuvd/dung_repo/raw/stars_03/fudan-zvg_SETR/SETR/hlg-detection/mmdet/datasets/pipelines/instaboost.py | 56,57 | 7,119 | _load_anns | InstaBoost | 57,78 | 57,78 | @PIPELINES.register_module()
class InstaBoost:
r"""Data augmentation method in `InstaBoost: Boosting Instance
Segmentation Via Probability Map Guided Copy-Pasting
<https://arxiv.org/abs/1908.07801>`_.
Refer to https://github.com/GothicAi/Instaboost for implementation details.
Args:
action_... | @PIPELINES.register_module()
class InstaBoost:
r"""Data augmentation method in `InstaBoost: Boosting Instance
Segmentation Via Probability Map Guided Copy-Pasting
<https://arxiv.org/abs/1908.07801>`_.
Refer to https://github.com/GothicAi/Instaboost for implementation details.
Args:
action_... | labels = results['ann_info']['labels']
masks = results['ann_info']['masks']
bboxes = results['ann_info']['bboxes']
n = len(labels)
anns = []
for i in range(n):
label = labels[i]
bbox = bboxes[i]
mask = masks[i]
x1, y1, x2, ... | labels = results['ann_info']['labels']
masks = results['ann_info']['masks']
bboxes = results['ann_info']['bboxes']
n = len(labels)
anns = []
for i in range(n):
label = labels[i]
bbox = bboxes[i]
mask = masks[i]
x1, y1, x2, ... | 67 | 1,182 | 221 | 1,403 | # Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
from ..builder import PIPELINES
@PIPELINES.register_module()
class InstaBoost:
r"""Data augmentation method in `InstaBoost: Boosting Instance
Segmentation Via Probability Map Guided Copy-Pasting
<https://arxiv.org/abs/1908.07801>`_.
... | # Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
from ..builder import PIPELINES
@PIPELINES.register_module()
class InstaBoost:
r"""Data augmentation method in `InstaBoost: Boosting Instance
Segmentation Via Probability Map Guided Copy-Pasting
<https://arxiv.org/abs/1908.07801>`_.
... |
45,467 | /home/hieuvd/dung_repo/raw/stars_03/fudan-zvg_SETR/SETR | /home/hieuvd/dung_repo/raw/stars_03/fudan-zvg_SETR/SETR/hlg-detection/mmdet/models/detectors/cascade_rcnn.py | 30,31 | 6,50 | show_result | CascadeRCNN | 41,50 | 31,50 | @DETECTORS.register_module()
class CascadeRCNN(TwoStageDetector):
r"""Implementation of `Cascade R-CNN: Delving into High Quality Object
Detection <https://arxiv.org/abs/1906.09756>`_"""
def __init__(self,
backbone,
neck=None,
rpn_head=None,
... | @DETECTORS.register_module()
class CascadeRCNN(TwoStageDetector):
r"""Implementation of `Cascade R-CNN: Delving into High Quality Object
Detection <https://arxiv.org/abs/1906.09756>`_"""
def __init__(self,
backbone,
neck=None,
rpn_head=None,
... | if self.with_mask:
ms_bbox_result, ms_segm_result = result
if isinstance(ms_bbox_result, dict):
result = (ms_bbox_result['ensemble'],
ms_segm_result['ensemble'])
else:
if isinstance(result, dict):
result = resu... | """Show prediction results of the detector.
Args:
data (str or np.ndarray): Image filename or loaded image.
result (Tensor or tuple): The results to draw over `img`
bbox_result or (bbox_result, segm_result).
Returns:
np.ndarray: The image wit... | 25 | 356 | 127 | 483 | # Copyright (c) OpenMMLab. All rights reserved.
from ..builder import DETECTORS
from .two_stage import TwoStageDetector
@DETECTORS.register_module()
class CascadeRCNN(TwoStageDetector):
r"""Implementation of `Cascade R-CNN: Delving into High Quality Object
Detection <https://arxiv.org/abs/1906.09756>`_"""
... | # Copyright (c) OpenMMLab. All rights reserved.
from ..builder import DETECTORS
from .two_stage import TwoStageDetector
@DETECTORS.register_module()
class CascadeRCNN(TwoStageDetector):
r"""Implementation of `Cascade R-CNN: Delving into High Quality Object
Detection <https://arxiv.org/abs/1906.09756>`_"""
... |
45,468 | /home/hieuvd/dung_repo/raw/stars_03/fudan-zvg_SETR/SETR | /home/hieuvd/dung_repo/raw/stars_03/fudan-zvg_SETR/SETR/hlg-detection/mmdet/models/detectors/fast_rcnn.py | 27,28 | 6,56 | forward_test | FastRCNN | 41,56 | 28,56 | @DETECTORS.register_module()
class FastRCNN(TwoStageDetector):
"""Implementation of `Fast R-CNN <https://arxiv.org/abs/1504.08083>`_"""
def __init__(self,
backbone,
roi_head,
train_cfg,
test_cfg,
neck=None,
pr... | @DETECTORS.register_module()
class FastRCNN(TwoStageDetector):
"""Implementation of `Fast R-CNN <https://arxiv.org/abs/1504.08083>`_"""
def __init__(self,
backbone,
roi_head,
train_cfg,
test_cfg,
neck=None,
pr... | for var, name in [(imgs, 'imgs'), (img_metas, 'img_metas')]:
if not isinstance(var, list):
raise TypeError(f'{name} must be a list, but got {type(var)}')
num_augs = len(imgs)
if num_augs != len(img_metas):
raise ValueError(f'num of augmentations ({len(img... | """
Args:
imgs (List[Tensor]): the outer list indicates test-time
augmentations and inner Tensor should have a shape NxCxHxW,
which contains all images in the batch.
img_metas (List[List[dict]]): the outer list indicates test-time
a... | 57 | 394 | 212 | 606 | # Copyright (c) OpenMMLab. All rights reserved.
from ..builder import DETECTORS
from .two_stage import TwoStageDetector
@DETECTORS.register_module()
class FastRCNN(TwoStageDetector):
"""Implementation of `Fast R-CNN <https://arxiv.org/abs/1504.08083>`_"""
def __init__(self,
backbone,
... | # Copyright (c) OpenMMLab. All rights reserved.
from ..builder import DETECTORS
from .two_stage import TwoStageDetector
@DETECTORS.register_module()
class FastRCNN(TwoStageDetector):
"""Implementation of `Fast R-CNN <https://arxiv.org/abs/1504.08083>`_"""
def __init__(self,
backbone,
... |
45,469 | /home/hieuvd/dung_repo/raw/stars_03/fudan-zvg_SETR/SETR | /home/hieuvd/dung_repo/raw/stars_03/fudan-zvg_SETR/SETR/hlg-detection/mmdet/models/detectors/htc.py | 13,15 | 6,17 | with_semantic | HybridTaskCascade | 16,17 | 15,17 | @DETECTORS.register_module()
class HybridTaskCascade(CascadeRCNN):
"""Implementation of `HTC <https://arxiv.org/abs/1901.07518>`_"""
def __init__(self, **kwargs):
super(HybridTaskCascade, self).__init__(**kwargs)
@property
def with_semantic(self):
FILL_FUNC_BODY | @DETECTORS.register_module()
class HybridTaskCascade(CascadeRCNN):
"""Implementation of `HTC <https://arxiv.org/abs/1901.07518>`_"""
def __init__(self, **kwargs):
super(HybridTaskCascade, self).__init__(**kwargs)
@property
def with_semantic(self):
"""bool: whether the detector has a se... | return self.roi_head.with_semantic
| """bool: whether the detector has a semantic head"""
return self.roi_head.with_semantic
| 2 | 128 | 15 | 143 | # Copyright (c) OpenMMLab. All rights reserved.
from ..builder import DETECTORS
from .cascade_rcnn import CascadeRCNN
@DETECTORS.register_module()
class HybridTaskCascade(CascadeRCNN):
"""Implementation of `HTC <https://arxiv.org/abs/1901.07518>`_"""
def __init__(self, **kwargs):
super(HybridTaskCasc... | # Copyright (c) OpenMMLab. All rights reserved.
from ..builder import DETECTORS
from .cascade_rcnn import CascadeRCNN
@DETECTORS.register_module()
class HybridTaskCascade(CascadeRCNN):
"""Implementation of `HTC <https://arxiv.org/abs/1901.07518>`_"""
def __init__(self, **kwargs):
super(HybridTaskCasc... |
45,470 | /home/hieuvd/dung_repo/raw/stars_03/fudan-zvg_SETR/SETR | /home/hieuvd/dung_repo/raw/stars_03/fudan-zvg_SETR/SETR/hlg-detection/mmdet/models/detectors/sparse_rcnn.py | 67,68 | 6,112 | simple_test | SparseRCNN | 81,93 | 68,93 | @DETECTORS.register_module()
class SparseRCNN(TwoStageDetector):
r"""Implementation of `Sparse R-CNN: End-to-End Object Detection with
Learnable Proposals <https://arxiv.org/abs/2011.12450>`_"""
def __init__(self, *args, **kwargs):
super(SparseRCNN, self).__init__(*args, **kwargs)
assert se... | @DETECTORS.register_module()
class SparseRCNN(TwoStageDetector):
r"""Implementation of `Sparse R-CNN: End-to-End Object Detection with
Learnable Proposals <https://arxiv.org/abs/2011.12450>`_"""
def __init__(self, *args, **kwargs):
super(SparseRCNN, self).__init__(*args, **kwargs)
assert se... | x = self.extract_feat(img)
proposal_boxes, proposal_features, imgs_whwh = \
self.rpn_head.simple_test_rpn(x, img_metas)
results = self.roi_head.simple_test(
x,
proposal_boxes,
proposal_features,
img_metas,
imgs_whwh=imgs_whw... | """Test function without test time augmentation.
Args:
imgs (list[torch.Tensor]): List of multiple images
img_metas (list[dict]): List of image information.
rescale (bool): Whether to rescale the results.
Defaults to False.
Returns:
... | 21 | 1,149 | 133 | 1,282 | # Copyright (c) OpenMMLab. All rights reserved.
from ..builder import DETECTORS
from .two_stage import TwoStageDetector
@DETECTORS.register_module()
class SparseRCNN(TwoStageDetector):
r"""Implementation of `Sparse R-CNN: End-to-End Object Detection with
Learnable Proposals <https://arxiv.org/abs/2011.12450>`... | # Copyright (c) OpenMMLab. All rights reserved.
from ..builder import DETECTORS
from .two_stage import TwoStageDetector
@DETECTORS.register_module()
class SparseRCNN(TwoStageDetector):
r"""Implementation of `Sparse R-CNN: End-to-End Object Detection with
Learnable Proposals <https://arxiv.org/abs/2011.12450>`... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.