code stringlengths 101 5.91M |
|---|
class CustomRBC(HourRBC):
def __init__(self, env: CityLearnEnv, action_map: Mapping[(int, float)]=None, loader: IntProgress=None):
super().__init__(env=env, action_map=action_map)
self.loader = loader
def next_time_step(self):
super().next_time_step()
if (self.loader is not None)... |
def set_random_seed(seed, deterministic=False):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
if deterministic:
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False |
class HighResolutionNet(nn.Module):
def __init__(self):
super(HighResolutionNet, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=2, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(64, momentum=BN_MOMENTUM)
self.conv2 = nn.Conv2d(64, 64, kernel_size=3, stride=2, ... |
class SampleNormalizeCLIMixin(NormalizeCLIMixin, intnormcli.CLIMixin):
def fit(self, images: ImageSeq, /, masks: MaskSeqOrNone=None, *, modality: intnormt.Modality=intnormt.Modality.T1, **kwargs: typing.Any) -> None:
return None
def process_directories(self, image_dir: intnormt.PathLike, /, mask_dir: (i... |
class WarmupLinearSchedule(_LRSchedule):
warn_t_total = True
def get_lr_(self, progress):
if (progress < self.warmup):
return (progress / self.warmup)
return max(((progress - 1.0) / (self.warmup - 1.0)), 0.0) |
class DB2(nn.Module):
def __init__(self, inplanes, outplanes):
super(DB2, self).__init__()
self.short_cut = nn.Conv2d(outplanes, outplanes, kernel_size=1, stride=1, padding=0)
self.conv = nn.Sequential(nn.Conv2d((inplanes + outplanes), outplanes, kernel_size=3, stride=1, padding=1), nn.Batch... |
def build_estimator(logits, probs, labels, mode):
if (mode == tf.estimator.ModeKeys.PREDICT):
predictions = {'probs': probs, 'logits': logits}
export_outputs = {'prediction': tf.estimator.export.PredictOutput(predictions)}
return tf.estimator.EstimatorSpec(mode, predictions=predictions, expo... |
def check_submodules():
from transformers.utils import direct_transformers_import
transformers = direct_transformers_import(PATH_TO_TRANSFORMERS)
module_not_registered = [module for module in get_transformers_submodules() if ((module not in IGNORE_SUBMODULES) and (module not in transformers._import_structur... |
def TrainForceField():
if 0:
a = MSet('chemspider9_force_cleaned')
a.Load()
TreatedAtoms = a.AtomTypes()
PARAMS['hidden1'] = 1000
PARAMS['hidden2'] = 1000
PARAMS['hidden3'] = 1000
PARAMS['learning_rate'] = 0.001
PARAMS['momentum'] = 0.95
PARAMS... |
class LucernHammer(BasePolearm):
def __init__(self):
super().__init__('lucern hammer', weight=150, damage=D.Dice.from_str('d6'), material=M.Iron, hit=0) |
def cleanup_dir(dir):
if os.path.exists(dir):
logging.info(f'Deleting directory: {dir}')
shutil.rmtree(dir)
logging.info(f'Deleted contents of directory: {dir}') |
class TorchImagenetLayerExtractor(BaseFeatureExtractor):
def __init__(self, model_name, tile_px, device=None, **kwargs):
super().__init__(backend='torch')
from ..torch import ModelParams, Features
from .. import torch_utils
from torchvision import transforms
self.device = tor... |
def _test_annotation_registration():
import fakelib
fakelib_class = fakelib.OnlyPresentSoThatHandlersCanBeRegistered
fakelib_method = fakelib_class.method_for_method_stub_presence
fakelib_method_a = fakelib_class.method_a
fakelib_method_b = fakelib_class.method_b
fakelib_function = fakelib.funct... |
def getbatch():
while True:
if (len(stack) == 0):
continue
return stack.pop(0) |
class Cutpaste_Dataset(Dataset):
def __init__(self, files: List, config: Namespace):
self.files = files
self.center = config.center
self.cutpaste_transform = CutPaste(type=config.cutpaste_type)
self.crop_size = ((32, 32) if config.localization else (config.image_size, config.image_si... |
((torch.cuda.device_count() < 2), 'test requires 2 GPUs')
class TestBMUF(unittest.TestCase):
def bmuf_process(self, cfg, args, iterations):
results = Manager().dict()
torch.multiprocessing.spawn(fn=functools.partial(single_gpu_training, cfg, args), args=(iterations, results), nprocs=args.distributed... |
def main():
args = parse_args()
local_rank = args.local_rank
if (local_rank != (- 1)):
msg = 'is not compatible with YOLOv5 Multi-GPU DDP training'
batch_size = args.per_device_train_batch_size
assert ((batch_size % WORLD_SIZE) == 0), f'--batch-size {batch_size} must be multiple of W... |
def load_kins_json(json_file, image_root, dataset_name=None):
from pycocotools.coco import COCO
timer = Timer()
json_file = PathManager.get_local_path(json_file)
with contextlib.redirect_stdout(io.StringIO()):
kins_api = COCO(json_file)
if (timer.seconds() > 1):
logger.info('Loading ... |
class AbsTensor():
def __init__(self, shape: List[Union[(int, z3.ExprRef)]], dtype: DType):
assert isinstance(shape, (list, tuple)), f'Shape must be a list/tuple, but got {shape}'
self.shape = list(shape)
self.dtype = DType(dtype)
def downcast_rank(self):
return AbsTensor(shape=(... |
(scope='module')
def sconv2dlstm_hidden_reset_zero_instance():
return snn.SConv2dLSTM(1, 8, 3, init_hidden=True, reset_mechanism='zero') |
class MinFrontExtractor(FrontExtractorOp):
op = 'Min'
enabled = True
def extract(cls, node: Node):
ReduceMin.update_node_stat(node, {'keep_dims': node.pb.attr['keep_dims'].b})
return cls.enabled |
def GetArgs():
parser = argparse.ArgumentParser(description='Prune pronunciation candidates based on soft-counts from lattice-alignmentoutputs, and a reference lexicon. Basically, for each word we sort all pronunciationcadidates according to their soft-counts, and then select the top r * N candidates(For words in t... |
def gen_iterator(out_path, dataset, gen_p):
global gen
gen = gen_p
if (not os.path.exists(out_path)):
os.makedirs(out_path)
print(out_path)
loader = dataset.get_loader(shuffle=True)
for (i, data) in tqdm(enumerate(loader)):
path = os.path.normpath(data['path'][0])
export_... |
def get_oracle_score(ground_truth, predicted_answers, qid_list=None, mute=False):
exact_match = common = 0
if (qid_list is None):
qid_list = ground_truth.keys()
for qid in qid_list:
if (qid not in predicted_answers):
if (not mute):
message = 'Irrelavant question {... |
class inconv(nn.Module):
def __init__(self, in_ch, out_ch):
super(inconv, self).__init__()
self.conv = double_conv(in_ch, out_ch)
def forward(self, x):
x = self.conv(x)
return x |
class AdversarialTopkErrorRate(TopkErrorRate):
def __init__(self, model, adversary=None, k=1):
super().__init__(model, k)
if (not adversary):
adversary = (lambda x, y: x)
self.adversary = adversary
def update(self, inputs, labels):
noisy = self.adversary(inputs, label... |
class DataSet(object):
def __init__(self, images, labels, fake_data=False):
if fake_data:
self._num_examples = 10000
else:
assert (images.shape[0] == labels.shape[0]), ('images.shape: %s labels.shape: %s' % (images.shape, labels.shape))
self._num_examples = images... |
def export_animated_mesh(output_path):
output_dir = os.path.dirname(output_path)
if (not os.path.isdir(output_dir)):
os.makedirs(output_dir, exist_ok=True)
bpy.ops.object.select_all(action='DESELECT')
bpy.data.objects['Armature'].select_set(True)
bpy.data.objects['Armature'].children[0].sele... |
_registry(pattern_type='MergedEmbeddingbag')
class MergedEmbeddingbag(Pattern):
def __call__(self, model):
pattern_mapping_config = {'MergedEmbeddingbag': [{'patterns': {'in': [[(0, 'Split'), (1, 'Squeeze'), (2, 'Shape'), (3, 'Gather'), (5, 'Unsqueeze'), (6, 'Concat'), (7, 'Slice'), (8, 'Shape'), (9, 'Gathe... |
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None, dilation=(1, 1), residual=True, BatchNorm=None):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride, padding=dilation[0], dilation=dilation[0])
self.bn... |
def load_network(model, network_label, epoch, iteration, args):
dataset = args.data_path.split(os.sep)[(- 1)]
save_filename = '{0}_net_{1}_{2}_{3}.pth'.format(network_label, args.model, epoch, iteration)
save_path = osp.join(args.load_dir, save_filename)
model_state = torch.load(save_path)
if ('stat... |
def get_cosine_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, num_cycles=0.5, last_epoch=(- 1)):
def lr_lambda(current_step):
if (current_step < num_warmup_steps):
return (float(current_step) / float(max(1, num_warmup_steps)))
progress = (float((current_step - num_... |
def eval_basemodel_precision_recall(pred_fn, source_fn, rel_topk, obj_topk, num_last_eval_points=4000):
pred_data = file_uri_reader_processor(pred_fn)[(- num_last_eval_points):]
source_data = file_uri_reader_processor(source_fn)['data']
group_pred_by_time = group_pred_data_in_time(pred_data, source_data)
... |
_start_docstrings('The bare SegFormer encoder (Mix-Transformer) outputting raw hidden-states without any specific head on top.', SEGFORMER_START_DOCSTRING)
class SegformerModel(SegformerPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.config = config
self.encoder =... |
class Expr(object):
def __init__(self, line=None, statement=False, original=None):
self.line = line
self.statement = statement
self.original = original
def copyargs(self):
return {'line': self.line, 'statement': self.statement, 'original': self.original}
def replace_original(... |
_REGISTRY.register()
def build_resnet_backbone(cfg, input_shape):
norm = cfg.MODEL.RESNETS.NORM
stem = BasicStem(in_channels=input_shape.channels, out_channels=cfg.MODEL.RESNETS.STEM_OUT_CHANNELS, norm=norm)
freeze_at = cfg.MODEL.BACKBONE.FREEZE_AT
out_features = cfg.MODEL.RESNETS.OUT_FEATURES
depth... |
class ResInitBlock(nn.Module):
def __init__(self, in_channels, out_channels):
super(ResInitBlock, self).__init__()
self.conv = conv7x7_block(in_channels=in_channels, out_channels=out_channels, stride=2)
self.pool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
def forward(self, x):
... |
def remove_unused_nodes_(gm: GraphModule, lint_and_recompile: bool=True):
graph = gm.graph
for node in graph.nodes:
if ((not node.users) and (node.op not in ['placeholder', 'output'])):
graph.erase_node(node)
if lint_and_recompile:
graph.lint()
gm.recompile() |
def get_mlp(features, activate):
if isinstance(activate, str):
activate = getattr(nn, activate)
layers = []
for (in_f, out_f) in zip(features[:(- 1)], features[1:]):
layers.append(nn.Linear(in_f, out_f))
layers.append(activate())
return nn.Sequential(*layers) |
def is_float(numStr):
flag = False
numStr = str(numStr).strip().lstrip('-').lstrip('+')
try:
reg = re.compile('^[-+]?[0-9]+\\.[0-9]+$')
res = reg.match(str(numStr))
if res:
flag = True
except Exception as ex:
print(('is_float() - error: ' + str(ex)))
retur... |
_vision
_torch
class VisionTextDualEncoderIntegrationTest(unittest.TestCase):
def test_inference(self):
model = VisionTextDualEncoderModel.from_pretrained('clip-italian/clip-italian', logit_scale_init_value=1)
processor = VisionTextDualEncoderProcessor.from_pretrained('clip-italian/clip-italian')
... |
class TestNMTMedium(ExampleConfigTest, EncoderDecoderTests):
def _config_path(self):
return os.path.join(EXAMPLE_CONFIG_DIR, 'nmt_medium.yml') |
def ltr_collate(batch):
error_msg = 'batch must contain tensors, numbers, dicts or lists; found {}'
elem_type = type(batch[0])
if isinstance(batch[0], torch.Tensor):
out = None
if _check_use_shared_memory():
numel = sum([x.numel() for x in batch])
storage = batch[0].s... |
class SimulationRobotAction(AbstractAction):
def __init__(self, arm_cmd=None, gripper_cmd=None, mobile_base_cmd=None, code=None, error=False):
self.arm_cmd = arm_cmd
self.gripper_cmd = gripper_cmd
self.mobile_base_cmd = mobile_base_cmd
self.error = error
self.code = code
... |
def check_type(param, param_name: str, typ, typ_name: str=None):
if (not isinstance(param, typ)):
typ_name = (str(typ) if (typ_name is None) else typ_name)
raise ValueError(f"'{param_name}' should be of type `{typ_name}`, got {type(param)}.")
return param |
class TimerCollection():
def __init__(self):
self._timers = collections.defaultdict(TimerStat)
self._enabled = True
def disable(self):
self._enabled = False
def enable(self):
self._enabled = True
def reset(self):
for timer in self._timers.values():
tim... |
def train(args, logger, dataloader, model, classifier1, classifier2, criterion1, criterion2, optimizer, epoch):
losses = AverageMeter()
losses_mse = AverageMeter()
losses_cet = AverageMeter()
losses_cet_across = AverageMeter()
losses_cet_within = AverageMeter()
model.train()
if args.mse:
... |
class Evaluator(object):
def __init__(self):
pass
def run(self, benchmark_name=None, gt_dir=None, res_dir=None, save_pkl=None, eval_mode='train', seqmaps_dir='seqmaps'):
start_time = time.time()
self.benchmark_gt_dir = gt_dir
self.seq_file = '{}-{}.txt'.format(benchmark_name, eva... |
def get_item_iterator(d):
assert isinstance(d, dict)
if (sys.version_info[0] == 2):
item_iter = d.iteritems()
assert hasattr(item_iter, 'next')
elif (sys.version_info[0] == 3):
item_iter = iter(d.items())
assert hasattr(item_iter, '__next__')
else:
raise RuntimeEr... |
def _conv_bn_relu(x, num_filters: int, bn_train: bool=True):
x = Conv2D(num_filters, kernel_size=(3, 3), padding='same', **_CONV)(x)
x = BatchNormalization()(x, training=bn_train)
x = Activation('relu')(x)
return x |
def info(msg, *args, **kwargs):
if isinstance(msg, dict):
for (_, line) in enumerate(_pretty_dict(msg).split('\n')):
Logger().get_logger().info(line, *args, **kwargs)
else:
Logger().get_logger().info(msg, *args, **kwargs) |
def plot_density(p, n_pts=1000, range_lim=0.7, figsize=(7, 7), title=None, ax=None):
if (ax is None):
(_, ax) = plt.subplots(1, 1, figsize=figsize)
xy = setup_grid(range_lim=range_lim, n_pts=n_pts)
ij = xy.transpose(0, 1)
(left, right, down, up) = (ij[(0, 0, 0)], ij[((- 1), 0, 0)], ij[(0, 0, 1)]... |
class _BaseNormalization(Layer):
def _moments(self, x, axes):
return (K.mean(x, axis=axes, keepdims=True), K.var(x, axis=axes, keepdims=True)) |
def dump(obj, file=None, file_format=None, file_client_args=None, **kwargs):
if isinstance(file, Path):
file = str(file)
if (file_format is None):
if is_str(file):
file_format = file.split('.')[(- 1)]
elif (file is None):
raise ValueError('file_format must be spec... |
def get_trainer(trainer):
if (trainer == 'ContrastiveLossTrainer'):
return ContrastiveLossTrainer
elif (trainer == 'HardestContrastiveLossTrainer'):
return HardestContrastiveLossTrainer
elif (trainer == 'TripletLossTrainer'):
return TripletLossTrainer
elif (trainer == 'HardestTri... |
def test_conv_ds():
k = (5, 5)
i = (60, 31, 16)
ch = 16
conv = stats.compute_conv2d(*i, ch, *k)
ds = stats.compute_conv2d_ds(*i, ch, *k)
ratio = (conv / ds)
assert (ratio > 9.0) |
def test_count_intersections():
cube = o3d.t.geometry.TriangleMesh.from_legacy(o3d.geometry.TriangleMesh.create_box())
scene = o3d.t.geometry.RaycastingScene()
scene.add_triangles(cube)
rays = o3d.core.Tensor([[0.5, 0.5, (- 1), 0, 0, 1], [0.5, 0.5, 0.5, 0, 0, 1], [10, 10, 10, 1, 0, 0]], dtype=o3d.core.f... |
class StableDiffusionXLPipelineOutput(BaseOutput):
images: Union[(List[PIL.Image.Image], np.ndarray)] |
def float2bitstr(f):
four_bytes = struct.pack('>f', f)
return ''.join((f'{byte:08b}' for byte in four_bytes)) |
class WarpCTC(chainer.Chain):
def __init__(self, odim, eprojs, dropout_rate):
super(WarpCTC, self).__init__()
self.dropout_rate = dropout_rate
self.loss = None
with self.init_scope():
self.ctc_lo = L.Linear(eprojs, odim)
def __call__(self, hs, ys):
self.loss =... |
def cal_model_parm_nums(model):
total = sum([param.nelement() for param in model.parameters()])
return total |
class classifier(nn.Module):
def __init__(self, in_channel=1, out_channel=10):
super(classifier, self).__init__()
self.fc5 = nn.Sequential(nn.ReLU(), nn.Linear(16, out_channel))
def forward(self, x):
label = self.fc5(x)
return label |
def get_ratio_avgk(instance, num_samples=20):
truncate_len = len(instance['original_human_response_truncate']['choices'][0]['logprobs']['token_logprobs'])
orignal_prob = instance['original_human_response']['choices'][0]['logprobs']['token_logprobs'][truncate_len:]
orignal_logprob = np.mean(orignal_prob)
... |
('AGENT_22')
class AGENT_22(BaseAgent):
type = PolicyType.CNN
features_extractor_class = EXTRACTOR_5
features_extractor_kwargs = dict(features_dim=64)
net_arch = [dict(pi=[64, 64, 64], vf=[64, 64, 64])]
activation_fn = nn.ReLU |
class ChangePointKernel(Kernel):
def __init__(self, dimension=None, location=None, steepness=None, operands=None):
assert (len(operands) == 2)
self.dimension = dimension
self.location = location
self.steepness = steepness
if (operands is None):
self.operands = []
... |
class AttributeCommand(BaseCLICommand):
_name = 'attribute'
_help = 'Perform feature attribution on one or multiple sentences'
_dataclasses = AttributeArgs
def run(args: AttributeArgs):
attribute(args.input_texts, args.generated_texts, args) |
def configure_experiment(problems: dict, n_run: int):
jobs = []
max_evaluations = 25000
for run in range(n_run):
for (problem_tag, problem) in problems.items():
jobs.append(Job(algorithm=NSGAII(problem=problem, population_size=100, offspring_population_size=100, mutation=PolynomialMutati... |
('ner_tag')
class NerTagIndexer(TokenIndexer[int]):
def __init__(self, namespace: str='ner_tags') -> None:
self._namespace = namespace
def count_vocab_items(self, token: Token, counter: Dict[(str, Dict[(str, int)])]):
tag = token.ent_type_
if (not tag):
tag = 'NONE'
c... |
def get_rank():
if _use_c10d[0]:
return dist_c10d.get_rank()
else:
return dist_no_c10d.get_rank() |
def time(solver, nccl):
fprop = []
bprop = []
total = caffe.Timer()
allrd = caffe.Timer()
for _ in range(len(solver.net.layers)):
fprop.append(caffe.Timer())
bprop.append(caffe.Timer())
display = solver.param.display
def show_time():
if ((solver.iter % display) == 0):... |
class PolyBlock5a(nn.Module):
def __init__(self):
super(PolyBlock5a, self).__init__()
self.branches = Concurrent()
self.branches.add_module('branch1', MaxPoolBranch())
self.branches.add_module('branch2', Conv3x3Branch(in_channels=192, out_channels=192))
def forward(self, x):
... |
class TFCvtConvEmbeddings(tf.keras.layers.Layer):
def __init__(self, config: CvtConfig, patch_size: int, embed_dim: int, stride: int, padding: int, **kwargs):
super().__init__(**kwargs)
self.padding = tf.keras.layers.ZeroPadding2D(padding=padding)
self.patch_size = (patch_size if isinstance(... |
def test_digits_euclidean_naive_init():
model1 = FacilityLocationSelection(100)
model2 = GraphCutSelection(100)
model = MixtureSelection(100, [model1, model2], [1.0, 0.3], metric='euclidean', optimizer='naive', initial_subset=digits_euclidean_ranking[:5])
model.fit(X_digits)
assert_array_equal(model... |
class PromptCap(nn.Module):
def __init__(self, ckpt='vqascore/promptcap-coco-vqa'):
super().__init__()
self.tokenizer = OFATokenizer.from_pretrained(ckpt)
self.model = OFAModel.from_pretrained(ckpt, use_cache=True)
self.model.eval()
(mean, std) = ([0.5, 0.5, 0.5], [0.5, 0.5, ... |
_CODERS.register_module()
class YOLOBBoxCoder(BaseBBoxCoder):
def __init__(self, eps=1e-06):
super(BaseBBoxCoder, self).__init__()
self.eps = eps
def encode(self, bboxes, gt_bboxes, stride):
assert (bboxes.size(0) == gt_bboxes.size(0))
assert (bboxes.size((- 1)) == gt_bboxes.size... |
class TheanoCurves(CurvesManifold, TheanoShapes):
def __init__(self, *args, **kwargs):
TheanoShapes.__init__(self, *args, **kwargs) |
class DenseDetector(nn.Module):
def __init__(self, backbone: Backbone, head: nn.Module, head_in_features: Optional[List[str]]=None, *, pixel_mean, pixel_std):
super().__init__()
self.backbone = backbone
self.head = head
if (head_in_features is None):
shapes = self.backbon... |
def test_score_hlr_sampler_empty_pred():
assigner = MaxIoUAssigner(pos_iou_thr=0.5, neg_iou_thr=0.5, ignore_iof_thr=0.5, ignore_wrt_candidates=False)
context = _context_for_ohem()
sampler = ScoreHLRSampler(num=10, pos_fraction=0.5, context=context, neg_pos_ub=(- 1), add_gt_as_proposals=True)
gt_bboxes_i... |
def plan_and_preprocess(task_string, processes_lowres=default_num_threads, processes_fullres=3, no_preprocessing=False):
from nnunet.experiment_planning.experiment_planner_baseline_2DUNet import ExperimentPlanner2D
from nnunet.experiment_planning.experiment_planner_baseline_3DUNet import ExperimentPlanner
p... |
class WN18RRProcessor(BaseProcessor):
def __init__(self, node_lut, relation_lut):
super().__init__(node_lut, relation_lut) |
def cluster_feat(dataset_json_file, tar_path):
with open(dataset_json_file, 'r') as fp:
data_json = json.load(fp)
data = data_json['data']
num_sample = len(data)
for (idx, entry) in enumerate(data):
wav = entry['wav']
if (idx == 0):
cur_sample ... |
def construct_dataloaders(dataset, defs, data_path='~/data', shuffle=True, normalize=True):
path = os.path.expanduser(data_path)
if (dataset == 'CIFAR10'):
(trainset, validset) = _build_cifar10(path, defs.augmentations, normalize)
loss_fn = Classification()
elif (dataset == 'CIFAR100'):
... |
def build(args, image_set, activated_class_ids, with_support=True):
assert (image_set == 'fewshot')
activated_class_ids.sort()
if (args.dataset_file in ['coco_base']):
root = Path('data/coco_fewshot')
img_folder = ((root.parent / 'coco') / 'train2017')
ann_file = ((root / f'seed{args... |
class ChineseCLIPModelTester():
def __init__(self, parent, text_kwargs=None, vision_kwargs=None, is_training=True):
if (text_kwargs is None):
text_kwargs = {}
if (vision_kwargs is None):
vision_kwargs = {}
self.parent = parent
self.text_model_tester = ChineseC... |
def build_and_train(slot_affinity_code, log_dir, run_ID, config_key):
affinity = affinity_from_code(slot_affinity_code)
config = configs[config_key]
variant = load_variant(log_dir)
config = update_config(config, variant)
sampler = SerialSampler(EnvCls=gym_make, env_kwargs=config['env'], CollectorCls... |
class ReformerForSequenceClassification(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class CityscapesInstanceEvaluator(CityscapesEvaluator):
def process(self, inputs, outputs):
from cityscapesscripts.helpers.labels import name2label
for (input, output) in zip(inputs, outputs):
file_name = input['file_name']
basename = os.path.splitext(os.path.basename(file_na... |
def eta(time_points, remaining_works, regression_points_used=200):
time_points = np.asarray(time_points)
remaining_works = np.asarray(remaining_works)
return np.mean([eta_linear_regression_shifted(time_points[(- regression_points_used):], remaining_works[(- regression_points_used):]), eta_lookback(time_poin... |
def freq_transit(q, rho=1.0, **kwargs):
fmax0 = fmax_transit0(rho=rho)
return (fmax0 * (np.sin((np.pi * q)) ** 1.5)) |
def plot_gate_outputs_to_numpy(gate_targets, gate_outputs):
(fig, ax) = plt.subplots(figsize=(12, 3))
ax.scatter(range(len(gate_targets)), gate_targets, alpha=0.5, color='green', marker='+', s=1, label='target')
ax.scatter(range(len(gate_outputs)), gate_outputs, alpha=0.5, color='red', marker='.', s=1, labe... |
class Swinv2PreTrainedModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def load_imagenet_family_model(type, folder, checkpoint, device, dataset_dir, num_classes, load_temp=False, model_params=None):
(model, model_folder_post, _) = build_model224(type, num_classes, **model_params)
state_dict_file = get_filename(folder, f'{dataset_dir}/{model_folder_post}', checkpoint, load_temp)
... |
def _segm_pvtv2(name, backbone_name, num_classes, output_stride, pretrained_backbone):
if (output_stride == 8):
aspp_dilate = [12, 24, 36]
else:
aspp_dilate = [6, 12, 18]
backbone = pvt_v2_b2()
if pretrained_backbone:
path = './pretrained_pth/pvt_v2_b2.pth'
save_model = t... |
class MapSeqsToReactants():
def __init__(self, json_reactants_to_id_path=None):
self.reactant_id_to_smi_dict = {v: k for (k, v) in mchef_config.get_reactant_smi_to_reactant_id_dict(json_reactants_to_id_path).items()}
self.stop_sym_idx = mchef_config.get_num_graphs(json_reactants_to_id_path)
... |
def reset_cfg(cfg, args):
if args.root:
cfg.DATASET.ROOT = args.root
if args.output_dir:
cfg.OUTPUT_DIR = args.output_dir
if args.resume:
cfg.RESUME = args.resume
if args.seed:
cfg.SEED = args.seed
if args.source_domains:
cfg.DATASET.SOURCE_DOMAINS = args.sour... |
def wait_for_session_and_get_session(self, master, config=None, max_wait_secs=float('Inf')):
global_dict = common_util.GlobalDict()
if ('session_creation_count' not in global_dict):
global_dict['session_creation_count'] = 0
global_dict['session_creation_count'] += 1
self._target = master
if ... |
class TestAPI(unittest.TestCase):
def test_cnn_train(self):
with io.open((DATA_DIR + '.labels'), 'r') as f:
labels = {line.rstrip('\n') for line in f}
model = Magpie()
model.init_word_vectors(DATA_DIR, vec_dim=100)
history = model.train(DATA_DIR, labels, nn_model='cnn', t... |
def fid_inception_v3():
inception = _inception_v3(num_classes=1008, aux_logits=False, pretrained=False)
inception.Mixed_5b = FIDInceptionA(192, pool_features=32)
inception.Mixed_5c = FIDInceptionA(256, pool_features=64)
inception.Mixed_5d = FIDInceptionA(288, pool_features=64)
inception.Mixed_6b = F... |
def save_data(data, out_path, darknet_label_path):
with open(out_path, 'w+') as f:
json.dump(data, f)
for group in data:
with open(os.path.join(darknet_label_path), 'w+') as f:
json.dump(data, f) |
def compose(base_map, next_map):
(ax1, a1, b1) = base_map
(ax2, a2, b2) = next_map
if (ax1 is None):
ax = ax2
elif ((ax2 is None) or (ax1 == ax2)):
ax = ax1
else:
raise AxisMismatchException
return (ax, (a1 * a2), ((a1 * b2) + b1)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.