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 |
|---|---|---|---|---|---|---|
CVPR19_Incremental_Learning | CVPR19_Incremental_Learning-master/cifar100-class-incremental/modified_linear.py | import math
import torch
from torch.nn.parameter import Parameter
from torch.nn import functional as F
from torch.nn import Module
class CosineLinear(Module):
def __init__(self, in_features, out_features, sigma=True):
super(CosineLinear, self).__init__()
self.in_features = in_features
self... | 2,235 | 36.898305 | 78 | py |
TRSSL | TRSSL-main/train.py | import argparse
import os
import shutil
import time
import random
import math
import numpy as np
from datetime import datetime
from tqdm import tqdm
import torch
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data as data
import torch.nn.functional as F
from utils.utils import Bar... | 19,121 | 40.934211 | 183 | py |
TRSSL | TRSSL-main/models/build_model.py | import torch
def build_model(args, ema=False):
if args.dataset in ['cifar10', 'cifar100']:
from . import resnet_cifar as models
elif args.dataset == 'tinyimagenet':
from . import resnet_tinyimagenet as models
else:
from . import resnet as models
if args.arch == 'resnet18':
... | 692 | 24.666667 | 55 | py |
TRSSL | TRSSL-main/models/resnet.py | import torch
from torch import Tensor
import torch.nn as nn
# from .._internally_replaced_utils import load_state_dict_from_url
from typing import Type, Any, Callable, Union, List, Optional
import torch.nn.functional as F
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152', 'r... | 15,539 | 38.846154 | 111 | py |
TRSSL | TRSSL-main/models/resnet_tinyimagenet.py | """
This code is based on the Torchvision repository, which was licensed under the BSD 3-Clause.
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, in_planes, planes, stride=1, is_last=False):
super(BasicBlock, self).__... | 5,141 | 37.088889 | 104 | py |
TRSSL | TRSSL-main/models/resnet_cifar.py | """
This code is based on the Torchvision repository, which was licensed under the BSD 3-Clause.
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, in_planes, planes, stride=1, is_last=False):
super(BasicBlock, self).__... | 5,073 | 36.865672 | 104 | py |
TRSSL | TRSSL-main/datasets/datasets.py | import numpy as np
from PIL import Image, ImageFilter, ImageOps
import random
from torchvision import datasets, transforms
import torch
import pickle
import os
import math
# normalization parameters
cifar10_mean, cifar10_std = (0.4914, 0.4822, 0.4465), (0.2471, 0.2435, 0.2616)
cifar100_mean, cifar100_std = (0.5071, 0... | 29,457 | 41.203438 | 214 | py |
TRSSL | TRSSL-main/utils/utils.py | import os
import torch
import numpy as np
import random
from progress.bar import Bar as Bar
import torch.nn.functional as F
import shutil
import matplotlib.pyplot as plt
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = targ... | 4,886 | 30.127389 | 95 | py |
TRSSL | TRSSL-main/utils/evaluate_utils.py | import numpy as np
import torch
import torch.nn.functional as F
from sklearn import metrics
from scipy.optimize import linear_sum_assignment
@torch.no_grad()
def hungarian_evaluate(predictions, targets, offset=0):
# Hungarian matching
targets = targets - offset
predictions = predictions - offset
predi... | 2,269 | 36.213115 | 161 | py |
TRSSL | TRSSL-main/utils/uncr_util.py | import random
import time
import pickle
import numpy as np
import torch
import torch.nn.functional as F
from tqdm import tqdm
from .utils import AverageMeter
def uncr_generator(args, data_loader, model):
batch_time = AverageMeter()
data_time = AverageMeter()
end = time.time()
pseudo_idx = []
pseud... | 3,161 | 31.265306 | 158 | py |
TRSSL | TRSSL-main/utils/sinkhorn_knopp.py | import torch
import numpy as np
def shoot_infs(inp_tensor):
"""Replaces inf by maximum of tensor"""
mask_inf = torch.isinf(inp_tensor)
ind_inf = torch.nonzero(mask_inf)
if len(ind_inf) > 0:
for ind in ind_inf:
if len(ind) == 2:
inp_tensor[ind[0], ind[1]] = 0
... | 2,410 | 32.957746 | 105 | py |
BiRTE | BiRTE-main/main.py | from transformers import WEIGHTS_NAME,AdamW, get_linear_schedule_with_warmup
from bert4keras.tokenizers import Tokenizer
from model import BiRTE
from util import *
from tqdm import tqdm
import random
import os
import torch.nn as nn
import torch
from transformers.modeling_bert import BertConfig
import json
def search(p... | 18,791 | 39.32618 | 126 | py |
BiRTE | BiRTE-main/model.py | from transformers.modeling_bert import BertModel,BertPreTrainedModel
import torch.nn as nn
import torch
from torch.autograd import Variable
import numpy as np
class Biaffine(nn.Module):
'''
Args:
in1_features: size of each first input sample
in2_features: size of each second input sample
... | 7,229 | 36.46114 | 100 | py |
BiRTE | BiRTE-main/run.py | import argparse
from main import *
import torch
parser = argparse.ArgumentParser(description='Model Controller')
parser.add_argument('--cuda_id', default="0", type=str)
parser.add_argument('--base_path', default="./dataset", type=str)
parser.add_argument('--dataset', default='WebNLG', type=str)
parser.add_argument('--... | 1,383 | 45.133333 | 108 | py |
BiRTE | BiRTE-main/util.py | #! -*- coding:utf-8 -*-
import numpy as np
import random
from copy import deepcopy
import os
import pickle
import torch
import json
def get_more_data(all_data):
s_more = []
o_more = []
for ex in all_data:
all_s = set()
all_o = set()
for s, p, o in ex["triple_list"]:
all... | 12,507 | 32.354667 | 114 | py |
BiRTE | BiRTE-main/bert4keras/optimizers.py | # -*- coding: utf-8 -*-
# 优化相关
import numpy as np
import tensorflow as tf
from bert4keras.backend import keras, K, is_tf_keras
from bert4keras.snippets import is_string, string_matching
from bert4keras.snippets import is_one_of, insert_arguments
from bert4keras.backend import piecewise_linear
import re
class Adam(ke... | 34,935 | 34.360324 | 83 | py |
BiRTE | BiRTE-main/bert4keras/tokenizers.py | #! -*- coding: utf-8 -*-
# 工具函数
import unicodedata, re
from bert4keras.snippets import is_string, is_py2
from bert4keras.snippets import open
def load_vocab(dict_path, encoding='utf-8', simplified=False, startswith=None):
"""从bert的词典文件中读取词典
"""
token_dict = {}
with open(dict_path, encoding=encoding) ... | 15,186 | 31.450855 | 502 | py |
BiRTE | BiRTE-main/bert4keras/layers.py | #! -*- coding: utf-8 -*-
# 自定义层
import numpy as np
import tensorflow as tf
from bert4keras.backend import keras, K
from bert4keras.backend import search_layer
from bert4keras.backend import sequence_masking
from bert4keras.backend import pool1d
from bert4keras.backend import divisible_temporal_padding
from bert4keras.... | 31,362 | 33.464835 | 80 | py |
BiRTE | BiRTE-main/bert4keras/snippets.py | #! -*- coding: utf-8 -*-
# 代码合集
import six
import logging
import numpy as np
import re
import sys
_open_ = open
is_py2 = six.PY2
if not is_py2:
basestring = str
def is_string(s):
"""判断是否是字符串
"""
return isinstance(s, basestring)
def strQ2B(ustring):
"""全角符号转对应的半角符号
"""
rstring = ''
... | 15,499 | 28.807692 | 80 | py |
BiRTE | BiRTE-main/bert4keras/backend.py | # -*- coding: utf-8 -*-
# 分离后端函数,主要是为了同时兼容原生keras和tf.keras
# 通过设置环境变量TF_KERAS=1来切换tf.keras
import os, sys
from distutils.util import strtobool
import numpy as np
import tensorflow as tf
# 判断是tf.keras还是纯keras的标记
is_tf_keras = strtobool(os.environ.get('TF_KERAS', '0'))
if is_tf_keras:
import tensorflow.keras as ke... | 5,182 | 23.799043 | 73 | py |
BiRTE | BiRTE-main/bert4keras/models.py | #! -*- coding: utf-8 -*-
# 主要模型
import numpy as np
from bert4keras.layers import *
from bert4keras.snippets import delete_arguments
from keras.models import Model
import json
class Transformer(object):
"""模型基类
"""
def __init__(
self,
vocab_size, # 词表大小
hidden_size, # 编码维度
... | 62,335 | 32.157447 | 87 | py |
rnn-seq2seq-learning | rnn-seq2seq-learning-main/scripts/dataloader.py | '''
Author: Zhengxiang (Jack) Wang
GitHub: https://github.com/jaaack-wang
Website: https://jaaack-wang.eu.org
About: Code for creating dataloader in PyTorch
'''
import torch
from functools import partial
from torch.utils.data import Dataset, DataLoader
import sys
import pathlib
# import from local script
sys.path.ins... | 6,202 | 32.711957 | 75 | py |
rnn-seq2seq-learning | rnn-seq2seq-learning-main/scripts/model.py | '''
Author: Zhengxiang (Jack) Wang
GitHub: https://github.com/jaaack-wang
Website: https://jaaack-wang.eu.org
About: RNN Seq2Seq models (Simple RNN, GRU, LSTM)
in PyTorch. Allows: attention, bidirectional RNN,
as well as multilayered RNN etc.
'''
import random
import torch
import torch.nn as nn
import torch.nn.functio... | 7,864 | 38.522613 | 80 | py |
rnn-seq2seq-learning | rnn-seq2seq-learning-main/scripts/pytorch_utils.py | '''
Author: Zhengxiang (Jack) Wang
GitHub: https://github.com/jaaack-wang
Website: https://jaaack-wang.eu.org
About: Utility functions for training, evaluation,
and deployment (i.e., prediction).
'''
import torch
import torch.nn as nn
import torch.nn.init as init
from functools import partial
import matplotlib.pyplot ... | 13,983 | 35.511749 | 89 | py |
libai | libai-main/libai/models/utils/model_loader/base_loader.py | # coding=utf-8
# Copyright 2021 The OneFlow 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 require... | 22,702 | 36.964883 | 100 | py |
libai | libai-main/libai/tokenizer/tokenization_bert.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# 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 ... | 19,425 | 36.720388 | 99 | py |
libai | libai-main/libai/utils/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 fnmatch
import hashlib
import json
import loggin... | 11,913 | 33.734694 | 99 | py |
libai | libai-main/libai/inference/utils/imagenet_class.py | IMAGENET_LABELS = [
"tench, Tinca tinca",
"goldfish, Carassius auratus",
"great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias", # noqa: E501
"tiger shark, Galeocerdo cuvieri",
"hammerhead, hammerhead shark",
"electric ray, crampfish, numbfish, torpedo",
"stin... | 29,033 | 27.947159 | 142 | py |
libai | libai-main/projects/mock_transformers/dist_infer_opt.py | # coding=utf-8
# Copyright 2021 The OneFlow 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 require... | 3,789 | 32.839286 | 99 | py |
libai | libai-main/projects/mock_transformers/dist_infer_llama.py | # coding=utf-8
# Copyright 2021 The Sugon Authors. All rights reserved.
# Copyright 2021 The OneFlow 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... | 4,277 | 31.656489 | 95 | py |
libai | libai-main/projects/mock_transformers/init_env.py | # coding=utf-8
# Copyright 2021 The OneFlow 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 require... | 4,360 | 33.338583 | 90 | py |
libai | libai-main/projects/mock_transformers/dist_infer_gpt.py | # coding=utf-8
# Copyright 2021 The OneFlow 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 require... | 4,812 | 29.656051 | 92 | py |
libai | libai-main/projects/mock_transformers/dist_infer_bloom.py | # coding=utf-8
# Copyright 2021 The OneFlow 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 require... | 3,820 | 30.578512 | 100 | py |
libai | libai-main/projects/mock_transformers/mock_tokenization.py | # coding=utf-8
# Copyright 2021 The OneFlow 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 require... | 5,136 | 35.432624 | 99 | py |
libai | libai-main/projects/MOCOV3/utils/load_checkpoint.py | # coding=utf-8
# Copyright 2021 The OneFlow 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 require... | 2,591 | 34.506849 | 83 | py |
libai | libai-main/projects/MOCOV3/utils/weight_convert.py | # coding=utf-8
# Copyright 2021 The OneFlow 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 require... | 3,558 | 31.953704 | 100 | py |
libai | libai-main/projects/MOCOV3/modeling/vit.py | # coding=utf-8
# Copyright 2021 The OneFlow 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 require... | 5,715 | 35.177215 | 95 | py |
libai | libai-main/projects/text_classification/modeling/load_megatron_weight.py | # coding=utf-8
# Copyright 2021 The OneFlow 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 require... | 5,294 | 35.770833 | 100 | py |
libai | libai-main/projects/MAE/train_net.py | # coding=utf-8
# Copyright 2021 The OneFlow 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 require... | 3,384 | 35.010638 | 99 | py |
libai | libai-main/projects/MAE/configs/mae_finetune.py | # coding=utf-8
# Copyright 2021 The OneFlow 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 require... | 3,855 | 28.212121 | 99 | py |
libai | libai-main/projects/MAE/utils/lr_decay.py | # coding=utf-8
# Copyright 2021 The OneFlow 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 require... | 3,656 | 32.550459 | 96 | py |
libai | libai-main/projects/MAE/utils/weight_convert.py | # coding=utf-8
# Copyright 2021 The OneFlow 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 require... | 3,986 | 31.153226 | 95 | py |
libai | libai-main/projects/SimCSE/config/config_simcse_sup.py | from omegaconf import OmegaConf
from configs.common.data.bert_dataset import tokenization
from configs.common.models.bert import cfg as simcse_cfg
from configs.common.models.graph import graph
from configs.common.optim import optim
from configs.common.train import train
from libai.config import LazyCall
from libai.dat... | 2,934 | 27.77451 | 77 | py |
libai | libai-main/projects/SimCSE/config/config_simcse_unsup.py | from omegaconf import OmegaConf
from configs.common.data.bert_dataset import tokenization
from configs.common.models.bert import cfg as simcse_cfg
from configs.common.models.graph import graph
from configs.common.optim import optim
from configs.common.train import train
from libai.config import LazyCall
from libai.dat... | 2,966 | 28.67 | 81 | py |
libai | libai-main/projects/SimCSE/utils/load_huggingface_weight.py | # coding=utf-8
# Copyright 2021 The OneFlow 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 require... | 7,362 | 44.732919 | 99 | py |
libai | libai-main/projects/CLIP/clip/clip.py | # --------------------------------------------------------
# Borrow code from:
# https://github.com/openai/CLIP/tree/main/clip/clip.py
# --------------------------------------------------------
import hashlib
import os
import urllib
import warnings
from typing import List, Union
import oneflow as flow
import torch
fr... | 7,197 | 34.99 | 168 | py |
libai | libai-main/projects/CLIP/clip/model.py | # --------------------------------------------------------
# Borrow code from:
# https://github.com/openai/CLIP/tree/main/clip/model.py
# --------------------------------------------------------
from collections import OrderedDict
from typing import Dict, Tuple, Union
import numpy as np
import oneflow as flow
import ... | 25,690 | 34.731572 | 100 | py |
libai | libai-main/projects/CLIP/tests/test_multi_head_attn.py | import os
import sys
import unittest
import numpy as np
import oneflow as flow
import torch
from torch.nn.functional import multi_head_attention_forward as multi_head_attention_forward_torch
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
from clip.ops import multi_head_atten... | 3,149 | 33.23913 | 100 | py |
libai | libai-main/projects/NeRF/datasets/nerf_dataset.py | # coding=utf-8
# Copyright 2021 The OneFlow 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 require... | 32,893 | 36.379545 | 99 | py |
libai | libai-main/projects/NeRF/modeling/NeRF.py | # coding=utf-8
# Copyright 2021 The OneFlow 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 require... | 5,175 | 34.210884 | 99 | py |
libai | libai-main/projects/QQP/modeling/load_megatron_weight.py | # coding=utf-8
# Copyright 2021 The OneFlow 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 require... | 4,859 | 35 | 100 | py |
libai | libai-main/projects/DALLE2/dalle2/dalle2_loader.py | import logging
import oneflow as flow
from oneflow.framework.check_point_v2 import _broadcast_py_object
import libai.utils.distributed as dist
from libai.models.build import build_model
from libai.models.utils.model_loader.base_loader import (
ModelLoaderHuggerFace,
_load_state_dict_into_model,
)
logger = lo... | 3,927 | 39.494845 | 100 | py |
libai | libai-main/projects/DALLE2/dalle2/vector_quantize_flow.py | # from https://github.com/lucidrains/vector_quantize_pytorch/vector_quantize_pytorch.py
import oneflow as flow
import oneflow.nn.functional as F
from einops import rearrange, repeat
from oneflow import einsum, nn
from libai.utils import distributed
def exists(val):
return val is not None
def default(val, d):
... | 19,209 | 30.033926 | 100 | py |
libai | libai-main/projects/DALLE2/swinir/utils.py | # -----------------------------------------------------------------------------------
# from
# https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/layers/weight_init.py
# -----------------------------------------------------------------------------------
import collections.abc
import math
import w... | 5,374 | 39.413534 | 99 | py |
libai | libai-main/projects/DALLE2/swinir/models.py | # -----------------------------------------------------------------------------------
# SwinIR: Image Restoration Using Swin Transformer, https://arxiv.org/abs/2108.10257
# Originally Written by Ze Liu, Modified by Jingyun Liang.
# -----------------------------------------------------------------------------------
# co... | 37,112 | 34.823359 | 100 | py |
libai | libai-main/projects/DALLE2/swinir/upsample.py | import os
import oneflow as flow
import requests
from .models import SwinIR as net
def load_torch_weight(model, model_path):
# load torch weight
import torch
param_key_g = "params_ema"
pretrained_model = torch.load(model_path, map_location="cpu")
pretrained_model = (
pretrained_model[pa... | 2,486 | 28.607143 | 88 | py |
libai | libai-main/projects/BLOOM/modeling/activation.py | # coding=utf-8
# Copyright 2021 The OneFlow Authors. All rights reserved.
# Copyright 2022 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... | 2,621 | 30.590361 | 97 | py |
libai | libai-main/projects/BLOOM/modeling/bloom_model.py | # coding=utf-8
# Copyright 2021 The OneFlow Authors. All rights reserved.
# Copyright 2022 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... | 15,297 | 35.080189 | 110 | py |
libai | libai-main/projects/BLOOM/modeling/attention.py | # coding=utf-8
# Copyright 2021 The OneFlow Authors. All rights reserved.
# Copyright 2022 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... | 7,869 | 33.669604 | 100 | py |
libai | libai-main/projects/BLOOM/modeling/mask.py | # coding=utf-8
# Copyright 2021 The OneFlow Authors. All rights reserved.
# Copyright 2022 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... | 3,662 | 35.63 | 86 | py |
libai | libai-main/projects/T5/utils/weight_convert.py | import argparse
import oneflow as flow
import torch
from libai.config import LazyConfig
def parse_args():
parser = argparse.ArgumentParser(description="MT5 Weight Convertor")
parser.add_argument(
"--oneflow_state_dict_path", type=str, help="The path of mt5's checkpoint in LiBai"
)
parser.add... | 10,611 | 47.678899 | 99 | py |
libai | libai-main/projects/Stable_Diffusion/generate_prior_image.py | # coding=utf-8
# Copyright 2021 The OneFlow 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 require... | 4,744 | 31.951389 | 99 | py |
libai | libai-main/tests/config/test_instantiate_config.py | # coding=utf-8
# Copyright 2021 The OneFlow Authors. All rights reserved.
# Copyright (c) Facebook, Inc. and its affiliates.
#
# 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... | 4,865 | 31.657718 | 96 | py |
libai | libai-main/tests/model_loader/test_mt5_loader.py | # coding=utf-8
# Copyright 2021 The OneFlow 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 require... | 7,293 | 33.899522 | 151 | py |
libai | libai-main/tests/model_loader/test_t5_loader.py | # coding=utf-8
# Copyright 2021 The OneFlow 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 require... | 7,282 | 33.84689 | 150 | py |
libai | libai-main/tests/model_loader/test_roberta_loader.py | # coding=utf-8
# Copyright 2021 The OneFlow 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 require... | 6,023 | 34.64497 | 155 | py |
libai | libai-main/tests/model_loader/test_gpt_loader.py | # coding=utf-8
# Copyright 2021 The OneFlow 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 require... | 8,936 | 32.724528 | 151 | py |
libai | libai-main/tests/model_loader/test_swin_loader.py | # coding=utf-8
# Copyright 2021 The OneFlow 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 require... | 7,713 | 34.223744 | 152 | py |
libai | libai-main/tests/model_loader/test_vit_loader.py | # coding=utf-8
# Copyright 2021 The OneFlow 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 require... | 7,553 | 33.493151 | 151 | py |
libai | libai-main/tests/model_loader/test_bert_loader.py | # coding=utf-8
# Copyright 2021 The OneFlow 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 require... | 5,969 | 34.325444 | 152 | py |
libai | libai-main/tests/model_loader/test_swinv2_loader.py | # coding=utf-8
# Copyright 2021 The OneFlow 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 require... | 7,819 | 34.067265 | 154 | py |
libai | libai-main/configs/swinv2_imagenet.py | from libai.config import LazyCall
from .common.models.swinv2.swinv2_tiny_patch4_window8_256 import model
from .common.models.graph import graph
from .common.train import train
from .common.optim import optim
from .common.data.imagenet import dataloader
from flowvision import transforms
from flowvision.data import Mixu... | 4,195 | 28.549296 | 97 | py |
spring | spring-main/spring_amr/optim.py | # taken from
import math
import torch
from torch.optim.optimizer import Optimizer, required
class RAdam(Optimizer):
def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0, degenerated_to_sgd=True):
if not 0.0 <= lr:
raise ValueError("Invalid learning rate: {}".forma... | 4,345 | 42.46 | 111 | py |
spring | spring-main/spring_amr/utils.py | from glob import glob
from pathlib import Path
import torch
from transformers import AutoConfig
from spring_amr.dataset import AMRDataset, AMRDatasetTokenBatcherAndLoader
from spring_amr.modeling_bart import AMRBartForConditionalGeneration
from spring_amr.tokenization_bart import AMRBartTokenizer, PENMANBartTokenizer... | 5,027 | 28.751479 | 84 | py |
spring | spring-main/spring_amr/dataset.py | import logging
import random
import torch
from cached_property import cached_property
from torch.utils.data import Dataset
from spring_amr.IO import read_raw_amr_data
def reverse_direction(x, y, pad_token_id=1):
input_ids = torch.cat([y['decoder_input_ids'], y['lm_labels'][:, -1:]], 1)
attention_mask = torch.o... | 4,991 | 32.503356 | 105 | py |
spring | spring-main/spring_amr/modeling_bart.py | import copy
import math
import random
from typing import *
import torch
from torch import Tensor
from torch import nn
from torch.nn import functional as F
from transformers import modeling_bart as bart
from transformers.modeling_utils import BeamHypotheses, calc_banned_ngram_tokens, calc_banned_bad_words_ids, \
to... | 60,795 | 46.055728 | 236 | py |
spring | spring-main/spring_amr/evaluation.py | import datetime
from pathlib import Path
import penman
from sacrebleu import corpus_bleu
import torch
from tqdm import tqdm
import smatch
from spring_amr.dataset import reverse_direction
def predict_amrs(
loader, model, tokenizer, beam_size=1, tokens=None, restore_name_ops=False, return_all=False):
shuf... | 4,920 | 32.937931 | 126 | py |
spring | spring-main/spring_amr/tokenization_bart.py | import copy
import sys
from pathlib import Path
import penman
import regex as re
import torch
from transformers import BartTokenizer
from spring_amr import ROOT, postprocessing
from spring_amr.linearization import AMRTokens, AMRLinearizer
from spring_amr.penman import encode
class AMRBartTokenizer(BartTokenizer):
... | 26,484 | 38.412202 | 120 | py |
spring | spring-main/bin/predict_sentences.py | from pathlib import Path
import penman
import torch
from spring_amr import ROOT
from spring_amr.evaluation import predict_amrs, compute_smatch, predict_sentences, compute_bleu
from spring_amr.penman import encode
from spring_amr.utils import instantiate_loader, instantiate_model_and_tokenizer
if __name__ == '__main_... | 3,988 | 45.383721 | 122 | py |
spring | spring-main/bin/patch_legacy_checkpoint.py | if __name__ == '__main__':
from argparse import ArgumentParser
import torch
parser = ArgumentParser()
parser.add_argument('legacy_checkpoint')
parser.add_argument('patched_checkpoint')
parser.parse_args()
args = parser.parse_args()
to_remove = []
fixed = False
w = torch.load... | 730 | 24.206897 | 62 | py |
spring | spring-main/bin/predict_amrs_from_plaintext.py | from pathlib import Path
import penman
import torch
from tqdm import tqdm
from spring_amr.penman import encode
from spring_amr.utils import instantiate_model_and_tokenizer
def read_file_in_batches(path, batch_size=1000, max_length=100):
data = []
idx = 0
for line in Path(path).read_text().strip().splitl... | 5,603 | 36.610738 | 125 | py |
spring | spring-main/bin/predict_amrs.py | from pathlib import Path
import penman
import torch
from spring_amr import ROOT
from spring_amr.evaluation import predict_amrs, compute_smatch
from spring_amr.penman import encode
from spring_amr.utils import instantiate_loader, instantiate_model_and_tokenizer
if __name__ == '__main__':
from argparse import Arg... | 3,415 | 38.264368 | 125 | py |
spring | spring-main/bin/inspect_.py | import torch
import penman
from spring_amr.utils import instantiate_model_and_tokenizer
if __name__ == '__main__':
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('--checkpoint', type=str, required=True)
parser.add_argument('--beam-size', type=int, default=1)
pars... | 1,673 | 37.045455 | 106 | py |
spring | spring-main/bin/train.py | from pathlib import Path
import torch
try:
from torch.cuda.amp import autocast
autocast_available = True
except ImportError:
class autocast:
def __init__(self, enabled=True): pass
def __enter__(self): return self
def __exit__(self, exc_type, exc_value, exc_traceback): pass
autoc... | 15,893 | 36.574468 | 115 | py |
AOE-Net | AOE-Net-main/main.py | import sys
import os
import argparse
from tqdm import tqdm
import pandas as pd
import torch
import torch.nn.parallel
import torch.optim as optim
from torch.utils.tensorboard import SummaryWriter
from models.model import EventDetection
from dataset import VideoDataSet, Collator
from loss_function import bmn_loss_func,... | 10,325 | 43.317597 | 163 | py |
AOE-Net | AOE-Net-main/dataset.py | # -*- coding: utf-8 -*-
import os
import json
import numpy as np
import torch
from torch.utils.data.dataset import Dataset
from utils import ioa_with_anchors, iou_with_anchors
def load_json(file):
with open(file) as json_file:
json_data = json.load(json_file)
return json_data
class Collator(o... | 14,047 | 44.170418 | 145 | py |
AOE-Net | AOE-Net-main/loss_function.py | # -*- coding: utf-8 -*-
import torch
import numpy as np
import torch.nn.functional as F
def get_mask(tscale, duration):
bm_mask = []
for idx in range(duration):
mask_vector = [1 for i in range(tscale - idx)
] + [0 for i in range(idx)]
bm_mask.append(mask_vector)
bm_m... | 3,233 | 32 | 89 | py |
AOE-Net | AOE-Net-main/models/utils.py | import copy
import torch
import torch.nn as nn
import torch.nn.functional as F
def masked_softmax(vector, mask, dim=-1, memory_efficient=False, mask_fill_value=-1e32):
"""A masked softmax module to correctly implement attention in Pytorch.
Implementation adapted from: https://github.com/allenai/allennlp/blob/... | 8,205 | 44.588889 | 133 | py |
AOE-Net | AOE-Net-main/models/model.py | # -*- coding: utf-8 -*-
import torch
import torch.nn as nn
import torch.nn.functional as F
from .utils import *
from .bmn import BoundaryMatchingNetwork
class EventDetection(nn.Module):
def __init__(self, cfg):
super(EventDetection, self).__init__()
self.use_env_linear = cfg.MODEL.ENV_HIDDEN_DIM ... | 11,169 | 47.146552 | 142 | py |
AOE-Net | AOE-Net-main/models/bmn.py | # -*- coding: utf-8 -*-
import math
import numpy as np
import torch
import torch.nn as nn
class BoundaryMatchingNetwork(nn.Module):
def __init__(self, cfg):
super(BoundaryMatchingNetwork, self).__init__()
self.prop_boundary_ratio = cfg.BMN.PROP_BOUNDARY_RATIO
self.num_sample = cfg.BMN.NUM_... | 5,810 | 41.416058 | 100 | py |
flair | flair-master/collect_env.py | import torch
import transformers
import flair
def main():
print("#### Versions:")
print(f"##### Flair\n{flair.__version__}")
print(f"##### Pytorch\n{torch.__version__}")
print(f"##### Transformers\n{transformers.__version__}")
print(f"#### GPU\n{torch.cuda.is_available()}")
if __name__ == "__ma... | 338 | 18.941176 | 60 | py |
flair | flair-master/examples/ner/run_ner.py | import inspect
import json
import logging
import os
import sys
from dataclasses import dataclass, field
import torch
from transformers import HfArgumentParser
import flair
from flair import set_seed
from flair.embeddings import TransformerWordEmbeddings
from flair.models import SequenceTagger
from flair.trainers impo... | 5,261 | 32.303797 | 112 | py |
flair | flair-master/flair/optim.py | import logging
import torch
from torch.optim import Optimizer
from torch.optim.lr_scheduler import LambdaLR, ReduceLROnPlateau, _LRScheduler
from torch.optim.optimizer import required # type: ignore[attr-defined]
log = logging.getLogger("flair")
class SGDW(Optimizer):
r"""Implements stochastic gradient descent... | 11,041 | 38.435714 | 120 | py |
flair | flair-master/flair/inference_utils.py | import logging
import pickle
import re
import shutil
import sqlite3
from pathlib import Path
from typing import Union
import numpy as np
import torch
from tqdm import tqdm
import flair
from flair.embeddings import WordEmbeddings
# this is the default init size of a lmdb database for embeddings
DEFAULT_MAP_SIZE = 100... | 12,086 | 39.834459 | 112 | py |
flair | flair-master/flair/data.py | import bisect
import logging
import re
import typing
from abc import ABC, abstractmethod
from collections import Counter, defaultdict, namedtuple
from operator import itemgetter
from pathlib import Path
from typing import Dict, Iterable, List, Optional, Union, cast
import torch
from deprecated import deprecated
from t... | 65,248 | 34.694201 | 138 | py |
flair | flair-master/flair/training_utils.py | import logging
import random
import sys
from collections import defaultdict
from enum import Enum
from functools import reduce
from math import inf
from pathlib import Path
from typing import Dict, List, Optional, Union
from scipy.stats import pearsonr, spearmanr
from sklearn.metrics import mean_absolute_error, mean_s... | 14,157 | 32.709524 | 118 | py |
flair | flair-master/flair/file_utils.py | """Utilities for working with the local dataset cache. Copied from AllenNLP."""
import base64
import functools
import io
import logging
import mmap
import os
import re
import shutil
import tempfile
import typing
import warnings
import zipfile
from pathlib import Path
from typing import Optional, Sequence, Tuple, Union,... | 12,566 | 34.600567 | 109 | py |
flair | flair-master/flair/__init__.py | import logging.config
import os
from pathlib import Path
import torch
from transformers import set_seed as hf_set_seed
# global variable: cache_root
from .file_utils import set_proxies
cache_root = Path(os.getenv("FLAIR_CACHE_ROOT", Path(Path.home(), ".flair")))
device: torch.device
"""Flair is using a single devic... | 1,705 | 20.871795 | 106 | py |
flair | flair-master/flair/samplers.py | import logging
import random
from collections import defaultdict
from typing import Dict
import torch
from torch.utils.data.sampler import Sampler
log = logging.getLogger("flair")
class FlairSampler(Sampler):
def set_dataset(self, data_source):
"""Initialize the data source for the FlairSampler.
... | 3,688 | 30 | 116 | py |
flair | flair-master/flair/nn/model.py | import inspect
import itertools
import logging
import typing
from abc import ABC, abstractmethod
from collections import Counter
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
import torch.nn
from torch.nn.modules.loss import _Loss
from torch.utils.data.dataset import Dataset
... | 41,127 | 41.443756 | 267 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.