code stringlengths 101 5.91M |
|---|
def privileged_information():
task = generate_task(task_generator_id='reaching')
env = CausalWorld(task=task, enable_visualization=True, normalize_actions=False)
env.expose_potential_partial_solution()
env.reset()
for _ in range(10):
goal_intervention_dict = env.sample_new_goal()
(su... |
class Plot(object):
def __init__(self, metrics, title, ylabel, xlabel='t', running_n=100):
self.vis = visdom.Visdom()
self.metrics = metrics
self.opts = dict(fillarea=False, xlabel=xlabel, ylabel=ylabel, title=title)
self.win = None
self.running_n = running_n
self.val... |
def is_valid(row):
if (row['agreement'] != 1):
return False
if (row['label'] == 'Neither'):
return False
return True |
class DiffusionPipeline(ConfigMixin):
config_name = 'model_index.json'
def register_modules(self, **kwargs):
from diffusers import pipelines
for (name, module) in kwargs.items():
library = module.__module__.split('.')[0]
pipeline_dir = module.__module__.split('.')[(- 2)]
... |
def getData(url):
try:
r = requests.get(url)
r.raise_for_status()
except:
print('Error while getting data from', url)
raise
return r.text |
class RDB(nn.Module):
def __init__(self, in_channels, num_dense_layer, growth_rate):
super(RDB, self).__init__()
_in_channels = in_channels
modules = []
for i in range(num_dense_layer):
modules.append(MakeDense(_in_channels, growth_rate))
_in_channels += growt... |
class ResUnetGenerator(NetworkBase):
def __init__(self, conv_dim=64, c_dim=5, repeat_num=6, k_size=4, n_down=2):
super(ResUnetGenerator, self).__init__()
self._name = 'resunet_generator'
self.repeat_num = repeat_num
self.n_down = n_down
encoders = []
encoders.append(n... |
def set_grad(params, params_with_grad):
for (param, param_w_grad) in zip(params, params_with_grad):
if (param.grad is None):
param.grad = torch.nn.Parameter(param.data.new().resize_(*param.data.size()))
param.grad.data.copy_(param_w_grad.grad.data) |
class InternalFortranAst():
def __init__(self, ast: f03.Program, tables: symbol_table.SymbolTables):
self.ast = ast
self.tables = tables
self.functions_and_subroutines = []
self.symbols = {}
self.types = {'LOGICAL': 'BOOL', 'CHARACTER': 'CHAR', 'INTEGER': 'INTEGER', 'INTEGER4... |
.experimental
def test_get_nearest_items(log):
model = ADMMSLIM(seed=SEED)
model.fit(log.filter((sf.col('item_idx') != 3)))
res = model.get_nearest_items(items=[0, 1], k=2, metric=None)
assert (res.count() == 4)
assert (set(res.toPandas().to_dict()['item_idx'].values()) == {0, 1})
res = model.ge... |
_function
def _bias_act_ref(x, b=None, dim=1, act='linear', alpha=None, gain=None, clamp=None):
assert isinstance(x, torch.Tensor)
assert ((clamp is None) or (clamp >= 0))
spec = activation_funcs[act]
alpha = float((alpha if (alpha is not None) else spec.def_alpha))
gain = float((gain if (gain is no... |
def get_log_prob_fn(model, model_args=(), model_kwargs={}, implementation='pyro', automatic_transform_enabled=False, transforms=None, max_plate_nesting=None, jit_compile=False, jit_options=None, skip_jit_warnings=False, **kwargs) -> (Callable, Dict[(str, Any)]):
if (transforms is None):
transforms = {}
... |
def test_execute_shell_allowlist_should_allow(agent: Agent, random_string: str):
agent.config.shell_command_control = sut.ALLOWLIST_CONTROL
agent.config.shell_allowlist = ['echo']
result = sut.execute_shell(f"echo 'Hello {random_string}!'", agent)
assert (('Hello' in result) and (random_string in result... |
def eval_iou(model, val_loader, logdir=None, epoch=0):
model.eval()
total_intersects = 0
total_union = 0
process_intersects = 0
process_union = 0
directory = os.path.join(logdir, 'vis')
if (not os.path.isdir(directory)):
os.makedirs(directory)
nums = 0
min_area_threshold = 22... |
def clean_replace(s, r, t, forward=True, backward=False):
def clean_replace_single(s, r, t, forward, backward, sidx=0):
idx = s.find(r)
if (idx == (- 1)):
return (s, (- 1))
idx_r = (idx + len(r))
if backward:
while ((idx > 0) and s[(idx - 1)]):
... |
def main(argv):
args = get_arg_parser().parse_args(sys.argv[1:])
if (not args.data_dir):
print('Data directory invalid.')
return
if (not args.route_name):
args.route_name = os.path.basename(args.data_dir)
args.data_dir = os.path.dirname(args.data_dir)
route = Route(args.r... |
def sample_from_categorical_distribution(batch_probs):
xp = chainer.cuda.get_array_module(batch_probs)
return xp.argmax((xp.log(batch_probs) + xp.random.gumbel(size=batch_probs.shape)), axis=1).astype(np.int32, copy=False) |
def conway_cross_product_doubled_power(self, p):
dim_list = [J.dim() for J in self.jordan_blocks_in_unimodular_list_by_scale_power(p)]
return sum(((((i - j) * dimi) * dim_list[j]) for (i, dimi) in enumerate(dim_list) for j in range(i))) |
def _Compare(t, symbols, inferred_symbols):
inf_type = _dispatch(t.left, symbols, inferred_symbols)
vec_len = None
if isinstance(inf_type, dtypes.vector):
vec_len = inf_type.veclen
for (o, e) in zip(t.ops, t.comparators):
if (o.__class__.__name__ not in cppunparse.CPPUnparser.cmpops):
... |
def eg_req_func(protocols: List['EntanglementProtocol'], args: Arguments) -> 'EntanglementGenerationA':
name = args['name']
reservation = args['reservation']
for protocol in protocols:
if (isinstance(protocol, EntanglementGenerationA) and (protocol.remote_node_name == name) and (protocol.rule.get_re... |
def test_plots():
plots = glob.glob('test_predictor_outputs/figures/*.png')
assert (len(plots) == 3) |
def sort_by_number_of_args(declaration, reverse=True):
def num_args(option):
return len(option['arguments'])
declaration['options'].sort(key=num_args, reverse=reverse) |
def count_congruence_solutions__good_type(self, p, k, m, zvec, nzvec):
return CountAllLocalTypesNaive(self, p, k, m, zvec, nzvec)[1] |
def test_input_error_related_to_feature_names():
pd = pytest.importorskip('pandas')
X = pd.DataFrame({'a': [0, 1, 2], 'b': [0, 1, 2]})
y = np.array([0, 1, 0])
monotonic_cst = {'d': 1, 'a': 1, 'c': (- 1)}
gbdt = HistGradientBoostingRegressor(monotonic_cst=monotonic_cst)
expected_msg = re.escape("... |
def transform_instance_annotations(annotation, transforms, image_size, *, keypoint_hflip_indices=None):
annotation = d2_transform_inst_anno(annotation, transforms, image_size, keypoint_hflip_indices=keypoint_hflip_indices)
if ('beziers' in annotation):
beziers = transform_beziers_annotations(annotation[... |
def register_Ns3SpectrumPhyHelper_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::SpectrumPhyHelper const &', 'arg0')])
cls.add_method('Create', 'ns3::Ptr< ns3::SpectrumPhy >', [param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::NetDevice >', 'device')], is_con... |
def register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter< ns3::AttributeChecker > > const &', 'o')])
... |
class TwoLayerRio(nn.Module):
def __init__(self, num_classes, inter1, inter2, lambda_1, last_label_scores):
super(TwoLayerRio, self).__init__()
self.inter1 = inter1
self.inter2 = inter2
self.xent = nn.CrossEntropyLoss()
self.weight = nn.Parameter(torch.FloatTensor(num_classes... |
class PygLinkPropPredDataset(InMemoryDataset):
def __init__(self, name, root='dataset', transform=None, pre_transform=None, meta_dict=None):
self.name = name
if (meta_dict is None):
self.dir_name = '_'.join(name.split('-'))
if osp.exists(osp.join(root, (self.dir_name + '_pyg'... |
def get_optimizer(opt, model):
if (opt.optim == 'adam'):
optimizer = torch.optim.Adam(model.parameters(), opt.lr)
elif (opt.optim == 'sgd'):
print('Using SGD')
optimizer = torch.optim.SGD(model.parameters(), opt.lr, momentum=0.9, weight_decay=0.0001)
else:
assert 0, opt.optim... |
def fromqpixmap(im):
from . import ImageQt
if (not ImageQt.qt_is_installed):
raise ImportError('Qt bindings are not installed')
return ImageQt.fromqpixmap(im) |
def distorted_bounding_box_crop(image, bbox, min_object_covered=0.1, aspect_ratio_range=(0.75, 1.33), area_range=(0.05, 1.0), max_attempts=100, scope=None):
with tf.name_scope((scope or 'distorted_bounding_box_crop')):
shape = tf.shape(image)
sample_distorted_bounding_box = tf.image.sample_distorted... |
def replace_xml_entities(text):
for (c, r) in xml_entities.items():
text = text.replace(c, r)
return text |
class IntegerModFactory(UniqueFactory):
def get_object(self, version, key, extra_args):
out = super().get_object(version, key, extra_args)
category = extra_args.get('category', None)
if (category is not None):
out._refine_category_(category)
out._factory_data[3]['cate... |
def encode_param_command(args, **kwargs):
in_files = [f for f in os.listdir(args.indir) if os.path.isfile(os.path.join(args.indir, f))]
logger.log(99, 'Loading parameters...')
for file_path in in_files:
key = urllib.parse.unquote(os.path.splitext(file_path)[0].replace('~', '/'))
logger.log(9... |
def test_slice():
with goos.OptimizationPlan() as plan:
x = goos.Variable([[0, 1, 2, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25]])
t = goos.Slice(x, ['c', 'c'])
np.testing.assert_allclose(t.get().array, 13)
g = np.array([[0, 0, 0, 0, 0], ... |
.parametrize('ty,num', add_table)
_utils.test(arch=[ti.cpu, ti.cuda, ti.vulkan], debug=True)
def test_add_no_overflow(capfd, ty, num):
if (not supports_overflow(ti.lang.impl.current_cfg().arch)):
return
capfd.readouterr()
def foo() -> ty:
a = ty(num)
b = ty((num - 1))
return ... |
class UnusedParamTwoLinLayerNet(nn.Module):
def __init__(self):
super().__init__()
self.a = nn.Linear(10, 10, bias=False)
self.b = nn.Linear(10, 10, bias=False)
self.c = nn.Linear(5, 5, bias=False)
def forward(self, x):
a = self.a(x)
b = self.b(x)
return (... |
def pt_repeat_n_times(niters):
for _ in range(niters):
for (input_tensor, repeat) in zip(input_tensors, repeats):
pt_repeat(input_tensor, repeat) |
def import_loader(opt):
dataset_name = (opt.model_task.upper() + 'Data')
dataset = getattr(import_module('data'), dataset_name)
if (opt.task == 'train'):
train_inp_path = opt.config['train']['train_inp']
train_gt_path = opt.config['train']['train_gt']
valid_inp_path = opt.config['tra... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--train_corpus', default=None, type=str, required=True, help='The input train corpus.')
parser.add_argument('--bert_model', default=None, type=str, required=True, help='Bert pre-trained model selected in the list: bert-base-uncased, bert-la... |
def get_split_list(in_dim, child_num):
in_dim_list = ([(in_dim // child_num)] * child_num)
for _i in range((in_dim % child_num)):
in_dim_list[_i] += 1
return in_dim_list |
def cached_path(url_or_filename, cache_dir=None):
if (cache_dir is None):
cache_dir = PYTORCH_PRETRAINED_BERT_CACHE
if ((sys.version_info[0] == 3) and isinstance(url_or_filename, Path)):
url_or_filename = str(url_or_filename)
if ((sys.version_info[0] == 3) and isinstance(cache_dir, Path)):
... |
class CopyCheckTester(unittest.TestCase):
def setUp(self):
self.transformer_dir = tempfile.mkdtemp()
os.makedirs(os.path.join(self.transformer_dir, 'models/bert/'))
check_copies.TRANSFORMER_PATH = self.transformer_dir
shutil.copy(os.path.join(git_repo_path, 'src/transformers/models/b... |
_cmd.command('client')
('-d', '--discoverhost', required=False, help='Hostname for discovery services(reducer).')
('-p', '--discoverport', required=False, help='Port for discovery services (reducer).')
('--token', required=False, help='Set token provided by reducer if enabled')
('-n', '--name', required=False, default=... |
def get_number_of_leaves_from_tree(alidir):
stdout = get_command_stdout('tree-info {0}/tree 2>/dev/null | grep num-pdfs'.format(alidir))
parts = stdout.split()
assert (parts[0] == 'num-pdfs')
num_leaves = int(parts[1])
if (num_leaves == 0):
raise Exception('Number of leaves is 0')
return... |
.parametrize('deriv_type', ('sigma', 'h', 'both'))
def test_adjoint(deriv_type):
n_layer = 4
np.random.seed(40)
log_cond = np.random.rand(n_layer)
log_thick = np.random.rand((n_layer - 1))
if (deriv_type != 'h'):
sigma_map = maps.ExpMap()
model = log_cond
sigma = None
els... |
def save_gray_numpy(data, index=0):
while (len(data.shape) > 2):
data = data[0]
if ((data.max() <= 1) and (data.min() >= 0)):
data = (data * 255)
out_path = os.path.join(str(folder), ('%05d.png' % index))
cv2.imwrite(out_path, data)
print(('Saved debug image to ' + out_path)) |
def flops_analysis_options(output_dir):
options = model_analyzer.TRAINABLE_VARS_PARAMS_STAT_OPTIONS.copy()
options['select'] = ['float_ops', 'micros', 'device']
options['min_float_ops'] = 1
options['order_by'] = 'float_ops'
options['account_type_regexes'] = ['.*']
if output_dir:
options[... |
def find_usages(query_att, query_file, lst_key_att, key_file):
usages = []
query_str = get_string(query_file, query_att[0], query_att[1])
for key_att in lst_key_att:
key_str = get_string(key_file, key_att[0], key_att[1])
if (key_str == query_str):
usages.append(key_att)
retur... |
()
('--seed', default=1)
('--epochs', default=500)
('--batch_size', default=1024)
_experiment(snapshot_mode='all')
def mtppo_metaworld_ml1_push(ctxt, seed, epochs, batch_size):
set_seed(seed)
env = GarageEnv(normalize(mwb.ML1.get_train_tasks('push-v1')))
policy = GaussianMLPPolicy(env_spec=env.spec, hidden_... |
class IterMeter(object):
def __init__(self):
self.val = 0
def step(self):
self.val += 1
def get(self):
return self.val |
def to_tensor(wrapped_func):
def func(*args, **kwargs):
result = wrapped_func(*args, **kwargs)
return {k: torch.tensor(v, dtype=torch.float) for (k, v) in result.items()}
return func |
def _test_func2d_nograd(x):
f = (((cos(((14.5 * x[0]) - 0.3)) + ((x[1] + 0.2) * x[1])) + ((x[0] + 0.2) * x[0])) + 1.)
return f |
class ImageClassifierCLI(CLI):
def add_arguments_to_parser(self, parser: LightningArgumentParser) -> None:
super().add_arguments_to_parser(parser)
parser.link_arguments('data.num_classes', 'model.num_classes', apply_on='instantiate')
parser.link_arguments('data.image_shape', 'model.image_sha... |
class TapasForMaskedLM():
def __init__(self, *args, **kwargs):
requires_pytorch(self)
def from_pretrained(self, *args, **kwargs):
requires_pytorch(self) |
def register_Ns3UanPhyListener_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::UanPhyListener const &', 'arg0')])
cls.add_method('NotifyCcaEnd', 'void', [], is_pure_virtual=True, is_virtual=True)
cls.add_method('NotifyCcaStart', 'void', [], is_pure_virtual=True, is_vi... |
def _do_python_eval_corloc(json_dataset, salt, output_dir='output'):
info = voc_info(json_dataset)
year = info['year']
anno_path = info['anno_path']
image_set_path = info['image_set_path']
devkit_path = info['devkit_path']
cachedir = os.path.join(devkit_path, 'annotations_cache')
corlocs = [... |
class HTTPVersionNotSupported(HTTPException):
code = 505
description = 'The server does not support the HTTP protocol version used in the request.' |
class MultiWozEvaluator(BaseEvaluator):
def __init__(self, data_name):
self.data_name = data_name
self.slot_dict = delex.prepareSlotValuesIndependent()
self.delex_dialogues = json.load(open('resources/multi-woz-2.1/delex.json', 'r'))
self.db = MultiWozDB()
self.labels = list(... |
def get_sentence_markup(sentence, layer, markup):
doc_name = sentence.document.name
if ((doc_name not in markup) or (layer not in markup[doc_name]) or (sentence.position not in markup[doc_name][layer]) or (markup[doc_name][layer][sentence.position] == None)):
return []
return sorted(markup[doc_name]... |
class Function_beta(GinacFunction):
def __init__(self):
GinacFunction.__init__(self, 'beta', nargs=2, latex_name='\\operatorname{B}', conversions=dict(maxima='beta', mathematica='Beta', maple='Beta', sympy='beta', fricas='Beta', giac='Beta'))
def _method_arguments(self, x, y):
return [x, y] |
class StackLayers(nn.Module):
def __init__(self, num_block_layers, dropped_mixed_ops, softmax_temp=1.0):
super(StackLayers, self).__init__()
if (num_block_layers != 0):
self.stack_layers = nn.ModuleList()
for i in range(num_block_layers):
self.stack_layers.app... |
def test_RecordArray_getitem():
array = ak.highlevel.Array([{'x': 0.0, 'y': []}, {'x': 1.1, 'y': [1]}, {'x': 2.2, 'y': [2, 2]}, {'x': 3.3, 'y': [3, 3, 3]}, {'x': 4.4, 'y': [4, 4, 4, 4]}], check_valid=True)
def f1(x, i):
return x[i]
assert (ak.operations.to_list(f1(array, 3)) == {'x': 3.3, 'y': [3, 3... |
def _run_task(test_template: Callable, tasks_queue: Queue, events_queue: Queue, generator_done: threading.Event, checks: Iterable[CheckFunction], targets: Iterable[Target], data_generation_methods: Iterable[DataGenerationMethod], settings: hypothesis.settings, generation_config: GenerationConfig, seed: (int | None), re... |
def build_regularization_map(volume, threshold, rw0, rw1):
data = np.array(volume, copy=False)
regmap = np.zeros(data.shape, dtype=np.float32)
regmap = ((rw0 * (data < threshold)) + (rw1 * (data >= threshold))).astype(np.float32)
regmap = pydeform.Volume(regmap)
regmap.copy_meta_from(volume)
ret... |
def _is_packed_list(list_value):
return (_is_value(list_value) and (list_value.node().kind() == 'prim::ListConstruct')) |
def _assemble_arrayl(lines, stretch=None):
return LatexExpr(((((('' if generate_real_LaTeX else '%notruncate\n') + ('' if (stretch is None) else ('\\renewcommand{\\arraystretch}{%f}\n' % stretch))) + '\\begin{array}{l}\n') + '\\\\\n'.join(lines)) + '\n\\end{array}')) |
def parse_lexicon(line: str) -> Tuple[(str, List[str])]:
line.replace('\t', ' ')
(word, *phonemes) = line.split()
return (word, phonemes) |
def plot_sqlite_db(sqliteConnection: Engine, analyze: bool=False):
db_name = os.path.splitext(os.path.basename(sqliteConnection.url.database))[0]
schema_name = []
schema_name.append(db_name)
if analyze:
sqliteConnection.execute('ANALYZE')
try:
version_sql = pd.read_sql('select sqlite... |
class Callback(EntryBase):
def __init__(self, j):
super().__init__(j, 'callback')
self.return_value_type = None
self.params = []
if ('parameters' in j):
for x in j['parameters']:
field = Field(x)
if (field.name.snake_case == ''):
... |
def check_database_table(db_name):
conn = sqlite3.connect(db_name)
conn.row_factory = sqlite3.Row
c = conn.cursor()
c.execute("SELECT name FROM sqlite_master WHERE type='table';")
if (len(c.fetchall()) == 0):
create_bot_test_database(db_name) |
def load_fvd_model(device):
i3d = InceptionI3d(400, in_channels=3).to(device)
current_dir = os.path.dirname(os.path.abspath(__file__))
i3d_path = os.path.join(current_dir, 'i3d_pretrained_400.pt')
i3d.load_state_dict(torch.load(i3d_path, map_location=device))
i3d.eval()
return i3d |
def rerank(model_file, ctx_file, rnk_file, score=False):
pstree = cacb.CACBInfer()
pstree.load(model_file)
output_file = open(((rnk_file + '_CACB') + ('.f' if score else '.gen')), 'w')
begin = True
for (num_line, (ctx_line, rnk_line)) in enumerate(itertools.izip(open(ctx_file), open(rnk_file))):
... |
class TFAutoModelForSequenceClassification(object):
def __init__(self):
raise EnvironmentError('TFAutoModelForSequenceClassification is designed to be instantiated using the `TFAutoModelForSequenceClassification.from_pretrained(pretrained_model_name_or_path)` or `TFAutoModelForSequenceClassification.from_co... |
def list_fnames():
base_path = os.path.dirname(__file__)
return [os.path.join(base_path, fname) for fname in os.listdir(base_path) if fname.endswith('.conf')] |
def get_plot_font_size(font_size: Optional[int], figure_size: Tuple[(int, int)]) -> int:
if (font_size is None):
font_size = 10
if (max(figure_size) >= 256):
font_size = 12
if (max(figure_size) >= 512):
font_size = 15
return font_size |
def test_bytearray():
array = ak.contents.NumpyArray(np.frombuffer(b'hellothere', 'u1'), parameters={'__array__': 'byte'})
assert (ak.operations.to_json(array, convert_bytes=bytes.decode) == '"hellothere"') |
class Conv2dBlock(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0):
super().__init__()
self.m = conv2d(in_channels, out_channels, kernel_size, stride, padding, bias=True, weight_init='kaiming')
def forward(self, x):
x = self.m(x)
return ... |
class InstrWorld(object):
sheet_name = 'Instr World'
def __init__(self, reg_list, columns, writer, split=False):
self.reg_list = reg_list
self.columns = columns
self.writer = writer
self.split = split
self.index = 1
def write(self, out_file):
df = pd.DataFrame... |
class TensorFlowBenchmarkArguments(metaclass=DummyObject):
_backends = ['tf']
def __init__(self, *args, **kwargs):
requires_backends(self, ['tf']) |
def simGetJointTargetVelocity(jointHandle):
vel = ffi.new('float *')
lib.simGetJointTargetVelocity(jointHandle, vel)
return vel[0] |
def probable_pivot_columns(A):
p = ZZ.random_element(10007, 46000).next_prime()
return A._reduce(p).pivots() |
def build_dict(imgs, wtoi, params):
wtoi['<eos>'] = 0
count_imgs = 0
refs_words = []
refs_idxs = []
for img in imgs:
if ((params['split'] == img['split']) or ((params['split'] == 'train') and (img['split'] == 'restval')) or (params['split'] == 'all')):
ref_words = []
... |
class ROIBoxHead(torch.nn.Module):
def __init__(self, cfg, in_channels):
super(ROIBoxHead, self).__init__()
self.feature_extractor = make_roi_box_feature_extractor(cfg, in_channels)
self.predictor = make_roi_box_predictor(cfg, self.feature_extractor.out_channels)
self.post_processor ... |
def vgg_16(inputs, num_classes=1000, is_training=True, dropout_keep_prob=0.5, spatial_squeeze=True, scope='vgg_16', fc_conv_padding='VALID', global_pool=False):
with tf.variable_scope(scope, 'vgg_16', [inputs]) as sc:
end_points_collection = (sc.original_name_scope + '_end_points')
with slim.arg_sco... |
def _check_executable(cmd):
if (subprocess.call(f'which {cmd}', shell=True) != 0):
return False
else:
return True |
def unfold_dict_recursively(_dict, run_no, num_training_runs):
row = {}
for entry in _dict:
if (type(_dict[entry]) == dict):
row.update(unfold_dict_recursively(_dict[entry], run_no, num_training_runs))
elif ((type(_dict[entry]) == list) and (len(_dict[entry]) == num_training_runs)):
... |
_task('wsc')
class WSCTask(FairseqTask):
def add_args(parser):
parser.add_argument('data', metavar='DIR', help='path to data directory; we load <split>.jsonl')
parser.add_argument('--init-token', type=int, default=None, help='add token at the beginning of each batch item')
def __init__(self, arg... |
class fx2mlir(object):
def __init__(self, submodule_name: str, args: Namespace, bwd_graph: bool):
self.work_dir = submodule_name.split('_')[0]
tmp = ('bwd' if bwd_graph else 'fwd')
self.model_name = f'{submodule_name}_{tmp}'
self.args = args
self.bwd = bwd_graph
self.... |
class HardMishJitAutoFn(torch.autograd.Function):
def forward(ctx, x):
ctx.save_for_backward(x)
return hard_mish_jit_fwd(x)
def backward(ctx, grad_output):
x = ctx.saved_tensors[0]
return hard_mish_jit_bwd(x, grad_output) |
class AmpProblemTest(unittest.TestCase):
def setUp(self):
H0 = (50000.0, 90.0, 0.0)
M = np.array([45.0, 90.0])
chi_e = 0.05
[xx, yy] = np.meshgrid(np.linspace((- 200), 200, 50), np.linspace((- 200), 200, 50))
b = 100
A = 50
zz = (A * np.exp(((- 0.5) * (((xx / ... |
def clip_gradient(optimizer, grad_clip):
assert (grad_clip > 0), 'gradient clip value must be greater than 1'
for group in optimizer.param_groups:
for param in group['params']:
if (param.grad is None):
continue
param.grad.data.clamp_((- grad_clip), grad_clip) |
def _chi(state: State, action):
c_p = state.current_player
tar_p = ((c_p + 3) % 4)
tar = state._target
state = _accept_riichi(state)
meld = Meld.init(action, tar, src=jnp.int32(3))
state = _append_meld(state, meld, c_p)
hand = state._hand.at[c_p].set(Hand.chi(state._hand[c_p], tar, action))
... |
def parse_xml(tree):
documents = []
root = tree.getroot()
for document in root:
if (document.tag != 'document'):
raise ValueError('Unexpected orchid xml layout: {}'.format(document.tag))
paragraphs = []
for paragraph in document:
if (paragraph.tag != 'paragrap... |
def _edge_matcher(digraph, nxpattern, node_pred, edge_pred):
pedge = next(iter(nxpattern.edges))
pu = nxpattern.nodes[pedge[0]]
pv = nxpattern.nodes[pedge[1]]
if (edge_pred is None):
for (u, v) in digraph.edges:
if (node_pred(digraph.nodes[u], pu) and node_pred(digraph.nodes[v], pv))... |
class sfftw_threads_info(fftw_info):
section = 'fftw'
dir_env_var = 'FFTW'
ver_info = [{'name': 'sfftw threads', 'libs': ['srfftw_threads', 'sfftw_threads'], 'includes': ['sfftw_threads.h', 'srfftw_threads.h'], 'macros': [('SCIPY_SFFTW_THREADS_H', None)]}] |
def mobilenet_v1_arg_scope(is_training=True, weight_decay=4e-05, stddev=0.09, regularize_depthwise=False, batch_norm_decay=0.9997, batch_norm_epsilon=0.001):
batch_norm_params = {'center': True, 'scale': True, 'decay': batch_norm_decay, 'epsilon': batch_norm_epsilon}
if (is_training is not None):
batch_... |
class TilingStrategyDummy(TilingStrategy):
def get_number_of_spatial_sample_per_image(self):
return 1
def get_window(self, idx):
return None |
class TensorDataset(torch.utils.data.Dataset):
def __init__(self, images, labels, transform=None):
self.images = images.detach().cpu().float()
self.targets = labels.detach().cpu()
self.transform = transform
def __getitem__(self, index):
sample = self.images[index]
if (sel... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.