code
stringlengths
101
5.91M
def data() -> Tuple[(np.ndarray, np.ndarray)]: X = np.random.randn(CONFIG.num_data, CONFIG.input_dim) Y = np.random.randn(CONFIG.num_data, CONFIG.output_dim) return (X, Y)
.parametrize('test_input', [0, (- 1), 1, 4, None, bool, int, 1.5, 'None', True]) def test_initialize_bad_target(test_input): _dn = BoostedRDNClassifier(target=test_input) (train, _) = load_toy_cancer() with pytest.raises(ValueError): _dn.fit(train)
def braycurtis(u, v, w=None): u = _validate_vector(u) v = _validate_vector(v, dtype=np.float64) l1_diff = abs((u - v)) l1_sum = abs((u + v)) if (w is not None): w = _validate_weights(w) l1_diff = (w * l1_diff) l1_sum = (w * l1_sum) return (l1_diff.sum() / l1_sum.sum())
class TestArticle(unittest.TestCase): def setUp(self): nlp = spacy.load('en') self.my_article = documents.Document.from_xml('2012-10-02', '<?xml version="1.0"?>\n<!DOCTYPE TimeML SYSTEM "TimeML.dtd">\n<TimeML>\nAt <TIMEX3 tid="t58" type="TIME" value="2009-05-29T13:28">1:28 pm</TIMEX3> on <TIMEX3 tid...
class AutoTokenCostEstimator(TokenCostEstimator): def __init__(self): self._token_cost_estimators: Dict[(str, TokenCostEstimator)] = {} def _get_estimator(self, organization: str) -> TokenCostEstimator: token_cost_estimator = self._token_cost_estimators.get(organization) if (token_cost_e...
class SchemaGuidedDST(object): def __init__(self, bert_config, use_one_hot_embeddings): self._bert_config = bert_config self._use_one_hot_embeddings = use_one_hot_embeddings def define_model(self, features, is_training): (self._encoded_utterance, self._encoded_tokens, self.input_embeddin...
def cot() -> operations.GraphOfOperations: operations_graph = operations.GraphOfOperations() operations_graph.append_operation(operations.Generate(1, 1)) operations_graph.append_operation(operations.Score(1, False, utils.num_errors)) operations_graph.append_operation(operations.GroundTruth(utils.test_so...
def load_pretrained_model(model_name_or_path_or_checkpoint, *args, **kwargs): if PathManager.isfile(model_name_or_path_or_checkpoint): return _load_pretrained_checkpoint(model_name_or_path_or_checkpoint, args, kwargs) else: return _load_pretrained_model(model_name_or_path_or_checkpoint, args, kw...
def from_rank(n, rank): factoradic = ([None] * n) for j in range(1, (n + 1)): factoradic[(n - j)] = Integer((rank % j)) rank = (int(rank) // j) return from_lehmer_code(factoradic, Permutations(n))
def plotIsoFreqNSimpedance(ax, freq, array, flag, par='abs', colorbar=True, colorNorm='SymLog', cLevel=True, contour=True): indUniFreq = np.where((freq == array['freq'])) (x, y) = (array['x'][indUniFreq], array['y'][indUniFreq]) if (par == 'abs'): zPlot = np.abs(array[flag][indUniFreq]) cmap...
def query_2_deepdb_sql(query: Query, table: Table, aggregate=True, split=False): preds = [] for (col, pred) in query.predicates.items(): if (pred is None): continue (op, val) = pred if (op == '[]'): val = table.columns[col].normalize(list(val)) assert ...
def build_lmdb(save_path, metas, commit_interval=1000): if (not save_path.endswith('.lmdb')): raise ValueError("lmdb_save_path must end with 'lmdb'.") if osp.exists(save_path): print('Folder [{:s}] already exists.'.format(save_path)) return if (not osp.exists('/'.join(save_path.split...
def regression_suite(sebs_client: 'SeBS', experiment_config: dict, providers: Set[str], deployment_config: dict, benchmark_name: Optional[str]=None): suite = unittest.TestSuite() global cloud_config cloud_config = deployment_config language = experiment_config['runtime']['language'] language_version...
def TranslateX(img, v, max_v, bias=0): v = (_float_parameter(v, max_v) + bias) if (random.random() < 0.5): v = (- v) v = int((v * img.size[0])) return img.transform(img.size, PIL.Image.AFFINE, (1, 0, v, 0, 1, 0))
class _ConvNd(Module): __constants__ = ['stride', 'padding', 'dilation', 'groups', 'padding_mode', 'output_padding', 'in_channels', 'out_channels', 'kernel_size'] __annotations__ = {'bias': Optional[torch.Tensor]} _in_channels: int out_channels: int kernel_size: Tuple[(int, ...)] stride: Tuple[(...
class ConfigDictionary(): def __init__(self, dictionary: dict=None): if (dictionary is None): dictionary = dict() self._keys = set(dictionary) for (key, value) in dictionary.items(): self.__setattr__(key, value) def __repr__(self): d = self.__dict__.copy()...
def test_quad_vec_pool(): from multiprocessing.dummy import Pool f = _lorenzian (res, err) = quad_vec(f, (- np.inf), np.inf, norm='max', epsabs=0.0001, workers=4) assert_allclose(res, np.pi, rtol=0, atol=0.0001) with Pool(10) as pool: f = (lambda x: (1 / (1 + (x ** 2)))) (res, err) =...
def figure4(): n_subjects = 10 net = xfr.models.lightcnn.LightCNN_29Layers_v2(num_classes=80013) statedict = xfr.models.lightcnn.Load_Checkpoint('../models/LightCNN_29Layers_V2_checkpoint.pth.tar') net.load_state_dict(statedict) wb = xfr.models.whitebox.Whitebox(xfr.models.whitebox.WhiteboxLightCNN(...
class LegacyVersion(_BaseVersion): def __init__(self, version): self._version = str(version) self._key = _legacy_cmpkey(self._version) def __str__(self): return self._version def __repr__(self): return '<LegacyVersion({0})>'.format(repr(str(self))) def public(self): ...
def generate_arch(task, net_type): update_cfg_from_cfg(search_cfg, cfg) if (task == 'pde'): merge_cfg_from_file('configs/pde_search_cfg_resnet.yaml', cfg) input_shape = (3, 85, 85) elif (task == 'protein'): merge_cfg_from_file('configs/protein_search_cfg_resnet.yaml', cfg) in...
class ProjectiveConic_finite_field(ProjectiveConic_field, ProjectivePlaneCurve_finite_field): def __init__(self, A, f): ProjectiveConic_field.__init__(self, A, f) def count_points(self, n): F = self.base_ring() q = F.cardinality() return [((q ** i) + 1) for i in range(1, (n + 1))...
def lex(s, name=None, trim_whitespace=True, line_offset=0, delimeters=None): if (delimeters is None): delimeters = (Template.default_namespace['start_braces'], Template.default_namespace['end_braces']) in_expr = False chunks = [] last = 0 last_pos = ((line_offset + 1), 1) token_re = re.c...
def load_config(save_config=True): gin.parse_config_files_and_bindings(flags.FLAGS.gin_configs, flags.FLAGS.gin_bindings, skip_unknown=True) config = Config() if (save_config and (jax.host_id() == 0)): if (not utils.isdir(config.checkpoint_dir)): os.makedirs(config.checkpoint_dir) ...
def get_dynamic_defaults(): if (FLAGS.logdir is None): new_logdir = f'./runs/{FLAGS.dataset}' log.info(f'No logdir set, using default of {new_logdir}') FLAGS.logdir = new_logdir
_utils.test() def test_pass_struct_mismatch(): sphere_type = ti.types.struct(center=ti.math.vec3, radius=float) circle_type = ti.types.struct(center=ti.math.vec2, radius=float) def foo(sphere: sphere_type): pass with pytest.raises(ti.TaichiRuntimeTypeError, match="Argument <class 'taichi.lang.st...
def test_method_token_segments_pretrained_tokenizer_fast(): AutoTokenizer = pytest.importorskip('transformers').AutoTokenizer tokenizer = AutoTokenizer.from_pretrained('distilbert-base-uncased', use_fast=True) masker = shap.maskers.Text(tokenizer) test_text = 'I ate a Cannoli' (output_token_segments...
class UDADecorator(BaseSegmentor): def __init__(self, **cfg): super(BaseSegmentor, self).__init__() self.model = build_segmentor(deepcopy(cfg['model'])) self.train_cfg = cfg['model']['train_cfg'] self.test_cfg = cfg['model']['test_cfg'] self.num_classes = cfg['model']['decode...
class SAN(nn.Module): def __init__(self, num_of_dim, vocab_size, embedding_size, r, lstm_hidden_dim=128, da=128, hidden_dim=256) -> None: super(SAN, self).__init__() self._embedding = nn.Embedding(vocab_size, embedding_size) self._bilstm = nn.LSTM(embedding_size, lstm_hidden_dim, batch_first...
_function_from_c_func_and_dispatcher(_multiarray_umath.unpackbits) def unpackbits(a, axis=None, count=None, bitorder='big'): return (a,)
class TransfoXLForSequenceClassification(): def __init__(self, *args, **kwargs): requires_pytorch(self) def from_pretrained(self, *args, **kwargs): requires_pytorch(self)
def filter_desc_df_lm(desc): df = desc return df[[(i, j) for i in ['ppl', 'total_time'] for j in ['mean', 'max', 'min', 'std']]]
.skip(reason='This test is covered by the Xilinx tests.') def test_hardware_axpy_double_pump(veclen=2): with dace.config.set_temporary('compiler', 'xilinx', 'frequency', value='"0:300\\|1:600"'): spec = importlib.util.spec_from_file_location('axpy', ((((Path(__file__).parent.parent.parent / 'samples') / 'fp...
def register_Ns3MeasurementReportHeader_methods(root_module, cls): cls.add_constructor([param('ns3::MeasurementReportHeader const &', 'arg0')]) cls.add_constructor([]) cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'bIterator')], is_virtual=True) cls.add_method('GetMessage', '...
class SExtInst(ConversionInst): code = 'sext' def type_constraints(self, tcs): tcs.integer(self) tcs.integer(self.arg) tcs.specific(self, self.ty) tcs.specific(self.arg, self.src_ty) tcs.width_order(self.arg, self)
def _v1_compatible_scope_naming(scope): if (scope is None): with tf.variable_scope(None, default_name='separable') as s, tf.name_scope(s.original_name_scope): (yield '') else: scope += '_' (yield scope)
class CheckpointConfig(FairseqDataclass): save_dir: str = field(default='checkpoints', metadata={'help': 'path to save checkpoints'}) restore_file: str = field(default='checkpoint_last.pt', metadata={'help': 'filename from which to load checkpoint (default: <save-dir>/checkpoint_last.pt'}) finetune_from_mod...
class CrystalOfAlcovePathsElement(ElementWrapper): def __iter__(self): return iter(self.value) def is_admissible(self): W = WeylGroup(self.parent()._R._cartan_type, prefix='s') s = W.simple_reflections() highest_weight_crystal = self.parent()._highest_weight_crystal if hi...
class AudioArrayClip(AudioClip): def __init__(self, array, fps): Clip.__init__(self) self.array = array self.fps = fps self.duration = ((1.0 * len(array)) / fps) def make_frame(t): if isinstance(t, np.ndarray): array_inds = (self.fps * t).astype(in...
def trace(func, example_inputs, optimize=None, check_trace=True, check_inputs=None, check_tolerance=1e-05, strict=True, _force_outplace=False, _module_class=None, _compilation_unit=_python_cu): if (not _enabled): return func if (optimize is not None): warnings.warn('`optimize` is deprecated and ...
def test_check_increasing_up_extreme(): x = [0, 1, 2, 3, 4, 5] y = [0, 1, 2, 3, 4, 5] with warnings.catch_warnings(): warnings.simplefilter('error', UserWarning) is_increasing = check_increasing(x, y) assert is_increasing
class NllbTokenizer(metaclass=DummyObject): _backends = ['sentencepiece'] def __init__(self, *args, **kwargs): requires_backends(self, ['sentencepiece'])
class NiftiSegmentationLabelList(NiftiImageList): _processor = SegmentationProcessor def __init__(self, items: Iterator, classes: Collection=None, **kwargs): super().__init__(items, **kwargs) self.copy_new.append('classes') (self.classes, self.loss_func) = (classes, None) def reconst...
class SliceParameter(message.Message): __metaclass__ = reflection.GeneratedProtocolMessageType DESCRIPTOR = _SLICEPARAMETER
class ProtocolWrapper(gym.Wrapper): def __init__(self, env, protocol): super(ProtocolWrapper, self).__init__(env) self.protocol = protocol self.env.add_wrapper_info({'evaluation_environment': self.protocol.get_name()}) self._elapsed_episodes = 0 self._elapsed_timesteps = 0 ...
def test_merge_indexed_categorical(): records = ak.contents.IndexedArray(ak.index.Index64([0, 2, 3]), ak.contents.RecordArray([ak.contents.NumpyArray(np.array([4.0, 3.0, 1.0, 9.0, 8.0, 7.0], dtype=np.int64))], ['x'], parameters={'inner': 'bar', 'drop': 'this'}), parameters={'outer': 'foo', 'ignore': 'me', '__array_...
def downsample_with_max_pooling(array): factor = (2, 2, 2) sections = [] for offset in np.ndindex(factor): part = array[tuple((np.s_[o::f] for (o, f) in zip(offset, factor)))] sections.append(part) output = sections[0].copy() for section in sections[1:]: np.maximum(output, se...
class TensorboardXWriter(): def __init__(self, log_dir: str, window_size: int=20, **kwargs): self._window_size = window_size from torch.utils.tensorboard import SummaryWriter self._writer = SummaryWriter(log_dir, **kwargs) def write(self): storage = get_event_storage() fo...
class OutputDiscriminator(nn.Module): def __init__(self, in_channel=2, softmax=False, init=False): super(OutputDiscriminator, self).__init__() self._softmax = softmax filter_num_list = [64, 128, 256, 512, 1] self.upsample = nn.UpsamplingBilinear2d(size=(224, 224)) self.conv1 ...
def recover_formula_internal(prefix_tree): from .propcalc import formula as propcalc_formula if (len(prefix_tree) == 3): bool_formula = (((('(' + prefix_tree[1]) + prefix_tree[0]) + prefix_tree[2]) + ')') else: bool_formula = ''.join(prefix_tree) try: bool_formula = propcalc_form...
def options(opt): opt.add_option('--simu', type='string', help='path to hexapod_dart_simu', dest='simu')
def is_tensor(x): if is_torch_available(): import torch if isinstance(x, torch.Tensor): return True if is_tf_available(): import tensorflow as tf if isinstance(x, tf.Tensor): return True return isinstance(x, np.ndarray)
class ReductionParameter(_message.Message): __metaclass__ = _reflection.GeneratedProtocolMessageType DESCRIPTOR = _REDUCTIONPARAMETER
def get_bootstrap_dataset_config() -> CN: _C = CN() _C.DATASET = '' _C.RATIO = 0.1 _C.IMAGE_LOADER = CN(new_allowed=True) _C.IMAGE_LOADER.TYPE = '' _C.IMAGE_LOADER.BATCH_SIZE = 4 _C.IMAGE_LOADER.NUM_WORKERS = 4 _C.INFERENCE = CN() _C.INFERENCE.INPUT_BATCH_SIZE = 4 _C.INFERENCE.OU...
.operations('slow') def test_hypothesis_deadline(any_app, any_app_schema): execute(any_app_schema, hypothesis_settings=hypothesis.settings(deadline=500)) assert_incoming_requests_num(any_app, 1) assert_request(any_app, 0, 'GET', '/api/slow')
def get_fine_tuning_parameters(model, ft_begin_index): if (ft_begin_index == 0): return model.parameters() ft_module_names = [] for i in range(ft_begin_index, 5): ft_module_names.append('layer{}'.format(i)) ft_module_names.append('fc') parameters = [] for (k, v) in model.named_pa...
def get_std_fsa_1label_2times(): fsa = Fsa() fsa.add_arc(0, 0, BlankLabel) fsa.add_arc(0, 1, Label1) fsa.add_arc(1, 1, Label1) fsa.add_arc(1, 2, BlankLabel) fsa.add_arc(2, 2, BlankLabel) fsa.add_arc(2, 3, Label1) fsa.add_arc(3, 3, Label1) fsa.add_arc(3, 4, BlankLabel) fsa.add_arc...
def get_all_fp_dtypes(include_half=True, include_bfloat16=True) -> List[torch.dtype]: dtypes = [torch.float32, torch.float64] if include_half: dtypes.append(torch.float16) if include_bfloat16: dtypes.append(torch.bfloat16) return dtypes
class Timer(object): def __init__(self): self.reset() def average_time(self): return ((self.total_time / self.calls) if (self.calls > 0) else 0.0) def tic(self): self.start_time = time.time() def toc(self, average=True): self.add((time.time() - self.start_time)) i...
class SimpleConfig(BaseConfig): param: float = 2.0 start_time: float = 0.0 end_time: float = 5.0
def total_intersect_and_union(results, gt_seg_maps, num_classes, ignore_index, label_map=dict(), reduce_zero_label=False): num_imgs = len(results) assert (len(gt_seg_maps) == num_imgs) total_area_intersect = torch.zeros((num_classes,), dtype=torch.float64) total_area_union = torch.zeros((num_classes,), ...
class RuleEG(Rule): def insertion(self, j, r): if (r[(- 1)] <= j): return None y_pos = bisect_right(r, j) if ((r[y_pos] == (j + 1)) and (y_pos > 0) and (j == r[(y_pos - 1)])): j += 1 else: (j, r[y_pos]) = (r[y_pos], j) return j def reve...
.parametrize('time_threshold, user_answer, item_answer', [(datetime.strptime('06-01-2020', '%d-%m-%Y'), [[1, 1, 1, 1, 1, 3, 3, 3, 3, 3], []], [[1, 2, 3, 4, 5, 1, 5, 3, 1, 2], []])]) .parametrize('dataset_type', [pytest.param('spark_dataframe_test', marks=pytest.mark.spark), pytest.param('pandas_dataframe_test', marks=p...
def test_random_state_pickle(): rs = RandomState(seed=0) random_integer = rs.randint(5) pickle_rs = pickle.dumps(rs) pickle_rs = pickle.loads(pickle_rs) pickle_random_integer = pickle_rs.randint(5) assert (random_integer == pickle_random_integer)
def make_kmer_vector(seq_list, kmer_list, rev_kmer_list, k, upto, revcomp, normalize): if upto: index = make_index_upto_k(k) sum = ([0] * k) len_k = k else: index = make_index(k) sum = [0] len_k = 1 vector = [] for seq in seq_list: kmer_count = {} ...
def to_mido_time_signature(time_signature: TimeSignature) -> MetaMessage: return MetaMessage('time_signature', time=time_signature.time, numerator=time_signature.numerator, denominator=time_signature.denominator)
class SpanPadder(Padder): def __init__(self, vocab): super(SpanPadder, self).__init__() self.vocab = vocab self.null_idx = self.vocab['NULL'] self.vocab_size = len(self.vocab) def __call__(self, contents, field_name, field_ele_dtype, dim: int): parent_span = [] ch...
class CornerPoolPack(nn.Module): def __init__(self, dim, pool1, pool2, conv_cfg=None, norm_cfg=None, first_kernel_size=3, kernel_size=3, corner_dim=128): super(CornerPoolPack, self).__init__() self.p1_conv1 = ConvModule(dim, corner_dim, first_kernel_size, stride=1, padding=((first_kernel_size - 1) /...
def save_cache(features, cached_features_file): writer = tf.io.TFRecordWriter(cached_features_file) for (ex_index, feature) in enumerate(features): if ((ex_index % 5000) == 0): logging.info(('Writing example %d of %d' % (ex_index, len(features)))) def create_int_feature(values): ...
def _compute_delta(log_moments, eps): min_delta = 1.0 for (moment_order, log_moment) in log_moments: if (moment_order == 0): continue if (math.isinf(log_moment) or math.isnan(log_moment)): sys.stderr.write(('The %d-th order is inf or Nan\n' % moment_order)) co...
def _op_stats(net_def): type_count = {} for t in [op.type for op in net_def.op]: type_count[t] = (type_count.get(t, 0) + 1) type_count_list = sorted(type_count.items(), key=(lambda kv: kv[0])) type_count_list = sorted(type_count_list, key=(lambda kv: (- kv[1]))) return '\n'.join(('{:>4}x {}'...
class TemplateError(Exception): if PY2: def __init__(self, message=None): if (message is not None): message = text_type(message).encode('utf-8') Exception.__init__(self, message) def message(self): if self.args: message = self.args[...
def test_fft_function(): np.random.seed(1234) import scipy x = (np.random.randn(10) + (1j * np.random.randn(10))) with pytest.deprecated_call(match='1\\.5\\.0'): X = scipy.fft(x) with pytest.deprecated_call(match='2\\.0\\.0'): y = scipy.ifft(X) assert_allclose(y, x) import sc...
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 = [] ...
def read_csv(fname): import pandas return pandas.read_csv(fname, index_col=None, comment='#')
def create_model(opt): model = find_model_using_name(opt.model) instance = model() instance.initialize(opt) instance.print_networks() print(('model [%s] was created' % instance.name())) return instance
def job_fssdJ5q_opt(p, data_source, tr, te, r): return job_fssdJ1q_opt(p, data_source, tr, te, r, J=5)
def _seg_76(): return [(194755, 'M', u''), (194756, 'M', u''), (194757, 'M', u''), (194758, 'M', u''), (194759, 'M', u''), (194760, 'M', u''), (194761, 'M', u''), (194762, 'M', u''), (194763, 'M', u''), (194764, 'M', u''), (194765, 'M', u''), (194766, 'M', u''), (194767, 'M', u''), (194768, 'M', u''), (194769, 'M',...
def main(): args = parse_args() num_classes = (10 if (args.dataset == 'CIFAR10') else 100) have_cuda = torch.cuda.is_available() def cast(x): return (x.cuda() if have_cuda else x) checkpoint = torch.load(args.checkpoint) weights_unpacked = {} for (k, w) in checkpoint.items(): ...
.parametrize('sparse_container', (((CSC_CONTAINERS + CSR_CONTAINERS) + DOK_CONTAINERS) + LIL_CONTAINERS)) def test_silhouette_samples_euclidean_sparse(sparse_container): X = np.array([[0.2, 0.1, 0.1, 0.2, 0.1, 1.6, 0.2, 0.1]], dtype=np.float32).T y = [0, 0, 0, 0, 1, 1, 1, 1] pdist_dense = pairwise_distances...
def fcos_config(): test_cfg = mmcv.Config(dict(deploy_nms_pre=0, min_bbox_size=0, score_thr=0.05, nms=dict(type='nms', iou_threshold=0.5), max_per_img=100)) model = FCOSHead(num_classes=4, in_channels=1, test_cfg=test_cfg) model.requires_grad_(False) return model
def measure_layer(layer, *args): global count_ops, count_params for x in args: delta_ops = 0 delta_params = 0 multi_add = 1 type_name = get_layer_info(layer) if (type_name in ['Conv2d']): out_h = int(((((x.size()[2] + ((2 * layer.padding[0]) / layer.dilation[0...
class Mesh(): def __init__(self, model: MeshModel): self.model = model (self.units, self.num_layers) = (self.model.units, self.model.num_layers) self.pairwise_perm_idx = pairwise_off_diag_permutation(self.units) (ss, cs, sc, cc) = self.model.mzi_error_tensors (self.ss, self.c...
class StringConst(object): def __init__(self, cname, text, byte_string): self.cname = cname self.text = text self.escaped_value = StringEncoding.escape_byte_string(byte_string) self.py_strings = None self.py_versions = [] def add_py_version(self, version): if (not...
class TensorIndex(ABC): def iteration_type(self) -> TensorIterationTypes: pass def locate(self) -> bool: pass def assembly(self) -> TensorAssemblyType: pass def full(self) -> bool: pass def ordered(self) -> bool: pass def unique(self) -> bool: pass...
(nopython=False, fastmath=True, cache=True) def apply_bxmask(u_hat, mask): if (mask is not None): N = mask.shape if (len(N) == 1): mask = np.broadcast_to(mask, u_hat.shape[(- 1)]) for i in range(u_hat.shape[(- 1)]): if (mask[i] == 0): u_hat...
class FlaxSpeechEncoderDecoderModel(metaclass=DummyObject): _backends = ['flax'] def __init__(self, *args, **kwargs): requires_backends(self, ['flax'])
def compute_reduced_graph(set_links): node_indices = utils.get_nodes(set_links) graph = TransitiveGraph(len(node_indices)) for (arg1, arg2, relation) in set_links: node_index1 = node_indices[arg1] node_index2 = node_indices[arg2] graph.add_edge(node_index1, node_index2) closure_m...
def test_vid4_dataset(): root_path = (Path(__file__).parent.parent.parent / 'data') txt_content = 'calendar 1 (320,480,3)\ncity 2 (320,480,3)\n' mocked_open_function = mock_open(read_data=txt_content) with patch('builtins.open', mocked_open_function): vid4_dataset = SRVid4Dataset(lq_folder=(root...
def get_filenames(data_root, task, sub_task, split=''): if (task == 'concode'): data_dir = '{}/{}'.format(data_root, task) train_fn = '{}/train.json'.format(data_dir) dev_fn = '{}/dev.json'.format(data_dir) test_fn = '{}/test.json'.format(data_dir) elif (task == 'summarize'): ...
def register_Ns3WaypointMobilityModel_methods(root_module, cls): cls.add_constructor([param('ns3::WaypointMobilityModel const &', 'arg0')]) cls.add_constructor([]) cls.add_method('AddWaypoint', 'void', [param('ns3::Waypoint const &', 'waypoint')]) cls.add_method('EndMobility', 'void', []) cls.add_me...
((device_cc() < 90), 'Device compute capability is insufficient for SM90 tests.') class GemmF16Sm90(unittest.TestCase): pass
def main(): parser = argparse.ArgumentParser(description='Worker script for the case study.') descriptors = ['Bakery', 'Sour', 'Intensity', 'Sweet', 'Burnt', 'Pleasantness', 'Fish', 'Fruit', 'Garlic', 'Spices', 'Cold', 'Acid', 'Warm', 'Musky', 'Sweaty', 'Ammonia', 'Decayed', 'Wood', 'Grass', 'Flower', 'Chemical...
class Convkxk(nn.Module): def __init__(self, in_planes, out_planes, kernel_size=1, stride=1, padding=0): super(Convkxk, self).__init__() self.conv = nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=padding, bias=False) self.bn = nn.BatchNorm2d(out_planes) ...
_processor(name=TOKENIZE) class TokenizeProcessor(UDProcessor): PROVIDES_DEFAULT = set([TOKENIZE]) REQUIRES_DEFAULT = set([]) MAX_SEQ_LENGTH_DEFAULT = 1000 def _set_up_model(self, config, pipeline, device): if config.get('pretokenized'): self._trainer = None else: ...
class TestDQN(TfGraphTestCase): .large def test_dqn_cartpole(self): with LocalTFRunner(snapshot_config, sess=self.sess) as runner: n_epochs = 10 steps_per_epoch = 10 sampler_batch_size = 500 num_timesteps = ((n_epochs * steps_per_epoch) * sampler_batch_siz...
def add_preprocess_arguments(parser): parser.add_argument('--entity-encoding-form', choices=['canonical', 'type'], default='canonical', help='Input entity form to the encoder') parser.add_argument('--entity-decoding-form', choices=['canonical', 'type'], default='canonical', help='Input entity form to the decode...
class AlbertForMultipleChoice(): def __init__(self, *args, **kwargs): requires_pytorch(self) def from_pretrained(self, *args, **kwargs): requires_pytorch(self)
class Partition22(nn.Module): LAYER_SCOPES = ['T5ForConditionalGeneration/T5Stack[decoder]/T5Block[4]/T5LayerCrossAttention[1]/T5Attention[EncDecAttention]/Linear[o]', 'T5ForConditionalGeneration/T5Stack[decoder]/T5Block[4]/T5LayerCrossAttention[1]/Dropout[dropout]', 'T5ForConditionalGeneration/T5Stack[decoder]/T5B...
_model_architecture('transformer_lm', 'transformer_lm_gpt') def transformer_lm_gpt(args): args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 768) args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', 3072) args.decoder_layers = getattr(args, 'decoder_layers', 12) args.decoder_atte...
class NamedArgument(): def __init__(self, name: str, arg: Argument): self.name = name self.arg = arg