code stringlengths 101 5.91M |
|---|
def input_fn(is_training, data_dir, batch_size):
filenames = get_filenames(is_training, data_dir)
dataset = tf.data.Dataset.from_tensor_slices(filenames)
if is_training:
dataset = dataset.shuffle(buffer_size=_NUM_TRAIN_FILES)
dataset = dataset.interleave(tf.data.TFRecordDataset, num_parallel_cal... |
def model_scaling(layer_setting, arch_setting):
new_layer_setting = copy.deepcopy(layer_setting)
for layer_cfg in new_layer_setting:
for block_cfg in layer_cfg:
block_cfg[1] = make_divisible((block_cfg[1] * arch_setting[0]), 8)
split_layer_setting = [new_layer_setting[0]]
for layer_c... |
class TFSegformerMLP(tf.keras.layers.Layer):
def __init__(self, config: SegformerConfig, **kwargs):
super().__init__(**kwargs)
self.proj = tf.keras.layers.Dense(config.decoder_hidden_size, name='proj')
def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
height = shape_list(hidden_stat... |
_schema(QasmQobjInstructionSchema)
class QasmQobjInstruction(QobjInstruction):
def __init__(self, name, **kwargs):
super().__init__(name=name, **kwargs) |
class ResnetCompleteNetworkTest(tf.test.TestCase):
def _resnet_small(self, inputs, num_classes=None, is_training=True, global_pool=True, output_stride=None, include_root_block=True, spatial_squeeze=True, reuse=None, scope='resnet_v2_small'):
block = resnet_v2.resnet_v2_block
blocks = [block('block1'... |
(scope='session')
def saliency_gpt2_model_tiny():
return inseq.load_model('hf-internal-testing/tiny-random-GPT2LMHeadModel', 'saliency') |
class Task(NamedTuple):
video_name: str
video_path: str
out_path: str
min_frame: int
max_frame: int
target_fps: float
max_height: int |
def block17(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None):
with tf.variable_scope(scope, 'Block17', [net], reuse=reuse):
with tf.variable_scope('Branch_0'):
tower_conv = slim.conv2d(net, 192, 1, scope='Conv2d_1x1')
with tf.variable_scope('Branch_1'):
tower... |
class InvertedResidual(nn.Module):
def __init__(self, in_channels, out_channels, stride, expand_ratio, dilation=1, norm_layer=nn.BatchNorm2d):
super(InvertedResidual, self).__init__()
assert (stride in [1, 2])
self.use_res_connect = ((stride == 1) and (in_channels == out_channels))
l... |
def process(args):
data_root = (Path(args.data_root).absolute() / args.lang)
print('Generating manifest...')
df_top_n = get_top_n(data_root)
(id_to_split, speakers) = get_splits(df_top_n)
if args.convert_to_wav:
convert_to_wav(data_root, df_top_n['path'].tolist())
manifest_by_split = {sp... |
class LinearClassifierEvaluation(pl.LightningModule):
def __init__(self, trunk: DictConfig, classifier: DictConfig, optimizer: DictConfig, pretrained_trunk_path: str, trunk_pattern: str='^(trunk\\.)', train_transform: Optional[DictConfig]=None, val_transform: Optional[DictConfig]=None, test_transform: Optional[Dict... |
class NeuronCoverage():
def __init__(self, thresholds=(0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)):
self._thresholds = thresholds
self._layer_neuron_id_to_global_neuron_id = {}
self._results = {}
self._num_layer = 0
self._num_neuron = 0
self._num_input = 0
... |
def _NeedToReturnNothingDiagnoser(msg):
gcc_regex = (_GCC_FILE_LINE_RE + "instantiated from here\\n.*gmock-actions\\.h.*error: instantiation of \\'testing::internal::ReturnAction<R>::Impl<F>::value_\\' as type \\'void\\'")
clang_regex1 = (("error: field has incomplete type \\'Result\\' \\(aka \\'void\\'\\)(\\r)... |
def training(sess, neuralnet, saver, dataset, epochs, batch_size):
start_time = time.time()
loss_tr = 0
list_loss = []
list_psnr = []
list_psnr_static = []
makedir((PACK_PATH + '/training'))
makedir((PACK_PATH + '/static'))
makedir((PACK_PATH + '/static/reconstruction'))
print(('\nTr... |
class ResidualAttentionModel(nn.Module):
def __init__(self):
super(ResidualAttentionModel, self).__init__()
self.conv1 = nn.Sequential(nn.Conv2d(1, 32, kernel_size=3, stride=1, padding=1, bias=False), nn.BatchNorm2d(32), nn.ReLU(inplace=True))
self.rb1 = ResidualBlock(32, 1)
self.mpo... |
class LightGCN(nn.Module):
def __init__(self, num_users: int, num_items: int, emb_dim: int, num_layers: int=3, drop_rate: float=0.0) -> None:
super().__init__()
(self.num_users, self.num_items) = (num_users, num_items)
self.num_layers = num_layers
self.drop_rate = drop_rate
s... |
def test_init_pose(index):
init_pose_list = [[25.0, 0.0, np.pi], [24.8, 3.13, ((np.pi * 26) / 25)], [24.21, 6.22, ((np.pi * 27) / 25)], [23.24, 9.2, ((np.pi * 28) / 25)], [21.91, 12.04, ((np.pi * 29) / 25)], [20.23, 14.69, ((np.pi * 30) / 25)], [18.22, 17.11, ((np.pi * 31) / 25)], [15.94, 19.26, ((np.pi * 32) / 25)... |
def longest_common_subsequence(a, b):
if ((not a) or (not b)):
return ''
elif (a[0] == b[0]):
return (a[0] + longest_common_subsequence(a[1:], b))
else:
return max(longest_common_subsequence(a, b[1:]), longest_common_subsequence(a[1:], b), key=len) |
class SpeakerDiarizationConfig(base.PipelineConfig):
def __init__(self, segmentation: (m.SegmentationModel | None)=None, embedding: (m.EmbeddingModel | None)=None, duration: float=5, step: float=0.5, latency: ((float | Literal[('max', 'min')]) | None)=None, tau_active: float=0.6, rho_update: float=0.3, delta_new: f... |
def split(table_path, train_path, val_path, test_path):
table = pd.read_csv(table_path)
table = table.drop_duplicates(['molecule', 'linker'])
linker_sizes = []
fragment_sizes = []
number_of_linkers = []
number_of_fragments = []
for (linker_smi, fragments_smi) in tqdm(table[['linker', 'fragme... |
def H(a, x):
P = (x ** 2)
H0 = np.exp((- (x ** 2)))
Q = (1.5 / (x ** 2))
return (H0 - (((a / np.sqrt(np.pi)) / P) * ((((H0 * H0) * (((((4.0 * P) * P) + (7.0 * P)) + 4.0) + Q)) - Q) - 1))) |
def medium_oshi_zumo_nfsp_avg_policy_params(env: MultiAgentEnv) -> Dict[(str, Any)]:
return {'framework': 'torch', 'num_gpus': float(os.getenv('WORKER_GPU_NUM', 0.0)), 'num_workers': 0, 'num_gpus_per_worker': float(os.getenv('WORKER_GPU_NUM', 0.0)), 'num_envs_per_worker': 1, 'learning_starts': 16000, 'train_batch_s... |
def svm_predict(arg1, arg2=None, arg3=None, arg4=None, arg5=None):
if arg2:
arg1_array = (c_float * len(arg1))()
arg1_array[:] = arg1
arg2_array = (c_char_p * len(arg2))()
arg2_array[:] = arg2
thundersvm.load_from_python_interface(arg1_array, arg2_array, len(arg1_array))
... |
class Div255Input(Module):
def __init__(self, inplace: bool=True, dtype: dtype=torch.get_default_dtype()) -> None:
super().__init__()
self.inplace = inplace
self.dtype = dtype
def forward(self, x: (Tensor | List[Tensor])) -> Tensor:
if (type(x) is Tensor):
return div_... |
class ImageNet21KParser():
def __init__(self, add_adj=False):
self.nlp = spacy.load('en_core_web_sm')
self.look_up = {}
with open('datasets/class_names/imagenet-21k.txt') as f:
class_names = f.read()
class_names = class_names.split()
self.class_names = ([''] * len... |
class GlobalContext(nn.Module):
def __init__(self, channels, use_attn=True, fuse_add=False, fuse_scale=True, init_last_zero=False, rd_ratio=(1.0 / 8), rd_channels=None, rd_divisor=1, act_layer=nn.ReLU, gate_layer='sigmoid'):
super(GlobalContext, self).__init__()
act_layer = get_act_layer(act_layer)
... |
def val(epoch):
global best_rmse
is_best_model = False
net.eval()
total_step_val = 0
eval_loss = 0.0
error_sum_val = {'MSE': 0, 'RMSE': 0, 'ABS_REL': 0, 'LG10': 0, 'MAE': 0, 'DELTA1.02': 0, 'DELTA1.05': 0, 'DELTA1.10': 0, 'DELTA1.25': 0, 'DELTA1.25^2': 0, 'DELTA1.25^3': 0}
tbar = tqdm(valloa... |
def main(source_root):
dest_root = '/media/pc/6T/jasonjzhao/data/MS-Celeb-1M_Resized'
mkdir(dest_root)
cwd = os.getcwd()
os.chdir(source_root)
os.system("find . -name '*.DS_Store' -type f -delete")
os.chdir(cwd)
if (not os.path.isdir(dest_root)):
os.mkdir(dest_root)
for subfolder... |
def _pad_kv_cache_view(t: torch.Tensor, len: int, device: torch.device, pos: int=2) -> torch.Tensor:
cur_size = list(t.size())
if (cur_size[pos] < len):
zeros = get_zero_tensor(len, cur_size, device, pos)
padded_view = torch.cat((zeros, t), dim=pos)
return padded_view
elif (cur_size[... |
class PyramidPooling(nn.Module):
def __init__(self, in_channels, upscale_out_size):
super(PyramidPooling, self).__init__()
pool_out_sizes = [1, 2, 3, 6]
assert (len(pool_out_sizes) == 4)
assert ((in_channels % 4) == 0)
mid_channels = (in_channels // 4)
self.branches =... |
class Logger():
def __init__(self, log_dir, n_logged_samples=10, summary_writer=SummaryWriter):
self._log_dir = log_dir
print('')
print('logging outputs to ', log_dir)
print('')
self._n_logged_samples = n_logged_samples
self._summ_writer = summary_writer(log_dir, flus... |
_metaclass(ABCMeta)
class Discretizer(object):
def get_nr_bin(self):
pass
def get_bin(self, v):
pass |
def get_reporting_integration_callbacks(report_to):
for integration in report_to:
if (integration not in INTEGRATION_TO_CALLBACK):
raise ValueError(f"{integration} is not supported, only {', '.join(INTEGRATION_TO_CALLBACK.keys())} are supported.")
return [INTEGRATION_TO_CALLBACK[integration]... |
def sampling(blm, w_mu=None, N=1, alpha=1.0):
if (w_mu is None):
w_mu = get_post_params_mean(blm)
if (N == 1):
z = (np.random.randn(blm.nbasis) * alpha)
else:
z = (np.random.randn(blm.nbasis, N) * alpha)
U = blm.stats[0]
invUz = scipy.linalg.solve_triangular(U, z, lower=False... |
class BaseVideoDataset(torch.utils.data.Dataset):
def __init__(self, name, root, image_loader=jpeg4py_loader_w_failsafe):
self.name = name
self.root = root
self.image_loader = image_loader
self.sequence_list = []
self.class_list = []
def __len__(self):
return self... |
def find_and_remove_errors(mode, out_root, ref_bin_xy, ref_data, s):
true_ref_xy = np.array([[e, n] for (e, n) in zip(ref_data['easting'], ref_data['northing'])])
binned_ref_xy = np.array([ref_bin_xy[math.floor(l)] for l in ref_data['l']])
ref_errors = np.linalg.norm((true_ref_xy - binned_ref_xy), axis=1)
... |
class BrokenRecordableEnv(object):
metadata = {'render.modes': [None, 'rgb_array']}
def render(self, mode=None):
pass |
def main(config):
cudnn.benchmark = True
if (not os.path.exists(config.log_dir)):
os.makedirs(config.log_dir)
if (not os.path.exists(config.model_save_dir)):
os.makedirs(config.model_save_dir)
if (not os.path.exists(config.sample_dir)):
os.makedirs(config.sample_dir)
vcc_load... |
def _dreg(model, x, K):
(_, px_z, zs) = model(x, K)
lpz = model.pz(*model.pz_params).log_prob(zs).sum((- 1))
lpx_z = (px_z.log_prob(x).view(*px_z.batch_shape[:2], (- 1)) * model.llik_scaling)
qz_x = model.qz_x(*[p.detach() for p in model.qz_x_params])
lqz_x = qz_x.log_prob(zs).sum((- 1))
lw = ((... |
_module()
class Loader():
def __init__(self, ann_file, parser, repeat=1):
assert isinstance(ann_file, str)
assert isinstance(repeat, int)
assert isinstance(parser, dict)
assert (repeat > 0)
assert osp.exists(ann_file), f'{ann_file} is not exist'
self.ori_data_infos = ... |
def calculate_fid_given_paths(paths, inception_path, low_profile=False):
for p in paths:
if (not os.path.exists(p)):
raise RuntimeError(('Invalid path: %s' % p))
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
with tf.Session(config=config) as sess:
sess.run(... |
class custom_build_ext(build_ext):
def build_extension(self, ext):
if isinstance(ext, TensorflowExtension):
ext.compile()
filename = self.get_ext_filename(ext.name)
if (not self.dry_run):
os.makedirs(path.join(self.build_lib, path.dirname(filename)), exist... |
def _cifar100_to_cifar20(target):
_dict = {0: 4, 1: 1, 2: 14, 3: 8, 4: 0, 5: 6, 6: 7, 7: 7, 8: 18, 9: 3, 10: 3, 11: 14, 12: 9, 13: 18, 14: 7, 15: 11, 16: 3, 17: 9, 18: 7, 19: 11, 20: 6, 21: 11, 22: 5, 23: 10, 24: 7, 25: 6, 26: 13, 27: 15, 28: 3, 29: 15, 30: 0, 31: 11, 32: 1, 33: 10, 34: 12, 35: 14, 36: 16, 37: 9, 3... |
def validation(data_iter, net):
net.eval()
(losses, batch_num, acc, acc_num) = (0, 0, 0, 0)
criterion = nn.BCELoss()
for (batch_idx, batch) in enumerate(data_iter):
(qbatch, rbatch, label) = batch
qbatch = torch.from_numpy(qbatch)
rbatch = torch.from_numpy(rbatch)
label =... |
def gen_downsample(inchannel, outchannel, layer_num):
if (layer_num == 1):
(yield nn.Conv2d(inchannel, outchannel, 1, stride=1, bias=False))
else:
(yield nn.Conv2d(inchannel, outchannel, 1, stride=2, bias=False))
(yield nn.BatchNorm2d(outchannel)) |
def test(model, queryloader, galleryloader, use_gpu, ranks=[1, 5, 10, 20], return_distmat=False):
batch_time = AverageMeter()
model.eval()
with torch.no_grad():
(qf, q_pids, q_cloth_ids, q_camids) = ([], [], [], [])
for (batch_idx, (imgs, pids, cloth_ids, camids, _)) in enumerate(queryloader... |
class LabelEncoderTransformer(AutotabularPreprocessingAlgorithm):
def __init__(self, random_state: Optional[np.random.RandomState]=None):
self.random_state = random_state
def fit(self, X: Optional[PIPELINE_DATA_DTYPE]=None, y: PIPELINE_DATA_DTYPE=None) -> 'LabelEncoderTransformer':
self.preproce... |
def gradient_update(scores, grads):
m = len(grads)
tmp = torch.zeros_like(grads[0])
for m_i in range(m):
tmp += (scores[m_i] * grads[m_i])
tmp /= m
return tmp |
def parse_args():
parser = argparse.ArgumentParser('Get Test Result of VQA Network')
parser.add_argument('--cfg', type=str, help='path to answer net config yaml')
parser.add_argument('--ckpt', type=str, help='path to checkpoint of answer net')
parser.add_argument('--bs', type=int)
parser.add_argumen... |
def export_fbx(pkl_path):
input = pkl_path
output = pkl_path.replace('.pkl', '.fbx')
execute_python = '/apdcephfs/share_1227775/shingxchen/libs/blender_bpy/blender-2.93.2-linux-x64/blender'
export_scripts = './scripts/fbx_output.py'
os.system(f'{execute_python} -noaudio --background --python {export... |
class GolbalContextBlock(tf.keras.layers.Layer):
def __init__(self, inplanes, ratio, headers, pooling_type='att', att_scale=False, fusion_type='channel_add', **kwargs):
super().__init__(name='GCB', **kwargs)
assert (pooling_type in ['att', 'avg'])
assert (fusion_type in ['channel_add', 'chan... |
class BloomForCausalLM(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def parse_args():
parser = argparse.ArgumentParser(description='Pretrain llama2 with atorch fsdp.')
parser.add_argument('--model_name_or_path', type=str, help='Path to pretrained model or model identifier from huggingface.co/models.', required=False)
parser.add_argument('--dataset_path', type=str, default=N... |
class UniGCN(nn.Module):
def __init__(self, in_channels: int, hid_channels: int, num_classes: int, use_bn: bool=False, drop_rate: float=0.5) -> None:
super().__init__()
self.layers = nn.ModuleList()
self.layers.append(UniGCNConv(in_channels, hid_channels, use_bn=use_bn, drop_rate=drop_rate))... |
class Dataset(ABC):
def __init__(self, name):
self.name = name
self.output_file = None
self.max_chunks = None
def from_default_config(cls, name):
config = json.loads(importlib.resources.read_text(mapping, 'default_{name}.json'.format(name=name)))
return cls(name, **config... |
def get_default_augmentation(dataloader_train, dataloader_val, patch_size, params=default_3D_augmentation_params, border_val_seg=(- 1), pin_memory=True, seeds_train=None, seeds_val=None, regions=None):
assert (params.get('mirror') is None), 'old version of params, use new keyword do_mirror'
tr_transforms = []
... |
def test_perfect_dice_score():
dice_score = metrics.dice(tp=75, fp=0, fn=0)
assert (dice_score == 1) |
def list_dtypes():
return [o3c.float32, o3c.float64, o3c.int8, o3c.int16, o3c.int32, o3c.int64, o3c.uint8, o3c.uint16, o3c.uint32, o3c.uint64, o3c.bool] |
class Resnet18(nn.Module):
def __init__(self, path):
super(Resnet18, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
self.bn1 = BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2... |
class PytorchGELUTanh(nn.Module):
def __init__(self):
super().__init__()
if (version.parse(torch.__version__) < version.parse('1.12.0')):
raise ImportError(f'You are using torch=={torch.__version__}, but torch>=1.12.0 is required to use PytorchGELUTanh. Please upgrade torch.')
def fo... |
class RandomVisionLabeledDataset(VisionDataset):
def __init__(self, size: Iterable[int], num_classes: int=10, transform: Optional[Module]=None):
super().__init__('data/', transform=transform)
self.length = size[0]
self.data = torch.randn(size)
self.labels = torch.randint(num_classes,... |
class ResNetBackboneGN(ResNetBackbone):
def __init__(self, layers, num_groups=32, in_channels=3):
super().__init__(layers, norm_layer=(lambda x: nn.GroupNorm(num_groups, x)), in_channels=in_channels)
def init_backbone(self, path):
with open(path, 'rb') as f:
state_dict = pickle.load(... |
class Memory():
def __init__(self):
self.actions = []
self.states = []
self.logprobs = []
self.rewards = []
self.is_terminals = []
def clear_memory(self):
del self.actions[:]
del self.states[:]
del self.logprobs[:]
del self.rewards[:]
... |
class UNet3D_CCT(nn.Module):
def __init__(self, in_channels=1, out_channels=3, init_features=64):
super(UNet3D_CCT, self).__init__()
features = init_features
self.encoder1 = UNet3D_CCT._block(in_channels, features, name='enc1')
self.pool1 = nn.MaxPool3d(kernel_size=2, stride=2)
... |
def eval_batch_s2cnn(mlp, s2cnn, data, batch_idxs, criterion, device_id=0):
geometry = data['features']['geometry'][(batch_idxs, ...)]
atom_types = data['features']['atom_types'][(batch_idxs, ...)]
atom_types_one_hot = to_one_hot(atom_types, NUM_ATOM_TYPES)
targets = data['targets'][(batch_idxs, ...)]
... |
def test_solarmach_pfss():
date = '2021-4-1 1:00:00'
body_list = ['Earth', 'STEREO-A']
vsw_list = [400, 400]
sm = SolarMACH(date, body_list, vsw_list, reference_long=100, reference_lat=10)
gong_map = get_gong_map(time=date, filepath=None)
assert (isinstance(gong_map, pfsspy.map.GongSynopticMap) ... |
class Cmns(NERBase, MentionDetectionBase):
def __init__(self, base_url, wiki_version, n=5):
self.__n = n
super().__init__(base_url, wiki_version)
def predict(self, sentence, sentences_doc):
self.__ngrams_overlap = []
self.mentions = []
self.rank_ens(sentence)
retu... |
class _TFVolume(tf.Module, Registrable):
def __init__(self, log_scale: bool=True, **kwargs: Any) -> None:
super().__init__()
self.log_scale = log_scale
def __call__(self, box_tensor: TFBoxTensor) -> tf.Tensor:
raise NotImplementedError |
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, in_planes, planes, stride=1):
super(BasicBlock, self).__init__()
self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
self.bn1 = FilterResponseNorm2d(planes)
self.conv2 = nn.Co... |
def missing_whitespace(logical_line):
line = logical_line
for index in range((len(line) - 1)):
char = line[index]
if ((char in ',;:') and (line[(index + 1)] not in WHITESPACE)):
before = line[:index]
if ((char == ':') and (before.count('[') > before.count(']')) and (befor... |
(os.environ.get('CIRCLECI'), 'Require COCO data and model zoo.')
class TestCaffe2Export(unittest.TestCase):
def setUp(self):
setup_logger()
def _test_model(self, config_path, device='cpu'):
from detectron2.export import Caffe2Model, add_export_config, export_caffe2_model
cfg = get_cfg()
... |
def training_loss_3rd_item_task_fastgcnnew(batch_index, model, sess, train_data, is_training):
train_loss = 0.0
(train_target_item, train_k_shot_user, train_second_order_items, train_third_order_users, train_oracle_item_ebd, train_mask_num_second_order_item, train_mask_num_third_order_user) = train_data
for... |
def _open_url(url):
try:
from webbrowser import open as wbopen
wbopen(url)
except:
pass |
class ImageLogger(Callback):
def __init__(self):
super().__init__()
_zero_only
def log_img(self, pl_module, batch, current_epoch, split='train'):
with torch.no_grad():
(images, labels) = batch
recons = pl_module.stage1(images)
images = images.cpu()
... |
def test_clpr_model(model, input_doc):
feature = input_doc._.CLPR_Features
label = input_doc._.CLPR_Labels
feature = np.asarray(feature)
predictions = model.predict(feature)
(acc, prec, rec, f1) = utilities.print_metrics(label, predictions)
return (acc, prec, rec, f1) |
class ResNet(nn.Module):
def __init__(self, block, layers, dataset_history, dataset2num_classes, network_width_multiplier, shared_layer_info, num_classes=1000, zero_init_residual=False, groups=1, width_per_group=64, replace_stride_with_dilation=None, norm_layer=None):
super(ResNet, self).__init__()
... |
_sentencepiece
_tokenizers
class FNetTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
tokenizer_class = FNetTokenizer
rust_tokenizer_class = FNetTokenizerFast
test_rust_tokenizer = True
test_sentencepiece = True
test_sentencepiece_ignore_case = True
test_seq2seq = False
def setUp(s... |
def search_replace_conv_linear(model, name_model='', arr=[]):
prev = None
for (i, m) in enumerate(model.children()):
modules_names = [key for key in model._modules.keys()]
layer_name = (((name_model + '.') + modules_names[i]) if (name_model != '') else (name_model + modules_names[i]))
ex... |
class Annealer():
def __init__(self, initial_value, final_value, n_steps_anneal, start_step=0, default=None, mode='geometric'):
if (n_steps_anneal < 0):
n_steps_anneal *= (- 1)
(initial_value, final_value) = (final_value, initial_value)
self.initial_value = initial_value
... |
def attention_layer(x, a, x_mask, a_mask, sim_func, scope='', output_alignment=False):
n = tf.shape(x)[1]
m = tf.shape(a)[1]
dist_matrix = sim_func(x, a)
joint_mask = compute_attention_mask(x_mask, a_mask, n, m)
if (joint_mask is not None):
dist_matrix += (VERY_NEGATIVE_NUMBER * (1 - tf.cast... |
class VNet(nn.Module):
def __init__(self, non_linearity='elu', in_channels=1, classes=4, init_features_maps=16, kernel_size=5, padding=2):
super(VNet, self).__init__()
self.classes = classes
self.in_channels = in_channels
self.in_tr = InputTransition(in_channels, init_features_maps, ... |
class Synface(Dataset):
def __init__(self, dataset_path, img_size, **kwargs):
super().__init__()
self.data = glob.glob(dataset_path)
assert (len(self.data) > 0), "Can't find data; make sure you specify the path to your dataset"
self.transform = transforms.Compose([transforms.CenterCr... |
def _test_tinshift_assert(dtype):
try:
from mmcv.ops import tin_shift
except ModuleNotFoundError:
pytest.skip('TINShift op is not successfully compiled')
inputs = [torch.rand(2, 3, 4, 2), torch.rand(2, 3, 4, 2)]
shifts = [torch.rand(2, 3), torch.rand(2, 5)]
for (x, shift) in zip(inpu... |
def test_get(fbdict):
fbdict['a'] = 'b'
assert (fbdict.get('a', 18) == 'b')
assert (fbdict.get('fall1', 18) == 7)
assert (fbdict.get('notexisting', 18) == 18)
assert (fbdict.get('fall3', 18) is True) |
def simplify_padding(padding_shapes):
all_same = True
padding_init = padding_shapes[0]
for pad in padding_shapes[1:]:
if (pad != padding_init):
all_same = False
return (all_same, padding_init) |
def sample_points(N, C, D):
assert (D == 3), 'D must be 3 to sample 3d points'
assert (C == 3), 'C must be 3 to sample 3d points'
p1 = np.array([1, (- 1), 3])
p2 = np.array([2, 3, 4])
p3 = np.array([(- 5), 6, 7])
np.random.seed(1)
x = np.random.uniform(size=(1, N))
np.random.seed(42)
... |
_tf
_retrieval
_sentencepiece
_tokenizers
class TFRagModelIntegrationTests(unittest.TestCase):
_property
def token_model(self):
return TFRagTokenForGeneration.from_pretrained_question_encoder_generator('facebook/dpr-question_encoder-single-nq-base', 'facebook/bart-large-cnn')
_property
def seque... |
def main():
args = parse_args()
assert (args.out or args.show), 'Please specify at least one operation (save or show the results) with the argument "--out" or "--show"'
if ((args.out is not None) and (not args.out.endswith(('.pkl', '.pickle')))):
raise ValueError('The output file must be a pkl file.... |
class PerturbLayer(nn.Module):
def __init__(self, in_channels=None, out_channels=None, nmasks=None, level=None, filter_size=None, debug=False, use_act=False, stride=1, act=None, unique_masks=False, mix_maps=None, train_masks=False, noise_type='uniform', input_size=None):
super(PerturbLayer, self).__init__()... |
class TransformerModel(nn.Module):
def __init__(self, seq_len: int, d_model: int, nhead: int, d_hid: int, nlayers: int, dropout: float=0.5, out_dim=91, num_labels=15):
super().__init__()
self.model_type = 'Transformer'
self.seq_len = seq_len
self.d_model = d_model
self.nhead ... |
def get_primes(num_primes, log_flag=False, log_scaler=1.0, prime_scaler=1.0):
primes = []
num = 2
prod_prime = 0
while (len(primes) < num_primes):
if is_prime(num):
if log_flag:
primes.append((np.log2((num * prime_scaler)) * log_scaler))
prod_prime += ... |
def linear_discriminant_analysis(name, solver=None, shrinkage=None, priors=None, n_components=None, store_covariance=False, tol=1e-05):
def _name(msg):
return ('%s.%s_%s' % (name, 'lda', msg))
solver_shrinkage = hp.choice(_name('solver_shrinkage_dual'), [('svd', None), ('lsqr', None), ('lsqr', 'auto'), ... |
def main():
(identities, attributes) = get_metadata()
celebrities = get_celebrities_and_images(identities)
targets = get_celebrities_and_target(celebrities, attributes)
json_data = build_json_format(celebrities, targets)
write_json(json_data) |
class CheckpointSaverTest(unittest.TestCase):
def setUp(self) -> None:
AsyncCheckpointSaver._saver_instance = None
AsyncCheckpointSaver.start_async_saving_ckpt()
def tearDown(self) -> None:
if AsyncCheckpointSaver._saver_instance:
AsyncCheckpointSaver._saver_instance.close()
... |
def get_pool_component(pool_name, spatial_size: Tuple[(int, int)]):
return {'adaptive_avg': nn.AdaptiveAvgPool2d(spatial_size), 'adaptive_max': nn.AdaptiveMaxPool2d(spatial_size), None: Identical(), 'none': Identical(), 'identical': Identical()}[pool_name] |
def to_leaf_format(some_json, start_idx=0):
leaf_json = {'users': [], 'num_samples': [], 'user_data': {}}
new_idx = start_idx
for (u, comments) in some_json.items():
new_idx += 1
leaf_json['users'].append(str(new_idx))
leaf_json['num_samples'].append(len(comments))
x = []
... |
def write_int(f, x, name, *args):
if any(args):
for arg in args:
f.write(('%s->' % arg))
f.write(('%s = %i;\n' % (name, x)))
else:
f.write(('c_int %s = %i;\n' % (name, x))) |
class KandinskyV22InpaintCombinedPipeline(DiffusionPipeline):
model_cpu_offload_seq = 'prior_text_encoder->prior_image_encoder->unet->movq'
_load_connected_pipes = True
def __init__(self, unet: UNet2DConditionModel, scheduler: DDPMScheduler, movq: VQModel, prior_prior: PriorTransformer, prior_image_encoder:... |
_module()
class ZeroCOCOStuffDataset(CustomDataset):
CLASSES = ('person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backp... |
def best_eer(val_scores, utt2len, utt2label, key_list):
def f_neg(threshold):
return utt_eer(val_scores, utt2len, utt2label, key_list, threshold)
thr_0 = ([0.2] * 1)
constraints = ([(0.0, 1.0)] * 1)
def bounds(**kwargs):
x = kwargs['x_new']
tmax = bool(np.all((x <= 1)))
t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.