code
stringlengths
101
5.91M
class Director(): def __init__(self, *, tls: bool=True, root_certificate: Union[(Path, str)]=None, private_key: Union[(Path, str)]=None, certificate: Union[(Path, str)]=None, sample_shape: list=None, target_shape: list=None, review_plan_callback: Union[(None, Callable)]=None, envoy_health_check_period: int=60, inst...
class Conv1x1(nn.Module): def __init__(self, in_channels, out_channels, bn_norm, stride=1, groups=1): super(Conv1x1, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, 1, stride=stride, padding=0, bias=False, groups=groups) self.bn = get_norm(bn_norm, out_channels) sel...
def random_rotation(): range = 1 phi = my_rand(0, ((range * math.pi) * 2)) theta = my_rand(0, (range * math.pi)) psi = my_rand(0, ((range * math.pi) * 2)) R0 = [] R0.append(((math.cos(psi) * math.cos(phi)) - ((math.cos(theta) * math.sin(phi)) * math.sin(psi)))) R0.append(((math.cos(psi) * ma...
.parametrize('seed', range(3)) .parametrize('monotonic_cst', (MonotonicConstraint.NO_CST, MonotonicConstraint.POS, MonotonicConstraint.NEG)) def test_nodes_values(monotonic_cst, seed): rng = np.random.RandomState(seed) n_samples = 1000 n_features = 1 X_binned = rng.randint(0, 255, size=(n_samples, n_fea...
def generate_content(index: int, task_id: str, base_filename: str, num_files: int) -> str: if (index == 1): return f'''This task_id is {task_id} Read the file {base_filename}{(index + 1)}.txt''' if (index != num_files): return f'Read the file {base_filename}{(index + 1)}.txt' return 'Write t...
def eval_success(result_file) -> list: df = pd.read_csv(result_file) return df['success'].tolist()
def train(model, x_train, y_train, batch_size, optimizer): model.train() total_loss = 0 for idx in DataLoader(range(y_train.size(0)), batch_size, shuffle=True): optimizer.zero_grad() loss = F.cross_entropy(model(x_train[idx]), y_train[idx]) loss.backward() optimizer.step() ...
def get_train_val_split(train_dataset, val_split=0.2): val_dataset = deepcopy(train_dataset) train_dataset = deepcopy(train_dataset) train_classes = np.unique(train_dataset.targets) train_idxs = [] val_idxs = [] for cls in train_classes: cls_idxs = np.where((train_dataset.targets == cls)...
class SineLR(lr_scheduler._LRScheduler): def __init__(self, optimizer, lr_min, lr_max, step_size): self.lr_min = lr_min self.lr_max = lr_max self.step_size = step_size self.iteration = 0 super().__init__(optimizer, (- 1)) def get_lr(self): lr = (self.lr_min + ((se...
class EvalBoxes(): def __init__(self): self.boxes = defaultdict(list) def __repr__(self): return 'EvalBoxes with {} boxes across {} samples'.format(len(self.all), len(self.sample_tokens)) def __getitem__(self, item) -> List[EvalBoxType]: return self.boxes[item] def __eq__(self, o...
def build_roi_heads(cfg, in_channels): roi_heads = [] if cfg.MODEL.RETINANET_ON: return [] if (not cfg.MODEL.RPN_ONLY): roi_heads.append(('box', build_roi_box_head(cfg, in_channels))) if cfg.MODEL.MASK_ON: roi_heads.append(('mask', build_roi_mask_head(cfg, in_channels))) if c...
def check_nsp(dist, attr, value): ns_packages = value assert_string_list(dist, attr, ns_packages) for nsp in ns_packages: if (not dist.has_contents_for(nsp)): raise DistutilsSetupError(('Distribution contains no modules or packages for ' + ('namespace package %r' % nsp))) (parent...
def set_default_fp_sort(ebits, sbits, ctx=None): global _dflt_fpsort_ebits global _dflt_fpsort_sbits _dflt_fpsort_ebits = ebits _dflt_fpsort_sbits = sbits
def is_image_file(filename): filename_lower = filename.lower() return any((filename_lower.endswith(ext) for ext in IMG_EXTENSIONS))
class _CountryNameDict(LazyDict): def _fill(self): data = {} zone_tab = open_resource('iso3166.tab') try: for line in zone_tab.readlines(): line = line.decode('UTF-8') if line.startswith('#'): continue (code, nam...
def register_Ns3Icmpv4L4Protocol_methods(root_module, cls): cls.add_constructor([param('ns3::Icmpv4L4Protocol const &', 'arg0')]) cls.add_constructor([]) cls.add_method('GetDownTarget', 'ns3::IpL4Protocol::DownTargetCallback', [], is_const=True, is_virtual=True) cls.add_method('GetDownTarget6', 'ns3::Ip...
def test_method_jit(): A = np.random.rand(20) cls = MyTestClass(10) assert np.allclose(cls.method_jit(A), (A + 10))
class TwoAFCDataset(Dataset): def __init__(self, root_dir: str, split: str='train', load_size: int=224, interpolation: transforms.InterpolationMode=transforms.InterpolationMode.BICUBIC, preprocess: str='DEFAULT', **kwargs): self.root_dir = root_dir self.csv = pd.read_csv(os.path.join(self.root_dir, ...
.parametrize('sampling_strategy, sampling_method', [({10: 10}, 'under-sampling'), ({10: 10}, 'over-sampling'), ([10], 'clean-sampling')]) def test_sampling_strategy_class_target_unknown(sampling_strategy, sampling_method): y = np.array(((([1] * 50) + ([2] * 100)) + ([3] * 25))) with pytest.raises(ValueError, ma...
def load_hparam_str(hp_str): path = 'temp-restore.yaml' with open(path, 'w') as f: f.write(hp_str) ret = HParam(path) os.remove(path) return ret
def init_net(net, init_type='normal', init_gain=0.02, gpu_ids=[]): if (len(gpu_ids) > 0): assert torch.cuda.is_available() net.to(gpu_ids[0]) if (len(gpu_ids) > 1): net = torch.nn.DataParallel(net, gpu_ids) init_weights(net, init_type, init_gain=init_gain) return net
class DataTrainingArguments(): dataset_name: Optional[str] = field(default=None, metadata={'help': 'The name of the dataset to use (via the datasets library).'}) dataset_config_name: Optional[str] = field(default=None, metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'}...
.dataclass class Stats(): loss: float losses: float weight_l2: float psnr: float psnrs: float grad_norm: float grad_abs_max: float grad_norm_clipped: float
class Tracker(): def __init__(self, log_dir, n_train_batch): self.log_dir = log_dir self.n_train_batch = n_train_batch self.loss = defaultdict(list) logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S', handlers=[logging.FileHandler((l...
def test_numpytype_int32_parameter(): t = NumpyType('int32', {'__array__': 'Something'}) assert (str(parser.parse(str(t))) == str(t))
def getattribute_from_module(module, attr): if (attr is None): return None if isinstance(attr, tuple): return tuple((getattribute_from_module(module, a) for a in attr)) if hasattr(module, attr): return getattr(module, attr) transformers_module = importlib.import_module('transform...
class BinarizedF(Function): def forward(ctx, input, threshold): ctx.save_for_backward(input, threshold) a = torch.ones_like(input).cuda() b = torch.zeros_like(input).cuda() output = torch.where((input >= threshold), a, b) return output def backward(ctx, grad_output): ...
def show_progress(iterable, total=None, desc=None, silent=False, start_delay=10): return ShowProgress(iterable, total, desc, silent, start_delay)
def parse_keras_history(logs): if hasattr(logs, 'history'): if (not hasattr(logs, 'epoch')): return (None, [], {}) logs.history['epoch'] = logs.epoch logs = logs.history else: logs = {log_key: [single_dict[log_key] for single_dict in logs] for log_key in logs[0]} ...
def load_tf2_state_dict_in_pytorch_model(pt_model, tf_state_dict, allow_missing_keys=False, output_loading_info=False): import torch new_pt_params_dict = {} current_pt_params_dict = dict(pt_model.named_parameters()) start_prefix_to_remove = '' if (not any((s.startswith(pt_model.base_model_prefix) fo...
class CommonMetricPrinter(EventWriter): def __init__(self, yaml, max_iter): self.max_iter = max_iter self.yaml = yaml logger = logging.getLogger('Training') logger.setLevel(logging.DEBUG) logger.propagate = False plain_formatter = logging.Formatter('[%(asctime)s] %(me...
_module() class IndexNetEncoder(nn.Module): def __init__(self, in_channels, out_stride=32, width_mult=1, index_mode='m2o', aspp=True, norm_cfg=dict(type='BN'), freeze_bn=False, use_nonlinear=True, use_context=True): super().__init__() if (out_stride not in [16, 32]): raise ValueError(f'o...
def Welchs_t_test(sample, full, alpha=0.05, axis=0, equal_var=False): np.warnings.filterwarnings('ignore') mask = (sample[axis] == 0.0).values n_space = full[axis].size npfull = np.reshape(full.values, (full.time.size, n_space)) npsample = np.reshape(sample.values, (sample.shape[axis], n_space)) ...
class actor(nn.Module): def __init__(self, env_params): super(actor, self).__init__() self.max_action = env_params['action_max'] self.fc1 = nn.Linear((env_params['obs'] + env_params['goal']), 256) self.fc2 = nn.Linear(256, 256) self.fc3 = nn.Linear(256, 256) self.acti...
class SimpleClient(CachingClient): def __init__(self, cache_config: CacheConfig): super().__init__(cache_config=cache_config) def make_request(self, request: Request) -> RequestResult: raw_request = {'engine': request.model_engine, 'prompt': request.prompt, 'n': request.num_completions} ...
(('%s.visualize_utils.mmcv.imshow' % __name__)) (('%s.visualize_utils.mmcv.imwrite' % __name__)) def test_imshow_text_char_boundary(mock_imshow, mock_imwrite): img = './tests/data/test_img1.jpg' text_quads = [[0, 0, 1, 0, 1, 1, 0, 1]] boundaries = [[0, 0, 1, 0, 1, 1, 0, 1]] char_quads = [[[0, 0, 1, 0, 1...
def get_home_dir(): _home_dir = os.environ.get('AUTO_MM_BENCH_HOME', os.path.join('~', '.auto_mm_bench')) _home_dir = os.path.expanduser(_home_dir) return _home_dir
class Composer(): def __init__(self): self.anchors = {} def check_node(self): if self.check_event(StreamStartEvent): self.get_event() return (not self.check_event(StreamEndEvent)) def get_node(self): if (not self.check_event(StreamEndEvent)): return se...
def load_data_normalised(root_path): (data_train, data_validate, data_test) = load_data(root_path) data = np.vstack((data_train, data_validate)) mu = data.mean(axis=0) s = data.std(axis=0) data_train = ((data_train - mu) / s) data_validate = ((data_validate - mu) / s) data_test = ((data_test...
class ResidueReductionMap(Morphism): def _create_(R, k): if R.is_field(): from sage.categories.sets_with_partial_maps import SetsWithPartialMaps cat = SetsWithPartialMaps() else: from sage.categories.rings import Rings cat = Rings() from sage.c...
def test_horizon_0_180_days(tmp_path: pathlib.Path): time_horizon = TimeHorizon(datetime.timedelta(days=0), datetime.timedelta(days=180)) labeler = DummyLabeler([2], time_horizon) events_with_labels: EventsWithLabels = [(event((2015, 1, 3), 2, None), 'duplicate'), (event((2015, 1, 3), 1, None), 'duplicate')...
def box_viz(df: pd.DataFrame, x: str, plot_width: int, plot_height: int, box: Box, y: Optional[str]=None, ttl_grps: Optional[int]=None) -> Panel: if (y and ttl_grps): width = 0.7 grp_cnt_stats = {f'{x}_ttl': ttl_grps, f'{x}_shw': len(df)} title = (_make_title(grp_cnt_stats, x, y) if ttl_grps...
class DataGenerationMethod(str, Enum): positive = 'positive' negative = 'negative' def default(cls) -> DataGenerationMethod: return cls.positive def all(cls) -> list[DataGenerationMethod]: return list(DataGenerationMethod) def as_short_name(self) -> str: return {DataGeneratio...
def op_t5_3b_tied_lmheads_512_4_8p_bw12_async_squad1_mpipe(): return dict(model_type='new_t5_stateless', model_name_or_path='t5-3b', do_lower_case=False, output_past=False, output_attentions=False, output_hidden_states=False, do_resize_token_embedding=True, explicitly_set_dict={'return_dict': False, 'use_cache': Fa...
def _vgg(arch: str, cfg: str, batch_norm: bool, pretrained: bool, progress: bool, **kwargs: Any) -> VGG: if pretrained: kwargs['init_weights'] = False model = VGG(make_layers(cfgs[cfg], batch_norm=batch_norm), **kwargs) if pretrained: state_dict = load_state_dict_from_url(model_urls[arch], p...
def test_functional_exceptions(variable_x): x = variable_x with pytest.raises(TypeError): f = sn.Functional(x) with pytest.raises(TypeError): ft = sn.Functional('ft', (2 * [10])) with pytest.raises(TypeError): ft = sn.Functional('ft', x, 'tanh') with pytest.raises(TypeError):...
def make_sdfg(make_tmp_local: bool): sdfg = dace.SDFG('instrumentation_test') sdfg.add_array('in0', (16,), dace.float32) sdfg.add_array('in1', (16,), dace.float32) sdfg.add_array('in2', (16,), dace.float32) sdfg.add_array('tmp0', (16,), dace.float32, transient=True) sdfg.add_array('tmp1', (16,),...
def GetRndWalkRestart_PNGraph(Graph, JumpProb, JumpNId, RwrNIdH): return _snap.GetRndWalkRestart_PNGraph(Graph, JumpProb, JumpNId, RwrNIdH)
class SqueezeBertTokenizer(PreTrainedTokenizer): vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__(self, vocab_file, d...
def make_sdfg(dtype): n = dace.symbol('n') sdfg = dace.SDFG('mpi_bcast') state = sdfg.add_state('dataflow') sdfg.add_array('x', [n], dtype, transient=False) sdfg.add_array('root', [1], dace.dtypes.int32, transient=False) x = state.add_access('x') xout = state.add_access('x') root = state...
def self_attention(x, channels, sn=False, scope='self_attention'): with tf.variable_scope(scope): f = conv(x, (channels // 8), kernel=1, stride=1, sn=sn, scope='f_conv') g = conv(x, (channels // 8), kernel=1, stride=1, sn=sn, scope='g_conv') h = conv(x, channels, kernel=1, stride=1, sn=sn, s...
def get_final_weights(weights, lora_module_list, cache): final_state_dict = {} keys = cache[lora_module_list[0]].keys() for (i, peft_model_id) in enumerate(lora_module_list): lora_state_dict = cache[peft_model_id] if (i == 0): for key in keys: final_state_dict[key...
def conv2d_gradfix(transpose, weight_shape, stride, padding, output_padding, dilation, groups): ndim = 2 weight_shape = tuple(weight_shape) stride = ensure_tuple(stride, ndim) padding = ensure_tuple(padding, ndim) output_padding = ensure_tuple(output_padding, ndim) dilation = ensure_tuple(dilati...
(repr=False, eq=False, frozen=True) class FunctionCounts(object): _data: Tuple[(FunctionCount, ...)] inclusive: bool truncate_rows: bool = True _linewidth: Optional[int] = None def __iter__(self) -> Generator[(FunctionCount, None, None)]: for i in self._data: (yield i) def __...
def store(self): old1(self) db = os.path.join(self.variant_dir, EXTRA_LOCK) env = ConfigSet.ConfigSet() env.SRCDIR = self.srcnode.abspath() env.store(db)
def streams(patch, params): o_retina = siam_stream(F.pad(patch, (((- 16),) * 4)), params, 'retina') o_fovea = siam_stream(F.avg_pool2d(patch, 2, 2), params, 'fovea') return torch.cat([o_retina, o_fovea], dim=1)
class StatementCheckedTestSuiteFitnessFunction(TestSuiteFitnessFunction): def compute_fitness(self, individual) -> float: results = self._run_test_suite_chromosome(individual) merged_trace = analyze_results(results) tracer = self._executor.tracer return (len(tracer.get_subject_proper...
class MultiHeadedAttention(nn.Module): def __init__(self, d_model, head, p=0.1): super().__init__() self.query_embedding = nn.Linear(d_model, d_model) self.value_embedding = nn.Linear(d_model, d_model) self.key_embedding = nn.Linear(d_model, d_model) self.output_linear = nn.L...
class OperationInfo(): def __init__(self, bound_name, op_name, ast_node, position, perf_hints): self.bound_name = bound_name self.op_name = op_name self.ast_node = ast_node self.position = position self.perf_hints = perf_hints self.usages = [] self.runtime_us ...
_numpy_output(check_dtype=True) def test_ufunc_arccos_c(A: dace.complex64[10]): return np.arccos(A)
_criterion('sentence_prediction', dataclass=SentencePredictionConfig) class SentencePredictionCriterion(FairseqCriterion): def __init__(self, cfg: SentencePredictionConfig, task): super().__init__(task) self.classification_head_name = cfg.classification_head_name self.regression_target = cfg...
def return_rel_docs_for_dict(labels: dict, dpr_dict: dict): label_keys = [key for key in labels] dpr_keys = [key for key in dpr_dict] assert (label_keys.sort() == dpr_keys.sort()) print('im here') filtered_dict = {} for query_id in labels.keys(): filtered_dict.update({query_id: {}}) ...
def test_initialize_object_binary_policy(digraph_with_object_policy): with pytest.raises(ValueError): digraph_with_object_policy._initialize_binary_policy()
def get_datapoints(): base = '/ssd_scratch/cvit/aditya1/processed_vlog_dataset_copy' valid_videos_json_path = os.path.join(base, 'valid_folders.json') min_landmark_files = 3 def get_name(x): return '/'.join(x.split('/')[(- 4):]) with open(valid_videos_json_path) as r: valid_videos = ...
def test_points2polygon(): with pytest.raises(AssertionError): points = 2 utils.points2polygon(points) with pytest.raises(AssertionError): points = [1, 2, 3, 4, 5, 6, 7] utils.points2polygon(points) with pytest.raises(AssertionError): points = [1, 2, 3, 4, 5, 6] ...
def get_suffix_path(current_path, levels=1): current_new = current_path for i in range((levels + 1)): current_new = os.path.dirname(current_new) return os.path.relpath(current_path, current_new)
def test_merge(): trace0 = ExecutionTrace() trace1 = ExecutionTrace() trace0.merge(trace1) assert (trace0 == ExecutionTrace())
def multi_func(member_check): def f(col): return member_check(col.name, col) return f
def lengths_to_encoder_padding_mask(lengths, batch_first: bool=False): max_lengths = torch.max(lengths).item() bsz = lengths.size(0) encoder_padding_mask = (torch.arange(max_lengths).to(lengths.device).view(1, max_lengths).expand(bsz, (- 1)) > lengths.view(bsz, 1).expand((- 1), max_lengths)) if (not bat...
class BetaSobolev(ProcessingPlasmaProperty): outputs = ('beta_sobolev',) latex_name = ('\\beta_{\\textrm{sobolev}}',) def calculate(self, tau_sobolevs): if (getattr(self, 'beta_sobolev', None) is None): initial = 0.0 else: initial = self.beta_sobolev beta_sobo...
class InputFeatures(object): def __init__(self, unique_id, example_index, doc_span_index, tokens, token_to_orig_map, token_is_max_context, input_ids, input_mask, segment_ids, cls_index, p_mask, paragraph_len, start_position=None, end_position=None, is_impossible=None): self.unique_id = unique_id sel...
class RandomCrop(object): def __init__(self, size, padding=0): if isinstance(size, numbers.Number): self.size = (int(size), int(size)) else: self.size = size self.padding = padding def get_params(img, output_size): (w, h) = img.size (th, tw) = outp...
def conv2d(input_, output_dim, ks=7, s=2, stddev=0.02, padding='SAME', name='conv2d'): with tf.variable_scope(name): return slim.conv2d(input_, output_dim, ks, s, padding=padding, activation_fn=None, weights_initializer=tf.truncated_normal_initializer(stddev=stddev), biases_initializer=None)
class Plotter(): __plotters = [] def __init__(self, env, policy, sess=None, graph=None, rollout=default_rollout): Plotter.__plotters.append(self) self.env = env self.policy = policy self.sess = (tf.compat.v1.get_default_session() if (sess is None) else sess) self.graph = ...
def test_generation_sort_by_len(file_factory, trained_model): with file_factory() as results_file: (trained_model_pickle, model_type) = trained_model log = invoke_wfp_script('generate', model_pickle=trained_model_pickle.name, data_path=DATA_PATH, output_pickle=results_file.name, sort_by_len=True, it...
def save_svg(state: State, filename: Union[(str, Path)], *, color_theme: Optional[Literal[('light', 'dark')]]=None, scale: Optional[float]=None) -> None: assert str(filename).endswith('.svg') if state.env_id.startswith('minatar'): state.save_svg(filename=filename) else: v = Visualizer(color_...
class SelectPolicy(): def __init__(self, fuzzer: GPTFuzzer): self.fuzzer = fuzzer def select(self) -> PromptNode: raise NotImplementedError('SelectPolicy must implement select method.') def update(self, prompt_nodes: 'list[PromptNode]'): pass
def MkdirFileLock(*args, **kwds): from . import mkdirlockfile return _fl_helper(mkdirlockfile.MkdirLockFile, 'lockfile.mkdirlockfile', *args, **kwds)
class Highway(torch.nn.Module): def __init__(self, input_dim: int, num_layers: int=1): super(Highway, self).__init__() self.input_dim = input_dim self.layers = nn.ModuleList([nn.Linear(input_dim, (input_dim * 2)) for _ in range(num_layers)]) self.activation = nn.ReLU() self.r...
class RL2PPO(RL2): def __init__(self, rl2_max_path_length, meta_batch_size, task_sampler, env_spec, policy, baseline, scope=None, max_path_length=500, discount=0.99, gae_lambda=1, center_adv=True, positive_adv=False, fixed_horizon=False, lr_clip_range=0.01, max_kl_step=0.01, optimizer_args=None, policy_ent_coeff=0....
def compute_num_params(G0, growth_factor, T0, D, levels): num_params = 0 for l in range(levels): G = compute_grid_size(G0, growth_factor, T0, l) T = compute_table_size(G, T0) num_params_l = force_align((T * D)) num_params += num_params_l return num_params
class SawyerAssemblyV1Policy(Policy): _fully_parsed def _parse_obs(obs): return {'hand_pos': obs[:3], 'wrench_pos': obs[3:6], 'peg_pos': obs[9:], 'unused_info': obs[6:9]} def get_action(self, obs): o_d = self._parse_obs(obs) action = Action({'delta_pos': np.arange(3), 'grab_effort': ...
.parametrize('action_dist, estimated_rewards_by_reg_model, description_1', valid_input_of_create_estimator_inputs) .parametrize('metric, ground_truth_policy_value, description_2', valid_input_of_evaluation_performance_of_estimators) def test_meta_evaluate_performance_of_estimators_using_valid_input_data(action_dist, es...
class MatchFirst(ParseExpression): def __init__(self, exprs, savelist=False): super(MatchFirst, self).__init__(exprs, savelist) if self.exprs: self.mayReturnEmpty = any((e.mayReturnEmpty for e in self.exprs)) else: self.mayReturnEmpty = True def streamline(self): ...
def read_csv_Raed(path): orig = pd.read_csv(path) orig = orig.drop('Unnamed: 0', axis=1) orig.index = pd.to_datetime([f'{y}-01-01' for y in orig.Year]) orig.index.name = 'time' return orig.drop('Year', 1)
def api_test(env: Env, num: int=100, use_key=True): api_test_single(env, num, use_key) api_test_batch(env, num, use_key)
def disable_text_training(cfg): new_cfg = copy.deepcopy(cfg) new_cfg['models']['MultimodalTextModel']['search_space']['model.num_trainable_layers'] = 0 new_cfg['models']['MultimodalTextModel']['search_space']['model._disable_update'] = True new_cfg['models']['MultimodalTextModel']['search_space']['optim...
class BaseTokenizer(): def __init__(self, tokens: List[str], starting_index=None, init_token='[CLS]', eos_token='[SEP]', pad_token='[PAD]', unk_token='[UNK]'): if (starting_index is None): starting_index = 4 self.pad_token = pad_token self.bos_token = init_token self.eos_...
def nag(opfunc, x, config, state=None): if ((config is None) and (state is None)): raise ValueError('nag requires a dictionary to retain state between iterations') state = (state if (state is not None) else config) lr = config.get('learningRate', 0.001) lrd = config.get('learningRateDecay', 0) ...
class ResNet(tf.keras.Model): _MODEL_CONFIG = {10: {'block': residual_block, 'layers': [1, 1, 1, 1]}, 14: {'block': bottleneck_block, 'layers': [1, 1, 1, 1]}, 18: {'block': residual_block, 'layers': [2, 2, 2, 2]}, 26: {'block': bottleneck_block, 'layers': [2, 2, 2, 2]}, 34: {'block': residual_block, 'layers': [3, 4...
def sn_dense(inputs, units, name='sn_dense'): with tf.variable_scope(name) as scope: weight = tf.get_variable('w', [inputs.get_shape()[1], units], tf.float32, initializer=DENSE_KERNEL_INITIALIZER) bias = tf.get_variable('b', [units], initializer=tf.zeros_initializer()) return (tf.matmul(inpu...
class RefLion(MixinWeightDecayFused, RefSolver): def __init__(self, lr, beta1, beta2): super().__init__() self.lr = _f(lr) self.beta1 = _f(beta1) self.beta2 = _f(beta2) self.m = {} self.t = {} def _set_state_impl(self, key, param): self.m[key] = np.zeros_l...
class UNet(nn.Module): def __init__(self, n_channels, n_classes, bilinear=False): super(UNet, self).__init__() self.n_channels = n_channels self.n_classes = n_classes self.bilinear = bilinear self.in_conv = UNetConvBlock(self.n_channels, 64) self.Down1 = Down(64, 128)...
def test_bucket_deletion(): print('Running test_bucket_deletion') storage_1 = storage.Storage(name=TEST_BUCKET_NAME, source=LOCAL_SOURCE_PATH) storage_1.add_store(StoreType.S3) storage_1.add_store(StoreType.GCS) storage_1.delete()
class GradientsInputs(VanillaGradients): def compute_gradients(images, model, class_index): gradients = VanillaGradients.compute_gradients(images, model, class_index) inputs = tf.cast(images, tf.float32) return tf.multiply(inputs, gradients)
def visualize(base_path, test_dataset, plot_dir, batch_size=4): device = torch.device('cuda') dataset = HeadDataset(test_dataset, base_path, dataset_param={}, train=False) batch_iterator = iter(data.DataLoader(dataset, batch_size, shuffle=False, num_workers=4, collate_fn=coco_collate)) for (ind, (images...
class OpenAIGPTTokenizerFast(): def __init__(self, *args, **kwargs): requires_tokenizers(self) def from_pretrained(self, *args, **kwargs): requires_tokenizers(self)
class TestBMUF(unittest.TestCase): def bmuf_process(self, args, iterations): processes = [] results = Manager().dict() ctx = torch.multiprocessing.get_context('spawn') for rank in range(args.distributed_world_size): p = ctx.Process(target=single_gpu_training, args=(args, ...
def parse_match_formulas(match_parse): assert isinstance(match_parse, MatchParse) match_atoms = [] for (label, terms) in match_parse.match_dict.iteritems(): for term in terms: assert isinstance(term, FormulaNode) if issubtype(term.return_type, 'entity'): if (t...
class ASTNode(): def __init__(self, nb=None, depth=None, children=None): self.id = nb self.depth = depth self.children = children self.production = None