code
stringlengths
101
5.91M
('download_file', 'Download File', '"url": "<url>", "filename": "<filename>"', (lambda config: config.allow_downloads), 'Error: You do not have user authorization to download files locally.') def download_file(url, filename, agent: Agent): try: directory = os.path.dirname(filename) os.makedirs(direc...
class Square(BaseFunction): def tf(self, x): return (tf.square(x) / self.norm) def sp(self, x): return ((x ** 2) / self.norm) def np(self, x): return (np.square(x) / self.norm)
class SpanBox(TextBlock): def __init__(self, text: str, bbox: Tuple[(float, float, float, float)], block_ids: Set[str], cell_size: Tuple[(float, float)]): super(SpanBox, self).__init__(text) self.bbox: Tuple[(float, float, float, float)] = bbox self.blocks: Set[str] = block_ids asser...
def write_tokenizer(tokenizer_path, input_tokenizer_path): os.makedirs(tokenizer_path, exist_ok=True) write_json({}, os.path.join(tokenizer_path, 'special_tokens_map.json')) write_json({'bos_token': '', 'eos_token': '', 'model_max_length': int(1e+30), 'tokenizer_class': 'LlamaTokenizer', 'unk_token': ''}, o...
class TSBase(object): thisown = _swig_property((lambda x: x.this.own()), (lambda x, v: x.this.own(v)), doc='The membership flag') __repr__ = _swig_repr def __init__(self, Nm): _snap.TSBase_swiginit(self, _snap.new_TSBase(Nm)) __swig_destroy__ = _snap.delete_TSBase def GetSNm(self): r...
def local_prediction_rigidity(X_train, X_test, alpha): X_atom = np.vstack(X_train) sfactor = np.sqrt(np.mean((X_atom ** 2), axis=0).sum()) X_struc = [] for X_i in X_train: X_struc.append(np.mean((X_i / sfactor), axis=0)) X_struc = np.vstack(X_struc) XX = (X_struc.T X_struc) Xprime =...
def _impl(array): layout = ak.operations.ak_to_layout._impl(array, allow_record=True, allow_unknown=False, none_policy='error', regulararray=True, use_from_iter=True, primitive_policy='error', string_policy='as-characters') return layout.is_tuple
def test_option_numpy_1(): text = '?int64' parsedtype = deduce_type(text) assert isinstance(parsedtype, ak.types.OptionType) assert (str(parsedtype) == text)
_module() class LinearLrUpdaterHook(LrUpdaterHook): def __init__(self, target_lr=0, start=0, interval=1, **kwargs): super().__init__(**kwargs) self.target_lr = target_lr self.start = start self.interval = interval def get_lr(self, runner, base_lr): if self.by_epoch: ...
class SentenceLevelScorer(scorer.Scorer): __metaclass__ = abc.ABCMeta def __init__(self): super(SentenceLevelScorer, self).__init__() self._total_loss = 0 self._true_labels = [] self._preds = [] def update(self, results): super(SentenceLevelScorer, self).update(result...
def _seg_51(): return [(65317, 'M', u'e'), (65318, 'M', u'f'), (65319, 'M', u'g'), (65320, 'M', u'h'), (65321, 'M', u'i'), (65322, 'M', u'j'), (65323, 'M', u'k'), (65324, 'M', u'l'), (65325, 'M', u'm'), (65326, 'M', u'n'), (65327, 'M', u'o'), (65328, 'M', u'p'), (65329, 'M', u'q'), (65330, 'M', u'r'), (65331, 'M', ...
def register_Ns3ApplicationContainer_methods(root_module, cls): cls.add_constructor([param('ns3::ApplicationContainer const &', 'arg0')]) cls.add_constructor([]) cls.add_constructor([param('ns3::Ptr< ns3::Application >', 'application')]) cls.add_constructor([param('std::string', 'name')]) cls.add_me...
class RunDirectiveNotAllowedInUserRules(ShowyourworkException): def __init__(self, name): super().__init__(f'The `run` directive is not allowed in user-defined rules. Please use `script` or `shell` instead in rule {name}.')
def env_0(): env = Warehouse(3, 8, 3, 1, 0, 1, 5, 10, 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.request_queue[0] = env.shel...
def test_psf_estimation(psf_data, true_psf_file, kernel=None, metric='mean'): true_psf = read_file(true_psf_file) if (true_psf.shape != psf_data.shape): raise ValueError('The number of true PSF images must match the number estimated PSF images.') return test_images(psf_data, true_psf, kernel, metric...
def average_checkpoints(inputs): params_dict = collections.OrderedDict() params_keys = None new_state = None num_models = len(inputs) for fpath in inputs: with PathManager.open(fpath, 'rb') as f: state = torch.load(f, map_location=(lambda s, _: torch.serialization.default_restore...
class ImageTextPairInstructDataset(ImageTextPairDataset): def __getitem__(self, index): data = super().__getitem__(index) if (data != None): data['text_output'] = data['text_input'] data['text_input'] = self.text_processor('') return data
def skip_if_no_gpu(func): (func) def wrapper(*args, **kwargs): if (not torch.cuda.is_available()): sys.exit(TEST_SKIPS['no_cuda'].exit_code) if (torch.cuda.device_count() < int(os.environ['WORLD_SIZE'])): message = 'Need at least {} CUDA devices'.format(os.environ['WORLD_...
def eval_loop(preprocess_fn, network_factory, data_x, data_y, camera_indices, log_dir, eval_log_dir, image_shape=None, run_id=None, loss_mode='cosine-softmax', num_galleries=10, random_seed=4321): if (image_shape is None): assert (type(data_x) == np.ndarray) image_shape = data_x.shape[1:] elif (...
def compile_time_env_variables(): return dict(PY_PLATFORM=sys.platform, PY_VERSION_HEX=sys.hexversion, PY_MAJOR_VERSION=sys.version_info[0])
def test_record_to_arrow(): x_content = ak.highlevel.Array([1.1, 2.2, 3.3, 4.4, 5.5]).layout z_content = ak.highlevel.Array([1, 2, 3, None, 5]).layout ak_array = ak.contents.RecordArray([x_content, ak.contents.UnmaskedArray(x_content), z_content], ['x', 'y', 'z']) pa_array = ak_array.to_arrow() asse...
class MultiPassSieveModel(): def __init__(self, *models): self.models = models def predict(self, df): preds = pd.DataFrame(([([False] * 2)] * len(df)), columns=['a_coref', 'b_coref']) for model in self.models: preds_ = model.predict(df) preds_ = pd.DataFrame(preds...
def make_matrix(arr, dt=None): if (len(arr) == 0): shape = [0] dt = primitive_types.i32 else: if isinstance(arr[0], Iterable): shape = [len(arr), len(arr[0])] arr = [elt for row in arr for elt in row] else: shape = [len(arr)] if (dt is ...
def ManualLLVM(inputs, *outputs): outputs_ravel = list(itertools.chain(*outputs)) cb = se.Lambdify(inputs, outputs_ravel, backend='llvm') def func(*args): result = [] n = np.empty(len(outputs_ravel)) t = cb.unsafe_real(np.concatenate([arg.ravel() for arg in args]), n) start =...
class Ego4DDataset(BaseDataset): def __init__(self, *args, split='', **kwargs): assert (split in ['train', 'val', 'test']) self.split = split if (split == 'train'): names = ['ego4d_train'] elif (split == 'val'): names = ['ego4d_val'] elif (split == 'te...
def prepare_dataset(path, built_vocab=None, user_only=False): data = open(path, 'r', encoding='utf-8').readlines() p_data = [] history = [['<null>']] for d in data: if (d == '\n'): history = [['<null>']] continue dd = d.replace('\n', '').split('|||') if (l...
def extract_convsdae_yale(slope=0.0): return extractconvSDAE(dim=[1, 50, 50, 50, 50, 50, 10], output_padding=[(0, 0), (1, 1), (1, 1), (0, 1), (0, 1)], numpen=6, slope=slope)
def check_labels(labels, dataset): new_labels = dataset_labels(dataset) not_found = [i for i in new_labels if (i not in labels)] if not_found: raise RuntimeError(('Dataset contains labels which the model does not know about:' + str(not_found)))
def test_load_SpatialEvents(): dataset = tau2020sse_nigens.Dataset(TEST_DATA_HOME) clip = dataset.clip('foa_dev/fold1_room1_mix001_ov1') annotations_path = clip.csv_path tau2020_annotations = tau2020sse_nigens.load_spatialevents(annotations_path) confidence = ([1.0] * 6) intervals = [[[0, 0], [0...
.torch def test_prediction_sasrec(item_user_sequential_dataset, train_sasrec_loader): pred = SasRecPredictionDataset(item_user_sequential_dataset, max_sequence_length=5) pred_sasrec_loader = torch.utils.data.DataLoader(pred) trainer = L.Trainer(max_epochs=1) model = SasRec(tensor_schema=item_user_sequen...
def pure_graph(dtype, transposed, expansion, veclen, alpha, beta, expansion_args=None): sdfg = dace.SDFG(f'gemv_{expansion}_{dtype}_{transposed}_w{veclen}') m = dace.symbol('m') n = dace.symbol('n') n /= veclen vtype = dace.vector(dtype, veclen) state = sdfg.add_state('gemv_compute') A_rows ...
def before_record_request(request: Any) -> Any: request = replace_request_hostname(request, ORIGINAL_URL, NEW_URL) filtered_request = filter_hostnames(request) filtered_request_without_dynamic_data = replace_timestamp_in_request(filtered_request) return filtered_request_without_dynamic_data
def GetIOU(Pred, GT, NumClasses, ClassNames=[], DisplyResults=False): ClassIOU = np.zeros(NumClasses) ClassWeight = np.zeros(NumClasses) for i in range(NumClasses): Intersection = np.float32(np.sum(((Pred == GT) * (GT == i)))) Union = ((np.sum((GT == i)) + np.sum((Pred == i))) - Intersection...
def simSetBoolParameter(parameter, value): ret = lib.simSetBoolParameter(parameter, value) _check_return(ret)
class BitModel(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def get_installed_apt_pkgs() -> set: with open('/var/lib/dpkg/status') as f: return set(RE_DPKG_STATUS.findall(f.read()))
def read_in_para_lengths(corpus_dir: str, output_dir: str): lengths = {} dict_paragraphs = {} failed_files = [] for (root, dirs, files) in os.walk(corpus_dir): for file in files: with open(os.path.join(corpus_dir, file), 'r') as f: lines = f.readlines() ...
class PublicSingleton(PrivateSingleton, Protocol): def instance(cls) -> Self: return cls._ensure_instance()
class Identity(nn.Module): def forward(self, *args): if (len(args) == 1): return args[0] return args
def collate_fn(batch): frames = [] target = [] times = [] if (sum([(s is not None) for s in batch]) == 0): return (None, None, None) for items in batch: if (items is None): continue frames.append(items[3]) target.append([items[2], items[5], items[6]]) ...
def plot3d_cubie(cnt, clrs): half = QQ((1, 2)) x = (cnt[0] - half) y = (cnt[1] - half) z = (cnt[2] - half) ptsF = [[(x + 1), (y + 0), (0 + z)], [(x + 1), (y + 1), (0 + z)], [(x + 1), (y + 1), (1 + z)], [(x + 1), (y + 0), (1 + z)], [(x + 1), (y + 0), (0 + z)]] ptsU = [[(x + 0), (y + 0), (1 + z)],...
def test_plot_dt() -> None: srs = pd.Series(['3/11/2001', '3/12/2002', '3/12/2003', '3/13/2003', '4/13/2003', '4/13/2003', '4/13/2003', '4/13/2003', '4/13/2003', '4/13/2003', '4/13/2003', '4/13/2003', '4/13/2003', '4/13/2003', '4/13/2003']) dt_col = pd.to_datetime(srs, infer_datetime_format=True) df = pd.Da...
class WriteDataCallback(Callback): def __init__(self, writer: wr.Writer) -> None: self.writer = writer def on_subject(self, params: dict): subject_files = params[defs.KEY_SUBJECT_FILES] subject_index = params[defs.KEY_SUBJECT_INDEX] index_str = defs.subject_index_to_str(subject_i...
def time_funcs(funcs, name='', func_names=None, num_iters=100, warmups=5, launch_wait=True): timer = CudaTimer(len(funcs)) pycudaprof.start_cuda_profiling() torch.cuda.nvtx.range_push((name + ' Warmup')) for _ in range(warmups): for f in funcs: f() torch.cuda.nvtx.range_pop() ...
class Classifier(): def __init__(self, path: str, label_list, args): self.args = args self.device = torch.device(('cuda:0' if (torch.cuda.is_available() and (not self.args.no_cuda)) else 'cpu')) self.label_list = label_list self.num_labels = len(self.label_list) self.config =...
def _pretrain_generator(generator, train_examples): print(('=' * 60), '\n', 'Generator Pre-training', '\n', ('=' * 60), sep='') best_dev_loss = .0 tag = time.time() for epoch in range(args.generator_pretrain_epochs): dev_loss = generator.train_epoch() if (dev_loss < best_dev_loss): ...
class WeylLieConformalAlgebra(LieConformalAlgebraWithStructureCoefficients): def __init__(self, R, ngens=None, gram_matrix=None, names=None, index_set=None): from sage.matrix.matrix_space import MatrixSpace if ngens: from sage.rings.integer_ring import ZZ if (not ((ngens in Z...
class _Pretty(Doc): __slots__ = ('obj',) def __init__(self, obj): self.obj = obj def send_to(self, out, indent): self.obj.pretty().send_to(out, indent)
def scatter_plot(dataset, data_range, title, axis_name, file_path): matplotlib.use('agg') plt.figure(figsize=(10, 8), dpi=300) for (ens10, era5, _, _) in tqdm(dataset, desc=f'[Plot]', unit='Batch', total=len(dataset)): era5 = era5.unsqueeze((- 1)).expand(ens10.shape) plt.scatter(era5.numpy()...
class Result(): def __init__(self, correct, total): self.correct = correct self.total = total def report_accuracy(self): print(('Accuracy: %.2f%%' % ((100.0 * self.correct) / self.total))) def accuracy(self): acc = ((100.0 * self.correct) / self.total) return float(('...
def test_redundant_array_success(): sdfg = _make_sdfg_1(succeed=True) sdfg.save('test2.sdfg') num = sdfg.apply_transformations(RedundantArray) assert (num == 1)
class StoreOpsTests(object): def _test_set_get(cls, queue, create_store_handler_fn, index, num_procs): store_handler = create_store_handler_fn() blob = 'blob' value = np.full(1, 1, np.float32) if (index == (num_procs - 1)): workspace.FeedBlob(blob, value) work...
class NoOpBuildEnvironment(BuildEnvironment): def __init__(self): pass def __enter__(self): pass def __exit__(self, exc_type, exc_val, exc_tb): pass def cleanup(self): pass def install_requirements(self, finder, requirements, prefix_as_string, message): raise ...
def __getattr__(name): return _sub_module_deprecation(sub_package='odr', module='models', private_modules=['_models'], all=__all__, attribute=name)
class BasicResBlock(nn.Module): def __init__(self, in_channels, out_channels, conv_cfg=None, norm_cfg=dict(type='BN')): super(BasicResBlock, self).__init__() self.conv1 = ConvModule(in_channels, in_channels, kernel_size=3, padding=1, bias=False, conv_cfg=conv_cfg, norm_cfg=norm_cfg) self.con...
class MultiInputController(GeneralController): def __init__(self, model_space, buffer_type='ordinal', with_skip_connection=True, with_input_blocks=True, share_embedding=None, use_ppo_loss=False, kl_threshold=0.05, num_input_blocks=2, input_block_unique_connection=True, skip_connection_unique_connection=False, buffe...
class TestLayerFusing(unittest.TestCase): def _compare(self, fused_nodes, expected_fusions): self.assertTrue((len(fused_nodes) == len(expected_fusions)), msg=f'Number of fusions is not as expected!') for (i, fusion) in enumerate(fused_nodes): self.assertTrue((get_type(fusion) == expected...
def test_issue_1864(): a = ak.from_iter([[None, 1], None, [1, 2]]) tt = ak.Array(a.layout.to_typetracer()) assert (str(ak.is_none(tt, axis=0).layout.form.type) == 'bool') assert (str(ak.is_none(tt, axis=1).layout.form.type) == 'option[var * bool]')
class EchoChamberDynamics(object): def __init__(self, num_agents, num_links, epsilon, sns_seed, l, data_dir): self.num_agents = num_agents self.l = l self.epsilon = epsilon self.set_agents(num_agents, epsilon) self.social_media = SocialMedia(num_agents, num_links, l, sns_seed...
def bernoulli(n, algorithm='default', num_threads=1): n = ZZ(n) if (algorithm == 'default'): if (n <= 20000): algorithm = 'flint' elif (n <= 300000): algorithm = 'arb' else: algorithm = 'bernmm' if (algorithm == 'arb'): import sage.libs.arb...
def average_state_dicts(state_dicts): iterator = iter(state_dicts) try: running_sum = next(iterator) except StopIteration: raise ValueError('No state dicts to average.') num_dicts = 1 with torch.no_grad(): for state_dict in iterator: for (pname, param) in state_di...
class Slim(nn.Module): def __init__(self, cfg=None, phase='train'): super(Slim, self).__init__() self.phase = phase self.num_classes = 2 self.conv1 = conv_bn(3, 16, 2) self.conv2 = conv_dw(16, 32, 1) self.conv3 = conv_dw(32, 32, 2) self.conv4 = conv_dw(32, 32,...
def quadratic(x: tf.Tensor) -> tf.Tensor: if ((x.shape == []) or (x.shape[(- 1)] == 0)): raise ValueError(f'x must have non-empty trailing dimension, got shape {x.shape}') return tf.reduce_sum((x ** 2), axis=(- 1), keepdims=True)
def min(*args): num_args = len(args) assert (num_args >= 1) if (num_args == 1): return args[0] if (num_args == 2): return min_impl(args[0], args[1]) return min_impl(args[0], min(*args[1:]))
def squash(vectors, axis=(- 1)): s_squared_norm = K.sum(K.square(vectors), axis, keepdims=True) scale = ((s_squared_norm / (1 + s_squared_norm)) / K.sqrt((s_squared_norm + K.epsilon()))) return (scale * vectors)
def register_Ns3SimpleRefCount__Ns3Ipv4MulticastRoute_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4MulticastRoute__gt___methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter< ns3::Ipv4MulticastRoute > > const &', 'o...
def valid_port(port): port = int(port) if (1 <= port <= 65535): return port else: raise argparse.ArgumentTypeError(('%d is not a valid port number' % port))
def get_unetw(x_train, pretrained_weights=None): print('Begining UNet Wide') weight = 38 nb_filter = [weight, (weight * 2), (weight * 4), (weight * 8), (weight * 16)] inputs = Input(shape=x_train.shape[1:]) conv1 = Conv2D(nb_filter[0], (3, 3), activation='relu', padding='same')(inputs) conv1 = C...
def compute_data_representations_only(net, data, device, has_features=True): net.eval() reps = [] if (not has_features): if (data.x is not None): log.warn('[WARNING] features overidden in adj matrix') data.x = net.get_node_feats().weight.data with torch.no_grad(): rep...
def mv_txt(dataset, aug_name): txt_dir = glob.glob('datasets/NewVersion/{}/test_label*.txt'.format(dataset)) write_dir = '{}/{}/test_label.txt'.format(aug_name, dataset) with open(txt_dir[(- 1)], 'r', encoding='UTF-8-sig') as f: all = f.readlines() with open(write_dir, 'w') as f: f.write...
class DistributedSamplerV2(Sampler): def __init__(self, dataset, num_replicas=None, rank=None, shuffle=True): if (num_replicas is None): if (not dist.is_available()): raise RuntimeError('Requires distributed package to be available') num_replicas = dist.get_world_size...
() def type4py_data(): return json.loads('{\n "error":null,\n "response":{\n "classes":[\n {\n "cls_var_ln":{\n "cls_var_name":[\n [\n 4,\n 4\n ],\n ...
def test_complex_dependencies(): cluster = generate_test_cluster('tests.fixtures.cluster.complex_dependencies') assert (cluster.num_accessible_objects_under_test() == 1)
def bulgarian_solitaire(n): from sage.combinat.partition import Partition, Partitions X = Partitions(n) def phi(lam): mu = [(p - 1) for p in lam if (p > 0)] nu = sorted((mu + [len(lam)]), reverse=True) return Partition(nu) return FiniteDynamicalSystem(X, phi)
def main(action, savedir, data_to_use, n_images, model_dir, batch_size): if (model_dir == 'download_from_web'): model_dir = './denoising_student_models' if (not os.path.exists(model_dir)): load_models_from_gdrive('./', False) device = ('/GPU:0' if tf.config.list_physical_devices('GPU...
def test_write_file_logs_checksum(test_file_path: Path, agent: Agent): new_content = 'This is new content.\n' new_checksum = file_ops.text_checksum(new_content) file_ops.write_to_file(str(test_file_path), new_content, agent=agent) with open(agent.config.file_logger_path, 'r', encoding='utf-8') as f: ...
def pushout(R, S): if ((R is S) or (R == S)): return R if hasattr(R, '_pushout_'): P = R._pushout_(S) if (P is not None): return P if hasattr(S, '_pushout_'): P = S._pushout_(R) if (P is not None): return P if isinstance(R, type): R...
class PromptGenerator(): def __init__(self) -> None: self.constraints = [] self.commands = [] self.resources = [] self.performance_evaluation = [] self.goals = [] self.command_registry: (CommandRegistry | None) = None self.name = 'Bob' self.role = 'AI'...
class SequentialCond(torch.nn.Sequential): def forward(self, input, *args, **kwargs): for module in self: if isinstance(module, (AdaptiveLayerNorm1D, SequentialCond, ResidualMLPBlock)): input = module(input, *args, **kwargs) else: input = module(input)...
class Algorithm(): def __init__(self, algorithm, *, heterogeneous=None, directed=None, weighted=None, temporal=None, features=None, nc=None, interpretability_nc=None, lp=None, rl=None, inductive=None, gc=None): columns = {ALGORITHM: algorithm, HETEROGENEOUS: heterogeneous, DIRECTED: directed, WEIGHTED: weig...
def get_visualizers(visualizers_config): visualizers = [] for renderer in visualizers_config: visualizers.append(get_visualizer(renderer['renderer_name'], renderer['renderer_config'])) return visualizers
def test_gcn_lstm_save_load(tmpdir, arange_graph): gen = SlidingFeaturesNodeGenerator(arange_graph, 2, batch_size=3) gcn_lstm = GCN_LSTM(None, None, [2], [4], generator=gen) test_utils.model_save_load(tmpdir, gcn_lstm)
def extract_sdae_reuters(slope=0.0, dim=10): return extractSDAE(dim=[2000, 500, 500, 2000, dim], slope=slope)
def register_Ns3TcpLedbat_methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::TcpLedbat const &', 'sock')]) cls.add_method('Fork', 'ns3::Ptr< ns3::TcpCongestionOps >', [], is_virtual=True) cls.add_method('GetName', 'std::string', [], is_const=True, is_virtual=True) cl...
class MLARAM(MLClassifierBase): def __init__(self, vigilance=0.9, threshold=0.02, neurons=None): super(MLARAM, self).__init__() if (neurons is not None): self.neurons = neurons else: self.neurons = [] self.vigilance = vigilance self.threshold = thresho...
def length_of_broadcast(inputs: Sequence) -> (int | type[unknown_length]): max_length: (int | None) = None has_seen_unknown_length: bool = False for x in inputs: if (not isinstance(x, Content)): continue if (x.length is unknown_length): has_seen_unknown_length = True ...
def register_Ns3EpcS1apSapEnbProvider_methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::EpcS1apSapEnbProvider const &', 'arg0')]) cls.add_method('SendErabReleaseIndication', 'void', [param('uint64_t', 'mmeUeS1Id'), param('uint16_t', 'enbUeS1Id'), param('std::list< ns3::EpcS...
def assert_identical(a, b): assert_equal(a, b) if (type(b) is str): assert_equal(type(a), type(b)) else: assert_equal(np.asarray(a).dtype.type, np.asarray(b).dtype.type)
def create_pipeline_configuration(DEBUG=False, batch_size=4): config = {'batch_dim': 0, 'depth': 10000, 'basic_blocks': (Softmax, LayerNorm, Dropout, Linear, Embedding, Gelu, Tanh), 'model_inputs': {'attention_mask': {'shape': torch.Size([4, 384]), 'dtype': torch.int64, 'is_batched': True, 'used_by': [0]}, 'input_i...
def test_brentq_full_output(): output = _zeros.full_output_example(((A0[0],) + ARGS), XLO, XHI, XTOL, RTOL, MITR) npt.assert_allclose(EXPECTED[0], output['root'], rtol=RTOL, atol=XTOL) npt.assert_equal(6, output['iterations']) npt.assert_equal(7, output['funcalls']) npt.assert_equal(0, output['error...
class CADData(torch.utils.data.Dataset): def __init__(self, cad_path, solid_path, profile_path, loop_path, mode, is_training=True): with open(cad_path, 'rb') as f: cad_data = pickle.load(f) with open(solid_path, 'rb') as f: solid_data = pickle.load(f) self.solid_code ...
def plot_cur_mem_spk(cur, mem, spk, thr_line=False, vline=False, title=False, ylim_max2=1.25): (fig, ax) = plt.subplots(3, figsize=(8, 6), sharex=True, gridspec_kw={'height_ratios': [1, 1, 0.4]}) ax[0].plot(cur, c='tab:orange') ax[0].set_ylim([0, 0.4]) ax[0].set_xlim([0, 200]) ax[0].set_ylabel('Inpu...
def c_type(tensor): if isinstance(tensor, torch.cuda.HalfTensor): return ctypes.c_float elif isinstance(tensor, torch.cuda.FloatTensor): return ctypes.c_float elif isinstance(tensor, torch.cuda.DoubleTensor): return ctypes.c_double else: raise ValueError("unknown type '{}...
class DatasetDeepglobe(Dataset): def __init__(self, datapath, fold, transform, split, shot, num=600): self.split = split self.benchmark = 'deepglobe' self.shot = shot self.num = num self.base_path = os.path.join(datapath, 'Deepglobe') self.categories = ['1', '2', '3',...
def generate_switch_batch_size(): s = "batch_dim = config['batch_dim']\n for d in chain(config['model_inputs'].values(),config['model_outputs'].values()):\n if d['is_batched']:\n shape = d['shape']\n d['shape'] = torch.Size(shape[:batch_dim] + (batch_size,) + shape[batch_dim+1:])\n ...
def tens2image(im): tmp = np.squeeze(im.numpy()) if (tmp.ndim == 2): return tmp else: return tmp.transpose((1, 2, 0))
_metric def rendering_train(opts): opts.dataset_kwargs.update(max_size=None, xflip=False) rendering_utils.render_train(opts, max_items=None) return dict(rendering_train=1)
def get_acronyms(entity): words = entity.split() first_letters = ''.join([w[0] for w in words]) acronyms = [first_letters] for split in range(2, len(first_letters)): acronyms.append(first_letters[:split]) return acronyms
def wmd_distance(model, sent1_cut_list, sent2_cut_list): distance = model.wmdistance(sent1_cut_list, sent2_cut_list) return distance
def filter_genre_edgelist(fname, genres_dict): edgelist = open(fname, 'r') lines = list(edgelist.readlines()) edgelist.close() with open('lastfm_edgelist_clean.csv', 'w') as f: write = csv.writer(f) fields = ['user_id', 'timestamp', 'tags', 'weight'] write.writerow(fields) ...