code
stringlengths
101
5.91M
.parametrize('observation_shape', [(100,)]) .parametrize('action_size', [10]) .parametrize('batch_size', [32]) .parametrize('eps', [0.3]) def test_standard_reward_scaler_with_transition_picker(observation_shape: Sequence[int], action_size: int, batch_size: int, eps: float) -> None: shape = (batch_size, *observation...
def _tensorviewer_from_slices(target_slices, names, batch_size): default_backend = pyhf.default_backend ranges = [] for sl in target_slices: ranges.append(default_backend.astensor(range(sl.start, sl.stop))) if (not target_slices): return None return _TensorViewer(ranges, names=names,...
class TwoMaxLayerPoolingAggregator(Layer): def __init__(self, input_dim, output_dim, model_size='small', neigh_input_dim=None, dropout=0.0, bias=False, act=tf.nn.relu, name=None, concat=False, **kwargs): super(TwoMaxLayerPoolingAggregator, self).__init__(**kwargs) self.dropout = dropout self...
class TestPruningInfo(unittest.TestCase): def setUp(self): self.mock_pruning_masks = {'Layer1': np.array([1, 0, 1]), 'Layer2': np.array([0, 1])} self.mock_importance_scores = {'Layer1': np.array([0.5, 0.3, 0.7]), 'Layer2': np.array([0.2, 0.8])} self.pruning_info = mct.pruning.PruningInfo(sel...
class VisionDataset(Dataset): preprocess = transforms.Compose([transforms.Resize((IMAGE_SIZE, IMAGE_SIZE)), transforms.ToTensor(), transforms.Normalize(mean=MEAN, std=STD)]) def __init__(self, image_paths: list): self.image_paths = image_paths def __getitem__(self, idx): return self.preproce...
def kmax_pooling(x, dim, k): index = x.topk(k, dim=dim)[1].sort(dim=dim)[0] return x.gather(dim, index).squeeze(dim)
def get_crfrnn_model_def(): (channels, height, width) = (3, 500, 500) input_shape = (height, width, 3) img_input = Input(shape=input_shape) x = ZeroPadding2D(padding=(100, 100))(img_input) x = Conv2D(64, (3, 3), activation='relu', padding='valid', name='conv1_1')(x) x = Conv2D(64, (3, 3), activa...
class ManifoldSubsetClosure(ManifoldSubset): def __init__(self, subset, name=None, latex_name=None): self._subset = subset base_manifold = subset.manifold() if (latex_name is None): if (name is None): latex_name = (('\\mathop{\\mathrm{cl}}(' + subset._latex_name) ...
def get_model_name(config): name = '' spec = config.MODEL.SPEC if (config.MODEL.NAME in ['cls_resnet', 'cls_resnet_d2']): num_groups = spec.NUM_GROUPS depth = spec.NUM_LAYERS if (num_groups == 1): model_type = 'r{}'.format(depth) else: model_type = 'x{...
def testval(config, test_dataset, testloader, model, sv_dir='', sv_pred=False): model.eval() confusion_matrix = np.zeros((config.DATASET.NUM_CLASSES, config.DATASET.NUM_CLASSES)) with torch.no_grad(): for (index, batch) in enumerate(tqdm(testloader)): (image, label, _, name) = batch ...
def get_matrix_variance(opset, graph, func_input, func_name, mean_out, axes, input_shape): nl = [] sub_out = fork_name((func_input + '_sub')) n = onnx.helper.make_node('Sub', [func_input, mean_out], [sub_out]) nl.append(n) mul_out = fork_name((func_input + '_mul')) n = onnx.helper.make_node('Mul...
def hist_viz(hist: List[Tuple[(np.ndarray, np.ndarray)]], nrows: List[int], col: str, yscale: str, plot_width: int, plot_height: int, show_yticks: bool, df_labels: List[str], orig: Optional[List[str]]=None) -> Figure: tooltips = [('Bin', ''), ('Frequency', ''), ('Percent', '{0.2f}%'), ('Source', '')] fig = Figu...
def get_platform_toolset_str(): default = 'v110' vstr = check_output(['msbuild', '/ver']) lines = vstr.split('\n') lline = lines[(- 1)] tokens = lline.split('.') if (len(tokens) < 2): return default elif (tokens[0] == '15'): return 'v141' else: return (('v' + toke...
def check_eol(filename): eol = u'\n' with open(filename, 'rb') as f: d = f.read() if (b'\r\n' in d): eol = u'\r\n' elif (b'\n' in d): eol = u'\n' elif (b'\r' in d): eol = u'\r' return eol
class BaseModel(ABC): def __init__(self, opt): self.opt = opt self.gpu_ids = opt.gpu_ids self.isTrain = opt.isTrain self.device = (torch.device('cuda:{}'.format(self.gpu_ids[0])) if self.gpu_ids else torch.device('cpu')) self.save_dir = os.path.join(opt.checkpoints_dir, opt.n...
def ResNet101(input_channels=3, imsize=32, output_dim=10): return ResNet(Bottleneck, [3, 4, 23, 3], input_channels, imsize, output_dim)
class TFAutoModelForZeroShotImageClassification(_BaseAutoModelClass): _model_mapping = TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
def _palette_is_grayscale(pil_image): if (pil_image.mode != 'P'): raise ValueError('pil_image.mode must be equal to "P".') palette = np.asarray(pil_image.getpalette()).reshape(((- 1), 3)) (start, stop) = pil_image.getextrema() valid_palette = palette[start:(stop + 1)] return np.allclose(np.d...
class FileSequence(AppendableSequence, Closeable): def __init__(self, path, serializer=None): if (serializer is None): serializer = UnicodeSerializer() self._path = path self._ser = serializer self._f_read = open_or_create(path, 'r') self._f_write = open_or_create...
class SpacyTokenizer(Tokenizer): def __init__(self, **kwargs): model = kwargs.get('model', 'en') self.annotators = copy.deepcopy(kwargs.get('annotators', set())) nlp_kwargs = {'parser': False} if (not any([(p in self.annotators) for p in ['lemma', 'pos', 'ner']])): nlp_kw...
def env_1(): env = Warehouse(3, 8, 3, 2, 0, 1, 5, None, None, RewardType.GLOBAL) env.reset() env.agents[0].x = 4 env.agents[0].y = 27 env.agents[0].dir = Direction.DOWN env.shelfs[0].x = 4 env.shelfs[0].y = 27 env.agents[0].carrying_shelf = env.shelfs[0] env.agents[1].x = 3 env.a...
def inception_v2_base(inputs, final_endpoint='Mixed_5c', min_depth=16, depth_multiplier=1.0, scope=None): end_points = {} if (depth_multiplier <= 0): raise ValueError('depth_multiplier is not greater than zero.') depth = (lambda d: max(int((d * depth_multiplier)), min_depth)) with tf.variable_sc...
class ResultVisualizer(): def __init__(self, show=False, wait_time=0, score_thr=0): self.show = show self.wait_time = wait_time self.score_thr = score_thr def _save_image_gts_results(self, dataset, results, mAPs, out_dir=None): mmcv.mkdir_or_exist(out_dir) for mAP_info in...
class DBEngine(): def __init__(self, fdb): self.db = records.Database('sqlite:///{}'.format(fdb)) def execute_query(self, table_id, query, *args, **kwargs): return self.execute(table_id, query.sel_index, query.agg_index, query.conditions, *args, **kwargs) def execute(self, table_id, select_i...
class NavierStokesIRK3(IRK3): def __init__(self, N=(10, 10), dt=0.01, Re=100.0, modplot=10, family='C'): self.Re = Re self.nu = (2.0 / Re) self.N = N self.dt = dt self.modplot = modplot D0 = FunctionSpace(N[0], family, bc=(0, 0)) D1 = FunctionSpace(N[1], famil...
def trunc_normal_(tensor, mean=0.0, std=1.0, a=(- 2.0), b=2.0): return _no_grad_trunc_normal_(tensor, mean, std, a, b)
class BertBaseline(BaseModel): def __init__(self, vocab=None, bert_dir='', version_2_with_negative=True): super(BertBaseline, self).__init__(vocab) self.bert_dir = bert_dir self.version_2_with_negative = version_2_with_negative self._build_graph() def _build_graph(self): ...
class PDELU_SENet(nn.Module): def __init__(self, block, num_blocks, num_classes=100): super(PDELU_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...
class CDilatedB(nn.Module): def __init__(self, nIn, nOut, kSize, stride=1, d=1, groups=1): super().__init__() padding = (int(((kSize - 1) / 2)) * d) self.conv = nn.Conv2d(nIn, nOut, kSize, stride=stride, padding=padding, bias=False, dilation=d, groups=groups) self.bn = nn.BatchNorm2d...
class WFRadiationMeshQxMax(RadiationField): glossary_name = 'params/Mesh/qxMax' def __init__(self, wf): super(WFRadiationMeshQxMax, self).__init__(wf) def value(self): if (self._wf.params.wSpace == 'Q-space'): return self._wf._srwl_wf.mesh.xFin else: warnings....
((GRAPH_EXECUTOR == ProfilingMode.SIMPLE), "Simple Executor doesn't support gradients") class TestAutodiffSubgraphSlicing(JitTestCase): def _perform_ad_subgraph_slicing(self, fn, *input_sizes): with disable_autodiff_subgraph_inlining(): with enable_profiling_mode_for_profiling_tests(): ...
def split_dataset(x, y, ratio=[0.7, 0.15, 0.15]): flags = [] data_len = len(x) flag += 1 lens = [int((data_len * item)) for item in ratio] new_flag = flag (trainX, trainY) = (x[:lens[0]], y[:lens[0]]) flag += 2 (testX, testY) = (x[lens[0]:(lens[0] + lens[1])], y[lens[0]:(lens[0] + lens[1...
def compute_rouge_scores(summs, refs, splitchar='.', options=None, parallel=True): assert (len(summs) == len(refs)) options = ['-a', '-c', 95, '-m', '-n', 2, '-w', 1.3] rr = Rouge(options=options) rouge_args = [] for (summ, ref) in zip(summs, refs): letter = 'A' ref_dict = {} ...
def register_metrics(types, device, has_detector=True): global TYPES, METRIC_DICT metric_dict = dict() for name in types: assert (name in TYPES) if (name in METRIC_DICT): metric_dict[name] = METRIC_DICT[name] continue if (name == 'ssim'): metric_di...
def logmethod(f): (f) def wrapper(self, *args, **kwds): debug_log(('%s in %s called' % (f.__name__, self.__class__.__name__))) return f(self, *args, **kwds) return wrapper
.gpu def test_dropout_vec(): _config() def halftest(A: dace.float16[N], mask: dace.float16[N]): out = np.ndarray([N], dace.float16) for i in dace.map[0:N]: with dace.tasklet: (a << A[i]) (d << mask[i]) (o >> out[i]) o = ...
.overload_method(IndexedOptionType, '_index', inline='always') def IndexedOption_index(builder): def getter(builder): return builder._index return getter
def test_NS2D(args): config.update({'nu': 0.01, 'dt': 0.05, 'T': 10}, 'doublyperiodic') solver = get_solver(regression_test=regression_test, mesh='doublyperiodic', parse_args=args) context = solver.get_context() initialize(solver, **context) solve(solver, context) config.params.dealias = '3/2-ru...
def get_scores(tokens, model, device, tokenizer, sequence_length, slide_by): chunk_list = list(chunks(tokens, 512)) toks = list() for c in chunk_list: toks += tokenizer.convert_tokens_to_ids(c) test_sequences = list() test_labels_dummy = list() test_token_indices = list() idx = 0 ...
def convert_cityscapes_instance_only(data_dir, out_dir): sets = ['gtFine_val'] ann_dirs = ['gtFine_trainvaltest/gtFine/val'] json_name = 'instancesonly_filtered_%s.json' ends_in = '%s_polygons.json' img_id = 0 ann_id = 0 cat_id = 1 category_dict = {} category_instancesonly = ['person...
class WEBVIDDataset(BaseDataset): def __init__(self, *args, split='', **kwargs): assert (split in ['train', 'val', 'test']) self.split = split self.metadata = None self.cut = 'jsfusion' if (split == 'train'): names = ['webvid_train'] elif (split == 'val'):...
def test_array_by_str_key(): class AClass(): def __init__(self): self.adict = dict(akey=(7.0 * np.ones((10,)))) def __call__(self, A): A[...] = self.adict['akey'] aobj = AClass() arr = np.empty((10,)) aobj(arr) assert np.allclose(7.0, arr)
def run_all(sizes={'b': 8, 'h': 16, 'i': 1024, 'j': 512, 'k': 512, 'p': 64, 'u': 4096, 'q': 3, 'v': 2}, output='.'): runtest('Q', 'phi,ibj->phbj', sizes=sizes, output_dir=output) runtest('lin1', 'bji,ui->bju', sizes=sizes, output_dir=output) runtest('lin2', 'bju,iu->bji', sizes=sizes, output_dir=output) ...
def create_diag_(A, diag): n = A.size(0) diag_z = torch.zeros((n - 1)) diag_z[::2] = diag A_init = torch.diag(diag_z, diagonal=1) A_init = (A_init - A_init.T) with torch.no_grad(): A.copy_(A_init) return A
class CompositionSpeciesStructure(GenericSpeciesStructure): def __init__(self, parent, labels, pi, f, gs): self._partition = pi GenericSpeciesStructure.__init__(self, parent, labels, [f, gs]) def __repr__(self): (f, gs) = self._list return ('F-structure: %s; G-structures: %s' % (...
def encoder(x, reuse=False): with tf.name_scope('model_xyz'): x = tflearn.layers.conv.conv_2d(x, 16, (3, 3), strides=1, activation='relu', weight_decay=1e-05, regularizer='L2', reuse=reuse, scope='conv1_1') x = tflearn.layers.conv.conv_2d(x, 16, (3, 3), strides=1, activation='relu', weight_decay=1e-...
class ValAndGradFn(Protocol[(M, X)]): def __call__(self, model: M, *inputs: X, **input_kwargs) -> Tuple[(float, M)]: ...
def autolabel(rects, counts): for (ii, rect) in enumerate(rects): height = rect.get_height() plt.text((rect.get_x() + (rect.get_width() / 2.0)), (1.02 * height), f'{counts[ii]:.2f}', ha='center', va='bottom')
def evaluate(label_path, result_path, label_split_file, current_class=0, coco=False, score_thresh=(- 1)): dt_annos = kitti.get_label_annos(result_path) if (score_thresh > 0): dt_annos = kitti.filter_annos_low_score(dt_annos, score_thresh) val_image_ids = _read_imageset_file(label_split_file) gt_...
.mujoco class TestRL2PPO(TfGraphTestCase): def setup_method(self): super().setup_method() self.max_path_length = 100 self.meta_batch_size = 10 self.episode_per_task = 4 self.tasks = task_sampler.SetTaskSampler((lambda : RL2Env(env=normalize(HalfCheetahDirEnv())))) sel...
def test_complex_with_nan_and_inf(): content = ak.contents.NumpyArray(np.array([(1.1 + 0.1j), 2.2, 3.3, (np.nan + (1j * np.nan)), 5.5, (- np.inf), 7.7, (np.inf + (1j * np.inf)), 9.9])) assert (ak.operations.to_json(content, complex_record_fields=('r', 'i'), nan_string='Not a number', posinf_string='Inf', neginf...
.parametrize('dtype', [np.float64, np.int64, np.uint8, None]) .parametrize('like_dtype', [np.float64, np.int64, np.uint8, None]) def test_zeros_like(dtype, like_dtype): array = ak.contents.numpyarray.NumpyArray(np.array([99, 88, 77, 66, 66], dtype=dtype)) full = ak.zeros_like(array.to_typetracer(), dtype=like_d...
def passages2text(passages: Union[(str, list, tuple)]) -> str: if isinstance(passages, str): return passages assert (type(passages) in [list, tuple]) if (len(passages) == 0): return 'N/A' if (len(passages) == 1): return f'{passages[0]}' return '\n'.join([f'[{(idx + 1)}] {txt}...
class Generator(nn.Module): def __init__(self, img_size=256, style_dim=64, max_conv_dim=512, w_hpf=1): super().__init__() dim_in = ((2 ** 14) // img_size) self.img_size = img_size self.from_rgb = nn.Conv2d(3, dim_in, 3, 1, 1) self.encode = nn.ModuleList() self.decode ...
def get_controller(model_space, session, data_description_len=3, layer_embedding_sharing=None, use_ppo_loss=False, is_training=True): with tf.device('/cpu:0'): controller = ZeroShotController(data_description_config={'length': data_description_len, 'hidden_layer': {'units': 16, 'activation': 'relu'}, 'regul...
class BasicUpdateBlock(nn.Module): def __init__(self, args, hidden_dim=128, input_dim=128): super(BasicUpdateBlock, self).__init__() self.args = args self.encoder = BasicMotionEncoder(args) self.gru = SepConvGRU(hidden_dim=hidden_dim, input_dim=(128 + hidden_dim)) self.flow_h...
def _get_info(cls_or_fn): if isinstance(cls_or_fn, type): if hasattr(cls_or_fn.__init__, '_autoargs_info'): return cls_or_fn.__init__._autoargs_info return {} else: if hasattr(cls_or_fn, '_autoargs_info'): return cls_or_fn._autoargs_info return {}
class SawyerPlateSlideV2Policy(Policy): _fully_parsed def _parse_obs(obs): return {'hand_pos': obs[:3], 'puck_pos': obs[3:6], 'shelf_x': obs[(- 3)], 'unused_info': obs[[6, 7, 8, 10, 11]]} def get_action(self, obs): o_d = self._parse_obs(obs) action = Action({'delta_pos': np.arange(3)...
def compute_sample_covariance(centered_data, sample_size, name): covariance = tf.matmul(((1.0 / (sample_size - 1.0)) * centered_data), centered_data, transpose_a=True, transpose_b=False) almost_zero_covariance = tf.fill(tf.shape(covariance), 1e-10) abs_sum = tf.reduce_sum(tf.abs(covariance)) cond = tf.e...
def process_trace(args): dir_name = args[0] trace_path = args[1] with open(os.path.join(dir_name, trace_path), 'r') as f: lines = f.readlines() dir_seq = np.zeros(5000, dtype=np.int8) time_seq = np.zeros(5000, dtype=np.float32) label = (0 if ('-' not in trace_path) else (int(trace_path.s...
class MilSimPush(Dataset): def __init__(self, training_size=693, validation_size=76): super().__init__(name='mil_sim_push', img_shape=(125, 125, 3), state_size=20, action_size=7, time_horizon=100, training_size=training_size, validation_size=validation_size)
def get_dist_transform_image(image): canny = cv2.Canny(image, 100, 200) edges_inv = (255 - canny) dist_image = cv2.distanceTransform(edges_inv, cv2.DIST_L2, 0) return dist_image
def mk_auto_soundness_tempvar(ctx: LeanGenContext, instr: LeanPreprocessedTempVar): ctx.add_main('-- tempvar') base_name = instr.identifier.identifier.name (temp_rewrites, temp_names, _) = process_assert_block(ctx=ctx, asserts=instr.asserts, temp_name_prefix=('tv_' + base_name)) (var_rw, var_type, var_c...
def custom_draw_geometry_with_optimization(mesh_list, handles, targets, res_path_imgs): custom_draw_geometry_with_optimization.index = (- 1) custom_draw_geometry_with_optimization.mesh_list = mesh_list custom_draw_geometry_with_optimization.rotation_step = 20 os.makedirs(res_path_imgs, exist_ok=True) ...
def register_Ns3Ipv6OptionHeader_methods(root_module, cls): cls.add_constructor([param('ns3::Ipv6OptionHeader const &', 'arg0')]) cls.add_constructor([]) cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) cls.add_method('GetAlignment', 'ns3::Ipv6OptionH...
class BeitConfig(PretrainedConfig): model_type = 'beit' def __init__(self, vocab_size=8192, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act='gelu', hidden_dropout_prob=0.0, attention_probs_dropout_prob=0.0, initializer_range=0.02, layer_norm_eps=1e-12, is_encode...
def test_threshold_synthetic_policy_continuous(): with pytest.raises(ValueError): context = np.array([1.0, 1.0]) threshold_synthetic_policy_continuous(context=context) with pytest.raises(ValueError): context = [1.0, 1.0] threshold_synthetic_policy_continuous(context=context) ...
class Exit(RuntimeError): __slots__ = ('exit_code',) def __init__(self, code=0): self.exit_code = code
def conv1x1(in_planes, out_planes): return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=1, padding=0, bias=False)
def register_Ns3Ipv4L3ClickProtocol_methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::Ipv4L3ClickProtocol const &', 'arg0')]) return
def train_example(loggers, loaders, model, optimizer, scheduler, datasets, **kwargs): start_epoch = 0 if cfg.train.auto_resume: start_epoch = load_ckpt(model, optimizer, scheduler) if (start_epoch == cfg.optim.max_epoch): logging.info('Checkpoint found, Task already done') else: ...
class TestJaccard(unittest.TestCase): def setUp(self): pass def test_similarity(self): a = [1, 2, 3, 4] b = [] c = [1, 2] d = [5, 6] self.assertAlmostEqual(jaccard(a, b), 0.0) self.assertAlmostEqual(jaccard(a, a), 1.0) self.assertAlmostEqual(jaccar...
def top_n_error_backward(grad_inputs, inputs, input_shapes, outputs, output_shapes, axis=None, n=1): dy = grad_inputs[0] x0 = inputs[0] raise NotImplementedError('top_n_error_backward is not implemented.')
class Partition2(nn.Module): LAYER_SCOPES = ['Net/BatchNorm1d[bn1]'] TENSORS = [] def __init__(self, layers, tensors, device='cuda:2'): super().__init__() for (idx, layer_scope) in enumerate(self.LAYER_SCOPES): self.add_module(f'l_{idx}', layers[layer_scope]) b = p = 0 ...
class SVGPModel(gpytorch.models.ApproximateGP): def __init__(self, initial_inducing, initial_lengthscale): variational_distribution = gpytorch.variational.NaturalVariationalDistribution(initial_inducing.size(0)) variational_strategy = gpytorch.variational.VariationalStrategy(self, initial_inducing, ...
.parametrize('seed', [412]) .parametrize('batch_size', [2, 4]) .parametrize('grid_size', [2, 8]) .parametrize('feature_size', [4]) .parametrize('m, M', [((- 1.0), 1.0)]) def test_query_on_voxel_double_backward(seed, batch_size, grid_size, feature_size, m, M): nn.clear_parameters() ctx = get_extension_context('c...
class Basic2DBlock(nn.Module): def __init__(self, in_planes, out_planes, kernel_size): super(Basic2DBlock, self).__init__() self.block = nn.Sequential(nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=1, padding=((kernel_size - 1) // 2)), nn.BatchNorm2d(out_planes), nn.ReLU(True)) ...
class MAMLPPO(MAML): def __init__(self, env, policy, baseline, inner_lr=_Default(0.1), outer_lr=0.001, lr_clip_range=0.5, max_path_length=100, discount=0.99, gae_lambda=1.0, center_adv=True, positive_adv=False, policy_ent_coeff=0.0, use_softplus_entropy=False, stop_entropy_gradient=False, entropy_method='no_entropy...
class WeightedIntegerVectors(Parent, UniqueRepresentation): def __classcall_private__(cls, n=None, weight=None): if (weight is None): if (n is None): raise ValueError('the weights must be specified') if (n in ZZ): weight = (n,) else: ...
class TestDetectionConfig(unittest.TestCase): def test_serialization(self): this_dir = os.path.dirname(os.path.abspath(__file__)) cfg_name = 'detection_cvpr_2019' config_path = os.path.join(this_dir, '..', 'configs', (cfg_name + '.json')) with open(config_path) as f: cfg ...
class BaseOverSampler(BaseSampler): _sampling_type = 'over-sampling' _sampling_strategy_docstring = "sampling_strategy : float, str, dict or callable, default='auto'\n Sampling information to resample the data set.\n\n - When ``float``, it corresponds to the desired ratio of the number of\n ...
def create_pipeline_configuration(DEBUG=False, batch_size=64): config = {'batch_dim': 0, 'depth': 10000, 'basic_blocks': (StatelessEmbedding, Linear, T5Block, Dropout, CrossEntropyLoss, T5LayerNorm), 'model_inputs': {'attention_mask': {'shape': torch.Size([64, 1, 1, 64]), 'dtype': torch.float32, 'is_batched': True,...
class MarkedYAMLError(YAMLError): def __init__(self, context=None, context_mark=None, problem=None, problem_mark=None, note=None): self.context = context self.context_mark = context_mark self.problem = problem self.problem_mark = problem_mark self.note = note def __str__(...
def get_all_in_parens(sequence): if (sequence[(- 1)] == ';'): sequence = sequence[:(- 1)] if (not ('(' in sequence)): return [] if ((sequence[0] == '(') and (sequence[(- 1)] == ')')): in_parens = sequence[1:(- 1)] return ([in_parens] + get_all_in_parens(in_parens)) else: ...
def test(): net = preactresnet34() y = net(Variable(torch.randn(1, 3, 32, 32))) print(y.size())
class FindPeaks(Benchmark): param_names = ['distance'] params = [[None, 8, 64, 512, 4096]] def setup(self, distance): self.x = electrocardiogram() def time_find_peaks(self, distance): find_peaks(self.x, distance=distance)
def _wrapreduction(obj, ufunc, method, axis, dtype, out, **kwargs): passkwargs = {k: v for (k, v) in kwargs.items() if (v is not np._NoValue)} if (type(obj) is not mu.ndarray): try: reduction = getattr(obj, method) except AttributeError: pass else: if ...
def lexical_diversity(sorted_A: List[str], sorted_B: List[str], top_p: float=0.2, num_samples: int=4, max_gap=None): (sorted_A, sorted_B) = (deepcopy(sorted_A), deepcopy(sorted_B)) a_candidates = [] b_candidates = [] if (max_gap is None): max_gap = ((num_samples // 4) + 1) reordered_A = re_o...
def agent(config: Config, workspace: Workspace) -> Agent: ai_config = AIConfig(ai_name='Base', ai_role='A base AI', ai_goals=[]) command_registry = CommandRegistry() ai_config.command_registry = command_registry config.set_memory_backend('json_file') memory_json_file = get_memory(config, init=True) ...
def create_model_from_pretrained(model_name: str, pretrained: str, precision: str='fp32', device: Union[(str, torch.device)]='cpu', jit: bool=False, force_quick_gelu: bool=False, force_custom_clip: bool=False, force_patch_dropout: Optional[float]=None, return_transform: bool=True, image_mean: Optional[Tuple[(float, ......
class SketchEncoder(nn.Module): def __init__(self): super(SketchEncoder, self).__init__() self.embed_dim = ENCODER_CONFIG['embed_dim'] self.coord_embed_x = Embedder(((2 ** CAD_BIT) + SKETCH_PAD), self.embed_dim) self.coord_embed_y = Embedder(((2 ** CAD_BIT) + SKETCH_PAD), self.embed_...
class WarmupConfig(): epoch: int = 1 multiplier: int = 1 buffer_epoch: int = 0 min_lr: float = 0.0 mode: str = 'fix' peak_lr: float = 0.0001 start_from_zero: bool = True
def plot_things(lines, scatters, filename): (fig, ax) = plt.subplots(nrows=len(lines), figsize=(12, 12)) for i in range(len(lines)): lines_tp = lines[i] for (j, _) in enumerate(lines_tp): (x, y, label, color) = lines_tp[j] ax[i].plot(x, y, label=label, c=color) for i ...
def _test_compiled_functions(): def func(a: ti.types.ndarray(ti.types.vector(n=10, dtype=ti.i32))): for i in range(5): for j in range(4): a[i][(j * j)] = (j * j) v = ti.Vector.ndarray(10, ti.i32, 5) func(v) assert (impl.get_runtime().get_num_compiled_functions() == 1)...
def run_validate(args): logging.info('Running validate.') num_files = len(args.filenames) if (num_files == 1): (task,) = args.filenames domain = util.find_domain_filename(task) elif (num_files == 2): (domain, task) = args.filenames else: returncodes.exit_with_driver_i...
def main(): parser = argparse.ArgumentParser(description='OGBN-Products (GraphSAINT)') parser.add_argument('--device', type=int, default=0) parser.add_argument('--log_steps', type=int, default=1) parser.add_argument('--inductive', action='store_true') parser.add_argument('--num_layers', type=int, de...
def parse_args(*arg_descriptors): def decorator(fn): fn._arg_descriptors = arg_descriptors def wrapper(g, *args, **kwargs): assert (len(arg_descriptors) >= len(args)) args = [_parse_arg(arg, arg_desc) for (arg, arg_desc) in zip(args, arg_descriptors)] assert (len(...
def compute_s_test(n_gpu: int, device: torch.device, model: torch.nn.Module, test_inputs: Dict[(str, torch.Tensor)], train_data_loaders: List[torch.utils.data.DataLoader], params_filter: Optional[List[str]], weight_decay: Optional[float], weight_decay_ignores: Optional[List[str]], damp: float, scale: float, num_samples...
class FlaxBigBirdPreTrainedModel(metaclass=DummyObject): _backends = ['flax'] def __init__(self, *args, **kwargs): requires_backends(self, ['flax'])
class CompilerDirectivesNode(Node): child_attrs = ['body'] def analyse_declarations(self, env): old = env.directives env.directives = self.directives self.body.analyse_declarations(env) env.directives = old def analyse_expressions(self, env): old = env.directives ...