code stringlengths 101 5.91M |
|---|
def read_langs_turn(args, file_name, max_line=None, ds_name=''):
print('Reading from {} for read_langs_turn'.format(file_name))
data = []
with open(file_name) as f:
dials = f.readlines()
cnt_lin = 1
dialog_history = []
turn_usr = ''
turn_sys = ''
turn_idx = 0
... |
def test_fit(X, model, model2):
model.fit(X)
assert_array_almost_equal(model.factors[0].probs, [[0.4545, 0.5455]], 4)
assert_array_almost_equal(model.factors[1].probs, [[[0.0909, 0.1818, 0.0], [0.0909, 0.0, 0.0909]], [[0.0, 0.1818, 0.0909], [0.0909, 0.0909, 0.0909]]], 4)
assert_array_almost_equal(model.... |
_torch
class SqueezeBertModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = ((SqueezeBertModel, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification) if is_torch_available()... |
(beta=floats(1.0, 50.0), threshold=integers(20, 50))
def test_creation_from_vector(beta, threshold):
shape = (3, 1, 5)
z = torch.tensor(np.random.rand(*shape))
w_delta = torch.tensor(np.random.rand(*shape))
v = torch.cat((z, w_delta), dim=(- 1))
box = MinDeltaBoxTensor.from_vector(v, beta=beta, thre... |
class AutoModelForTokenClassification(nn.Module):
def __init__(self, args, Model, config, num_labels=2):
super(AutoModelForTokenClassification, self).__init__()
self.num_labels = num_labels
self.bert = Model
self.config = config
self.dropout = nn.Dropout(args.drop_ratio)
... |
class LiltForQuestionAnswering(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def predict_fn(image):
loaded_model = load_model(model_id='1y6tseN0194T6d-4iIh5wo7RL9ttQERe0')
(loaded_image, original_shape) = image_process(image)
(heatmap_a, heatmap_b, preds) = make_gradcam_heatmap(loaded_image, loaded_model)
int_label = tf.argmax(preds, axis=(- 1)).numpy()[0]
str_label = str_la... |
def test_pr3635_diamond_e():
o = m.MVE()
assert (o.b == 1)
assert (o.c == 2)
assert (o.d0 == 3)
assert (o.d1 == 4)
assert (o.e == 5)
assert (o.get_b_b() == 1)
assert (o.get_c_b() == 1)
assert (o.get_d0_b() == 1)
assert (o.get_d1_b() == 1)
assert (o.get_e_b() == 1)
assert ... |
class CTRLLMHeadModel():
def __init__(self, *args, **kwargs):
requires_pytorch(self)
def from_pretrained(self, *args, **kwargs):
requires_pytorch(self) |
.parametrize('naive_dice', [True, False])
def test_dice_loss(naive_dice):
loss_class = DiceLoss
pred = torch.rand((10, 4, 4))
target = torch.rand((10, 4, 4))
weight = torch.rand(10)
loss = loss_class(naive_dice=naive_dice)(pred, target)
assert isinstance(loss, torch.Tensor)
loss = loss_class... |
class DictKeepInputLabelIdx(DictKeepKeys):
def __init__(self):
super().__init__(['input', 'label', 'idx', 'aug_index']) |
def main():
seen = tf.placeholder(tf.float32, shape=[None, 1024])
unseen = tf.placeholder(tf.float32, shape=[None, 1024])
(mmd, n) = rbf_mmd2(seen, unseen)
(mmd, n) = mix_rbf_mmd2(seen, unseen, gammas=[10.0, 1.0, 0.1, 0.01, 0.001])
source_numpy = np.load(sys.argv[1])
target_numpy = np.load(sys.a... |
class TestCenterRegionAssigner(TestCase):
def test_center_region_assigner(self):
center_region_assigner = CenterRegionAssigner(pos_scale=0.2, neg_scale=0.2, min_pos_iof=0.01)
priors = torch.FloatTensor([[0, 0, 10, 10], [10, 10, 20, 20], [5, 5, 15, 15], [32, 32, 38, 42]])
gt_bboxes = torch.Fl... |
def seresnet26_cub(num_classes=200, **kwargs):
return get_seresnet(num_classes=num_classes, blocks=26, bottleneck=False, model_name='seresnet26_cub', **kwargs) |
def generator_loss(fake):
loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=tf.ones_like(fake), logits=fake))
return loss |
def resnet50_fc512_ms12_a0d3(num_classes, loss='softmax', pretrained=True, **kwargs):
model = ResNet(num_classes=num_classes, loss=loss, block=Bottleneck, layers=[3, 4, 6, 3], last_stride=1, fc_dims=[512], dropout_p=None, mixstyle_layers=['layer1', 'layer2'], mixstyle_alpha=0.3, **kwargs)
if pretrained:
... |
class Decoder(nn.Module):
def __init__(self, num_points_per_patch=1024):
super(Decoder, self).__init__()
self.m = num_points_per_patch
self.meshgrid = [[(- 0.3), 0.3, 32], [(- 0.3), 0.3, 32]]
self.mlp1 = nn.Sequential(nn.Linear(514, 256), nn.ReLU(), nn.Linear(256, 128), nn.ReLU(), nn... |
def string_sub(args):
params = functionParams(args, ('s', 'i', 'j'))
s = params.get('s', '')
i = int((params.get('i', 1) or 1))
j = int((params.get('j', (- 1)) or (- 1)))
if (i > 0):
i -= 1
if (j < 0):
j += 1
if (j == 0):
j = len(s)
return s[i:j] |
class TFBaseModelOutputWithPoolingAndCrossAttentions(ModelOutput):
last_hidden_state: tf.Tensor = None
pooler_output: tf.Tensor = None
past_key_values: Optional[List[tf.Tensor]] = None
hidden_states: Optional[Tuple[tf.Tensor]] = None
attentions: Optional[Tuple[tf.Tensor]] = None
cross_attentions... |
class CrossAttention(nn.Module):
def __init__(self, dim, heads=8, dim_head=64, dropout=0.0):
super().__init__()
inner_dim = (dim_head * heads)
project_out = (not ((heads == 1) and (dim_head == dim)))
self.heads = heads
self.scale = (dim_head ** (- 0.5))
self.attend = ... |
def plot_gif(v):
instr_id = v['instr_id']
gt = e.gt[int(instr_id.split('_')[0])]
graph = e.graphs[gt['scan']]
node_pos = nx.get_node_attributes(graph, 'position')
for (k, vv) in node_pos.items():
node_pos[k] = vv[:(- 1)]
rel_pos = [node_pos[vp] for vp in v['path']]
rel_x = [r[0] for ... |
def load(model, optimizer, filename):
try:
dump = torch.load(filename)
except BaseException:
print('[ Fail: model loading failed. ]')
if (model is not None):
model.load_state_dict(dump['model'])
if (optimizer is not None):
optimizer.load_state_dict(dump['optimizer'])
... |
class ProbabilisticLayer(Random):
def __init__(self, **kwargs):
super(ProbabilisticLayer, self).__init__(**kwargs)
def sample_expected(self, Y):
raise NotImplemented
def sample(self, Y):
raise NotImplemented
def log_prob(self, X, Y):
raise NotImplemented |
class T5TokenizerFast():
def __init__(self, *args, **kwargs):
requires_tokenizers(self)
def from_pretrained(self, *args, **kwargs):
requires_tokenizers(self) |
def forward_backward_benchmark(net, run_segment, device, input_size=(1, 3, 224, 224), repeat=100, min_repeat=5):
assert (repeat > min_repeat)
net.train()
(regular_start_memory, regular_end_memory, regular_peak_memory, regular_avg_time) = forward_backward(net, device, input_size, repeat, min_repeat)
(che... |
def config_class_to_model_type(config):
for (key, cls) in CONFIG_MAPPING_NAMES.items():
if (cls == config):
return key
return None |
def get_accuracy(n):
return (float((n[0][0] + n[1][1])) / (((n[0][0] + n[1][1]) + n[0][1]) + n[1][0])) |
class ConvLSTM(nn.Module):
def __init__(self, input_channels, hidden_channels, kernel_size, step=1, effective_step=[1], bias=True):
super(ConvLSTM, self).__init__()
self.input_channels = ([input_channels] + hidden_channels)
self.hidden_channels = hidden_channels
self.kernel_size = ke... |
_incremental_state
class FConvDecoder(FairseqDecoder):
def __init__(self, dictionary, embed_dim=512, out_embed_dim=256, max_positions=1024, convolutions=(((512, 3),) * 8), attention=True, dropout=0.1, selfattention=False, attention_nheads=1, selfattention_nheads=1, project_input=False, gated_attention=False, downsa... |
def print_headless_mentions(out, parses, heads, mentions):
for mention in mentions:
(sentence, start, end) = mention
if ((end - start) > 1):
node = parses[sentence].get_nodes('lowest', start, end)
if (node is None):
print(mention_text(text, mention), file=out)... |
class Mastering_Effects_Manipulator():
def __init__(self, block_size=(2 ** 17)):
self.block_size = block_size
self.sample_rate = 44100
self.processors_pre = ProcessorList(block_size=self.block_size, sample_rate=self.sample_rate)
self.processors_pre.add(Gain(gain=(- 8.0), block_size=s... |
class HRateHyperprior(HRateEstimator):
def __init__(self, z_dim, factor_dim=5, side_z_dim=None, is_pred_mean=True, **kwargs):
super().__init__(z_dim, **kwargs)
if (side_z_dim is None):
side_z_dim = max(10, (self.z_dim // factor_dim))
self.side_z_dim = side_z_dim
self.is_p... |
def write_text(path: Path, text: str, encoding=None):
with path.open(mode='w', encoding=encoding) as f:
f.write(text) |
class ModuleManager():
def __init__(self, name=None):
self._modules_dict = dict()
self._name = name
def __len__(self):
return len(self._modules_dict)
def __repr__(self):
name_str = (self._name if self._name else self.__class__.__name__)
return '{}:{}'.format(name_str,... |
class MinibatchRlEval(MinibatchRlBase):
_eval = True
def train(self):
n_itr = self.startup()
with logger.prefix(f'itr #0 '):
(eval_traj_infos, eval_time) = self.evaluate_agent(0)
self.log_diagnostics(0, eval_traj_infos, eval_time)
for itr in range(n_itr):
... |
class DictDataset(Dataset):
def __init__(self, **kwargs):
self.data = kwargs
self.data_len = None
for v in kwargs.values():
if (self.data_len is None):
self.data_len = v.size(0)
else:
assert (self.data_len == v.size(0))
def __getite... |
def rbf_kernel(x, y, sigma):
return np.exp(((- (np.linalg.norm((x - y)) ** 2)) / (2 * (sigma ** 2)))) |
class NPQueue(object):
def __init__(self, initial_capacity: int=100, dtype=np.int64):
self._arr = np.zeros(initial_capacity, dtype=dtype)
self._start_idx = 0
self._end_idx = 0
def _reset(self):
current_size = (self._end_idx - self._start_idx)
new_arr = np.zeros((2 * curre... |
def parse_requirements(filename):
lineiter = (line.strip() for line in open(filename))
return [line for line in lineiter if (line and (not line.startswith('#')))] |
def benchmark(exec_func=None, *, plot=True, auto=False):
if (exec_func is None):
return functools.partial(benchmark, plot=plot, auto=auto)
(exec_func)
def wrapper_func():
global _plot, _log_dir, _auto
_plot = ({} if plot else None)
plt.close('all')
_log_dir = _get_log... |
_module()
class Contrast(object):
def __init__(self, magnitude, prob=0.5, random_negative_prob=0.5):
assert isinstance(magnitude, (int, float)), f'The magnitude type must be int or float, but got {type(magnitude)} instead.'
assert (0 <= prob <= 1.0), f'The prob should be in range [0,1], got {prob} i... |
class StaticCombiner(Combiner):
def __init__(self, database: Database, top_k: int, mixing_weight: float, kernel: Kernel, bandwidth: float) -> None:
super(StaticCombiner, self).__init__()
self.database = database
self.top_k = top_k
self.mixing_weight = mixing_weight
self.kerne... |
class GraphConvolution(nn.Module):
def __init__(self, d_model):
super().__init__()
self.d_model = d_model
self.num_relations = 40
self.fc_dir_weight = clones(nn.Linear(d_model, d_model, bias=False), 3)
self.fc_dir_bias = [nn.Parameter(torch.zeros(d_model)) for _ in range(((se... |
def avg_sq_ch_mean(model, input, output):
return torch.mean((output.mean(axis=[0, 2, 3]) ** 2)).item() |
def worker_init_rand(worker_id):
random.seed(torch.initial_seed())
np.random.seed((torch.initial_seed() % (2 ** 32))) |
class PyramidNet(nn.Module):
def __init__(self, dataset, depth, alpha, num_classes, bottleneck=False):
super(PyramidNet, self).__init__()
self.dataset = dataset
if self.dataset.startswith('cifar'):
self.inplanes = 16
if (bottleneck == True):
n = int(((... |
def load_args():
parser = argparse.ArgumentParser(description='Transformer baseline', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--seed', type=int, default=0, help='random seed')
parser.add_argument('--dataset', type=str, default='NCI1', help='name of dataset')
parser.a... |
def attention_from_original_checkpoint(model, diffuser_attention_prefix, original_attention_prefix):
attention = {}
attention.update({f'{diffuser_attention_prefix}.attention.query.weight': model[f'{original_attention_prefix}.self.query.weight']})
attention.update({f'{diffuser_attention_prefix}.attention.que... |
class AdamW(Optimizer):
def __init__(self, params, lr=0.001, betas=(0.9, 0.999), eps=1e-08, weight_decay=0, warmup=0):
if (not (0.0 <= lr)):
raise ValueError('Invalid learning rate: {}'.format(lr))
if (not (0.0 <= eps)):
raise ValueError('Invalid epsilon value: {}'.format(eps... |
def cifar10_loader(args):
args.num_classes = 10
normalize = transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.201))
transform_train = transforms.Compose([transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), normalize])
transform_test = transform... |
def train(model, dataloader, optimizer, criterion, epoch_number, max_gradient_norm):
model.train()
device = model.device
epoch_start = time.time()
batch_time_avg = 0.0
running_loss = 0.0
correct_preds = 0
tqdm_batch_iterator = tqdm(dataloader)
for (batch_index, batch) in enumerate(tqdm_b... |
class DictConfig():
def __init__(self):
pass
def to_dict(self):
return {k: v for (k, v) in vars(self).items() if ((k not in ('self', 'model_fn', 'loss_fn', 'build_model', 'is_multimodal')) and (not k.startswith('_')))} |
def _strip_snodes(base_graph: ag.Graph) -> ag.Graph:
g = base_graph.copy(nlp=nlp.parse)
g.strip_snodes()
return g |
def main():
patch = make_patch()
copyfile('jheppub.sty', 'jheppub.sty.bak')
with open('jheppub.sty.bak') as read_file, open('jheppub.sty', 'w+') as write_file:
for line in read_file:
write_file.write(line.replace('\\newcommand\\{\\renewcommand\\{}\\renewcommand\\{}}', patch)) |
def main():
args = parse_args()
send_example_telemetry('run_summarization_no_trainer', args)
accelerator_log_kwargs = {}
if args.with_tracking:
accelerator_log_kwargs['log_with'] = args.report_to
accelerator_log_kwargs['logging_dir'] = args.output_dir
accelerator = Accelerator(gradie... |
class FairseqDecoder(nn.Module):
def __init__(self, dictionary):
super().__init__()
self.dictionary = dictionary
self.onnx_trace = False
self.adaptive_softmax = None
def forward(self, prev_output_tokens, encoder_out=None, **kwargs):
(x, extra) = self.extract_features(prev... |
class Trainer():
def __init__(self, args, loader, my_model, my_loss, ckp):
self.args = args
self.scale = args.scale
self.quality = args.quality
self.ckp = ckp
self.loader_train = loader.loader_train
self.loader_test = loader.loader_test
self.model = my_model
... |
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, prob=None, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(p... |
def fix_ratio(image, cfg):
(h, w, c) = image.shape
if (h >= w):
ratio = ((h * 1.0) / w)
h_ = cfg.long_side
w_ = round((h_ / ratio))
else:
ratio = ((w * 1.0) / h)
w_ = cfg.long_side
h_ = round((w_ / ratio))
image = cv2.resize(image, dsize=(w_, h_), interpol... |
def _tokenize_fn(strings: Sequence[str], tokenizer: transformers.PreTrainedTokenizer) -> Dict:
tokenized_list = [tokenizer(text, return_tensors='pt', padding='longest', max_length=tokenizer.model_max_length, truncation=True) for text in strings]
input_ids = labels = [tokenized.input_ids[0] for tokenized in toke... |
class _CAM():
def __init__(self, model: nn.Module, target_layer: Optional[str]=None, input_shape: Tuple[(int, ...)]=(3, 224, 224)) -> None:
self.assert_model(model)
self.submodule_dict = dict(model.named_modules())
if (target_layer is None):
target_layer = locate_candidate_layer(... |
def f1_eval(logits, features):
def getpred(result, T1=0.5, T2=0.4):
ret = []
for i in range(len(result)):
r = []
(maxl, maxj) = ((- 1), (- 1))
for j in range(len(result[i])):
if (result[i][j] > T1):
r += [j]
if (... |
class IFFT2Op(gof.Op):
__props__ = ()
def output_type(self, inp):
return T.TensorType(inp.dtype, broadcastable=([False] * inp.type.ndim))
def make_node(self, a, s=None):
a = T.as_tensor_variable(a)
if (a.ndim < 4):
raise TypeError((('%s: input must have dimension >= 4, w... |
def collate(samples, pad_idx, eos_idx, vocab, left_pad_source=False, left_pad_target=False, input_feeding=True):
assert input_feeding
if (len(samples) == 0):
return {}
def merge(key, left_pad, move_eos_to_beginning=False):
return data_utils.collate_tokens([s[key] for s in samples], pad_idx, ... |
def make_pooler(cfg, head_name):
resolution = cfg.MODEL[head_name].POOLER_RESOLUTION
scales = cfg.MODEL[head_name].POOLER_SCALES
sampling_ratio = cfg.MODEL[head_name].POOLER_SAMPLING_RATIO
pooler = Pooler(output_size=(resolution, resolution), scales=scales, sampling_ratio=sampling_ratio)
return pool... |
(reuse_venv=True)
def build(session: nox.Session) -> None:
session.install('build')
session.log('Building normal files')
session.run('python', '-m', 'build', *session.posargs)
session.log('Building pybind11-global files (PYBIND11_GLOBAL_SDIST=1)')
session.run('python', '-m', 'build', *session.posarg... |
def check_all_auto_object_names_being_defined():
check_missing_backends()
failures = []
mappings_to_check = {'TOKENIZER_MAPPING_NAMES': TOKENIZER_MAPPING_NAMES, 'IMAGE_PROCESSOR_MAPPING_NAMES': IMAGE_PROCESSOR_MAPPING_NAMES, 'FEATURE_EXTRACTOR_MAPPING_NAMES': FEATURE_EXTRACTOR_MAPPING_NAMES, 'PROCESSOR_MAPP... |
class EncoderText(nn.Module):
def __init__(self, vocab_size, word_dim, embed_size, num_layers, use_abs=False):
super(EncoderText, self).__init__()
self.use_abs = use_abs
self.embed_size = embed_size
self.embed = nn.Embedding(vocab_size, word_dim)
self.rnn = nn.GRU(word_dim, e... |
class TrainingArguments(transformers.TrainingArguments):
cache_dir: Optional[str] = field(default=None)
optim: str = field(default='adamw_torch')
remove_unused_columns: bool = field(default=False)
freeze_mm_mlp_adapter: bool = field(default=False)
force_fsdp: bool = field(default=False)
model_ma... |
def main(args):
import glob
import random
import numpy as np
import json
import itertools
with open(args.input_path, 'r') as json_file:
json_list = list(json_file)
fixed_list = [[int(item) for item in one.split()] for one in args.position_list.split(',')]
global_designed_chain_li... |
class PhraseTree(object):
puncs = [',', '.', ':', '``', "''", 'PU']
def __init__(self, symbol=None, children=[], sentence=[], leaf=None):
self.symbol = symbol
self.children = children
self.sentence = sentence
self.leaf = leaf
self._str = None
def __str__(self):
... |
class isInContourV3_Hard(Contour_Checking_fn):
def __init__(self, contour, patch_size, center_shift=0.5):
self.cont = contour
self.patch_size = patch_size
self.shift = int(((patch_size // 2) * center_shift))
def __call__(self, pt):
center = ((pt[0] + (self.patch_size // 2)), (pt[... |
def build_stereo_dataset(cfg, type):
if (type not in cfg.data):
return None
data_root = cfg.data[type].data_root
data_type = cfg.data[type].type
annFile = cfg.data[type].annfile
is_train = (True if (type == 'train') else False)
transforms = build_transforms(cfg, type, is_train=is_train)
... |
class HyperParams():
def __init__(self):
pass
def get_uniwarp_config(self, argv):
config = {}
config['optimizer:num_epochs'] = 1000000
config['model:num_batch_pairs'] = 100
config['uniwarp:length'] = 1024
config['uniwarp:rnn_encoder_layers'] = [256, 128, 64]
... |
def reorder_tsv_keys(in_tsv_file, ordered_keys, out_tsv_file):
tsv = TSVFile(in_tsv_file)
logging.info('loading keys in input')
keys = [tsv.seek_first_column(i) for i in tqdm(range(len(tsv)), mininterval=2)]
key_to_idx = {key: i for (i, key) in enumerate(keys)}
def gen_rows():
logging.info('... |
_registry(operator_type='_FusedMatMul')
class _FusedMatMul(Operator):
def __init__(self):
super().__init__()
def set_attr(self, framework, node):
if (framework == 'tensorflow'):
transpose_a = node.attr['transpose_a'].b
transpose_b = node.attr['transpose_b'].b
... |
def run_validating():
if (not os.path.exists(model_save_dir)):
os.makedirs(model_save_dir)
model_filename = './mfb_dis_ucf24.model'
(tower_grads, tower_ac) = ([], [])
(tower_losses, tower_ac_losses, tower_wd_losses) = ([], [], [])
global_step = tf.get_variable('global_step', [], initializer=... |
class KvVariableSaveable(BaseSaverBuilder.SaveableObject):
def __init__(self, var, name):
self._var = var
tensors_dict = var.export(name=name)
self._key_dtype = var.key_dtype
self._value_dtype = var.dtype
self._embedding_dim = var.shape.as_list()[1]
self._is_loading_f... |
def test_glorot_normal_c01b_4d_only():
from lasagne.init import GlorotNormal
with pytest.raises(RuntimeError):
GlorotNormal(c01b=True).sample((100,))
with pytest.raises(RuntimeError):
GlorotNormal(c01b=True).sample((100, 100))
with pytest.raises(RuntimeError):
GlorotNormal(c01b=T... |
def write_hyperparameters_json(hyperparams: dict, PATHS: dict) -> None:
doc_location = os.path.join(PATHS.get('model'), 'hyperparameters.json')
with open(doc_location, 'w', encoding='utf-8') as target:
json.dump(hyperparams, target, ensure_ascii=False, indent=4) |
def convert_PDF_to_plaintext(fpath, keep_layout=False):
if (not os.path.isfile(CFG_PATH_PDFTOTEXT)):
raise IOError('Missing pdftotext executable')
if keep_layout:
layout_option = '-layout'
else:
layout_option = '-raw'
doclines = []
p_break_in_line = re.compile('^\\s*\\f(.+)$'... |
def avg_prec(correct_duplicates: List, retrieved_duplicates: List) -> float:
if ((len(retrieved_duplicates) == 0) and (len(correct_duplicates) == 0)):
return 1.0
if ((not len(retrieved_duplicates)) or (not len(correct_duplicates))):
return 0.0
count_real_correct = len(correct_duplicates)
... |
def _mobilenet_v3_model(arch: str, inverted_residual_setting: List[InvertedResidualConfig], last_channel: int, pretrained: bool, progress: bool, quantize: bool, **kwargs: Any):
model = QuantizableMobileNetV3(inverted_residual_setting, last_channel, block=QuantizableInvertedResidual, **kwargs)
_replace_relu(mode... |
def main():
print(window_width, window_height)
top_widgets = []
left_widgets = []
for i in range(num_top):
top_widgets.append(ORCWidget(('HF_' + str(i)), [top_button_width_min, top_button_width_pref, top_button_width_max, top_button_height_min, top_button_height_pref, top_button_height_max]))
... |
class JobLibProvider(ComputeProvider):
def __init__(self, n_jobs=(- 1)):
self.n_jobs = n_jobs
def parallel(self, compute_fn, compute_args_iter):
results = Parallel(n_jobs=self.n_jobs)((delayed(compute_fn)(*args) for args in compute_args_iter))
return results |
def topic_recommendation(json):
json = json.get('recommendations')
if (not json):
return ('No recommendations submitted.', 400)
if (len(json) > app.config['max_users_per_recommendation']):
return (('Requests must not contain more than %s users.' % app.config['max_users_per_recommendation']),... |
def test_bin_pack_step__jit(bin_pack: BinPack) -> None:
chex.clear_trace_counter()
step_fn = jax.jit(chex.assert_max_traces(bin_pack.step, n=1))
key = jax.random.PRNGKey(0)
(state, timestep) = bin_pack.reset(key)
action = bin_pack.action_spec().generate_value()
_ = step_fn(state, action)
(st... |
def get_outputscale(kernel):
if isinstance(kernel, gpytorch.kernels.ScaleKernel):
return kernel.outputscale
else:
return None |
def EfficientNetV2B3(include_top=False, weights='imagenet', input_tensor=None, input_shape=None, pooling=None, classes=1000, stride_size=2, classifier_activation='softmax', include_preprocessing=True, **kwargs):
return EfficientNetV2(width_coefficient=1.2, depth_coefficient=1.4, default_size=300, model_name='effici... |
def aquila_attention_forward(self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor]=None, position_ids: Optional[torch.LongTensor]=None, past_key_value: Optional[Tuple[torch.Tensor]]=None, output_attentions: bool=False, use_cache: bool=False) -> Tuple[(torch.Tensor, Optional[torch.Tensor], Optional[T... |
_registry(operator_type='ListConstruct')
class ListConstruct(Operator):
def __init__(self):
super().__init__() |
class MinorityCoalescer(AutotabularPreprocessingAlgorithm):
def __init__(self, minimum_fraction: float=0.01, random_state: Optional[np.random.RandomState]=None):
self.minimum_fraction = minimum_fraction
def fit(self, X: PIPELINE_DATA_DTYPE, y: Optional[PIPELINE_DATA_DTYPE]=None) -> 'MinorityCoalescer':
... |
_torch
class CTRLModelTest(ModelTesterMixin, unittest.TestCase):
all_model_classes = ((CTRLModel, CTRLLMHeadModel) if is_torch_available() else ())
all_generative_model_classes = ((CTRLLMHeadModel,) if is_torch_available() else ())
test_pruning = False
test_torchscript = False
test_resize_embeddings... |
(version='2.0')
def initial_tuning_cfg_with_quant_mode(op_name_type, quant_mode, tuning_space: TuningSpace) -> OpTuningConfig:
internal_pattern = pattern_to_internal(quant_mode)
full_path = {'activation': None, 'weight': None}
(full_path['activation'], full_path['weight']) = pattern_to_path(internal_pattern... |
def test_interpolation_potential_dens():
rzpot = potential.interpRZPotential(RZPot=potential.MWPotential, rgrid=(0.01, 2.0, 201), zgrid=(0.0, 0.2, 201), logR=False, interpDens=True, zsym=True)
rs = numpy.linspace(0.01, 2.0, 21)
zs = numpy.linspace((- 0.2), 0.2, 41)
for r in rs:
for z in zs:
... |
def profile_fvcore(model, input_size=(3, 224, 224), input_dtype=torch.float32, max_depth=4, batch_size=1, detailed=False, force_cpu=False):
if force_cpu:
model = model.to('cpu')
(device, dtype) = (next(model.parameters()).device, next(model.parameters()).dtype)
example_input = torch.ones(((batch_siz... |
def optimize_qparams_matmul(layer, cached_inps, cached_outs, test_inp, test_out, batch_size=100):
print('\nOptimize quantization params')
inp1_range_orig = layer.quantize_input1.running_range.data.clone()
inp1_zp_orig = layer.quantize_input1.running_zero_point.data.clone()
inp2_range_orig = layer.quanti... |
class ConstantTimeGenerator(InterArrivalTimeGenerator):
def __init__(self, step_duration: float) -> None:
self.step_duration: float = step_duration
def next(self) -> float:
return self.step_duration
def mean(self) -> float:
return self.step_duration |
def main(args):
components = list(make_version_tuple())
if args.bump:
components[(- 1)] += 1
version = '.'.join((str(c) for c in components))
if args.tag:
subprocess.check_output(['git', 'tag', version])
for package_dot_json_loc in ['./frontend/labextension', './frontend/nbextension'... |
class PrivilegeEscalation(Action):
def __init__(self, name, target, cost, access, process=None, os=None, prob=1.0, req_access=AccessLevel.USER, **kwargs):
super().__init__(name=name, target=target, cost=cost, prob=prob, req_access=req_access)
self.access = access
self.os = os
self.pr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.