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,191
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/examples/cnn_lstm/cnn_lstm.py
23,39
1,106
cnn_lstm_classifier
73,106
39,106
# 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 from examples.cnn_lstm.cnn_encoder import CNNEncoder from examples.cnn_lstm.lstm_encod...
# 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 from examples.cnn_lstm.cnn_encoder import CNNEncoder from examples.cnn_lstm.lstm_encod...
image_encoder = CNNEncoder( input_dims=cnn_input_dims, output_dims=cnn_output_dims, kernel_sizes=cnn_kernel_sizes, ) text_encoder = LSTMEncoder( vocab_size=text_vocab_size, embedding_dim=text_embedding_dim, input_size=lstm_input_size, hidden_size=lst...
""" A simple example to show the composability in TorchMultimodal, and how to make use of builder functions to build a given model from an architecture. A builder_function takes in all of the parameters needed for building the individual layers and simplifies the interface for the architecture. ...
64
1,042
350
1,392
# 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 from examples.cnn_lstm.cnn_encoder import CNNEncoder from examples.cnn_lstm.lstm_encod...
# 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 from examples.cnn_lstm.cnn_encoder import CNNEncoder from examples.cnn_lstm.lstm_encod...
45,192
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/examples/flava/tools/convert_weights.py
35,36
1,73
convert_weights
36,64
36,64
# 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 argparse import torch from torchmultimodal.models.flava.model import flava_model_for_pretraining KEY_R...
# 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 argparse import torch from torchmultimodal.models.flava.model import flava_model_for_pretraining KEY_R...
ckpt = torch.load(args.ckpt_file, map_location="cpu") flava = flava_model_for_pretraining() model = ckpt["model"] import pdb pdb.set_trace() for key in list(model.keys()): original = key for option, replacement in KEY_REPLACEMENTS.items(): key = key.replace(option, r...
ckpt = torch.load(args.ckpt_file, map_location="cpu") flava = flava_model_for_pretraining() model = ckpt["model"] import pdb pdb.set_trace() for key in list(model.keys()): original = key for option, replacement in KEY_REPLACEMENTS.items(): key = key.replace(option, r...
79
608
301
909
# 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 argparse import torch from torchmultimodal.models.flava.model import flava_model_for_pretraining KEY_R...
# 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 argparse import torch from torchmultimodal.models.flava.model import flava_model_for_pretraining KEY_R...
45,196
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/examples/mdetr/loss.py
205,210
179,290
total_losses_with_weights
MDETRLoss
210,215
210,215
class MDETRLoss(nn.Module): def __init__( self, soft_token_loss: Callable[..., Tensor], box_losses: Callable[..., BoxLosses], contrastive_alignment_loss: Optional[nn.Module] = None, vqa_losses: Optional[Iterable[Callable[..., Dict[str, Tensor]]]] = None, ): super(...
class MDETRLoss(nn.Module): def __init__( self, soft_token_loss: Callable[..., Tensor], box_losses: Callable[..., BoxLosses], contrastive_alignment_loss: Optional[nn.Module] = None, vqa_losses: Optional[Iterable[Callable[..., Dict[str, Tensor]]]] = None, ): super(...
for k in weight_dict.keys(): if k not in loss_dict.keys(): raise ValueError(f"Weight dict contains invalid key {k}") return sum([weight_dict[k] * loss_dict[k] for k in weight_dict.keys()])
for k in weight_dict.keys(): if k not in loss_dict.keys(): raise ValueError(f"Weight dict contains invalid key {k}") return sum([weight_dict[k] * loss_dict[k] for k in weight_dict.keys()])
24
1,372
74
1,446
# 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 functools import partial from typing import Any, Callable, Dict, Itera...
# 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 functools import partial from typing import Any, Callable, Dict, Itera...
45,197
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/examples/mdetr/optimizer.py
34,41
1,131
adjust_learning_rate
63,101
41,101
# 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. """Collections of utilities related to optimization.""" from bisect import bisect_right import torch def upd...
# 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. """Collections of utilities related to optimization.""" from bisect import bisect_right import torch def upd...
num_warmup_steps: int = round(args.fraction_warmup_steps * num_training_steps) if args.schedule == "step": gamma = 0.1 ** (epoch // args.lr_drop) text_encoder_gamma = gamma elif args.schedule == "multistep": milestones = list(range(args.lr_drop, args.epochs, 50)) gamma = 0.5 ...
"""Adjust the lr according to the schedule. Based on the implementation in the MDETR repo: https://bit.ly/3J5fspI. Args: Optimizer: torch optimizer to update. epoch(int): number of the current epoch. curr_step(int): number of optimization step taken so far. num_training_step...
134
969
591
1,560
# 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. """Collections of utilities related to optimization.""" from bisect import bisect_right import torch def upd...
# 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. """Collections of utilities related to optimization.""" from bisect import bisect_right import torch def upd...
45,198
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/examples/mdetr/phrase_grounding.py
26,34
1,174
evaluate
34,80
34,80
# 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 argparse import json import random from copy import deepcopy from pathlib import Path import numpy as n...
# 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 argparse import json import random from copy import deepcopy from pathlib import Path import numpy as n...
model.eval() metric_logger = MetricLogger(delimiter=" ") header = "Test:" for batch_dict in metric_logger.log_every(data_loader, 10, header): samples = [x.to(device) for x in batch_dict["samples"]] targets = batch_dict["targets"] text = [t["tokenized"].to(device) for t in targ...
model.eval() metric_logger = MetricLogger(delimiter=" ") header = "Test:" for batch_dict in metric_logger.log_every(data_loader, 10, header): samples = [x.to(device) for x in batch_dict["samples"]] targets = batch_dict["targets"] text = [t["tokenized"].to(device) for t in targ...
130
1,174
556
1,730
# 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 argparse import json import random from copy import deepcopy from pathlib import Path import numpy as n...
# 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 argparse import json import random from copy import deepcopy from pathlib import Path import numpy as n...
45,200
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/examples/mdetr/utils/dist.py
140,141
1,170
init_distributed_mode
142,170
141,170
# 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 functools import io import os import torch import torch.distributed as dist _LOCAL_PROCESS_GROUP = Non...
# 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 functools import io import os import torch import torch.distributed as dist _LOCAL_PROCESS_GROUP = Non...
if "RANK" in os.environ and "WORLD_SIZE" in os.environ: args.rank = int(os.environ["RANK"]) args.world_size = int(os.environ["WORLD_SIZE"]) args.gpu = int(os.environ["LOCAL_RANK"]) elif "SLURM_PROCID" in os.environ: args.rank = int(os.environ["SLURM_PROCID"]) args.gpu = a...
"""Initialize distributed training, if appropriate""" if "RANK" in os.environ and "WORLD_SIZE" in os.environ: args.rank = int(os.environ["RANK"]) args.world_size = int(os.environ["WORLD_SIZE"]) args.gpu = int(os.environ["LOCAL_RANK"]) elif "SLURM_PROCID" in os.environ: args.r...
65
1,376
353
1,729
# 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 functools import io import os import torch import torch.distributed as dist _LOCAL_PROCESS_GROUP = Non...
# 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 functools import io import os import torch import torch.distributed as dist _LOCAL_PROCESS_GROUP = Non...
45,201
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/examples/mdetr/utils/metrics.py
117,118
83,191
log_every
MetricLogger
118,191
118,191
class MetricLogger(object): def __init__(self, delimiter="\t"): self.meters = defaultdict(SmoothedValue) self.delimiter = delimiter def update(self, **kwargs): for k, v in kwargs.items(): if isinstance(v, torch.Tensor): v = v.item() assert isinsta...
class MetricLogger(object): def __init__(self, delimiter="\t"): self.meters = defaultdict(SmoothedValue) self.delimiter = delimiter def update(self, **kwargs): for k, v in kwargs.items(): if isinstance(v, torch.Tensor): v = v.item() assert isinsta...
i = 0 if not header: header = "" start_time = time.time() end = time.time() iter_time = SmoothedValue(fmt="{avg:.4f}") data_time = SmoothedValue(fmt="{avg:.4f}") space_fmt = ":" + str(len(str(len(iterable)))) + "d" if torch.cuda.is_available():...
i = 0 if not header: header = "" start_time = time.time() end = time.time() iter_time = SmoothedValue(fmt="{avg:.4f}") data_time = SmoothedValue(fmt="{avg:.4f}") space_fmt = ":" + str(len(str(len(iterable)))) + "d" if torch.cuda.is_available():...
167
371
774
1,145
# 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. """ Various utilities related to track and report metrics """ import datetime import time from collections 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. """ Various utilities related to track and report metrics """ import datetime import time from collections impo...
45,202
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/examples/mdetr/utils/metrics.py
220,221
191,232
report
RecallTracker
224,232
221,232
class RecallTracker: """Utility class to track recall@k for various k, split by categories""" def __init__(self, topk: Sequence[int]): """ Parameters: - topk : tuple of ints corresponding to the recalls being tracked (eg, recall@1, recall@10, ...) """ self.total_byk_...
class RecallTracker: """Utility class to track recall@k for various k, split by categories""" def __init__(self, topk: Sequence[int]): """ Parameters: - topk : tuple of ints corresponding to the recalls being tracked (eg, recall@1, recall@10, ...) """ self.total_byk_...
report: Dict[int, Dict[str, float]] = {} for k in self.total_byk_bycat: assert k in self.positives_byk_bycat report[k] = { cat: self.positives_byk_bycat[k][cat] / self.total_byk_bycat[k][cat] for cat in self.total_byk_bycat[k] } ...
"""Return a condensed report of the results as a dict of dict. report[k][cat] is the recall@k for the given category """ report: Dict[int, Dict[str, float]] = {} for k in self.total_byk_bycat: assert k in self.positives_byk_bycat report[k] = { ...
28
431
122
553
# 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. """ Various utilities related to track and report metrics """ import datetime import time from collections 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. """ Various utilities related to track and report metrics """ import datetime import time from collections impo...
45,203
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/examples/mdetr/utils/metrics.py
69,71
19,83
value
SmoothedValue
71,73
71,73
class SmoothedValue: """Track a series of values and provide access to smoothed values over a window or the global series average. """ def __init__(self, window_size=20, fmt=None): if fmt is None: fmt = "{median:.4f} ({global_avg:.4f})" self.deque = deque(maxlen=window_size)...
class SmoothedValue: """Track a series of values and provide access to smoothed values over a window or the global series average. """ def __init__(self, window_size=20, fmt=None): if fmt is None: fmt = "{median:.4f} ({global_avg:.4f})" self.deque = deque(maxlen=window_size)...
return self.deque[-1]
return self.deque[-1]
2
543
13
556
# 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. """ Various utilities related to track and report metrics """ import datetime import time from collections 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. """ Various utilities related to track and report metrics """ import datetime import time from collections impo...
45,204
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/examples/mdetr/utils/misc.py
13,20
1,65
interpolate
23,44
20,44
# 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, List, Optional import torch from torch import Tensor def interpolate( inpu...
# 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, List, Optional import torch from torch import Tensor def interpolate( inpu...
if input.numel() > 0: return torch.nn.functional.interpolate( input, size, scale_factor, mode, align_corners ) assert ( input.shape[0] != 0 or input.shape[1] != 0 ), "At least one of the two first dimensions must be non zero" if input.shape[1] == 0: # Pytorc...
""" Equivalent to nn.functional.interpolate, but with support for empty channel sizes. """ if input.numel() > 0: return torch.nn.functional.interpolate( input, size, scale_factor, mode, align_corners ) assert ( input.shape[0] != 0 or input.shape[1] != 0 ), "A...
84
371
249
620
# 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, List, Optional import torch from torch import Tensor def interpolate( inpu...
# 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, List, Optional import torch from torch import Tensor def interpolate( inpu...
45,205
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/examples/mdetr/vqa_eval.py
104,105
1,194
main
105,186
105,186
# 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 argparse import json import random from copy import deepcopy from pathlib import Path import numpy as n...
# 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 argparse import json import random from copy import deepcopy from pathlib import Path import numpy as n...
# Init distributed mode dist.init_distributed_mode(args) # Update dataset specific configs if args.dataset_config is not None: # https://stackoverflow.com/a/16878364 d = vars(args) with open(args.dataset_config, "r") as f: cfg = json.load(f) d.update(cfg) ...
# Init distributed mode dist.init_distributed_mode(args) # Update dataset specific configs if args.dataset_config is not None: # https://stackoverflow.com/a/16878364 d = vars(args) with open(args.dataset_config, "r") as f: cfg = json.load(f) d.update(cfg) ...
187
1,045
893
1,938
# 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 argparse import json import random from copy import deepcopy from pathlib import Path import numpy as n...
# 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 argparse import json import random from copy import deepcopy from pathlib import Path import numpy as n...
45,208
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/examples/mugen/data/video_utils.py
38,39
1,53
convert_grayscale_to_color_label
39,53
39,53
# 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 tqdm import tqdm label_color_map = { 0: torch.FloatTensor((0, 0, 0)), 1: torch.Floa...
# 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 tqdm import tqdm label_color_map = { 0: torch.FloatTensor((0, 0, 0)), 1: torch.Floa...
b_in, t_in, h_in, w_in = input_tensor.shape input_tensor = input_tensor.reshape(-1) output_tensor = torch.zeros(input_tensor.shape[0], 3) for i, t in tqdm( enumerate(input_tensor.cpu().numpy()), total=input_tensor.shape[0] ): output_tensor[i] = label_color_map[t] output_tensor ...
b_in, t_in, h_in, w_in = input_tensor.shape input_tensor = input_tensor.reshape(-1) output_tensor = torch.zeros(input_tensor.shape[0], 3) for i, t in tqdm( enumerate(input_tensor.cpu().numpy()), total=input_tensor.shape[0] ): output_tensor[i] = label_color_map[t] output_tensor ...
39
652
195
847
# 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 tqdm import tqdm label_color_map = { 0: torch.FloatTensor((0, 0, 0)), 1: torch.Floa...
# 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 tqdm import tqdm label_color_map = { 0: torch.FloatTensor((0, 0, 0)), 1: torch.Floa...
45,209
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/examples/mugen/generation/video_vqvae.py
26,39
1,114
video_vqvae_mugen
69,114
39,114
# 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 from torchmultimodal.models.video_gpt.video_vqvae import ( preprocess_int_conv...
# 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 from torchmultimodal.models.video_gpt.video_vqvae import ( preprocess_int_conv...
encoder_strides = ((2, 2, 2), (2, 2, 2), (1, 2, 2), (1, 2, 2), (1, 2, 2), (1, 1, 1)) decoder_strides = ((2, 2, 2), (2, 2, 2), (1, 2, 2), (1, 2, 2), (1, 2, 2)) encoder_n_layers = len(encoder_strides) decoder_n_layers = len(decoder_strides) encoder_in_channel_dims = (in_channel_dim,) + (encoder_hidden...
"""Constructor for MUGEN's Video VQVAE. Expects input video data of shape ``{8,16,32}x256x256``. Trained for tokenization of video data and use in video-audio-text retrieval and generation tasks. See Hayes et al. 2022 for more details: https://arxiv.org/pdf/2204.08058.pdf Code ref: https://github.co...
128
1,219
640
1,859
# 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 from torchmultimodal.models.video_gpt.video_vqvae import ( preprocess_int_conv...
# 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 from torchmultimodal.models.video_gpt.video_vqvae import ( preprocess_int_conv...
45,211
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/examples/omnivore/data/rand_aug3d.py
154,155
115,194
forward
RandAugment3d
161,194
155,194
class RandAugment3d(autoaugment.RandAugment): """Modified RandAugment in order to handle single-view depth image. In here, color / non-geometric operation will only be applied on RGB channel. Args: num_ops (int): Number of augmentation transformations to apply sequentially. magnitude (int):...
class RandAugment3d(autoaugment.RandAugment): """Modified RandAugment in order to handle single-view depth image. In here, color / non-geometric operation will only be applied on RGB channel. Args: num_ops (int): Number of augmentation transformations to apply sequentially. magnitude (int):...
fill = self.fill channels, height, width = F.get_dimensions(img) if isinstance(img, Tensor): if isinstance(fill, (int, float)): fill = [float(fill)] * channels elif fill is not None: fill = [float(f) for f in fill] op_meta = self._...
""" img (PIL Image or Tensor): Image to be transformed. Returns: PIL Image or Tensor: Transformed image. """ fill = self.fill channels, height, width = F.get_dimensions(img) if isinstance(img, Tensor): if isinstance(fill, (int, float))...
116
503
417
920
# 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 typing import List, Optional import torch from torch import Tensor from torchvision.transform...
# 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 typing import List, Optional import torch from torch import Tensor from torchvision.transform...
45,212
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/examples/omnivore/data/transforms.py
235,236
234,244
forward
ColorJitter3d
236,244
236,244
class ColorJitter3d(T.ColorJitter): def forward(self, img): FILL_FUNC_BODY
class ColorJitter3d(T.ColorJitter): def forward(self, img): FILL_FUNC_BODY
assert isinstance(img, torch.Tensor) img[:3, :, :] = super().forward(img[:3, :, :]) return img # From original implementation # https://www.internalfb.com/code/fbsource/[f1a98f41bcce7ee621f0248a6e0235a3e3dea628]/ # fbcode/deeplearning/projects/omnivore/vissl/data/ssl_transforms/depth_T.py?line...
assert isinstance(img, torch.Tensor) img[:3, :, :] = super().forward(img[:3, :, :]) return img # From original implementation # https://www.internalfb.com/code/fbsource/[f1a98f41bcce7ee621f0248a6e0235a3e3dea628]/ # fbcode/deeplearning/projects/omnivore/vissl/data/ssl_transforms/depth_T.py?line...
20
33
151
184
# 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. # Modified from https://github.com/pytorch/vision/blob/main/references/classification/transforms.py import mat...
# 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. # Modified from https://github.com/pytorch/vision/blob/main/references/classification/transforms.py import mat...
45,213
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/examples/omnivore/data/transforms.py
230,231
227,234
forward
ConvertTCHWtoCTHW
231,234
231,234
class ConvertTCHWtoCTHW(torch.nn.Module): """Convert tensor from (T, C, H, W) to (C, T, H, W)""" def forward(self, vid: torch.Tensor) -> torch.Tensor: FILL_FUNC_BODY
class ConvertTCHWtoCTHW(torch.nn.Module): """Convert tensor from (T, C, H, W) to (C, T, H, W)""" def forward(self, vid: torch.Tensor) -> torch.Tensor: FILL_FUNC_BODY
return vid.permute(1, 0, 2, 3)
return vid.permute(1, 0, 2, 3)
5
79
26
105
# 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. # Modified from https://github.com/pytorch/vision/blob/main/references/classification/transforms.py import mat...
# 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. # Modified from https://github.com/pytorch/vision/blob/main/references/classification/transforms.py import mat...
45,214
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/examples/omnivore/data/transforms.py
345,346
318,366
forward
DepthNorm
346,366
346,366
class DepthNorm(torch.nn.Module): """ Normalize the depth channel: in an RGBD input of shape (4, H, W), only the last channel is modified. The depth channel is also clamped at 0.0. The Midas depth prediction model outputs inverse depth maps - negative values correspond to distances far away so c...
class DepthNorm(torch.nn.Module): """ Normalize the depth channel: in an RGBD input of shape (4, H, W), only the last channel is modified. The depth channel is also clamped at 0.0. The Midas depth prediction model outputs inverse depth maps - negative values correspond to distances far away so c...
c, h, w = image.shape if c != 4: err_msg = ( f"This transform is for 4 channel RGBD input only; got {image.shape}" ) raise ValueError(err_msg) color_img = image[:3, ...] # (3, H, W) depth_img = image[3:4, ...] # (1, H, W) # C...
c, h, w = image.shape if c != 4: err_msg = ( f"This transform is for 4 channel RGBD input only; got {image.shape}" ) raise ValueError(err_msg) color_img = image[:3, ...] # (3, H, W) depth_img = image[3:4, ...] # (1, H, W) # C...
73
312
245
557
# 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. # Modified from https://github.com/pytorch/vision/blob/main/references/classification/transforms.py import mat...
# 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. # Modified from https://github.com/pytorch/vision/blob/main/references/classification/transforms.py import mat...
45,215
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/examples/omnivore/data/transforms.py
275,276
244,318
forward
DropChannels
276,318
276,318
class DropChannels(torch.nn.Module): """ Drops Channels with predefined probability values. Pads the dropped channels with `pad_value`. Channels can be tied using `tie_channels` For example, for RGBD input, RGB can be tied by using `tie_channels=[0,1,2]`. In this case, channels [0,1,2] will be d...
class DropChannels(torch.nn.Module): """ Drops Channels with predefined probability values. Pads the dropped channels with `pad_value`. Channels can be tied using `tie_channels` For example, for RGBD input, RGB can be tied by using `tie_channels=[0,1,2]`. In this case, channels [0,1,2] will be d...
assert isinstance(x, torch.Tensor) if x.ndim == 3: # CxHxW num_channels = x.shape[0] channel_index = 0 elif x.ndim == 4: # TxCxHxW num_channels = x.shape[1] channel_index = 1 else: raise ValueError(f"Unex...
assert isinstance(x, torch.Tensor) if x.ndim == 3: # CxHxW num_channels = x.shape[0] channel_index = 0 elif x.ndim == 4: # TxCxHxW num_channels = x.shape[1] channel_index = 1 else: raise ValueError(f"Unex...
134
415
503
918
# 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. # Modified from https://github.com/pytorch/vision/blob/main/references/classification/transforms.py import mat...
# 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. # Modified from https://github.com/pytorch/vision/blob/main/references/classification/transforms.py import mat...
45,216
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/examples/omnivore/data/transforms.py
146,147
112,218
forward
RandomCutmix
155,206
147,206
class RandomCutmix(torch.torch.nn.Module): """Randomly apply Cutmix to the provided batch and targets. The class implements the data augmentations as described in the paper `"CutMix: Regularization Strategy to Train Strong Classifiers with Localizable Features" <https://arxiv.org/abs/1905.04899>`_. ...
class RandomCutmix(torch.torch.nn.Module): """Randomly apply Cutmix to the provided batch and targets. The class implements the data augmentations as described in the paper `"CutMix: Regularization Strategy to Train Strong Classifiers with Localizable Features" <https://arxiv.org/abs/1905.04899>`_. ...
if batch.ndim < 4: raise ValueError(f"Batch ndim should be 4. Got {batch.ndim}") if target.ndim != 1: raise ValueError(f"Target ndim should be 1. Got {target.ndim}") if not batch.is_floating_point(): raise TypeError(f"Batch dtype should be a float tensor. Got ...
""" Args: batch (Tensor): Float tensor of size (..., H, W) target (Tensor): Integer tensor of size (B, ) Returns: Tensor: Randomly transformed batch. """ if batch.ndim < 4: raise ValueError(f"Batch ndim should be 4. Got {batch.ndim...
201
535
747
1,282
# 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. # Modified from https://github.com/pytorch/vision/blob/main/references/classification/transforms.py import mat...
# 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. # Modified from https://github.com/pytorch/vision/blob/main/references/classification/transforms.py import mat...
45,217
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/examples/omnivore/data/transforms.py
54,55
19,112
forward
RandomMixup
63,100
55,100
class RandomMixup(torch.torch.nn.Module): """Randomly apply Mixup to the provided batch and targets. The class implements the data augmentations as described in the paper `"mixup: Beyond Empirical Risk Minimization" <https://arxiv.org/abs/1710.09412>`_. Args: num_classes (int): number of classe...
class RandomMixup(torch.torch.nn.Module): """Randomly apply Mixup to the provided batch and targets. The class implements the data augmentations as described in the paper `"mixup: Beyond Empirical Risk Minimization" <https://arxiv.org/abs/1710.09412>`_. Args: num_classes (int): number of classe...
if batch.ndim < 4: raise ValueError(f"Batch ndim should be 4. Got {batch.ndim}") if target.ndim != 1: raise ValueError(f"Target ndim should be 1. Got {target.ndim}") if not batch.is_floating_point(): raise TypeError(f"Batch dtype should be a float tensor. Got ...
""" Args: batch (Tensor): Float tensor of size (..., H, W) target (Tensor): Integer tensor of size (B, ) Returns: Tensor: Randomly transformed batch. """ if batch.ndim < 4: raise ValueError(f"Batch ndim should be 4. Got {batch.ndim...
125
541
480
1,021
# 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. # Modified from https://github.com/pytorch/vision/blob/main/references/classification/transforms.py import mat...
# 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. # Modified from https://github.com/pytorch/vision/blob/main/references/classification/transforms.py import mat...
45,218
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/examples/omnivore/data/transforms.py
223,224
218,227
forward
Unsqueeze
224,227
224,227
class Unsqueeze(torch.torch.nn.Module): def __init__(self, pos=0): super().__init__() self.pos = pos def forward(self, x): FILL_FUNC_BODY
class Unsqueeze(torch.torch.nn.Module): def __init__(self, pos=0): super().__init__() self.pos = pos def forward(self, x): FILL_FUNC_BODY
return x.unsqueeze(self.pos)
return x.unsqueeze(self.pos)
2
64
19
83
# 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. # Modified from https://github.com/pytorch/vision/blob/main/references/classification/transforms.py import mat...
# 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. # Modified from https://github.com/pytorch/vision/blob/main/references/classification/transforms.py import mat...
45,220
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/examples/omnivore/utils.py
191,192
183,197
ema_avg
ExponentialMovingAverage
192,194
192,194
class ExponentialMovingAverage(torch.optim.swa_utils.AveragedModel): """Maintains moving averages of model parameters using an exponential decay. ``ema_avg = decay * avg_model_param + (1 - decay) * model_param`` `torch.optim.swa_utils.AveragedModel <https://pytorch.org/docs/stable/optim.html#custom-averagin...
class ExponentialMovingAverage(torch.optim.swa_utils.AveragedModel): """Maintains moving averages of model parameters using an exponential decay. ``ema_avg = decay * avg_model_param + (1 - decay) * model_param`` `torch.optim.swa_utils.AveragedModel <https://pytorch.org/docs/stable/optim.html#custom-averagin...
return decay * avg_model_param + (1 - decay) * model_param
return decay * avg_model_param + (1 - decay) * model_param
10
205
24
229
# 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. # This file is modified from: # https://github.com/pytorch/vision/blob/main/references/classification/utils.py ...
# 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. # This file is modified from: # https://github.com/pytorch/vision/blob/main/references/classification/utils.py ...
45,221
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/examples/omnivore/utils.py
113,114
79,183
log_every
MetricLogger
114,183
114,183
class MetricLogger: def __init__(self, delimiter="\t"): self.meters = defaultdict(SmoothedValue) self.delimiter = delimiter def update(self, **kwargs): for k, v in kwargs.items(): if isinstance(v, torch.Tensor): v = v.item() assert isinstance(v, (...
class MetricLogger: def __init__(self, delimiter="\t"): self.meters = defaultdict(SmoothedValue) self.delimiter = delimiter def update(self, **kwargs): for k, v in kwargs.items(): if isinstance(v, torch.Tensor): v = v.item() assert isinstance(v, (...
i = 0 if not header: header = "" start_time = time.time() end = time.time() iter_time = SmoothedValue(fmt="{avg:.4f}") data_time = SmoothedValue(fmt="{avg:.4f}") space_fmt = ":" + str(len(str(len(iterable)))) + "d" if torch.cuda.is_available():...
i = 0 if not header: header = "" start_time = time.time() end = time.time() iter_time = SmoothedValue(fmt="{avg:.4f}") data_time = SmoothedValue(fmt="{avg:.4f}") space_fmt = ":" + str(len(str(len(iterable)))) + "d" if torch.cuda.is_available():...
149
365
731
1,096
# 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. # This file is modified from: # https://github.com/pytorch/vision/blob/main/references/classification/utils.py ...
# 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. # This file is modified from: # https://github.com/pytorch/vision/blob/main/references/classification/utils.py ...
45,222
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/examples/omnivore/utils.py
52,54
20,79
avg
SmoothedValue
54,57
54,57
class SmoothedValue: """Track a series of values and provide access to smoothed values over a window or the global series average. """ def __init__(self, window_size=20, fmt=None): if fmt is None: fmt = "{median:.4f} ({global_avg:.4f})" self.deque = deque(maxlen=window_size)...
class SmoothedValue: """Track a series of values and provide access to smoothed values over a window or the global series average. """ def __init__(self, window_size=20, fmt=None): if fmt is None: fmt = "{median:.4f} ({global_avg:.4f})" self.deque = deque(maxlen=window_size)...
d = torch.tensor(list(self.deque), dtype=torch.float32) return d.mean().item()
d = torch.tensor(list(self.deque), dtype=torch.float32) return d.mean().item()
6
456
39
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. # This file is modified from: # https://github.com/pytorch/vision/blob/main/references/classification/utils.py ...
# 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. # This file is modified from: # https://github.com/pytorch/vision/blob/main/references/classification/utils.py ...
45,223
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/examples/utils/common.py
16,22
1,78
store_model_weights
42,78
22,78
# 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 copy import hashlib import os from typing import Optional import torch from torch import nn def store...
# 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 copy import hashlib import os from typing import Optional import torch from torch import nn def store...
# Store the new model next to the checkpoint_path checkpoint_path = os.path.abspath(checkpoint_path) output_dir = os.path.dirname(checkpoint_path) # Deep copy to avoid side-effects on the model object. model = copy.deepcopy(model) checkpoint = torch.load(checkpoint_path, map_location="cpu") ...
""" This method can be used to prepare weights files for new models. It receives as input a model architecture and a checkpoint from the training script and produces a file with the weights ready for release. Code reference: https://github.com/pytorch/vision/blob/main/references/classificat...
135
419
517
936
# 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 copy import hashlib import os from typing import Optional import torch from torch import nn def store...
# 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 copy import hashlib import os from typing import Optional import torch from torch import nn def store...
45,224
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/setup.py
52,53
1,103
parse_args
53,63
53,63
#!/usr/bin/env python3 # 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 argparse import os import re import sys from datetime import date from setuptool...
#!/usr/bin/env python3 # 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 argparse import os import re import sys from datetime import date from setuptool...
parser = argparse.ArgumentParser(description="torchmultimodal setup") parser.add_argument( "--package_name", type=str, default="torchmultimodal", help="The name of this output wheel", ) return parser.parse_known_args(argv)
parser = argparse.ArgumentParser(description="torchmultimodal setup") parser.add_argument( "--package_name", type=str, default="torchmultimodal", help="The name of this output wheel", ) return parser.parse_known_args(argv)
17
901
96
997
#!/usr/bin/env python3 # 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 argparse import os import re import sys from datetime import date from setuptool...
#!/usr/bin/env python3 # 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 argparse import os import re import sys from datetime import date from setuptool...
45,226
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/diffusion_labs/models/adm_unet/adm.py
459,465
428,476
forward
ADMStack
465,476
465,476
class ADMStack(nn.Module): """A container that acts like a ModuleList of ADM blocks and handles passing timestep and context embeddings correctly to its children. Usually, blocks such as residual blocks consume timestep embeddings, while attention blocks consume optional contextual embeddings in addition ...
class ADMStack(nn.Module): """A container that acts like a ModuleList of ADM blocks and handles passing timestep and context embeddings correctly to its children. Usually, blocks such as residual blocks consume timestep embeddings, while attention blocks consume optional contextual embeddings in addition ...
h = x for name, block in zip(self._module_types, self._module_list): # noqa: B905 if name == ADMStackModuleType.ResidualBlock: h = block(h, residual_conditional_embedding) elif name == ADMStackModuleType.AttentionBlock: h = block(h, attention_cond...
h = x for name, block in zip(self._module_types, self._module_list): # noqa: B905 if name == ADMStackModuleType.ResidualBlock: h = block(h, residual_conditional_embedding) elif name == ADMStackModuleType.AttentionBlock: h = block(h, attention_cond...
34
528
127
655
# 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 Callable, Dict, List, Optional, Sequence, Tuple, Union import torch 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 enum import Enum from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union import torch f...
45,229
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/diffusion_labs/models/adm_unet/attention_block.py
57,62
16,74
forward
ADMAttentionBlock
62,74
62,74
class ADMAttentionBlock(nn.Module): """Attention block in the ADM net that consists of group norm, multihead attention, and a residual connection. Follows the architecture described in "Diffusion Models Beat GANs on Image Synthesis" (https://arxiv.org/abs/2105.05233) Code ref: https://github.com/o...
class ADMAttentionBlock(nn.Module): """Attention block in the ADM net that consists of group norm, multihead attention, and a residual connection. Follows the architecture described in "Diffusion Models Beat GANs on Image Synthesis" (https://arxiv.org/abs/2105.05233) Code ref: https://github.com/o...
norm_out = self.norm(x) # [b, c, h, w] -> [b, h, w, c] norm_out = shift_dim(norm_out, 1, -1) attn_out = self.attn(norm_out, conditional_embedding=conditional_embedding) # [b, h, w, c] -> [b, c, h, w] attn_out = shift_dim(attn_out, -1, 1) if self.rescale_skip_conne...
norm_out = self.norm(x) # [b, c, h, w] -> [b, h, w, c] norm_out = shift_dim(norm_out, 1, -1) attn_out = self.attn(norm_out, conditional_embedding=conditional_embedding) # [b, h, w, c] -> [b, c, h, w] attn_out = shift_dim(attn_out, -1, 1) if self.rescale_skip_conne...
50
659
184
843
# 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 from torchmultimodal.modules.layers.atte...
# 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 from torchmultimodal.modules.layers.atte...
45,230
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/diffusion_labs/models/adm_unet/attention_block.py
104,111
74,155
forward
ADMCrossAttention
111,155
111,155
class ADMCrossAttention(nn.Module): """Similar to standard cross-attention, except conditioning inputs are passed through a separate projection and then concatenated with the key and value vectors before scaled dot product attention. Code ref: https://fburl.com/code/rxl1md57 Attributes: dim_qk...
class ADMCrossAttention(nn.Module): """Similar to standard cross-attention, except conditioning inputs are passed through a separate projection and then concatenated with the key and value vectors before scaled dot product attention. Code ref: https://fburl.com/code/rxl1md57 Attributes: dim_qk...
_, n_head, *spatial_dims, dim_q = q.shape dim_q = dim_q * n_head dim_k = k.shape[-1] * n_head dim_v = v.shape[-1] * n_head if self.dim_qkv != dim_q or self.dim_qkv != dim_k or self.dim_qkv != dim_v: raise ValueError( f"The embedding dim of q, k, v does...
_, n_head, *spatial_dims, dim_q = q.shape dim_q = dim_q * n_head dim_k = k.shape[-1] * n_head dim_v = v.shape[-1] * n_head if self.dim_qkv != dim_q or self.dim_qkv != dim_k or self.dim_qkv != dim_v: raise ValueError( f"The embedding dim of q, k, v does...
223
507
749
1,256
# 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 from torchmultimodal.modules.layers.atte...
# 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 from torchmultimodal.modules.layers.atte...
45,232
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/diffusion_labs/models/adm_unet/res_block.py
119,124
12,146
forward
ADMResBlock
124,146
124,146
class ADMResBlock(nn.Module): """Residual block in the ADM net. Supports projecting a conditional embedding to add to the hidden state. This typically contains the timestep embedding, but can also contain class embedding for classifier free guidance, CLIP image embedding and text encoder output for text-to-...
class ADMResBlock(nn.Module): """Residual block in the ADM net. Supports projecting a conditional embedding to add to the hidden state. This typically contains the timestep embedding, but can also contain class embedding for classifier free guidance, CLIP image embedding and text encoder output for text-to-...
t = self.cond_proj(conditional_embedding) # [b, c] -> [b, c, 1, 1] t = t.unsqueeze(-1).unsqueeze(-1) skip = self.skip_block(x) h = self.in_block(x) # If specified, split conditional embedding into two separate projections. # Use half to multiply with hidden state ...
t = self.cond_proj(conditional_embedding) # [b, c] -> [b, c, 1, 1] t = t.unsqueeze(-1).unsqueeze(-1) skip = self.skip_block(x) h = self.in_block(x) # If specified, split conditional embedding into two separate projections. # Use half to multiply with hidden state ...
95
1,700
287
1,987
# 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 from torchmultimodal.modules.layers.normalizations import Fp32GroupNo...
# 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 from torchmultimodal.modules.layers.normalizations import Fp32GroupNo...
45,233
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/diffusion_labs/models/dalle2/dalle2_decoder.py
19,39
1,109
dalle2_decoder
75,109
39,109
# 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 torchmultimodal.diffusion_labs.models.adm_unet.adm import adm_unet from torchmultimodal.diffu...
# 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 torchmultimodal.diffusion_labs.models.adm_unet.adm import adm_unet from torchmultimodal.diffu...
# Construct UNet diffusion_model = adm_unet( time_embed_dim=time_embed_dim, cond_embed_dim=cond_embed_dim, embed_dim=clip_embed_dim, embed_name=clip_embed_name, predict_variance_value=predict_variance_value, image_channels=image_channels, depth=depth, ...
"""Constructs primary DALLE-2 diffusion decoder without upsampling. Consists of an ADM UNet diffusion model conditioned on CLIP image embeddings. Uses DDPM to generate images. Ref: https://arxiv.org/abs/2204.06125 Follows parameters in this config: https://fburl.com/code/jyi0nhdt Args: ...
69
1,085
423
1,508
# 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 torchmultimodal.diffusion_labs.models.adm_unet.adm import adm_unet from torchmultimodal.diffu...
# 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 torchmultimodal.diffusion_labs.models.adm_unet.adm import adm_unet from torchmultimodal.diffu...
45,234
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/diffusion_labs/models/dalle2/transforms.py
51,52
18,61
forward
Dalle2ImageTransform
52,61
52,61
class Dalle2ImageTransform(nn.Module): """Dalle image transform normalizes the data between a min and max value. Defaults are -1 and 1 like the Dalle2 Paper. Args: image_size (int): desired output image size. image_min (float): min of images, used for normalization. image_max (float...
class Dalle2ImageTransform(nn.Module): """Dalle image transform normalizes the data between a min and max value. Defaults are -1 and 1 like the Dalle2 Paper. Args: image_size (int): desired output image size. image_min (float): min of images, used for normalization. image_max (float...
assert self.image in x, f"{type(self).__name__} expects key {self.image}" image = x[self.image] if isinstance(image, Image): im = self.image_transform(image) else: # pyre-ignore im = torch.stack([self.image_transform(x) for x in image]) x[self....
assert self.image in x, f"{type(self).__name__} expects key {self.image}" image = x[self.image] if isinstance(image, Image): im = self.image_transform(image) else: # pyre-ignore im = torch.stack([self.image_transform(x) for x in image]) x[self....
32
347
115
462
# 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, Dict import torch import torchvision.transforms as tv fr...
# 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, Dict import torch import torchvision.transforms as tv fr...
45,235
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/diffusion_labs/models/vae/attention.py
102,107
1,110
attention_res_block
107,110
107,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 collections import OrderedDict import torch from torch import nn, Tensor from torch.nn import functional ...
# 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 import torch from torch import nn, Tensor from torch.nn import functional ...
return AttentionResBlock( channels, VanillaAttention(channels), norm_groups, norm_eps )
return AttentionResBlock( channels, VanillaAttention(channels), norm_groups, norm_eps )
7
1,403
33
1,436
# 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 import torch from torch import nn, Tensor from torch.nn import functional ...
# 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 import torch from torch import nn, Tensor from torch.nn import functional ...
45,236
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/diffusion_labs/models/vae/attention.py
62,63
15,66
forward
AttentionResBlock
63,66
63,66
class AttentionResBlock(nn.Module): """Attention block in the LDM Autoencoder that consists of group norm, attention, conv projection and a residual connection. Follows the architecture described in "High-Resolution Image Synthesis with Latent Diffusion Models" (https://arxiv.org/abs/2112.10752) C...
class AttentionResBlock(nn.Module): """Attention block in the LDM Autoencoder that consists of group norm, attention, conv projection and a residual connection. Follows the architecture described in "High-Resolution Image Synthesis with Latent Diffusion Models" (https://arxiv.org/abs/2112.10752) C...
return self.net(x) + x
return self.net(x) + x
4
613
16
629
# 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 import torch from torch import nn, Tensor from torch.nn import functional ...
# 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 import torch from torch import nn, Tensor from torch.nn import functional ...
45,237
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/diffusion_labs/models/vae/attention.py
91,92
66,102
forward
VanillaAttention
92,102
92,102
class VanillaAttention(nn.Module): """Attention module used in the LDM Autoencoder. Similar to standard Q, k V attention, but using 2d convolutions instead of linear projections for obtaining q, k, v tensors. Follows the architecture described in "High-Resolution Image Synthesis with Latent Diffusion M...
class VanillaAttention(nn.Module): """Attention module used in the LDM Autoencoder. Similar to standard Q, k V attention, but using 2d convolutions instead of linear projections for obtaining q, k, v tensors. Follows the architecture described in "High-Resolution Image Synthesis with Latent Diffusion M...
q, k, v = self.query(x), self.key(x), self.value(x) B, C, H, W = q.shape # [B, C, H, W] -> [B, H*W, C] q, k, v = (t.reshape(B, C, H * W).permute(0, 2, 1) for t in (q, k, v)) # [B, H*W, C] out = F.scaled_dot_product_attention(q, k, v) # [B, H*W, C] -> [B, C, H, W] ...
q, k, v = self.query(x), self.key(x), self.value(x) B, C, H, W = q.shape # [B, C, H, W] -> [B, H*W, C] q, k, v = (t.reshape(B, C, H * W).permute(0, 2, 1) for t in (q, k, v)) # [B, H*W, C] out = F.scaled_dot_product_attention(q, k, v) # [B, H*W, C] -> [B, C, H, W] ...
64
433
202
635
# 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 import torch from torch import nn, Tensor from torch.nn import functional ...
# 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 import torch from torch import nn, Tensor from torch.nn import functional ...
45,239
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/diffusion_labs/models/vae/encoder_decoder.py
249,250
130,265
forward
ResNetDecoder
250,265
250,265
class ResNetDecoder(nn.Module): """Resnet decoder used in the LDM Autoencoder that consists of a init convolution, middle resnet blocks with attention, upsamling resnet blocks and output convolution block with group normalization and nonlinearity. Optionally, also supports alpha channel in output. ...
class ResNetDecoder(nn.Module): """Resnet decoder used in the LDM Autoencoder that consists of a init convolution, middle resnet blocks with attention, upsamling resnet blocks and output convolution block with group normalization and nonlinearity. Optionally, also supports alpha channel in output. ...
h = self.init_conv(z) h = self.mid_block(h) h = self.up_block(h) h = self.out_nonlinearity_block(h) # If alpha channel is required as output, compute it separately with its # own conv layer and concatenate with the output from the out convolulution if self.output...
h = self.init_conv(z) h = self.mid_block(h) h = self.up_block(h) h = self.out_nonlinearity_block(h) # If alpha channel is required as output, compute it separately with its # own conv layer and concatenate with the output from the out convolulution if self.output...
51
1,388
168
1,556
# 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 Sequence 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 functools import partial from typing import Sequence import torch from torch import nn, Tensor from torch...
45,240
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/diffusion_labs/models/vae/encoder_decoder.py
122,123
21,130
forward
ResNetEncoder
123,130
123,130
class ResNetEncoder(nn.Module): """Resnet encoder used in the LDM Autoencoder that consists of a init convolution, downsampling resnet blocks, middle resnet blocks with attention and output convolution block with group normalization and nonlinearity. Follows the architecture described in "High-Resoluti...
class ResNetEncoder(nn.Module): """Resnet encoder used in the LDM Autoencoder that consists of a init convolution, downsampling resnet blocks, middle resnet blocks with attention and output convolution block with group normalization and nonlinearity. Follows the architecture described in "High-Resoluti...
h = self.init_conv(x) h = self.down_block(h) h = self.mid_block(h) h = self.out_block(h) return h
h = self.init_conv(x) h = self.down_block(h) h = self.mid_block(h) h = self.out_block(h) return h
14
1,192
61
1,253
# 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 Sequence 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 functools import partial from typing import Sequence import torch from torch import nn, Tensor from torch...
45,243
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/diffusion_labs/models/vae/residual_sampling.py
67,68
35,69
forward
Downsample2D
68,69
68,69
class Downsample2D(nn.Module): """2-Dimensional downsampling layer with zero padding and 2D convolution, used for image encoders. Code ref: https://github.com/CompVis/latent-diffusion/blob/main/ldm/modules/diffusionmodules/openaimodel.py#L134 Attributes: channels (int): Number of channels ...
class Downsample2D(nn.Module): """2-Dimensional downsampling layer with zero padding and 2D convolution, used for image encoders. Code ref: https://github.com/CompVis/latent-diffusion/blob/main/ldm/modules/diffusionmodules/openaimodel.py#L134 Attributes: channels (int): Number of channels ...
return self.op(x)
return self.op(x)
2
336
10
346
# 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, Union from torch import nn as nn, Tensor from torch.nn import functional as F clas...
# 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, Union from torch import nn as nn, Tensor from torch.nn import functional as F clas...
45,244
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/diffusion_labs/models/vae/residual_sampling.py
31,32
13,35
forward
Upsample2D
32,35
32,35
class Upsample2D(nn.Module): """2-Dimensional upsampling layer with nearest neighbor interpolation and 2D convolution, used for image decoders. Code ref: https://github.com/CompVis/latent-diffusion/blob/main/ldm/modules/diffusionmodules/openaimodel.py#L91 Attributes: channels (int): Number...
class Upsample2D(nn.Module): """2-Dimensional upsampling layer with nearest neighbor interpolation and 2D convolution, used for image decoders. Code ref: https://github.com/CompVis/latent-diffusion/blob/main/ldm/modules/diffusionmodules/openaimodel.py#L91 Attributes: channels (int): Number...
return self.conv(F.interpolate(x, scale_factor=2, mode="nearest"))
return self.conv(F.interpolate(x, scale_factor=2, mode="nearest"))
4
218
32
250
# 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, Union from torch import nn as nn, Tensor from torch.nn import functional as F clas...
# 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, Union from torch import nn as nn, Tensor from torch.nn import functional as F clas...
45,245
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/diffusion_labs/models/vae/vae.py
76,90
1,143
ldm_variational_autoencoder
90,143
90,143
# 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 NamedTuple, Sequence import torch 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 NamedTuple, Sequence import torch from torch import nn,...
encoder = nn.Sequential( # pyre-ignore OrderedDict( [ ( "resnet_encoder", ResNetEncoder( in_channels=in_channels, z_channels=z_channels, channels=channels, ...
encoder = nn.Sequential( # pyre-ignore OrderedDict( [ ( "resnet_encoder", ResNetEncoder( in_channels=in_channels, z_channels=z_channels, channels=channels, ...
67
985
483
1,468
# 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 NamedTuple, Sequence import torch 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 NamedTuple, Sequence import torch from torch import nn,...
45,246
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/diffusion_labs/models/vae/vae.py
53,54
24,76
encode
VariationalAutoencoder
54,63
54,63
class VariationalAutoencoder(nn.Module): """Variational Autoencoder (https://arxiv.org/abs/1906.02691) is a special type of autoencoder where the encoder outputs the the parameters of the posterior latent distribution instead of outputting fixed vectors in the latent space. The decoder consumes a sample fro...
class VariationalAutoencoder(nn.Module): """Variational Autoencoder (https://arxiv.org/abs/1906.02691) is a special type of autoencoder where the encoder outputs the the parameters of the posterior latent distribution instead of outputting fixed vectors in the latent space. The decoder consumes a sample fro...
h = self.encoder(x) # output of encoder is mean and log variaance of a normal distribution mean, log_variance = torch.chunk(h, 2, dim=1) # clamp logvariance to [-30. 20] log_variance = torch.clamp(log_variance, -30.0, 20.0) stddev = torch.exp(log_variance / 2.0) p...
h = self.encoder(x) # output of encoder is mean and log variaance of a normal distribution mean, log_variance = torch.chunk(h, 2, dim=1) # clamp logvariance to [-30. 20] log_variance = torch.clamp(log_variance, -30.0, 20.0) stddev = torch.exp(log_variance / 2.0) p...
44
523
144
667
# 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 NamedTuple, Sequence import torch 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 NamedTuple, Sequence import torch from torch import nn,...
45,248
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/diffusion_labs/modules/adapters/inpainting.py
45,51
16,64
forward
InPainting
51,64
51,64
class InPainting(nn.Module, Adapter): """Inpainting masks a target artifact during generation to infill the masked region. This approach is based on "Palette: Image-to-Image Diffusion Models" (https://arxiv.org/abs/2111.05826) and "GLIDE: Towards Photorealistic Image Generation and Editing with Text-Gui...
class InPainting(nn.Module, Adapter): """Inpainting masks a target artifact during generation to infill the masked region. This approach is based on "Palette: Image-to-Image Diffusion Models" (https://arxiv.org/abs/2111.05826) and "GLIDE: Towards Photorealistic Image Generation and Editing with Text-Gui...
if ( conditional_inputs and self.target_name in conditional_inputs and self.mask_name in conditional_inputs ): target = conditional_inputs[self.target_name] mask = conditional_inputs[self.mask_name] masked_target = target * mask ...
if ( conditional_inputs and self.target_name in conditional_inputs and self.mask_name in conditional_inputs ): target = conditional_inputs[self.target_name] mask = conditional_inputs[self.mask_name] masked_target = target * mask ...
41
485
178
663
# 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, Optional import torch from torch import nn, Tensor from torchmultimodal.diffusion_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 Dict, Optional import torch from torch import nn, Tensor from torchmultimodal.diffusion_la...
45,249
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/diffusion_labs/modules/adapters/super_resolution.py
61,67
17,84
forward
SuperResolution
67,84
67,84
class SuperResolution(nn.Module, Adapter): """ A wrapper for super resolution training. Takes a low resolution input from the conditional input and scales it accordingly to be appended to the input. The new input will have 2x total channels, and the inner model should expect this larger input. Attr...
class SuperResolution(nn.Module, Adapter): """ A wrapper for super resolution training. Takes a low resolution input from the conditional input and scales it accordingly to be appended to the input. The new input will have 2x total channels, and the inner model should expect this larger input. Attr...
if conditional_inputs: low_res = conditional_inputs.get(self.low_res_name, torch.zeros_like(x)) else: low_res = torch.zeros_like(x) # upsample to target resolution if not already at target resolution if x.size() != low_res.size(): low_res = F.interpola...
if conditional_inputs: low_res = conditional_inputs.get(self.low_res_name, torch.zeros_like(x)) else: low_res = torch.zeros_like(x) # upsample to target resolution if not already at target resolution if x.size() != low_res.size(): low_res = F.interpola...
50
577
251
828
# 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, Optional import torch import torch.nn.functional as F from torch import nn, 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 Dict, Optional import torch import torch.nn.functional as F from torch import nn, Tensor f...
45,250
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/diffusion_labs/modules/losses/diffusion_hybrid_loss.py
50,60
15,66
forward
DiffusionHybridLoss
60,66
60,66
class DiffusionHybridLoss(nn.Module): """ Combines both simple loss (typically MSE) and VLB loss weighted by lambda, as described in Eq. 16 of "Improved Denoising Diffusion Probabilistic Models" (https://arxiv.org/abs/2102.09672). VLB loss is only used to train the model learned variance. Attribute...
class DiffusionHybridLoss(nn.Module): """ Combines both simple loss (typically MSE) and VLB loss weighted by lambda, as described in Eq. 16 of "Improved Denoising Diffusion Probabilistic Models" (https://arxiv.org/abs/2102.09672). VLB loss is only used to train the model learned variance. Attribute...
# Detach mean as stop gradient for vlb loss # Weight the vlb loss smaller, for stability, when training in a hybrid setting using # another criterion to train the predictor as in the paper (recommended 0.001) return self.simple_loss(input, target) + self.lmbda * self.vlb_loss( ...
# Detach mean as stop gradient for vlb loss # Weight the vlb loss smaller, for stability, when training in a hybrid setting using # another criterion to train the predictor as in the paper (recommended 0.001) return self.simple_loss(input, target) + self.lmbda * self.vlb_loss( ...
50
563
112
675
# 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 from torchmultimodal.diffusion_labs.modules.losses.vlb_loss import VL...
# 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 from torchmultimodal.diffusion_labs.modules.losses.vlb_loss import VL...
45,251
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/diffusion_labs/modules/losses/vlb_loss.py
51,59
16,120
discretized_gaussian_log_likelihood
VLBLoss
59,82
59,82
class VLBLoss(nn.Module): """VLBLoss minimizes the KL divergence between the distribution of the forward diffusion process (noising) and the learned reverse process (denoising). Its name is derived from the Variational Lower Bound which is being optimized. This loss function can be used on it's own or used ...
class VLBLoss(nn.Module): """VLBLoss minimizes the KL divergence between the distribution of the forward diffusion process (noising) and the learned reverse process (denoising). Its name is derived from the Variational Lower Bound which is being optimized. This loss function can be used on it's own or used ...
if not x.shape == mean.shape == log_scale.shape: ValueError("x, mean, and log_scale must all be the same shape") # TODO: lucidrain found eps = 1e-3 worked better for fp16 centered_x = x - mean inv_stdv = torch.exp(-log_scale) plus_in = inv_stdv * (centered_x + 1.0 / 2...
if not x.shape == mean.shape == log_scale.shape: ValueError("x, mean, and log_scale must all be the same shape") # TODO: lucidrain found eps = 1e-3 worked better for fp16 centered_x = x - mean inv_stdv = torch.exp(-log_scale) plus_in = inv_stdv * (centered_x + 1.0 / 2...
90
1,042
365
1,407
# 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 torch from torch import nn, Tensor from torchmultimodal.diffusion_labs.schedules.discrete_g...
# 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 torch from torch import nn, Tensor from torchmultimodal.diffusion_labs.schedules.discrete_g...
45,252
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/diffusion_labs/predictors/noise_predictor.py
31,32
16,42
predict_x0
NoisePredictor
32,40
32,40
class NoisePredictor(Predictor): """Given a model that's trained to predict diffusion noise and corresponding schedule, this class computes the predicted noise and x0 at step t. Attributes: schedule (DiffusionSchedule): defines diffusion of noise through time clamp_func (Callable): func...
class NoisePredictor(Predictor): """Given a model that's trained to predict diffusion noise and corresponding schedule, this class computes the predicted noise and x0 at step t. Attributes: schedule (DiffusionSchedule): defines diffusion of noise through time clamp_func (Callable): func...
shape, dtype = xt.shape, xt.dtype x_coef = self.schedule("sqrt_recip_alphas_cumprod", t, shape) e_coef = self.schedule("sqrt_recip_alphas_cumprod_minus_one", t, shape) x0 = x_coef * xt - e_coef * prediction if self.clamp_func is not None: x0 = self.clamp_func(x0) ...
shape, dtype = xt.shape, xt.dtype x_coef = self.schedule("sqrt_recip_alphas_cumprod", t, shape) e_coef = self.schedule("sqrt_recip_alphas_cumprod_minus_one", t, shape) x0 = x_coef * xt - e_coef * prediction if self.clamp_func is not None: x0 = self.clamp_func(x0) ...
34
219
144
363
# 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 from torch import Tensor from torchmultimodal.diffusion_labs.predictors....
# 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 from torch import Tensor from torchmultimodal.diffusion_labs.predictors....
45,253
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/diffusion_labs/predictors/target_predictor.py
31,32
16,43
predict_x0
TargetPredictor
32,36
32,36
class TargetPredictor(Predictor): """Given a model that's trained to predict x0 and corresponding schedule, this class computes the predicted noise and x0 at step t. Attributes: schedule (DiffusionSchedule): defines diffusion of noise through time clamp_func (Callable): function to clam...
class TargetPredictor(Predictor): """Given a model that's trained to predict x0 and corresponding schedule, this class computes the predicted noise and x0 at step t. Attributes: schedule (DiffusionSchedule): defines diffusion of noise through time clamp_func (Callable): function to clam...
if self.clamp_func is not None: prediction = self.clamp_func(prediction) return prediction
if self.clamp_func is not None: prediction = self.clamp_func(prediction) return prediction
10
342
36
378
# 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 from torch import Tensor from torchmultimodal.diffusion_labs.predictors....
# 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 from torch import Tensor from torchmultimodal.diffusion_labs.predictors....
45,254
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/diffusion_labs/predictors/v_predictor.py
44,45
16,51
predict_noise
VPredictor
45,51
45,51
class VPredictor(Predictor): """Given a model that's trained to predict v and corresponding schedule, this class computes the predicted noise and x0 at step t. V is an interpolation between x0 and noise designed to keep the prediciton target stable as Signal to Noise (SNR) ratio varies through the diffu...
class VPredictor(Predictor): """Given a model that's trained to predict v and corresponding schedule, this class computes the predicted noise and x0 at step t. V is an interpolation between x0 and noise designed to keep the prediciton target stable as Signal to Noise (SNR) ratio varies through the diffu...
shape, dtype = xt.shape, xt.dtype x_coef = self.schedule("sqrt_recip_alphas_cumprod", t, shape) e_coef = self.schedule("sqrt_recip_alphas_cumprod_minus_one", t, shape) x0 = self.predict_x0(prediction, xt, t) e = (x_coef * xt - x0) / e_coef return e.to(dtype)
shape, dtype = xt.shape, xt.dtype x_coef = self.schedule("sqrt_recip_alphas_cumprod", t, shape) e_coef = self.schedule("sqrt_recip_alphas_cumprod_minus_one", t, shape) x0 = self.predict_x0(prediction, xt, t) e = (x_coef * xt - x0) / e_coef return e.to(dtype)
31
435
134
569
# 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 from torch import Tensor from torchmultimodal.diffusion_labs.predictors....
# 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 from torch import Tensor from torchmultimodal.diffusion_labs.predictors....
45,255
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/diffusion_labs/samplers/ddim.py
135,140
19,171
generator
DDIModule
141,150
140,150
class DDIModule(nn.Module, Sampler): """ DDIModule implements "Denoising Diffusion Implicit Models" presented by Song et. al (https://arxiv.org/abs/2010.02502). DDIMs are a class of iterative implicit probabilistic models that has the same training procedure as DDPMs, but can produce high quality s...
class DDIModule(nn.Module, Sampler): """ DDIModule implements "Denoising Diffusion Implicit Models" presented by Song et. al (https://arxiv.org/abs/2010.02502). DDIMs are a class of iterative implicit probabilistic models that has the same training procedure as DDPMs, but can produce high quality s...
steps = self.eval_steps.flip(0) for step, next_step in zip(steps[:-1], steps[1:]): # Convert steps to batched tensors t = step * torch.ones(x.size(0), device=x.device, dtype=torch.long) t1 = next_step * torch.ones(x.size(0), device=x.device, dtype=torch.long) ...
"""Generate xt for each t in self.eval_steps""" steps = self.eval_steps.flip(0) for step, next_step in zip(steps[:-1], steps[1:]): # Convert steps to batched tensors t = step * torch.ones(x.size(0), device=x.device, dtype=torch.long) t1 = next_step * torch.one...
45
1,548
156
1,704
# 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, Generator, Iterable, Optional, Union import torch from torch import nn, Tensor from t...
# 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, Generator, Iterable, Optional, Union import torch from torch import nn, Tensor from t...
45,259
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/diffusion_labs/transforms/diffusion_transform.py
49,50
13,67
forward
RandomDiffusionSteps
50,67
50,67
class RandomDiffusionSteps(nn.Module): """Data Transform to randomly sample noised data from the diffusion schedule. During diffusion training, random diffusion steps are sampled per model update. This transform samples steps and returns the steps (t), seed noise (noise), and transformed data at time t ...
class RandomDiffusionSteps(nn.Module): """Data Transform to randomly sample noised data from the diffusion schedule. During diffusion training, random diffusion steps are sampled per model update. This transform samples steps and returns the steps (t), seed noise (noise), and transformed data at time t ...
assert self.x0 in x, f"{type(self).__name__} expects key {self.x0}" x0 = x[self.x0] if not self.batched: t = self.schedule.sample_steps(x0.unsqueeze(0)) t = t.squeeze(0) else: t = self.schedule.sample_steps(x0) noise = self.schedule.sample_nois...
assert self.x0 in x, f"{type(self).__name__} expects key {self.x0}" x0 = x[self.x0] if not self.batched: t = self.schedule.sample_steps(x0.unsqueeze(0)) t = t.squeeze(0) else: t = self.schedule.sample_steps(x0) noise = self.schedule.sample_nois...
44
396
203
599
# 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 from torch import nn from torchmultimodal.diffusion_labs.schedules.schedule 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 typing import Any, Dict from torch import nn from torchmultimodal.diffusion_labs.schedules.schedule impor...
45,260
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/diffusion_labs/transforms/super_resolution_transform.py
59,60
14,89
forward
SuperResolutionTransform
60,89
60,89
class SuperResolutionTransform(nn.Module): """Data transform to generate small image for training with super resolution. Attributes: size (int): expected size of data low_res_size (int): size of scaled down data data_field (str): key name for data low_res_field (str): key name f...
class SuperResolutionTransform(nn.Module): """Data transform to generate small image for training with super resolution. Attributes: size (int): expected size of data low_res_size (int): size of scaled down data data_field (str): key name for data low_res_field (str): key name f...
assert ( self.data_field in x ), f"{type(self).__name__} expects key {self.data_field}" data = x[self.data_field] # downsample down_scaled = F.interpolate( data, size=self.low_res_size, mode=self.mode, antialias=self.ant...
assert ( self.data_field in x ), f"{type(self).__name__} expects key {self.data_field}" data = x[self.data_field] # downsample down_scaled = F.interpolate( data, size=self.low_res_size, mode=self.mode, antialias=self.ant...
63
486
367
853
# 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, Dict, Optional import torch.nn.functional as F from torch import nn 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 Any, Callable, Dict, Optional import torch.nn.functional as F from torch import nn class...
45,261
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/diffusion_labs/transforms/v_transform.py
47,48
15,58
forward
ComputeV
48,58
48,58
class ComputeV(nn.Module): """Data transform to compute v prediction target from x0 and noise. This transfrom is meant to be used with the VPredictor. V is first proposed in "Progressive Distillation for Fast Sampling of Diffusion Models" by Salimans and Ho (https://arxiv.org/abs/2202.00512). Attri...
class ComputeV(nn.Module): """Data transform to compute v prediction target from x0 and noise. This transfrom is meant to be used with the VPredictor. V is first proposed in "Progressive Distillation for Fast Sampling of Diffusion Models" by Salimans and Ho (https://arxiv.org/abs/2202.00512). Attri...
assert self.x0 in x, f"{type(self).__name__} expects key {self.x0}" assert self.t in x, f"{type(self).__name__} expects key {self.t}" assert self.noise in x, f"{type(self).__name__} expects key {self.noise}" x0, t, noise = x[self.x0], x[self.t], x[self.noise] shape, dtype = x0.sh...
assert self.x0 in x, f"{type(self).__name__} expects key {self.x0}" assert self.t in x, f"{type(self).__name__} expects key {self.t}" assert self.noise in x, f"{type(self).__name__} expects key {self.noise}" x0, t, noise = x[self.x0], x[self.t], x[self.noise] shape, dtype = x0.sh...
60
365
229
594
# 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 from torch import nn from torchmultimodal.diffusion_labs.schedules.discrete_gauss...
# 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 from torch import nn from torchmultimodal.diffusion_labs.schedules.discrete_gauss...
45,262
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/albef/image_encoder.py
73,74
14,75
forward
ALBEFVisionEncoder
74,75
74,75
class ALBEFVisionEncoder(nn.Module): """ Modified VisionTransformer used by ALBEF. This class returns the output of the encoder ('encoder.ln'), without passing it to the heads. Args: image_size (int): The size (resolution) of each image. Default is 256. patch_size (int) The...
class ALBEFVisionEncoder(nn.Module): """ Modified VisionTransformer used by ALBEF. This class returns the output of the encoder ('encoder.ln'), without passing it to the heads. Args: image_size (int): The size (resolution) of each image. Default is 256. patch_size (int) The...
return self.encoder(x)[self.encoder_layer_name]
return self.encoder(x)[self.encoder_layer_name]
2
660
20
680
# 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 torch import nn, Tensor from torchvision.models.feature_extraction import c...
# 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 torch import nn, Tensor from torchvision.models.feature_extraction import c...
45,263
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/albef/multimodal_encoder.py
239,246
184,258
forward
ALBEFMultimodalEncoder
246,258
246,258
class ALBEFMultimodalEncoder(nn.Module): """ Construct multimodal embeddings from image embeddings, text embeddings, and text attention mask. The ALBEFMultimodalEncoder is similar to ALBEFTextEncoder, with the addition of image-text cross attention in encoder layers. Args: hidden_size (int): D...
class ALBEFMultimodalEncoder(nn.Module): """ Construct multimodal embeddings from image embeddings, text embeddings, and text attention mask. The ALBEFMultimodalEncoder is similar to ALBEFTextEncoder, with the addition of image-text cross attention in encoder layers. Args: hidden_size (int): D...
attention_mask = get_extended_attention_mask(attention_mask) if encoder_attention_mask is not None: encoder_attention_mask = get_extended_attention_mask(encoder_attention_mask) for layer_module in self.layer: hidden_states = layer_module( hidden_states, ...
attention_mask = get_extended_attention_mask(attention_mask) if encoder_attention_mask is not None: encoder_attention_mask = get_extended_attention_mask(encoder_attention_mask) for layer_module in self.layer: hidden_states = layer_module( hidden_states, ...
25
751
144
895
# 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 from torch import nn, Tensor from torchmultimodal.modules.layers.attent...
# 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 from torch import nn, Tensor from torchmultimodal.modules.layers.attent...
45,264
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/albef/multimodal_encoder.py
106,107
17,184
_feedforward_block
TransformerCrossAttentionLayer
107,111
107,111
class TransformerCrossAttentionLayer(nn.Module): """Transformer layer with self-attention on inputs and cross-attention on an encoder's outputs. Can be used in a transformer decoder or an encoder with cross-attention. Similar to ``nn.TransformerDecoderLayer``, but generalized for use in an encoder with cros...
class TransformerCrossAttentionLayer(nn.Module): """Transformer layer with self-attention on inputs and cross-attention on an encoder's outputs. Can be used in a transformer decoder or an encoder with cross-attention. Similar to ``nn.TransformerDecoderLayer``, but generalized for use in an encoder with cros...
h = self.feedforward(hidden_states) h = self.feedforward_dropout(h) return h
h = self.feedforward(hidden_states) h = self.feedforward_dropout(h) return h
8
1,902
36
1,938
# 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 from torch import nn, Tensor from torchmultimodal.modules.layers.attent...
# 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 from torch import nn, Tensor from torchmultimodal.modules.layers.attent...
45,265
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/blip2/blip2.py
91,97
39,158
forward
BLIP2
106,158
97,158
class BLIP2(nn.Module): """ BLIP2(https://arxiv.org/pdf/2301.12597.pdf) provides a pre-training strategy to bootstrap vision-language pre-training from frozen image encoders and frozen large language models(LLM). BLIP-2 bridges the modality gap and facilitates cross-modal alignment via Querying Transfor...
class BLIP2(nn.Module): """ BLIP2(https://arxiv.org/pdf/2301.12597.pdf) provides a pre-training strategy to bootstrap vision-language pre-training from frozen image encoders and frozen large language models(LLM). BLIP-2 bridges the modality gap and facilitates cross-modal alignment via Querying Transfor...
vision_encoder_output = self.vision_encoder(image) if isinstance(vision_encoder_output, TransformerOutput): vision_encoder_output = vision_encoder_output.last_hidden_state assert vision_encoder_output is not None image_embeds = self.ln_vision(vision_encoder_output) # ...
""" Args: image(Tensor): Image input tensor with shape [B, C, H, W] input_ids(Optional[Tensor]): Text input tensor with shape [bsz, seq_len] attention_mask(Optional[Tensor]): Attention mask tensor with shape [bsz, seq_len] Returns: return BLIP2 mo...
129
942
714
1,656
# 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 import torch from torch import nn, Tensor from torch.nn import funct...
# 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 import torch from torch import nn, Tensor from torch.nn import funct...
45,266
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/blip2/qformer_layers.py
346,353
312,388
forward
QformerEmbedding
365,388
353,388
class QformerEmbedding(nn.Module): """ Qformer embedding module. Args: embedding_dim (int): dim of embedding space max_position_embeddings (int): max sequence length allowed for positional embeddings vocab_size (int): size of vocabulary pad_token_id (int): id used for paddin...
class QformerEmbedding(nn.Module): """ Qformer embedding module. Args: embedding_dim (int): dim of embedding space max_position_embeddings (int): max sequence length allowed for positional embeddings vocab_size (int): size of vocabulary pad_token_id (int): id used for paddin...
if input_ids is None and query_embeddings is None: raise ValueError("Either input_ids or query_embeddings must be passed.") seq_length = input_ids.size(1) if input_ids is not None else 0 embeddings = query_embeddings if input_ids is not None: if position_ids is...
""" Inputs: input_ids (Optional[Tensor]): input token ids position_ids (Optional[Tensor]): batches of of 1D integer tensors used to identify each token's position, if no position_ids is provided, the IDs are automatically created as absolute positional embeddings....
80
645
284
929
# 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, Tuple import torch from torch import nn, Tensor from torchmulti...
# 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, Tuple import torch from torch import nn, Tensor from torchmulti...
45,267
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/blip2/qformer_layers.py
271,280
221,312
forward
QformerEncoder
294,312
280,312
class QformerEncoder(nn.Module): """ Qformer encoder module including multiple Qformer layers. Args: num_hidden_layers (int): number of Qformer layers inside encoder dim_q (int): dimensionality of the query tensor dim_feedforward (int): dimensionality of the feedforward layer ...
class QformerEncoder(nn.Module): """ Qformer encoder module including multiple Qformer layers. Args: num_hidden_layers (int): number of Qformer layers inside encoder dim_q (int): dimensionality of the query tensor dim_feedforward (int): dimensionality of the feedforward layer ...
current_key_values = torch.jit.annotate(List[Tuple[Tensor, Tensor]], []) for i, layer_module in enumerate(self.layers): past_key_value = past_key_values[i] if past_key_values is not None else None hidden_states, current_key_value = layer_module( hidden_states=hidd...
""" 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 in CA case attention_mask (Optional[Tensor]): attention mask, supported mask typ...
40
921
235
1,156
# 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, Tuple import torch from torch import nn, Tensor from torchmulti...
# 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, Tuple import torch from torch import nn, Tensor from torchmulti...
45,269
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/blip2/qformer_model.py
251,261
186,295
forward
QformerForCLM
276,295
261,295
class QformerForCLM(nn.Module): """ A QformerModel wrapper class for causal language modeling(clm). Args: num_hidden_layers (int): number of Qformer layers inside encoder dim_q (int): dimensionality of the query tensor dim_feedforward (int): dimensionality of the feedforward layer ...
class QformerForCLM(nn.Module): """ A QformerModel wrapper class for causal language modeling(clm). Args: num_hidden_layers (int): number of Qformer layers inside encoder dim_q (int): dimensionality of the query tensor dim_feedforward (int): dimensionality of the feedforward layer ...
# TODO: revisit if it's required for edge cases after BLIP-2 impl. if past_key_values is not None: assert query_embeds is None sequence_output, _ = self.model( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, ...
""" Inputs: input_ids (Optional[Tensor]): input token ids for QFormer attention_mask (Optional[Tensor]): attention mask for QFormer position_ids (Optional[Tensor]): position ids for QFormer query_embeds (Optional[Tensor]): query embeddings for QFormer ...
56
1,167
238
1,405
# 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, Tuple from torch import nn, Tensor from torchmultimodal.models.bl...
# 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, Tuple from torch import nn, Tensor from torchmultimodal.models.bl...
45,270
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/blip2/qformer_model.py
77,88
15,148
forward
QformerModel
104,148
88,148
class QformerModel(nn.Module): """ Qformer model including Qformer embedding and Qformer encoder. Args: num_hidden_layers (int): number of Qformer layers inside encoder dim_q (int): dimensionality of the query tensor dim_feedforward (int): dimensionality of the feedforward layer ...
class QformerModel(nn.Module): """ Qformer model including Qformer embedding and Qformer encoder. Args: num_hidden_layers (int): number of Qformer layers inside encoder dim_q (int): dimensionality of the query tensor dim_feedforward (int): dimensionality of the feedforward layer ...
past_seq_length = ( # overall_seq_length - query_length past_key_values[0][0].shape[2] - self.query_length if past_key_values is not None else 0 ) query_length = query_embeds.shape[1] if query_embeds is not None else 0 embedding_output = s...
""" Inputs: input_ids (Optional[Tensor]): input token ids for QFormer attention_mask (Optional[Tensor]): attention mask for QFormer position_ids (Optional[Tensor]): position ids for QFormer query_embeds (Optional[Tensor]): query embeddings for QFormer ...
144
1,216
545
1,761
# 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, Tuple from torch import nn, Tensor from torchmultimodal.models.bl...
# 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, Tuple from torch import nn, Tensor from torchmultimodal.models.bl...
45,271
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/blip2/qformer_model.py
172,173
148,186
forward
QformerPredictionHead
179,186
173,186
class QformerPredictionHead(nn.Module): """ MLP head for computinng prediction score from QformerModel output Args: dim_q (int): dimensionality of the query tensor vocab_size (int): the size of vocabulary used by QFormer layer_norm_eps (float): the epsilon used by the layer normaliz...
class QformerPredictionHead(nn.Module): """ MLP head for computinng prediction score from QformerModel output Args: dim_q (int): dimensionality of the query tensor vocab_size (int): the size of vocabulary used by QFormer layer_norm_eps (float): the epsilon used by the layer normaliz...
hidden_states = self.linear_1(sequence_output) hidden_states = self.activation(hidden_states) hidden_states = self.layernorm(hidden_states) predictions = self.linear_2(hidden_states) return predictions
""" Inputs (Tensor): sequence_output of shape bsz x seq_len x embed_dim Returns: prediction scores (Tensor) of shape: bsz x seq_len x vocab_size """ hidden_states = self.linear_1(sequence_output) hidden_states = self.activation(hidden_states) ...
14
376
74
450
# 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, Tuple from torch import nn, Tensor from torchmultimodal.models.bl...
# 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, Tuple from torch import nn, Tensor from torchmultimodal.models.bl...
45,272
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/blip2/qformer_utils.py
15,20
1,72
get_causal_mask
38,72
20,72
# 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 from torch import Tensor from torchmultimodal.utils.attention import ge...
# 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 from torch import Tensor from torchmultimodal.utils.attention import ge...
device = attention_mask.device batch_size, seq_len = input_shape causal_mask = get_causal_attention_mask(seq_len).to(device) causal_mask = causal_mask.repeat(batch_size, 1).view(batch_size, seq_len, seq_len) # compare seq_len in input and attention mask if causal_mask.shape[1] < attention_mask.s...
"""A causal mask in addition to the padding mask for Q-Former for generation task. when input seq_len is shorter than attn_mask, increasing causal_mask by prefix_seq_len with 1s; if query is available, apply causal self-attention mask to control query-text interaction; Arguments: attentio...
120
479
487
966
# 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 from torch import Tensor from torchmultimodal.utils.attention import ge...
# 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 from torch import Tensor from torchmultimodal.utils.attention import ge...
45,274
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/clip/model.py
66,71
37,79
forward
CLIP
71,79
71,79
class CLIP(nn.Module): """CLIP is a model for contrastive pretraining between two modalities. CLIP (https://arxiv.org/pdf/2103.00020.pdf) jointly trains an image encoder (either ResNet or ViT) and a text encoder (Transformer) to predict correct (image, text) pairings via a contrastive loss function. Th...
class CLIP(nn.Module): """CLIP is a model for contrastive pretraining between two modalities. CLIP (https://arxiv.org/pdf/2103.00020.pdf) jointly trains an image encoder (either ResNet or ViT) and a text encoder (Transformer) to predict correct (image, text) pairings via a contrastive loss function. Th...
embeddings_a = self.encoder_a(features_a) embeddings_b = self.encoder_b(features_b) embeddings_a = F.normalize(embeddings_a) embeddings_b = F.normalize(embeddings_b) return CLIPOutput(embeddings_a=embeddings_a, embeddings_b=embeddings_b)
embeddings_a = self.encoder_a(features_a) embeddings_b = self.encoder_b(features_b) embeddings_a = F.normalize(embeddings_a) embeddings_b = F.normalize(embeddings_b) return CLIPOutput(embeddings_a=embeddings_a, embeddings_b=embeddings_b)
15
398
108
506
# 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 import torch import torch.nn.functional as F from torch import nn from torchmu...
# 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 import torch import torch.nn.functional as F from torch import nn from torchmu...
45,275
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/clip/text_encoder.py
114,115
16,136
forward
CLIPTextEncoder
115,136
115,136
class CLIPTextEncoder(nn.Module): """CLIP text encoder class. Should be instantiated and passed to CLIP (models/clip.py) As in CLIP, the text encoder follows a Transformer architecture. Args: embedding_dim (int): Embedding dimension for text and image encoders projections. context_leng...
class CLIPTextEncoder(nn.Module): """CLIP text encoder class. Should be instantiated and passed to CLIP (models/clip.py) As in CLIP, the text encoder follows a Transformer architecture. Args: embedding_dim (int): Embedding dimension for text and image encoders projections. context_leng...
if text.size(1) != self.context_length: raise ValueError( f"length of input should be {self.context_length} but found {text.size(1)}" ) embeddings = self.token_embedding(text) embeddings = embeddings + self.positional_embedding embeddings = embeddi...
if text.size(1) != self.context_length: raise ValueError( f"length of input should be {self.context_length} but found {text.size(1)}" ) embeddings = self.token_embedding(text) embeddings = embeddings + self.positional_embedding embeddings = embeddi...
83
1,190
319
1,509
# 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 from torch.nn import TransformerEncoder, TransformerEncoderLayer fr...
# 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 from torch.nn import TransformerEncoder, TransformerEncoderLayer fr...
45,277
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/coca/coca_model.py
430,433
401,457
forward
CoCaForPretraining
443,457
433,457
class CoCaForPretraining(nn.Module): """ CoCa pretraining model class. Ties CoCa model to captioning and contrastive losses. Args: model (CoCaModel): Instantiated CoCa model. pad_idx (int): Index of padding tokens (used to filter captioning loss indices). Default: 0 contr...
class CoCaForPretraining(nn.Module): """ CoCa pretraining model class. Ties CoCa model to captioning and contrastive losses. Args: model (CoCaModel): Instantiated CoCa model. pad_idx (int): Index of padding tokens (used to filter captioning loss indices). Default: 0 contr...
model_outs = self.model(images, texts, text_padding_mask) captioning_labels = texts[:, 1:].contiguous() contrastive_loss = self.contrastive_loss( model_outs.image_pooled_output, model_outs.text_pooled_output ) vocab_size = model_outs.multimodal_embeddings.shape[-1] ...
""" Args: images (Tensor): Tensor of size (bsz, c, h, w) containing image pixels. texts (Tensor): Tensor of size (bsz, seq_len) containing text tokens. text_padding_mask (Optional[Tensor]): Boolean mask indicating padded tokens. True for unpadded token...
30
546
195
741
# 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 functools import partial from typing import Any, Callable, Dict, List, NamedTuple, Optional, T...
# 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 functools import partial from typing import Any, Callable, Dict, List, NamedTuple, Optional, T...
45,278
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/coca/coca_model.py
69,72
34,133
forward
CoCaModel
82,133
72,133
class CoCaModel(nn.Module): """ CoCa model class containing vision encoder, text decoder, and multimodal decoder. Reference: https://arxiv.org/abs/2205.01917 Args: vision_encoder (nn.Module): Instantiated vision encoder. Should return either TransformerOutput or Tensor. text_...
class CoCaModel(nn.Module): """ CoCa model class containing vision encoder, text decoder, and multimodal decoder. Reference: https://arxiv.org/abs/2205.01917 Args: vision_encoder (nn.Module): Instantiated vision encoder. Should return either TransformerOutput or Tensor. text_...
# Image encoder vision_encoder_outs = self.vision_encoder(images) # Extract image embeddings if isinstance(vision_encoder_outs, TransformerOutput): image_embeddings = vision_encoder_outs.last_hidden_state elif isinstance(vision_encoder_outs, tuple): visi...
""" Args: images (Tensor): Tensor of size (bsz, c, h, w) containing image pixels. texts (Tensor): Tensor of size (bsz, seq_len) containing text tokens. text_padding_mask (Optional[Tensor]): Boolean mask indicating padded tokens. True for unpadded token...
136
664
651
1,315
# 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 functools import partial from typing import Any, Callable, Dict, List, NamedTuple, Optional, T...
# 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 functools import partial from typing import Any, Callable, Dict, List, NamedTuple, Optional, T...
45,279
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/coca/coca_model.py
493,496
465,510
forward
CoCaModelWithHeads
496,510
496,510
class CoCaModelWithHeads(nn.Module): """ CoCa model with heads. Args: model (CoCaModel): Instantiated CoCa model. heads (nn.ModuleDict): Dictionary of heads, taking either unimodal or multimodal embeddings as inputs pad_idx (int): Index of padding tokens (used to filter c...
class CoCaModelWithHeads(nn.Module): """ CoCa model with heads. Args: model (CoCaModel): Instantiated CoCa model. heads (nn.ModuleDict): Dictionary of heads, taking either unimodal or multimodal embeddings as inputs pad_idx (int): Index of padding tokens (used to filter c...
model_out = self.model(images, texts, text_padding_mask) mm_out = model_out.multimodal_embeddings bsz = mm_out.shape[0] # reshape in the case of attention pooler pooled_output = self.pooler(mm_out).view((bsz, -1)) # run the heads head_outputs = {} for k...
model_out = self.model(images, texts, text_padding_mask) mm_out = model_out.multimodal_embeddings bsz = mm_out.shape[0] # reshape in the case of attention pooler pooled_output = self.pooler(mm_out).view((bsz, -1)) # run the heads head_outputs = {} for k...
40
349
158
507
# 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 functools import partial from typing import Any, Callable, Dict, List, NamedTuple, Optional, T...
# 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 functools import partial from typing import Any, Callable, Dict, List, NamedTuple, Optional, T...
45,280
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/coca/multimodal_decoder.py
86,87
15,109
forward
CoCaMultimodalDecoder
95,109
87,109
class CoCaMultimodalDecoder(nn.Module): """ Multimodal decoder for CoCa model. Uses a transformer decoder with causal mask for text embeddings that cross-attends to image embeddings, followed by output projection. Based on the implementation in open_clip: https://tinyurl.com/mn35vdmd Args: ...
class CoCaMultimodalDecoder(nn.Module): """ Multimodal decoder for CoCa model. Uses a transformer decoder with causal mask for text embeddings that cross-attends to image embeddings, followed by output projection. Based on the implementation in open_clip: https://tinyurl.com/mn35vdmd Args: ...
seq_len = texts.shape[1] assert self.causal_mask.shape == (seq_len, seq_len) decoder_outputs = self.transformer_decoder( hidden_states=texts, encoder_hidden_states=images, attention_mask=self.causal_mask, ) hidden_states = decoder_outputs.last_...
""" Args: texts (Tensor): Tensor containing text embeddings of shape [batch_size, text_seq_length, embeddings_dim] images (Tensor): Tensor containing image embeddings of shape [batch_size, image_seq_length, embeddings_dim] text_causal_mask (Tensor): Tensor containing ...
43
998
180
1,178
# 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.modules.l...
# 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.modules.l...
45,282
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/coca/text_decoder.py
58,59
16,84
forward
CoCaTextEmbeddings
66,84
59,84
class CoCaTextEmbeddings(nn.Module): """ Text embeddings for CoCa model. Includes token embeddings, positional embeddings, and optional CLS embedding. Args: vocab_size (int): Size of the vocab num_positions (int): Number of token positions for positional embeddings not inclu...
class CoCaTextEmbeddings(nn.Module): """ Text embeddings for CoCa model. Includes token embeddings, positional embeddings, and optional CLS embedding. Args: vocab_size (int): Size of the vocab num_positions (int): Number of token positions for positional embeddings not inclu...
assert input_ids.shape[1] == ( self.num_positions if self.cls_embedding is None else self.num_positions - 1 ) embeddings = self.token_embeddings(input_ids) if self.cls_embedding is not None: # Expand cls embedding (embedding_dim) -> (batch_size, 1, embedding_dim...
""" Args: input_ids (Tensor of size (batch_size, seq_length)): Indices of input sequence tokens. Returns: Tensor of size (batch_size, seq_length, embedding_dim) """ assert input_ids.shape[1] == ( self.num_positions if self.cls_...
52
540
220
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 Callable, Optional, Tuple import torch import torch.nn.functional as F 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 typing import Callable, Optional, Tuple import torch import torch.nn.functional as F from torch import nn...
45,284
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/flava/image_encoder.py
102,105
68,178
interpolate_pos_encoding
ImageEmbeddings
111,139
105,139
class ImageEmbeddings(nn.Module): """ Construct the CLS token, position and patch embeddings. """ def __init__( self, image_size: int = 224, patch_size: int = 16, num_channels: int = 3, hidden_size: int = 768, hidden_dropout_prob: float = 0.0, use...
class ImageEmbeddings(nn.Module): """ Construct the CLS token, position and patch embeddings. """ def __init__( self, image_size: int = 224, patch_size: int = 16, num_channels: int = 3, hidden_size: int = 768, hidden_dropout_prob: float = 0.0, use...
npatch = embeddings.shape[1] - 1 n = self.position_embeddings.shape[1] - 1 if npatch == n and height == width: return self.position_embeddings class_pos_embed = self.position_embeddings[:, 0] patch_pos_embed = self.position_embeddings[:, 1:] dim = embeddings....
""" This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution images. Source: https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174 """ npatch...
112
929
461
1,390
# 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 functools import partial from typing import Any, Callable, Dict, Optional, Tup...
# 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 functools import partial from typing import Any, Callable, Dict, Optional, Tup...
45,285
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/flava/image_encoder.py
204,210
178,237
forward
ImageTransformer
210,237
210,237
class ImageTransformer(nn.Module): # TODO(asg): Add support for pretrained checkpoint loading def __init__( self, embeddings: nn.Module, encoder: nn.Module, layernorm: nn.Module, pooler: nn.Module, weight_init_fn: Optional[Callable] = None, initializer_ran...
class ImageTransformer(nn.Module): # TODO(asg): Add support for pretrained checkpoint loading def __init__( self, embeddings: nn.Module, encoder: nn.Module, layernorm: nn.Module, pooler: nn.Module, weight_init_fn: Optional[Callable] = None, initializer_ran...
if pixel_values is None: raise ValueError("You have to specify pixel_values") embedding_output = self.embeddings( pixel_values, image_patches_mask=image_patches_mask ) encoder_output = self.encoder( embedding_output, attention_mask=attent...
if pixel_values is None: raise ValueError("You have to specify pixel_values") embedding_output = self.embeddings( pixel_values, image_patches_mask=image_patches_mask ) encoder_output = self.encoder( embedding_output, attention_mask=attent...
49
296
266
562
# 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 functools import partial from typing import Any, Callable, Dict, Optional, Tup...
# 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 functools import partial from typing import Any, Callable, Dict, Optional, Tup...
45,286
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/flava/image_encoder.py
293,299
281,314
forward
ImageTransformerWithVAE
299,314
299,314
class ImageTransformerWithVAE(nn.Module): def __init__( self, image_transformer: nn.Module, vae: nn.Module, **kwargs: Dict[str, Any], ) -> None: super().__init__() self.image_transformer = image_transformer self.vae = vae def forward( self, ...
class ImageTransformerWithVAE(nn.Module): def __init__( self, image_transformer: nn.Module, vae: nn.Module, **kwargs: Dict[str, Any], ) -> None: super().__init__() self.image_transformer = image_transformer self.vae = vae def forward( self, ...
image_labels = self.vae(pixel_values).flatten(1) image_patches_mask = image_patches_mask.flatten(1).to(torch.bool) image_labels[image_patches_mask == False] = -1 # noqa output = self.image_transformer( pixel_values=pixel_values, image_patches_mask=image_patches_...
image_labels = self.vae(pixel_values).flatten(1) image_patches_mask = image_patches_mask.flatten(1).to(torch.bool) image_labels[image_patches_mask == False] = -1 # noqa output = self.image_transformer( pixel_values=pixel_values, image_patches_mask=image_patches_...
27
169
202
371
# 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 functools import partial from typing import Any, Callable, Dict, Optional, Tup...
# 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 functools import partial from typing import Any, Callable, Dict, Optional, Tup...
45,287
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/flava/image_encoder.py
55,58
29,68
forward
PatchEmbeddings
58,68
58,68
class PatchEmbeddings(nn.Module): """ Image to Patch Embedding. """ def __init__( self, image_size: int = 224, patch_size: int = 16, num_channels: int = 3, embed_dim: int = 768, ) -> None: super().__init__() image_size = to_2tuple(image_size) ...
class PatchEmbeddings(nn.Module): """ Image to Patch Embedding. """ def __init__( self, image_size: int = 224, patch_size: int = 16, num_channels: int = 3, embed_dim: int = 768, ) -> None: super().__init__() image_size = to_2tuple(image_size) ...
_, _, height, width = pixel_values.shape if not interpolate_pos_encoding: if height != self.image_size[0] or width != self.image_size[1]: raise ValueError( f"Input image size ({height}*{width}) doesn't match model ({self.image_size[0]}*{self.image_size[1]}...
_, _, height, width = pixel_values.shape if not interpolate_pos_encoding: if height != self.image_size[0] or width != self.image_size[1]: raise ValueError( f"Input image size ({height}*{width}) doesn't match model ({self.image_size[0]}*{self.image_size[1]}...
34
301
142
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. import math import warnings from functools import partial from typing import Any, Callable, Dict, Optional, Tup...
# 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 functools import partial from typing import Any, Callable, Dict, Optional, Tup...
45,289
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/flava/model.py
595,596
584,599
forward
DalleConv2d
596,599
596,599
class DalleConv2d(nn.Module): def __init__(self, n_in: int, n_out: int, kw: int) -> None: super().__init__() w = torch.empty((n_out, n_in, kw, kw), dtype=torch.float32) w.normal_(std=1 / math.sqrt(n_in * kw**2)) b = torch.zeros((n_out,), dtype=torch.float32) self.w, self.b ...
class DalleConv2d(nn.Module): def __init__(self, n_in: int, n_out: int, kw: int) -> None: super().__init__() w = torch.empty((n_out, n_in, kw, kw), dtype=torch.float32) w.normal_(std=1 / math.sqrt(n_in * kw**2)) b = torch.zeros((n_out,), dtype=torch.float32) self.w, self.b ...
return nn.functional.conv2d(x, self.w, self.b, padding=(self.kw - 1) // 2)
return nn.functional.conv2d(x, self.w, self.b, padding=(self.kw - 1) // 2)
9
199
42
241
# 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. # Code for some of the transformers components in this file are initialized # from their counterparts in Huggin...
# 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. # Code for some of the transformers components in this file are initialized # from their counterparts in Huggin...
45,290
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/flava/model.py
683,691
625,717
_create_group
DalleEncoder
691,705
691,705
class DalleEncoder(nn.Module): def __init__( self, group_count: int = 4, n_hid: int = 256, n_blk_per_group: int = 2, input_channels: int = 3, vocab_size: int = 8192, **kwargs: Any, ) -> None: super().__init__() self.input_channels = input_...
class DalleEncoder(nn.Module): def __init__( self, group_count: int = 4, n_hid: int = 256, n_blk_per_group: int = 2, input_channels: int = 3, vocab_size: int = 8192, **kwargs: Any, ) -> None: super().__init__() self.input_channels = input_...
make_blk = partial(DalleEncoderBlock, n_layers=n_layers) blk_range = range(n_blk_per_group) blocks: OrderedDict[str, nn.Module] = OrderedDict() for i in blk_range: if i == 0: blocks[f"block_{i+1}"] = make_blk(n_in, n_hid) else: bloc...
make_blk = partial(DalleEncoderBlock, n_layers=n_layers) blk_range = range(n_blk_per_group) blocks: OrderedDict[str, nn.Module] = OrderedDict() for i in blk_range: if i == 0: blocks[f"block_{i+1}"] = make_blk(n_in, n_hid) else: bloc...
36
733
195
928
# 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. # Code for some of the transformers components in this file are initialized # from their counterparts in Huggin...
# 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. # Code for some of the transformers components in this file are initialized # from their counterparts in Huggin...
45,291
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/flava/model.py
621,622
599,625
forward
DalleEncoderBlock
622,625
622,625
class DalleEncoderBlock(nn.Module): def __init__(self, n_in: int, n_out: int, n_layers: int) -> None: super().__init__() n_hid = n_out // 4 self.post_gain = 1 / (n_layers**2) self.id_path = DalleConv2d(n_in, n_out, 1) if n_in != n_out else nn.Identity() self.res_path = nn.Se...
class DalleEncoderBlock(nn.Module): def __init__(self, n_in: int, n_out: int, n_layers: int) -> None: super().__init__() n_hid = n_out // 4 self.post_gain = 1 / (n_layers**2) self.id_path = DalleConv2d(n_in, n_out, 1) if n_in != n_out else nn.Identity() self.res_path = nn.Se...
return self.id_path(x) + self.post_gain * self.res_path(x)
return self.id_path(x) + self.post_gain * self.res_path(x)
6
344
32
376
# 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. # Code for some of the transformers components in this file are initialized # from their counterparts in Huggin...
# 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. # Code for some of the transformers components in this file are initialized # from their counterparts in Huggin...
45,292
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/flava/model.py
736,737
717,746
get_codebook_indices
DalleVAEEncoder
737,740
737,740
class DalleVAEEncoder(nn.Module): def __init__( self, image_size: Union[int, Tuple[int, int]] = 112, pretrained: bool = True ): super().__init__() self.image_size = image_size self.encoder = DalleEncoder() if pretrained: self.load_model() def load_model(s...
class DalleVAEEncoder(nn.Module): def __init__( self, image_size: Union[int, Tuple[int, int]] = 112, pretrained: bool = True ): super().__init__() self.image_size = image_size self.encoder = DalleEncoder() if pretrained: self.load_model() def load_model(s...
z_logits = self.encoder(images) return torch.argmax(z_logits, axis=1) # type: ignore
z_logits = self.encoder(images) return torch.argmax(z_logits, axis=1) # type: ignore
9
366
41
407
# 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. # Code for some of the transformers components in this file are initialized # from their counterparts in Huggin...
# 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. # Code for some of the transformers components in this file are initialized # from their counterparts in Huggin...
45,293
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/flava/model.py
393,401
380,428
forward
FLAVAForClassification
401,428
401,428
class FLAVAForClassification(nn.Module): def __init__( self, model: FLAVAModel, classifier: nn.Module, loss: Union[nn.Module, Callable[[Tensor, Tensor], Tensor]], **kwargs: Any, ) -> None: super().__init__() self.model = model self.classifier = cla...
class FLAVAForClassification(nn.Module): def __init__( self, model: FLAVAModel, classifier: nn.Module, loss: Union[nn.Module, Callable[[Tensor, Tensor], Tensor]], **kwargs: Any, ) -> None: super().__init__() self.model = model self.classifier = cla...
flava_output: FLAVAOutput = self.model( image=image, text=text, required_embedding=required_embedding, # Don't skip the encoder for classification skip_unmasked_mm_encoder=False, ) hidden_state: Optional[Tensor] = None if requi...
flava_output: FLAVAOutput = self.model( image=image, text=text, required_embedding=required_embedding, # Don't skip the encoder for classification skip_unmasked_mm_encoder=False, ) hidden_state: Optional[Tensor] = None if requi...
74
212
299
511
# 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. # Code for some of the transformers components in this file are initialized # from their counterparts in Huggin...
# 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. # Code for some of the transformers components in this file are initialized # from their counterparts in Huggin...
45,294
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/flava/model.py
314,319
301,380
encode_image
FLAVAForPreTraining
319,323
319,323
class FLAVAForPreTraining(nn.Module): # TODOs: # 1. Expose logit scale # 2. For FLAVA model, allow interpolating the embeddings to # for patch embeddings def __init__( self, model: FLAVAModel, image_codebook: nn.Module, loss: FLAVAPretrainingLoss ) -> None: super().__init__() ...
class FLAVAForPreTraining(nn.Module): # TODOs: # 1. Expose logit scale # 2. For FLAVA model, allow interpolating the embeddings to # for patch embeddings def __init__( self, model: FLAVAModel, image_codebook: nn.Module, loss: FLAVAPretrainingLoss ) -> None: super().__init__() ...
encoded_result = self.model.encode_image(image, projection=True) encoded_image = encoded_result[1] return encoded_image
encoded_result = self.model.encode_image(image, projection=True) encoded_image = encoded_result[1] return encoded_image
9
902
43
945
# 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. # Code for some of the transformers components in this file are initialized # from their counterparts in Huggin...
# 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. # Code for some of the transformers components in this file are initialized # from their counterparts in Huggin...
45,296
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/flava/text_encoder.py
21,38
1,73
flava_text_encoder
38,73
38,73
# 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 Callable from torch import nn from torchmultimodal.models.fla...
# 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 Callable from torch import nn from torchmultimodal.models.fla...
embeddings = BERTTextEmbeddings( hidden_size=hidden_size, vocab_size=vocab_size, pad_token_id=pad_token_id, type_vocab_size=type_vocab_size, max_position_embeddings=max_position_embeddings, layer_norm_eps=layer_norm_eps, dropout=dropout, ) encoder = ...
embeddings = BERTTextEmbeddings( hidden_size=hidden_size, vocab_size=vocab_size, pad_token_id=pad_token_id, type_vocab_size=type_vocab_size, max_position_embeddings=max_position_embeddings, layer_norm_eps=layer_norm_eps, dropout=dropout, ) encoder = ...
44
439
380
819
# 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 Callable from torch import nn from torchmultimodal.models.fla...
# 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 Callable from torch import nn from torchmultimodal.models.fla...
45,298
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/flava/transformer.py
48,53
19,81
forward
FLAVATransformerWithoutEmbeddings
53,81
53,81
class FLAVATransformerWithoutEmbeddings(nn.Module): # TODO(asg): Add support for pretrained checkpoint loading def __init__( self, encoder: nn.Module, layernorm: nn.Module, pooler: nn.Module, hidden_size: int = 768, weight_init_fn: Optional[Callable] = None, ...
class FLAVATransformerWithoutEmbeddings(nn.Module): # TODO(asg): Add support for pretrained checkpoint loading def __init__( self, encoder: nn.Module, layernorm: nn.Module, pooler: nn.Module, hidden_size: int = 768, weight_init_fn: Optional[Callable] = None, ...
if hidden_states is None: raise ValueError("You have to specify hidden_states") if self.cls_token is not None: batch_size = hidden_states.shape[0] cls_tokens = self.cls_token.expand(batch_size, -1, -1) hidden_states = torch.cat((cls_tokens, hidden_states)...
if hidden_states is None: raise ValueError("You have to specify hidden_states") if self.cls_token is not None: batch_size = hidden_states.shape[0] cls_tokens = self.cls_token.expand(batch_size, -1, -1) hidden_states = torch.cat((cls_tokens, hidden_states)...
61
338
310
648
# 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, Optional, Tuple, Union import torch 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 functools import partial from typing import Any, Callable, Optional, Tuple, Union import torch from torch...
45,299
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/flava/transformer.py
256,264
224,298
forward
TransformerEncoder
264,298
264,298
class TransformerEncoder(nn.Module): def __init__( self, n_layer: int, d_model: int, n_head: int, dim_feedforward: int, dropout: float = 0.0, activation: Callable[..., nn.Module] = nn.ReLU, layer_norm_eps: float = 1e-12, norm_first: bool = Fals...
class TransformerEncoder(nn.Module): def __init__( self, n_layer: int, d_model: int, n_head: int, dim_feedforward: int, dropout: float = 0.0, activation: Callable[..., nn.Module] = nn.ReLU, layer_norm_eps: float = 1e-12, norm_first: bool = Fals...
all_hidden_states = [] if return_hidden_states else None all_self_attentions = [] if return_attn_weights else None for layer_module in self.layer: if return_hidden_states: all_hidden_states.append(hidden_states) layer_outputs = layer_module( ...
all_hidden_states = [] if return_hidden_states else None all_self_attentions = [] if return_attn_weights else None for layer_module in self.layer: if return_hidden_states: all_hidden_states.append(hidden_states) layer_outputs = layer_module( ...
56
373
332
705
# 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, Optional, Tuple, Union import torch 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 functools import partial from typing import Any, Callable, Optional, Tuple, Union import torch from torch...
45,300
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/flava/transformer.py
179,186
81,224
_forward_postnorm
TransformerEncoderLayer
186,201
186,201
class TransformerEncoderLayer(nn.Module): """Transformer encoder layer is made up of multihead self-attention and feedforward blocks, based on the architecture in "Attention Is All You Need" (Vaswani et al. 2017). Similar to ``nn.TransformerEncoderLayer``, but uses a custom ``MultiHeadAttention`` that suppo...
class TransformerEncoderLayer(nn.Module): """Transformer encoder layer is made up of multihead self-attention and feedforward blocks, based on the architecture in "Attention Is All You Need" (Vaswani et al. 2017). Similar to ``nn.TransformerEncoderLayer``, but uses a custom ``MultiHeadAttention`` that suppo...
x = hidden_states attn_output, attn_weights = self._attention_block( x, attention_mask=attention_mask, head_mask=head_mask, ) attn_residual = attn_output + x attn_residual = self.attention_layernorm(attn_residual) ff_residual = attn_res...
x = hidden_states attn_output, attn_weights = self._attention_block( x, attention_mask=attention_mask, head_mask=head_mask, ) attn_residual = attn_output + x attn_residual = self.attention_layernorm(attn_residual) ff_residual = attn_res...
35
1,476
178
1,654
# 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, Optional, Tuple, Union import torch 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 functools import partial from typing import Any, Callable, Optional, Tuple, Union import torch from torch...
45,301
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/late_fusion.py
42,43
13,49
forward
LateFusion
43,49
43,49
class LateFusion(nn.Module): """A generic architecture for late fusion multimodal models. A late fusion model contains separate encoders for each modality, followed by a fusion layer and then a head module. For an example of a late fusion model, see the TorchMultimodal implementation of the cnn-lstm ...
class LateFusion(nn.Module): """A generic architecture for late fusion multimodal models. A late fusion model contains separate encoders for each modality, followed by a fusion layer and then a head module. For an example of a late fusion model, see the TorchMultimodal implementation of the cnn-lstm ...
embeddings = {} for key, encoder in self.encoders.items(): assert key in modalities, f"{key} missing in input" embeddings[key] = encoder(modalities[key]) fused = self.fusion_module(embeddings) return self.head_module(fused)
embeddings = {} for key, encoder in self.encoders.items(): assert key in modalities, f"{key} missing in input" embeddings[key] = encoder(modalities[key]) fused = self.fusion_module(embeddings) return self.head_module(fused)
24
335
86
421
# 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 LateFusion(nn.Module): """A generic arch...
# 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 LateFusion(nn.Module): """A generic arch...
45,303
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/masked_auto_encoder/model.py
223,228
194,245
forward
DecoderEmbeddings
228,245
228,245
class DecoderEmbeddings(nn.Module): """ Construct the decoder embeddings from encoder embeddings. Args: encoder_embed_dim (int): Input dim for decoder embedding i.e. output dim of the encoder. decoder_embed_dim (int): output dim for decoder embedding. image_size (Union[int, Tuple[int...
class DecoderEmbeddings(nn.Module): """ Construct the decoder embeddings from encoder embeddings. Args: encoder_embed_dim (int): Input dim for decoder embedding i.e. output dim of the encoder. decoder_embed_dim (int): output dim for decoder embedding. image_size (Union[int, Tuple[int...
x = self.decoder_embed(x) mask_tokens = self.mask_token.repeat( x.shape[0], ids_restore.shape[1] + 1 - x.shape[1], 1 ) x_ = torch.cat([x[:, 1:, :], mask_tokens], dim=1) # no cls token x_ = torch.gather( x_, dim=1, index=ids_restore.unsqueeze(-1).repeat(1...
x = self.decoder_embed(x) mask_tokens = self.mask_token.repeat( x.shape[0], ids_restore.shape[1] + 1 - x.shape[1], 1 ) x_ = torch.cat([x[:, 1:, :], mask_tokens], dim=1) # no cls token x_ = torch.gather( x_, dim=1, index=ids_restore.unsqueeze(-1).repeat(1...
58
435
223
658
# 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, Tuple, Union 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, NamedTuple, Optional, Tuple, Union import torch from torch import nn, Tensor fro...
45,304
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/masked_auto_encoder/model.py
154,155
42,194
forward
MaskedAutoEncoder
165,194
155,194
class MaskedAutoEncoder(nn.Module): """ MAE (https://arxiv.org/abs/2111.06377) is a pretraining technique to mask out patches of the input before passing through the encoder and then using a decoder to predict the masked patches The code has been adapted from the original implementation https://github.c...
class MaskedAutoEncoder(nn.Module): """ MAE (https://arxiv.org/abs/2111.06377) is a pretraining technique to mask out patches of the input before passing through the encoder and then using a decoder to predict the masked patches The code has been adapted from the original implementation https://github.c...
embedding_out = self.embeddings(x) encoder_out = self.encoder(embedding_out.embeddings) if not self.training: # TODO: check if error should be raised is masking ratio != 0 here return MAEOutput(encoder_out) decoder_embedding = self.decoder_embed( encod...
""" Args: x (Tensor): input tensor with shape bsz x channels x height x width Returns: output of MAEOutput type where encoder_output gives the output from the encoder, decoder_pred gives prediction from the decoder followed by linear head, mask ind...
65
1,650
331
1,981
# 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, Tuple, Union 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, NamedTuple, Optional, Tuple, Union import torch from torch import nn, Tensor fro...
45,305
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/masked_auto_encoder/position_embeddings.py
73,76
1,117
get_2d_sin_cos_embeddings
83,102
76,102
# 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 from torch import Tensor def get_3d_sin_cos_embeddings( embed_dim:...
# 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 from torch import Tensor def get_3d_sin_cos_embeddings( embed_dim:...
# dim gets halved twice, once for h and w axis and once for sin and cos if embed_dim % 4 != 0: raise ValueError(f"embed_dim must be divisible by 4, got {embed_dim}") h, w = input_size pos_h = torch.arange(h) pos_w = torch.arange(w) pos_grid = torch.meshgrid(pos_w, pos_h, indexing="xy") ...
""" 2d position sin cos embeddings. Args: embed_dim (int): embedding dimension of the position embedding input_size (Tuple[int, int]): input dimensions of the grid include_cls_embed (bool): Whether to include positional embedding for [CLS] token. Defaults to True. """ # dim ...
88
1,288
308
1,596
# 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 from torch import Tensor def get_3d_sin_cos_embeddings( embed_dim:...
# 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 from torch import Tensor def get_3d_sin_cos_embeddings( embed_dim:...
45,306
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/mdetr/image_encoder.py
142,147
1,158
mdetr_resnet101_backbone
147,158
147,158
# 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 import torch import torch.nn.functional as F from torch import nn, 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 Callable, Tuple import torch import torch.nn.functional as F from torch import nn, Tensor f...
body = resnet101( replace_stride_with_dilation=[False, False, False], weights=weights, norm_layer=norm_layer, ) if freeze_weights: for name, parameter in body.named_parameters(): if "layer2" not in name and "layer3" not in name and "layer4" not in name: ...
body = resnet101( replace_stride_with_dilation=[False, False, False], weights=weights, norm_layer=norm_layer, ) if freeze_weights: for name, parameter in body.named_parameters(): if "layer2" not in name and "layer3" not in name and "layer4" not in name: ...
38
1,876
146
2,022
# 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 import torch import torch.nn.functional as F from torch import nn, 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 Callable, Tuple import torch import torch.nn.functional as F from torch import nn, Tensor f...
45,307
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/mdetr/image_encoder.py
42,43
17,54
forward
FrozenBatchNorm2d
43,54
43,54
class FrozenBatchNorm2d(nn.Module): """ BatchNorm2d where the batch statistics and the affine parameters are fixed. Copied from torchvision.ops.misc with added eps before rsqrt, without which any other models than torchvision.models.resnet[18,34,50,101] produce nans. This module is a useful replace...
class FrozenBatchNorm2d(nn.Module): """ BatchNorm2d where the batch statistics and the affine parameters are fixed. Copied from torchvision.ops.misc with added eps before rsqrt, without which any other models than torchvision.models.resnet[18,34,50,101] produce nans. This module is a useful replace...
# move reshapes to the beginning to make it fuser-friendly # ignore mypy errors because fixing them would break checkpoint loading w = self.weight.reshape(1, -1, 1, 1) # type: ignore b = self.bias.reshape(1, -1, 1, 1) # type: ignore rv = self.running_var.reshape(1, -1, 1, 1) #...
# move reshapes to the beginning to make it fuser-friendly # ignore mypy errors because fixing them would break checkpoint loading w = self.weight.reshape(1, -1, 1, 1) # type: ignore b = self.bias.reshape(1, -1, 1, 1) # type: ignore rv = self.running_var.reshape(1, -1, 1, 1) #...
77
348
192
540
# 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 import torch import torch.nn.functional as F from torch import nn, 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 Callable, Tuple import torch import torch.nn.functional as F from torch import nn, Tensor f...
45,308
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/mdetr/image_encoder.py
131,134
110,142
forward
MaskedIntermediateLayer
134,142
134,142
class MaskedIntermediateLayer(nn.Module): """ This class wraps a backbone returning an intermediate layer (e.g. a ResNet where we do not want to perform pooling) while casting masks to the appropriate sizes. Note: for simplicity we only support returning a single intermediate layer. Args: bo...
class MaskedIntermediateLayer(nn.Module): """ This class wraps a backbone returning an intermediate layer (e.g. a ResNet where we do not want to perform pooling) while casting masks to the appropriate sizes. Note: for simplicity we only support returning a single intermediate layer. Args: bo...
out = self.body(images) tensor = out[next(iter(out))] mask = F.interpolate(image_masks[None].float(), size=tensor.shape[-2:]).bool()[ 0 ] return tensor, mask
out = self.body(images) tensor = out[next(iter(out))] mask = F.interpolate(image_masks[None].float(), size=tensor.shape[-2:]).bool()[ 0 ] return tensor, mask
15
298
76
374
# 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 import torch import torch.nn.functional as F from torch import nn, 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 Callable, Tuple import torch import torch.nn.functional as F from torch import nn, Tensor f...
45,309
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/mdetr/image_encoder.py
84,85
54,110
forward
PositionEmbedding2D
85,110
85,110
class PositionEmbedding2D(nn.Module): """ This is a more standard version of the position embedding, very similar to the one used by the Attention Is All You Need paper (https://arxiv.org/abs/1706.03762), generalized to work on images. Args: num_pos_feats (int): Number of positional features ...
class PositionEmbedding2D(nn.Module): """ This is a more standard version of the position embedding, very similar to the one used by the Attention Is All You Need paper (https://arxiv.org/abs/1706.03762), generalized to work on images. Args: num_pos_feats (int): Number of positional features ...
not_mask = ~mask y_embed = not_mask.cumsum(1, dtype=torch.float32) x_embed = not_mask.cumsum(2, dtype=torch.float32) if self.scale is not None: eps = 1e-6 y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale x_embed = x_embed / (x_embed[:, :, -1...
not_mask = ~mask y_embed = not_mask.cumsum(1, dtype=torch.float32) x_embed = not_mask.cumsum(2, dtype=torch.float32) if self.scale is not None: eps = 1e-6 y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale x_embed = x_embed / (x_embed[:, :, -1...
111
357
435
792
# 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 import torch import torch.nn.functional as F from torch import nn, 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 Callable, Tuple import torch import torch.nn.functional as F from torch import nn, Tensor f...
45,311
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/mdetr/model.py
102,103
37,177
_pad_images
MDETR
103,116
103,116
class MDETR(nn.Module): """ MDETR (https://arxiv.org/abs/2104.12763) is a modulated detection model used to detect objects in an image conditioned on text or captions. This class contains the entire MDETR architecture, including the image backbone, text encoder, and multimodal transformer. (Note tha...
class MDETR(nn.Module): """ MDETR (https://arxiv.org/abs/2104.12763) is a modulated detection model used to detect objects in an image conditioned on text or captions. This class contains the entire MDETR architecture, including the image backbone, text encoder, and multimodal transformer. (Note tha...
max_size = tuple(max(s) for s in zip(*[img.shape for img in images])) batch_shape = (len(images),) + max_size b, _, h, w = batch_shape dtype = images[0].dtype device = images[0].device padded_images = torch.zeros(batch_shape, dtype=dtype, device=device) mask = to...
max_size = tuple(max(s) for s in zip(*[img.shape for img in images])) batch_shape = (len(images),) + max_size b, _, h, w = batch_shape dtype = images[0].dtype device = images[0].device padded_images = torch.zeros(batch_shape, dtype=dtype, device=device) mask = to...
63
1,623
224
1,847
# 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 collections import OrderedDict from typing import Dict, List, NamedTuple, Optional, Tuple im...
# 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 collections import OrderedDict from typing import Dict, List, NamedTuple, Optional, Tuple im...
45,312
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/mdetr/model.py
390,395
374,418
forward
MDETRForPhraseGrounding
395,418
395,418
class MDETRForPhraseGrounding(nn.Module): def __init__( self, model: MDETR, contrastive_alignment_image_projection: nn.Module, contrastive_alignment_text_projection: nn.Module, ): super().__init__() self.model = model self.contrastive_alignment_image_proje...
class MDETRForPhraseGrounding(nn.Module): def __init__( self, model: MDETR, contrastive_alignment_image_projection: nn.Module, contrastive_alignment_text_projection: nn.Module, ): super().__init__() self.model = model self.contrastive_alignment_image_proje...
model_output = self.model(images, text) final_hidden_state = model_output.transformer_output.decoder_hidden_states[-1] contrastive_query_embeddings = F.normalize( self.contrastive_alignment_image_projection(final_hidden_state), p=2, dim=-1, ) ...
model_output = self.model(images, text) final_hidden_state = model_output.transformer_output.decoder_hidden_states[-1] contrastive_query_embeddings = F.normalize( self.contrastive_alignment_image_projection(final_hidden_state), p=2, dim=-1, ) ...
33
206
254
460
# 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 collections import OrderedDict from typing import Dict, List, NamedTuple, Optional, Tuple im...
# 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 collections import OrderedDict from typing import Dict, List, NamedTuple, Optional, Tuple im...
45,313
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/mdetr/model.py
289,294
264,325
forward
MDETRForVQA
294,325
294,325
class MDETRForVQA(nn.Module): def __init__( self, model: MDETR, vqa_heads: nn.ModuleDict, contrastive_alignment_image_projection: nn.Module, contrastive_alignment_text_projection: nn.Module, ): super().__init__() self.model = model self.vqa_heads =...
class MDETRForVQA(nn.Module): def __init__( self, model: MDETR, vqa_heads: nn.ModuleDict, contrastive_alignment_image_projection: nn.Module, contrastive_alignment_text_projection: nn.Module, ): super().__init__() self.model = model self.vqa_heads =...
# Calculate MDETR model outputs model_output = self.model(images, text) final_hidden_state = model_output.transformer_output.decoder_hidden_states[-1] # Perform projections for contrastive alignment loss. contrastive_query_embeddings = F.normalize( self.contrastive_...
# Calculate MDETR model outputs model_output = self.model(images, text) final_hidden_state = model_output.transformer_output.decoder_hidden_states[-1] # Perform projections for contrastive alignment loss. contrastive_query_embeddings = F.normalize( self.contrastive_...
71
328
388
716
# 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 collections import OrderedDict from typing import Dict, List, NamedTuple, Optional, Tuple im...
# 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 collections import OrderedDict from typing import Dict, List, NamedTuple, Optional, Tuple im...
45,314
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/mdetr/text_encoder.py
113,127
1,151
mdetr_roberta_text_encoder
127,151
127,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 Optional import torch from torch import nn, Tensor from torchmultimodal.modules.encoders.be...
# 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 from torchmultimodal.modules.encoders.be...
embeddings = BERTTextEmbeddings( hidden_size=embedding_dim, vocab_size=vocab_size, pad_token_id=pad_token_id, type_vocab_size=type_vocab_size, max_position_embeddings=max_position_embeddings, layer_norm_eps=layer_norm_eps, dropout=embedding_dropout_prob, ...
embeddings = BERTTextEmbeddings( hidden_size=embedding_dim, vocab_size=vocab_size, pad_token_id=pad_token_id, type_vocab_size=type_vocab_size, max_position_embeddings=max_position_embeddings, layer_norm_eps=layer_norm_eps, dropout=embedding_dropout_prob, ...
30
1,404
294
1,698
# 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 from torchmultimodal.modules.encoders.be...
# 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 from torchmultimodal.modules.encoders.be...
45,315
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/mdetr/text_encoder.py
105,106
80,113
forward
FeatureResizer
106,113
106,113
class FeatureResizer(nn.Module): """ This class takes as input a set of embeddings of dimension C1 and outputs a set of embedding of dimension C2, after a linear transformation, dropout and normalization (LN). Args: input_feat_size (int): Dimension of input features. output_feat_size (int)...
class FeatureResizer(nn.Module): """ This class takes as input a set of embeddings of dimension C1 and outputs a set of embedding of dimension C2, after a linear transformation, dropout and normalization (LN). Args: input_feat_size (int): Dimension of input features. output_feat_size (int)...
x = self.fc(encoder_features) if self.do_ln: x = self.layer_norm(x) output = self.dropout(x) return output
x = self.fc(encoder_features) if self.do_ln: x = self.layer_norm(x) output = self.dropout(x) return output
13
346
58
404
# 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 from torchmultimodal.modules.encoders.be...
# 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 from torchmultimodal.modules.encoders.be...
45,316
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal
/home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/torchmultimodal/models/mdetr/text_encoder.py
63,70
17,80
forward
ModifiedTransformerEncoder
70,80
70,80
class ModifiedTransformerEncoder(nn.Module): """ Modified version of TorchText's RoBERTa transformer encoder taking in embeddings instead of input IDs. Args: embedding_dim (int): Number of features in the input. num_encoder_layers (int): Number of layers in the encoder. num_a...
class ModifiedTransformerEncoder(nn.Module): """ Modified version of TorchText's RoBERTa transformer encoder taking in embeddings instead of input IDs. Args: embedding_dim (int): Number of features in the input. num_encoder_layers (int): Number of layers in the encoder. num_a...
encoded = embeddings batch_size, seq_len = embeddings.size()[:2] mask = attention_mask.reshape(batch_size, seq_len) # Do this in a loop because otherwise it can cause OOM for layer in self.layers.layers: encoded = layer(encoded, src_key_padding_mask=mask) ret...
encoded = embeddings batch_size, seq_len = embeddings.size()[:2] mask = attention_mask.reshape(batch_size, seq_len) # Do this in a loop because otherwise it can cause OOM for layer in self.layers.layers: encoded = layer(encoded, src_key_padding_mask=mask) ret...
33
563
119
682
# 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 from torchmultimodal.modules.encoders.be...
# 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 from torchmultimodal.modules.encoders.be...
45,318
/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
88,97
20,135
forward
MDETRTransformer
97,135
97,135
class MDETRTransformer(nn.Module): """ Transformer class for MDETR model. Args: d_model (int): Number of features in the input. num_heads (int): Number of heads in multi-head attention. num_encoder_layers (int): Number of layers in the encoder. Default: 6 num_decoder_l...
class MDETRTransformer(nn.Module): """ Transformer class for MDETR model. Args: d_model (int): Number of features in the input. num_heads (int): Number of heads in multi-head attention. num_encoder_layers (int): Number of layers in the encoder. Default: 6 num_decoder_l...
# flatten NxCxHxW to HWxNxC bs = image_embeddings.size(0) image_embeddings = image_embeddings.flatten(2).permute(2, 0, 1) pos_embed = pos_embed.flatten(2).permute(2, 0, 1) # Object query embeddings for each sample in the batch # Size: (num_queries, batch_size, hidden_dim)...
# flatten NxCxHxW to HWxNxC bs = image_embeddings.size(0) image_embeddings = image_embeddings.flatten(2).permute(2, 0, 1) pos_embed = pos_embed.flatten(2).permute(2, 0, 1) # Object query embeddings for each sample in the batch # Size: (num_queries, batch_size, hidden_dim)...
128
874
558
1,432
# 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,319
/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
223,234
186,264
forward
TransformerDecoder
234,264
234,264
class TransformerDecoder(nn.Module): """ A transformer decoder. Args: decoder_layer (nn.Module): Module for an individual decoder layer. num_layers (int): Number of decoder layers. norm (Optional[nn.Module]): Normalization applied after last decoder layer. Default:...
class TransformerDecoder(nn.Module): """ A transformer decoder. Args: decoder_layer (nn.Module): Module for an individual decoder layer. num_layers (int): Number of decoder layers. norm (Optional[nn.Module]): Normalization applied after last decoder layer. Default:...
output = tgt intermediate = [] for layer in self.layers: output = layer( output, memory, tgt_mask=tgt_mask, memory_mask=memory_mask, tgt_key_padding_mask=tgt_key_padding_mask, memory_key...
output = tgt intermediate = [] for layer in self.layers: output = layer( output, memory, tgt_mask=tgt_mask, memory_mask=memory_mask, tgt_key_padding_mask=tgt_key_padding_mask, memory_key...
45
542
238
780
# 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,320
/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
411,422
357,450
forward
TransformerDecoderLayer
422,450
422,450
class TransformerDecoderLayer(nn.Module): """ A single layer from a transformer decoder. 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 TransformerDecoderLayer(nn.Module): """ A single layer from a transformer decoder. 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 = tgt q = k = self.with_pos_embed(x, query_pos) # Self attention self_attention_outputs = self.self_attn( q, k, value=x, attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask )[0] x = x + self.dropout1(self_attention_outputs) x = self.norm1(x) ...
x = tgt q = k = self.with_pos_embed(x, query_pos) # Self attention self_attention_outputs = self.self_attn( q, k, value=x, attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask )[0] x = x + self.dropout1(self_attention_outputs) x = self.norm1(x) ...
68
808
331
1,139
# 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...