code stringlengths 101 5.91M |
|---|
def query_yes_no(question, default='yes'):
valid = {'yes': True, 'y': True, 'ye': True, 'no': False, 'n': False}
if (default is None):
prompt = ' [y/n] '
elif (default == 'yes'):
prompt = ' [Y/n] '
elif (default == 'no'):
prompt = ' [y/N] '
else:
raise ValueError(("in... |
def before_generate_case(context: HookContext, strategy: st.SearchStrategy[Case]) -> st.SearchStrategy[Case]:
seen = set()
def is_not_seen(case: Case) -> bool:
hashed = hash(case)
if (hashed not in seen):
seen.add(hashed)
return True
return False
return strate... |
.parametrize('statement_type', [stmt.IntPrimitiveStatement, stmt.FloatPrimitiveStatement, stmt.StringPrimitiveStatement, stmt.BytesPrimitiveStatement, stmt.BooleanPrimitiveStatement, stmt.ComplexPrimitiveStatement, stmt.ClassPrimitiveStatement])
def test_primitive_statement_value_none(statement_type, default_test_case)... |
class StayAgent(Agent):
def __init__(self, sim_threads=None):
self.sim_threads = sim_threads
def action(self, state):
return Action.STAY
def direct_action(self, obs):
return ([Action.ACTION_TO_INDEX[Action.STAY]] * self.sim_threads) |
class MessageCollection(object):
def __init__(self):
self.messages = set()
def error(self, pos, message):
self.messages.add((pos, True, message))
def warning(self, pos, message):
self.messages.add((pos, False, message))
def report(self):
for (pos, is_error, message) in so... |
def get_annotation(mtg_path, split_type=False):
if split_type:
train = read_file(os.path.join(mtg_path, 'split-0', f'{split_type}-train.tsv'))
validation = read_file(os.path.join(mtg_path, 'split-0', f'{split_type}-validation.tsv'))
test = read_file(os.path.join(mtg_path, 'split-0', f'{split... |
def dma_reg_fmt_base(reg: Union[(DMA_tensor_0x000__reg, DMA_matrix_reg)]):
if isinstance(reg, DMA_tensor_0x000__reg):
addr = [(reg.src_start_addr_h8, reg.src_start_addr_l32), (reg.dst_start_addr_h8, reg.dst_start_addr_l32)]
elif isinstance(reg, DMA_matrix_reg):
addr = [(reg.src_start_addr_l8, re... |
class _MutationMetrics():
num_created_mutants: int
num_killed_mutants: int
num_timeout_mutants: int
def get_score(self) -> float:
divisor = (self.num_created_mutants - self.num_timeout_mutants)
assert (divisor >= 0)
if (divisor == 0):
return 1.0
return (self.n... |
_utils.test(arch=get_host_arch_list())
def test_order_vector():
X = 4
Y = 2
Z = 2
S = 4
a = ti.Vector.field(Z, ti.i32, shape=(X, Y), order='ij', layout=ti.Layout.AOS)
b = ti.Vector.field(Z, ti.i32, shape=(X, Y), order='ji', layout=ti.Layout.AOS)
c = ti.Vector.field(Z, ti.i32, shape=(X, Y), o... |
class StaticCuboid(RigidObject):
def __init__(self, pybullet_client_ids, name, size=np.array([0.065, 0.065, 0.065]), position=np.array([0.0, 0.0, 0.0425]), orientation=np.array([0, 0, 0, 1]), color=np.array([1, 0, 0]), lateral_friction=1):
super(StaticCuboid, self).__init__(pybullet_client_ids=pybullet_clie... |
class MemRef(MemRefBase):
device = Target.BM1684X
def __init__(self, address, shape, dtype: DType, stride=None, layout=None):
super().__init__(address, shape, dtype, stride, layout)
if ((self.mtype == MType.R) and (layout != Layout.stride)):
self.stride = local_layout_to_stride(self)... |
def filter_pathlist(path_list, expr):
if (expr == 'all'):
return path_list
elif (expr[:2] == 'I:'):
fl = eval(f'path_list[{expr[2:]}]')
if (type(fl) == str):
return [fl]
return fl
elif (expr[:2] == 'R:'):
regexp = re.compile(expr[2:])
return [e for... |
class InnerAngleRepresentation():
def __call__(self, p1s: tf.Tensor, p2s: tf.Tensor, p3s: tf.Tensor) -> tf.Tensor:
v1 = (p1s - p2s)
v2 = (p3s - p2s)
v1_norm = get_vectors_norm(v1)
v2_norm = get_vectors_norm(v2)
slopes = tf.reduce_sum((v1_norm * v2_norm), axis=3)
angle... |
def save_to_hub(pred_nets, domain_net, theory_hub, theory_type, theory_add_threshold, is_Lagrangian):
if load_previous:
theory_hub = load_model_dict_at_theory_hub(pickle.load(open(filename_hub, 'rb')))
added_theory_info = theory_hub.add_theories(name=(hub_theory_name if (theory_type == 'neural') else (h... |
class BasicDeconv(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, activate=None):
super(BasicDeconv, self).__init__()
bias = (False if (activate == 'bn') else True)
self.tconv = nn.ConvTranspose2d(in_channels, out_channels, kernel_size, stride=stride, padding... |
def import_scheme(scheme_name):
full_name = f'{SCHEME_LIB}.{scheme_name}.{SCHEME_CLS}'
(module_name, object_name) = full_name.rsplit('.', 1)
imported_module = importlib.import_module(module_name)
return getattr(imported_module, object_name) |
('euler_maruyama')
class EulerMaruyamaPredictor(Predictor):
def __init__(self, sde, score_fn, probability_flow=False):
super().__init__(sde, score_fn, probability_flow=probability_flow)
def update_fn(self, x, t, *args, **kwargs):
dt = ((- 1.0) / self.rsde.N)
z = torch.randn_like(x)
... |
def main(args):
imgaug.seed(42)
torch.random.manual_seed(42)
random.seed(42)
if os.path.isabs(args.cfg):
cfg.merge_from_file(args.cfg)
else:
cfg.merge_from_file(os.path.join(RepoPaths.configs_dir(), args.cfg))
if (args.dataset == 'coco'):
dataset = CocoDataLoader(CocoPath... |
def normal_kld(q_mean, q_std, p_mean, p_std):
return (((((p_std.pow(2) + (p_mean - q_mean).pow(2)).div(q_std.pow(2)) * 0.5) - 0.5) + q_std.log()) - p_std.log()).sum(1).mean() |
def write_data(data, folder):
ase.io.write(str((folder / 'data.traj')), data.as_Atoms(), format='traj', parallel=False) |
def _impl(array, highlevel, behavior, attrs):
from awkward._connect.pyarrow import import_pyarrow_compute
pc = import_pyarrow_compute('c')
with HighLevelContext(behavior=behavior, attrs=attrs) as ctx:
layout = ctx.unwrap(array)
out = ak._do.recursively_apply(layout, ak.operations.str._get_ufunc_... |
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, norm_type='batch', stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = normalization(planes, norm_type)
self.c... |
def checkpoint(acc, epoch):
print('Saving..')
state = {'model': model.state_dict(), 'optimizer': optimizer.state_dict(), 'acc': acc, 'epoch': epoch, 'seed': args.manualSeed}
torch.save(state, (args.save_dir + 'checkpoint.t7')) |
class ImprimitiveLocalComponent(LocalComponentBase):
def __init__(self, newform, prime, twist_factor, min_twist, chi):
LocalComponentBase.__init__(self, newform, prime, twist_factor)
self._min_twist = min_twist
self._chi = chi
def is_primitive(self):
return False
def minimal_... |
.spark
.parametrize('dataset, column, number_of_unique', [('full_spark_dataset', 'user_id', 3), ('full_pandas_dataset', 'user_id', 3), ('full_spark_dataset', 'item_id', 4), ('full_pandas_dataset', 'item_id', 4)])
def test_number_of_unique_values(dataset, column, number_of_unique, request):
dataset = request.getfixt... |
def create_network():
num_conv_channels = 4
kernel = 3
conv_w1 = get_random_weights(kernel, num_conv_channels, num_conv_channels)
conv_w2 = get_random_weights(kernel, num_conv_channels, num_conv_channels)
inputs = Input(shape=(16, 16, num_conv_channels))
x = Conv2D(num_conv_channels, kernel, use... |
class Assembly():
def __init__(self, path, assembler):
self.assembler = assembler
if (not os.path.exists(path)):
raise Error(('Input path to Assembly.__init__ not found: ' + path))
elif os.path.isdir(path):
self.assembler_dir = os.path.abspath(path)
else:
... |
class UnityCommunicationException(Exception):
def __init__(self, message):
self.message = message |
def evaluate(trainer: Algorithm, env, cfg: EvalConfig, timesteps_total):
if (trainer._timesteps_total is None):
trainer._timesteps_total = timesteps_total
eval_stats = {'timesteps_total': trainer._timesteps_total}
n_params = 0
for param in trainer.get_policy().model.parameters():
n_param... |
def recursive_partitioning(inp_file, out_dir, modulename, path):
modulenames = []
print('Partitioning input circuit...')
part_dir = os.path.join(out_dir, 'partition')
num_parts = ((number_of_cell(inp_file, path['yosys']) // 1500) + 1)
lsoracle_command = ((((((('read_verilog ' + inp_file) + '; partit... |
class MaskFormerFeatureExtractor(MaskFormerImageProcessor):
def __init__(self, *args, **kwargs) -> None:
warnings.warn('The class MaskFormerFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please use MaskFormerImageProcessor instead.', FutureWarning)
super().__init__(... |
class InteractingLayer(nn.Module):
def __init__(self, embedding_size, head_num=2, use_res=True, scaling=False, seed=1024, device='cpu'):
super(InteractingLayer, self).__init__()
if (head_num <= 0):
raise ValueError('head_num must be a int > 0')
if ((embedding_size % head_num) != ... |
class BenchmarkDiscreteTabular(BenchmarkDiscreteTabularBase):
def __init__(self, algo_dict: Dict=None, kargs_dict: Dict=None, num_exp: int=20, custom_metric_dict: Optional[Dict]={}, **kargs):
BenchmarkDiscreteTabularBase.__init__(self, algo_dict=algo_dict, num_exp=num_exp, kargs_dict=kargs_dict, custom_metr... |
def register_Ns3CallbackImplBase_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::CallbackImplBase const &', 'arg0')])
cls.add_method('GetTypeid', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True)
cls.add_method('IsEqual', 'bool', [param('ns3::Pt... |
def make_stub_as(asn: int, exchange: str):
stub_as = base.createAutonomousSystem(asn)
if (bot_desc.get(asn) == 'c2'):
botnet_server = stub_as.createHost('c2_server')
else:
botnet_server = stub_as.createHost('bot')
router = stub_as.createRouter('router0')
net = stub_as.createNetwork('... |
class SequentialNetwork(SequenceNetwork):
def __init_subclass__(cls, **kwargs):
warn(f'{cls.__name__} will be deprecated. Use `SequenceNetwork` instead.', DeprecationWarning, stacklevel=2)
super().__init_subclass__(**kwargs)
def __init__(self, *args, **kwargs):
warn(f'{self.__class__.__n... |
def test_get_item_1d_errors():
with pytest.raises(IndexError, match='index [0-9]+ is out of bounds for dimension 0 with size [0-9]+'):
(x, y) = mamoDataset1.__getitem__(55)
with pytest.raises(IndexError):
(x, y) = mamoDataset1.__getitem__(5.5) |
def to_double(img):
img = np.atleast_3d(img)
channels = img.shape[2]
if (channels < 3):
img = np.tile(img, 3)
img[np.isnan(img)] = 0
img -= np.amin(img)
img /= np.amax(img)
return img |
def test_out_of_bounds():
left = ak.Array([1, 2, 3])
right = ak.Array([['lambda', 'sigma', 'eta', 'phi'], ['delta']])
with pytest.raises(np.AxisError):
ak.cartesian([left, right], axis=2) |
def test_case111():
url = (brokerIp + '/ngsi-ld/v1/entityOperations/upsert')
headers = {'Content-Type': 'application/json', 'Accept': 'application/ld+json', 'Link': '<{{link}}>; rel=" type="application/ld+json"'}
r = requests.post(url, data=json.dumps(ld_data.subdata111), headers=headers)
print(r.conten... |
def adjust_learning_rate(optimizers, init_lr, epoch):
lr = (init_lr * (0.5 ** (epoch // 30)))
for optimizer in optimizers:
for param_group in optimizer.param_groups:
param_group['lr'] = lr |
.spark
.parametrize('row_count', [None, 1000, 1500])
.parametrize('column_count', [None, 2000, 1700])
.usefixtures('interactions_spark', 'true_size')
def test_CSRConverter_user_column_counts(row_count, column_count, interactions_spark, true_size):
current_size = ((row_count if (row_count is not None) else true_size... |
class FakeRolloutWorker(RolloutWorker):
def init_agent_interfaces(self, env_desc: Dict[(str, Any)], runtime_ids: Sequence[AgentID]) -> Dict[(AgentID, Any)]:
return {}
def init_actor_pool(self, env_desc: Dict[(str, Any)], rollout_config: Dict[(str, Any)], agent_mapping_func: Callable) -> ActorPool:
... |
def register_Ns3Names_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::Names const &', 'arg0')])
cls.add_method('Add', 'void', [param('std::string', 'name'), param('ns3::Ptr< ns3::Object >', 'object')], is_static=True)
cls.add_method('Add', 'void', [param('std::string'... |
class deeplab_xception_transfer_projection(deeplab_xception_transfer_basemodel):
def __init__(self, nInputChannels=3, n_classes=7, os=16, input_channels=256, hidden_layers=128, out_channels=256, transfer_graph=None, source_classes=20):
super(deeplab_xception_transfer_projection, self).__init__(nInputChannel... |
def main(args):
options = parser.parse_args(args)
build = confu.Build.from_options(options)
build.export_cpath('include', ['clog.h'])
with build.options(source_dir='src', extra_include_dirs='src'):
build.static_library('clog', build.cc('clog.c'))
with build.options(source_dir='test', deps={(... |
def test_two_arrays():
str = '{"one": 1, "two": 2.2}{"one": 10, "two": 22}'
with pytest.raises(ValueError):
ak.operations.from_json(str)
str = '{"one": 1, "two": 2.2} {"one": 10, "two": 22}'
with pytest.raises(ValueError):
ak.operations.from_json(str)
str = '{"one": 1, \t "two": ... |
class TestFlowInclude(FLSpec):
include_error_list = []
def start(self):
print((f'{bcolors.OKBLUE}Testing FederatedFlow - Starting Test for Include Attributes ' + f'{bcolors.ENDC}'))
self.collaborators = self.runtime.collaborators
self.exclude_agg_to_agg = 10
self.include_agg_to_a... |
_utils.test()
def test_matrix_field_dynamic_index_different_path_length():
v = ti.Vector.field(2, ti.i32)
x = v.get_scalar_field(0)
y = v.get_scalar_field(1)
ti.root.dense(ti.i, 8).place(x)
ti.root.dense(ti.i, 2).dense(ti.i, 4).place(y)
impl.get_runtime().materialize()
assert (v._get_dynamic... |
def run_defense_method(graph, method, k=3, seed=None):
protected = []
if ((method in methods) and (k > 0)):
if (seed is not None):
np.random.seed(seed)
protected = methods[method](graph, k)
else:
print('{} not implemented or k <= 0'.format(method))
return protected |
_metric
def overlap50k_alignment50k_layoutwise_iou50k_layoutwise_docsim50k_val(opts):
opts.dataset_kwargs.update(max_size=None, xflip=False)
(overlap, alignment, layoutwiseIoU, layoutwiseDocSim) = overlap50k_alignment50k_layoutwise_iou50k_layoutwise_docsim50k.compute_overlap_alignment_laywise_IoU_layerwise_DocS... |
def get_agent_cls(agent_class_name):
sub_classes = [sub_class for sub_class in get_all_subclasses(habitat.Agent) if (sub_class.__name__ == agent_class_name)]
return sub_classes[0] |
def plot_UCI():
fname = 'datasets/UCI_processed/OCnodeslinks_chars.txt'
max_nodes = 1901
G_times = UCI_loader.load_temporarl_edgelist(fname, max_nodes=max_nodes)
graph_name = 'UCI_Message'
labels_dict = {}
print('edge')
labels_dict['edge'] = normal_util.plot_edges(G_times, graph_name)
pr... |
def _central_crop(image_list, crop_height, crop_width):
outputs = []
for image in image_list:
image_height = tf.shape(image)[0]
image_width = tf.shape(image)[1]
offset_height = ((image_height - crop_height) / 2)
offset_width = ((image_width - crop_width) / 2)
outputs.appe... |
('simple')
class SimpleWordSplitter(WordSplitter):
def __init__(self):
self.special_cases = set(['mr.', 'mrs.', 'etc.', 'e.g.', 'cf.', 'c.f.', 'eg.', 'al.'])
self.contractions = set(["n't", "'s", "'ve", "'re", "'ll", "'d", "'m"])
self.contractions |= set([x.replace("'", '') for x in self.con... |
class func_persist():
def __init__(self, f, dir='func_persist'):
self.__func = f
self.__dir = dir
os.makedirs(dir, exist_ok=True)
self.__doc__ = ('%s%s%s' % (f.__name__, inspect.signature(f), f.__doc__))
def __call__(self, *args, **kwds):
key = (tuple(args), tuple(kwds.it... |
def notna(target_column, features, df):
out = pd.Series(features, index=features).apply((lambda feature: df.select([feature, target_column]).na.drop('any').count())).astype(float)
return out |
def ffmpeg_merge_video_audio(video, audio, output, vcodec='copy', acodec='copy', ffmpeg_output=False, logger='bar'):
cmd = [get_setting('FFMPEG_BINARY'), '-y', '-i', audio, '-i', video, '-vcodec', vcodec, '-acodec', acodec, output]
subprocess_call(cmd, logger=logger) |
class LSTMCell(BaseCell):
def __call__(self, inputs, state, scope=None):
with tf.variable_scope((scope or type(self).__name__)):
(cell_tm1, hidden_tm1) = tf.split(state, 2, axis=1)
input_list = [inputs, hidden_tm1]
lin = linear(input_list, self.output_size, add_bias=True,... |
class XmlJoint(XmlElem):
tag = 'joint'
JOINT_TYPES = {'revolute': Box2D.b2RevoluteJoint, 'friction': Box2D.b2FrictionJoint, 'prismatic': Box2D.b2PrismaticJoint}
class Meta():
bodyA = XmlAttr('bodyA', String(), required=True)
bodyB = XmlAttr('bodyB', String(), required=True)
anchor = ... |
class TensorboardLogger():
def __init__(self, run_dir, py_logger: logging.Logger, *, enabled_tb):
self.run_dir = run_dir
self.py_log = py_logger
if enabled_tb:
self.tb_log = SummaryWriter(run_dir)
else:
self.tb_log = None
try:
import git
... |
class DDPGAgent(object):
def __init__(self, state_dim, action_dim, max_action, device, discount=0.99, tau=0.005):
self.device = device
self.discount = discount
self.tau = tau
self.actor = Actor(state_dim, action_dim, max_action).to(device)
self.actor_target = deepcopy(self.ac... |
class ScispaCy(BaseLinker):
def __init__(self, args):
import scispacy, spacy
from scispacy.abbreviation import AbbreviationDetector
from scispacy.umls_linking import UmlsEntityLinker
self.nlp = spacy.load('en_core_sci_sm')
self.nlp.add_pipe('abbreviation_detector')
se... |
def tf_toposort(ts, within_ops=None):
all_ops = ge.get_forward_walk_ops([x.op for x in ts], within_ops=within_ops)
deps = {}
for op in all_ops:
for o in op.outputs:
deps[o] = set(op.inputs)
sorted_ts = toposort(deps)
ts_sorted_lists = []
for l in sorted_ts:
keep = lis... |
def tcd(xs, base=2):
xis = [entropyd(column(xs, i), base) for i in range(0, len(xs[0]))]
hx = entropyd(xs, base)
return (np.sum(xis) - hx) |
def evaluate_model(epoch):
combined_model.eval()
val_loss = 0.0
total = 0.0
correct = 0.0
with torch.no_grad():
for (batch_idx, (img, text_match, text_diff, seq_len_match, seq_len_diff, bboxes, bbox_classes)) in enumerate(tqdm(val_loader, desc='')):
(text_match, text_diff) = proc... |
.usefixtures('spark')
def interactions_users_spark_dataset(spark):
events = spark.createDataFrame(pd.DataFrame({'user_id': [0, 0, 1, 1, 1, 2], 'item_id': [0, 1, 0, 2, 3, 1], 'timestamp': [0, 1, 2, 3, 4, 5], 'rating': [1.1, 1.2, 1.3, 2, 3, 4]}))
users = spark.createDataFrame(pd.DataFrame({'user_id': [0, 1, 2], '... |
def calc_one_mrr(data):
score = 0
data = sorted(data, key=(lambda d: d[1]), reverse=True)
for (idx, item) in enumerate(data):
if (int(item[0][2]) == 1):
score = (1.0 / (idx + 1))
break
return score |
def run(size):
FLAGS.min_dec_steps = (size // 4)
FLAGS.max_dec_steps = size
FLAGS.max_enc_steps = size
tf.logging.set_verbosity(tf.logging.INFO)
tf.logging.info('Starting seq2seq_attention in %s mode...', FLAGS.mode)
FLAGS.log_root = log_path
FLAGS.log_root = os.path.join(FLAGS.log_root, FLA... |
class SelfAttentionBlock(_SelfAttentionBlock):
def __init__(self, low_in_channels, high_in_channels, channels, out_channels, share_key_query, query_scale, key_pool_scales, conv_cfg, norm_cfg, act_cfg):
key_psp = PPMConcat(key_pool_scales)
if (query_scale > 1):
query_downsample = nn.MaxPo... |
def truncate_seq_pair(tokens_a, tokens_b, max_length):
is_too_long = False
while True:
total_length = (len(tokens_a) + len(tokens_b))
if (total_length <= max_length):
break
is_too_long = True
if (len(tokens_a) > len(tokens_b)):
tokens_a.pop()
else:... |
class Artanh(torch.autograd.Function):
def forward(ctx, x):
x = x.clamp(((- 1) + 1e-05), (1 - 1e-05))
ctx.save_for_backward(x)
res = torch.log_((1 + x)).sub_(torch.log_((1 - x))).mul_(0.5)
return res
def backward(ctx, grad_output):
(input,) = ctx.saved_tensors
ret... |
class SAB(nn.Module):
def __init__(self, dim_in, dim_out, num_heads=4, ln=False, attention_dropout=0.1, dim_feedforward=512, attn_mode='Normal'):
super(SAB, self).__init__()
self.mab = MultiHeadSelfAttentionBlock(dim_in, dim_out, num_heads, ln=ln, attention_dropout=attention_dropout, dim_feedforward... |
class JointDataLoader(object):
def __init__(self, cfg):
self.cfg = cfg
self.dataloader_A = None
self.dataloader_B = None
self.stop_A = False
self.stop_B = False
self.max_dataset_size = None
self.is_train = None
def build(self, dataloader_A, dataloader_B, i... |
def __validate_extra_deps(extra_section: str, error: bool=False) -> None:
ignore_deps = os.environ.get('DOCUMENTATION_ENV', False)
md = distribution('lightautoml').metadata
extra_pattern = 'extra == "{}"'.format(extra_section)
reqs_info = []
for (k, v) in md.items():
if ((k == 'Requires-Dist... |
def validate_yaml_file(file: str):
try:
with open(file, encoding='utf-8') as fp:
yaml.load(fp.read(), Loader=yaml.FullLoader)
except FileNotFoundError:
return (False, f"The file {Fore.CYAN}`{file}`{Fore.RESET} wasn't found")
except yaml.YAMLError as e:
return (False, f'Th... |
def test_transfer_fields_correct_batch(adata1, adata2):
del adata2.obs['batch']
adata1_manager = generic_setup_adata_manager(adata1, batch_key='batch')
with pytest.raises(KeyError):
adata1_manager.transfer_fields(adata2) |
def keras_train_and_save(estimator, model_params, save, FLAGS, train_dataset_fn, val_dataset_fn, label_meta, epochs, verbose, metric_names, validation_steps, load, model_meta, is_pai):
print('Start training using keras model...')
classifier = None
try:
(classifier, has_none_optimizer) = keras_compil... |
def clip_grad_norm(named_parameters, max_norm, clip=False, verbose=False):
max_norm = float(max_norm)
total_norm = 0
param_to_norm = {}
param_to_shape = {}
for (n, p) in named_parameters:
if (p.grad is not None):
param_norm = p.grad.data.norm(2)
total_norm += (param_n... |
def weights_init_classifier(m):
classname = m.__class__.__name__
if (classname.find('Linear') != (- 1)):
if (m.weight is not None):
init.normal_(m.weight.data, std=0.001)
if (m.bias is not None):
init.constant_(m.bias.data, 0.0) |
class Net(BaseNet):
def __init__(self, config):
super(Net, self).__init__(config)
self.build_net()
def build_net(self):
num_agents = self.config.num_agents
num_items = self.config.num_items
num_a_layers = self.config.net.num_a_layers
num_p_layers = self.config.net... |
def to_cuda(batch):
for (key, value) in batch.items():
if isinstance(value, torch.Tensor):
batch[key] = value.cuda()
return batch |
class WandbCallback(TrainerCallback):
def __init__(self):
assert _has_wandb, 'WandbCallback requires wandb to be installed. Run `pip install wandb`.'
self._initialized = False
def setup(self, args, state, model):
self._initialized = True
if state.is_world_process_zero:
... |
def wait_for_process(p):
try:
return p.wait()
except KeyboardInterrupt:
exit_status = p.wait(timeout=5)
if (exit_status is not None):
return exit_status
else:
p.kill()
raise
except:
p.kill()
raise
finally:
p.wait... |
def maybe_do_theoretical_analysis(DO_THEORETICAL, PRINT_THEORETICAL, PRINT_MIN_MAX_BALANCE, async_pipeline, graph, recomputation):
s = ''
if ((graph is not None) and DO_THEORETICAL):
(sequential_f, sequential_b, parallel_f, parallel_b) = theoretical_analysis(graph, recomputation=recomputation, async_pip... |
class LieAlgebraWithGenerators(LieAlgebra):
def __init__(self, R, names=None, index_set=None, category=None, prefix='L', **kwds):
self._indices = index_set
LieAlgebra.__init__(self, R, names, category)
_method
def lie_algebra_generators(self):
return Family(self._indices, self.monomi... |
class _Missing(object):
def __repr__(self):
return 'no value'
def __reduce__(self):
return '_missing' |
class DetrConfig(PretrainedConfig):
model_type = 'detr'
keys_to_ignore_at_inference = ['past_key_values']
attribute_map = {'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads'}
def __init__(self, num_queries=100, max_position_embeddings=1024, encoder_layers=6, encoder_ffn_dim=2048,... |
def test_init_objects():
trainer = SingleObjectiveTrainer(dataHandler, model, correctness_loss, validation_metrics, save_to_path, params)
assert (type(trainer._train_dataloader) == DataLoader)
assert (type(trainer.pareto_manager) == ParetoManager)
assert (trainer.pareto_manager.path == save_to_path)
... |
def get_optimizer(student, len_dataloader, args):
params_groups = get_params_groups(student)
if (args.optimizer == 'adamw'):
optimizer = torch.optim.AdamW(params_groups)
elif (args.optimizer == 'sgd'):
optimizer = torch.optim.SGD(params_groups, lr=0, momentum=0.9)
elif (args.optimizer ==... |
def thread_safe_generator(f):
def g(*a, **kw):
return ThreadSafeIter(f(*a, **kw))
return g |
def obtain_wikihow_step_task_occurrence(args, logger):
with open(os.path.join(args.wikihow_dir, 'step_label_text.json'), 'r') as f:
wikihow = json.load(f)
step_id = 0
step_id_to_article_po = defaultdict(tuple)
for article_id in range(len(wikihow)):
for article_step_idx in range(len(wikih... |
class DWCPatchEmbed(nn.Module):
def __init__(self, in_chans=3, embed_dim=768, patch_size=16, stride=1, act_layer=nn.Hardswish):
super().__init__()
self.patch_conv = DWConv2d_BN(in_chans, embed_dim, kernel_size=patch_size, stride=stride, act_layer=act_layer)
def forward(self, x):
x = self... |
class MaskedLMDictionary(Dictionary):
def __init__(self, pad='<pad>', eos='</s>', unk='<unk>', mask='<mask>'):
super().__init__(pad, eos, unk)
self.mask_word = mask
self.mask_index = self.add_symbol(mask)
self.nspecial = len(self.symbols)
def mask(self):
return self.mask_... |
def StochasticResNet56_08(num_classes=10):
return StochasticResNet(StochasticBlock, layers=([9] * 3), filters=[16, 32, 64], min_survival_rate=0.8, decay='linear', num_classes=num_classes) |
def dynamic_mix_data_prep(hparams):
train_data = sb.dataio.dataset.DynamicItemDataset.from_csv(csv_path=hparams['train_data'], replacements={'data_root': hparams['data_folder']})
(spk_hashtable, spk_weights) = build_spk_hashtable(hparams)
spk_list = [x for x in spk_hashtable.keys()]
spk_weights = [(x / ... |
def register_Ns3UlGrant_s_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::UlGrant_s const &', 'arg0')])
cls.add_instance_attribute('m_cqiRequest', 'bool', is_const=False)
cls.add_instance_attribute('m_hopping', 'bool', is_const=False)
cls.add_instance_attribute('m... |
class AuxData(Generic[T]):
def __init__(self, layout: (contents.Content | record.Record), is_highlevel: bool, behavior: (dict | None)=None):
self._layout = layout
self._behavior = behavior
self._is_highlevel = is_highlevel
def from_array_or_layout(cls, obj: T):
is_highlevel = isi... |
.parametrize('edges', (False, True))
.parametrize('texture', (False, True))
def test_multiscale_basic_features_gray(edges, texture):
img = np.zeros((20, 20))
img[:10] = 1
img += (0.05 * np.random.randn(*img.shape))
features = multiscale_basic_features(img, edges=edges, texture=texture)
n_sigmas = 6
... |
def get_version() -> str:
init = open(os.path.join('offlinerl', '__init__.py'), 'r').read().split()
return init[(init.index('__version__') + 2)][1:(- 1)] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.