code
stringlengths
101
5.91M
class PropDualVars(): def __init__(self, lambdas, mus): self.lambdas = lambdas self.mus = mus def get_duals_from(weights, additional_coeffs, lower_bounds, upper_bounds, init_type='crown', alphas=None): (mus, mu, lay_idx) = handle_propagation_add_coeff(weights, additional_coeffs, lower_bo...
def convert_func_to_numpy(func, shape, device, dtype): def np_func(t, y): t = torch.tensor(t).to(device, dtype) y = torch.reshape(torch.tensor(y).to(device, dtype), shape) with torch.no_grad(): f = func(t, y) return f.detach().cpu().numpy().reshape((- 1)) return np_fu...
class TestDocsLinks(unittest.TestCase): def check_link(_url): try: response = requests.get(_url) if (response.status_code == 200): return True except Exception as e: print(f"Error checking link '{_url}': {e}") return False def test_...
class ExperimentManager(object): def __init__(self, experiment_dir, model=None, optimizer=None): self.logger = logging.getLogger(type(self).__name__) self.experiment_dir = experiment_dir self.model = model self.optimizer = optimizer self.model_dir = os.path.join(self.experime...
def calculate_iou_simple(pred_arr1, pred_arr2): diff = (pred_arr1.shape[0] - (pred_arr1 - pred_arr2).count_nonzero()) iou = (diff / pred_arr1.shape[0]) return iou.cpu()
def visualfrontend_checker(): device = torch.device(('cuda' if torch.cuda.is_available() else 'cpu')) model = VisualFrontend().to(device) model.to(device) model.eval() (T, N, C, H, W) = (10, args['BATCH_SIZE'], 1, args['ROI_SIZE'], args['ROI_SIZE']) inputBatch = torch.rand(T, N, C, H, W).to(devi...
class TestGammaincc(object): .parametrize('a, x', INVALID_POINTS) def test_domain(self, a, x): assert np.isnan(sc.gammaincc(a, x)) def test_a_eq_0_x_gt_0(self): assert (sc.gammaincc(0, 1) == 0) .parametrize('a, x, desired', [(np.inf, 1, 1), (np.inf, 0, 1), (np.inf, np.inf, np.nan), (1, n...
class Net(): def __init__(self, config, mode): self.config = config self.mode = mode self.w_init = tf.keras.initializers.RandomNormal() self.b_init = tf.keras.initializers.RandomUniform(*self.config.net.b_init) self.build_net() def build_net(self): num_items = sel...
def _invert_perm(perm): perm_inv = ([0] * len(perm)) for (i, j) in enumerate(perm): perm_inv[j] = i return tuple(perm_inv)
class Tacotron2Brain(sb.Brain): def on_fit_start(self): self.hparams.progress_sample_logger.reset() self.last_epoch = 0 self.last_batch = None self.last_preds = None if self.hparams.log_audio_samples: self.vocoder = HIFIGAN.from_hparams(source=self.hparams.vocoder...
def simplify_abs_trig(expr): w0 = SR.wild() if (expr.has(abs_symbolic(sin(w0))) or expr.has(abs_symbolic(cos(w0)))): return SimplifyAbsTrig(expr)() return expr
_utils.test(debug=True) def test_assign_assign(): def func_assign(): a = 0 a = 1 assert (a == 1) func_assign()
def url_to_path(url): assert url.startswith('file:'), 'You can only turn file: urls into filenames (not {url!r})'.format(**locals()) (_, netloc, path, _, _) = urllib_parse.urlsplit(url) if ((not netloc) or (netloc == 'localhost')): netloc = '' elif (sys.platform == 'win32'): netloc = ('\...
class ReflectionPad2d(_ReflectionPadNd): padding: _size_4_t def __init__(self, padding: _size_4_t) -> None: super(ReflectionPad2d, self).__init__() self.padding = _quadruple(padding)
class SamConfig(PretrainedConfig): model_type = 'sam' is_composition = True def __init__(self, vision_config=None, prompt_encoder_config=None, mask_decoder_config=None, initializer_range=0.02, **kwargs): super().__init__(**kwargs) vision_config = (vision_config if (vision_config is not None)...
def test_listoffsetarray(): with open((SAMPLES_DIR / 'awkward1-listoffsetarray.pkl'), 'rb') as file: array = pickle.load(file) assert (array.to_list() == [[1.1, 2.2, 3.3], [], [4.4, 5.5]]) assert (pickle.loads(pickle.dumps(array)).layout.form == array.layout.form)
class PET_Prompt(): def __init__(self, dataset_name=''): (self.label_texts, self.template) = ([], '') if (dataset_name in ['SST-2', 'MR', 'CR']): self.label_texts = ['terrible', 'great'] self.template = '[sentence1] It was [label].' elif (dataset_name == 'Subj'): ...
def random_sample_cls(sentences: List[str], labels: List[str], n_support: int, n_query: int, label: str): data = [sentences[i] for (i, lab) in enumerate(labels) if (lab == label)] perm = torch.randperm(len(data)) idx = perm[:n_support] support = [data[i] for i in idx] idx = perm[n_support:(n_support...
class wordEmbedding(object): def __init__(self, filename): f = open(filename) self.vocab2id = {} self.id2vocab = {} self.vectors = [] id = 0 for line in f.readlines(): word = line.strip().split()[0] vector = np.asarray(map(float, line.split()[1...
def initialize_train_state(config, device): params = [] nnet = get_nnet(**config.nnet) params += nnet.parameters() nnet_ema = get_nnet(**config.nnet) nnet_ema.eval() logging.info(f'nnet has {cnt_params(nnet)} parameters') optimizer = get_optimizer(params, **config.optimizer) lr_scheduler...
class CIFAR10_BASE_DRP05(nn.Module): def __init__(self, dropout=0.5): super(CIFAR10_BASE_DRP05, self).__init__() self.dropout = dropout self.conv_layer = nn.Sequential(nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, padding=1), nn.BatchNorm2d(32), nn.ReLU(inplace=True), nn.Conv2d(in...
def make_discriminator(kind, **kwargs): logging.info(f'Make discriminator {kind}') if (kind == 'pix2pixhd_nlayer_multidilated'): return MultidilatedNLayerDiscriminator(**kwargs) if (kind == 'pix2pixhd_nlayer'): return NLayerDiscriminator(**kwargs) raise ValueError(f'Unknown discriminator...
def load(root): root = os.path.expanduser(root) system = compat_system(root) builder = functools.partial(build, source_dir=root, system=system) path = Path(build_as_zip(builder)) return imp_meta.PathDistribution(path)
class VariationalRecurrentDropout(torch.nn.Module): def __init__(self): super().__init__() def forward(self, x, dropout, mean_field_inference=False): if (mean_field_inference is True): return x else: m = x.data.new(1, x.size(1), x.size(2)).bernoulli_((1 - dropout)...
class BertForQuestionAnswering(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def register_Ns3DefaultSimulatorImpl_methods(root_module, cls): cls.add_constructor([param('ns3::DefaultSimulatorImpl const &', 'arg0')]) cls.add_constructor([]) cls.add_method('Cancel', 'void', [param('ns3::EventId const &', 'id')], is_virtual=True) cls.add_method('Destroy', 'void', [], is_virtual=True...
class GroupMode(enum.Enum): NoneGroup = enum_auto() SingleGroup = enum_auto() MultipleGroup = enum_auto() Depthwise = enum_auto()
def train(hparams, run_opts): test(hparams, run_opts, hparams['base_locales'], f'wer_test_before.txt') for (i, locale) in enumerate(hparams['new_locales']): old_mas_params = hparams.pop('mas_params', None) if (not hparams['skip_mas']): if (i == 0): mas_params = comput...
def _activation(input, activation=None): assert (activation in ['relu', 'leaky', 'tanh', 'sigmoid', None]) if (activation == 'relu'): return tf.nn.relu(input) elif (activation == 'leaky'): return tf.contrib.keras.layers.LeakyReLU(0.1)(input) elif (activation == 'tanh'): return tf...
def compile_single(source, options, full_module_name=None): return run_pipeline(source, options, full_module_name)
class EdgeConv2(MessagePassing): def __init__(self, nn, aggr='max', **kwargs): super(EdgeConv2, self).__init__(aggr=aggr, **kwargs) self.nn = nn self.reset_parameters() def reset_parameters(self): reset(self.nn) def forward(self, x, edge_index): x = (x.unsqueeze((- 1)...
class UninitializedParameter(UninitializedTensorMixin, Parameter): cls_to_become = Parameter def __new__(cls, requires_grad=True, device=None, dtype=None) -> None: factory_kwargs = {'device': device, 'dtype': dtype} data = torch.tensor([], **factory_kwargs) return torch.Tensor._make_subc...
def verify_assignments(assignments): for cur in assignments: for (x, y) in zip(cur[0:(- 1)], cur[1:]): assert (x[1].used < y[1].defined)
_utils.test() def test_atomic_mul_expr_evaled(): c = ti.field(ti.i32) base = 2 ti.root.place(c) def func(): c[None] = 1 for i in range(16): ti.atomic_mul(c[None], base) func() assert (c[None] == (base ** 16))
def load_ckpt(model: torch.nn.Module, optimizer: Optional[torch.optim.Optimizer]=None, scheduler: Optional[Any]=None, epoch: int=(- 1)) -> int: epoch = get_ckpt_epoch(epoch) path = get_ckpt_path(epoch) if (not osp.exists(path)): return 0 ckpt = torch.load(path) model.load_state_dict(ckpt[MOD...
class lora_sdr_lora_rx(gr.hier_block2): def __init__(self, center_freq=, bw=125000, cr=1, has_crc=True, impl_head=False, pay_len=255, samp_rate=250000, sf=7, sync_word=[18], soft_decoding=False, ldro_mode=2, print_rx=[True, True]): gr.hier_block2.__init__(self, 'lora_sdr_lora_rx', gr.io_signature(1, 1, (gr....
class GoogleCalendarCreateOrUpdateEvent(VirtualFunctionTool): name = 'GoogleCalendarCreateOrUpdateEvent' summary = 'Create a new event or update an existing event in the calendar.' parameters: List[ArgParameter] = [{'name': 'event_id', 'type': 'string', 'description': 'The unique identifier of the event to ...
def fOptProps(cid, length, direction, fOptDict=None): if ((cid < 0) or (cid > 255)): raise ValueError('cid must be between 0 and 255') if (length < 0): raise ValueError('length must be positive') if (not isinstance(direction, FOptsDir)): raise ValueError('direction must be an instanc...
def _load_stop_words(stop_words_path): with stop_words_path.open(encoding='utf8') as f: stop_words = set((l.strip() for l in f if l)) return stop_words
class ERFNet(nn.Sequential): def __init__(self, n_classes=19): super().__init__(Downsampler(3, 16, 0.0), Downsampler(16, 64, 0.03), NonBottleneck1D(64, 0.03), NonBottleneck1D(64, 0.03), NonBottleneck1D(64, 0.03), NonBottleneck1D(64, 0.03), NonBottleneck1D(64, 0.03), Downsampler(64, 128, 0.3), NonBottleneck1...
def downsample_module(data, num_filter, kernel, stride, pad, b_h_w, name, aggre_type=None): assert isinstance(data, list) data = mx.sym.concat(*data, dim=0) ret = conv2d_act(data=data, num_filter=num_filter, kernel=kernel, stride=stride, pad=pad, act_type=cfg.MODEL.CNN_ACT_TYPE, name=(name + '_conv')) r...
def register_Ns3TypeId_methods(root_module, cls): cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('<') cls.add_constructor([param('char const *', 'name')]) cls.add_constructor([]) cls.add_co...
.parametrize('device', devices) def test_spline_weighting_backward(device): pseudo = torch.rand((4, 2), dtype=torch.double, device=device) kernel_size = tensor([5, 5], torch.long, device) is_open_spline = tensor([1, 1], torch.uint8, device) degree = 1 (basis, weight_index) = spline_basis(pseudo, ker...
class IndexedRawTextDataset(IndexedDataset): def __init__(self, path, dictionary, append_eos=True, reverse_order=False): self.tokens_list = [] self.lines = [] self.sizes = [] self.append_eos = append_eos self.reverse_order = reverse_order self.read_data(path, dictiona...
def get_emotion(wav_path): num = wav_path.split('_')[(- 1)][:(- 4)] num = (int(num) - 1) if ((num // 350) == 1): return 'angry' elif ((num // 350) == 2): return 'happy' elif ((num // 350) == 3): return 'sad'
def get_device(): is_device_available = {'npu': is_npu_available(), 'cuda': torch.cuda.is_available(), 'mlu': is_mlu_available()} device_list = [k for (k, v) in is_device_available.items() if v] return (device_list[0] if (len(device_list) >= 1) else 'cpu')
def _return_output(input, sorted=True, return_inverse=False, return_counts=False, dim=None): if (not torch.jit.is_scripting()): if ((type(input) is not Tensor) and has_torch_function((input,))): return _unique_impl(input, sorted, return_inverse, return_counts, dim) (output, _, _) = _unique_i...
('/dump', method='POST') def dump_data(): data = measurer.get_data() samples_counter = len(data) with open(out_file, 'w') as f: csv_writer = csv.writer(f) csv_writer.writerow(metrics[args.metric].header()) for val in data: csv_writer.writerow(val) measurer.cleanup()
def test_specify_label(simpledf: dd.DataFrame) -> None: plot_diff([simpledf, simpledf], config={'diff.label': ['label_1', 'label_2']})
_decorator('') def get_orignalmid(html): if is_root(html): return get_mid(html) else: cont = _get_statushtml(html) soup = BeautifulSoup(cont, 'lxml') return soup.find(attrs={'action-type': 'feed_list_item'})['omid']
class ReLU(tf.keras.layers.ReLU): def compute_output_shape(self, input_shape): return tf.TensorShape(input_shape)
def fusion_two_mat(input1, input2, hn=None, scope=None, wd=0.0, keep_prob=1.0, is_train=None): ivec1 = input1.get_shape()[(- 1)] ivec2 = input2.get_shape()[(- 1)] if (hn is None): hn = ivec1 with tf.variable_scope((scope or 'fusion_two_mat')): part1 = linear(input1, hn, False, 0.0, 'line...
class CriteoDataset(torch.utils.data.Dataset): def __init__(self, dataset_path=None, cache_path='.criteo', rebuild_cache=False, min_threshold=10, category_only=False): self.NUM_FEATS = 39 self.NUM_INT_FEATS = 13 self.min_threshold = min_threshold self.category_only = category_only ...
def calc_shifted_geometric_mean(list_of_numbers, shift_by=10.0): geometric_mean = 1.0 nitems = 0 for number in list_of_numbers: nitems = (nitems + 1) nextnumber = (number + shift_by) geometric_mean = (pow(geometric_mean, ((nitems - 1) / float(nitems))) * pow(nextnumber, (1 / float(ni...
def infixNotation(baseExpr, opList, lpar=Suppress('('), rpar=Suppress(')')): ret = Forward() lastExpr = (baseExpr | ((lpar + ret) + rpar)) for (i, operDef) in enumerate(opList): (opExpr, arity, rightLeftAssoc, pa) = (operDef + (None,))[:4] termName = (('%s term' % opExpr) if (arity < 3) else...
def max_unconstrained(weights, lengths, max_ratio): max_tokens = math.ceil((sum(lengths) * max_ratio)) glob_sort = global_argsort(weights) return tuple([g[(- max_tokens):] for g in glob_sort])
def _scikit_umfpack_version(pkg_name): try: import scikits.umfpack scikits.umfpack try: return scikits.umfpack.__version__ except AttributeError: return '<0.3.1' except: return None
class IndexedSequence(SageObject): def __init__(self, L, index_object): try: ind = index_object.list() except AttributeError: ind = list(index_object) self._index_object = index_object self._list = Sequence(L) self._base_ring = self._list.universe() ...
def virtualenv_no_global(): if _running_under_venv(): return _no_global_under_venv() if _running_under_regular_virtualenv(): return _no_global_under_regular_virtualenv() return False
def build_batch_data_sampler(sampler, images_per_batch, group_bin_edges=None, grouping_features=None): if (group_bin_edges and grouping_features): assert isinstance(group_bin_edges, (list, tuple)) assert isinstance(grouping_features, (list, tuple)) group_ids = _quantize(grouping_features, gr...
def supplementary_difference_set(q, existence=False, check=True): from sage.misc.superseded import deprecation deprecation(35211, 'This function is deprecated, please use supplementary_difference_set_from_rel_diff_set instead.') if existence: return supplementary_difference_set_from_rel_diff_set(q, ...
class IndicatorBox(BasePenalty): def __init__(self, alpha): self.alpha = alpha def get_spec(self): spec = (('alpha', float64),) return spec def params_to_dict(self): return dict(alpha=self.alpha) def value(self, w): if (np.max(w) > self.alpha): return ...
class LabelMapper(): UNCERTAIN = (- 1) MISSING = (- 2) def __init__(self, from_seq, to_seq): assert (len(set(from_seq)) == len(from_seq)) assert (len(set(to_seq)) == len(to_seq)) assert (len(set(to_seq.values())) == len(to_seq.values())) assert (len(set(from_seq.values())) ==...
def basinhopping(func, x0, niter=100, T=1.0, stepsize=0.5, minimizer_kwargs=None, take_step=None, accept_test=None, callback=None, interval=50, disp=False, niter_success=None, seed=None, *, target_accept_rate=0.5, stepwise_factor=0.9): if ((target_accept_rate <= 0.0) or (target_accept_rate >= 1.0)): raise V...
class DeepSpeech2Extractor(CNNExtractor): def __init__(self, activation: str='hardtanh', mask_conv: bool=False) -> None: super(DeepSpeech2Extractor, self).__init__(activation) self.mask_conv = mask_conv self.conv = nn.Sequential(nn.Conv2d(1, 32, kernel_size=(41, 11), stride=(2, 2), padding=(...
('just_spaces') class JustSpacesWordSplitter(WordSplitter): def split_words(self, sentence: str) -> List[Token]: return [Token(t) for t in sentence.split()]
def load_non_english_user_set(): non_english_user_set = set(np.load('uids.npz')['data']) return non_english_user_set
def test_clustering_ADP_pure_python_with_merging(): cl = Clustering(coordinates=X) _ = cl.compute_density_kNN(k=5) cl.kstar = (np.ones(cl.N, dtype=int) * 5) _ = cl.compute_clustering_ADP_pure_python() assert (cl.N_clusters == 2) assert (cl.cluster_assignment == expected_cluster_assignment).all()
def get_dense_json_path(data_dir: str, data_type: str, split: str='1.0') -> str: json_path = f'{data_dir}/visdial_{split}_{data_type}_dense_annotations.json' return json_path
class SS3Prompt(Cmd): _args def do_new(self, args): global CLF args = split_args(args) model_name = args[0].lower() if args: if (model_name in MODELS): print() Print.warn(WARN_OVERWRITE, False) if (input() == 'Y'): ...
def cal_running_avg_loss(loss, running_avg_loss, decay=0.99): if (running_avg_loss == 0): return loss else: running_avg_loss = ((running_avg_loss * decay) + ((1 - decay) * loss)) return running_avg_loss
_function def cmunu1(mu, nu): (q, t) = QQqt.gens() for (i, val) in enumerate(nu._list): if (val < mu._list[i]): A = prod(((((t ** mu.leg_length(i, s)) - (q ** (mu.arm_length(i, s) + 1))) / ((t ** nu.leg_length(i, s)) - (q ** (nu.arm_length(i, s) + 1)))) for s in range(val))) B = ...
def load_proto(fpath): with open(fpath, 'rb') as f: loaded = f.read() model = base_pb2.ModelProto().FromString(loaded) return model
def coarse_model(F, bcs, J, y, u, p, config_ocsm): return ocsm.CoarseModel(F, bcs, J, y, u, p, config=config_ocsm)
_set_init def func_set_import_onnx_config(config): def handle_source_func_list(func): source_func_list.append(func) def handle_target_func_list(func, opset): if opset.startswith('opset_'): opset = opset[len('opset_'):] target_func_list.append('{}{}'.format(func, opset)) d...
def test_ifloordiv(): value = 42 copy = proxy = tt.ObjectProxy(value) value //= 3 proxy //= 3 assert (value == proxy) assert (int in tt.UsageTraceNode.from_proxy(copy).children['__ifloordiv__'].arg_types[0])
class TriStageLRScheduler(LearningRateScheduler): def __init__(self, optimizer, init_lr, peak_lr, final_lr, init_lr_scale, final_lr_scale, warmup_steps, total_steps): assert isinstance(warmup_steps, int), 'warmup_steps should be inteager type' assert isinstance(total_steps, int), 'total_steps should...
class BaseMetric(ABC): def __init__(self, name, **kwargs): self.name = name self.kwargs = kwargs def compute(self, y_true, y_pred):
def run_bo_table1_tf(landscape, wt, problem_name, start_num): alphabet = s_utils.DNAA def _robustness(landscape: flexs.Landscape, make_explorer: Callable[([flexs.Model, float, str], flexs.Explorer)]): results = [] for ss in [0.0, 0.5, 0.9, 1.0]: print(f'Evaluating for robustness with...
() class FQEConfig(LearnableConfig): learning_rate: float = 0.0001 optim_factory: OptimizerFactory = make_optimizer_field() encoder_factory: EncoderFactory = make_encoder_field() q_func_factory: QFunctionFactory = make_q_func_field() batch_size: int = 100 gamma: float = 0.99 n_critics: int =...
class Evaluator(): def __init__(self, case_sensitive=False): self.case_sensitive = case_sensitive self.get_edit_distance = editdistance.eval self.anls_threshold = 0.5 self.total_accuracies = [] self.total_anls = [] self.best_accuracy = 0 self.best_epoch = 0 ...
def pad_starts_stops(starts, stops, length): outstarts = [] outstops = [] for x in starts: outstarts.append(x) for y in range(len(stops)): outstops.append((starts[y] + length)) return (outstarts, outstops)
def test_inductor_Q(): ind = Inductor(10, 'GHz', Q=1) assert (ind.Q((- 1), 0) == 1) assert (ind.Q(10, 12) == 1) assert (ind.Q(0, 11) == 1) ind = Inductor(10, 'GHz', Q=.0) assert (ind.Q((- 1), 5) == .0) assert (ind.Q(10, 6) == .0) assert (ind.Q(0, 1) == .0) ind = Inductor(10, 'GHz') ...
class DummyTransf(Transf): def fit(self, X, y): self.means_ = np.mean(X, axis=0) self.timestamp_ = time.time() return self
class AverageMetric(NumericMetric): def show(self): return ('%.2f' % (1.0 * self.value()))
class Adafactor(torch.optim.Optimizer): def __init__(self, params, lr=None, eps=1e-30, eps_scale=0.001, clip_threshold=1.0, decay_rate=(- 0.8), betas=None, weight_decay=0.0, scale_parameter=True, warmup_init=False): relative_step = (not lr) if (warmup_init and (not relative_step)): raise...
def write_cov(cpath, cov, cargs): cfile = open(cpath, 'a') for f in cov: cfile.write(('File: %s\n' % f)) for ctype in sorted(cov[f]): if (ctype == 'function'): for val in sorted(cov[f][ctype]): cfile.write((' %s: %s\n' % (ctype, val))) ...
def _get_global_builtins(): supported_builtins = ['print', 'tuple', 'float', 'int', 'bool', 'str', 'getattr', 'hasattr', 'isinstance', 'len', 'hex', 'oct', 'round', 'hash', 'min', 'max', 'abs', 'all', 'divmod', 'list', 'ord', 'chr', 'bin', 'range', 'zip', 'enumerate', 'sorted'] op_renames = {'bool': 'aten::Bool...
def register_Ns3PbbAddressBlockIpv4_methods(root_module, cls): cls.add_constructor([param('ns3::PbbAddressBlockIpv4 const &', 'arg0')]) cls.add_constructor([]) cls.add_method('DeserializeAddress', 'ns3::Address', [param('uint8_t *', 'buffer')], is_const=True, visibility='protected', is_virtual=True) cls...
def kendall_top_k(a, b, k=None, p=0.5): a = np.array(a) b = np.array(b) if (k is None): k = a.size if (a.size != b.size): raise NameError('The two arrays need to have same lengths') k = min(k, a.size) a_top_k = np.argpartition(a, (- k))[(- k):] b_top_k = np.argpartition(b, (-...
class GoalFollower(RandomAgent): def __init__(self, success_distance, goal_sensor_uuid): super().__init__(success_distance, goal_sensor_uuid) self.pos_th = self.dist_threshold_to_stop self.angle_th = float(np.deg2rad(15)) self.random_prob = 0 def normalize_angle(self, angle): ...
def test_train_gpt2(): dataset = TextDataset(DATASET_OTHER_EXAMPLE_DICT) model = BaseModel.create('distilgpt2') finetuning_config = model.finetuning_config() finetuning_config.num_train_epochs = 1 model.finetune(dataset=dataset) generation_config = model.generation_config() generation_config...
class TFImageClassifierOutputWithNoAttention(ModelOutput): loss: Optional[tf.Tensor] = None logits: tf.Tensor = None hidden_states: Optional[Tuple[(tf.Tensor, ...)]] = None
def _get_ctx59_meta(): stuff_ids = [k['id'] for k in PASCAL_CTX_59_CATEGORIES] assert (len(stuff_ids) == 59), len(stuff_ids) stuff_dataset_id_to_contiguous_id = {k: i for (i, k) in enumerate(stuff_ids)} stuff_classes = [k['name'] for k in PASCAL_CTX_59_CATEGORIES] ret = {'stuff_dataset_id_to_contigu...
class WaveStream(): def __init__(self, filename, is_tmp=False): self.is_tmp = None self.file = open(filename, 'rb') self.wave = wave.open(HackExtensibleWave(self.file)) self.smpsize = (self.wave.getnchannels() * self.wave.getsampwidth()) self.sample_rate = self.wave.getframer...
class TrainableSupportsPredictJointHasReparamSampler(TrainableSupportsPredictJoint, HasReparamSampler, Protocol): pass
def test_render_coverage_report(sample_report, tmp_path: Path): report_path = (tmp_path / 'report.html') render_coverage_report(sample_report, report_path, datetime.datetime(1970, 1, 1)) with report_path.open(encoding='utf-8', mode='r') as file: content = file.readlines() assert (content == ...
_mode('generic') class GenericHyperparameterOptimizationReporter(HyperparameterOptimizationReporter): def __init__(self, reference_date=None, output=None, *args, **kwargs): super().__init__(*args, **kwargs) self.output = (output or sys.stdout) self.reference_date = reference_date sel...
def register_Ns3RrcAsn1Header_methods(root_module, cls): cls.add_constructor([param('ns3::RrcAsn1Header const &', 'arg0')]) cls.add_constructor([]) cls.add_method('GetMessageType', 'int', []) cls.add_method('BandwidthToEnum', 'int', [param('uint8_t', 'bandwidth')], is_const=True, visibility='protected')...
def train_controller(xloader, network, criterion, optimizer, prev_baseline, epoch_str, print_freq, logger): (data_time, batch_time) = (AverageMeter(), AverageMeter()) (GradnormMeter, LossMeter, ValAccMeter, EntropyMeter, BaselineMeter, RewardMeter, xend) = (AverageMeter(), AverageMeter(), AverageMeter(), Averag...