repo
stringlengths
1
99
file
stringlengths
13
215
code
stringlengths
12
59.2M
file_length
int64
12
59.2M
avg_line_length
float64
3.82
1.48M
max_line_length
int64
12
2.51M
extension_type
stringclasses
1 value
tensorflow
tensorflow-master/tensorflow/compiler/mlir/tensorflow/tests/tf_saved_model/keras.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
1,705
33.816327
128
py
tensorflow
tensorflow-master/tensorflow/lite/tools/optimize/python/modify_model_interface_lib_test.py
# Copyright 2020 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
6,651
39.809816
80
py
tensorflow
tensorflow-master/tensorflow/lite/testing/op_tests/prelu.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
3,567
34.326733
80
py
tensorflow
tensorflow-master/tensorflow/lite/python/tflite_keras_util.py
# Copyright 2020 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
6,682
33.271795
80
py
tensorflow
tensorflow-master/tensorflow/lite/python/interpreter_test.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
24,036
41.618794
86
py
tensorflow
tensorflow-master/tensorflow/lite/python/lite_v2_test.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
198,532
40.13821
174
py
tensorflow
tensorflow-master/tensorflow/lite/python/tflite_convert_test.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
23,156
37.919328
80
py
tensorflow
tensorflow-master/tensorflow/lite/python/lite.py
# Copyright 2023 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
125,211
37.432167
126
py
tensorflow
tensorflow-master/tensorflow/lite/python/interpreter.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
38,775
37.970854
119
py
tensorflow
tensorflow-master/tensorflow/lite/python/lite_v2_test_util.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
10,180
34.106897
80
py
tensorflow
tensorflow-master/tensorflow/lite/python/lite_test.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
122,961
40.966553
128
py
tensorflow
tensorflow-master/tensorflow/lite/python/analyzer.py
# Copyright 2021 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
3,933
36.113208
99
py
tensorflow
tensorflow-master/tensorflow/lite/python/util.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
40,808
36.96186
100
py
tensorflow
tensorflow-master/tensorflow/lite/python/tflite_convert.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
26,390
36.972662
80
py
tensorflow
tensorflow-master/tensorflow/lite/python/convert.py
# Copyright 2022 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
48,303
39.219817
102
py
tensorflow
tensorflow-master/tensorflow/lite/python/util_test.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
17,660
39.976798
80
py
tensorflow
tensorflow-master/tensorflow/lite/python/metrics/metrics_nonportable_test.py
# Copyright 2021 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
24,544
40.885666
80
py
DataPoisoning_FL
DataPoisoning_FL-master/generate_default_models.py
from federated_learning.arguments import Arguments from federated_learning.nets import Cifar10CNN from federated_learning.nets import FashionMNISTCNN import os import torch from loguru import logger if __name__ == '__main__': args = Arguments(logger) if not os.path.exists(args.get_default_model_folder_path()):...
928
37.708333
96
py
DataPoisoning_FL
DataPoisoning_FL-master/client.py
import torch import torch.optim as optim from sklearn.metrics import confusion_matrix from sklearn.metrics import classification_report from federated_learning.schedulers import MinCapableStepLR import os import numpy import copy class Client: def __init__(self, args, client_idx, train_data_loader, test_data_load...
7,303
33.616114
155
py
DataPoisoning_FL
DataPoisoning_FL-master/federated_learning/arguments.py
from .nets import Cifar10CNN from .nets import FashionMNISTCNN from .worker_selection import BeforeBreakpoint from .worker_selection import AfterBreakpoint from .worker_selection import PoisonerProbability import torch.nn.functional as F import torch import json # Setting the seed for Torch SEED = 1 torch.manual_seed(...
7,025
32.298578
152
py
DataPoisoning_FL
DataPoisoning_FL-master/federated_learning/nets/cifar_10_cnn.py
import torch import torch.nn as nn import torch.nn.functional as F class Cifar10CNN(nn.Module): def __init__(self): super(Cifar10CNN, self).__init__() self.conv1 = nn.Conv2d(3, 32, kernel_size=3, padding=1) self.bn1 = nn.BatchNorm2d(32) self.conv2 = nn.Conv2d(32, 32, kernel_size=3...
1,509
29.2
66
py
DataPoisoning_FL
DataPoisoning_FL-master/federated_learning/nets/fashion_mnist_cnn.py
import torch import torch.nn as nn import torch.nn.functional as F class FashionMNISTCNN(nn.Module): def __init__(self): super(FashionMNISTCNN, self).__init__() self.layer1 = nn.Sequential( nn.Conv2d(1, 16, kernel_size=5, padding=2), nn.BatchNorm2d(16), nn.ReLU...
730
21.84375
56
py
DataPoisoning_FL
DataPoisoning_FL-master/federated_learning/datasets/dataset.py
from abc import abstractmethod from torch.utils.data import DataLoader from torch.utils.data import TensorDataset import torch import numpy class Dataset: def __init__(self, args): self.args = args self.train_dataset = self.load_train_dataset() self.test_dataset = self.load_test_dataset() def get_args(self)...
2,732
23.401786
110
py
DataPoisoning_FL
DataPoisoning_FL-master/federated_learning/datasets/fashion_mnist.py
from .dataset import Dataset from torchvision import datasets from torchvision import transforms from torch.utils.data import DataLoader class FashionMNISTDataset(Dataset): def __init__(self, args): super(FashionMNISTDataset, self).__init__(args) def load_train_dataset(self): self.get_args()....
1,332
38.205882
160
py
DataPoisoning_FL
DataPoisoning_FL-master/federated_learning/datasets/cifar10.py
from .dataset import Dataset from torchvision import datasets from torchvision import transforms from torch.utils.data import DataLoader class CIFAR10Dataset(Dataset): def __init__(self, args): super(CIFAR10Dataset, self).__init__(args) def load_train_dataset(self): self.get_args().get_logger...
1,729
36.608696
126
py
DataPoisoning_FL
DataPoisoning_FL-master/federated_learning/datasets/data_distribution/iid_equal.py
import torch def distribute_batches_equally(train_data_loader, num_workers): """ Gives each worker the same number of batches of training data. :param train_data_loader: Training data loader :type train_data_loader: torch.utils.data.DataLoader :param num_workers: number of workers :type num_wo...
607
29.4
66
py
DataPoisoning_FL
DataPoisoning_FL-master/federated_learning/schedulers/min_lr_step.py
class MinCapableStepLR: def __init__(self, logger, optimizer, step_size, gamma, min_lr): """ :param logger: logger :type logger: loguru.logger :param optimizer: :type optimizer: torch.optim :param step_size: # of epochs between LR updates :type step_size: int...
1,451
28.632653
95
py
DataPoisoning_FL
DataPoisoning_FL-master/federated_learning/parameters/model_comparison.py
import torch def compare_models(logger, model_1, model_2): models_differ = 0 for key_item_1, key_item_2 in zip(model_1.state_dict().items(), model_2.state_dict().items()): if not torch.equal(key_item_1[1], key_item_2[1]): models_differ += 1 if (key_item_1[0] == key_item_2[0]): ...
651
39.75
98
py
DataPoisoning_FL
DataPoisoning_FL-master/federated_learning/parameters/gradients.py
import numpy def calculate_model_gradient(logger, model_1, model_2): """ Calculates the gradient (parameter difference) between two Torch models. :param logger: loguru.logger :param model_1: torch.nn :param model_2: torch.nn """ model_1_parameters = list(dict(model_1.state_dict())) mod...
945
32.785714
88
py
SACD
SACD-main/SACD/inference.py
import time import json import torch import torch.nn.functional as F from collections import defaultdict from utils import AverageMeter def get_video_results(outputs, class_names, output_topk): sorted_scores, locs = torch.topk(outputs, k=min(output_topk, len(class_names))) video_results = [] for i in ran...
2,798
33.555556
85
py
SACD
SACD-main/SACD/main.py
import json import pdb import random import os import numpy as np import torch import torchvision import torch.multiprocessing as mp import torch.distributed as dist from torch.backends import cudnn from torch.nn import CrossEntropyLoss from torch.optim import SGD, lr_scheduler from torch.utils.data import DataLoader f...
21,360
39.533207
142
py
SACD
SACD-main/SACD/val.py
from pathlib import Path import json import random import os import numpy as np import torch from torch.nn import CrossEntropyLoss from torch.optim import SGD, lr_scheduler import torch.multiprocessing as mp import torch.distributed as dist from torch.backends import cudnn import torchvision from opts import parse_op...
16,681
37.976636
86
py
SACD
SACD-main/SACD/validation.py
import time import torch import torch.distributed as dist from utils import AverageMeter, calculate_accuracy def val_epoch(epoch, data_loader, model, criterion, device, logger, tb_writer=None, distributed=False): pri...
2,770
34.987013
99
py
SACD
SACD-main/SACD/training.py
import time import torch import torch.distributed as dist import torch.nn.functional as F import random from utils import AverageMeter, calculate_accuracy, write_to_batch_logger, write_to_epoch_logger from graph_configure import * def train_epoch(epoch, data_loader, model, ...
9,275
39.330435
137
py
SACD
SACD-main/SACD/utils.py
import csv import random from functools import partialmethod import torch import numpy as np from sklearn.metrics import precision_recall_fscore_support class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): ...
2,969
23.957983
95
py
SACD
SACD-main/SACD/model.py
import torch from torch import nn from models import r21d from models import resnet, resnet2p1d, pre_act_resnet, wide_resnet, resnext, densenet from models import composition_classifier def get_module_name(name): name = name.split('.') if name[0] == 'module': i = 1 else: i = 0 if name[...
2,433
28.682927
133
py
SACD
SACD-main/SACD/dataset.py
from torchvision import get_image_backend from datasets.videodataset import VideoDataset from datasets.videodataset_multiclips import (VideoDatasetMultiClips, collate_fn) from datasets.loader import VideoLoader, VideoLoaderHDF5, VideoLoaderFlowHDF5 from datasets.videodata...
8,779
41.829268
106
py
SACD
SACD-main/SACD/train.py
import argparse import os import torch from torch import nn from torch.nn import functional as F from data import data_helper from models import model_factory from optimizer.optimizer_helper import * from utils.Logger import Logger from utils.losses import * from utils.anchor_selector import * from tqdm import tqdm imp...
14,626
48.921502
155
py
SACD
SACD-main/SACD/spatial_transforms.py
import random from torchvision.transforms import transforms from torchvision.transforms import functional as F from PIL import Image class Compose(transforms.Compose): def randomize_parameters(self): for t in self.transforms: t.randomize_parameters() class ToTensor(transforms.ToTensor): ...
5,663
24.628959
95
py
SACD
SACD-main/SACD/models/resnet2p1d.py
import math from functools import partial import torch import torch.nn as nn import torch.nn.functional as F def get_inplanes(): return [64, 128, 256, 512] def conv1x3x3(in_planes, mid_planes, stride=1): return nn.Conv3d(in_planes, mid_planes, kernel_size=(1, 3, 3)...
9,642
32.716783
80
py
SACD
SACD-main/SACD/models/pre_act_resnet.py
import torch import torch.nn as nn import torch.nn.functional as F from .resnet import conv3x3x3, conv1x1x1, get_inplanes, ResNet class PreActivationBasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None): super().__init__() self.bn1 = nn.BatchNo...
3,041
27.698113
79
py
SACD
SACD-main/SACD/models/resnet.py
import math from functools import partial import torch import torch.nn as nn import torch.nn.functional as F def get_inplanes(): return [64, 128, 256, 512] def conv3x3x3(in_planes, out_planes, stride=1): return nn.Conv3d(in_planes, out_planes, kernel_size=3, ...
7,549
31.12766
80
py
SACD
SACD-main/SACD/models/densenet.py
import math import torch import torch.nn as nn import torch.nn.functional as F from collections import OrderedDict class _DenseLayer(nn.Sequential): def __init__(self, num_input_features, growth_rate, bn_size, drop_rate): super().__init__() self.add_module('norm1', nn.BatchNorm3d(num_input_featu...
7,182
37.827027
95
py
SACD
SACD-main/SACD/models/resnext.py
import math from functools import partial import torch import torch.nn as nn import torch.nn.functional as F from .resnet import conv1x1x1, Bottleneck, ResNet from utils import partialclass def get_inplanes(): return [128, 256, 512, 1024] class ResNeXtBottleneck(Bottleneck): expansion = 2 def __init_...
2,402
31.04
74
py
SACD
SACD-main/SACD/models/wide_resnet.py
import torch import torch.nn as nn import torch.nn.functional as F from . import resnet class WideBottleneck(resnet.Bottleneck): expansion = 2 def generate_model(model_depth, k, **kwargs): assert model_depth in [50, 101, 152, 200] inplanes = [x * k for x in resnet.get_inplanes()] if model_depth ==...
784
28.074074
80
py
SACD
SACD-main/SACD/models/r21d.py
"""R2plus1D""" import math from collections import OrderedDict import torch import torch.nn as nn from torch.nn.modules.utils import _triple class SpatioTemporalConv(nn.Module): """Applies a factored 3D convolution over an input signal composed of several input planes with distinct spatial and time axes, by p...
10,212
43.212121
135
py
SACD
SACD-main/SACD/models/composition_classifier.py
import torch import torch.nn as nn import torch.nn.functional as F class CompositionClassifier(nn.Module): def __init__(self, input_dim, num_classes, normalization_sign=False): super().__init__() half_input_dim = int(input_dim / 2) self.mlp = nn.Linear(input_dim, half_input_dim) s...
1,286
29.642857
113
py
SACD
SACD-main/SACD/datasets/activitynet.py
import math import json import torch import torch.utils.data as data from .loader import VideoLoader from .videodataset import VideoDataset def get_n_frames(video_path): return len([ x for x in video_path.iterdir() if 'image' in x.name and x.name[0] != '.' ]) def get_class_labels(data): ...
5,382
31.624242
80
py
SACD
SACD-main/SACD/datasets/videodataset_multiclips.py
import copy import torch from torch.utils.data.dataloader import default_collate from .videodataset import VideoDataset def collate_fn(batch): batch_clips, batch_targets = zip(*batch) batch_clips = [clip for multi_clips in batch_clips for clip in multi_clips] batch_targets = [ target for multi_ta...
2,303
33.909091
79
py
SACD
SACD-main/SACD/datasets/videodataset.py
import json import os import torch import torch.utils.data as data from pathlib import Path from .loader import VideoLoader from .loader import EEGFeatureLoader from random import randrange import numpy as np def get_class_labels(data): class_labels_map = {} index = 0 for class_label in data['labels']: ...
10,023
33.805556
99
py
SACD
SACD-main/SACD/grad_cam/main_swin.py
import os import math import numpy as np import torch from PIL import Image import matplotlib.pyplot as plt from torchvision import transforms from utils import GradCAM, show_cam_on_image, center_crop_img from swin_model import swin_base_patch4_window7_224 class ResizeTransform: def __init__(self, im_h: int, im_w...
2,632
31.109756
109
py
SACD
SACD-main/SACD/grad_cam/swin_model.py
""" Swin Transformer A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` - https://arxiv.org/pdf/2103.14030 Code/weights from https://github.com/microsoft/Swin-Transformer """ import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoin...
28,233
40.704579
113
py
SACD
SACD-main/SACD/grad_cam/utils.py
import cv2 import numpy as np class ActivationsAndGradients: """ Class for extracting activations and registering gradients from targeted intermediate layers """ def __init__(self, model, target_layers, reshape_transform): self.model = model self.gradients = [] self.activations = ...
8,018
33.714286
111
py
SACD
SACD-main/SACD/grad_cam/main_cnn.py
import os import numpy as np import torch from PIL import Image import matplotlib.pyplot as plt from torchvision import models from torchvision import transforms from utils import GradCAM, show_cam_on_image, center_crop_img def main(): model = models.mobilenet_v3_large(pretrained=True) target_layers = [model....
1,846
30.844828
109
py
SACD
SACD-main/SACD/grad_cam/vit_model.py
""" original code from rwightman: https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py """ from functools import partial from collections import OrderedDict import torch import torch.nn as nn def drop_path(x, drop_prob: float = 0., training: bool = False): """ Drop ...
18,204
42.037825
126
py
SACD
SACD-main/SACD/grad_cam/main_vit.py
import os import numpy as np import torch from PIL import Image import matplotlib.pyplot as plt from torchvision import transforms from utils import GradCAM, show_cam_on_image, center_crop_img from vit_model import vit_base_patch16_224 class ReshapeTransform: def __init__(self, model): input_size = model....
2,710
35.146667
101
py
SACD
SACD-main/SACD/util_scripts/remove_dataparallel.py
import argparse from collections import OrderedDict import torch parser = argparse.ArgumentParser() parser.add_argument('file_path', type=str) parser.add_argument('--dst_file_path', default=None, type=str) args = parser.parse_args() if args.dst_file_path is None: args.dst_file_path = args.file_path x = torch.lo...
569
22.75
62
py
SACD
SACD-main/SACD/loss/nce_loss.py
import torch import torch.nn.functional as F from torch import nn EPISILON=1e-10 class NCELoss(torch.nn.Module): def __init__(self, temperature=1): super(NCELoss, self).__init__() self.temperature = temperature self.softmax = nn.Softmax(dim=1) def where(self, cond, x_1, x_2): cond = cond.type(to...
1,346
28.933333
122
py
SACD
SACD-main/SACD/loss/jsd_loss.py
import torch import torch.nn.functional as F EPISILON=1e-10 class JSDLoss(torch.nn.Module): def __init__(self, weight=1.0, softmax_sign=False): super(JSDLoss, self).__init__() self.weight = weight self.softmax_sign = softmax_sign def forward(self, p, q): if self.softmax_sign is False: p = ...
587
20.777778
53
py
linkPrediction
linkPrediction-master/classification.py
import pandas as pd import networkx as nx import utils as ut import numpy as np from keras.models import Model, Sequential from keras import optimizers from keras.layers import LSTM, Dense from keras.layers.normalization import BatchNormalization from keras.layers.core import Dense, Dropout, Activation, Reshape from sk...
9,347
40.180617
111
py
linkPrediction
linkPrediction-master/versions.py
# scipy import scipy print('scipy: %s' % scipy.__version__) # numpy import numpy print('numpy: %s' % numpy.__version__) # matplotlib import matplotlib print('matplotlib: %s' % matplotlib.__version__) # pandas import pandas print('pandas: %s' % pandas.__version__) # scikit-learn import sklearn print('sklearn: %s' % skle...
627
21.428571
50
py
Fund-EL
Fund-EL-main/Entity Linking/EDFunctions.py
from transformers import BertTokenizerFast from torch.utils.data import TensorDataset import torch #Functions ENT_START_TAG = "[unused0]" ENT_END_TAG = "[unused1]" def get_context_representation( sample, tokenizer, max_seq_length, mention_key="mention", context_key="context", ent_start_token=EN...
3,133
30.979592
142
py
Fund-EL
Fund-EL-main/Entity Linking/NERFunctions.py
import pandas as pd import numpy as np import torch #Add [CLS] and [SEP] tokens, pad until "pad_len" chars. def add_and_pad(lst,pad_len,cls,sep,pad): new_lst = [] for item in lst: new_item = [cls] + item + [sep] while len(new_item) != pad_len: new_item.append(pad) new_lst.ap...
7,287
37.765957
135
py
Fund-EL
Fund-EL-main/Named Entity Recognition/NERFunctions.py
import pandas as pd import numpy as np import torch #Add [CLS] and [SEP] tokens, pad until "pad_len" chars. def add_and_pad(lst,pad_len,cls,sep,pad): new_lst = [] for item in lst: new_item = [cls] + item + [sep] while len(new_item) != pad_len: new_item.append(pad) new_lst.ap...
7,287
37.765957
135
py
RelationalFutureCaptioningModel
RelationalFutureCaptioningModel-main/precompute_text.py
""" Utility to precompute text features. Notes: If running other models than BERT, be aware of the following things: The preprocessor function for BERT adds [SEP] and [CLS], use a different preprocessor to create different tokens for another models. Optionally set "add_special_tokens" to True in the da...
20,065
44.295711
119
py
RelationalFutureCaptioningModel
RelationalFutureCaptioningModel-main/mart_build_vocab.py
""" Build vocabulary for MART. References: Copyright (c) 2017 Jie Lei Licensed under The MIT License, see https://choosealicense.com/licenses/mit/ @inproceedings{lei2020mart, title={MART: Memory-Augmented Recurrent Transformer for Coherent Video Paragraph Captioning}, author={Lei, Jie and W...
4,698
33.551471
110
py
RelationalFutureCaptioningModel
RelationalFutureCaptioningModel-main/train_caption.py
""" Train captioning with MART. Originally published by https://github.com/jayleicn/recurrent-transformer under MIT license Reworked by https://github.com/gingsi/coot-videotext under Apache 2 license """ import numpy as np from coot.configs_retrieval import ExperimentTypesConst from mart import arguments_mart from m...
5,521
42.825397
121
py
RelationalFutureCaptioningModel
RelationalFutureCaptioningModel-main/mart/optimization.py
""" PyTorch optimization for BERT model. Required. References: Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. Licensed under the Apache License, Version 2.0, see http://www.apache.org/licenses/LICENSE-2.0 check if this is needed? Can't I just use regular Adam, AdamW, RAdam, ...
15,322
35.570406
118
py
RelationalFutureCaptioningModel
RelationalFutureCaptioningModel-main/mart/recursive_caption_dataset.py
""" Captioning dataset. """ import copy import json import math import os from pathlib import Path from typing import List, Optional, Tuple import h5py import nltk import numpy as np import torch from torch.utils import data from torch.utils.data.dataloader import default_collate from tqdm import tqdm import sys from...
27,806
34.377863
105
py
RelationalFutureCaptioningModel
RelationalFutureCaptioningModel-main/mart/model.py
""" MART model. """ import copy import logging import math from pathlib import Path import sys import numpy as np import torch import torch.nn.functional as F from torch import nn from torch.utils.tensorboard.summary import video from mart.configs_mart import MartConfig, MartPathConst from mart.masked_transformer imp...
35,697
36.03112
320
py
RelationalFutureCaptioningModel
RelationalFutureCaptioningModel-main/mart/loss_caption.py
""" MART loss. """ import torch import torch.nn.functional as F from torch import nn class LabelSmoothingLoss(nn.Module): """ With label smoothing, KL-divergence between q_{smoothed ground truth prob.}(w) and p_{prob. computed by model}(w) is minimized. """ def __init__(self, label_smoothing...
1,719
32.076923
96
py
RelationalFutureCaptioningModel
RelationalFutureCaptioningModel-main/mart/masked_transformer.py
""" Classic Vanilla Transformer (BERT-like). References: Copyright (c) 2018, salesforce.com, inc. All rights reserved. SPDX-License-Identifier: BSD-3-Clause, see https://opensource.org/licenses/BSD-3-Clause History: https://github.com/salesforce/densecap https://github.com/jayleicn/recurrent-t...
10,247
32.6
113
py
RelationalFutureCaptioningModel
RelationalFutureCaptioningModel-main/mart/beam_search.py
""" https://github.com/OpenNMT/OpenNMT-py/blob/master/onmt/translate/beam_search.py References: Copyright (c) 2017 Adam Lerer Licensed under The MIT License, see https://choosealicense.com/licenses/mit/ @inproceedings{klein-etal-2017-opennmt, title = "{O}pen{NMT}: Open-Source Toolkit for Neural Mac...
17,745
36.438819
88
py
RelationalFutureCaptioningModel
RelationalFutureCaptioningModel-main/mart/trainer_caption.py
""" Trainer for retrieval training and validation. Holds the main training loop. """ import json import logging import os from collections import defaultdict from collections.abc import Mapping from glob import glob from pathlib import Path from timeit import default_timer as timer from typing import Dict, List, Optio...
41,225
39.220488
118
py
RelationalFutureCaptioningModel
RelationalFutureCaptioningModel-main/mart/translator.py
""" Text generation, greedy or beam search. References: Copyright (c) 2017 Jie Lei Licensed under The MIT License, see https://choosealicense.com/licenses/mit/ @inproceedings{lei2020mart, title={MART: Memory-Augmented Recurrent Transformer for Coherent Video Paragraph Captioning}, author={L...
22,226
37.256454
109
py
RelationalFutureCaptioningModel
RelationalFutureCaptioningModel-main/nntrainer/lr_scheduler.py
""" LR Schedulers completely rewritten from scratch. These fit better to some use cases than the PyTorch LR schedulers. Features: All required information is passed to the schedulers: (total number of epochs, training steps per epoch, validation improvements) Option for warmup per step or per epoch in...
17,000
36.039216
116
py
RelationalFutureCaptioningModel
RelationalFutureCaptioningModel-main/nntrainer/optimization.py
""" Optimizers. """ import math from typing import Dict, Iterable import torch as th from torch.optim import Adam from torch.optim.optimizer import Optimizer from nntrainer import typext class OptimizerConst(typext.ConstantHolder): """ Optimizer name constants. """ ADAM = "adam" RADAM = "radam"...
10,552
38.524345
110
py
RelationalFutureCaptioningModel
RelationalFutureCaptioningModel-main/nntrainer/data.py
""" Dataset utilities. """ from typing import Any, Callable, List, Optional from torch.utils import data from nntrainer import trainer_configs, typext class DataSplitConst(typext.ConstantHolder): """ Store dataset splits. """ TRAIN = "train" VAL = "val" TEST = "test" def create_loader(dat...
966
25.135135
105
py
RelationalFutureCaptioningModel
RelationalFutureCaptioningModel-main/nntrainer/typext.py
""" Custom typing extension. Classes: ConstantHolder: Base class for storing constants and avoiding to hardcode everything. SaveableBaseModel: Child class of pydantic.BaseModel which enables saving and loading that BaseModel. TypedNamedTuple: Child class of SaveableBaseModel, can be used similarly to a Nam...
16,825
31.671845
118
py
RelationalFutureCaptioningModel
RelationalFutureCaptioningModel-main/nntrainer/retrieval.py
""" Utility code for doing retrieval. """ from timeit import default_timer as timer from typing import Callable, Dict, Tuple import numpy as np import torch as th VALKEYS = ["r1", "r5", "r10", "r50", "medr", "meanr", "sum"] VALHEADER = "Retriev | R@1 | R@5 | R@10 | R@50 | MeanR | MedR | Sum" def retriev...
3,505
34.414141
114
py
RelationalFutureCaptioningModel
RelationalFutureCaptioningModel-main/nntrainer/initialization.py
""" Network initialization. """ import torch as th from torch import nn from nntrainer import utils_torch, typext, utils def init_weight_(w: th.Tensor, init_type="uniform", init_std=1) -> None: """ Initialize given tensor. Args: w: Tensor to initialize in-place. init_type: Distribution t...
3,871
33.571429
114
py
RelationalFutureCaptioningModel
RelationalFutureCaptioningModel-main/nntrainer/trainer_base.py
""" Generic Deep Learning trainer that automates tasks required for all kinds of training. """ import datetime import logging import os from pathlib import Path from timeit import default_timer as timer from typing import Any, Dict, List, Optional, Tuple import torch as th from torch import nn from torch.backends impo...
32,989
43.104278
120
py
RelationalFutureCaptioningModel
RelationalFutureCaptioningModel-main/nntrainer/utils_torch.py
""" Utilities for randomness. """ import ctypes import multiprocessing import os import random import subprocess import time import traceback from timeit import default_timer as timer from typing import Any, Dict, List, Tuple import GPUtil import numpy as np import psutil import torch as th import torch.backends.cudnn...
8,025
32.302905
118
py
RelationalFutureCaptioningModel
RelationalFutureCaptioningModel-main/nntrainer/metric.py
""" Metric writing and reading utilities. This automates the following: - Logging the same metrics both to text files and to tensorboard. - Reload old metrics when resuming training. - Only save metrics where something was logged to. """ import json import logging from collections import defaultdict from ...
16,453
36.825287
117
py
RelationalFutureCaptioningModel
RelationalFutureCaptioningModel-main/nntrainer/examples/mlp_mnist.py
""" Setup a simple 2-layer MLP experiment on the MNIST dataset. """ import logging from functools import partial from timeit import default_timer as timer from typing import Dict, Optional, Tuple import torch as th from torch import nn from torch.utils import data as th_data from tqdm import tqdm from nntrainer impo...
11,933
36.29375
120
py
RelationalFutureCaptioningModel
RelationalFutureCaptioningModel-main/nntrainer/examples/run_mlp_mnist.py
""" Script to run the MLP MNIST example. Examples: python -m nntrainer.examples.run_mlp_mnist -e mnist python -m nntrainer.examples.run_mlp_mnist -c config/mlp/default/mnist.yaml python -m nntrainer.examples.run_mlp_mnist -e mnist -n 3 Notes: Training workflow will look like this: 1. Load config...
4,849
35.466165
120
py
RelationalFutureCaptioningModel
RelationalFutureCaptioningModel-main/nntrainer/models/mlp.py
""" Fully connected network model. """ from functools import partial from typing import Any, Dict, List, Optional from torch import nn from nntrainer import models, typext, utils class ResidualsEnum(typext.ConstantHolder): """ Residuals. None: No residual. Passthrough: Pass input directly as the re...
6,203
36.373494
118
py
RelationalFutureCaptioningModel
RelationalFutureCaptioningModel-main/nntrainer/models/transformer_legacy.py
""" Transformer implementation. Similar inference speed to pytorch built-in transformers. """ from typing import Any, Dict, List, Optional, cast import numpy as np import torch as th from torch import nn import nntrainer.trainer_configs import nntrainer.typext import nntrainer.utils_torch from nntrainer.initializat...
22,104
36.915952
119
py
RelationalFutureCaptioningModel
RelationalFutureCaptioningModel-main/nntrainer/models/encoder.py
""" Positional encoding for transformer input. """ from __future__ import annotations from typing import Any, Dict, Optional, Union import torch as th from torch import nn from nntrainer import typext, utils def make_encoder_module(dim: int, name: str, cfg: Optional[EncoderConfig] = None) -> Optional[nn.Module]: ...
3,839
30.735537
115
py
RelationalFutureCaptioningModel
RelationalFutureCaptioningModel-main/nntrainer/models/poolers.py
""" Pooling modules. """ from __future__ import annotations from typing import Any, Dict, List, Optional, Union import torch from torch import nn from nntrainer import typext from nntrainer.models.activations import ActivationConfig, make_activation_module from nntrainer.typext import INF def make_pooler_module(no...
10,048
33.771626
119
py
RelationalFutureCaptioningModel
RelationalFutureCaptioningModel-main/nntrainer/models/activations.py
""" Activation functions. """ from __future__ import annotations from typing import Any, Dict, Optional, Union from torch import nn from nntrainer import typext, utils def make_activation_module(name: str, cfg: Optional[ActivationConfig] = None) -> nn.Module: """ Get activation module instance given by nam...
1,923
28.151515
110
py
RelationalFutureCaptioningModel
RelationalFutureCaptioningModel-main/nntrainer/models/normalizations.py
""" Normalization functions. """ from __future__ import annotations from typing import Any, Dict, List, Optional, Union import torch as th from torch import nn import nntrainer.utils from nntrainer.typext import ConfigClass, ConstantHolder def make_normalization_module(normalized_shape: Union[int, List[int], th.Si...
3,479
33.117647
120
py
RelationalFutureCaptioningModel
RelationalFutureCaptioningModel-main/nntrainer/models/model_manager_base.py
""" Base class for the model manager that handles generic model-related tasks. This way, trainer and model can be separated in the code. """ from typing import Any, Dict, List, Tuple import numpy as np import torch as th from torch import nn import nntrainer.trainer_configs class BaseModelManager: def __init_...
6,006
36.779874
105
py
RelationalFutureCaptioningModel
RelationalFutureCaptioningModel-main/coot/features_loader.py
""" Feature loading. """ import json import os from pathlib import Path from typing import List, Tuple import h5py import numpy as np from tqdm import tqdm from nntrainer.utils_torch import create_shared_array class VideoFeatureLoader: """ Helper class to load video features (h5) format. Args: ...
8,017
39.908163
117
py
RelationalFutureCaptioningModel
RelationalFutureCaptioningModel-main/coot/loss_fn.py
""" Loss functions. """ from typing import Callable, Dict import torch as th from torch import nn from nntrainer import typext from nntrainer.typext import INF class LossesConst(typext.ConstantHolder): CONTRASTIVE = "contrastive" CROSSENTROPY = "crossentropy" def cosine_sim(visual_emb: th.Tensor, text_em...
15,912
40.012887
120
py
BNPG
BNPG-main/BN_MAPPO_Aloha/onpolicy/config.py
import argparse def get_config(): """ The configuration parser for common hyperparameters of all environment. Please reach each `scripts/train/<env>_runner.py` file to find private hyperparameters only used in <env>. Prepare parameters: --algorithm_name <algorithm_name> specifi...
16,575
55.767123
261
py
BNPG
BNPG-main/BN_MAPPO_Aloha/onpolicy/envs/env_wrappers.py
""" Modified from OpenAI Baselines code to work with multi-agent envs """ import numpy as np import torch from multiprocessing import Process, Pipe from abc import ABC, abstractmethod from onpolicy.utils.util import tile_images class CloudpickleWrapper(object): """ Uses cloudpickle to serialize contents (other...
28,231
33.262136
118
py
BNPG
BNPG-main/BN_MAPPO_Aloha/onpolicy/envs/aloha/aloha.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from .multiagentenv import MultiAgentEnv import atexit from operator import attrgetter from copy import deepcopy import numpy as np import enum import math from absl import logging import random from gym imp...
6,394
30.658416
172
py
BNPG
BNPG-main/BN_MAPPO_Aloha/onpolicy/algorithms/r_mappo/r_mappo.py
import numpy as np import torch import torch.nn as nn from onpolicy.utils.util import get_gard_norm, huber_loss, mse_loss from onpolicy.algorithms.utils.util import _h_A from onpolicy.utils.popart import PopArt from onpolicy.algorithms.utils.util import check import json class R_MAPPO(): """ Trainer class for ...
11,581
47.258333
266
py
BNPG
BNPG-main/BN_MAPPO_Aloha/onpolicy/algorithms/r_mappo/algorithm/r_actor_critic.py
import torch import torch.nn as nn from onpolicy.algorithms.utils.util import init, check from onpolicy.algorithms.utils.cnn import CNNBase from onpolicy.algorithms.utils.mlp import MLPBase from onpolicy.algorithms.utils.rnn import RNNLayer from onpolicy.algorithms.utils.act import ACTLayer from onpolicy.utils.util imp...
11,876
51.321586
137
py