code stringlengths 101 5.91M |
|---|
def get_shard_range(tot, nshard, rank):
assert ((rank < nshard) and (rank >= 0)), f'invaid rank/nshard {rank}/{nshard}'
start = round(((tot / nshard) * rank))
end = round(((tot / nshard) * (rank + 1)))
assert (start < end), f'start={start}, end={end}'
logger.info(f'rank {rank} of {nshard}, process {... |
def logsumexp_2d(tensor):
tensor_flatten = tensor.view(tensor.size(0), tensor.size(1), (- 1))
(s, _) = torch.max(tensor_flatten, dim=2, keepdim=True)
outputs = (s + (tensor_flatten - s).exp().sum(dim=2, keepdim=True).log())
return outputs |
class ResNetBottleNeckLayer(nn.Module):
def __init__(self, in_channels: int, out_channels: int, stride: int=1, activation: str='relu', reduction: int=4):
super().__init__()
should_apply_shortcut = ((in_channels != out_channels) or (stride != 1))
reduces_channels = (out_channels // reduction)... |
def bidirectional_rnn(cell_fw, cell_bw, inputs, initial_state_fw=None, initial_state_bw=None, dtype=None, sequence_length=None, scope=None):
if (not isinstance(cell_fw, BaseCell)):
raise TypeError('cell_fw must be an instance of RNNCell')
if (not isinstance(cell_bw, BaseCell)):
raise TypeError('... |
class _BasePRank(BaseEstimator):
def score(self, X, y):
y_pred = self.predict(X)
return np.mean(np.abs((y - y_pred)))
def classes_(self):
return self._label_encoder.classes_ |
def test_BBPSSW_phi_plus_psi_plus():
counter = 0
for i in range(100):
(tl, kept1, kept2, meas1, meas2, ep1, ep2) = create_scenario(phi_plus, psi_plus, i)
assert (kept1.entangled_memory == kept2.entangled_memory == {'node_id': None, 'memo_id': None})
assert (ep1.meas_res != ep2.meas_res)
... |
def unscaled_dropout(inputs, keep_prob, noise_shape=None):
if isinstance(noise_shape, (tuple, list)):
noise_shape = tf.stack(noise_shape)
return (tf.nn.dropout(inputs, keep_prob=keep_prob, noise_shape=noise_shape) * keep_prob) |
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None, use_se=True, aa_layer=None):
super(BasicBlock, self).__init__()
if (stride == 1):
self.conv1 = conv2d_iabn(inplanes, planes, stride=1, act_param=0.001)
elif (aa_layer is... |
class DiscriminatorMLP(nn.Module):
def __init__(self, input_dim):
super(DiscriminatorMLP, self).__init__()
self.model = nn.Sequential(nn.Linear((args.n_timesteps * input_dim), 1024), nn.LeakyReLU(0.2, inplace=True), nn.Linear(1024, 512), nn.LeakyReLU(0.2, inplace=True), nn.Linear(512, 256), nn.Leaky... |
class SawyerDoorCloseEnvV2(SawyerDoorEnvV2):
def __init__(self):
goal_low = (0.2, 0.65, 0.1499)
goal_high = (0.3, 0.75, 0.1501)
super().__init__()
self.init_config = {'obj_init_angle': 0.3, 'obj_init_pos': np.array([0.1, 0.95, 0.15], dtype=np.float32), 'hand_init_pos': np.array([0, 0... |
.parametrize('context, action, reward, pscore, description', invalid_input_of_nn_policy_learner_fit)
def test_nn_policy_learner_fit_using_invalid_inputs(context, action, reward, pscore, description):
with pytest.raises(ValueError, match=f'{description}*'):
dim_context = 2
pg_method = 'dpg'
l... |
class Swish_SENet(nn.Module):
def __init__(self, block, num_blocks, num_classes=100):
super(Swish_SENet, self).__init__()
self.in_planes = 64
self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.layer1 = self._make_l... |
def have_compatible_glibc(required_major, minimum_minor):
version_str = glibc_version_string()
if (version_str is None):
return False
return check_glibc_version(version_str, required_major, minimum_minor) |
class A083216(RecurrenceSequence2):
def __init__(self):
SloaneSequence.__init__(self, offset=0)
self._b = []
self._params = (, , 1, 1)
self._precompute(2)
def _repr_(self):
return 'Second-order linear recurrence sequence with a(n) = a(n-1) + a(n-2).' |
def plot_tensor(tensor):
plt.style.use('default')
(fig, ax) = plt.subplots(figsize=(12, 3))
im = ax.imshow(tensor, aspect='auto', origin='lower', interpolation='none')
plt.colorbar(im, ax=ax)
plt.tight_layout()
fig.canvas.draw()
data = save_figure_to_numpy(fig)
plt.close()
return dat... |
.parametrize('cv', [5, 'split'])
def test_check_cv_same_split_no_random_state(cv: BaseCrossValidator) -> None:
cv = check_cv(cv, random_state=None)
(train_indices_1, train_indices_2) = ([], [])
for (train_index, _) in cv.split(X):
train_indices_1.append(train_index)
for (train_index, _) in cv.sp... |
class Speaker(nn.Module):
def __init__(self, speaker_dim=20):
super().__init__()
self.embeds = nn.Sequential(nn.Embedding(3, speaker_dim, padding_idx=0), nn.Dropout(0.2))
def forward(self, speaker_labels):
return self.embeds(to_cuda(torch.tensor(speaker_labels))) |
def binary_eps_search(eps_lower_bound, eps_upper_bound, bab_function, quantization=0.001, mode='LB'):
assert (mode in ['LB', 'UB'])
print(f'Starting epsilon bounds: LB: {eps_lower_bound}, UB: {eps_upper_bound}')
while ((eps_upper_bound - eps_lower_bound) > quantization):
c_epsilon = ((eps_upper_boun... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--task_name', default=None, type=str, required=True, help='The name of the task to train.')
parser.add_argument('--cache_dir', default='', type=str, help='Where do you want to store the pre-trained models downloaded from s3')
parser.add... |
class TokenizerSettings():
query_token_id: str = DefaultVal('[unused0]')
doc_token_id: str = DefaultVal('[unused1]')
query_token: str = DefaultVal('[Q]')
doc_token: str = DefaultVal('[D]') |
def add_arguments_lipschitz(parser):
parser.add_argument('--lip', action='store_true', help='1-lipschitz network')
parser.add_argument('--global-lip', action='store_true') |
class BiFpn():
def __init__(self, config, feature_info, name):
self.num_levels = config.num_levels
norm_layer = (config.norm_layer or tf.keras.layers.BatchNormalization)
norm_kwargs = {**config.norm_kwargs}
norm_kwargs['epsilon'] = norm_kwargs.pop('eps', 0.001)
if config.norm... |
class SKUp(nn.Module):
def __init__(self, kernel_size, padding, bias, reduction, in_channels, out_channels, bilinear=True):
super().__init__()
if bilinear:
self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
else:
self.up = nn.ConvTranspose2d((i... |
def test_recall_macro_2d_list():
y_true = [[1, 2], [1, 2]]
y_pred = [[1, 5, 6, 7], [1, 2, 3, 4]]
assert (0.75 == recall(y_true, y_pred, 'macro'))
assert (0.375 == recall(y_pred, y_true, 'macro')) |
def getcolumns(stream):
pipe = Pipeline()
pipe.append(ColumnsSelect())
return pipe(stream) |
class _Root():
def parent(n=1):
return _root_fb.root.parent(n)
def _loop_range():
return _root_fb.root._loop_range()
def _get_children():
return _root_fb.root._get_children()
def deactivate_all():
warning("'ti.root.deactivate_all()' would deactivate all finalized snodes."... |
class DistributedGivenIterationSampler(Sampler):
def __init__(self, dataset, total_iter, batch_size, world_size=None, rank=None, last_iter=(- 1)):
if (world_size is None):
world_size = dist.get_world_size()
if (rank is None):
rank = dist.get_rank()
assert (rank < worl... |
class DataBundle():
def __init__(self, vocabs: dict=None, datasets: dict=None):
self.vocabs = (vocabs or {})
self.datasets = (datasets or {})
def set_vocab(self, vocab, field_name):
assert isinstance(vocab, Vocabulary), 'Only fastNLP.Vocabulary supports.'
self.vocabs[field_name] ... |
def binary_loss_array(recon_x, x, z_mu, z_var, z_0, z_k, ldj, beta=1.0):
batch_size = x.size(0)
if (len(ldj.size()) > 1):
ldj = ldj.view(ldj.size(0), (- 1)).sum((- 1))
bce = (- log_bernoulli(x.view(batch_size, (- 1)), recon_x.view(batch_size, (- 1)), dim=1))
log_p_zk = log_normal_standard(z_k, d... |
def main_canonical_360(opt):
nerf = instant_nsr.NeRFNetwork()
nerf.load_state_dict(torch.load(opt.weights_path))
(center, up) = (np.array([0.0, 0.0, 0.0]), np.array([0.0, 1.0, 0.0]))
(body_poses, _) = render_utils.default_360_path(center, up, CANONICAL_CAMERA_DIST_VAL, opt.trajectory_resolution)
hea... |
def indent_level(code, level=0):
rtn_code = ''
for i in range(level):
rtn_code += ' '
rtn_code += code
return rtn_code |
def build_model(input_shape, n_cl_out=1, use_upsampling=False, dropout=0.2, print_summary=True, seed=816, depth=5, dropout_at=(2, 3), initial_filters=16, batch_norm=True, **kwargs):
if ((input_shape[0] % (2 ** depth)) > 0):
raise ValueError(f'Crop dimension must be a multiple of 2^(depth of U-Net) = {(2 ** ... |
def __scale_width(img, target_width, crop_width, method=Image.BICUBIC):
(ow, oh) = img.size
if ((ow == target_width) and (oh >= crop_width)):
return img
w = target_width
h = int(((target_width * oh) / ow))
return img.resize((w, h), method) |
def check(args):
_deck = deck.copy()
res = []
np.random.shuffle(_deck)
landlord = _deck[:17]
landlord.sort()
other = _deck[17:]
dic = {tuple(landlord): []}
for _ in range((10 * args.games)):
np.random.shuffle(other)
card_play_data = {'landlord': (landlord + other[:3]), 'l... |
class InputExample(object):
def __init__(self, id_, text, span, labels):
self.id = id_
self.text = text
self.span = span
self.labels = labels |
((device_cc() < 80), 'Device compute capability is insufficient for SM80 tests.')
class GemmF32nF32nF32nTensorOpF32Sm80(unittest.TestCase):
def test_SM80_Device_Gemm_f32t_f32n_f32t_tensor_op_bf16_f32_128x128x32_64x64x32(self):
math_inst = MathInstruction(instruction_shape=[16, 8, 8], element_a=cutlass.float... |
def warning(position, message, level=0):
if (level < LEVEL):
return
if (Options.warning_errors and position):
return error(position, message)
warn = CompileWarning(position, message)
line = ('warning: %s\n' % warn)
if listing_file:
listing_file.write(line)
if echo_file:
... |
class Field():
def __init__(self, *, prefix=None, desc=None, input, format=None):
self.prefix = prefix
self.desc = desc
self.format = format
def finalize(self, key, inferred_prefix):
if (self.prefix is None):
self.prefix = (inferred_prefix + ':')
if (self.desc... |
def sort_dict_keys_by_vals_with_conditions(d: Dict[(int, float)], condition_func: Callable[([Tuple[(int, float)]], bool)]) -> List[int]:
sorted_items = sorted(list(d.items()), key=(lambda pair: pair[1]))
return [pair[0] for pair in sorted_items if condition_func(pair)] |
def train(configs):
print('Configurations:', len(configs))
for (output_mode, config_file_index) in configs:
(args, filename) = get_args_and_hdf5_file(output_mode, config_file_index)
if os.path.exists(filename):
print('Skipping test', filename)
else:
print('\n\nRun... |
class PoseResNet(nn.Module):
def __init__(self, num_layers, heads, head_convs, _):
super(PoseResNet, self).__init__(heads, head_convs, 1, 64)
(block, layers) = resnet_spec[num_layers]
self.inplanes = 64
self.deconv_with_bias = False
self.heads = heads
super(PoseResNet... |
class GCT(nn.Module):
def __init__(self, num_channels, epsilon=1e-05, mode='l2', after_relu=False):
super(GCT, self).__init__()
self.alpha = nn.Parameter(torch.ones(1, num_channels, 1, 1))
self.gamma = nn.Parameter(torch.zeros(1, num_channels, 1, 1))
self.beta = nn.Parameter(torch.ze... |
def DeclareList(sort):
List = Datatype(('List_of_%s' % sort.name()))
List.declare('cons', ('car', sort), ('cdr', List))
List.declare('nil')
return List.create() |
class Encoder(tf.keras.layers.Layer):
def __init__(self, vocab_size, embedding_dim, enc_units, batch_sz):
super(Encoder, self).__init__()
self.batch_sz = batch_sz
self.enc_units = enc_units
self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim)
self.gru = tf.ke... |
def component_points(component, width: int, height: int, num: int):
if (component is not None):
lm = component.landmark
return (np.array([[(p.x * width), (p.y * height), p.z] for p in lm]), np.ones(num))
return (np.zeros((num, 3)), np.zeros(num)) |
class LLamaEngine(CausalEngine):
config_name: str = 'llama_engine'
def __init__(self, weights_path: Optional[Union[(str, Path)]]=None):
model_name = 'aleksickx/llama-7b-hf'
model = LlamaForCausalLM.from_pretrained(model_name, torch_dtype=DEFAULT_DTYPE)
tokenizer = LlamaTokenizer.from_pre... |
class DCProblemAnalyticTests_Dirichlet(unittest.TestCase):
def setUp(self):
cs = 25.0
hx = [(cs, 7, (- 1.3)), (cs, 21), (cs, 7, 1.3)]
hy = [(cs, 7, (- 1.3)), (cs, 21), (cs, 7, 1.3)]
hz = [(cs, 7, (- 1.3)), (cs, 20), (cs, 7, (- 1.3))]
mesh = discretize.TensorMesh([hx, hy, hz],... |
def get_pars(dim, full=False):
import numpy as nm
sym = (((dim + 1) * dim) // 2)
lam = 10.0
mu = 1.0
o = nm.array((([1.0] * dim) + ([0.0] * (sym - dim))), dtype=nm.float64)
oot = nm.outer(o, o)
if full:
return ((lam * oot) + (mu * nm.diag((o + 1.0))))
else:
return (lam, m... |
def get_or_find_cached_data(dataset, data_cache_name, data_cache_base_path, **kwargs):
if (kwargs.get('target', None) is None):
del kwargs['target']
res = Pickler(data_cache_name, Path(data_cache_base_path)).find_or_create((lambda : dataset.load_stratified_targets(**kwargs)))
else:
kwarg... |
def match_case(row):
for (old, new) in [('pytorch', 'PyTorch'), ('tensorflow', 'TensorFlow'), ('lasagne', 'Lasagne'), ('keras', 'Keras'), ('theano', 'Theano'), ('cudnnLSTM', 'cuDNNLSTM')]:
row['bench'] = row['bench'].replace(old, new)
return row |
class BeneparComponent():
name = 'benepar'
def __init__(self, name, subbatch_max_tokens=500, disable_tagger=False, batch_size='ignored'):
self._parser = load_trained_model(name)
if torch.cuda.is_available():
self._parser.cuda()
self.subbatch_max_tokens = subbatch_max_tokens
... |
def load_protein0():
(X_train, y_train, X_test, y_test) = load_protein()
selected = (y_train == 0)
y_train[selected] = 1
y_train[(~ selected)] = 0
selected = (y_test == 0)
y_test[selected] = 1
y_test[(~ selected)] = 0
return (X_train, y_train, X_test, y_test) |
class ShuffleV2Block(nn.Module):
def __init__(self, bn_norm, inp, oup, mid_channels, *, ksize, stride):
super(ShuffleV2Block, self).__init__()
self.stride = stride
assert (stride in [1, 2])
self.mid_channels = mid_channels
self.ksize = ksize
pad = (ksize // 2)
... |
def import_statement_string(module, names, lazy):
if lazy:
if (len(names) == 1):
(name, alias) = names[0]
if (name == alias):
if (name is None):
raise ValueError('cannot lazy import modules')
return ("lazy_import('%s', '%s')" % (mod... |
def get_scheduler(indicator, lr):
if (indicator == 'warm-cos'):
multiplier = WarmupParamScheduler(CosineParamScheduler(lr, (lr * 0.001)), warmup_factor=0.001, warmup_length=0.05, warmup_method='linear')
else:
raise ValueError('Unknown indicator: {:}'.format(indicator))
return multiplier |
def test_multipart_form_open_api_3(assert_parameters, make_openapi_3_schema, user_jsonschema_with_file, open_api_3_user_with_file):
schema = make_openapi_3_schema({'required': True, 'content': {'multipart/form-data': {'schema': open_api_3_user_with_file}}})
assert_parameters(schema, PayloadAlternatives([OpenAPI... |
def test_20news_length_consistency(fetch_20newsgroups_fxt):
data = fetch_20newsgroups_fxt(subset='all')
assert (len(data['data']) == len(data.data))
assert (len(data['target']) == len(data.target))
assert (len(data['filenames']) == len(data.filenames)) |
class CrossBatchMemory(ModuleWithRecords):
def __init__(self, loss, embedding_size, memory_size=1024, miner=None, **kwargs):
super().__init__(**kwargs)
self.loss = loss
self.miner = miner
self.embedding_size = embedding_size
self.memory_size = memory_size
self.embeddi... |
class SyncMaster(object):
def __init__(self, master_callback):
self._master_callback = master_callback
self._queue = queue.Queue()
self._registry = collections.OrderedDict()
self._activated = False
def register_slave(self, identifier):
if self._activated:
asse... |
.parametrize('precision_level', ['32b', '64b'])
def test_set_precision_by_string(precision_level):
pyhf.set_backend(pyhf.tensorlib.name, precision=precision_level)
assert (pyhf.tensorlib.precision == precision_level.lower())
pyhf.set_backend(pyhf.tensor.numpy_backend(precision=precision_level))
assert (... |
_AA_and_QQbar
def _singular_normal(ideal):
from sage.libs.singular.function import singular_function, lib
lib('normal.lib')
normal = singular_function('normal')
execute = singular_function('execute')
try:
get_printlevel = singular_function('get_printlevel')
except NameError:
exec... |
def main():
np.random.seed(args['SEED'])
torch.manual_seed(args['SEED'])
gpuAvailable = torch.cuda.is_available()
device = torch.device(('cuda' if gpuAvailable else 'cpu'))
kwargs = ({'num_workers': args['NUM_WORKERS'], 'pin_memory': True} if gpuAvailable else {})
torch.backends.cudnn.determinis... |
def kullback_leibler_divergence(p, q):
p = np.asarray(p)
q = np.asarray(q)
filt = np.logical_and((p != 0), (q != 0))
return np.sum((p[filt] * np.log2((p[filt] / q[filt])))) |
def MkInfinitesimal(name='eps', ctx=None):
ctx = z3.get_ctx(ctx)
return RCFNum(Z3_rcf_mk_infinitesimal(ctx.ref()), ctx) |
def transform_pet_eprstmt(example, label_normalize_dict=None, is_test=False, pattern_id=0):
if is_test:
example['label_length'] = 1
if (pattern_id == 0):
example['sentence1'] = (u'<unk>!' + example['sentence'])
elif (pattern_id == 1):
example['sentence1'] = (u'<unk>!,... |
def test_restriced(rpool):
for i in range(20):
rpool.add_constant(i)
assert (rpool.get_all_constants_for(int) == OrderedSet([15, 16, 17, 18, 19])) |
def compute_features(eval_loader, model, args):
print('Computing features...')
model.eval()
features = torch.zeros(len(eval_loader.dataset), args.low_dim).cuda()
for (i, (images, index)) in enumerate(tqdm(eval_loader)):
with torch.no_grad():
images = images.cuda(non_blocking=True)
... |
class ResNet(nn.Module):
def __init__(self, block: Type[Union[(BasicBlock, Bottleneck)]], layers: List[int], num_classes: int=1000, in_channels: int=3, zero_init_residual: bool=False, groups: int=1, width_per_group: int=64, replace_stride_with_dilation: Optional[List[bool]]=None, norm_layer: Optional[Callable[(...,... |
def _simple_validate_commit_rev(rev):
assert ((len(rev) >= _MinNumHashDigits) and _RevDigitsRe.match(rev)) |
def epoch_wrapup(pl_module):
phase = ('train' if pl_module.training else 'val')
the_metric = 0
the_metric_qar = 0
if (pl_module.hparams.config['get_recall_metric'] and (not pl_module.training)):
(ir_r1, ir_r5, ir_r10, tr_r1, tr_r5, tr_r10) = compute_irtr_recall(pl_module)
if (torch.distr... |
class AutoTokenizer():
def __init__(self):
raise EnvironmentError('AutoTokenizer is designed to be instantiated using the `AutoTokenizer.from_pretrained(pretrained_model_name_or_path)` method.')
_list_option_in_docstrings(TOKENIZER_MAPPING_NAMES)
def from_pretrained(cls, pretrained_model_name_or_pat... |
def run_episode(env, agent, optimisers, total_episodic_rewards, i_episode, max_steps_per_episode=1000):
current_episodic_reward = 0.0
env.reset()
agent.set_initial_state()
for t in range(max_steps_per_episode):
observation = env.observe()
action = agent.get_action(observation)
ob... |
def mapper(x):
if (x == 'Very Difficult'):
return 1.0
elif (x == 'Difficult'):
return 2.0
elif (x == 'Neutral'):
return 3.0
elif (x == 'Easy'):
return 4.0
elif (x == 'Very Easy'):
return 5.0 |
def register_Ns3Dot11sHwmpProtocol_methods(root_module, cls):
cls.add_constructor([])
cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')])
cls.add_method('DoDispose', 'void', [], is_virtual=True)
cls.add_method('GetRoutingTable', 'ns3::Ptr< ns3::dot11s::HwmpRtable >', [], is_const=Tr... |
class ViTBase_pretrained(nn.Module):
def __init__(self):
super().__init__()
model_name = 'google/vit-base-patch16-224'
config = transformers.ViTConfig.from_pretrained(model_name)
config.update({'num_channels': 1})
config.update({'image_size': (129, 500)})
config.updat... |
def load_soba_json(json_file, image_root, dataset_name=None):
from pysobatools.soba import SOBA
timer = Timer()
json_file = PathManager.get_local_path(json_file)
with contextlib.redirect_stdout(io.StringIO()):
soba_api = SOBA(json_file)
if (timer.seconds() > 1):
logger.info('Loading ... |
def MatchingPennies():
from sage.matrix.constructor import matrix
A = matrix([[1, (- 1)], [(- 1), 1]])
g = NormalFormGame([A])
g.rename(('Matching pennies - ' + repr(g)))
return g |
def GetAllImageIds():
page = 1
next = ('/api/v0/images/all?page=' + str(page))
ids = []
while True:
data = utils.RetrieveData(next)
ids.extend(data['results'])
if (data['next'] is None):
break
page += 1
next = ('/api/v0/images/all?page=' + str(page))
... |
def process_it_vit(paths, dataset_name, *args):
assert (dataset_name == 'it_vit')
convert_it_vit(paths, dataset_name) |
def _flatten_sparse_tensors(tensors):
flat_indices = _flatten_dense_tensors([t._indices() for t in tensors])
flat_values = _flatten_dense_tensors([t._values() for t in tensors])
return (flat_indices, flat_values) |
def run(task: Task, num_samples: int, num_simulations: int, num_observation: Optional[int]=None, observation: Optional[torch.Tensor]=None, num_rounds: int=10, neural_net: str='resnet', hidden_features: int=50, simulation_batch_size: int=1000, training_batch_size: int=10000, num_atoms: int=10, automatic_transforms_enabl... |
def register_Ns3RngSeedManager_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::RngSeedManager const &', 'arg0')])
cls.add_method('GetNextStreamIndex', 'uint64_t', [], is_static=True)
cls.add_method('GetRun', 'uint64_t', [], is_static=True)
cls.add_method('GetSeed'... |
class ComputeTime():
def __call__(self, explanation, name):
return BenchmarkResult('compute time', name, value=(explanation.compute_time / explanation.shape[0])) |
class InceptionTest(tf.test.TestCase):
def testBuildLogits(self):
batch_size = 5
(height, width) = (299, 299)
num_classes = 1000
with self.test_session():
inputs = tf.random_uniform((batch_size, height, width, 3))
(logits, _) = inception.inception_resnet_v2(in... |
def get_shape(val: object) -> typing.List[int]:
if val.isCompleteTensor():
r = val.type().sizes()
if (not r):
r = [1]
return r
elif (val.type().kind() in ('IntType', 'FloatType')):
return [1]
else:
raise ValueError() |
class RestPittSpec(DomainSpec):
name = 'rest_pitt'
greet = 'I am an expert about Pittsburgh restaurant.'
nlg_spec = {'loc': {'inform': ['I am at %s.', '%s.', "I'm interested in food at %s.", 'At %s.', 'In %s.'], 'request': ['Which city are you interested in?', 'Which place?']}, 'food_pref': {'inform': ['I l... |
def read_json(input_filename):
docs = []
blank = 0
unlabeled = 0
broken = 0
with open(input_filename, encoding='utf-8') as fin:
for (line_idx, line) in enumerate(fin):
doc = json.loads(line)
if (sorted(doc.keys()) == ['source']):
unlabeled += 1
... |
.environment
class cuTensor():
cmake_minimum_version = None
cmake_packages = ['CUDA']
cmake_variables = {}
cmake_includes = []
cmake_libraries = ['cutensor']
cmake_compile_flags = []
cmake_link_flags = ['-L -lcutensor']
cmake_files = []
headers = {'frame': ['../include/dace_cutensor.... |
def loadJson(dirname, epoch, rank):
filename = '/rollout_{0}_{1}.txt'.format(epoch, rank)
with open((dirname + filename), 'r') as file:
os = json.loads(file.read())
return os |
class Transition(nn.Module):
def __init__(self, in_planes, out_planes):
super(Transition, self).__init__()
self.bn = nn.BatchNorm2d(in_planes)
self.conv = nn.Conv2d(in_planes, out_planes, kernel_size=1, bias=False)
def forward(self, x):
out = self.conv(F.leaky_relu(self.bn(x)))
... |
def _getEdgesIter(input_path, comparator):
logger.debug(('generate edges from: %s' % input_path))
edges = defaultdict(list)
if (not os.path.exists(input_path)):
return edges
if os.path.isfile(input_path):
base_filename = os.path.basename(input_path)
topic = re.sub('-.*$', '', bas... |
def newsample(nnn, ratio):
if (ratio > len(nnn)):
return random.sample((nnn * ((ratio // len(nnn)) + 1)), ratio)
else:
return random.sample(nnn, ratio) |
_quantizer(quantization_target=QuantizationTarget.Weights, quantization_method=[QuantizationMethod.POWER_OF_TWO, QuantizationMethod.SYMMETRIC], identifier=RoundingType.SoftQuantizer)
class SymmetricSoftRoundingGPTQ(BasePytorchGPTQTrainableQuantizer):
def __init__(self, quantization_config: TrainableQuantizerWeights... |
class StepFunc(Protocol):
def __call__(self, *, model: rf.Module, extern_data: TensorDict) -> None:
... |
def open_segmentation_mask(segmentation_filename, dataset_name):
transformer = transforms.Compose([transforms.Resize((224, 224))])
mask = Image.open(segmentation_filename).convert('L')
mask = transformer(mask)
mask = (np.array(mask) / 255.0)
if (dataset_name == 'VOC'):
mask[(mask > 0)] = 1
... |
class ModelContextFusion(ModelTemplate):
def __init__(self, token_emb_mat, glove_emb_mat, tds, tel, hn, scope):
super(ModelContextFusion, self).__init__(token_emb_mat, glove_emb_mat, tds, tel, hn, scope)
self.update_tensor_add_ema_and_opt()
def build_network(self):
(tds, tel, hn) = (self... |
def register_types_ns3_Hash(module):
root_module = module.get_root()
module.add_class('Implementation', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >'])
typehandlers.add_type_alias(u'uint32_t ( *... |
def test_channel(sol):
config.update({'Re': 8000.0, 'nu': (1.0 / 8000.0), 'dt': 0.001, 'T': 0.01, 'L': [2, (2 * pi), ((4 * pi) / 3.0)], 'M': [7, 5, 2], 'eps': 1e-07}, 'channel')
solver = get_solver(regression_test=regression_test, mesh='channel', parse_args=[sol])
context = solver.get_context()
initiali... |
def convert_temperature(val, old_scale, new_scale):
if (old_scale.lower() in ['celsius', 'c']):
tempo = (_np.asanyarray(val) + zero_Celsius)
elif (old_scale.lower() in ['kelvin', 'k']):
tempo = _np.asanyarray(val)
elif (old_scale.lower() in ['fahrenheit', 'f']):
tempo = ((((_np.asany... |
(repr=False)
class Check():
name: str
value: Status
response: (GenericResponse | None)
elapsed: float
example: Case
message: (str | None) = None
context: (FailureContext | None) = None
request: (requests.PreparedRequest | None) = None |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.