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
Merak
Merak-main/Merak/mpu/cross_entropy.py
# coding=utf-8 # Copyright (c) 2020, 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 at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless re...
4,921
42.946429
115
py
Merak
Merak-main/Merak/mpu/utils.py
# coding=utf-8 # Copyright (c) 2020, 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 at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless re...
2,819
38.166667
107
py
Merak
Merak-main/Merak/mpu/layers.py
# coding=utf-8 # Copyright (c) 2020, 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 at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless re...
27,441
40.390649
108
py
Merak
Merak-main/Merak/mpu/p2p_communication.py
# coding=utf-8 # Copyright (c) 2022, HPDL group, PDL lab, NUDT. All rights reserved. # # Maintainer: Swli (lucasleesw9@gmail.com) # # 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...
7,279
36.916667
155
py
Merak
Merak-main/Merak/utils/checkpoint.py
# coding=utf-8 # Copyright (c) 2022, HPDL group, PDL lab, NUDT. All rights reserved. # # Maintainer: TXacs (txacs1993@gmail.com) # # 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:...
15,099
38.528796
115
py
Merak
Merak-main/Merak/utils/timer.py
''' Copyright 2019 The Microsoft DeepSpeed Team ''' # https://github.com/microsoft/DeepSpeed/blob/85ce85dd5f4b18c0019a5121b06900e3a2c3933b/deepspeed/utils/timer.py import time import torch from .logging import log_dist from . import logger try: import psutil PSUTILS_INSTALLED = True except ImportError: ...
6,354
33.166667
111
py
Merak
Merak-main/Merak/utils/dataloader.py
# coding=utf-8 # Copyright (c) 2022, HPDL group, PDL lab, NUDT. All rights reserved. # # Maintainer: TXacs (txacs1993@gmail.com) # # 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:...
11,426
40.252708
188
py
Merak
Merak-main/Merak/utils/logging.py
# https://github.com/microsoft/DeepSpeed/blob/85ce85dd5f4b18c0019a5121b06900e3a2c3933b/deepspeed/utils/logging.py import logging import sys import torch from .. import print_rank_0 import torch.distributed as dist log_levels = { "debug": logging.DEBUG, "info": logging.INFO, "warning": logging.WARNING, ...
3,741
24.986111
127
py
Merak
Merak-main/Merak/utils/fp16_optimizer.py
''' Copyright 2019 The Microsoft DeepSpeed Team Copyright NVIDIA/apex This file is adapted from FP16_Optimizer in NVIDIA/apex ''' # the code here are adapted from https://github.com/microsoft/DeepSpeed/blob/v0.5.10/deepspeed/runtime/fp16/unfused_optimizer.py import torch from torch._utils import _flatten_dense_tenso...
17,530
40.056206
128
py
Merak
Merak-main/Merak/utils/merak_args.py
# coding=utf-8 # Copyright (c) 2022, HPDL group, PDL lab, NUDT. All rights reserved. # # Maintainer: Swli (lucasleesw9@gmail.com), TXacs (txacs1993@gmail.com) # # 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 o...
16,997
48.412791
191
py
Merak
Merak-main/Merak/utils/profiler.py
# code here are adapted from https://github.com/microsoft/DeepSpeed/blob/5218177922a4be5c14cf0db893dbfcb139179ba5/deepspeed/profiling/flops_profiler/profiler.py import time import torch import torch.nn as nn import torch.nn.functional as F from functools import partial from typing import Callable, List, Optional, Tup...
48,368
37.145899
650
py
Merak
Merak-main/Merak/autoshard/graph_shard.py
# coding=utf-8 # Copyright (c) 2022, HPDL group, PDL lab, NUDT. All rights reserved. # # Maintainer: Swli (lucasleesw9@gmail.com) # # 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...
16,956
43.623684
173
py
Merak
Merak-main/Merak/autoshard/convert.py
# coding=utf-8 # Copyright (c) 2022, HPDL group, PDL lab, NUDT. All rights reserved. # # Maintainer: Swli (lucasleesw9@gmail.com) # # 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...
17,468
39.531323
143
py
Merak
Merak-main/examples/torch-models/config.py
# -------------------------------------------------------- # Swin Transformer # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ze Liu # --------------------------------------------------------' import os import yaml from yacs.config import CfgNode as CN _C = CN() ...
7,072
31.74537
79
py
Merak
Merak-main/examples/torch-models/run_torchvision.py
# coding=utf-8 # Copyright (c) 2022, HPDL group, PDL lab, NUDT. All rights reserved. # # Maintainer: TXacs (txacs1993@gmail.com) # # 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:...
1,971
27.171429
102
py
Merak
Merak-main/examples/torch-models/models/swin_mlp.py
# -------------------------------------------------------- # Swin Transformer # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ze Liu # -------------------------------------------------------- import torch import torch.nn as nn import torch.nn.functional as F impor...
18,508
38.464819
118
py
Merak
Merak-main/examples/torch-models/models/swin_transformer.py
# -------------------------------------------------------- # Swin Transformer # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ze Liu # -------------------------------------------------------- import torch import torch.nn as nn import torch.utils.checkpoint as chec...
27,189
40.830769
119
py
Merak
Merak-main/examples/torch-models/data/build.py
# -------------------------------------------------------- # Swin Transformer # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ze Liu # -------------------------------------------------------- import os import torch import torch.distributed as dist from torchvision...
5,018
37.022727
113
py
Merak
Merak-main/examples/bert_pretraining/run_bert.py
# coding=utf-8 # Copyright (c) 2022, HPDL group, PDL lab, NUDT. All rights reserved. # # Maintainer: TXacs (txacs1993@gmail.com) # # 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:...
7,887
44.333333
186
py
Merak
Merak-main/examples/bert_pretraining/schedulers.py
# Copyright (c) 2019 NVIDIA CORPORATION. All rights reserved. # Copyright 2018 The Google AI Language Team Authors and The HugginFace 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 ...
5,075
36.323529
168
py
Merak
Merak-main/examples/bert_pretraining/bert_data.py
# coding=utf-8 # Copyright (c) 2022, HPDL group, PDL lab, NUDT. All rights reserved. # # Maintainer: TXacs (txacs1993@gmail.com) # # 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:...
6,781
38.430233
129
py
Merak
Merak-main/examples/bert_pretraining/lamb.py
import torch from torch.optim import Optimizer # code from https://github.com/cybertronai/pytorch-lamb/blob/master/pytorch_lamb/lamb.py class Lamb(Optimizer): r"""Implements Lamb algorithm. It has been proposed in `Large Batch Optimization for Deep Learning: Training BERT in 76 minutes`_. Arguments: ...
5,287
43.066667
109
py
Merak
Merak-main/examples/image-classification/utils.py
# coding=utf-8 # Copyright (c) 2022, HPDL group, PDL lab, NUDT. All rights reserved. # # Maintainer: TXacs (txacs1993@gmail.com) # # 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:...
4,223
33.341463
164
py
Merak
Merak-main/examples/language-modeling/utils.py
# coding=utf-8 # Copyright (c) 2022, HPDL group, PDL lab, NUDT. All rights reserved. # # Maintainer: TXacs (txacs1993@gmail.com) # # 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:...
12,648
38.652038
160
py
victim_counts
victim_counts-main/inference.py
import numpy as np import torch from torch.utils.data import DataLoader from text2digits import text2digits from tqdm import tqdm import sys sys.path.append("./") from calibration.post_hoc import softmax # generate answer def get_allowed_answer(tokenizer, num_only): """ Helper function to only output digit tok...
6,593
39.703704
130
py
victim_counts
victim_counts-main/run_regression.py
import sys import os import argparse from sklearn.isotonic import IsotonicRegression from sklearn.metrics import mean_absolute_percentage_error, mean_squared_error, r2_score sys.path.append(os.path.abspath(".")) os.environ["WANDB_DISABLED"] = "true" from torch.utils.data import Subset import pickle from torch.utils.dat...
8,794
47.861111
136
py
victim_counts
victim_counts-main/run_classification.py
""" Fine-tune Classification Task """ import sys import os sys.path.append(os.path.abspath(".")) os.environ["WANDB_DISABLED"] = "true" import pickle import argparse from torch.utils.data import Subset from transformers import Trainer, T5Tokenizer, set_seed from utils import do_eval, get_trainingargs, load_config, get_c...
5,494
40.007463
133
py
victim_counts
victim_counts-main/Dataset.py
import os import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import numpy as np import torch from torch.utils.data import Dataset, random_split class RawDataset: def __init__(self, direc): self.header = 0 self.direc = direc self.fnames = [] self.columns = [] ...
9,493
37.437247
203
py
victim_counts
victim_counts-main/run_generation.py
""" Fine-tune Text Generation Task """ import sys import os from torch.utils.data import Subset sys.path.append(os.path.abspath(".")) os.environ["WANDB_DISABLED"] = "true" import argparse from transformers import Trainer, set_seed from utils import get_lm_data, get_nt5_model, get_trainingargs, do_train, do_eval, load_c...
2,480
33.943662
111
py
victim_counts
victim_counts-main/models.py
from transformers import T5PreTrainedModel, T5EncoderModel from transformers.modeling_outputs import SequenceClassifierOutput from torch import nn class T5Classification(T5PreTrainedModel): def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels if self.num_...
1,833
44.85
90
py
ori
ori-master/ori/train/target.py
from .base import * import yaml import datetime import tensorflow_addons as tfa from .util import * tf.get_logger().setLevel('ERROR') class oi_target(target_base): def __init__(self,cfg_file) -> None: print("Init OpenImage Target ...") with open(cfg_file, 'r') as stream: self.cfg = yam...
2,472
36.469697
96
py
ori
ori-master/ori/train/util.py
import sys, os, json import tensorflow as tf import tensorflow.keras as K import numpy as np from sklearn.svm import SVC from sklearn.metrics import classification_report from sklearn import tree from sklearn.neighbors import KNeighborsClassifier from PIL import Image from sklearn.ensemble import RandomForestClassifier...
11,517
37.912162
114
py
ori
ori-master/ori/train/infer.py
from .base import * import yaml from .util import * import pandas as pd import numpy as np import os from keras import backend as K import tensorflow as tf import pickle class oi_infer(infer_base): def __init__(self, cfg_file): with open(cfg_file, 'r') as stream: self.cfg = yaml.safe_load(strea...
9,605
39.361345
141
py
disentangled-retriever
disentangled-retriever-main/setup.py
from setuptools import setup, find_packages setup( name='disentangled_retriever', version='0.0.2', packages=find_packages("src"), package_dir={'': 'src'}, description='Disentangled Modeling of Domain and Relevance for Adaptable Dense Retrieval', url='https://github.com/jingtaozhan/disentangled-...
846
32.88
94
py
disentangled-retriever
disentangled-retriever-main/src/disentangled_retriever/splade/finetune/contrast_utils.py
import os import torch import random import logging from tqdm import tqdm from collections import defaultdict from dataclasses import dataclass, field from typing import List, Dict, Any, Union, Optional from torch import nn, Tensor import torch.nn.functional as F import torch.distributed as dist from torch.utils.data ...
7,463
45.943396
124
py
disentangled-retriever
disentangled-retriever-main/src/disentangled_retriever/splade/finetune/distill_utils.py
import torch import random import logging import gzip, pickle from tqdm import tqdm from dataclasses import dataclass from collections import defaultdict from typing import List, Dict, Any, Union, Optional from torch import nn, Tensor import torch.nn.functional as F import torch.distributed as dist from torch.utils.da...
5,217
41.770492
140
py
disentangled-retriever
disentangled-retriever-main/src/disentangled_retriever/splade/finetune/run_distill.py
import os import sys import torch import logging import transformers from typing import List from transformers import ( AutoConfig, AutoTokenizer, HfArgumentParser, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process from dataclasses import dataclass, field from .d...
6,759
36.555556
154
py
disentangled-retriever
disentangled-retriever-main/src/disentangled_retriever/splade/evaluate/run_eval.py
import os import math import json import torch import shutil import logging import numpy as np import torch.distributed as dist from dataclasses import field, dataclass import transformers from transformers import ( AutoConfig, AutoTokenizer, HfArgumentParser, TrainingArguments, set_seed) from tr...
5,909
35.036585
148
py
disentangled-retriever
disentangled-retriever-main/src/disentangled_retriever/splade/evaluate/index_utils.py
import re import os import sys import json import math import torch import faiss import queue import logging import threading import subprocess import numpy as np from tqdm import tqdm import torch.distributed as dist import faiss.contrib.torch_utils from torch.utils.data import Dataset from typing import Dict, List, T...
7,158
35.712821
134
py
disentangled-retriever
disentangled-retriever-main/src/disentangled_retriever/splade/modeling/bert_splade.py
import torch from transformers import BertForMaskedLM class BertSplade(BertForMaskedLM): def forward(self, input_ids, attention_mask, token_type_ids=None, position_ids=None, return_dict=False): outputs = super().forward( input_ids = input_ids, attention_mask = attention_mask, ...
4,109
46.241379
133
py
disentangled-retriever
disentangled-retriever-main/src/disentangled_retriever/splade/modeling/__init__.py
import torch from torch import Tensor import torch.nn.functional as F from transformers import AutoConfig from .bert_splade import BertSplade class AutoSpladeModel: @classmethod def from_pretrained(cls, model_path: str, config = None): if config is None: config = AutoConfig.from_pretraine...
523
26.578947
73
py
disentangled-retriever
disentangled-retriever-main/src/disentangled_retriever/rerank/finetune/train_utils.py
import os import torch import random import logging import pytrec_eval import numpy as np from tqdm import tqdm import torch.nn.functional as F import torch.distributed as dist from dataclasses import dataclass, field from collections import defaultdict from typing import List, Dict, Any, Union, Optional, Tuple from to...
8,996
38.460526
139
py
disentangled-retriever
disentangled-retriever-main/src/disentangled_retriever/rerank/finetune/__init__.py
import math import torch import faiss import logging import numpy as np from tqdm import tqdm from collections import defaultdict import faiss.contrib.torch_utils from torch.utils.data import Dataset from typing import Dict, List, Tuple, Optional, Any, Union from transformers import BertTokenizer, TrainingArguments, Tr...
4,538
31.654676
110
py
disentangled-retriever
disentangled-retriever-main/src/disentangled_retriever/rerank/finetune/run_train.py
import os import sys import torch import logging import transformers from typing import List from transformers import ( AutoConfig, AutoTokenizer, HfArgumentParser, TrainingArguments, AutoAdapterModel, set_seed, ) from transformers.trainer_utils import is_main_process from dataclasses import dat...
9,501
40.675439
154
py
disentangled-retriever
disentangled-retriever-main/src/disentangled_retriever/rerank/evaluate/run_eval.py
from collections import defaultdict import os import json import torch import logging import numpy as np from tqdm import tqdm from dataclasses import field, dataclass import transformers from transformers import ( AutoConfig, AutoTokenizer, HfArgumentParser, TrainingArguments, AutoAdapterModel, ...
4,436
33.937008
137
py
disentangled-retriever
disentangled-retriever-main/src/disentangled_retriever/rerank/evaluate/eval_utils.py
import re import math import torch import faiss import logging import numpy as np from tqdm import tqdm from collections import defaultdict import faiss.contrib.torch_utils from torch.utils.data import Dataset from typing import Dict, List, Tuple, Optional, Any, Union from transformers import BertTokenizer, TrainingArg...
4,600
32.100719
134
py
disentangled-retriever
disentangled-retriever-main/src/disentangled_retriever/unicoil/finetune/contrast_utils.py
import os import torch import random import logging from tqdm import tqdm from collections import defaultdict from dataclasses import dataclass, field from typing import List, Dict, Any, Union, Optional from torch import nn, Tensor import torch.nn.functional as F import torch.distributed as dist from torch.utils.data ...
5,099
44.535714
116
py
disentangled-retriever
disentangled-retriever-main/src/disentangled_retriever/unicoil/finetune/distill_utils.py
import torch import random import logging import gzip, pickle from tqdm import tqdm from dataclasses import dataclass from collections import defaultdict from typing import List, Dict, Any, Union, Optional from torch import nn, Tensor import torch.nn.functional as F import torch.distributed as dist from torch.utils.da...
2,773
38.628571
140
py
disentangled-retriever
disentangled-retriever-main/src/disentangled_retriever/unicoil/finetune/run_distill.py
import os import sys import torch import logging import transformers from typing import List from transformers import ( AutoConfig, AutoTokenizer, HfArgumentParser, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process from dataclasses import dataclass, field from .d...
6,467
35.96
154
py
disentangled-retriever
disentangled-retriever-main/src/disentangled_retriever/unicoil/evaluate/run_eval.py
import os import math import json import torch import shutil import logging import numpy as np import torch.distributed as dist from dataclasses import field, dataclass import transformers from transformers import ( AutoConfig, AutoTokenizer, HfArgumentParser, TrainingArguments, set_seed) from tr...
5,913
35.060976
148
py
disentangled-retriever
disentangled-retriever-main/src/disentangled_retriever/unicoil/evaluate/index_utils.py
import re import os import sys import json import math import torch import faiss import logging import subprocess import numpy as np from tqdm import tqdm import faiss.contrib.torch_utils from torch.utils.data import Dataset from typing import Dict, List, Tuple, Optional, Any, Union from transformers import TrainingArg...
1,180
24.673913
124
py
disentangled-retriever
disentangled-retriever-main/src/disentangled_retriever/unicoil/modeling/bert_unicoil.py
import torch from transformers import BertAdapterModel class BertUnicoil(BertAdapterModel): def forward(self, input_ids, attention_mask, token_type_ids=None, position_ids=None, return_dict=False): outputs = super().forward( input_ids = input_ids, attention_mask = attention_mask, ...
2,860
36.644737
117
py
disentangled-retriever
disentangled-retriever-main/src/disentangled_retriever/unicoil/modeling/__init__.py
import torch from torch import Tensor import torch.nn.functional as F from transformers import AutoConfig from .bert_unicoil import BertUnicoil class AutoUnicoilModel: @classmethod def from_pretrained(cls, model_path: str, config = None): if config is None: config = AutoConfig.from_pretra...
527
26.789474
74
py
disentangled-retriever
disentangled-retriever-main/src/disentangled_retriever/dense/finetune/validate_utils.py
import math import torch import logging import pytrec_eval from typing import Dict from collections import defaultdict import transformers from transformers.trainer_utils import is_main_process from ..evaluate.index_utils import ( load_corpus, load_queries, encode_dense_corpus, encode_dense_query, batch_dense...
2,968
40.236111
209
py
disentangled-retriever
disentangled-retriever-main/src/disentangled_retriever/dense/finetune/contrast_utils.py
import os import torch import random import logging from tqdm import tqdm from collections import defaultdict from dataclasses import dataclass, field from typing import List, Dict, Any, Union, Optional from torch import nn, Tensor import torch.nn.functional as F import torch.distributed as dist from torch.utils.data ...
11,687
41.194946
138
py
disentangled-retriever
disentangled-retriever-main/src/disentangled_retriever/dense/finetune/distill_utils.py
import torch import random import logging import gzip, pickle from tqdm import tqdm from dataclasses import dataclass from collections import defaultdict from typing import List, Dict, Any, Union, Optional from torch import nn, Tensor import torch.nn.functional as F import torch.distributed as dist from torch.utils.da...
9,108
39.847534
140
py
disentangled-retriever
disentangled-retriever-main/src/disentangled_retriever/dense/finetune/run_distill.py
import os import sys import torch import logging import transformers from typing import List from transformers import ( AutoConfig, AutoTokenizer, HfArgumentParser, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process from dataclasses import dataclass, field from .d...
7,152
36.062176
154
py
disentangled-retriever
disentangled-retriever-main/src/disentangled_retriever/dense/evaluate/run_eval.py
import os import math import json import torch import logging import numpy as np from dataclasses import field, dataclass import transformers from transformers import ( AutoConfig, AutoTokenizer, HfArgumentParser, TrainingArguments, set_seed) from transformers.trainer_utils import is_main_process...
7,264
41.48538
241
py
disentangled-retriever
disentangled-retriever-main/src/disentangled_retriever/dense/evaluate/index_utils.py
import re import math import torch import faiss import logging import numpy as np from tqdm import tqdm import faiss.contrib.torch_utils from torch.utils.data import Dataset from typing import Dict, List, Tuple, Optional, Any, Union from transformers import TrainingArguments, Trainer logger = logging.getLogger(__name_...
8,217
35.852018
134
py
disentangled-retriever
disentangled-retriever-main/src/disentangled_retriever/dense/modeling/utils.py
import torch from torch import Tensor import torch.nn.functional as F SIMILARITY_METRIC_IP = "ip" SIMILARITY_METRIC_COS = "cos" SIMILARITY_METRICS = [SIMILARITY_METRIC_IP, SIMILARITY_METRIC_COS] POOLING_AVERAGE = "average" POOLING_CLS = "cls" POOLING_METHODS = [POOLING_AVERAGE, POOLING_CLS] def extract_text_embed(...
1,034
29.441176
92
py
disentangled-retriever
disentangled-retriever-main/src/disentangled_retriever/dense/modeling/__init__.py
import torch from torch import Tensor import torch.nn.functional as F from transformers import AutoConfig from .bert_dense import BertDense from .roberta_dense import RobertaDense from .distilbert_dense import DistilBertDense from .utils import SIMILARITY_METRICS, POOLING_METHODS class AutoDenseModel: @classmeth...
908
33.961538
78
py
disentangled-retriever
disentangled-retriever-main/src/disentangled_retriever/colbert/finetune/contrast_utils.py
import os import torch import random import logging from tqdm import tqdm from collections import defaultdict from dataclasses import dataclass, field from typing import List, Dict, Any, Union, Optional from torch import nn, Tensor import torch.nn.functional as F import torch.distributed as dist from torch.utils.data ...
5,090
44.053097
116
py
disentangled-retriever
disentangled-retriever-main/src/disentangled_retriever/colbert/finetune/distill_utils.py
import torch import random import logging import gzip, pickle from tqdm import tqdm from dataclasses import dataclass from collections import defaultdict from typing import List, Dict, Any, Union, Optional from torch import nn, Tensor import torch.nn.functional as F import torch.distributed as dist from torch.utils.da...
2,962
38.506667
133
py
disentangled-retriever
disentangled-retriever-main/src/disentangled_retriever/colbert/finetune/run_distill.py
import os import sys import torch import logging import transformers from typing import List from transformers import ( AutoConfig, AutoTokenizer, HfArgumentParser, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process from dataclasses import dataclass, field from .d...
6,581
36.186441
154
py
disentangled-retriever
disentangled-retriever-main/src/disentangled_retriever/colbert/evaluate/model_inference.py
import torch from tqdm import tqdm def _split_into_batches(ids, mask, bsize): batches = [] for offset in range(0, ids.size(0), bsize): batches.append((ids[offset:offset+bsize], mask[offset:offset+bsize])) return batches def _sort_by_length(ids, mask, bsize): if ids.size(0) <= bsize: ...
4,440
32.390977
117
py
disentangled-retriever
disentangled-retriever-main/src/disentangled_retriever/colbert/evaluate/index_faiss.py
import os import sys import math import time import ujson import queue import faiss import torch import datetime import itertools import threading import numpy as np import argparse def load_doclens(directory, flatten=True): parts, _, _ = get_parts(directory) doclens_filenames = [os.path.join(directory, 'doc...
11,813
30.504
116
py
disentangled-retriever
disentangled-retriever-main/src/disentangled_retriever/colbert/evaluate/retrieve.py
import os import time import ujson import torch import faiss import random import logging import itertools from functools import partial from itertools import accumulate from multiprocessing import Pool from contextlib import contextmanager from dataclasses import field, dataclass import transformers from transformers...
21,340
35.858377
131
py
disentangled-retriever
disentangled-retriever-main/src/disentangled_retriever/colbert/evaluate/index.py
import os import time import torch import ujson import numpy as np import logging import itertools import threading import queue from dataclasses import field, dataclass import transformers from transformers import ( TrainingArguments, AutoConfig, AutoModel, AutoTokenizer, HfArgumentParser ) from tr...
8,776
32.757692
135
py
disentangled-retriever
disentangled-retriever-main/src/disentangled_retriever/colbert/modeling/__init__.py
import torch from torch import Tensor import torch.nn.functional as F from transformers import AutoConfig from .bert_colbert import ColBERT class AutoColBERTModel: @classmethod def from_pretrained(cls, model_path: str, config = None): if config is None: config = AutoConfig.from_pretrained...
519
26.368421
70
py
disentangled-retriever
disentangled-retriever-main/src/disentangled_retriever/colbert/modeling/bert_colbert.py
import torch from transformers import BertAdapterModel class ColBERT(BertAdapterModel): def forward(self, input_ids, attention_mask, token_type_ids=None, position_ids=None, return_dict=False): outputs = super().forward( input_ids = input_ids, attention_mask = attention_mask, ...
2,828
35.74026
117
py
disentangled-retriever
disentangled-retriever-main/src/disentangled_retriever/adapt/run_adapt_with_mlm.py
import os import sys import gzip import random import logging import numpy as np from tqdm import tqdm from torch.utils.data import Dataset from typing import Optional, List, Dict from dataclasses import dataclass, field import transformers from transformers import ( AutoConfig, AutoTokenizer, AutoModelFor...
6,047
34.576471
147
py
ParallelNeLLoC
ParallelNeLLoC-master/models/train-shearloc.py
import torch from torch import optim from shearloc_model import * import numpy as np import torch.nn.functional as F from torch.optim import lr_scheduler from utils import * def train_model(opt): k_h=opt['k_h'] k_w=opt['k_w'] offset=opt['offset'] name='shearloc_res'+str(opt['res_num'])+'_mixnum'+str(o...
2,753
31.4
141
py
ParallelNeLLoC
ParallelNeLLoC-master/models/train-nelloc.py
import torch from torch import optim from nelloc_model import * import numpy as np from torch.optim import lr_scheduler from utils import * def train_model(opt): name='nelloc_res'+str(opt['res_num'])+'_mixnum'+str(opt['mix_num'])+'_rf'+str(opt['rf']) train_data_loader,test_data_loader,_=LoadData(opt) net ...
2,147
30.588235
125
py
ParallelNeLLoC
ParallelNeLLoC-master/models/utils.py
import torchvision from torchvision import transforms import torch import numpy as np from torch.utils import data rescaling = lambda x : (x - .5) * 2. rescaling_inv = lambda x : .5 * x + .5 def shear(x,offset=2): bs=x.size(0) D=x.size(2) L=D+(D-1)*offset sheared_img=torch.zeros(bs,3,D,L) for...
3,802
38.614583
140
py
ParallelNeLLoC
ParallelNeLLoC-master/models/shearloc_model.py
import torch.nn as nn import torch def discretized_mix_logistic_uniform(x, l,sheared_mask, alpha=0.0001): xs=list(x.size()) x=x.unsqueeze(2) mix_num = int(l.size(1)/10) pi = torch.softmax(l[:, :mix_num,:,:],1).unsqueeze(1).repeat(1,3,1,1,1) l=l[:, mix_num:,:,:].view(xs[:2]+[-1]+xs[2:]) means...
3,172
37.228916
117
py
ParallelNeLLoC
ParallelNeLLoC-master/models/nelloc_model.py
import torch.nn as nn import torch import torch.nn.functional as F def discretized_mix_logistic_uniform(x, l, alpha=0.0001): xs=list(x.size()) x=x.unsqueeze(2) mix_num = int(l.size(1)/10) pi = torch.softmax(l[:, :mix_num,:,:],1).unsqueeze(1).repeat(1,3,1,1,1) l=l[:, mix_num:,:,:].view(xs[:2]+[-1]+...
3,481
39.964706
117
py
ParallelNeLLoC
ParallelNeLLoC-master/coders/pnelloc_ans.py
import torch.nn.functional as F from coders.coder_utils import * def p_ans_compression(model,img,time_index,h,w,rf,p_prec=16): c_list=[] p_list=[] p2d = (rf, rf, rf, 0) img = F.pad(img, p2d, "constant", 0) with torch.no_grad(): for t,par_index_list in enumerate(time_index): pat...
3,568
45.350649
135
py
ParallelNeLLoC
ParallelNeLLoC-master/coders/shearloc_ans.py
import torch.nn.functional as F from coders.coder_utils import * from models.utils import * def ans_compression(model,img,Q,K,p_prec=16): model.eval() c_list=[] p_list=[] D,O,T,up_batch,down_batch,bs_batch=Q sheared_o_img=shear(img,O).to(torch.int32) kh,kw=K p2d=[kw,0,kh-1,0] pa...
3,834
42.579545
135
py
ParallelNeLLoC
ParallelNeLLoC-master/coders/coder_utils.py
import torch import numpy as np rescaling = lambda x : (x - .5) * 2. rescaling_inv = lambda x : .5 * x + .5 def discretized_mix_logistic_cdftable(means, log_scales,pi, alpha=0.0001): bs=means.size(0) nr_mix=pi.size(-1) pi=pi.unsqueeze(1) x=rescaling(torch.arange(0,256)/255.).view(1,256,1).rep...
3,462
34.336735
115
py
ParallelNeLLoC
ParallelNeLLoC-master/coders/nelloc_ans.py
import torch.nn.functional as F from coders.coder_utils import * def ans_compression(model,img,h,w,rf,p_prec=16): c_list=[] p_list=[] p2d = (rf, rf, rf, 0) img = F.pad(img, p2d, "constant", 0) with torch.no_grad(): for i in range(0,h): for j in range(0,w): patch...
2,881
47.847458
139
py
TEXTOIR
TEXTOIR-main/open_intent_detection/methods/ADB/pretrain.py
import torch import torch.nn.functional as F import numpy as np import os import copy import logging from torch import nn from sklearn.metrics import confusion_matrix, f1_score, accuracy_score from tqdm import trange, tqdm from losses import loss_map from utils.functions import save_model, restore_model, centroids_cal ...
8,067
35.506787
154
py
TEXTOIR
TEXTOIR-main/open_intent_detection/methods/ADB/boundary.py
import torch from torch import nn import torch.nn.functional as F class BoundaryLoss(nn.Module): """ Deep Open Intent Classification with Adaptive Decision Boundary. https://arxiv.org/pdf/2012.10209.pdf """ def __init__(self, num_labels=10, feat_dim=2, device = None): super(BoundaryLoss, s...
1,074
30.617647
69
py
TEXTOIR
TEXTOIR-main/open_intent_detection/methods/ADB/manager.py
import torch import torch.nn.functional as F import numpy as np import os import logging from sklearn.metrics import confusion_matrix, f1_score, accuracy_score from tqdm import trange, tqdm from .boundary import BoundaryLoss from losses import loss_map from utils.functions import save_model, euclidean_metric from utils...
7,992
39.573604
133
py
TEXTOIR
TEXTOIR-main/open_intent_detection/methods/MSP/manager.py
from importlib import import_module import torch import torch.nn.functional as F import copy import logging from sklearn.metrics import confusion_matrix, accuracy_score, f1_score from tqdm import trange, tqdm from losses import loss_map from utils.functions import restore_model, save_model from utils.metrics import F_m...
5,673
33.809816
133
py
TEXTOIR
TEXTOIR-main/open_intent_detection/methods/KNNCL/KNNCL_utils.py
import torch import random from typing import Any, Dict, Union def create_negative_dataset(train_dataloader): list = [] for step, inputs in enumerate(train_dataloader): input_ids, input_masks, segment_ids, label_ids = inputs input_ids = input_ids.tolist() input_masks = input_masks.tol...
2,169
30.449275
112
py
TEXTOIR
TEXTOIR-main/open_intent_detection/methods/KNNCL/manager.py
import torch import copy import pandas as pd import logging from tqdm import trange, tqdm from sklearn.metrics import confusion_matrix, accuracy_score, f1_score from sklearn.neighbors import LocalOutlierFactor from utils.functions import restore_model, save_model from utils.metrics import F_measure from .KNNCL_utils i...
6,629
38.464286
133
py
TEXTOIR
TEXTOIR-main/open_intent_detection/methods/DOC/manager.py
from importlib import import_module import torch import numpy as np import os import copy import logging from torch import nn from datetime import datetime from sklearn.metrics import confusion_matrix, accuracy_score from tqdm import trange, tqdm from scipy.stats import norm as dist_model from losses import loss_map fr...
7,495
34.028037
133
py
TEXTOIR
TEXTOIR-main/open_intent_detection/methods/K_1_way/manager.py
from importlib import import_module import torch import torch.nn.functional as F import copy import logging from sklearn.metrics import confusion_matrix, accuracy_score from tqdm import trange, tqdm from losses import loss_map from utils.functions import restore_model, save_model from utils.metrics import F_measure c...
5,586
35.045161
133
py
TEXTOIR
TEXTOIR-main/open_intent_detection/methods/MDF/pretrain.py
import torch import torch.nn.functional as F import os import copy import logging import torch.nn as nn from sklearn.metrics import confusion_matrix, f1_score, accuracy_score from tqdm import trange, tqdm from losses import loss_map from torch.utils.data import RandomSampler, DataLoader from utils.functions import sav...
6,375
37.409639
133
py
TEXTOIR
TEXTOIR-main/open_intent_detection/methods/MDF/manager.py
import torch import torch.nn.functional as F import logging import os import torch.nn as nn import numpy as np import copy import json from sklearn import svm import sklearn from sklearn.metrics import confusion_matrix, f1_score, accuracy_score, roc_curve, auc from tqdm import trange, tqdm from losses import loss_map...
8,840
37.43913
133
py
TEXTOIR
TEXTOIR-main/open_intent_detection/methods/DeepUnk/manager.py
import torch import torch.nn.functional as F import numpy as np import os import copy import pandas as pd import logging from sklearn.metrics import confusion_matrix, accuracy_score from tqdm import trange, tqdm from sklearn.neighbors import LocalOutlierFactor from losses import loss_map from utils.functions import sa...
6,374
35.016949
133
py
TEXTOIR
TEXTOIR-main/open_intent_detection/methods/OpenMax/manager.py
from importlib import import_module import torch import torch.nn.functional as F import numpy as np import copy import logging from losses import loss_map from torch import nn from datetime import datetime from sklearn.metrics import confusion_matrix, accuracy_score from tqdm import trange, tqdm from utils.functions im...
8,615
32.65625
133
py
TEXTOIR
TEXTOIR-main/open_intent_detection/methods/SEG/manager.py
import torch import torch.nn.functional as F import numpy as np import os import copy import logging import pandas as pd from torch import nn from datetime import datetime from sklearn.metrics import confusion_matrix, accuracy_score from tqdm import trange, tqdm from utils.functions import save_model from utils.metric...
8,313
37.669767
155
py
TEXTOIR
TEXTOIR-main/open_intent_detection/methods/ARPL/pretrain.py
import torch import torch.nn.functional as F import numpy as np import os import copy import logging from torch import nn from sklearn.metrics import confusion_matrix, f1_score, accuracy_score from tqdm import trange, tqdm from losses import loss_map from utils.functions import save_model, restore_model class Pretrai...
5,122
34.331034
133
py
TEXTOIR
TEXTOIR-main/open_intent_detection/methods/ARPL/manager.py
import torch import torch.nn.functional as F import numpy as np import os import copy import logging from torch import nn from sklearn.metrics import confusion_matrix, f1_score, accuracy_score from tqdm import trange, tqdm from losses import loss_map from utils.metrics import F_measure from utils.functions import resto...
6,461
37.011765
96
py
TEXTOIR
TEXTOIR-main/open_intent_detection/dataloaders/base.py
import numpy as np import os import random import torch import logging from .__init__ import max_seq_lengths, backbone_loader_map, benchmark_labels def set_seed(seed): random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.backends.cudnn.determini...
2,025
29.238806
112
py
TEXTOIR
TEXTOIR-main/open_intent_detection/dataloaders/bert_loader.py
import numpy as np import torch import os import csv import sys import logging from transformers import BertTokenizer from torch.utils.data import (DataLoader, RandomSampler, SequentialSampler, TensorDataset) class BERT_Loader: def __init__(self, args, base_attrs, logger_name = 'Detection'): self.logger =...
12,120
41.381119
164
py
TEXTOIR
TEXTOIR-main/open_intent_detection/dataloaders/__init__.py
from .bert_loader import BERT_Loader max_seq_lengths = { 'stackoverflow':45, 'banking':55, 'oos':30, 'snips':35 } backbone_loader_map = { 'bert': BERT_Loader, ...
6,404
72.62069
181
py
TEXTOIR
TEXTOIR-main/open_intent_detection/utils/functions.py
import os import torch import numpy as np import pandas as pd from tqdm import tqdm from transformers import WEIGHTS_NAME, CONFIG_NAME def mask_tokens(inputs, tokenizer, special_tokens_mask=None, mlm_probability=0.15): """ Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, ...
5,183
35.765957
157
py
TEXTOIR
TEXTOIR-main/open_intent_detection/losses/Dist.py
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np class Dist(nn.Module): def __init__(self, num_classes=10, num_centers=1, feat_dim=2, init='random'): super(Dist, self).__init__() self.feat_dim = feat_dim self.num_classes = num_classes self.num_ce...
1,612
39.325
119
py