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
EmpTransfo
EmpTransfo-master/pytorch_pretrained_bert/optimization.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # # 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/LICEN...
13,028
42
139
py
EmpTransfo
EmpTransfo-master/pytorch_pretrained_bert/optimization_openai.py
# coding=utf-8 # Copyright 2018 The Open AI Team Authors and The HuggingFace Inc. team. # # 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 # # ...
5,517
42.109375
134
py
EmpTransfo
EmpTransfo-master/pytorch_pretrained_bert/__main__.py
# coding: utf8 def main(): import sys if (len(sys.argv) != 4 and len(sys.argv) != 5) or sys.argv[1] not in [ "convert_tf_checkpoint_to_pytorch", "convert_openai_checkpoint", "convert_transfo_xl_checkpoint", "convert_gpt2_checkpoint", ]: print( "Should be used ...
4,393
51.309524
145
py
EmpTransfo
EmpTransfo-master/pytorch_pretrained_bert/convert_gpt2_checkpoint_to_pytorch.py
# coding=utf-8 # Copyright 2018 The HuggingFace Inc. team. # # 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 applicable...
3,017
40.342466
111
py
EmpTransfo
EmpTransfo-master/pytorch_pretrained_bert/convert_openai_checkpoint_to_pytorch.py
# coding=utf-8 # Copyright 2018 The HuggingFace Inc. team. # # 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 applicable...
3,106
41.561644
118
py
EmpTransfo
EmpTransfo-master/pytorch_pretrained_bert/tokenization.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # # 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/LICEN...
18,169
40.770115
135
py
EmpTransfo
EmpTransfo-master/pytorch_pretrained_bert/modeling.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. 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 cop...
85,247
51.524954
187
py
EmpTransfo
EmpTransfo-master/pytorch_pretrained_bert/modeling_gpt2.py
# coding=utf-8 # Copyright 2018 The OpenAI Team Authors and HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. 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...
38,587
45.944039
146
py
EmpTransfo
EmpTransfo-master/pytorch_pretrained_bert/modeling_openai.py
# coding=utf-8 # Copyright 2018 The OpenAI Team Authors and HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. 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...
53,002
47.626606
186
py
EmpTransfo
EmpTransfo-master/pytorch_pretrained_bert/convert_transfo_xl_checkpoint_to_pytorch.py
# coding=utf-8 # Copyright 2018 The HuggingFace Inc. team. # # 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 applicable...
5,671
47.478632
121
py
EmpTransfo
EmpTransfo-master/pytorch_pretrained_bert/file_utils.py
""" Utilities for working with the local dataset cache. This file is adapted from the AllenNLP library at https://github.com/allenai/allennlp Copyright by the AllenNLP authors. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import sys import json import logging import os impor...
9,347
32.385714
98
py
EmpTransfo
EmpTransfo-master/pytorch_pretrained_bert/convert_tf_checkpoint_to_pytorch.py
# coding=utf-8 # Copyright 2018 The HuggingFace Inc. team. # # 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 applicable...
2,593
37.716418
101
py
EmpTransfo
EmpTransfo-master/pytorch_pretrained_bert/modeling_transfo_xl.py
# coding=utf-8 # Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Lice...
59,065
41.40201
131
py
EmpTransfo
EmpTransfo-master/pytorch_pretrained_bert/tokenization_transfo_xl.py
# coding=utf-8 # Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Lice...
22,060
36.582624
110
py
EmpTransfo
EmpTransfo-master/pytorch_pretrained_bert/modeling_transfo_xl_utilities.py
# coding=utf-8 # Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Lice...
16,108
38.972705
132
py
potapov_interpolation
potapov_interpolation-master/docs/conf.py
# -*- coding: utf-8 -*- # # Potapov_interpolation documentation build configuration file, created by # sphinx-quickstart on Mon Apr 25 15:36:39 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerat...
10,438
30.923547
85
py
gnn_cff
gnn_cff-main/graphconv.py
"""Torch modules for graph convolutions(GCN).""" # pylint: disable= no-member, arguments-differ, invalid-name import torch as th from torch import nn from torch.nn import init from .... import function as fn from ....base import DGLError from ....utils import expand_as_pair from ....transform import reverse from ....c...
30,598
40.072483
102
py
gnn_cff
gnn_cff-main/models/gcn.py
import numpy as np from dgl.nn.pytorch import GraphConv import dgl import torch # class GCNGraphNew(torch.nn.Module): # def __init__(self, in_feats, h_feats): # super(GCNGraphNew, self).__init__() # self.conv1 = GraphConv(in_feats, h_feats) # self.conv2 = GraphConv(h_feats, h_feats) # ...
4,777
36.622047
112
py
gnn_cff
gnn_cff-main/models/explainer_models.py
from re import S import numpy as np import torch import math import tqdm import sys import matplotlib.pyplot as plt import networkx as nx from utils.common_utils import mutag_dgl_to_networkx, get_mutag_color_dict, ba_shapes_dgl_to_networkx class GraphExplainerEdge(torch.nn.Module): def __init__(self, base_model, ...
27,933
40.079412
142
py
gnn_cff
gnn_cff-main/scripts/exp_node_tree_cycles.py
import os import numpy as np import torch from utils.argument import arg_parse_exp_node_tree_cycles from models.explainer_models import NodeExplainerEdgeMulti from models.gcn import GCNNodeTreeCycles from utils.preprocessing.tree_cycles_preprocessing import TreeCyclesDataset import sys if __name__ == "__main__": ...
1,650
35.688889
116
py
gnn_cff
gnn_cff-main/scripts/exp_node_ba_shapes.py
import os import numpy as np import torch from utils.argument import arg_parse_exp_node_ba_shapes from models.explainer_models import NodeExplainerEdgeMulti from models.gcn import GCNNodeBAShapes from utils.preprocessing.ba_shapes_preprocessing import BAShapesDataset import sys if __name__ == "__main__": torch.ma...
1,646
37.302326
116
py
gnn_cff
gnn_cff-main/scripts/train_graph_classification.py
import numpy as np import torch import os import time from pathlib import Path from models.gcn import GCNGraph from utils.argument import arg_parse_train_graph_mutag_0 from utils.graph_init import graph_init_real from torch.utils.data.sampler import SubsetRandomSampler from dgl.dataloading import GraphDataLoader def ...
3,833
39.787234
117
py
gnn_cff
gnn_cff-main/scripts/exp_graph.py
import os import numpy as np import torch from utils.argument import arg_parse_exp_graph_mutag_0 from models.explainer_models import GraphExplainerEdge from models.gcn import GCNGraph from utils.preprocessing.mutag_preprocessing_0 import MutagDataset0 import sys if __name__ == "__main__": np.set_printoptions(thre...
1,428
32.232558
96
py
gnn_cff
gnn_cff-main/scripts/train_node_classification.py
import numpy as np import torch import os import time from pathlib import Path from models.gcn import GCNNodeBAShapes from utils.argument import arg_parse_train_node_ba_shapes from utils.graph_init import graph_init_real from torch.utils.data.sampler import SubsetRandomSampler from dgl.dataloading import GraphDataLoade...
4,554
38.95614
104
py
gnn_cff
gnn_cff-main/utils/preprocessing/ba_shapes_preprocessing.py
"""Read the Mutag dataset and create the graphx""" import numpy as np import os import dgl from dgl.data import DGLDataset import torch import networkx as nx import matplotlib.pyplot as plt from dgl import save_graphs, load_graphs from utils.common_utils import read_file from utils.common_utils import ba_shapes_dgl_to...
5,366
37.335714
109
py
gnn_cff
gnn_cff-main/utils/preprocessing/mutag_preprocessing_0.py
"""Read the Mutag dataset and create the graphx""" import numpy as np import os import dgl from dgl.data import DGLDataset import torch from dgl import save_graphs, load_graphs from utils.common_utils import read_file class MutagDataset0(DGLDataset): def __init__(self, edges=None, graph_indicator=None, node_labe...
5,400
41.865079
128
py
gnn_cff
gnn_cff-main/utils/preprocessing/tree_cycles_preprocessing.py
"""Read the Mutag dataset and create the graphx""" import numpy as np import os import dgl from dgl.data import DGLDataset import torch import networkx as nx import matplotlib.pyplot as plt from dgl import save_graphs, load_graphs from utils.common_utils import read_file from utils.common_utils import ba_shapes_dgl_to...
5,903
36.367089
109
py
gnn_cff
gnn_cff-main/utils/preprocessing/citeseer_preprocessing.py
"""Read the Mutag dataset and create the graphx""" import numpy as np import os import dgl from dgl.data import DGLDataset import torch import networkx as nx import matplotlib.pyplot as plt from dgl import save_graphs, load_graphs from utils.common_utils import read_file_citeseer from utils.common_utils import ba_shap...
5,767
34.170732
109
py
gnn_cff
gnn_cff-main/utils/preprocessing/nci1_preprocessing.py
"""Read the Mutag dataset and create the graphx""" import numpy as np import os import dgl from dgl.data import DGLDataset import torch from dgl import save_graphs, load_graphs from utils.common_utils import read_file class NCI1Dataset(DGLDataset): def __init__(self, edges=None, graph_indicator=None, node_labels...
4,663
41.4
112
py
hifi-gan
hifi-gan-master/inference.py
from __future__ import absolute_import, division, print_function, unicode_literals import glob import os import argparse import json import torch from scipy.io.wavfile import write from env import AttrDict from meldataset import mel_spectrogram, MAX_WAV_VALUE, load_wav from models import Generator h = None device = N...
2,652
26.635417
107
py
hifi-gan
hifi-gan-master/inference_e2e.py
from __future__ import absolute_import, division, print_function, unicode_literals import glob import os import numpy as np import argparse import json import torch from scipy.io.wavfile import write from env import AttrDict from meldataset import MAX_WAV_VALUE from models import Generator h = None device = None de...
2,444
25.868132
105
py
hifi-gan
hifi-gan-master/meldataset.py
import math import os import random import torch import torch.utils.data import numpy as np from librosa.util import normalize from scipy.io.wavfile import read from librosa.filters import mel as librosa_mel_fn MAX_WAV_VALUE = 32768.0 def load_wav(full_path): sampling_rate, data = read(full_path) return data...
6,314
36.366864
115
py
hifi-gan
hifi-gan-master/utils.py
import glob import os import matplotlib import torch from torch.nn.utils import weight_norm matplotlib.use("Agg") import matplotlib.pylab as plt def plot_spectrogram(spectrogram): fig, ax = plt.subplots(figsize=(10, 2)) im = ax.imshow(spectrogram, aspect="auto", origin="lower", interpolatio...
1,377
22.355932
63
py
hifi-gan
hifi-gan-master/models.py
import torch import torch.nn.functional as F import torch.nn as nn from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm from utils import init_weights, get_padding LRELU_SLOPE = 0.1 class ResBlock1(torch.nn.Module): def __init__...
9,905
33.880282
107
py
hifi-gan
hifi-gan-master/train.py
import warnings warnings.simplefilter(action='ignore', category=FutureWarning) import itertools import os import time import argparse import json import torch import torch.nn.functional as F from torch.utils.tensorboard import SummaryWriter from torch.utils.data import DistributedSampler, DataLoader import torch.multip...
12,153
43.683824
123
py
LowFat
LowFat-master/llvm-4.0.0.src/tools/clang/docs/conf.py
# -*- coding: utf-8 -*- # # Clang documentation build configuration file, created by # sphinx-quickstart on Sun Dec 9 20:01:55 2012. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All c...
9,128
32.317518
83
py
LowFat
LowFat-master/llvm-4.0.0.src/tools/clang/docs/analyzer/conf.py
# -*- coding: utf-8 -*- # # Clang Static Analyzer documentation build configuration file, created by # sphinx-quickstart on Wed Jan 2 15:54:28 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated...
8,070
31.544355
80
py
DMASTE
DMASTE-main/Span-ASTE/span_model/training/ner_metrics.py
from overrides import overrides from typing import Optional import torch from allennlp.training.metrics.metric import Metric from span_model.training.f1 import compute_f1 # TODO: Need to use the decoded predictions so that we catch the gold examples longer than # the span boundary. class NERMetrics(Metric): "...
2,358
29.636364
95
py
DMASTE
DMASTE-main/Span-ASTE/span_model/models/ner.py
import logging from typing import Any, Dict, List, Optional, Callable import torch from torch.nn import functional as F from overrides import overrides from allennlp.data import Vocabulary from allennlp.models.model import Model from allennlp.modules import TimeDistributed from allennlp.nn import util, InitializerApp...
10,868
39.707865
121
py
DMASTE
DMASTE-main/Span-ASTE/span_model/models/embedder.py
from typing import Optional, Tuple from overrides import overrides import torch from allennlp.modules.token_embedders import PretrainedTransformerEmbedder, TokenEmbedder from allennlp.nn import util from allennlp.modules.scalar_mix import ScalarMix @TokenEmbedder.register("double_mix_ptm") class DoubleMixPTMEmbedde...
7,218
44.689873
131
py
DMASTE
DMASTE-main/Span-ASTE/span_model/models/relation_proper.py
import logging from typing import Any, Dict, List, Optional, Callable import torch import torch.nn.functional as F from overrides import overrides from allennlp.data import Vocabulary from allennlp.models.model import Model from allennlp.nn import util, RegularizerApplicator from allennlp.modules import TimeDistribut...
20,888
39.561165
128
py
DMASTE
DMASTE-main/Span-ASTE/span_model/models/shared.py
""" Short utility functions. """ from typing import Optional, Callable import torch import torch.nn.functional as F from allennlp.modules import FeedForward from allennlp.modules.span_extractors import EndpointSpanExtractor, SpanExtractor from allennlp.nn.util import batched_span_select from overrides import override...
10,701
33.634304
106
py
DMASTE
DMASTE-main/Span-ASTE/span_model/models/span_model.py
import logging from typing import Dict, List, Optional, Union import copy import torch import torch.nn.functional as F from overrides import overrides from allennlp.data import Vocabulary from allennlp.common.params import Params from allennlp.models.model import Model from allennlp.modules import TextFieldEmbedder, ...
17,657
35.941423
111
py
DMASTE
DMASTE-main/Span-ASTE/span_model/models/entity_beam_pruner.py
""" This is basically a copy of AllenNLP's Pruner module, but with support for entity beams. """ from typing import Tuple, Union from overrides import overrides import torch from allennlp.nn import util from allennlp.modules import TimeDistributed def make_pruner(scorer, entity_beam=False, gold_beam=False): ""...
18,631
43.46778
99
py
DMASTE
DMASTE-main/Span-ASTE/aste/main.py
import json import shutil import time from os import remove from pathlib import Path from typing import List, Tuple, Optional import _jsonnet # noqa import pandas as pd from fire import Fire from pydantic import BaseModel from data_utils import ( LabelEnum, SplitEnum, Sentence, SentimentTriple, D...
9,999
33.129693
99
py
DMASTE
DMASTE-main/Span-ASTE/aste/wrapper.py
import json import os from pathlib import Path from typing import List import _jsonnet from fire import Fire from pydantic import BaseModel from tqdm import tqdm from data_utils import Data, SentimentTriple, SplitEnum from main import SpanModelData, SpanModelPrediction from utils import Shell, safe_divide class Spa...
5,884
33.617647
85
py
DMASTE
DMASTE-main/BMRC/main.py
# coding: UTF-8 # @Author: Shaowei Chen, Contact: chenshaowei0507@163.com # @Date: 2021-5-4 import argparse import Data import Model import utils import torch from torch.nn import functional as F from transformers import AdamW, get_linear_schedule_with_warmup, BertTokenizer import os from torch.utils.data import...
34,866
52.3951
156
py
DMASTE
DMASTE-main/BMRC/DANN_main.py
# coding: UTF-8 # @Author: Shaowei Chen, Contact: chenshaowei0507@163.com # @Date: 2021-5-4 import argparse import Data import DANN_Model as Model import utils import torch from torch.nn import functional as F from transformers import AdamW, get_linear_schedule_with_warmup, BertTokenizer import os from torch.uti...
40,827
54.928767
229
py
DMASTE
DMASTE-main/BMRC/DANN_Model.py
# coding: UTF-8 # @Author: Shaowei Chen, Contact: chenshaowei0507@163.com # @Date: 2021-5-4 from transformers import BertTokenizer, BertModel, BertConfig import torch.nn as nn from functions import ReverseLayerF class BERTModel(nn.Module): def __init__(self, args): hidden_size = args.hidden_size ...
2,062
38.673077
112
py
DMASTE
DMASTE-main/BMRC/Data.py
# coding: UTF-8 # @Author: Shaowei Chen, Contact: chenshaowei0507@163.com # @Date: 2021-5-4 from torch.utils.data import Dataset, DataLoader import numpy as np class OriginalDataset(Dataset): def __init__(self, pre_data): self._forward_asp_query = pre_data['_forward_asp_query'] self._forwar...
8,838
53.561728
87
py
DMASTE
DMASTE-main/BMRC/functions.py
from torch.autograd import Function class ReverseLayerF(Function): @staticmethod def forward(ctx, x, alpha): ctx.alpha = alpha return x.view_as(x) @staticmethod def backward(ctx, grad_output): output = grad_output.neg() * ctx.alpha return output, None
305
18.125
46
py
DMASTE
DMASTE-main/BMRC/dataProcess.py
# @Author: Shaowei Chen, Contact: chenshaowei0507@163.com # @Date: 2021-5-4 import pickle import torch import os class dual_sample(object): def __init__(self, original_sample, text, forward_querys, forward_answers, backward...
7,431
42.209302
230
py
DMASTE
DMASTE-main/BMRC/utils.py
# coding: UTF-8 # @Author: Shaowei Chen, Contact: chenshaowei0507@163.com # @Date: 2021-5-4 import torch from torch.nn import functional as F import logging def normalize_size(tensor): if len(tensor.size()) == 3: tensor = tensor.contiguous().view(-1, tensor.size(2)) elif len(tensor.size()) == 2...
3,575
35.121212
128
py
DMASTE
DMASTE-main/BMRC/data_utils.py
from torch.utils.data import Dataset import random import torch class Domain: Target = 1 Source = 0 class Unlabeled_Dataset(Dataset): def __init__(self, path, tokenizer, max_len=256): self.data = [] self.max_len = max_len with open(path) as f: for line in f: ...
2,601
45.464286
150
py
DMASTE
DMASTE-main/BMRC/makeData_dual.py
# @Author: Shaowei Chen, Contact: chenshaowei0507@163.com # @Date: 2021-5-4 import torch from torch.utils.data import Dataset from transformers import BertTokenizer import numpy as np _tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') class dual_sample(object): def __init__(self, ...
24,242
50.037895
144
py
DMASTE
DMASTE-main/BMRC/Model.py
# coding: UTF-8 # @Author: Shaowei Chen, Contact: chenshaowei0507@163.com # @Date: 2021-5-4 from transformers import BertTokenizer, BertModel, BertConfig import torch.nn as nn class BERTModel(nn.Module): def __init__(self, args): hidden_size = args.hidden_size super(BERTModel, self).__init...
1,477
35.04878
104
py
DMASTE
DMASTE-main/BMRC/makeData_standard.py
# @Author: Shaowei Chen, Contact: chenshaowei0507@163.com # @Date: 2021-5-4 import torch import pickle from dataProcess import get_text def make_standard(home_path, dataset_name, dataset_type): # read triple f = open(home_path + dataset_name + "/" + dataset_type + ".txt", "r", encoding="utf-8") te...
2,219
35.393443
113
py
DMASTE
DMASTE-main/Generative-ABSA/main.py
import argparse import os import logging import time import pickle from tqdm import tqdm import torch from torch.utils.data import DataLoader import pytorch_lightning as pl from pytorch_lightning import seed_everything from transformers import AdamW, T5ForConditionalGeneration, T5Tokenizer from transformers import ge...
16,407
42.638298
158
py
DMASTE
DMASTE-main/Generative-ABSA/data_utils.py
# This file contains all data loading and transformation functions import time from torch.utils.data import Dataset senttag2word = {'POS': 'positive', 'NEG': 'negative', 'NEU': 'neutral'} def read_line_examples_from_file(data_path): """ Read data from file, each line is: sent####labels Return List[List[...
11,367
34.304348
105
py
DMASTE
DMASTE-main/GTS/code/NNModel/main.py
#coding utf-8 import json, os import random import argparse import numpy import torch import torch.nn.functional as F from tqdm import trange import numpy as np from data import load_data_instances, DataIterator from model import MultiInferRNNModel, MultiInferCNNModel import utils def train(args): # load doub...
7,166
39.954286
127
py
DMASTE
DMASTE-main/GTS/code/NNModel/attention_module.py
import copy import math import torch import torch.nn.functional as F def attention(query, key, value, mask=None, dropout=None): "Compute 'Scaled Dot Product Attention'" d_k = query.size(-1) scores = torch.matmul(query, key.transpose(-2, -1)) \ / math.sqrt(d_k) if mask is not None: ...
4,281
38.648148
112
py
DMASTE
DMASTE-main/GTS/code/NNModel/model.py
import torch import torch.nn from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence import torch.nn.functional as F from attention_module import MultiHeadedAttention, SelfAttention class MultiInferRNNModel(torch.nn.Module): def __init__(self, gen_emb, domain_emb, args): '''double embedd...
7,886
41.632432
123
py
DMASTE
DMASTE-main/GTS/code/NNModel/data.py
import math import torch sentiment2id = {'negative': 3, 'neutral': 4, 'positive': 5} def get_spans(tags): '''for BIO tag''' tags = tags.strip().split() length = len(tags) spans = [] start = -1 for i in range(length): if tags[i].endswith('B'): if start != -1: ...
5,123
36.955556
93
py
DMASTE
DMASTE-main/GTS/code/BertModel/main.py
#coding utf-8 import json, os import random import argparse import torch import torch.nn.functional as F from tqdm import trange from data import load_data_instances, DataIterator from model import MultiInferBert import utils def train(args): # load dataset train_sentence_packs = json.load(open(args.prefi...
6,176
37.60625
124
py
DMASTE
DMASTE-main/GTS/code/BertModel/model.py
import torch import torch.nn from transformers import BertModel, BertTokenizer class MultiInferBert(torch.nn.Module): def __init__(self, args): super(MultiInferBert, self).__init__() self.args = args self.bert = BertModel.from_pretrained(args.bert_model_path) self.tokenizer = Ber...
2,451
37.3125
114
py
DMASTE
DMASTE-main/GTS/code/BertModel/data.py
import math import torch import numpy as np sentiment2id = {'negative': 3, 'neutral': 4, 'positive': 5} from transformers import BertTokenizer def get_spans(tags): '''for BIO tag''' tags = tags.strip().split() length = len(tags) spans = [] start = -1 for i in range(length): if tags[i...
7,269
36.864583
100
py
DMASTE
DMASTE-main/BARTABSA/peng/train.py
import sys sys.path.append('../') import os if 'p' in os.environ: os.environ['CUDA_VISIBLE_DEVICES'] = os.environ['p'] # os.environ['CUDA_VISIBLE_DEVICES'] = '7' import warnings warnings.filterwarnings('ignore') from data.pipe import BartBPEABSAPipe from peng.model.bart_absa import BartSeq2SeqModel from fastN...
7,183
37.623656
128
py
DMASTE
DMASTE-main/BARTABSA/peng/model/losses.py
from fastNLP import LossBase import torch.nn.functional as F from fastNLP import seq_len_to_mask class Seq2SeqLoss(LossBase): def __init__(self): super().__init__() def get_loss(self, tgt_tokens, tgt_seq_len, pred): """ :param tgt_tokens: bsz x max_len, [sos, tokens, eos] :p...
671
27
81
py
DMASTE
DMASTE-main/BARTABSA/peng/model/bart_absa.py
import torch from .modeling_bart import BartEncoder, BartDecoder, BartModel from transformers import BartTokenizer from fastNLP import seq_len_to_mask from fastNLP.modules import Seq2SeqEncoder, Seq2SeqDecoder, State import torch.nn.functional as F from fastNLP.models import Seq2SeqModel from torch import nn import mat...
14,844
46.428115
145
py
DMASTE
DMASTE-main/BARTABSA/peng/model/modeling_bart.py
# coding=utf-8 # Copyright 2020 The Facebook AI Research Team Authors and The HuggingFace Inc. team. # # 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/LIC...
58,282
41.234058
213
py
DMASTE
DMASTE-main/BARTABSA/peng/model/generator.py
r"""Modify from fastNLP""" import torch from torch import nn from fastNLP.models.seq2seq_model import Seq2SeqModel from fastNLP.modules.decoder.seq2seq_decoder import Seq2SeqDecoder, State import torch.nn.functional as F from fastNLP.core.utils import _get_model_device from functools import partial class SequenceGen...
23,989
44.435606
126
py
DMASTE
DMASTE-main/mySpanASTE/main.py
import os import random import argparse import torch from transformers import BertTokenizer, BertModel from torch.utils.data import DataLoader from torch.optim import AdamW from tqdm import tqdm from transformers.optimization import get_linear_schedule_with_warmup from torch.utils.tensorboard import SummaryWriter ...
8,336
46.369318
190
py
DMASTE
DMASTE-main/mySpanASTE/DANN_main.py
import os import random import argparse import torch from transformers import BertTokenizer, BertModel from torch.utils.data import DataLoader from torch.optim import AdamW from tqdm import tqdm from transformers.optimization import get_linear_schedule_with_warmup from torch.utils.tensorboard import SummaryWriter ...
10,335
47.754717
232
py
DMASTE
DMASTE-main/mySpanASTE/models/relation.py
from os import read import torch import math from utils.data_utils import RelationLabel, SpanLabel from utils.index_select import batched_index_select from models.feedForward import FeedForward def bucket_values( distances: torch.Tensor, num_identity_buckets: int = 4, num_total_buckets: int = 10 ) -> torch.Tens...
8,024
51.796053
186
py
DMASTE
DMASTE-main/mySpanASTE/models/feedForward.py
import torch class FeedForward(torch.nn.Module): def __init__(self, input_dim, hidden_dim, num_layers, activation, dropout): super(FeedForward, self).__init__() hidden_dims = [hidden_dim] * num_layers # type: ignore activations = [activation] * num_layers # type: ignore dropout =...
1,421
39.628571
79
py
DMASTE
DMASTE-main/mySpanASTE/models/DANN_span_aste.py
import torch from torch.nn import functional as F from utils.index_select import batched_index_select from models.ner import NERModel from models.relation import RelationModel from models.functions import ReverseLayerF class SpanModel(torch.nn.Module): def __init__(self, encoder, width_embedding_dim=20, max_width...
3,605
59.1
157
py
DMASTE
DMASTE-main/mySpanASTE/models/ner.py
import torch from torch.nn.modules import dropout import torch.nn.functional as F from utils.data_utils import SpanLabel from models.feedForward import FeedForward class NERModel(torch.nn.Module): def __init__(self, span_embed_dim, hidden_dim=150, num_layers=2, activation=torch.nn.ReLU(), dropout=0.4, n_labels=3...
2,651
48.111111
188
py
DMASTE
DMASTE-main/mySpanASTE/models/functions.py
from torch.autograd import Function class ReverseLayerF(Function): @staticmethod def forward(ctx, x, alpha): ctx.alpha = alpha return x.view_as(x) @staticmethod def backward(ctx, grad_output): output = grad_output.neg() * ctx.alpha return output, None
305
18.125
46
py
DMASTE
DMASTE-main/mySpanASTE/models/span_aste.py
import torch from utils.index_select import batched_index_select from models.ner import NERModel from models.relation import RelationModel class SpanModel(torch.nn.Module): def __init__(self, encoder, width_embedding_dim=20, max_width=512, spans_per_word=0.5): super(SpanModel, self).__init__() sel...
2,370
52.886364
157
py
DMASTE
DMASTE-main/mySpanASTE/utils/data_utils_unlabeled.py
import os from enum import IntEnum from torch.utils.data import Dataset class DomainLabel(IntEnum): Source = 0 Target = 1 class UnlabeledDataset(Dataset): def __init__(self, features): self.features = features def __getitem__(self, index): return self.features[index] ...
3,572
33.68932
92
py
DMASTE
DMASTE-main/mySpanASTE/utils/collate_unlabeled.py
import torch from utils.data_utils import RelationLabel from utils.data_utils_unlabeled import DomainLabel def collate_fn_target(data): """批处理,填充同一batch中句子最大的长度""" def pad_and_tensor(data, pad_value=0): max_len = max([len(x) for x in data]) new_data = [] mask = [] for x in dat...
1,535
36.463415
99
py
DMASTE
DMASTE-main/mySpanASTE/utils/data_utils.py
import os from enum import IntEnum from pydantic import BaseModel from typing import List from torch.utils.data import Dataset import torch class SpanLabel(IntEnum): INVALID = 0 ASPECT = 1 OPINION = 2 class RelationLabel(IntEnum): INVALID = 0 POS = 1 NEG = 2 NEU = 3 class ABSADataset...
8,811
38.339286
155
py
DMASTE
DMASTE-main/mySpanASTE/utils/collate.py
import torch from utils.data_utils import RelationLabel def collate_fn(data): """批处理,填充同一batch中句子最大的长度""" def pad_and_tensor(data, pad_value=0): max_len = max([len(x) for x in data]) new_data = [] mask = [] for x in data: tmp_data = torch.tensor(x) siz...
2,502
39.370968
106
py
DMASTE
DMASTE-main/mySpanASTE/utils/index_select.py
import torch def batched_index_select(target, indices): """ target : `torch.Tensor`, required. A 3 dimensional tensor of shape (batch_size, sequence_length, embedding_size). This is the tensor to be indexed. indices : `torch.LongTensor` A tensor of shape (batch_size, ...), where eac...
1,622
42.864865
111
py
DMASTE
DMASTE-main/mySpanASTE/utils/metric.py
import torch from utils.data_utils import convert_pad_tensor_to_list, convert_predictions_to_triples, SpanLabel, RelationLabel from sklearn.metrics import precision_score, recall_score, f1_score def convert_relations_to_list(relations, mask): ret = [] for i in range(relations.shape[0]): r, m = relatio...
6,970
51.022388
159
py
Learning-Debiased-Disentangled
Learning-Debiased-Disentangled-master/test.py
import numpy as np import torch import random from learner import Learner import argparse if __name__ == '__main__': parser = argparse.ArgumentParser(description='Learning Debiased Representation via Disentangled Feature Augmentation (NeurIPS 21 Oral)') # training parser.add_argument("--batch_size", help=...
3,784
63.152542
170
py
Learning-Debiased-Disentangled
Learning-Debiased-Disentangled-master/learner.py
from tqdm import tqdm import wandb import numpy as np import torch import torch.nn as nn from torch.utils.data import DataLoader import os import torch.optim as optim from data.util import get_dataset, IdxDataset from module.loss import GeneralizedCELoss from module.util import get_model from util import EMA class ...
25,007
39.400646
161
py
Learning-Debiased-Disentangled
Learning-Debiased-Disentangled-master/util.py
'''Modified from https://github.com/alinlab/LfF/blob/master/util.py''' import io import torch import numpy as np import torch.nn as nn class EMA: def __init__(self, label, num_classes=None, alpha=0.9): self.label = label.cuda() self.alpha = alpha self.parameter = torch.zeros(label.size(0))...
1,178
35.84375
118
py
Learning-Debiased-Disentangled
Learning-Debiased-Disentangled-master/train.py
import numpy as np import torch import random from learner import Learner import argparse if __name__ == '__main__': parser = argparse.ArgumentParser(description='Learning Debiased Representation via Disentangled Feature Augmentation (NeurIPS 21 Oral)') # training parser.add_argument("--batch_size", help=...
4,084
59.970149
170
py
Learning-Debiased-Disentangled
Learning-Debiased-Disentangled-master/module/resnet.py
''' From https://github.com/alinlab/LfF/blob/master/module/resnet.py ''' """ Properly implemented ResNet-s for CIFAR10 as described in paper [1]. The implementation and structure of this file is hugely influenced by [2] which is implemented for ImageNet and doesn't have option A for identity. Moreover, most of the imp...
6,270
27.375566
78
py
Learning-Debiased-Disentangled
Learning-Debiased-Disentangled-master/module/mlp.py
''' Modified from https://github.com/alinlab/LfF/blob/master/module/mlp.py''' import torch import torch.nn as nn import torch.nn.functional as F class MLP_DISENTANGLE(nn.Module): def __init__(self, num_classes = 10): super(MLP_DISENTANGLE, self).__init__() self.feature = nn.Sequential( ...
2,245
26.728395
77
py
Learning-Debiased-Disentangled
Learning-Debiased-Disentangled-master/module/loss.py
'''From https://github.com/alinlab/LfF/blob/master/module/loss.py''' import torch import torch.nn as nn import torch.nn.functional as F import numpy as np class GeneralizedCELoss(nn.Module): def __init__(self, q=0.7): super(GeneralizedCELoss, self).__init__() self.q = q ...
813
28.071429
79
py
Learning-Debiased-Disentangled
Learning-Debiased-Disentangled-master/module/util.py
''' Modified from https://github.com/alinlab/LfF/blob/master/module/util.py ''' import torch.nn as nn from module.resnet import resnet20 from module.mlp import * from torchvision.models import resnet18, resnet50 def get_model(model_tag, num_classes): if model_tag == "ResNet20": return resnet20(num_classes...
1,099
34.483871
79
py
Learning-Debiased-Disentangled
Learning-Debiased-Disentangled-master/data/util.py
'''Modified from https://github.com/alinlab/LfF/blob/master/data/util.py''' import os import torch from torch.utils.data.dataset import Dataset, Subset from torchvision import transforms as T from glob import glob from PIL import Image class IdxDataset(Dataset): def __init__(self, dataset): self.dataset =...
9,788
31.73913
160
py
fast-dpsgd
fast-dpsgd-main/opacusdp.py
''' Opacus experiments for all the models ''' import time import torch import torch.nn.functional as F from opacus import PrivacyEngine from opacus.layers import DPLSTM from torch import nn, optim import data import utils from pytorch import get_data, model_dict class LSTMNet(nn.Module): def __init__(self, voca...
3,656
31.078947
99
py
fast-dpsgd
fast-dpsgd-main/runtime_experiment.py
import argparse import pprint import subprocess from utils import pr_green, pr_red def launch(expt, batch_size, epochs): """Runs expt at batch_size for all the scripts""" errors = [] # yapf: disable cmds = [ ('jax', f'CUDA_VISIBLE_DEVICES=0 python jaxdp.py {expt} --no_dpsgd --epochs {epochs} ...
5,190
59.360465
163
py
fast-dpsgd
fast-dpsgd-main/pytorch.py
''' Model file and non-differentially private file ''' import time import torch import torch.nn.functional as F from torch import nn, optim import data import utils class EmbeddingNet(nn.Module): def __init__(self, vocab_size: int, **_): super().__init__() # Embedding dimension: vocab_size + <un...
5,651
30.4
92
py
fast-dpsgd
fast-dpsgd-main/data.py
import numpy as np import tensorflow as tf from keras.preprocessing import sequence def dataloader(x, y, batch_size): if batch_size > len(x): raise ValueError('Batch Size too big.') num_eg = len(x) assert num_eg == len(y) for i in range(0, num_eg, batch_size): yield x[i:i + batch_size]...
5,648
36.410596
96
py
fast-dpsgd
fast-dpsgd-main/jaxdp.py
''' Code for JAX implementations presented in: Enabling Fast Differentially Private SGD via Just-in-Time Compilation and Vectorization ''' import itertools import time from functools import partial import haiku as hk import jax import jax.numpy as jnp import numpy as np from jax import grad, jit, random, vmap from ja...
11,056
35.734219
99
py
fast-dpsgd
fast-dpsgd-main/tf2dp.py
import time from functools import partial import tensorflow as tf from tensorflow_privacy.privacy.analysis.gdp_accountant import (compute_eps_poisson, compute_mu_poisson) from jax.tree_util import tree_multimap import data import utils def get_logreg_m...
10,368
39.346304
100
py