code
stringlengths
101
5.91M
def parse_command_args(training_or_testing): if (training_or_testing == 'training'): parser = argparse.ArgumentParser(description='BoundingBox-less Location with PyTorch.', formatter_class=CustomFormatter) optional_args = parser._action_groups.pop() required_args = parser.add_argument_group(...
def insert_tagged_tokens(tokens, tags, template): to_insert = {} cur = (None, []) for (token, tag) in zip(tokens, tags): if (tag != cur[0]): if (cur[0] is not None): value = ' '.join(cur[1]) to_insert[cur[0]] = value if (tag == 'O'): ...
class Optimizable_optimizer(Optimizer): def __init__(self, optimizer: Optimizer, num_epochs: int): super(optimizer, self).__init__(num_epochs) self.optimizer = optimizer def optimize(self, temp_model: ModelWithTemperature, lr: float, nll_criterion, logits: torch.FloatTensor, labels: torch.FloatT...
_model('lstm_lm') class LSTMLanguageModel(FairseqLanguageModel): def __init__(self, decoder): super().__init__(decoder) def add_args(parser): parser.add_argument('--dropout', type=float, metavar='D', help='dropout probability') parser.add_argument('--decoder-embed-dim', type=int, metavar...
def _open_stream(stream, read_or_write): if hasattr(stream, read_or_write): return (False, stream) try: return (True, open(stream, (read_or_write[0] + 'b'))) except TypeError: raise RuntimeError('expected open file or filename')
def parse_args(): parser = argparse.ArgumentParser(description='Code generator for tensor contruction') parser.add_argument('-s', metavar='style', dest='style', type=str, default=None, choices=['numpy', 'mptensor'], help='set output style ("numpy" or "mptensor")') parser.add_argument('-v', '--verbose', acti...
def CheckArgs(args): if (not os.path.exists(args.config_dir)): os.makedirs(args.config_dir) if (args.feat_dir is not None): args.feat_dim = common_lib.get_feat_dim(args.feat_dir) if (args.ali_dir is not None): args.num_targets = common_lib.get_number_of_leaves_from_tree(args.ali_dir)...
def preresnet101(**kwargs): return get_preresnet(blocks=101, model_name='preresnet101', **kwargs)
class T5Adapter(BaseAdapter): def match(self, model_path: str): return ('t5' in model_path) def load_model(self, model_path: str, from_pretrained_kwargs: dict): tokenizer = T5Tokenizer.from_pretrained(model_path, use_fast=False) model = AutoModelForSeq2SeqLM.from_pretrained(model_path, l...
class Cell(object): def __init__(self, data=None, fmt=None, span=1, align=None): self.data = data if (fmt is None): fmt = CellFormat() if isinstance(fmt, str): fmt = CellFormat(fmt=fmt) self.fmt = fmt self.span = span self.align = align def...
class MolGraph(): def __init__(self, smiles: str, args: Namespace): self.smiles = smiles self.n_atoms = 0 self.n_bonds = 0 self.f_atoms = [] self.f_bonds = [] self.a2b = [] self.b2a = [] self.b2revb = [] mol = Chem.MolFromSmiles(smiles) ...
class OptimizationMethod(object): def __init__(self, name, group, supported_devices=['cpu', 'cuda'], min_sm_version=None, opt_computation=None, opt_memory=None, opt_communication=None, distributed_only=False, process_mode='ONE_PROCESS', is_tunable=True): self.name = name self.group = group s...
def write_predictions(all_examples, all_features, all_results, n_best_size, max_answer_length, do_lower_case, output_prediction_file, output_nbest_file, output_null_log_odds_file, verbose_logging, version_2_with_negative, null_score_diff_threshold): logger.info(('Writing predictions to: %s' % output_prediction_file...
def save_pickle(filepath, x): with open(filepath, 'wb') as handle: pickle.dump(x, handle, protocol=pickle.HIGHEST_PROTOCOL)
class SigmoidNode(Node): def __init__(self, prev_node): super().__init__(prev_node) self.in_var = prev_node.out_var self.in_dim = prev_node.out_dim self.out_dim = self.in_dim self.out_var = Allocation.allocate_var('float', 'x', self.out_dim) def lowering(self): (l...
def fuse_bn(conv, bn): kernel = conv.weight running_mean = bn.running_mean running_var = bn.running_var gamma = bn.weight beta = bn.bias eps = bn.eps std = (running_var + eps).sqrt() t = (gamma / std).reshape((- 1), 1, 1, 1) return ((kernel * t), (beta - ((running_mean * gamma) / std...
def main(): reader = csv.reader(sys.stdin) writer = csv.writer(sys.stdout) header = True for row in reader: fixed_spans = row[0] if (not header): fixed_spans = _fix_spans(ast.literal_eval(row[0]), row[1]) writer.writerow([fixed_spans, row[1]]) header = False
class DistilBertModel(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
class EndToEndModel(nn.Module): def __init__(self, segm_model, pose_model, object_names, object_ids): super(EndToEndModel, self).__init__() self.segm_model = segm_model self.resize = nn.AdaptiveMaxPool2d((240, 320)) self.pose_model = pose_model self.object_names = object_name...
class myMerlinFlow(FlowSpec): MODEL_FOLDER = Parameter(name='model_folder', help='Folder to store the model from Merlin, between steps', default='merlin_model') ROW_SAMPLING = Parameter(name='row_sampling', help='Snowflake row sampling: if 0, NO sampling is applied', default='1') TRAINING_END_DATE = Paramet...
def split_data_slice(data, output_file, slice_id, days_offset, days_train, days_test): data_start = datetime.fromtimestamp(data.Time.min(), timezone.utc) data_end = datetime.fromtimestamp(data.Time.max(), timezone.utc) print('Full data set {}\n\tEvents: {}\n\tSessions: {}\n\tItems: {}\n\tSpan: {} / {}'.form...
class MetricList(): def __init__(self, metrics): assert isinstance(metrics, dict), "'metrics' must be a dictionary of callables" self.metrics = metrics self.results = {key: 0.0 for key in self.metrics.keys()} def __call__(self, y_out, y_batch): for (key, value) in self.metrics.it...
def TorchComplexMul(v1_complex, v2_complex): (v1_real, v1_imag) = v1_complex.chunk(2, dim=(- 1)) (v2_real, v2_imag) = v2_complex.chunk(2, dim=(- 1)) return torch.cat((((v1_real * v2_real) - (v1_imag * v2_imag)), ((v1_real * v2_imag) + (v1_imag * v2_real))), dim=(- 1))
def mock_k8s_client(): k8s_client = k8sClient.singleton_instance('default') k8s_client.get_custom_resource = _get_training_job k8s_client.get_pod = _get_pod k8s_client.list_namespaced_pod = mock_list_namespaced_pod k8s_client.create_custom_resource = mock.MagicMock(return_value=True) k8s_client....
def convert_examples_to_features(examples, label_list, max_seq_length, tokenizer, output_mode, cls_token_at_end=False, pad_on_left=False, cls_token='[CLS]', sep_token='[SEP]', pad_token=0, sequence_a_segment_id=0, sequence_b_segment_id=1, cls_token_segment_id=1, pad_token_segment_id=0, mask_padding_with_zero=True, do_l...
class ErnieForMaskedLM(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def get_bernoulli_vae_schema(config): return [{'type': 'flatten'}, {'type': 'bernoulli-likelihood', 'num_z_channels': config['num_z_channels'], 'logit_net': {'type': 'mlp', 'activation': 'tanh', 'hidden_channels': config['logit_net']}, 'q_coupler': get_q_coupler_config(config, flattened=True)}]
def build_fake_yaml(): fake_yaml = '\n model:\n name: fake_yaml\n framework: tensorflow\n inputs: input\n device: cpu\n quantization:\n model_wise:\n weight:\n granularity: per_tensor\n scheme: sym\n dty...
def test_set_reactivity(): assert (flow().mut_settings.reactivity_mode == ReactivityMode.BATCH) run_cell(f'%flow reactivity {ReactivityMode.INCREMENTAL.value}') assert (flow().mut_settings.reactivity_mode == ReactivityMode.INCREMENTAL) run_cell(f'%flow reactivity {ReactivityMode.BATCH.value}') asser...
class Residual(nn.Module): def __init__(self, do_batchnorm, c, **kw): super().__init__() self.res1 = ConvBN(do_batchnorm, c, c, **kw) self.res2 = ConvBN(do_batchnorm, c, c, **kw) def forward(self, x): return (x + F.relu(self.res2(self.res1(x)))) def prep_finetune(self, iid, c...
_module() class DistSamplerSeedHook(Hook): def before_epoch(self, runner): if hasattr(runner.data_loader.sampler, 'set_epoch'): runner.data_loader.sampler.set_epoch(runner.epoch) elif hasattr(runner.data_loader.batch_sampler.sampler, 'set_epoch'): runner.data_loader.batch_sam...
def init_yolov3(args, device): import torch from models.yolo import Model from utils.google_utils import attempt_download from utils.torch_utils import intersect_dicts, torch_distributed_zero_first log.info('Loading yolov3.pt weights.') hyp = args.yolo_hyp() with torch_distributed_zero_first...
class ConditionalBatchNorm2d(nn.Module): def __init__(self, num_features, num_classes, eps=0.0001, momentum=0.1): super().__init__() self.num_features = num_features self.bn = nn.BatchNorm2d(num_features, affine=False, eps=eps, momentum=momentum) self.gamma_embed = SpectralNorm(nn.Li...
def deeplabv3plus_pvtv2(num_classes=1, output_stride=8, pretrained_backbone=True): return _segm_pvtv2('deeplabv3plus', 'pvtv2', num_classes, output_stride=output_stride, pretrained_backbone=pretrained_backbone)
def test_eddington_differentpotentials_dMdE_integral(): pots = [potential.PlummerPotential(amp=2.3, b=1.3), potential.PowerSphericalPotentialwCutoff(amp=1.3, alpha=1.9, rc=1.2)] tols = [1e-06 for pot in pots] for (pot, tol) in zip(pots, tols): dfh = eddingtondf(pot=pot) check_dMdE_integral(d...
def set_visible_area(point_dict, axes): min_x = .0 min_y = .0 max_x = (- .0) max_y = (- .0) for (id, point) in dict_utils.get_item_iterator(point_dict): min_x = min(point.x, min_x) min_y = min(point.y, min_y) max_x = max(point.x, max_x) max_y = max(point.y, max_y) ...
def prototype_test(): state = prototype_state() state['train_dialogues'] = './tests/data/ttrain.dialogues.pkl' state['test_dialogues'] = './tests/data/ttest.dialogues.pkl' state['valid_dialogues'] = './tests/data/tvalid.dialogues.pkl' state['dictionary'] = './tests/data/ttrain.dict.pkl' state['s...
def get_processor_name(): if (platform.system() == 'Windows'): return platform.processor() elif (platform.system() == 'Darwin'): os.environ['PATH'] = ((os.environ['PATH'] + os.pathsep) + '/usr/sbin') command = 'sysctl -n machdep.cpu.brand_string' return subprocess.check_output(co...
def main(): args = get_argument() if args.resnet: import torchvision.models as models model = models.resnet18(pretrained=True) model = ProbModel(model) else: model = mobilenet_v2('modeling/classification/mobilenetv2_1.0-f2a8633.pth.tar') model = ProbModel(model) m...
class AlbertTokenizerFast(PreTrainedTokenizerFast): vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES slow_tokenizer_class = AlbertTokenizer def __init__(self, vocab_file=None, tokenizer_file=N...
class HRModule(nn.Module): def __init__(self, num_branches, blocks, num_blocks, in_channels, num_channels, multiscale_output=True, with_cp=False, conv_cfg=None, norm_cfg=dict(type='BN')): super(HRModule, self).__init__() self._check_branches(num_branches, num_blocks, in_channels, num_channels) ...
def create_model(bert_config, is_training, input_ids, input_mask, P_mask, A_mask, B_mask, segment_ids, labels, num_labels, use_one_hot_embeddings): model = modeling.BertModel(config=bert_config, is_training=is_training, input_ids=input_ids, input_mask=input_mask, token_type_ids=segment_ids, use_one_hot_embeddings=u...
def checkpoint(step, epoch): model_out_path = 'models/{}/GFN_epoch_{}.pkl'.format(step, epoch) torch.save(model, model_out_path) print('===>Checkpoint saved to {}'.format(model_out_path))
class ounoise(): def __init__(self, std, action_dim, mean=0, theta=0.15, dt=0.01, x0=None): self.std = std self.mean = mean self.action_dim = action_dim self.theta = theta self.dt = dt self.x0 = x0 def reset(self): self.x_prev = (self.x0 if (self.x0 is not...
def get_games_from_file(filename): pgn = open(filename, errors='ignore') offsets = [] while True: offset = pgn.tell() headers = chess.pgn.read_headers(pgn) if (headers is None): break offsets.append(offset) n = len(offsets) print(f'found {n} games') ga...
class ThreeCarsHighSpeedCollision(Scenario): def init_scene(self, prefix, settings=None, spectator_tr=None): super().init_scene(prefix, settings, spectator_tr) blueprint_library = self.world.get_blueprint_library() vehicle00_tr = carla.Transform(carla.Location(110, (- 255), 0.05), carla.Rota...
def main(): parser = ArgumentParser() parser.add_argument('pcd', help='Point cloud file') parser.add_argument('config', help='Config file') parser.add_argument('checkpoint', help='Checkpoint file') parser.add_argument('--device', default='cuda:0', help='Device used for inference') parser.add_arg...
class RNNLearnerState(NamedTuple): params: Params opt_states: OptStates key: chex.PRNGKey env_state: LogEnvState timestep: TimeStep dones: Done hstates: HiddenStates
def _ent_in_context_at_k(guess_item, gold_item, k): titles = eval_downstream.get_gold_titles(gold_item) if ('provenance' in guess_item['output'][0]): provenance = guess_item['output'][0]['provenance'] for i in range(0, min(k, len(provenance))): if ('text' in provenance[i]): ...
class AVATAR_PT_MotionPanel(bpy.types.Panel): bl_idname = 'AVATAR_PT_MotionPanel' bl_label = 'Motion' bl_space_type = 'VIEW_3D' bl_region_type = 'UI' bl_category = 'Avatar' bpy.types.Object.bvh_offset = IntProperty(name='Offset', description='Start motion offset', default=0, min=0, max=250) ...
class StatefulContainer(object): def __init__(self): self._state = dict() self._factories = dict() def add_factory(self, name, factory: Callable[([], Any)]): self._factories[name] = factory def merge_state_dict(self, state_dict: Dict[(str, Any)]): self._state.update(state_dic...
class MultiLoop(object): no_resolve_ = (str, set) class _multi_loop_container(object): def __init__(self, item, level=0): self.item = item self.level = level def multi_loop(self, method, *args, **kwargs): kwargs = kwargs.copy() descend = kwargs.pop('loop_desce...
class LSTMState(object): def __init__(self, states): self.states = states def from_pytorch(cls, states): (hs, cs) = states (_, bs, d) = hs.shape hs = hs.view((- 1), 2, bs, d) cs = cs.view((- 1), 2, bs, d) nl = hs.shape[0] states = [(h.sum(dim=0), c.sum(dim...
class GatherOperation(Function): def forward(ctx, features: torch.Tensor, idx: torch.Tensor) -> torch.Tensor: assert features.is_contiguous() assert idx.is_contiguous() (B, npoint) = idx.size() (_, C, N) = features.size() output = torch.cuda.FloatTensor(B, C, npoint) ...
class SegformerDropPath(nn.Module): def __init__(self, drop_prob: Optional[float]=None) -> None: super().__init__() self.drop_prob = drop_prob def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: return drop_path(hidden_states, self.drop_prob, self.training) def extra_repr...
def _do_apply_self_mask(m): if (not g_options.use_self_mask): return m self_mask = _get_self_mask(m) return ((m * (1 - self_mask)) + ((- 10) * self_mask))
def test_summarize_weighted(model, X, w): d1 = model.distributions[0] d2 = model.distributions[1] model.summarize(X, sample_weight=w) assert_array_almost_equal(model._xw_sum, [0., 4.173105, 4.912965, 4.113657], 4) assert_array_almost_equal(model._xw_starts_sum, [0.136405, 3.163595], 4) assert_ar...
def data_preparation(args): dataset_path = path.join('data', (('data_3d_' + args.dataset) + '.npz')) if (args.dataset == 'h36m'): from common.h36m_dataset import Human36mDataset, TEST_SUBJECTS dataset = Human36mDataset(dataset_path) if args.s1only: subjects_train = ['S1'] ...
class PointNet2FPModule(nn.Module): def __init__(self, *, mlp: List[int], bn: bool=True, use_paconv=False, args=None): super().__init__() self.use_paconv = use_paconv if self.use_paconv: self.mlp = paconv.SharedPAConv(mlp, bn=bn, config=args) else: self.mlp = ...
class Exp(MyExp): def __init__(self): super(Exp, self).__init__() self.num_classes = 1 self.depth = 0.33 self.width = 0.5 self.exp_name = os.path.split(os.path.realpath(__file__))[1].split('.')[0] self.train_ann = 'train.json' self.val_ann = 'train.json' ...
def load_file_list(path=None, regx='\\.npz', printable=True): if (path == False): path = os.getcwd() file_list = os.listdir(path) return_list = [] for (idx, f) in enumerate(file_list): if re.search(regx, f): return_list.append(f) if printable: print(('Match file l...
class ElementWiseUnaryOp(UnaryOpBase): def __init__(self): super().__init__() self.inp_ranks = [rank_all()] self.out_ranks = [rank_all()] def type_transfer(self, input_shapes: List[AbsTensor]) -> List[AbsTensor]: SanityCheck.eq(len(input_shapes), 1) return [input_shapes[0...
class CoarseAlign(): def __init__(self, nbScale, nbIter, tolerance, transform, minSize, segId, segFg, scaleR=2, imageNet=True, segNet=True): self.nbIter = nbIter self.tolerance = tolerance resnet_feature_layers = ['conv1', 'bn1', 'relu', 'maxpool', 'layer1', 'layer2', 'layer3'] if im...
def visual_image_MT(vis, mask_train, pred_train1, mask_val, pred_val1, pred_val2): vis.heatmap(mask_train, win='train_mask', opts=dict(title='Train Mask', colormap='Viridis')) vis.heatmap(pred_train1, win='train_pred1', opts=dict(title='Train Pred', colormap='Viridis')) vis.heatmap(mask_val, win='val_mask',...
def evaluate(y_true, y_pred_proba, debug=False): max_threshold = (- 1) max_f1 = 0 max_recall = 0 max_precision = 0 mac_acc = 0 for THRESHOLD in range(50, 51): THRESHOLD = (THRESHOLD / 100) y_pred_thr = [(1 if (x >= THRESHOLD) else 0) for x in y_pred_proba] f1 = f1_score(y...
class ResUnetSkipConnectionBlock(nn.Module): def __init__(self, outer_nc, inner_nc, input_nc=None, submodule=None, outermost=False, innermost=False, norm_layer=nn.BatchNorm2d, use_dropout=False): super(ResUnetSkipConnectionBlock, self).__init__() self.outermost = outermost use_bias = (norm_l...
def match_api(A: str, B: str, num=50, equal_type=1, fuzz=True, neq_dir='output/neq', fail_dir='output/fail', success_dir='output/success', err_dir='output/err', bug_dir='output/bug'): def verify_wrapper(api_A, api_B, indices, neq_dir, fail_dir, success_dir, err_dir, bug_dir, index=None, value=None): for _ i...
def _extract_archive(file_path, path='.', archive_format='auto'): if (archive_format is None): return False if (archive_format == 'auto'): archive_format = ['tar', 'zip'] if isinstance(archive_format, six.string_types): archive_format = [archive_format] for archive_type in archiv...
class Blip2Model(nn.Module): def __init__(self, args: Namespace): super(Blip2Model, self).__init__() self.args = args (self.model, self.vis_processors, _) = load_model_and_preprocess(name='blip2_t5', model_type='pretrain_flant5xxl', is_eval=True, device=args.device) def forward(self, q: ...
class ContinuousMLPPolicy(Policy): def __init__(self, env_spec, name='ContinuousMLPPolicy', hidden_sizes=(64, 64), hidden_nonlinearity=tf.nn.relu, hidden_w_init=tf.initializers.glorot_uniform(seed=deterministic.get_tf_seed_stream()), hidden_b_init=tf.zeros_initializer(), output_nonlinearity=tf.nn.tanh, output_w_ini...
class DatasetLossGame(StochasticCooperativeGame): def __init__(self, extension, data, labels, loss, groups=None): self.extension = extension self.loss = loss self.N = len(data) assert (len(labels) == self.N) self.exogenous = (data, labels) num_features = data.shape[1]...
def mixres50_w234a234(**kwargs): return ResNet(Bottleneck, qm.MixActivConv2d, [3, 4, 6, 3], wbits=[2, 3, 4], abits=[2, 3, 4], share_weight=True, **kwargs)
def _get_local_ip(): try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('8.8.8.8', 80)) ip = s.getsockname()[0] finally: s.close() return ip
class GradientReceiver(Receiver): def receive_notify(self, solver: 'Solver', message): if (not (Signal.TRAIN_PIPE_END in message)): return for netnode in solver.netnodes: if (not netnode.require_no_grad): model = netnode.net total_norm = 0 ...
def _test_update(inertia): x1 = torch.tensor([1.0, 1.4, 1.8, (- 1.1), 0.0]) x2 = torch.tensor([2.2, 8.2, 0.1, 105.2, 0.0]) y = ((x1 * inertia) + (x2 * (1 - inertia))) _update_parameter(x1, x2, inertia=inertia) assert_array_almost_equal(x1, y)
def train(args, train_dataset, model, tokenizer, train_highway=False): if (args.local_rank in [(- 1), 0]): tb_writer = SummaryWriter() args.train_batch_size = (args.per_gpu_train_batch_size * max(1, args.n_gpu)) train_sampler = (RandomSampler(train_dataset) if (args.local_rank == (- 1)) else Distrib...
def custom_loss(y_pred, y_true, model_name): if ('stochastic' in model_name): return KL_loss(y_pred, ((Coeff_Energy * y_true[0]) + (Coeff_Latency * y_true[1]))) return torch.sum(((y_pred - y_true) ** 2))
class Statement(SliceableMixin): _TEXT_REPR_MAX_LENGTH: int = 70 _stmts_by_ts: Dict[(Timestamp, List['Statement'])] = {} _stmts_by_id: Dict[(IdType, List['Statement'])] = {} def __init__(self, stmt_node: ast.stmt, frame: Optional[FrameType]=None, timestamp: Optional[Timestamp]=None, prev_stmt: Optional[...
def test_subscript_dependency_fp(): run_cell('lst = [0, 1, 2]') run_cell('x = 5') run_cell('y = x + lst[0]') run_cell('lst[1] = 10') run_cell('logging.info(y)') assert_not_detected('y depends only on unchanged lst[0] and not on changed lst[1]')
class ImageSize(PyClassnameExceptionRaiser): def __init__(self, *args, **kwargs): if ((len(args) == 0) and (len(kwargs) == 0)): self.x = 0 self.y = 0 self.z = 0 self.c = 0 self.t = 0 return missing_keys = get_missing_keys(kwargs...
def clip_random(image, min_shape): (img_height, img_width) = (tf.shape(image)[0], tf.shape(image)[1]) (min_height, min_width) = (min_shape[0], min_shape[1]) height = tf.cond(tf.math.greater(img_height, min_height), (lambda : tf.random.uniform([], min_height, img_height, dtype=tf.int32)), (lambda : img_heigh...
def main(): parser = prepare_parser() config = vars(parser.parse_args()) print(config) run(config)
def metrics_mean(l): metrics = {} for e in l: for metric_name in e: if (metric_name not in metrics): metrics[metric_name] = [] metrics[metric_name].append(e[metric_name]) for metric_name in metrics: metrics[metric_name] = np.mean(np.array(metrics[metri...
def get_frame(discr, gen, dc_vars, device=None, discr_src=None): if (type(dc_vars) is not edic): dc_vars = edic(dc_vars) shape_x = (dc_vars['shape_x'] if ('shape_x' in dc_vars) else (dc_vars['dim_x'],)) shape_s = (discr.shape_s if hasattr(discr, 'shape_s') else (dc_vars['dim_s'],)) shape_v = (di...
class ChatBotBasedSudokuSolver(object): def __init__(self, llm_agent) -> None: self.llm_agent = llm_agent self.parser = LLMReplyParserForSudoku() def generate_prompt(self, init_board): (role, msg_content) = ('user', self._generate_message_content(init_board)) msgs = self.llm_agen...
def main(argv): with open(FLAGS.config, 'r') as f: args = AttrDict(yaml.safe_load(f)) logdir = 'logs/exp' for (k, v) in args.items(): if (k == 'ref'): logdir += f"_{v.split('/')[(- 1)].split('.')[0]}" else: logdir += f'_{v}' demo_traj = jnp.array(np.load(a...
def test_getitem(): np.random.seed(1) torch.manual_seed(1) point_cloud_range = [(- 50), (- 50), (- 5), 50, 50, 3] file_client_args = dict(backend='disk') class_names = ['car', 'truck', 'trailer', 'bus', 'construction_vehicle', 'bicycle', 'motorcycle', 'pedestrian', 'traffic_cone', 'barrier'] pip...
def numseconds_to_numsamples(numseconds, sample_rate): candidate = int((numseconds * sample_rate)) log2 = np.log2(candidate) out_value = int((2 ** np.round(log2))) assert (out_value != 0), 'The inputs given gave an output value of 0. This is not acceptable.' return out_value
def add_interactive_args(parser): group = parser.add_argument_group('Interactive') gen_parser_from_dataclass(group, InteractiveConfig())
def PrintCategories(): sys.stderr.write(''.join(((' %s\n' % cat) for cat in _ERROR_CATEGORIES))) sys.exit(0)
class SparseBottleneck(nn.Module): def __init__(self, in_planes, growth_rate, sparsity=0.5, sparse_func='reg'): super(SparseBottleneck, self).__init__() assert (sparse_func in models.sparse_func_dict) self.bn1 = nn.BatchNorm2d(in_planes) self.conv1 = nn.Conv2d(in_planes, (4 * growth_...
class _FC_Layers(nn.Module): def __init__(self, opt): super(_FC_Layers, self).__init__() self.opt = opt self.classifier = nn.Sequential(nn.Linear(4096, 4096), nn.ReLU(True), nn.Dropout(), nn.Linear(4096, 4096), nn.ReLU(True), nn.Dropout(), nn.Linear(4096, self.opt.num_classes)) self....
class PUSlice(object): num_classes = 32 inputchannel = 1 def __init__(self, data_dir, normlizetype): self.data_dir = data_dir self.normlizetype = normlizetype def data_preprare(self, test=False): if (len(os.path.basename(self.data_dir).split('.')) == 2): with open(sel...
def glue_eval_data_collator(dataset: Dataset, batch_size: int): batch_idx = np.arange(len(dataset)) steps_per_epoch = math.ceil((len(dataset) / batch_size)) batch_idx = np.array_split(batch_idx, steps_per_epoch) for idx in batch_idx: batch = dataset[idx] batch = {k: np.array(v) for (k, v...
class TestQuantization(unittest.TestCase): def tearDownClass(self): shutil.rmtree('./saved_results', ignore_errors=True) def test_int8_huggingface_model(self): from neural_compressor.utils.load_huggingface import OptimizedModel model_name_or_path = 'Intel/distilbert-base-uncased-finetune...
def run_clpr_train(input_doc): input_doc = filter_feats(input_doc, load=True) print('Finished Feature selection') input_doc = add_embeddings(input_doc) clpr_feats = [] for (idx, l) in enumerate(input_doc._.Labels): if (l == 1): clpr_feats.append(input_doc._.Features[idx]) inp...
_flax class FlaxDDIMSchedulerTest(FlaxSchedulerCommonTest): scheduler_classes = (FlaxDDIMScheduler,) forward_default_kwargs = (('num_inference_steps', 50),) def get_scheduler_config(self, **kwargs): config = {'num_train_timesteps': 1000, 'beta_start': 0.0001, 'beta_end': 0.02, 'beta_schedule': 'line...
def combine_columns(df: pd.DataFrame, columns: List[str], separator: str=' / ') -> pd.DataFrame: def _pad_percentage(f: float) -> str: return '{:5.1f}'.format(f).replace(' ', '\\phantom{0}') out_df = df.xs(columns[0], axis=1, level=(- 1)).applymap(_pad_percentage) for col in columns[1:]: out...
class Parallelize(): def __init__(self, benchmark: Benchmark, num_workers: int=4): self.benchmark = benchmark self.num_workers = num_workers def run_single_job(self, pipeline_class: type, config: blocks.PipelineConfig, filepath: Path, description: Text) -> Annotation: idx_process = (int(...
def get_images(directory, img_ext): assert os.path.isdir(directory) image_paths = glob.glob((directory + f'/**/*{img_ext}'), recursive=True) for path in image_paths: if (path.split(os.sep)[(- 2)] not in ['damaged_jpeg', 'jpeg_write']): (yield path)