code stringlengths 101 5.91M |
|---|
def is_per_channel(qscheme):
return (qscheme in [torch.per_channel_affine, torch.per_channel_affine_float_qparams, torch.per_channel_symmetric]) |
def post_process_result(result):
if (result == float_info.max).any():
mask = (result == float_info.max)
result[mask] = 0
result = np.ma.MaskedArray(result, mask)
return result |
def benchmark_backward(fn, *inputs, grad=None, repeats=10, desc='', verbose=True, amp=False, amp_dtype=torch.float16, **kwinputs):
if verbose:
print(desc, '- Backward pass')
with torch.autocast(device_type='cuda', dtype=amp_dtype, enabled=amp):
y = fn(*inputs, **kwinputs)
if (type(y) is ... |
def set_weight_decay(model, skip_list=(), skip_keywords=(), lr=None):
assert lr
has_decay = []
no_decay = []
skip_keywords_prefix = []
for (name, module) in model.named_modules():
if isinstance(module, nn.LayerNorm):
skip_keywords_prefix.append(name)
continue
... |
_utils.in_tempdir
def test_dory_estimate_query_abundance(location):
copy_dory_catlas()
copy_dory_head()
args = '-k 21 dory_k21 --contigs-db dory_k21/bcalm.unitigs.db'.split()
assert (index_cdbg_by_kmer.main(args) == 0)
args = 'dory_k21 dory-head.fa -o abundances.csv -k 21'.split()
print('** runn... |
_datapipe('concat')
class ConcaterMapDataPipe(MapDataPipe):
datapipes: Tuple[MapDataPipe]
length: int
def __init__(self, *datapipes: MapDataPipe):
if (len(datapipes) == 0):
raise ValueError('Expected at least one DataPipe, but got nothing')
if (not all((isinstance(dp, MapDataPipe... |
def main(config):
device = torch.device(('cuda' if torch.cuda.is_available() else 'cpu'))
model = UGCVQA_NR_model.resnet50(pretrained=True)
model = model.to(device)
print('loading the trained model')
model.load_state_dict(torch.load(config.trained_model))
if (config.database == 'UGCCompressed'):... |
def _init_dist_slurm(backend, port=29500, **kwargs):
proc_id = int(os.environ['SLURM_PROCID'])
ntasks = int(os.environ['SLURM_NTASKS'])
node_list = os.environ['SLURM_NODELIST']
num_gpus = torch.cuda.device_count()
torch.cuda.set_device((proc_id % num_gpus))
addr = subprocess.getoutput('scontrol ... |
_function_dispatch(_logspace_dispatcher)
def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0):
y = linspace(start, stop, num=num, endpoint=endpoint, axis=axis)
if (dtype is None):
return _nx.power(base, y)
return _nx.power(base, y).astype(dtype, copy=False) |
def test_sis_model():
params = {'model': 'SIS', 'b': 0.00208, 'd': 0.01, 'c': 1, 'runs': 10, 'steps': 5000, 'diffusion': 'max', 'method': 'add_edge_random', 'k': 15, 'seed': 1, 'plot_transition': False, 'gif_animation': False}
graph = karate()
ds = Diffusion(graph, **params)
increased_diffusion = ds.run... |
_PREDICTOR_REGISTRY.register()
class DensePoseChartWithConfidencePredictor(DensePoseChartConfidencePredictorMixin, DensePoseChartPredictor):
pass |
class MultiHeadAttention(nn.Module):
def __init__(self, dim: int=512, num_attention_heads: int=8) -> None:
super(MultiHeadAttention, self).__init__()
assert ((dim % num_attention_heads) == 0), 'hidden_dim % num_attention_heads should be zero.'
self.d_head = int((dim / num_attention_heads))
... |
def get_logical_forms_from_entities(entities):
logical_forms = []
if (not entities):
return []
for entity in entities:
logical_forms.extend(webqsp_enum_one_hop_one_entity_candidates(entity))
lfs_2 = webqsp_enum_two_hop_one_entity_candidates(entity)
logical_forms.extend(lfs_2)... |
class AppendableSequenceTester(object):
def empty_list(self):
pass
def reference_list(self):
pass
def test_append_getitem(self, empty_list, reference_list):
lst = empty_list
item = reference_list[0]
lst.append(item)
assert (lst[0] == item)
def test_extend(... |
def _decode_record(record, name_to_features):
example = tf.parse_single_example(record, name_to_features)
for name in list(example.keys()):
t = example[name]
if (t.dtype == tf.int64):
t = tf.to_int32(t)
example[name] = t
return example |
def create_sentencepiece(filenames, model_type, vocab_size, output_prefix):
sp.SentencePieceTrainer.train(input=','.join(filenames), model_prefix=output_prefix, vocab_size=vocab_size, model_type=model_type, character_coverage=1.0, unk_id=UNK_TOKEN_ID, bos_id=BOS_TOKEN_ID, eos_id=EOS_TOKEN_ID, pad_id=PAD_TOKEN_ID)
... |
def recall_at_k(actual, predicted, topk):
sum_recall = 0.0
num_users = len(predicted)
true_users = 0
for i in range(num_users):
act_set = set(actual[i])
pred_set = set(predicted[i][:topk])
if (len(act_set) != 0):
sum_recall += (len((act_set & pred_set)) / float(len(ac... |
class Example(UniqueRepresentation, Parent):
def __init__(self):
self._set = [Integer(_) for _ in [1, 2, 3]]
Parent.__init__(self, facade=IntegerRing(), category=FiniteEnumeratedSets())
def _repr_(self):
return 'An example of a finite enumerated set: {1,2,3}'
def __contains__(self, o... |
def _move_files(dirname, file_prefixes):
print(file_prefixes)
for prefix in file_prefixes:
matching = glob.glob('{}_*'.format(osp.join(dirname, prefix)))
print(matching)
if (len(matching) != 1):
raise NotImplementedError
ext = osp.splitext(matching[0])[1]
outp... |
class StopwatchMeter(Meter):
def __init__(self, round: Optional[int]=None):
self.round = round
self.sum = 0
self.n = 0
self.start_time = None
def start(self):
self.start_time = time.perf_counter()
def stop(self, n=1):
if (self.start_time is not None):
... |
class train_discriminator():
def __init__(self, real_data, latent_data, opt_d, generator, discriminator, device, minority_class, majority_class):
self.real_data = real_data
self.latent_data = latent_data
self.opt_d = opt_d
self.discriminator = discriminator
self.generator = g... |
_cmd('python')
class Python():
ctx = CONTEXT
pythonpath = Option(['--pythonpath', '-p'], metavar='PYTHONPATH', default=None, help='Paths to prepend to PYTHONPATH')
extra_argv = Argument(['extra_argv'], nargs=(- 1), metavar='ARGS', required=False)
def _setup(cls, pythonpath, **kwargs):
vals = Bui... |
class TestFeatureImportance(unittest.TestCase):
def test(self):
exp = FeatureImportance(mode='classification')
exp.add(instance=pd.DataFrame([['a', 'b'], ['c', 'd']], columns=['col 1', 'col 2']), target_label=0, feature_names=['a', 'b', 'c'], feature_values=[1, 2, 3], importance_scores=[0.1, 0.2, 0.... |
.parametrize('impl', MKL_AND_CUBLAS)
def test_4x4(impl):
A_desc = dace.float32[(8, 12, 5, 3)]
B_desc = dace.float32[(8, 12, 3, 6)]
C_desc = dace.float32[(8, 12, 5, 6)]
with change_default(blas, impl):
def test_4x4(A: A_desc, B: B_desc, C: C_desc):
C[:] = np.einsum('abik,abkj->abij', ... |
class Argument():
__slots__ = ('name', 'typename', 'direction', 'role')
def __init__(self, name, typename, direction, role='default'):
self.name = name
self.typename = typename
self.direction = direction
self.role = role |
def register_coco_instances(name, metadata, json_file, image_root):
DatasetCatalog.register(name, (lambda : load_coco_json(json_file, image_root, name)))
MetadataCatalog.get(name).set(json_file=json_file, image_root=image_root, evaluator_type='coco', **metadata) |
def normalize_index(phyche_index, is_convert_dict=False):
normalize_phyche_value = []
for phyche_value in phyche_index:
average_phyche_value = ((sum(phyche_value) * 1.0) / len(phyche_value))
sd_phyche = standard_deviation(phyche_value)
normalize_phyche_value.append([round(((e - average_p... |
_serialization_tests
def test_keras_testing_util_layer_test_multidim(kernel_cls, batch_size, n_dims, n_components):
kernel = kernel_cls()
tf.keras.utils.get_custom_objects()['QuadratureFourierFeatures'] = QuadratureFourierFeatures
layer_test(QuadratureFourierFeatures, kwargs={'kernel': kernel, 'n_components... |
class TruncExpon(ReferenceDistribution):
def __init__(self, *, b):
super().__init__(b=b)
def _support(self, b):
return (0, b)
def _pdf(self, x, b):
return ((- mp.exp((- x))) / mp.expm1((- b)))
def _sf(self, x, b):
return ((mp.exp((- b)) - mp.exp((- x))) / mp.expm1((- b))) |
class FrozenRequirement(object):
def __init__(self, name, req, editable, comments=()):
self.name = name
self.req = req
self.editable = editable
self.comments = comments
_rev_re = re.compile('-r(\\d+)$')
_date_re = re.compile('-(20\\d\\d\\d\\d\\d\\d)$')
def from_dist(cls, ... |
def get_weights(weights):
weights_list = {'resnet': '1Bw4gUsRBxy8XZDGchPJ_URQjbHItikjw', 'resnet18': '1k_v1RrDO6da_NDhBtMZL5c0QSogCmiRn', 'vgg11': '1vZcB-NaPUCovVA-pH-g-3NNJuUA948ni'}
url = f'
output = f'./{weights}.pkl'
gdown.download(url, output, quiet=False) |
def get_dm_mujoco():
global _DM_MUJOCO_MODULE
if _DM_MUJOCO_MODULE:
return _DM_MUJOCO_MODULE
try:
from dm_control import mujoco
except ImportError:
print('Failed to import dm_control.mujoco. Ensure that dm_control (using MuJoCo v2.00) is installed.', file=sys.stderr)
sys.... |
def frechet_distance(mu, cov, mu2, cov2):
(cc, _) = linalg.sqrtm(np.dot(cov, cov2), disp=False)
dist = (np.sum(((mu - mu2) ** 2)) + np.trace(((cov + cov2) - (2 * cc))))
return np.real(dist) |
class SearchAlgorithm():
def __init__(self) -> None:
pass
def search(self, pattern: str, text: str) -> int:
pass |
class Replace(Common):
def __init__(self, log_level=Log.info):
self.__numNode = 0
self.__ar = []
self.LogLevel = log_level
def __calc(self, plan, param, queryid, planid, depth):
def get_children_plan_rows(plan):
_X = [[], []]
_NP = [[], []]
_NP... |
class DoubleSignal(Signal):
def set(self, value) -> None:
sim.simSetDoubleSignal(self._name, value)
def get(self) -> float:
(ret, value) = sim.simGetDoubleSignal(self._name)
self._check_signal(ret, 'double')
return value
def clear(self) -> int:
return sim.simClearDoub... |
def models_all_close(*models):
assert (len(models) > 1)
for model in models[1:]:
are_same_models(models[0], model) |
def main(args):
if (not os.path.exists('./experiments/pretrained_models/NAFNet-REDS-width64.pth')):
gdown.download(' './experiments/pretrained_models/', quiet=False)
opt_path = '/opt/NAFNet/options/test/REDS/NAFNet-width64.yml'
opt = parse(opt_path, is_train=False)
opt['dist'] = False
model ... |
class _CVObjects(_Constraint):
def __init__(self):
super().__init__()
self._constraints = [Interval(Integral, 2, None, closed='left'), HasMethods(['split', 'get_n_splits']), _IterablesNotString(), _NoneConstraint()]
def is_satisfied_by(self, val):
return any((c.is_satisfied_by(val) for c... |
def patch_runtime():
from .runtime import BlockReference, Macro
BlockReference.__call__ = wrap_block_reference_call(BlockReference.__call__)
Macro._invoke = wrap_macro_invoke(Macro._invoke) |
class Sequence(object):
def __getitem__(self, index):
raise NotImplementedError
def __len__(self):
raise NotImplementedError
def on_epoch_end(self):
pass |
def build_default_pretrains(default_treebanks):
default_pretrains = dict(default_treebanks)
for lang in no_pretrain_languages:
default_pretrains.pop(lang, None)
for lang in specific_default_pretrains.keys():
default_pretrains[lang] = specific_default_pretrains[lang]
return default_pretra... |
def test_rosetta():
try:
problem = flexs.landscapes.rosetta.registry()['3msi']
landscape = flexs.landscapes.RosettaFolding(**problem['params'])
seq_length = len(landscape.wt_pose.sequence())
test_seqs = s_utils.generate_random_sequences(seq_length, 100, s_utils.AAS)
landscape... |
def pad_lr(x, fsize, fshift):
M = num_frames(len(x), fsize, fshift)
pad = (fsize - fshift)
T = (len(x) + (2 * pad))
r = ((((M - 1) * fshift) + fsize) - T)
return (pad, (pad + r)) |
class TestModels(TestCase):
keep_initializers_as_inputs = False
from torch.onnx.symbolic_helper import _export_onnx_opset_version
opset_version = _export_onnx_opset_version
def exportTest(self, model, inputs, rtol=0.01, atol=1e-07):
with torch.onnx.select_model_mode_for_export(model, None):
... |
class MIRNet(nn.Module):
def __init__(self, in_channels=3, out_channels=3, n_feat=64, kernel_size=3, stride=2, n_RRG=3, n_MSRB=2, height=3, width=2, bias=False):
super(MIRNet, self).__init__()
self.conv_in = nn.Conv2d(in_channels, n_feat, kernel_size=kernel_size, padding=((kernel_size - 1) // 2), bi... |
def main():
args = parse_args()
print('Called with args:')
print(args)
if (not torch.cuda.is_available()):
sys.exit('Need a CUDA device to run the code.')
if (args.cuda or (cfg.NUM_GPUS > 0)):
cfg.CUDA = True
else:
raise ValueError('Need Cuda device to run !')
if (arg... |
def test_multi_objective_set_normalized():
multi_cdv_tmp = MultiObjectiveCDV(analytical, max_empirical_losses=max_empirical_losses)
multi_cdv_tmp.set_normalized(True)
(final_loss, alphas) = multi_cdv_tmp.get_descent_vector(losses, gradient)
assert (final_loss.data == ((alphas[0] * max_empirical_loss_1) ... |
class SGDOptimizer(BaseOptimizer):
def _apply_dense(self, cache):
g_t = cache['g_t']
cache['s_t'] = (self.learning_rate * g_t)
return cache
def _apply_sparse(self, cache):
(g_t, idxs) = (cache['g_t'], cache['idxs'])
(idxs, idxs_) = tf.unique(idxs)
g_t_ = tf.unsort... |
def _print_net(net):
for i in net.external_input:
print('Input: {}'.format(i))
for i in net.external_output:
print('Output: {}'.format(i))
for op in net.op:
print('Op {}'.format(op.type))
for x in op.input:
print(' input: {}'.format(x))
for y in op.output... |
class DenseBlock(nn.Module):
def __init__(self, h, kernel_size=(3, 3), depth=4):
super(DenseBlock, self).__init__()
self.h = h
self.depth = depth
self.dense_block = nn.ModuleList([])
for i in range(depth):
dil = (2 ** i)
dense_conv = nn.Sequential(nn.C... |
class PrimeNumbers_Inherits(PrimeNumbers_Abstract):
def __init__(self):
super().__init__()
self._populate_coercion_lists_(embedding=IntegerRing())
def __contains__(self, p):
return ((isinstance(p, self.element_class) and (p.parent() is self)) or (isinstance(p, Integer) and p.is_prime()))... |
.torch
def test_can_get_windowed_sequence(sequential_dataset: SequentialDataset):
sd = TorchSequentialDataset(sequential_dataset, max_sequence_length=3, sliding_window_step=2, padding_value=(- 1))
assert (len(sd) == 6)
_compare_sequence(sd, 0, 'item_id', [(- 1), 0, 1])
_compare_sequence(sd, 1, 'item_id'... |
def isSession(timestamp1, timestamp2):
t1 = datetime.fromtimestamp(timestamp1)
t2 = datetime.fromtimestamp(timestamp2)
delta_sec = ((((t1 - t2).days * 24) * 3600) + (t1 - t2).seconds)
return (delta_sec < (30 * 60)) |
def load_op_dep_graph(fname):
with open(fname, 'r') as stream:
result = defaultdict(set)
for op in yaml.safe_load(stream):
op_name = canonical_name(op['name'])
for dep in op.get('depends', []):
dep_name = canonical_name(dep['name'])
result[op_n... |
def is_valid_parameter(object):
has_value = hasattr(object, 'value')
has_set_value = hasattr(object, 'set_value')
has_floating = hasattr(object, 'floating')
return (has_value and has_set_value and has_floating) |
_utils.test()
def test_func_default_value():
def bar(s, t=1):
return (s + t)
def foo() -> ti.i32:
return bar(1)
assert (foo() == 2) |
def process_grouped_by_first_item(lst):
groups = defaultdict(list)
started = False
last_group = None
for (first, *rest) in lst:
rest = (rest[0] if (len(rest) == 1) else rest)
if (started and (first != last_group)):
(yield (last_group, groups[last_group]))
assert (... |
def train(args):
set_seed(args.seed)
print('initializing model')
config = AutoConfig.from_pretrained(args.model)
config.gradient_checkpointing = True
config.use_cache = False
model = AutoModelForCausalLM.from_pretrained(args.model, config=config)
model.train()
model.gradient_checkpointin... |
def digraph_one_root():
classifier = HierarchicalClassifier()
classifier.logger_ = logging.getLogger('HC')
classifier.hierarchy_ = nx.DiGraph([('a', 'b'), ('b', 'c'), ('c', 'd')])
return classifier |
class BioGptForTokenClassification(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def verify_task_dof_maps(dof_maps, id_map, field, use_expand_dofs=False, verbose=False):
timer = Timer(start=True)
if verbose:
output('verifying...')
output('total number of DOFs:', field.n_nod)
output('number of tasks:', len(dof_maps))
count = count2 = 0
dofs = []
if use_exp... |
def composite(image1, image2, mask):
image = image2.copy()
image.paste(image1, None, mask)
return image |
def auto_augment_policy(name='original'):
hparams = _HPARAMS_DEFAULT
if (name == 'original'):
return auto_augment_policy_original(hparams)
elif (name == 'originalr'):
return auto_augment_policy_originalr(hparams)
elif (name == 'v0'):
return auto_augment_policy_v0(hparams)
eli... |
def register_Ns3TransmissionModesLayers_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::TransmissionModesLayers const &', 'arg0')])
cls.add_method('TxMode2LayerNum', 'uint8_t', [param('uint8_t', 'txMode')], is_static=True)
return |
class L2Loss(_Loss):
logger = logging.getLogger()
def forward(self, state_a, state_b):
if (type(state_a) is tuple):
losses = 0.0
for (s_a, s_b) in zip(state_a, state_b):
losses += torch.pow((s_a - s_b), 2)
else:
losses = torch.pow((state_a - st... |
class BitConfig(BackboneConfigMixin, PretrainedConfig):
model_type = 'bit'
layer_types = ['preactivation', 'bottleneck']
supported_padding = ['SAME', 'VALID']
def __init__(self, num_channels=3, embedding_size=64, hidden_sizes=[256, 512, 1024, 2048], depths=[3, 4, 6, 3], layer_type='preactivation', hidde... |
class HandBlockEnv(ManipulateEnv):
def __init__(self, max_step=100, target_position='random', target_rotation='xyz', reward_type='sparse', distance_threshold=0.01, rotation_threshold=0.1):
self.num_step = 0
self.max_step = max_step
super(HandBlockEnv, self).__init__(model_path=MANIPULATE_BLO... |
def layout_grid(img, grid_w=None, grid_h=1, float_to_uint8=True, chw_to_hwc=True, to_numpy=True):
(batch_size, channels, img_h, img_w) = img.shape
if (grid_w is None):
grid_w = (batch_size // grid_h)
assert (batch_size == (grid_w * grid_h))
if float_to_uint8:
img = ((img * 127.5) + 128).... |
.parametrize('tifunc,npfunc', [((lambda x: ti.sqrt(x)), (lambda x: np.sqrt(x))), ((lambda x: ti.rsqrt(x)), (lambda x: (1 / np.sqrt(x)))), ((lambda x: ti.exp(x)), (lambda x: np.exp(x))), ((lambda x: ti.log(x)), (lambda x: np.log(x)))])
_has_autograd
_utils.test()
def test_unary(tifunc, npfunc):
grad_test(tifunc, npf... |
def test_count_string_tokens_empty_input():
assert (count_string_tokens('', model_name='gpt-3.5-turbo-0301') == 0) |
def test_skipper():
def f():
pass
class c():
def __init__(self):
self.me = 'I think, therefore...'
docstring = ' Header\n\n >>> something # skip if not HAVE_AMODULE\n >>> something + else\n >>> a = 1 # skip if not HAVE_BMODULE\n >>> som... |
def tensorize(arr):
ret = torch.from_numpy(arr).float().cuda()
if (len(arr.shape) == 1):
ret = ret.reshape((- 1), 1)
return ret |
def extract_embeddings_vggish(annotation_path, dataset_dir, output_dir, vggish_resource_dir, frame_duration=0.96, hop_duration=0.96, progress=True, vggish_embedding_size=128):
print('* Loading annotations.')
annotation_data = pd.read_csv(annotation_path).sort_values('audio_filename')
extract_vggish_embeddin... |
def main(args):
base_path = f'{args.dpath}/image'
if (not os.path.exists(base_path)):
assert f"args.dpath ({args.dpath}) must contain 'image' directory"
base_opath = f'{args.dpath}/mask'
os.makedirs(base_opath, exist_ok=True)
fpaths = glob.glob(f'{base_path}/*')
for fpath in fpaths:
... |
def _file_rendezvous_handler(url, **kwargs):
def _error(msg):
return _rendezvous_error(('file:// rendezvous: ' + msg))
result = urlparse(url)
path = result.path
if (sys.platform == 'win32'):
import urllib.request
path = urllib.request.url2pathname(result.path)
if (not path):
... |
def calculate_contrastive_empowerment(discriminator, obs, next_obs, latents, num_prior_samples=512, distribution_type='uniform', split_group=(4096 * 32), obs_mean=None, obs_std=None, return_diagnostics=False, prior=None):
discriminator.eval()
if (obs_mean is not None):
obs = ((obs - obs_mean) / (obs_std... |
def GetBfsTree_PNGraph(Graph, StartNId, FollowOut, FollowIn):
return _snap.GetBfsTree_PNGraph(Graph, StartNId, FollowOut, FollowIn) |
def get_padding_2d(kernel_size, dilation=(1, 1)):
return (int((((kernel_size[0] * dilation[0]) - dilation[0]) / 2)), int((((kernel_size[1] * dilation[1]) - dilation[1]) / 2))) |
def load_exp_data(exp_path):
exp_data = None
try:
params_json = load_json(os.path.join(exp_path, 'variant.json'))
progress_csv_path = os.path.join(exp_path, 'progress.csv')
pkl_paths = [os.path.join(exp_path, 'offline_itr_2000.pt')]
exp_data = dict(csv=progress_csv_path, json=par... |
class BartTokenizerFast(RobertaTokenizerFast):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
slow_tokenizer_class = BartTokenizer |
def _test_size_in_bytes():
a = ti.ndarray(ti.i32, 8)
assert (a._get_element_size() == 4)
assert (a._get_nelement() == 8)
b = ti.Vector.ndarray(10, ti.f64, 5)
assert (b._get_element_size() == 80)
assert (b._get_nelement() == 5) |
class Partition0(nn.Module):
LAYER_SCOPES = ['T5ForConditionalGeneration/T5Stack[encoder]/StatelessEmbedding[embed_tokens]', 'T5ForConditionalGeneration/T5Stack[encoder]/Dropout[dropout]', 'T5ForConditionalGeneration/T5Stack[encoder]/ModuleList[block]/T5Block[0]', 'T5ForConditionalGeneration/T5Stack[encoder]/Module... |
def mass_center(model, sim):
mass = np.expand_dims(model.body_mass, 1)
xpos = sim.data.xipos
return (np.sum((mass * xpos), 0) / np.sum(mass))[0] |
_OUTPUTS.register('conv1x1_outputs')
class Conv1x1Outputs(nn.Module):
def __init__(self, cfg, dim_in, spatial_in):
super().__init__()
self.dim_in = dim_in[(- 1)]
self.spatial_in = spatial_in
self.classify = nn.Conv2d(self.dim_in, cfg.MASK.NUM_CLASSES, kernel_size=1, stride=1, padding... |
class WorldConstants():
ROBOT_ID = 1
FLOOR_ID = 2
STAGE_ID = 3
FLOOR_HEIGHT = 0.011
ROBOT_HEIGHT = 0.34
ARENA_BB = np.array([[(- 0.15), (- 0.15), 0], [0.15, 0.15, 0.3]])
LINK_IDS = {'robot_finger_60_link_0': 1, 'robot_finger_60_link_1': 2, 'robot_finger_60_link_2': 3, 'robot_finger_60_link_3... |
def test_anntorchdataset_getitem_pro_exp(adata):
adata.obsm['protein_expression'] = pd.DataFrame(adata.obsm['protein_expression'], index=adata.obs_names)
adata_manager = generic_setup_adata_manager(adata, batch_key='batch', protein_expression_obsm_key='protein_expression')
bd = AnnTorchDataset(adata_manager... |
def main():
args = get_args()
device = ('cuda' if torch.cuda.is_available() else 'cpu')
transform = transforms.Compose([transforms.Scale()])
transform = transforms.Compose([transforms.Scale((512, 512, 3)), transforms.ToTensor(), transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))])
G = G... |
def train_imgf(opt):
model = img2state(opt).cuda()
dataset = Robotdata.get_loader(opt)
optimizer = torch.optim.Adam(model.parameters())
loss_fn = nn.MSELoss()
for epoch in range(50):
for (i, item) in enumerate(dataset):
(state, action, result) = item[0]
state = state.... |
def test_control_newton_cr_multiple(state_forms, bcs_list, J, states, controls, adjoints, config_ocp):
config_ocp.set('AlgoTNM', 'inner_newton', 'cr')
ocp = cashocs.OptimalControlProblem(state_forms, bcs_list, J, states, controls, adjoints, config=config_ocp)
ocp.solve(algorithm='newton', rtol=0.01, atol=0.... |
_tokenizer('space', dataclass=FairseqDataclass)
class SpaceTokenizer(object):
def __init__(self, *unused):
self.space_tok = re.compile('\\s+')
def encode(self, x: str) -> str:
return self.space_tok.sub(' ', x)
def decode(self, x: str) -> str:
return x |
class Mixed_4c(nn.Module):
def __init__(self):
super(Mixed_4c, self).__init__()
self.branch0 = nn.Sequential(BasicConv3d(512, 160, kernel_size=1, stride=1))
self.branch1 = nn.Sequential(BasicConv3d(512, 112, kernel_size=1, stride=1), SepConv3d(112, 224, kernel_size=3, stride=1, padding=1))
... |
class EfficientDMC():
def __init__(self, clusterings: List[Clustering], measure_type='mutual_info'):
self.clusterings = clusterings
self.eps = 1e-20
def init_cache(self):
P = len(self.combinations)
C = self.clusterings[0].ncentroids
N = torch.full((P, C), self.eps)
... |
def LF_nonunion(c):
complication = c.complication.get_span().lower()
v = ((complication == 'nonunion') or (complication == 'non-union'))
return ((- 1) if v else 0) |
class TwoAFCDataset(BaseDataset):
def initialize(self, dataroots, load_size=64):
if (not isinstance(dataroots, list)):
dataroots = [dataroots]
self.roots = dataroots
self.load_size = load_size
self.dir_ref = [os.path.join(root, 'ref') for root in self.roots]
self.... |
class Scanner():
def __init__(self):
self.done = False
self.flow_level = 0
self.tokens = []
self.fetch_stream_start()
self.tokens_taken = 0
self.indent = (- 1)
self.indents = []
self.allow_simple_key = True
self.possible_simple_keys = {}
de... |
class ConvBN(nn.Sequential):
def __init__(self, c1, c2, k, s, p):
super().__init__(nn.Conv2d(c1, c2, k, s, p), nn.BatchNorm2d(c2)) |
def endstate(state):
A = state.add_read('A')
t = state.add_tasklet('endtask', {'a'}, {}, 'printf("done %f\\n", a)')
state.add_edge(A, None, t, 'a', dace.Memlet(data='A', subset='0')) |
class LongT5OnnxConfig(OnnxSeq2SeqConfigWithPast):
def inputs(self) -> Mapping[(str, Mapping[(int, str)])]:
common_inputs = {'input_ids': {0: 'batch', 1: 'encoder_sequence'}, 'attention_mask': {0: 'batch', 1: 'encoder_sequence'}}
if self.use_past:
common_inputs['attention_mask'][1] = 'pa... |
def _get_generator(seed: int) -> torch.Generator:
rng = torch.Generator()
rng.manual_seed(seed)
return rng |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.