code stringlengths 17 6.64M |
|---|
def run_experiment(argv):
default_log_dir = config.LOG_DIR
now = datetime.datetime.now(dateutil.tz.tzlocal())
rand_id = str(uuid.uuid4())[:5]
timestamp = now.strftime('%Y_%m_%d_%H_%M_%S_%f_%Z')
default_exp_name = ('experiment_%s_%s' % (timestamp, rand_id))
parser = argparse.ArgumentParser()
... |
def setup_iam():
iam_client = boto3.client('iam', aws_access_key_id=ACCESS_KEY, aws_secret_access_key=ACCESS_SECRET)
iam = boto3.resource('iam', aws_access_key_id=ACCESS_KEY, aws_secret_access_key=ACCESS_SECRET)
try:
existing_role = iam.Role('rllab')
existing_role.load()
if (not qu... |
def setup_s3():
print(('Creating S3 bucket at s3://%s' % S3_BUCKET_NAME))
s3_client = boto3.client('s3', aws_access_key_id=ACCESS_KEY, aws_secret_access_key=ACCESS_SECRET)
try:
s3_client.create_bucket(ACL='private', Bucket=S3_BUCKET_NAME, CreateBucketConfiguration={'LocationConstraint': 'us-west-1... |
def setup_ec2():
for region in ['us-west-1', 'us-west-2', 'us-east-1']:
print(('Setting up region %s' % region))
ec2 = boto3.resource('ec2', region_name=region, aws_access_key_id=ACCESS_KEY, aws_secret_access_key=ACCESS_SECRET)
ec2_client = boto3.client('ec2', region_name=region, aws_acces... |
def write_config():
print('Writing config file...')
content = CONFIG_TEMPLATE.substitute(all_region_aws_key_names=json.dumps(ALL_REGION_AWS_KEY_NAMES, indent=4), all_region_aws_security_group_ids=json.dumps(ALL_REGION_AWS_SECURITY_GROUP_IDS, indent=4), s3_bucket_name=S3_BUCKET_NAME)
config_personal_file =... |
def setup():
setup_s3()
setup_iam()
setup_ec2()
write_config()
|
def query_yes_no(question, default='yes'):
'Ask a yes/no question via raw_input() and return their answer.\n\n "question" is a string that is presented to the user.\n "default" is the presumed answer if the user just hits <Enter>.\n It must be "yes" (the default), "no" or None (meaning\n an an... |
def getcameras(self, context):
cameras = []
for object in context.scene.objects:
if (object.type == 'CAMERA'):
cameras.append(object)
return [(cam.name, cam.name, cam.name) for cam in cameras]
|
def printLogo():
log('===========================================================================')
log(' __ __ __ __ _ ')
log(' __ ___ __/ / / /___ / /___ ____ __________ _____ / /_ (_)_________')
log(' / / / / | / / /_/ / __ \\/ / _... |
def log(s):
'print a debug message'
if DEBUG:
print(s)
|
def create_image(name, k=1):
'creates defect textures'
if (name not in bpy.data.images):
bpy.ops.image.new(name=name, width=(k * 1024), height=(k * 1024), color=(0.0, 0.0, 0.0, 0.0))
else:
log('- create_image() : textures exists')
|
def create_view_layers(context):
'todo: checks naming of view layers'
context.scene.view_layers[0].name = 'real'
if ('Ground Truth' not in context.scene.view_layers):
context.scene.view_layers.new(name='ground_truth')
|
def create_mode_switcher_node_group():
if ('mode_switcher' not in bpy.data.node_groups):
test_group = bpy.data.node_groups.new('mode_switcher', 'ShaderNodeTree')
group_inputs = test_group.nodes.new('NodeGroupInput')
group_inputs.location = ((- 350), 0)
test_group.inputs.new('NodeSo... |
def add_camera_focus(context, cameraName, target):
camera = context.scene.objects[cameraName]
if ('Track To' not in camera.constraints):
tracker = camera.constraints.new(type='TRACK_TO')
tracker.target = target
tracker.track_axis = 'TRACK_NEGATIVE_Z'
tracker.up_axis = 'UP_Y'
... |
def toggle_mode(context):
'helper function for background switching'
scene = context.scene
uvh = scene.uv_holographics
if (uvh.mode == 0):
log('switching to GT')
uvh.mode = 1
scene.render.filter_size = 0
scene.view_settings.view_transform = 'Standard'
else:
... |
def render_layer(context, layer, id):
'\n Renders a specific layer, useful for compositing view.\n This function is mode agnostic.\n '
scene = context.scene
uvh = scene.uv_holographics
scene.render.filepath = f'{uvh.output_dir}{layer}/{id:04d}.png'
bpy.ops.render.render(write_still=True, ... |
def run_variation(context):
'\n manipulates objects to create variations\n todo: scenarios\n todo: read from XML file\n '
camera = context.scene.objects['Camera']
uvh = context.scene.uv_holographics
r = (uvh.camera_dist_mean + uniform((- uvh.camera_dist_var), uvh.camera_dist_var))
thet... |
def insert_mode_switcher_node(context, material):
'Inserts a mode_switcher group node in the materials that are in target_collection'
log(f'checking for {material.name}')
for l in material.node_tree.links:
if (l.to_socket.name == 'Surface'):
if (l.from_socket.name == 'Switch'):
... |
class MyProperties(PropertyGroup):
separate_background: BoolProperty(name='Separate background class', description='Extra class for background', default=True)
n_defects: IntProperty(name='Defect classes', description='Number of defect classes', default=1, min=1, max=10)
n_samples: IntProperty(name='Number... |
class WM_OT_GenerateComponents(Operator):
'Generate blank texture maps and view layers'
bl_label = 'Generate components'
bl_idname = 'wm.gen_components'
def execute(self, context):
scene = context.scene
uvh = scene.uv_holographics
log('- generating components')
for i ... |
class WM_OT_UpdateMaterials(Operator):
'Updates existing material nodes of objects in target_collection'
bl_label = 'Update Materials'
bl_idname = 'wm.update_materials'
def execute(self, context):
for o in context.scene.uv_holographics.target_collection.objects:
for m in o.data.ma... |
class WM_OT_ToggleMaterials(Operator):
'Toggle between realistic view and ground truth'
bl_label = 'Toggle Real/GT'
bl_idname = 'wm.toggle_real_gt'
def execute(self, context):
toggle_mode(context)
return {'FINISHED'}
|
class WM_OT_SampleVariation(Operator):
'Runs a sample variation'
bl_label = 'Sample variation'
bl_idname = 'wm.sample_variation'
def execute(self, context):
run_variation(context)
return {'FINISHED'}
|
class WM_OT_StartScenarios(Operator):
'Vary camera positions'
bl_label = 'Generate'
bl_idname = 'wm.start_scenarios'
def execute(self, context):
scene = context.scene
uvh = scene.uv_holographics
if (uvh.mode != 0):
toggle_mode(context)
for i in range(uvh.n_... |
class OBJECT_PT_CustomPanel(Panel):
bl_label = 'uvHolographics'
bl_idname = 'OBJECT_PT_custom_panel'
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = 'Annotation'
bl_context = 'objectmode'
@classmethod
def poll(self, context):
return (context.object is not None)
... |
def register():
from bpy.utils import register_class
global custom_icons
printLogo()
for cls in classes:
register_class(cls)
custom_icons = bpy.utils.previews.new()
script_path = bpy.context.space_data.text.filepath
icons_dir = os.path.join(os.path.dirname(script_path), 'icons')
... |
def unregister():
from bpy.utils import unregister_class
global custom_icons
for cls in reversed(classes):
unregister_class(cls)
del bpy.types.Scene.uv_holographics
bpy.utils.previews.remove(custom_icons)
|
class S2VGraph(object):
def __init__(self, g, label, node_tags=None, node_features=None):
'\n g: a networkx graph\n label: an integer graph label\n node_tags: a list of integer node tags\n node_features: a torch float tensor, one-hot representation of the tag t... |
def load_data(dataset, degree_as_tag):
'\n dataset: name of dataset\n test_proportion: ratio of test train split\n seed: random seed for random splitting of dataset\n '
print('loading data')
g_list = []
label_dict = {}
feat_dict = {}
triggered = False
with open(('da... |
def separate_data(graph_list, seed, fold_idx):
assert ((0 <= fold_idx) and (fold_idx < 10)), 'fold_idx must be from 0 to 9.'
skf = StratifiedKFold(n_splits=10, shuffle=True, random_state=seed)
labels = [graph.label for graph in graph_list]
idx_list = []
for idx in skf.split(np.zeros(len(labels)), ... |
class MLP(tf.keras.layers.Layer):
def __init__(self, num_layers, hidden_dim, output_dim):
'\n num_layers: number of layers in the neural networks (EXCLUDING the input layer). If num_layers=1, this reduces to linear model.\n hidden_dim: dimensionality of hidden units at ALL layers\n o... |
class Linear_model(tf.keras.layers.Layer):
def __init__(self, output_dim):
super(Linear_model, self).__init__()
self.output_layer = tf.keras.layers.Dense(units=output_dim)
def call(self, input_features):
return self.output_layer(input_features)
|
class Multi_model(tf.keras.layers.Layer):
def __init__(self, layers, hidden_dim, output_dim):
super(Multi_model, self).__init__()
self.layers = layers
self.dense_list = []
self.batch_list = []
for i in range((layers - 1)):
self.dense_list.append(tf.keras.layers... |
class GraphCNN(tf.keras.Model):
def __init__(self, num_layers, num_mlp_layers, hidden_dim, output_dim, final_dropout, learn_eps, graph_pooling_type, neighbor_pooling_type):
'\n num_layers: number of layers in the neural networks (INCLUDING the input layer)\n num_mlp_layers: number o... |
def train(args, model, train_graphs, opt, epoch):
total_iters = args.iters_per_epoch
pbar = tqdm(range(total_iters), unit='batch')
loss_accum = 0
for pos in pbar:
selected_idx = np.random.permutation(len(train_graphs))[:args.batch_size]
batch_graph = [train_graphs[idx] for idx in selec... |
def pass_data_iteratively(model, graphs, minibatch_size=64):
output = []
idx = np.arange(len(graphs))
for i in range(0, len(graphs), minibatch_size):
sampled_idx = idx[i:(i + minibatch_size)]
if (len(sampled_idx) == 0):
continue
output.append(model([graphs[j] for j in s... |
def tf_check_acc(pred, labels):
pred = tf.cast(pred, tf.int32)
correct = tf.equal(pred, labels)
answer = 0
for element in correct:
if element:
answer += 1
return answer
|
def test(args, model, train_graphs, test_graphs, epoch):
output = pass_data_iteratively(model, train_graphs)
pred = tf.argmax(output, 1)
labels = tf.constant([graph.label for graph in train_graphs])
correct = tf_check_acc(pred, labels)
acc_train = (correct / float(len(train_graphs)))
output = ... |
def train(args, model, train_graphs, opt, epoch):
total_iters = args.iters_per_epoch
pbar = tqdm(range(total_iters), unit='batch')
loss_accum = 0
for pos in pbar:
selected_idx = np.random.permutation(len(train_graphs))[:args.batch_size]
batch_graph = [train_graphs[idx] for idx in selec... |
def pass_data_iteratively(model, graphs, minibatch_size=64):
output = []
idx = np.arange(len(graphs))
for i in range(0, len(graphs), minibatch_size):
sampled_idx = idx[i:(i + minibatch_size)]
if (len(sampled_idx) == 0):
continue
output.append(model([graphs[j] for j in s... |
def tf_check_acc(pred, labels):
pred = tf.cast(pred, tf.int32)
correct = tf.equal(pred, labels)
answer = 0
for element in correct:
if element:
answer += 1
return answer
|
def test(args, model, train_graphs, test_graphs, epoch):
output = pass_data_iteratively(model, train_graphs)
pred = tf.argmax(output, 1)
labels = tf.constant([graph.label for graph in train_graphs])
correct = tf_check_acc(pred, labels)
acc_train = (correct / float(len(train_graphs)))
output = ... |
class GraphCNN(tf.keras.Model):
def __init__(self, num_layers, num_mlp_layers, hidden_dim, output_dim, final_dropout, learn_eps, graph_pooling_type, neighbor_pooling_type):
'\n num_layers: number of layers in the neural networks (INCLUDING the input layer)\n num_mlp_layers: number o... |
class MLP(tf.keras.layers.Layer):
def __init__(self, num_layers, hidden_dim, output_dim):
'\n num_layers: number of layers in the neural networks (EXCLUDING the input layer). If num_layers=1, this reduces to linear model.\n hidden_dim: dimensionality of hidden units at ALL layers\n o... |
class Linear_model(tf.keras.layers.Layer):
def __init__(self, output_dim):
super(Linear_model, self).__init__()
self.output_layer = tf.keras.layers.Dense(units=output_dim)
def call(self, input_features):
return self.output_layer(input_features)
|
class Multi_model(tf.keras.layers.Layer):
def __init__(self, layers, hidden_dim, output_dim):
super(Multi_model, self).__init__()
self.layers = layers
self.dense_list = []
self.batch_list = []
for i in range((layers - 1)):
self.dense_list.append(tf.keras.layers... |
class S2VGraph(object):
def __init__(self, g, label, node_tags=None, node_features=None):
'\n g: a networkx graph\n label: an integer graph label\n node_tags: a list of integer node tags\n node_features: a torch float tensor, one-hot representation of the tag t... |
def load_data(dataset, degree_as_tag):
'\n dataset: name of dataset\n test_proportion: ratio of test train split\n seed: random seed for random splitting of dataset\n '
print('loading data')
g_list = []
label_dict = {}
feat_dict = {}
triggered = False
with open(('da... |
def separate_data(graph_list, seed, fold_idx):
assert ((0 <= fold_idx) and (fold_idx < 10)), 'fold_idx must be from 0 to 9.'
skf = StratifiedKFold(n_splits=10, shuffle=True, random_state=seed)
labels = [graph.label for graph in graph_list]
idx_list = []
for idx in skf.split(np.zeros(len(labels)), ... |
def remap_module(module_type, k, v):
if (module_type == 'ConvBnAct'):
k = k.replace('bn1.', 'bn.')
elif (module_type == 'InvertedResidual'):
k = k.replace('conv_pw.', 'conv_exp.')
k = k.replace('bn1.', 'bn_exp.')
k = k.replace('bn2.', 'bn_dw.')
k = k.replace('bn3.', 'bn... |
def export_model(model_name, output_dir=''):
timm_model_name = model_name.replace('pt_', '')
m = timm.create_model(timm_model_name, pretrained=True)
d = dict(m.named_modules())
data = {}
names = []
types = []
for (k, v) in m.state_dict().items():
if ('num_batches' in k):
... |
def main():
args = parser.parse_args()
all_models = list_models(pretrained=True)
if (args.model == 'all'):
for model_name in all_models:
export_model(model_name, args.output)
else:
export_model(args.model, args.output)
|
def _parse_ksize(ss):
if ss.isdigit():
return int(ss)
else:
return [int(k) for k in ss.split('.')]
|
def _decode_block_str(block_str):
" Decode block definition string\n\n Gets a list of block arg (dicts) through a string notation of arguments.\n E.g. ir_r2_k3_s2_e1_i32_o16_se0.25_noskip\n\n All args can exist in any order with the exception of the leading string which\n is assumed to indicate the bl... |
def _scale_stage_depth(stage_defs, repeats, depth_multiplier=1.0, depth_trunc='ceil'):
' Per-stage depth scaling\n Scales the block repeats in each stage. This depth scaling impl maintains\n compatibility with the EfficientNet scaling method, while allowing sensible\n scaling for other models that may ha... |
def decode_arch_def(arch_def, depth_multiplier=1.0, depth_trunc='ceil', experts_multiplier=1, fix_first_last=False):
arch_args = []
for (stage_idx, block_strings) in enumerate(arch_def):
assert isinstance(block_strings, list)
stage_args = []
repeats = []
for block_str in block_... |
def arch_mnasnet_a1(variant, feat_multiplier=1.0, **kwargs):
'Creates a mnasnet-a1 model.\n\n Ref impl: https://github.com/tensorflow/tpu/tree/master/models/official/mnasnet\n Paper: https://arxiv.org/pdf/1807.11626.pdf.\n\n Args:\n feat_multiplier: multiplier to number of channels per layer.\n '... |
def arch_mnasnet_b1(variant, feat_multiplier=1.0, **kwargs):
'Creates a mnasnet-b1 model.\n\n Ref impl: https://github.com/tensorflow/tpu/tree/master/models/official/mnasnet\n Paper: https://arxiv.org/pdf/1807.11626.pdf.\n\n Args:\n feat_multiplier: multiplier to number of channels per layer.\n '... |
def arch_mnasnet_small(variant, feat_multiplier=1.0, **kwargs):
'Creates a mnasnet-b1 model.\n\n Ref impl: https://github.com/tensorflow/tpu/tree/master/models/official/mnasnet\n Paper: https://arxiv.org/pdf/1807.11626.pdf.\n\n Args:\n feat_multiplier: multiplier to number of channels per layer.\n ... |
def arch_mobilenet_v2(variant, feat_multiplier=1.0, depth_multiplier=1.0, fix_stem_head=False, **kwargs):
' Generate MobileNet-V2 network\n Ref impl: https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet_v2.py\n Paper: https://arxiv.org/abs/1801.04381\n '
arch_def = ... |
def arch_fbnetc(variant, feat_multiplier=1.0, **kwargs):
" FBNet-C\n\n Paper: https://arxiv.org/abs/1812.03443\n Ref Impl: https://github.com/facebookresearch/maskrcnn-benchmark/blob/master/maskrcnn_benchmark/modeling/backbone/fbnet_modeldef.py\n\n NOTE: the impl above does not relate to the ... |
def arch_spnasnet(variant, feat_multiplier=1.0, **kwargs):
'Creates the Single-Path NAS model from search targeted for Pixel1 phone.\n\n Paper: https://arxiv.org/abs/1904.02877\n\n Args:\n feat_multiplier: multiplier to number of channels per layer.\n '
arch_def = [['ds_r1_k3_s1_c16_noskip'], ['... |
def arch_efficientnet(variant, feat_multiplier=1.0, depth_multiplier=1.0, **kwargs):
"Creates an EfficientNet model.\n\n Ref impl: https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/efficientnet_model.py\n Paper: https://arxiv.org/abs/1905.11946\n\n EfficientNet params\n name: ... |
def arch_efficientnet_edge(variant, feat_multiplier=1.0, depth_multiplier=1.0, **kwargs):
' Creates an EfficientNet-EdgeTPU model\n\n Ref impl: https://github.com/tensorflow/tpu/tree/master/models/official/efficientnet/edgetpu\n '
arch_def = [['er_r1_k3_s1_e4_c24_fc24_noskip'], ['er_r2_k3_s2_e8_c32'], [... |
def arch_efficientnet_lite(variant, feat_multiplier=1.0, depth_multiplier=1.0, **kwargs):
"Creates an EfficientNet-Lite model.\n\n Ref impl: https://github.com/tensorflow/tpu/tree/master/models/official/efficientnet/lite\n Paper: https://arxiv.org/abs/1905.11946\n\n EfficientNet params\n name: (feat_m... |
def arch_mixnet_s(variant, feat_multiplier=1.0, **kwargs):
'Creates a MixNet Small model.\n\n Ref impl: https://github.com/tensorflow/tpu/tree/master/models/official/mnasnet/mixnet\n Paper: https://arxiv.org/abs/1907.09595\n '
arch_def = [['ds_r1_k3_s1_e1_c16'], ['ir_r1_k3_a1.1_p1.1_s2_e6_c24', 'ir_r... |
def arch_mixnet_m(variant, feat_multiplier=1.0, depth_multiplier=1.0, **kwargs):
'Creates a MixNet Medium-Large model.\n\n Ref impl: https://github.com/tensorflow/tpu/tree/master/models/official/mnasnet/mixnet\n Paper: https://arxiv.org/abs/1907.09595\n '
arch_def = [['ds_r1_k3_s1_e1_c24'], ['ir_r1_k... |
def arch_mobilenet_v3(variant, feat_multiplier=1.0, **kwargs):
'Creates a MobileNet-V3 model.\n\n Ref impl: ?\n Paper: https://arxiv.org/abs/1905.02244\n\n Args:\n feat_multiplier: multiplier to number of channels per layer.\n '
if ('small' in variant):
num_features = 1024
if ... |
def make_divisible(v, divisor=8, min_value=None):
min_value = (min_value or divisor)
new_v = max(min_value, ((int((v + (divisor / 2))) // divisor) * divisor))
if (new_v < (0.9 * v)):
new_v += divisor
return new_v
|
def round_features(features, multiplier=1.0, divisor=8, feat_min=None):
'Round number of filters based on depth multiplier.'
if (not multiplier):
return features
features *= multiplier
return make_divisible(features, divisor, feat_min)
|
def _log_info_if(msg, condition):
if condition:
_logger.info(msg)
|
class EfficientNetBuilder():
' Build Trunk Blocks\n\n This ended up being somewhat of a cross between\n https://github.com/tensorflow/tpu/blob/master/models/official/mnasnet/mnasnet_models.py\n and\n https://github.com/facebookresearch/maskrcnn-benchmark/blob/master/maskrcnn_benchmark/modeling/backbon... |
def get_bn_args_tf():
return _BN_ARGS_TF.copy()
|
def get_bn_args_pt():
return _BN_ARGS_PT.copy()
|
def load_state_dict(filename, include_type_map=False, transpose=False):
np_weights = np.load(filename)
var_names = np_weights['names']
var_types = []
if ('types' in np_weights):
var_types = np_weights['types']
var_values = [np_weights[str(i)] for i in range(len(var_names))]
jax_state_d... |
def split_state_dict(state_dict):
' split a state_dict into params and other state\n FIXME currently other state is assumed to be norm running state\n '
out_params = {}
out_state = {}
for (k, v) in state_dict.items():
if any(((n in k) for n in _STATE_NAMES)):
out_state[k] = v... |
def get_outdir(path, *paths, retry_inc=False):
outdir = os.path.join(path, *paths)
if (not os.path.exists(outdir)):
os.makedirs(outdir)
elif retry_inc:
count = 1
outdir_inc = ((outdir + '-') + str(count))
while os.path.exists(outdir_inc):
count = (count + 1)
... |
def cross_entropy_loss(logits, labels, label_smoothing=0.0, dtype=jnp.float32):
'Compute cross entropy for logits and labels w/ label smoothing\n Args:\n logits: [batch, length, num_classes] float array.\n labels: categorical labels [batch, length] int array.\n label_smoothing: label smoot... |
def onehot(labels, num_classes, on_value=1.0, off_value=0.0, dtype=jnp.float32):
x = (labels[(..., None)] == jnp.arange(num_classes)[None])
x = lax.select(x, jnp.full(x.shape, on_value), jnp.full(x.shape, off_value))
return x.astype(dtype)
|
def weighted_cross_entropy_loss(logits, labels, weights=None, label_smoothing=0.0, dtype=jnp.float32):
'Compute weighted cross entropy for logits and labels w/ label smoothing.\n Args:\n logits: [batch, length, num_classes] float array.\n labels: categorical labels [batch, length] int array.\n ... |
def create_lr_schedule_epochs(base_lr, decay_type, steps_per_epoch, total_epochs, decay_rate=0.1, decay_epochs=0, warmup_epochs=5.0, power=1.0, min_lr=1e-05):
total_steps = int((total_epochs * steps_per_epoch))
decay_steps = int((decay_epochs * steps_per_epoch))
warmup_steps = int((warmup_epochs * steps_p... |
def create_lr_schedule(base_lr, decay_type, total_steps, decay_rate=0.1, decay_steps=0, warmup_steps=0, power=1.0, min_lr=1e-05):
'Creates learning rate schedule.\n\n Currently only warmup + {linear,cosine} but will be a proper mini-language\n like preprocessing one in the future.\n\n Args:\n tota... |
class AverageMeter():
'Computes and stores the average and current value'
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += (val * n)
... |
def correct_topk(logits, labels, topk=(1,)):
top = lax.top_k(logits, max(topk))[1].transpose()
correct = (top == labels.reshape(1, (- 1)))
return [correct[:k].reshape((- 1)).sum(axis=0) for k in topk]
|
def acc_topk(logits, labels, topk=(1,)):
top = lax.top_k(logits, max(topk))[1].transpose()
correct = (top == labels.reshape(1, (- 1)))
return [((correct[:k].reshape((- 1)).sum(axis=0) * 100) / labels.shape[0]) for k in topk]
|
def get_model_cfg(name):
return deepcopy(_model_cfg[name])
|
def list_models(pattern='', pretrained=True):
model_names = []
for (k, c) in _model_cfg.items():
if ((pretrained and c['default_cfg']['url']) or (not pretrained)):
model_names.append(k)
if pattern:
model_names = fnmatch.filter(model_names, pattern)
return model_names
|
def dcfg(url='', **kwargs):
' Default Dataset Config (ie ImageNet pretraining config)'
cfg = dict(url=url, num_classes=1000, input_size=(3, 224, 224), pool_size=(7, 7), crop_pct=0.875, interpolation='bicubic', mean=IMAGENET_MEAN, std=IMAGENET_STD)
cfg.update(kwargs)
return cfg
|
def pt_acfg(**kwargs):
' Architecture Config (PyTorch model origin) '
bn_cfg = (kwargs.pop('bn_cfg', None) or get_bn_args_pt())
return {'pad_type': 'LIKE', 'bn_cfg': bn_cfg, **kwargs}
|
def tf_acfg(**kwargs):
' Architecture Config (Tensorflow model origin) '
bn_cfg = (kwargs.pop('bn_cfg', None) or get_bn_args_tf())
return {'pad_type': 'SAME', 'bn_cfg': bn_cfg, **kwargs}
|
def get_jax_dir():
jax_home = os.path.expanduser(os.getenv(ENV_JAX_HOME, os.path.join(os.getenv(ENV_XDG_CACHE_HOME, DEFAULT_CACHE_DIR), 'jax')))
return jax_home
|
def download_url_to_file(url, dst, hash_prefix=None, progress=True):
'Download object at the given URL to a local path.\n\n Args:\n url (string): URL of the object to download\n dst (string): Full path where object will be saved, e.g. `/tmp/temporary_file`\n hash_prefix (string, optional):... |
def load_state_dict_from_url(url, model_dir=None, transpose=False, progress=True, check_hash=True, file_name=None):
"Loads the serialized npz object at the given URL.\n\n If the object is already present in `model_dir`, it's deserialized and returned.\n\n The default value of `model_dir` is ``<jax_dir>/chec... |
def scale_by_learning_rate(learning_rate: ScalarOrSchedule):
if callable(learning_rate):
return optax.scale_by_schedule((lambda count: (- learning_rate(count))))
return optax.scale((- learning_rate))
|
def update_moment(updates, moments, decay, order):
return jax.tree_multimap((lambda g, t: (((1 - decay) * (g ** order)) + (decay * t))), updates, moments)
|
def exclude_bias_and_norm(path: Tuple[Any], val: jnp.ndarray) -> jnp.ndarray:
'Filter to exclude biaises and normalizations weights.'
del val
if ((path[(- 1)] == 'bias') or (path[(- 1)] == 'scale')):
return False
return True
|
def _partial_update(updates: optax.Updates, new_updates: optax.Updates, params: optax.Params, filter_fn: Optional[FilterFn]=None) -> optax.Updates:
'Returns new_update for params which filter_fn is True else updates.'
if (filter_fn is None):
return new_updates
wrapped_filter_fn = (lambda x, y: jnp... |
class ScaleByLarsState(NamedTuple):
mu: jnp.ndarray
|
def scale_by_lars(momentum: float=0.9, eta: float=0.001, filter_fn: Optional[FilterFn]=None) -> optax.GradientTransformation:
'Rescales updates according to the LARS algorithm.\n\n Does not include weight decay.\n References:\n [You et al, 2017](https://arxiv.org/abs/1708.03888)\n\n Args:\n ... |
class AddWeightDecayState(NamedTuple):
'Stateless transformation.'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.