code stringlengths 101 5.91M |
|---|
def predict_cases(model, list_of_lists, output_filenames, folds, save_npz, num_threads_preprocessing, num_threads_nifti_save, segs_from_prev_stage=None, do_tta=True, overwrite_existing=False):
assert (len(list_of_lists) == len(output_filenames))
if (segs_from_prev_stage is not None):
assert (len(segs_fr... |
def remove(text, n_max_gram=3):
tokens = text.split()
n_gram = random.randint(1, n_max_gram)
remove_token_idx = random.randint(0, (len(tokens) - n_gram))
tokens = (tokens[:remove_token_idx] + tokens[(remove_token_idx + n_gram):])
new_text = ' '.join(tokens)
return new_text |
class StructureConsensuLossFunction(nn.Module):
def __init__(self, consensus_loss_alpha=10.0, consensus_loss_beta=5.0, reduce_pixel='idx', reduce_pixel_kl='idx'):
super(StructureConsensuLossFunction, self).__init__()
self.consensus_loss_alpha = consensus_loss_alpha
self.consensus_loss_beta =... |
def random_pair_range(a, b, min_dist=1, index1=None):
r1 = (random.randint(a, b) if (index1 is None) else index1)
d_left = min((r1 - a), min_dist)
d_right = min((b - r1), min_dist)
r2 = random.randint(a, (((b - 1) - d_left) - d_right))
r2 = ((((r2 + d_left) + 1) + d_right) if (r2 >= (r1 - d_left)) e... |
def load_params(path, params):
pp = numpy.load(path)
for (kk, vv) in params.iteritems():
if (kk not in pp):
warnings.warn(('%s is not in the archive' % kk))
continue
params[kk] = pp[kk]
return params |
def inception_v4_base(inputs, final_endpoint='Mixed_7d', scope=None):
end_points = {}
def add_and_check_final(name, net):
end_points[name] = net
return (name == final_endpoint)
with tf.variable_scope(scope, 'InceptionV4', [inputs]):
with slim.arg_scope([slim.conv2d, slim.max_pool2d, ... |
class ClusterNet5g(ResNet):
def __init__(self, num_channel: int=3, output_k: int=10, num_sub_heads: int=5, batchnorm_track: bool=True):
super(ClusterNet5g, self).__init__()
self.batchnorm_track = batchnorm_track
self.trunk = ClusterNet5gTrunk(num_channel=num_channel, batchnorm_track=self.bat... |
def convert(msh_file, h5_file):
(root, _) = os.path.splitext(msh_file)
assert (os.path.splitext(msh_file)[1] == '.msh')
assert (os.path.splitext(h5_file)[1] == '.h5')
xml_file = '.'.join([root, 'xml'])
subprocess.call([('dolfin-convert %s %s' % (msh_file, xml_file))], shell=True)
assert os.path.... |
def imagenet_resnet34_pretrained(output_dim):
return _replace_fc(torchvision.models.resnet34(pretrained=True), output_dim) |
class QTranBase(nn.Module):
def __init__(self, args):
super(QTranBase, self).__init__()
self.args = args
self.n_agents = args.n_agents
self.n_actions = args.n_actions
self.state_dim = int(np.prod(args.state_shape))
self.arch = self.args.qtran_arch
self.embed_d... |
def assert_is_mag(arg1: str):
if ((not isinstance(arg1, str)) or (not is_mag(arg1))):
raise ValueError(f'Invalid magnification {arg1}. Must be of format [int/float]x, such as "10x", "20X", or "2.5x"') |
def cleanup(processes):
for (process, stdout, stderr) in processes:
if (stdout is not None):
stdout.close()
if (stderr is not None):
stderr.close()
if (process.poll() is None):
process.terminate() |
def convert_episode_to_batch_major(episode):
episode_batch = {}
for key in episode.keys():
val = np.array(episode[key]).copy()
episode_batch[key] = val.swapaxes(0, 1)
return episode_batch |
def load_google_mobility(data_dir='.'):
cur_dir = os.getcwd()
os.chdir(data_dir)
os.system('wget -O google_mobility.csv')
raw = pd.read_csv('google_mobility.csv')
os.chdir(cur_dir)
return raw |
class XLMTokenizer(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, merges_fi... |
class DAVISLoader(MyDataset):
def __init__(self, args, transform=None, target_transform=None, augment=False, split='train', resize=False, inputRes=None, video_mode=True, use_prev_mask=False):
self._year = args.year
self._phase = split
self._single_object = args.single_object
self._le... |
def distribute_config_updates(prefixes, scaffolding, config_updates):
for (path, value) in iterate_flattened(config_updates):
(scaffold_name, suffix) = find_best_match(path, prefixes)
scaff = scaffolding[scaffold_name]
set_by_dotted_path(scaff.config_updates, suffix, value) |
def spawn_shelf(shelf_coordinates: chex.Array, requested: chex.Array) -> chex.Array:
(x, y) = shelf_coordinates
shelf_pos = Position(x=x, y=y)
shelf = Shelf(position=shelf_pos, is_requested=requested)
return shelf |
class HDF5Writer(BaseWriter):
def __init__(self, wspecifier, write_num_frames=None, compress=False):
spec_dict = parse_wspecifier(wspecifier)
self.filename = spec_dict['ark']
if compress:
self.kwargs = {'compression': 'gzip'}
else:
self.kwargs = {}
sel... |
def print_evaluate_index(model, eval_dataLoader, num_indexes=7):
name_index = ['ACC', 'Sens', 'Spec', 'PPV', 'NPV', 'F1', 'MCC']
ret_index = evaluate(model, eval_dataLoader, num_indexes=7)
for i in range(num_indexes):
print(f'{name_index[i]}:{round((ret_index[i] * 100), 2)}', end=' ')
print('\n'... |
def _create_annotations(gt, camera_id, frame_shape):
annotations = SequenceAnnotations()
delta = (- 8)
for (start_frame, end_frame, x, y) in gt['BallPos']:
for i in range(start_frame, (end_frame + 1)):
if ((camera_id == 2) or (camera_id == 6)):
x = (frame_shape[1] - x)
... |
class ClusterBasedBucketer(object):
def __init__(self, encoder, clustering):
self.encoder = encoder
self.clustering = clustering
def fit(self, X, y=None):
dt_encoded = self.encoder.fit_transform(X)
self.clustering.fit(dt_encoded)
return self
def predict(self, X, y=Non... |
def _cast_to_type_if_compatible(name, param_type, value):
fail_msg = ("Could not cast hparam '%s' of type '%s' from value %r" % (name, param_type, value))
if issubclass(param_type, type(None)):
return value
if (issubclass(param_type, (six.string_types, six.binary_type)) and (not isinstance(value, (s... |
class Prop_Inflected_Verbs(object):
def __init__(self, sentence_objs):
self.sentence_objs = sentence_objs
def handle(self):
(tot_num_inflected_verbs, tot_num_verbs) = (0, 0)
for so in self.sentence_objs:
tot_num_verbs += so.pos_tag_counter.get_pos_tag_count(VERB)
... |
class GQADataset(VQADataset, __DisplMixin):
def __init__(self, vis_processor, text_processor, vis_root, ann_paths):
super().__init__(vis_processor, text_processor, vis_root, ann_paths)
def __getitem__(self, index):
ann = self.annotation[index]
image_path = os.path.join(self.vis_root, ann... |
class GLPNImageProcessingTester(unittest.TestCase):
def __init__(self, parent, batch_size=7, num_channels=3, image_size=18, min_resolution=30, max_resolution=400, do_resize=True, size_divisor=32, do_rescale=True):
self.parent = parent
self.batch_size = batch_size
self.num_channels = num_chan... |
def run_net(args, config, train_writer=None, val_writer=None):
logger = get_logger(args.log_name)
((train_sampler, train_dataloader), (_, test_dataloader)) = (builder.dataset_builder(args, config.dataset.train), builder.dataset_builder(args, config.dataset.val))
(_, extra_train_dataloader) = (builder.datase... |
class MemoryDataParameter(_message.Message):
__metaclass__ = _reflection.GeneratedProtocolMessageType
DESCRIPTOR = _MEMORYDATAPARAMETER |
class QActionEx(QAction):
def __init__(self, icon, text, shortcut=None, trigger_func=None, shortcut_in_tooltip=False, is_checkable=False, is_auto_repeat=False):
super().__init__(icon, text)
if (shortcut is not None):
self.setShortcut(shortcut)
if shortcut_in_tooltip:
... |
_MASK_HEAD_REGISTRY.register()
class MaskRCNNConvUpsamplePointSupHead(MaskRCNNConvUpsampleHead):
def forward(self, x, instances: List[Instances]) -> Any:
x = self.layers(x)
if self.training:
(N, C, H, W) = x.shape
assert (H == W)
proposal_boxes = [x.proposal_boxes... |
def decode_with_crf(crf, word_reps, mask_v, l_map):
seq_len = word_reps.size(0)
bat_size = word_reps.size(1)
decoded_crf = crf.decode(word_reps, mask_v)
scores = crf.cal_score(word_reps).data
mask_v = mask_v.data
decoded_crf = decoded_crf.data
decoded_crf_withpad = torch.cat((torch.cuda.Long... |
def prepare_data_taskmaster(args):
ds_name = 'TaskMaster'
example_type = args['example_type']
max_line = args['max_line']
fr_trn_id = open(os.path.join(args['data_path'], 'Taskmaster/TM-1-2019/train-dev-test/train.csv'), 'r')
fr_dev_id = open(os.path.join(args['data_path'], 'Taskmaster/TM-1-2019/tra... |
class GTestEnvVarTest(gtest_test_utils.TestCase):
def testEnvVarAffectsFlag(self):
TestFlag('break_on_failure', '1', '0')
TestFlag('color', 'yes', 'auto')
TestFlag('filter', 'FooTest.Bar', '*')
SetEnvVar('XML_OUTPUT_FILE', None)
TestFlag('output', 'xml:tmp/foo.xml', '')
... |
class DataItem():
def __init__(self, x, y, block, code_id):
self.x = x
self.y = y
self.block = block
self.code_id = code_id |
def _compute_fans_stacked(shape):
if (len(shape) < 1):
fan_in = fan_out = 1
elif (len(shape) == 1):
fan_in = fan_out = shape[0]
elif (len(shape) == 2):
fan_in = shape[1]
fan_out = 1
else:
fan_in = shape[(- 2)]
fan_out = shape[(- 1)]
return (fan_in, fan... |
class ResNet(SimpleNet):
def __init__(self, block, num_blocks, num_classes=10, name=None, created_time=None):
super(ResNet, self).__init__()
self.in_planes = 32
self.conv1 = nn.Conv2d(3, 32, kernel_size=3, stride=1, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(32)
self.la... |
def require_torch_gpu(test_case):
if (not torch.cuda.is_available()):
return unittest.skip('test requires GPU')(test_case)
else:
return test_case |
def get_deepnorm_coefficients(encoder_layers: int, decoder_layers: int) -> Tuple[(Optional[DeepNormCoefficients], Optional[DeepNormCoefficients])]:
N = encoder_layers
M = decoder_layers
if (decoder_layers == 0):
return (DeepNormCoefficients(alpha=((2 * N) ** 0.25), beta=((8 * N) ** (- 0.25))), None)... |
class MBartTokenizerFast(XLMRobertaTokenizerFast):
vocab_files_names = {'vocab_file': 'sentencepiece.bpe.model'}
max_model_input_sizes = {m: 1024 for m in _all_mbart_models}
pretrained_vocab_files_map = {'vocab_file': {m: SPM_URL for m in _all_mbart_models}}
slow_tokenizer_class = MBartTokenizer
pre... |
def _isotropy_on_leaf(r_ei_leaf: Array, norbitals: int, kernel_initializer: WeightInitializer) -> Array:
x_nion = jnp.swapaxes(r_ei_leaf, axis1=(- 1), axis2=(- 2))
x_nion = jnp.expand_dims(x_nion, axis=(- 1))
x_nion = jnp.broadcast_to(x_nion, (*x_nion.shape[:(- 1)], norbitals))
iso_out = ElementWiseMult... |
class _AsyncEventLoop():
class _Task():
_g_next_id = 0
def __init__(self, func, *args, **kwargs):
self.task_id = self._g_next_id
self.func = (func, args, kwargs)
_AsyncEventLoop._Task._g_next_id += 1
def __init__(self):
o3d.utility.reset_print_function... |
(nopython=True)
def diagonal_update(spins, op_string, bonds, beta):
n_bonds = bonds.shape[0]
M = op_string.shape[0]
n = np.sum((op_string != (- 1)))
prob_ratio = ((0.5 * beta) * n_bonds)
for p in range(M):
op = op_string[p]
if (op == (- 1)):
b = np.random.randint(0, n_bon... |
def bind_optional(x: (T | None), f: Callable[([T], U)]) -> (U | None):
return (None if (x is None) else f(x)) |
def get_args_parser():
parser = argparse.ArgumentParser('Training Vision Transformers for Image Retrieval', add_help=False)
parser.add_argument('--model', default='deit_small_distilled_patch16_224', type=str, help='Name of model to train')
parser.add_argument('--input-size', default=224, type=int, help='ima... |
class TFXLMRobertaForMultipleChoice(metaclass=DummyObject):
_backends = ['tf']
def __init__(self, *args, **kwargs):
requires_backends(self, ['tf']) |
def compute_density(user_product_graph, product_user_graph, c, t):
density = {}
aux_user_graph = copy.deepcopy(user_product_graph)
aux_prod_graph = copy.deepcopy(product_user_graph)
for u in c:
aux_user_graph[u].append((t, 1, (- 1), '2012-06-01'))
aux_prod_graph[t].append((u, 1, (- 1), '... |
class NN_MBE_Linear():
def __init__(self, tfm_=None):
self.mbe_order = PARAMS['MBE_ORDER']
self.nn_mbe = tfm_
self.max_num_frags = None
self.nnz_frags = None
return
def EnergyForceDipole(self, N_MB):
eval_set = MSet('TmpMBESet')
MBE_C = []
MBE_Inde... |
class FDA4(FDA):
M = 3
def __init__(self, number_of_variables: int=12):
super(FDA4, self).__init__()
self.number_of_variables = number_of_variables
self.number_of_objectives = 3
self.number_of_constraints = 0
self.obj_directions = [self.MINIMIZE, self.MINIMIZE]
se... |
def main():
global args, v_id
args = parser.parse_args()
net = SiamRPNotb()
net.load_state_dict(torch.load(join(realpath(dirname(__file__)), 'SiamRPNOTB.model')))
net.eval().cuda()
dataset = load_dataset(args.dataset)
fps_list = []
for (v_id, video) in enumerate(dataset.keys()):
... |
def gen_name_from_header(header_array, header_order):
names = ['article_sections', 'ico_encoder', 'article_encoder', 'attn', 'cond_attn', 'tokenwise_attention', 'data_config', 'pretrain_attention']
final_name = ''
for n in names:
final_name += ((n + '=') + str(header_array[header_order[n]]))
... |
def quantize_nparray(qtype, arr, scale, zero_point, low=None, high=None):
dtype = (np.uint8 if (qtype == 'uint8') else np.int8)
cliplow = max((0 if (dtype == np.uint8) else (- 127)), ((- 127) if (low is None) else low))
cliphigh = min((255 if (dtype == np.uint8) else 127), (255 if (high is None) else high))... |
def get_torsion_energy(m):
mp = ChemicalForceFields.MMFFGetMoleculeProperties(m)
if (mp is None):
return 0.0
ffTerms = ('Bond', 'Angle', 'StretchBend', 'Torsion', 'Oop', 'VdW', 'Ele')
iTerm = 'Torsion'
for jTerm in ffTerms:
state = (iTerm == jTerm)
setMethod = getattr(mp, (('... |
def test_isotropic_hernquist_meanvr_directint():
pot = potential.HernquistPotential(amp=2.3, a=1.3)
dfh = isotropicHernquistdf(pot=pot)
tol = 1e-08
check_meanvr_directint(dfh, pot, tol, beta=0.0, rmin=(pot._scale / 10.0), rmax=(pot._scale * 10.0), bins=31)
return None |
class Encoder():
def __init__(self):
pass
def __mul__(self, x: Any):
raise NotImplementedError
def __rmul__(self, x: Any):
raise NotImplementedError |
def test_center_to_corner_box2d():
from mmdet3d.core.bbox.box_np_ops import center_to_corner_box2d
center = np.array([[9.348705, (- 3.6271024)]])
dims = np.array([[0.47, 0.98]])
angles = np.array([(- 3.14)])
corner = center_to_corner_box2d(center, dims, angles)
expected_corner = np.array([[[9.58... |
def get_process_cpu_percent():
try:
procTotalPercent = 0
result = {}
proc_info = []
for proc in psutil.process_iter(['pid', 'ppid', 'name', 'username', 'cmdline']):
proc_percent = proc.cpu_percent()
procTotalPercent += proc_percent
proc.info['cpu_p... |
_module()
class HeadMixin():
def __init__(self, loss, postprocessor):
assert isinstance(loss, dict)
assert isinstance(postprocessor, dict)
self.loss_module = build_loss(loss)
self.postprocessor = build_postprocessor(postprocessor)
def resize_boundary(self, boundaries, scale_facto... |
class vgg16bn(torch.nn.Module):
def __init__(self, pretrained=False):
super(vgg16bn, self).__init__()
model = list(torchvision.models.vgg16_bn(pretrained=pretrained).features.children())
model = (model[:33] + model[34:43])
self.model = torch.nn.Sequential(*model)
def forward(self... |
class Emomusic(Dataset):
_ext_audio = '.mp3'
def __init__(self, root: Union[(str, Path)], audio_transform: Callable=None, subset: Optional[str]='training') -> None:
super().__init__()
self.subset = subset
assert ((subset is None) or (subset in ['training', 'validation', 'testing'])), ('W... |
class TableTransformerConfig(PretrainedConfig):
model_type = 'table-transformer'
keys_to_ignore_at_inference = ['past_key_values']
attribute_map = {'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads'}
def __init__(self, use_timm_backbone=True, backbone_config=None, num_channels=3,... |
class SchemaField(namedtuple('SchemaField', ('feature_type', 'dtype', 'shape'))):
def to_dict(self) -> Dict[(str, Any)]:
return {'feature_type': self.feature_type, 'dtype': self.dtype, 'shape': self.shape}
def from_dict(cls, d: Dict[(str, Union[(FeatureType, DType, List[int])])]) -> 'SchemaField':
... |
def _bytes_feature_list(values):
return tf.train.FeatureList(feature=[_bytes_feature(v) for v in values]) |
def test_model(model_range: Union[(int, tuple)]):
network = Network()
network.eval()
network.to(device)
test_set = configs.test_env_settings
pool = mp.Pool(mp.cpu_count())
if isinstance(model_range, int):
state_dict = torch.load('./models/{}.pth'.format(model_range), map_location=device)... |
class AutoTCN(BaseAutomodel):
def __init__(self, input_feature_num, output_target_num, past_seq_len, future_seq_len, optimizer, loss, metric, metric_mode=None, hidden_units=None, levels=None, num_channels=None, kernel_size=7, lr=0.001, dropout=0.2, backend='torch', logs_dir='/tmp/auto_tcn', cpus_per_trial=1, name='... |
def dobldobl_usolve(pol, mxi, eps):
from phcpy.phcpy2c3 import py2c_usolve_dobldobl
from phcpy.interface import store_dobldobl_system, load_dobldobl_solutions
store_dobldobl_system([pol])
nit = py2c_usolve_dobldobl(mxi, eps)
rts = load_dobldobl_solutions()
return (nit, rts) |
class Government(BaseEntity):
name = 'government'
def __init__(self, entity_args):
super().__init__()
self.entity_args = entity_args
self.reset()
self.action_dim = entity_args['action_shape']
self.action_space = Box(low=(- 1), high=1, shape=(self.action_dim,), dtype=np.fl... |
def create_aspect_ratio_groups(dataset, k=0):
aspect_ratios = compute_aspect_ratios(dataset)
bins = ((2 ** np.linspace((- 1), 1, ((2 * k) + 1))).tolist() if (k > 0) else [1.0])
groups = _quantize(aspect_ratios, bins)
counts = np.unique(groups, return_counts=True)[1]
fbins = (([0] + bins) + [np.inf])... |
class ImpalaBlock(nn.Module):
def __init__(self, in_channels, out_channels):
super(ImpalaBlock, self).__init__()
self.conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=3, stride=1, padding=1)
self.res1 = ResidualBlock(out_channels)
self.res2 = ResidualB... |
def to_pytorch_func(tvm_func):
import torch
import torch.utils.dlpack
return convert_func(tvm_func, torch.Tensor, torch.utils.dlpack.to_dlpack) |
def create_explanation(topics):
topics = ['**{}**'.format(topic) for topic in topics]
last = topics.pop()
topic_str = ', '.join(topics)
topic_str += ((' and ' + last) if topic_str else last)
explanation = 'This article seems to be about {}.'.format(topic_str)
return explanation |
class DebertaForSequenceClassification(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def dump_cfg(cfg, logdir):
out_f = os.path.join(logdir, 'config.yaml')
with open(out_f, 'w') as f:
f.write(OmegaConf.to_yaml(cfg))
print('Wrote config to: {}'.format(out_f)) |
def setup_logging(output_dir=None):
_FORMAT = '[%(levelname)s: %(filename)s: %(lineno)4d]: %(message)s'
if du.is_master_proc():
logging.root.handlers = []
else:
_suppress_print()
return EmptyLogger('ignore')
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
logg... |
def add_args(parser: ArgumentParser):
parser.add_argument('--dynamic-linear', action='store_true')
parser.add_argument('--dynamic-ntk', type=float)
parser.add_argument('--dynamic-part-ntk', action='store_true')
parser.add_argument('--dynamic-yarn', action='store_true')
parser.add_argument('--ntk', t... |
def convert_pytorch_state_dict_to_flax(pt_state_dict, flax_model, init_key=42):
pt_state_dict = {k: v.numpy() for (k, v) in pt_state_dict.items()}
random_flax_params = flax_model.init_weights(PRNGKey(init_key))
random_flax_state_dict = flatten_dict(random_flax_params)
flax_state_dict = {}
for (pt_ke... |
def dense_model():
num_imgs = 10
nncg = NNCG()
dense_model = Sequential()
dense_model.add(Convolution2D(8, (3, 3), input_shape=(70, 50, 1), activation='relu', padding='same'))
dense_model.add(MaxPooling2D(pool_size=(2, 2)))
dense_model.add(Convolution2D(16, (3, 3), padding='valid', activation='r... |
class SyntheticSimpleVisualizer(object):
def __init__(self, dataset_loader: str, dataset_path: str, postures_generator: Optional[Generator]=None, video_name: str=None, **kwargs):
resize_options = ResizeOptions(**kwargs)
dataset = load_dataset(dataset_loader, dataset_path, resize_options=resize_optio... |
def softmax_smooth(a, b, smooth=0.0):
t = (smooth / 2.0)
return (torch.log((torch.exp((((1.0 - t) * a) + (b * t))) + torch.exp((((1.0 - t) * b) + (t * a))))) - np.log((1.0 + smooth))) |
def version_greaterorequal(l1, l2):
if (l1[0] > l2[0]):
return True
elif (l1[0] < l2[0]):
return False
elif (l1[0] == l2[0]):
if (len(l1) == 1):
return True
else:
return version_greaterorequal(l1[1:], l2[1:]) |
class SparseTransformerSentenceEncoder(TransformerSentenceEncoder):
def __init__(self, padding_idx: int, vocab_size: int, num_encoder_layers: int=6, embedding_dim: int=768, ffn_embedding_dim: int=3072, num_attention_heads: int=8, dropout: float=0.1, attention_dropout: float=0.1, activation_dropout: float=0.1, max_s... |
def efficientnet_lite4(pretrained=False, **kwargs):
model = _gen_efficientnet_lite('efficientnet_lite4', channel_multiplier=1.4, depth_multiplier=1.8, pretrained=pretrained, **kwargs)
return model |
class FlaubertForQuestionAnswering(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class Vision(BaseWDModelComponent):
('pretrained_model_setup', ['pretrained_model_name'])
def __init__(self, pretrained_model_setup: Union[(str, Dict[(str, Union[(str, WeightsEnum)])])]=None, n_trainable: Optional[int]=None, trainable_params: Optional[List[str]]=None, channel_sizes: List[int]=[64, 128, 256, 512... |
class Generator(nn.Module):
def __init__(self, G_ch=64, dim_z=128, bottom_width=4, resolution=128, G_kernel_size=3, G_attn='64', n_classes=1000, num_G_SVs=1, num_G_SV_itrs=1, G_shared=True, shared_dim=0, hier=False, cross_replica=False, mybn=False, G_activation=nn.ReLU(inplace=True), optimizer='Adam', G_lr=5e-05, G... |
def _find_bn(module):
for m in module.modules():
if isinstance(m, (nn.BatchNorm1d, nn.BatchNorm2d, SynchronizedBatchNorm1d, SynchronizedBatchNorm2d)):
return m |
class _ParallelDomainDataset(_SynchronizedDataset):
def __init__(self, dataset_metadata, scenes=None, datum_names=None, requested_annotations=None, requested_autolabels=None, forward_context=0, backward_context=0, generate_depth_from_datum=None, only_annotated_datums=False, use_virtual_camera_datums=True, accumulat... |
class TransitionBlock(nn.Module):
def __init__(self, in_channels, out_channels):
super(TransitionBlock, self).__init__()
self.conv = conv1x1_block(in_channels=in_channels, out_channels=out_channels)
self.pool = nn.AvgPool2d(kernel_size=2, stride=2, padding=0)
def forward(self, x):
... |
class AttrDict(dict):
def __init__(self, *args, **kwargs):
super(AttrDict, self).__init__(*args, **kwargs)
super(AttrDict, self).__setattr__('_mutable', False)
def __getattr__(self, key):
if key.startswith('__'):
raise AttributeError
return self.get(key, None)
def... |
def download_dataset(to_folder, dl_dataset, completed_urls={}):
download_files(to_folder, dl_dataset.train_urls, completed_urls)
download_files(to_folder, dl_dataset.valid_urls, completed_urls)
download_files(to_folder, dl_dataset.test_urls, completed_urls)
print('completed downloading')
return comp... |
def read_langs_dial(file_name, ontology, dialog_act, max_line=None, domain_act_flag=False):
print('Reading from {} for read_langs_dial'.format(file_name))
raise NotImplementedError |
class Claude(AgentClient):
def __init__(self, api_args=None, *args, **config):
super().__init__(*args, **config)
if (not api_args):
api_args = {}
api_args = deepcopy(api_args)
self.key = (api_args.pop('key', None) or os.getenv('Claude_API_KEY'))
api_args['model'] ... |
def get():
cls = (InProcessCommunicator if __use_threads else DistributedCommunicator)
if (not cls.is_initialized()):
raise RuntimeError('Crypten not initialized. Please call crypten.init() first.')
return cls.get() |
def main(args):
data_path = Path(args.data_path)
output_path = Path(args.out_path)
os.makedirs(str(output_path), exist_ok=True)
(next_img_id, next_id) = (0, 0)
for dataset_name in ['refcoco/refs(unc).p', 'refcoco+/refs(unc).p', 'refcocog/refs(umd).p']:
for split in ['train', 'val']:
... |
class _TFTrainModelInputTensorsFormer(ModelInputTensorsFormer):
def to_model_input_form(self, input_tensors: ReaderInputTensors):
return (input_tensors.target_index, input_tensors.path_source_token_indices, input_tensors.path_indices, input_tensors.path_target_token_indices, input_tensors.context_valid_mask... |
class ModuleProxyWrapper(nn.Module):
def __init__(self, module: nn.Module):
super().__init__()
assert hasattr(module, 'module'), 'ModuleProxyWrapper expects input to wrap another module'
self.module = module
def __getattr__(self, name):
try:
return super().__getattr__... |
def grid_search(model_class, init_args, param_grid, x_unvec, y, num_class, k=3, max_num_sample=10000):
param_list = _param_combinations(param_grid)
(best_param_set, best_loss, worst_loss) = _search(model_class, init_args, param_list, x_unvec, y, num_class=num_class, k=k, max_num_sample=max_num_sample)
print... |
_model('fconv_self_att')
class FConvModelSelfAtt(FairseqEncoderDecoderModel):
def __init__(self, encoder, decoder, pretrained_encoder=None):
super().__init__(encoder, decoder)
self.encoder.num_attention_layers = sum(((layer is not None) for layer in decoder.attention))
self.pretrained_encode... |
def makeVocabulary(filename, size, is_target, char=False):
if is_target:
vocab = dict.Dict([], lower=opt.lower)
else:
vocab = dict.Dict([dict.PAD_WORD, dict.UNK_WORD, dict.BOS_WORD, dict.EOS_WORD], lower=opt.lower)
if char:
vocab.addSpecial(dict.SPA_WORD)
lengths = []
if (typ... |
def get_host_info():
host = ''
try:
host = f'{getuser()}{gethostname()}'
except Exception as e:
warnings.warn(f'Host or user not found: {str(e)}')
finally:
return host |
class ZDT2TestCases(unittest.TestCase):
def test_should_constructor_create_a_non_null_object(self) -> None:
problem = ZDT2()
self.assertIsNotNone(problem)
def test_should_constructor_create_a_valid_problem_with_default_settings(self) -> None:
problem = ZDT2()
self.assertEqual(30,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.