code stringlengths 101 5.91M |
|---|
class InPlaceABN(ABN):
def __init__(self, num_features, eps=1e-05, momentum=0.1, affine=True, activation='leaky_relu', slope=0.01):
super(InPlaceABN, self).__init__(num_features, eps, momentum, affine, activation, slope)
def forward(self, x):
return inplace_abn(x, self.weight, self.bias, self.ru... |
def main(args):
logging_dir = Path(args.output_dir, args.logging_dir)
accelerator_project_config = ProjectConfiguration(total_limit=args.checkpoints_total_limit)
accelerator = Accelerator(gradient_accumulation_steps=args.gradient_accumulation_steps, mixed_precision=args.mixed_precision, log_with=args.report... |
class SimpleNet(Model):
OUT_PIXEL_DIST = 4
def __init__(self, in_channels, out_channels, config, D=3, **kwargs):
super(SimpleNet, self).__init__(in_channels, out_channels, config, D)
kernel_size = 3
self.conv1 = ME.MinkowskiConvolution(in_channels=in_channels, out_channels=64, pixel_dist... |
class NodeResourceLimit(object):
MAX_CPU_CORES = 32
MIN_CPU_CORES = 4
MIN_MEMORY = 6144
MAX_MEMORY = 65536
MAX_WORKER_NUM = 60
MAX_PS_NUM = 15
INCREMENTAL_MEMORY_FACTOR = 2
MAX_INCREMENTAL_MEMORY = 8192
HUGE_MEMORY_THRESHOLD = 102400
HUGE_CPU_THRESHOLD = 100
WAIT_CHIEF_TIMEOU... |
def test_impure_interaction_is_zero():
X = [['A', 'A'], ['A', 'B'], ['B', 'A'], ['B', 'B']]
y = [(3.0 + 11.0), (3.0 + 7.0), (5.0 + 11.0), (5.0 + 7.0)]
sample_weight = [24.25, 21.5, 8.125, 11.625]
ranked_strengths = dict(measure_interactions(X, y, min_samples_leaf=1, sample_weight=sample_weight, objectiv... |
class Tracker():
def __init__(self, metric, max_iou_distance=0.7, max_age=70, n_init=3):
self.metric = metric
self.max_iou_distance = max_iou_distance
self.max_age = max_age
self.n_init = n_init
self.kf = kalman_filter.KalmanFilter()
self.tracks = []
self._nex... |
_start_docstrings('CamemBERT Model transformer with a sequence classification/regression head on top (a linear layer\n on top of the pooled output) e.g. for GLUE tasks. ', CAMEMBERT_START_DOCSTRING)
class TFCamembertForSequenceClassification(TFRobertaForSequenceClassification):
config_class = CamembertConfig
... |
class StemWithFixedBatchNorm(BaseStem):
def __init__(self, cfg):
super(StemWithFixedBatchNorm, self).__init__(cfg, norm_func=FrozenBatchNorm2d) |
class DynamicLossScale(LossScale):
def __init__(self, init_loss_scale=(2 ** 15), increment_every=2000, factor=2.0):
super(DynamicLossScale, self).__init__()
self.scale = layers.create_global_var(name=unique_name.generate('loss_scale'), shape=[1], value=init_loss_scale, dtype='float32', persistable=T... |
_metaclass(abc.ABCMeta)
class TextMetricSpec(Configurable, MetricSpec):
def __init__(self, params, name):
Configurable.__init__(self, params, tf.contrib.learn.ModeKeys.EVAL)
self._name = name
self._eos_token = self.params['eos_token']
self._sos_token = self.params['sos_token']
... |
def load_model(model, checkpoint_file):
(e, p) = (model.embed, 'bert/embeddings/')
load_param(checkpoint_file, {e.tok_embed.weight: (p + 'word_embeddings'), e.pos_embed.weight: (p + 'position_embeddings'), e.seg_embed.weight: (p + 'token_type_embeddings'), e.norm.gamma: (p + 'LayerNorm/gamma'), e.norm.beta: (p ... |
def ca_perspective(n=5):
c = pd.read_csv('data/c_parenttext.csv')
c.set_index(['id'], inplace=True)
data = [pd.read_csv(f'data/standard.622/random_ten/{i}/ic.val.csv') for i in range(n)]
scores = []
for sample in data:
sample['ca_score'] = sample['id'].apply((lambda x: c.loc[x].TOXICITY))
... |
class MultiProcessFileTensorStorage(MultiProcessTensorStorage):
def __init__(self, data_schema: Dict[(str, SizeData)], rank_to_fpath: Dict[(int, str)], mode: str):
rank_to_storage = {rank: SingleProcessFileTensorStorage(data_schema, fpath, mode) for (rank, fpath) in rank_to_fpath.items()}
super().__... |
class ResidualBlock(nn.Module):
def __init__(self, in_planes, planes, norm_fn='group', stride=1):
super(ResidualBlock, self).__init__()
self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, padding=1, stride=stride)
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, padding=1)
... |
def main():
args = get_args()
set_seed(args.seed)
dataset = load_dataset('codeparrot/codecomplex', split='train')
train_test = dataset.train_test_split(test_size=0.2)
test_validation = train_test['test'].train_test_split(test_size=0.5)
train_test_validation = DatasetDict({'train': train_test['tr... |
class ODEBlockTimeLastK(nn.Module):
def __init__(self, odeFunction, num_split, solver, K):
super(ODEBlockTimeLastK, self).__init__()
self.odefunc = odeFunction
self.num_split = num_split
self.final_time = world.config['K']
self.one = torch.tensor([self.final_time], requires_g... |
class NN_tb3():
def __init__(self, env, policy, action_bound, OBS_SIZE, index, num_env):
self.beam_mum = OBS_SIZE
self.laser_cb_num = 0
self.scan = None
self.env = env
self.env.index = 0
self.policy = policy
self.action_bound = action_bound
self.global... |
class SummationNode(ExprNode):
def __init__(self, parse_info=None, raw_text=None):
super().__init__(IRNodeType.Summation, parse_info=parse_info, raw_text=raw_text)
self.sub = None
self.exp = None
self.id = None
self.cond = None
self.symbols = None
self.symbol ... |
def main():
args = parse_args()
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', handlers=[logging.StreamHandler(sys.stdout)])
log_level = logging.INFO
logger.setLevel(log_level)
datasets.utils.logging.set_verbosity(log_level)
transf... |
def main():
args = parse(sys.argv[1:])
experiments = pandas.read_csv(args.experiments)
settings = common.load_settings_path(args.settings_path)
stop = (len(experiments) if (args.stop is None) else args.stop)
experiments = experiments.loc[range(args.start, stop)]
overrides = {}
folds = list(r... |
class PredictionBuilder():
def __init__(self, max_depth: int=20):
self.max_depth = max_depth
self.env = None
def set_env(self, env: Environment):
self.env = env
def reset(self):
pass
def get(self, handle: int=0):
raise NotImplementedError() |
class BatchFeature(UserDict):
def __init__(self, data: Optional[Dict[(str, Any)]]=None, tensor_type: Union[(None, str, TensorType)]=None):
super().__init__(data)
self.convert_to_tensors(tensor_type=tensor_type)
def __getitem__(self, item: str) -> Union[Any]:
if isinstance(item, str):
... |
class LTRTrainer(BaseTrainer):
def __init__(self, actor, loaders, optimizer, settings, lr_scheduler=None, ratio=(1 / 8)):
super().__init__(actor, loaders, optimizer, settings, lr_scheduler)
self._set_default_settings()
self.stats = OrderedDict({loader.name: None for loader in self.loaders})
... |
def test_show():
import mmcv
from os import path as osp
from mmdet3d.core.bbox import LiDARInstance3DBoxes
tmp_dir = tempfile.TemporaryDirectory()
temp_dir = tmp_dir.name
(data_root, ann_file, classes, pts_prefix, pipeline, modality, split) = _generate_kitti_dataset_config()
kitti_dataset = ... |
class PResNet(Module):
def __init__(self, block, layers, num_classes=1000):
self.ni = 64
super().__init__()
self.conv1 = conv_act(3, 16, stride=2)
self.conv2 = conv_act(16, 32)
self.conv3 = conv_act(32, 64)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=... |
class BConvCell(nn.Module):
def __init__(self, input_dim, output_dim, kernel_size=3, stride=1, padding=0):
super(BConvCell, self).__init__()
self.output_dim = output_dim
self.stride = stride
self.padding = padding
self.kernel_size = kernel_size
self.gates = nn.Conv2d(... |
def test_pair_aggregator(saliency_mt_model: HuggingfaceEncoderDecoderModel):
out = saliency_mt_model.attribute([EXAMPLES['source'], EXAMPLES['alternative_source']], show_progress=False)
orig_seqattr = out.sequence_attributions[0].aggregate(['vnorm'])
alt_seqattr = out.sequence_attributions[1].aggregate(['vn... |
def main():
input = ImageParam(UInt(8), 3, 'input')
erode = get_erode(input)
erode.compile_jit()
input_data = get_input_data()
input_image = Buffer(input_data)
input.set(input_image)
output_data = np.empty(input_data.shape, dtype=input_data.dtype, order='F')
output_image = Buffer(output_... |
class Instruction():
def __init__(self, name, num_qubits, num_clbits, params):
if ((not isinstance(num_qubits, int)) or (not isinstance(num_clbits, int))):
raise QiskitError('num_qubits and num_clbits must be integer.')
if ((num_qubits < 0) or (num_clbits < 0)):
raise QiskitE... |
def IB_IRM_hyper(sample):
if sample:
return {'ib_weight': (lambda r: (10 ** r.uniform((- 1), 5))), 'ib_anneal': (lambda r: r.uniform(0, 2000)), 'irm_weight': (lambda r: (10 ** r.uniform((- 1), 5))), 'irm_anneal': (lambda r: r.uniform(0, 2000))}
else:
return {'ib_weight': (lambda r: 100.0), 'ib_a... |
def generate_memory(sent, speaker, time):
sent_new = []
sent_token = sent.split(' ')
if ((speaker == '$u') or (speaker == '$s')):
for (idx, word) in enumerate(sent_token):
temp = ([word, speaker, ('turn' + str(time)), ('word' + str(idx))] + (['PAD'] * (MEM_TOKEN_SIZE - 4)))
s... |
def main(args):
update_config_from_file(args.cfg)
if (args.launcher == 'none'):
args.distributed = False
else:
args.distributed = True
init_dist(launcher=args.launcher)
args.rank = int(os.environ['SLURM_PROCID'])
args.gpu = (args.rank % torch.cuda.device_count())
... |
def find_index_path(index_file):
with open(index_file, 'r') as f:
lines = f.readlines()
for line in lines:
pos = line.find('index.html" class="icon icon-home"')
if (pos < 0):
continue
pos1 = line.rfind('"', 0, pos)
if (pos1 < 0):
... |
def create_pseudo_labeled_data(args, infer_input, infer_output, eval_result, id2label, next_data_dir):
dataset = datasets.concatenate_datasets([infer_input, infer_output], axis=1)
if args.do_filter_by_confidence:
dataset = dataset.filter((lambda example: (example['probability'] > args.confidence_thresho... |
def test_transformer_layer():
decoder_layer = TFDecoderLayer()
in_dec = torch.rand(1, 30, 512)
out_enc = torch.rand(1, 128, 512)
out_dec = decoder_layer(in_dec, out_enc)
assert (out_dec.shape == torch.Size([1, 30, 512]))
decoder_layer = TFDecoderLayer(operation_order=('self_attn', 'norm', 'enc_d... |
def main():
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
if ((len(sys.argv) == 2) and sys.argv[1].endswith('.json')):
(model_args, data_args) = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
else:
(model_args, data_args, training_args)... |
def json_encode_np(obj):
if isinstance(obj, np.ndarray):
return list(obj)
elif isinstance(obj, np.float32):
return float(obj)
elif isinstance(obj, np.float64):
return float(obj)
elif isinstance(obj, np.int32):
return int(obj)
elif isinstance(obj, np.int64):
re... |
def loadShader(shaderType, shaderFile):
strFilename = findFileOrThrow(shaderFile)
shaderData = None
with open(strFilename, 'r') as f:
shaderData = f.read()
shader = glCreateShader(shaderType)
glShaderSource(shader, shaderData)
glCompileShader(shader)
status = glGetShaderiv(shader, GL... |
class PyTorchBenchmarkArguments():
def __init__(self, *args, **kwargs):
requires_pytorch(self) |
def validsample(model, val_inputs, train_opt):
try:
val_inputs = [val_inputs['ret_img'], val_inputs['ret_img'], val_inputs['ret_img'], val_inputs['ret_img_mo']]
except:
(xfull, xbg, xid, xmo) = val_inputs
val_inputs = [xfull, xfull, xfull, xmo]
val_inputs = [item.to(train_opt['device... |
def prefetch_batch_input_shape(model: nn.Module, ori_wh: Tuple[(int, int)]) -> dict:
cfg = model.cfg
(w, h) = ori_wh
cfg.test_dataloader.dataset.pipeline[0].type = 'LoadImageFromNDArray'
test_pipeline = Compose(cfg.test_dataloader.dataset.pipeline)
data = {'img': np.zeros((h, w, 3), dtype=np.uint8),... |
class APIPool():
def __init__(self, base_model_path='stabilityai/stable-diffusion-xl-base-1.0', image_encoder_path='checkpoints/sdxl_models/image_encoder', ip_ckpt='checkpoints/sdxl_models/ip-adapter_sdxl.bin', device='cuda') -> None:
self.pipe = StableDiffusionXLPipeline.from_pretrained(base_model_path, to... |
def clip_grad_norm(model, max_norm, norm_type=2, optimizer=None, process_group_name_prefix=''):
if isinstance(optimizer, DeepSpeedZeroOptimizer):
assert (norm_type == 2), 'deep speed zero optimizer only supports L2 norm'
optimizer.clip_grad = max_norm
return None
if ((torch_version() >= ... |
class B2_VGG(nn.Module):
def __init__(self):
super(B2_VGG, self).__init__()
conv1 = nn.Sequential()
conv1.add_module('conv1_1', nn.Conv2d(3, 64, 3, 1, 1))
conv1.add_module('relu1_1', nn.ReLU(inplace=True))
conv1.add_module('conv1_2', nn.Conv2d(64, 64, 3, 1, 1))
conv1.... |
class TestPruningTypes(unittest.TestCase):
model = torchvision.models.resnet18()
def test_pruning_types(self):
compression_manager = prepare_compression(model=self.model, confs=fake_snip_config)
compression_manager.callbacks.on_train_begin()
criterion = nn.CrossEntropyLoss()
opti... |
class LossWrapperBase(nn.Module):
def __init__(self):
super().__init__()
self._LossModuleDict = nn.ModuleDict()
def __iter__(self):
for (k, v) in self._LossModuleDict.items():
(yield v)
def __getitem__(self, item):
if (item in self._LossModuleDict.keys()):
... |
def _parse_args():
parser = argparse.ArgumentParser(description='\n This script will walk into each folder in path, read and count h5f\n files with nonzero image frames, read pre-existing train/val/test\n txt files, and split all the h5f files in this directo... |
def calibrate_thresholds(K, *args):
(fx, fy) = (K[(0, 0)], K[(1, 1)])
factor = (1.0 / (0.5 * (fx + fy)))
for cfg in args:
if isinstance(cfg, dict):
key = [k for k in cfg.keys() if ('threshold' in k.lower())]
assert (len(key) == 1)
cfg[key[0]] *= factor
eli... |
class TestGradient(unittest.TestCase):
def test_odeint(self):
for device in DEVICES:
for method in METHODS:
if (method == 'scipy_solver'):
continue
with self.subTest(device=device, method=method):
(f, y0, t_points, _) = cons... |
def tolerance_clustsolonpath_set(tol):
from phcpy.phcpy2c3 import py2c_set_value_of_continuation_parameter as set
return set(31, tol) |
def weight_l1_loss(pred_loc, label_loc, loss_weight):
(b, _, sh, sw) = pred_loc.size()
pred_loc = pred_loc.view(b, 4, (- 1), sh, sw)
diff = (pred_loc - label_loc).abs()
diff = diff.sum(dim=1).view(b, (- 1), sh, sw)
loss = (diff * loss_weight)
return loss.sum().div(b) |
class _RPN(nn.Module):
def __init__(self, din):
super(_RPN, self).__init__()
self.din = din
self.anchor_scales = cfg.ANCHOR_SCALES
self.anchor_ratios = cfg.ANCHOR_RATIOS
self.feat_stride = cfg.FEAT_STRIDE[0]
self.RPN_Conv = nn.Conv2d(self.din, 512, 3, 1, 1, bias=True)... |
def get_global_rank() -> int:
if (dist.is_available() and dist.is_initialized()):
return dist.get_rank()
if (('RANK' in os.environ) and ('WORLD_SIZE' in os.environ)):
rank = int(os.environ['RANK'])
elif (int(os.environ.get('SLURM_NPROCS', 1)) > 1):
rank = int(os.environ['SLURM_PROCID... |
def main(infile, outfile, num_symbols, min_frequency=2, verbose=False, is_dict=False):
outfile.write('#version: 0.2\n')
vocab = get_vocabulary(infile, is_dict)
vocab = dict([((tuple(x[:(- 1)]) + ((x[(- 1)] + '</w>'),)), y) for (x, y) in vocab.items()])
sorted_vocab = sorted(vocab.items(), key=(lambda x:... |
def search_topics(search_string, max_results=50):
with closing(getDb().cursor()) as cur:
sql = "SELECT topic FROM topics WHERE topic \n LIKE CONCAT(LOWER(%s), '%') LIMIT %s"
cur.execute(sql, (search_string, max_results))
return [x[0] for x in cur.fetchall()] |
def hard2chandep(chan_deps, params=None, device=None):
if (device is None):
device = torch.device('cpu')
split_deps = torch.split(chan_deps, 1, 1)
split_deps = list(split_deps)
(b_sz, __, h_sz, w_sz) = split_deps[0].size()
alpha = torch.sigmoid(split_deps[2])
max_dep = (alpha > 0.5).long... |
class RASampler(torch.utils.data.Sampler):
def __init__(self, dataset, num_replicas=None, rank=None, shuffle=True, num_repeats: int=3):
if (num_replicas is None):
if (not dist.is_available()):
raise RuntimeError('Requires distributed package to be available')
num_repl... |
def cnn_to_mlp(convs, hiddens, dueling=False, layer_norm=False):
return (lambda *args, **kwargs: _cnn_to_mlp(convs, hiddens, dueling, *args, layer_norm=layer_norm, **kwargs)) |
def _tower_loss(scope, images, labels, network, dataset, num_classes, top_name, tf_training, kargs):
logits = network.network(images, num_classes=num_classes, scope=top_name, is_training=tf_training, kargs=kargs)
(total_loss, re_loss) = network.loss(scope, logits, labels)
metric_op = network.metric_op(logit... |
def rename_layernorm_keys(sd):
keys = ['model.encoder.layernorm_embedding.weight', 'model.encoder.layernorm_embedding.bias', 'model.decoder.layernorm_embedding.weight', 'model.decoder.layernorm_embedding.bias']
for k in keys:
v = sd.pop(k)
new_k = k.replace('layernorm_embedding', 'layer_norm')
... |
def UnPickleTM(file):
tmp = None
if (sys.version_info[0] < 3):
f = open(file, 'rb')
unpickler = pickle.Unpickler(f)
unpickler.dispatch[pickle.GLOBAL] = mapped_load_global
tmp = unpickler.load()
f.close()
else:
f = open(file, 'rb')
unpickler = MyUnpickl... |
def mmdet2torchserve(config_file: str, checkpoint_file: str, output_folder: str, model_name: str, model_version: str='1.0', force: bool=False):
mkdir_or_exist(output_folder)
config = Config.fromfile(config_file)
with TemporaryDirectory() as tmpdir:
config.dump(f'{tmpdir}/config.py')
args = N... |
class LeftPaddingMaskDataset(PaddingMaskDataset):
def __init__(self, dataset):
super().__init__(dataset, left_pad=True) |
class ExampleGreyboxExplainer(ExplainerMixin):
available_explanations = ['local']
explainer_type = 'specific'
def __init__(self, model, data, feature_names=None, feature_types=None):
pass
def explain_local(self, X, y=None, name=None):
return ExampleExplanation() |
class TFTrainingHelper(Layer):
def __init__(self, path, config_proto, saver, meta, sess):
self.saver = saver
self.meta = meta
self.export_dir = path
self.sess = sess
if (config_proto is not None):
import tensorflow as tf
invalidInputError(isinstance(co... |
def eval(args, model=None):
if (model is None):
if ('summarization' in args.task_mode):
if (args.tuning_mode == 'prefixtune'):
model = PrefixSummarizationModule(args)
print('the length penalty is {}'.format(args.length_penalty))
with torch.no_grad():
model.eval()
... |
def _tether_sprites(sprites, updates_per_env_step, update_angle_vel=True, anchor=None):
if (len(sprites) == 0):
return
total_mass = sum([s.mass for s in sprites])
if np.isinf(total_mass):
return
center_of_mass = (sum([(s.mass * s.position) for s in sprites]) / total_mass)
total_momen... |
.parametrize('env_config', _ALL_ENV_CONFIGS)
def test_render(env_config):
env = gym.make(env_config[0], render_mode='rgb_array', **env_config[1])
env.reset()
frames = []
for _ in range(10):
frames.append(env.render())
env.step(env.action_space.sample())
for frame in frames:
a... |
def temporal_nms(predictions, nms_thd, max_after_nms=100):
if (len(predictions) == 1):
return predictions
predictions = sorted(predictions, key=(lambda x: x[2]), reverse=True)
tstart = [e[0] for e in predictions]
tend = [e[1] for e in predictions]
tscore = [e[2] for e in predictions]
rst... |
def get_logger(name='root'):
formatter = logging.Formatter(fmt='%(asctime)s [%(levelname)s]: %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger = logging.getLogger(name)
logger.setLevel(logging.INFO)
logger.addHandler(handler)
... |
def colorize(diff_lines):
def bold(s):
return (('\x1b[1m' + s) + '\x1b[0m')
def cyan(s):
return (('\x1b[36m' + s) + '\x1b[0m')
def green(s):
return (('\x1b[32m' + s) + '\x1b[0m')
def red(s):
return (('\x1b[31m' + s) + '\x1b[0m')
for line in diff_lines:
if (lin... |
def hsv_node(node_tree: bpy.types.NodeTree, input_node: bpy.types.Node) -> bpy.types.Node:
hsv_node = zpy.nodes.get_or_make('HSV', 'CompositorNodeHueSat', node_tree)
node_tree.links.new(input_node.outputs['Image'], hsv_node.inputs['Image'])
return hsv_node |
def read_cifar10(filename_queue):
class CIFAR10Record(object):
pass
result = CIFAR10Record()
label_bytes = 1
result.height = 32
result.width = 32
result.depth = 3
image_bytes = ((result.height * result.width) * result.depth)
record_bytes = (label_bytes + image_bytes)
reader =... |
def convSuper(c, **kargs):
return n.LeNet([(32, 3, 3, 1), (32, 4, 4, 1), (64, 3, 3, 1), (64, 4, 4, 1)], [512, 512, c], last_lin=True, **kargs) |
class DglLinkPropPredDataset(object):
'Adapted from
def __init__(self, name, root='dataset', meta_dict=None):
self.name = name
if (meta_dict is None):
self.dir_name = '_'.join(name.split('-'))
if osp.exists(osp.join(root, (self.dir_name + '_dgl'))):
self.... |
def add_itm_params(parser: argparse.ArgumentParser):
parser.add_argument('--conf_th', default=0.2, type=float, help='')
parser.add_argument('--caption_score_weight', default=0.0, type=float, help='')
parser.add_argument('--negative_size', default=10, type=int, help='')
parser.add_argument('--num_hard_ne... |
def rollout(env, policy, max_path_length=np.inf, animated=False, ignore_done=False, num_rollouts=1, adapt_batch_size=None):
wrapped_env = env
while hasattr(wrapped_env, '_wrapped_env'):
wrapped_env = wrapped_env._wrapped_env
paths = []
a_bs = adapt_batch_size
for i in range(num_rollouts):
... |
def resolve_overlaps(ctm_edits, segments):
total_ctm_edits = []
assert (len(ctm_edits) > 0)
next_utt = ctm_edits[0][0][0]
for (utt_index, ctm_edits_for_cur_utt) in enumerate(ctm_edits):
if (utt_index == (len(ctm_edits) - 1)):
break
if (len(ctm_edits_for_cur_utt) == 0):
... |
def test_tactile():
config = get_config()
if (not os.path.exists(config.SIMULATOR.SCENE)):
pytest.skip('Please download Habitat test data to data folder.')
config.defrost()
config.TASK.SENSORS = ['PROXIMITY_SENSOR']
config.freeze()
with habitat.Env(config=config, dataset=None) as env:
... |
.parametrize('seed', range(10))
.parametrize('which', ['greedy', 'optimal'])
def test_basic_perverse(seed, which):
(inputs, output, shapes, size_dict) = ctg.utils.perverse_equation(10, seed=seed)
eq = ctg.utils.inputs_output_to_eq(inputs, output)
print(eq)
path = {'greedy': pb.optimize_greedy, 'optimal'... |
def get_config():
arg_seed = 1
parser = argparse.ArgumentParser()
parser.add_argument('--project-dir', type=str, default='output')
parser.add_argument('--dataset-dir', type=str, default='output')
parser.add_argument('--num-epochs', type=float, default=300)
parser.add_argument('--data-seed', type... |
class BatchNorm2d(_BatchNorm2d):
def forward(self, inputs):
if (not (has_parameters(self) or has_running_stats(self))):
return inputs
return super(BatchNorm2d, self).forward(inputs) |
def DPrint(name, var):
if (PRINT_VARS is False):
return var
return theano.printing.Print(name)(var) |
def FedAvg(w, dict_len):
w_avg = copy.deepcopy(w[0])
for k in w_avg.keys():
w_avg[k] = (w_avg[k] * dict_len[0])
for i in range(1, len(w)):
w_avg[k] += (w[i][k] * dict_len[i])
w_avg[k] = (w_avg[k] / sum(dict_len))
return w_avg |
def conv_init(m):
classname = m.__class__.__name__
if (classname.find('Conv') != (- 1)):
init.xavier_uniform_(m.weight, gain=1.414)
init.constant_(m.bias, 0)
elif (classname.find('BatchNorm') != (- 1)):
init.constant_(m.weight, 1)
init.constant_(m.bias, 0) |
class DummyGenerator(Generator):
def __init__(self) -> None:
super().__init__(num_cities=5)
def __call__(self, key: chex.PRNGKey) -> State:
del key
coordinates = jnp.array([[0.0, 0.0], [0.0, 1.0], [1.0, 0.0], [1.0, 1.0], [0.5, 0.5]], float)
position = jnp.array((- 1), jnp.int32)
... |
def get_config(model: str, trust_remote_code: bool, revision: Optional[str]=None) -> PretrainedConfig:
if ('mistral' in model.lower()):
return MistralConfig.from_pretrained(model, revision=revision)
try:
config = AutoConfig.from_pretrained(model, trust_remote_code=trust_remote_code, revision=rev... |
def encode_region(region):
if isinstance(region, Polygon):
return ','.join(['{},{}'.format(p.x, p.y) for p in region.points])
elif isinstance(region, Rectangle):
return '{},{},{},{}'.format(region.x, region.y, region.width, region.height)
else:
return '' |
def get_placeholder(name, dtype, shape):
if (name in _PLACEHOLDER_CACHE):
(out, dtype1, shape1) = _PLACEHOLDER_CACHE[name]
if (out.graph == tf.get_default_graph()):
assert ((dtype1 == dtype) and (shape1 == shape)), 'Placeholder with name {} has already been registered and has shape {}, d... |
def _validate_data(data_json, n_class):
for split in data_json['splits']:
assert isinstance(split['float_feature_index'], int)
assert isinstance(split['border'], (int, float))
for value in data_json['leaf_values']:
assert isinstance(value, (int, float, list, tuple))
num_splits = len(... |
class Histogram(np.ndarray):
def __new__(cls, *args, **kwargs):
return np.asarray(*args, **kwargs).view(cls) |
def biop(opname, vtype):
g = GraphInterface()
vtype = (('t(' + vtype) + ')')
vp = g.add_vertex(vtype, is_input=True)
vp1 = g.add_vertex(vtype, is_output=True)
vp2 = g.add_vertex(vtype, is_output=True)
vpar = g.add_vertex((('t(' + opname) + ')'))
g.add_edge(vp, vpar)
g.add_edge(vpar, vp1)... |
_model
def tf_efficientnet_b8(pretrained=False, **kwargs):
kwargs['bn_eps'] = BN_EPS_TF_DEFAULT
kwargs['pad_type'] = 'same'
model = _gen_efficientnet('tf_efficientnet_b8', channel_multiplier=2.2, depth_multiplier=3.6, pretrained=pretrained, **kwargs)
return model |
def dump_yaml_and_check_difference(obj, filename, sort_keys=False):
str_dump = dump(obj, None, file_format='yaml', sort_keys=sort_keys)
if osp.isfile(filename):
file_exists = True
with open(filename, 'r', encoding='utf-8') as f:
str_orig = f.read()
else:
file_exists = Fal... |
class VQVAEModel(nn.Module):
def __init__(self, model_opt, opt):
super(VQVAEModel, self).__init__()
num_hiddens = model_opt['num_hiddens']
num_residual_layers = model_opt['num_residual_layers']
num_residual_hiddens = model_opt['num_residual_hiddens']
suf_method = model_opt['s... |
class quantize_attn_pos_model2(base):
_init_pytorch
def __init__(self, vocab_size, embed_dim, embed_init, max_nsent, max_npara, experiment, *args, **kwargs):
super(quantize_attn_pos_model2, self).__init__(vocab_size, embed_dim, embed_init, experiment)
if (self.expe.config.encoder_type.lower() in... |
def filter_keys(key_set):
def _f(dictionary):
return {k: v for (k, v) in dictionary.items() if (k in key_set)}
return _f |
def popen(cmd, mode='rb'):
if (not isinstance(cmd, str)):
raise TypeError(('invalid cmd type (%s, expected string)' % type(cmd)))
import subprocess, io, threading
def cleanup(proc, cmd):
ret = proc.wait()
if (ret > 0):
raise SubprocessFailed(('cmd %s returned %d !' % (cmd... |
class ResNet(nn.Module):
def __init__(self, block, layers, zero_init_residual=False, groups=1, widen=1, width_per_group=64, replace_stride_with_dilation=None, norm_layer=None, normalize=False, output_dim=0, hidden_mlp=0, nmb_prototypes=0, eval_mode=False):
super(ResNet, self).__init__()
if (norm_lay... |
def default_collate(batch):
elem = batch[0]
elem_type = type(elem)
if isinstance(elem, torch.Tensor):
out = None
if (torch.utils.data.get_worker_info() is not None):
numel = sum([x.numel() for x in batch])
storage = elem.storage()._new_shared(numel)
out = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.