code stringlengths 101 5.91M |
|---|
class ResnetCompleteNetworkTest(tf.test.TestCase):
def _resnet_small(self, inputs, num_classes=None, is_training=True, global_pool=True, output_stride=None, include_root_block=True, spatial_squeeze=True, reuse=None, scope='resnet_v2_small'):
block = resnet_v2.resnet_v2_block
blocks = [block('block1'... |
def compute_BERT_CLS_feature(model, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None) -> torch.FloatTensor:
if (model.training is True):
raise ValueError
outputs = model.bert(in... |
class FrameworkInfo():
def __init__(self, activation_quantizer_mapping: Dict[(QuantizationMethod, Callable)], kernel_channels_mapping: DefaultDict, activation_min_max_mapping: Dict[(str, tuple)], layer_min_max_mapping: Dict[(Any, tuple)], kernel_ops_attributes_mapping: DefaultDict, out_channel_axis_mapping: Default... |
def convert_space_to_rllab_space(space):
from sandbox.rocky.tf.spaces import Box as TfBox
from sandbox.rocky.tf.spaces import Discrete as TfDiscrete
from rllab.spaces.discrete import Discrete as RllabDiscrete
from rllab.spaces.box import Box as RllabBox
if (isinstance(space, RllabBox) or isinstance(... |
class _dispatch_dtypes(tuple):
def __add__(self, other):
assert isinstance(other, tuple)
return _dispatch_dtypes(tuple.__add__(self, other)) |
def _simplify_atans(exprn):
if (not _exprn_contains_funcs(exprn, [atan2])):
return factor_terms(exprn)
pnames = ('a', 'x', 'y')
(a_w, x_w, y_w) = symbols(','.join(((n_ + '_w') for n_ in pnames)), cls=Wild, real=True)
n_w = Wild('n_w', properties=((lambda x: x.is_integer),))
c = Function('c',... |
def get_preprocessing_model(input_size=224):
preprocessing_model = keras.Sequential()
preprocessing_model.add(layers.CenterCrop(input_size, input_size))
preprocessing_model.add(layers.Normalization(mean=[(0.485 * 255), (0.456 * 255), (0.406 * 255)], variance=[((0.229 * 255) ** 2), ((0.224 * 255) ** 2), ((0.... |
class ECM(SageObject):
def __init__(self, B1=10, B2=None, **kwds):
self._cmd = self._make_cmd(B1, B2, kwds)
def _make_cmd(self, B1, B2, kwds):
ecm = ['ecm']
options = []
for (x, v) in kwds.items():
if (v is False):
continue
options.append('... |
def test_RFE_fit_score_params():
class TestEstimator(BaseEstimator, ClassifierMixin):
def fit(self, X, y, prop=None):
if (prop is None):
raise ValueError('fit: prop cannot be None')
self.svc_ = SVC(kernel='linear').fit(X, y)
self.coef_ = self.svc_.coef_
... |
def frontalcortex_dropseq(save_path: str='data/') -> anndata.AnnData:
return _load_frontalcortex_dropseq(save_path=save_path) |
class NCISPrecision(NCISMetric):
_scala_udf_name = 'getNCISPrecisionMetricValue'
def _get_metric_value_by_user(k, *args):
(pred, ground_truth, pred_weights) = args
if ((len(pred) == 0) or (len(ground_truth) == 0)):
return 0
mask = np.isin(pred[:k], ground_truth)
retur... |
class CustomEntityParserUsage(Enum):
WITH_STEMS = 0
WITHOUT_STEMS = 1
WITH_AND_WITHOUT_STEMS = 2
def merge_usages(cls, lhs_usage, rhs_usage):
if (lhs_usage is None):
return rhs_usage
if (rhs_usage is None):
return lhs_usage
if (lhs_usage == rhs_usage):
... |
def cut_J_based_on_mean_func(J, e_mean):
if (J is None):
J_before = None
J_after = None
elif (e_mean >= max(J)):
J_before = J
J_after = None
elif (e_mean <= min(J)):
J_before = None
J_after = J
else:
J_before = (min(J), e_mean)
J_after = (e... |
class HalfCheetahVelEnv(HalfCheetahEnvMetaBase):
def __init__(self, task=None):
task = (task or {'velocity': 0.0})
self._task = task
self._goal_vel = task['velocity']
super().__init__()
def step(self, action):
xposbefore = self.sim.data.qpos[0]
self.do_simulation(... |
class MultiPassModelTests(tf.test.TestCase):
def _test_single_pass(self, method):
config = get_config('resnet-test')
config.momentum = 0.0
config.base_learn_rate = 0.1
np.random.seed(0)
BSIZE = config.batch_size
xval = np.random.uniform((- 1.0), 1.0, [BSIZE, config.he... |
def parse_args():
parser = argparse.ArgumentParser(description='Generate COCO test image information for COCO panoptic segmentation.')
parser.add_argument('data_root', help='Path to COCO annotation directory.')
args = parser.parse_args()
return args |
def main():
if (FAST_DEV_RUN == True):
training_args = TrainingArguments(output_dir='./roberta_gen/checkpoints', overwrite_output_dir=True, max_steps=1, warmup_steps=0, logging_steps=1, save_steps=1, max_grad_norm=5.0, per_device_eval_batch_size=8, per_device_train_batch_size=8, gradient_accumulation_steps=... |
def test_alpha_exponent_insertion_none():
insert = []
with mock.patch('pynguin.utils.randomness.next_float') as float_mock:
float_mock.return_value = 0.2
func = MagicMock()
func.return_value = None
alpha_exponent_insertion(insert, func)
assert (insert == []) |
class OutliersFilter():
def __init__(self, interquartile_coeff, mode_percentile, min_percentile, max_percentile):
self.interquartile_coeff = interquartile_coeff
self.mode_percentile = mode_percentile
self.min_percentile = min_percentile
self.max_percentile = max_percentile
def pe... |
def dump_torchscript_IR(model, dir):
PathManager.mkdirs(dir)
def _get_script_mod(mod):
if isinstance(mod, torch.jit.TracedModule):
return mod._actual_script_module
return mod
with PathManager.open(os.path.join(dir, 'model_ts_code.txt'), 'w') as f:
def get_code(mod):
... |
def evaluate(algo, make_env_test, num_eval_episodes: int=5, seed: int=0):
returns = []
for i_ep in range(num_eval_episodes):
env_test = make_env_test(((seed * 100) + i_ep))
(state, _) = env_test.reset()
episode_return = 0.0
(terminated, truncated) = (False, False)
while (... |
class domain_classifier(nn.Module):
def __init__(self, hidden_size, device):
super(domain_classifier, self).__init__()
self.classify = nn.Sequential(nn.Linear(hidden_size, 512), nn.LeakyReLU(0.2, True), nn.Linear(512, 1), nn.Sigmoid())
self.to(device)
def forward(self, x):
output... |
def test_n_features_in_validation():
est = MyEstimator()
X_train = [[1, 2, 3], [4, 5, 6]]
est._check_n_features(X_train, reset=True)
assert (est.n_features_in_ == 3)
msg = 'X does not contain any features, but MyEstimator is expecting 3 features'
with pytest.raises(ValueError, match=msg):
... |
def test_broadcast_float_int_2d_regular():
this = ak.contents.RegularArray(ak.contents.NumpyArray(np.array([1.0, 2.0, 3.0, 4.0], dtype='float64')), size=2, parameters={'name': 'this'})
that = ak.contents.RegularArray(ak.contents.NumpyArray(np.array([1, 9], dtype='int64')), size=1, parameters={'name': 'that'})
... |
def get_tf_metrics(m):
if callable(m):
return m
elif (m.lower() == 'mae'):
return tf.keras.metrics.MAE
elif (m.lower() == 'mse'):
return tf.keras.metrics.MSE
elif (m.lower() == 'acc'):
def acc(y_true, y_pred):
return tf.reduce_mean(y_true)
return acc
... |
def test_MLR():
model_name = 'MLR'
(region_x, y, region_feature_columns) = get_test_data(SAMPLE_SIZE, sparse_feature_num=3, dense_feature_num=3, prefix='region')
(base_x, y, base_feature_columns) = get_test_data(SAMPLE_SIZE, sparse_feature_num=3, dense_feature_num=3, prefix='base')
(bias_x, y, bias_feat... |
def register_functions_ns3_Config(module, root_module):
module.add_function('Connect', 'void', [param('std::string', 'path'), param('ns3::CallbackBase const &', 'cb')])
module.add_function('ConnectWithoutContext', 'void', [param('std::string', 'path'), param('ns3::CallbackBase const &', 'cb')])
module.add_f... |
def torch_persistent_save(obj, filename, async_write: bool=False):
if async_write:
with PathManager.opena(filename, 'wb') as f:
_torch_persistent_save(obj, f)
else:
with PathManager.open(filename, 'wb') as f:
_torch_persistent_save(obj, f) |
def decoder_with_encoder_attention_backward(x, encoder_out, dy, sattn_concat, sattn_proj_q, sattn_proj_k, sattn_proj_v, sattn_scaled_scores, sattn_dropout_mask, norm1_mean, norm1_std, norm1_normed, edattn_concat, edattn_proj_q, edattn_proj_k, edattn_proj_v, edattn_scaled_scores, edattn_dropout_mask, norm2_mean, norm2_s... |
def construct_beta_hats(Sigma, R, eps_list, max_norm):
halved_eps_list = [(eps / 2.0) for eps in eps_list]
sigma_sensitivity = 2.0
Sigma_hats = noise_reduc.gen_list(Sigma, sigma_sensitivity, halved_eps_list)
r_sensitivity = 2.0
R_hats = noise_reduc.gen_list(R, r_sensitivity, halved_eps_list)
bet... |
def find_executable_batch_size(function: callable=None, starting_batch_size: int=128, auto_find_batch_size: bool=False):
if (function is None):
return functools.partial(find_executable_batch_size, starting_batch_size=starting_batch_size, auto_find_batch_size=auto_find_batch_size)
if auto_find_batch_size... |
def test_waveform_id_to_network_station_location():
assert (waveform_id_to_network_station_location('NET.STA.LOC.CHA') == 'NET.STA.LOC')
assert (waveform_id_to_network_station_location('NET.STA..CHA') == 'NET.STA.')
assert (waveform_id_to_network_station_location('invalid') == 'invalid') |
class B100(base.SRBase):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
return
def get_path(self) -> str:
return path.join(self.dpath, 'benchmark', 'b100') |
def logical_xor_scalar_backward(grad_inputs, inputs, input_shapes, outputs, output_shapes, val):
return ([None] * (len(grad_inputs) + len(inputs))) |
def maybe_decode_diffs(diff_decoders, h_t: _Array, edge_fts: _Array, graph_fts: _Array, decode_diffs: bool) -> Optional[Dict[(str, _Array)]]:
if decode_diffs:
preds = {}
node = _Location.NODE
edge = _Location.EDGE
graph = _Location.GRAPH
preds[node] = _decode_node_diffs(diff_... |
class LEDTokenizerFast(PreTrainedTokenizerFast):
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 = LEDTokenizer
model_input_names = ['input_ids', 'attention_mask']
de... |
def prepare_data_for_parallel(tokenizer, train_data, test_data, max_length, max_length_per_example, method_type, n_classes, test_inputs, prefixes, idx, prefixes_with_space, bos_token_id, eos_token_id):
assert (train_data is not None)
demonstrations_list = []
np.random.shuffle(train_data)
for (sent, labe... |
def hard_osimertinib(mean_cls=GeometricMeanScoringFunction) -> GoalDirectedBenchmark:
smiles = 'COc1cc(N(C)CCN(C)C)c(NC(=O)C=C)cc1Nc2nccc(n2)c3cn(C)c4ccccc34'
modifier = ClippedScoreModifier(upper_x=0.8)
similar_to_osimertinib = TanimotoScoringFunction(smiles, fp_type='FCFP4', score_modifier=modifier)
b... |
def _write(out_path, text):
try:
with open(out_path, 'r') as f:
old_text = f.read()
except IOError:
old_text = None
if (old_text != text):
with open(out_path, 'w') as f:
logger.info('Writing {}'.format(out_path))
f.write(text)
else:
log... |
def parse_args():
parser = argparse.ArgumentParser(description='A demo of person search')
parser.add_argument('--gpu', default=(- 1), type=int, help='GPU device id to use. Default: -1, means using CPU')
parser.add_argument('--checkpoint', help='The checkpoint to be used. Default: None')
parser.add_argum... |
def _singular_func(self, singular=singular):
self.parent()._singular_(singular).set_ring()
try:
self.__singular._check_valid()
if (self.__singular.parent() is singular):
return self.__singular
except (AttributeError, ValueError):
pass
return _singular_init_func(self, ... |
def get_reward_targets(env: Union[(offline_env.OfflineEnv, gym.wrappers.TimeLimit)], env_name: str, reward_fractions: List[float], targets: str='of expert', average_reward_to_go: bool=True) -> List[float]:
if (targets == 'of demos'):
reward_to_go = dataset.reward_to_go(env.get_dataset(), average=average_rew... |
def train_policy(num_of_envs, log_relative_path, maximum_episode_length, skip_frame, seed_num, her_config, total_time_steps, validate_every_timesteps, task_name):
task = generate_task(task_generator_id=task_name, dense_reward_weights=np.array([100000, 0, 0, 0]), fractional_reward_weight=0)
env = CausalWorld(tas... |
def cw_trans_reg_format(reg: sTRANS_sBC_reg):
(n, c, h, w) = (reg[f'res0_{d}'] for d in 'nchw')
opd0 = dict(address=reg.opd0_addr, dtype=DType(reg.res0_prec), shape=(n, w, h, c), layout=Layout.alignEU)
res0 = dict(address=reg.res0_addr, dtype=DType(reg.res0_prec), shape=(n, c, h, w), layout=Layout.alignEU)
... |
class OwlViTOnnxConfig(OnnxConfig):
def inputs(self) -> Mapping[(str, Mapping[(int, str)])]:
return OrderedDict([('input_ids', {0: 'batch', 1: 'sequence'}), ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ('attention_mask', {0: 'batch', 1: 'sequence'})])
def outputs(self) -> ... |
def register_Ns3UanPhyPerUmodem_methods(root_module, cls):
cls.add_constructor([param('ns3::UanPhyPerUmodem const &', 'arg0')])
cls.add_constructor([])
cls.add_method('CalcPer', 'double', [param('ns3::Ptr< ns3::Packet >', 'pkt'), param('double', 'sinrDb'), param('ns3::UanTxMode', 'mode')], is_virtual=True)
... |
def readTSVFile(path, verbose=False):
with open(path, 'r') as f:
data = [line.strip().split('\t') for line in f]
if verbose:
print('[I] file read complete with length', len(data))
return data |
def entrygen(execute_path):
abspath = os.path.join(os.path.dirname(__file__), execute_path)
files = os.listdir(abspath)
entrygen_functions.append(f'''# f"{{package_path}}/{execute_path}
''')
entrygen_count = 0
for file in files:
file_abspath = os.path.join(os.path.dirname(execute_path), file... |
def train_mixup(epoch, args):
print(('\nEpoch: %d' % epoch))
net.train()
train_loss = 0
correct = 0
total = 0
for (batch_idx, (inputs, targets)) in enumerate(trainloader):
(inputs, targets) = (inputs.to(device), targets.to(device))
(inputs, targets_a, targets_b, lam) = mixup_data... |
.gpu
def test_scalar_output_ptr_access():
sdfg = dace.SDFG('scalptrtest')
state = sdfg.add_state()
sdfg.add_scalar('scal', dace.float64, transient=True, storage=dace.dtypes.StorageType.GPU_Global)
sdfg.add_array('__return', [1], dace.float64)
tasklet = state.add_tasklet('write', {}, {'outp': dace.po... |
def soft_rounding_uniform_quantizer(input_tensor: tf.Tensor, auxvar_tensor: tf.Variable, min_tensor: tf.Tensor, max_tensor: tf.Tensor, num_bits: int) -> tf.Tensor:
(min_range, max_range) = qutils.fix_range_to_include_zero(min_tensor, max_tensor, num_bits)
delta = qutils.calculate_delta_uniform(min_range, max_ra... |
def test_read_tag():
str_io = BytesIO()
r = _make_readerlike(str_io)
c_reader = m5u.VarReader5(r)
assert_raises(IOError, c_reader.read_tag)
tag = _make_tag('i4', 1, mio5p.miINT32, sde=True)
tag['byte_count'] = 5
_write_stream(str_io, tag.tostring())
assert_raises(ValueError, c_reader.rea... |
class MetaSimulation(BaseSimulation):
_repeat_sim = False
def __init__(self, simulations, mappings):
warnings.warn('The MetaSimulation class is a work in progress and might change in the future', stacklevel=2)
self.simulations = simulations
self.mappings = mappings
self.model = N... |
('dace.comm.BCGather')
def _bcgather(pv: ProgramVisitor, sdfg: SDFG, state: SDFGState, in_buffer: str, out_buffer: str, block_sizes: Union[(str, Sequence[Union[(sp.Expr, Number)]])]):
from dace.libraries.pblas.nodes.pgeadd import BlockCyclicGather
libnode = BlockCyclicGather('_BCGather_')
inbuf_range = None... |
class TestRuntime(unittest.TestCase):
def dummy_intervalset():
return IntervalSet([TestRuntime.dummy_interval()])
def query(vids):
return IntervalSetMapping({vid: TestRuntime.dummy_intervalset() for vid in vids})
def dummy_interval(payload=None):
return Interval(Bounds3D(1, 10), payl... |
class MultiVAE(RecMixin, BaseRecommenderModel):
_charger
def __init__(self, data, config, params, *args, **kwargs):
self._random = np.random
self._random_p = random
self._ratings = self._data.train_dict
self._sampler = sp.Sampler(self._data.sp_i_train)
if (self._batch_siz... |
class FrozenRequirement(object):
def __init__(self, name, req, editable, comments=()):
self.name = name
self.canonical_name = canonicalize_name(name)
self.req = req
self.editable = editable
self.comments = comments
def from_dist(cls, dist):
(req, editable, comment... |
def register_Ns3MmWaveSpectrumSignalParametersDlCtrlFrame_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::MmWaveSpectrumSignalParametersDlCtrlFrame const &', 'p')])
cls.add_method('Copy', 'ns3::Ptr< ns3::SpectrumSignalParameters >', [], is_virtual=True)
cls.add_instan... |
def load_shard(meta_path):
(i, meta_path) = meta_path
shard_name = Path(meta_path).stem
metadata = {}
with open(meta_path, 'r') as f:
shard_file = json.load(f)
count = len(shard_file)
for line in shard_file:
idx = line['filename'].split('.')[0]
line['shard... |
def test_enc_head():
inputs = [torch.randn(1, 32, 21, 21)]
head = EncHead(in_channels=[32], channels=16, num_classes=19, in_index=[(- 1)])
if torch.cuda.is_available():
(head, inputs) = to_cuda(head, inputs)
outputs = head(inputs)
assert (isinstance(outputs, tuple) and (len(outputs) == 2))
... |
def main():
scheduler = BlockingScheduler(timezone=utc)
scheduler.add_job(tick, 'interval', seconds=10)
try:
scheduler.start()
except (KeyboardInterrupt, SystemExit):
pass |
def collect_core_entities_simple(x):
all_entities = []
for (i, j) in zip(*x['entityCell'].nonzero()):
if ((j == 0) and (j in x['entityColumn'])):
all_entities.append(str(x['tableData'][i][j]['surfaceLinks'][0]['target']['id']))
return all_entities |
class Camera():
def __init__(self, cameraResolution=[320, 240]):
self.cameraResolution = cameraResolution
camTargetPos = [0.5, 0, 0.05]
camDistance = 0.4
upAxisIndex = 2
yaw = 90
pitch = (- 30.0)
roll = 0
fov = 60
nearPlane = 0.01
farPl... |
def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=None):
(host, port) = address
err = None
for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
(af, socktype, proto, canonname, sa) = res
sock = None
try:
sock = socket.socket(af, s... |
class LatentTransformerDecoderLayer(TransformerDecoderLayer):
def __init__(self, args, idx, layer_select=None, no_encoder_attn=False, add_bias_kv=False, add_zero_attn=False):
super().__init__(args, no_encoder_attn, add_bias_kv, add_zero_attn)
self.idx = idx
self.layer_select = layer_select
... |
def clean_input(prompt: str='', talk=False):
try:
cfg = Config()
if cfg.chat_messages_enabled:
for plugin in cfg.plugins:
if (not hasattr(plugin, 'can_handle_user_input')):
continue
if (not plugin.can_handle_user_input(user_input=prompt... |
def run_deep_graph_infomax(base_model, generator, epochs, reorder=(lambda sequence, subjects: subjects)):
corrupted_generator = CorruptedGenerator(generator)
gen = corrupted_generator.flow(G.nodes())
infomax = DeepGraphInfomax(base_model, corrupted_generator)
(x_in, x_out) = infomax.in_out_tensors()
... |
def train(net, optimizer, data, target, NUM_BATCHES):
for i in range(NUM_BATCHES):
net.zero_grad()
x = data[i].reshape(((- 1), 1))
y = target[i].reshape(((- 1), 1))
loss = net.BBB_loss(x, y)
loss.backward()
optimizer.step() |
class AlbertConfig(PretrainedConfig):
model_type = 'albert'
def __init__(self, vocab_size=30000, embedding_size=128, hidden_size=4096, num_hidden_layers=12, num_hidden_groups=1, num_attention_heads=64, intermediate_size=16384, inner_group_num=1, hidden_act='gelu_new', hidden_dropout_prob=0, attention_probs_drop... |
class Bilinear(Module):
__constants__ = ['in1_features', 'in2_features', 'out_features']
in1_features: int
in2_features: int
out_features: int
complex_weights: bool
weight: Union[(Tensor, Tuple[(Tensor, Tensor)])]
bias: Optional[Union[(Tensor, Tuple[(Tensor, Tensor)])]]
def __init__(self... |
class StandardPermutations_avoiding_12(StandardPermutations_avoiding_generic):
def __init__(self, n):
super().__init__(n, (Permutations()([1, 2]),))
def __iter__(self):
(yield self.element_class(self, range(self.n, 0, (- 1)), check=False))
def cardinality(self):
return ZZ.one() |
class RealTrafficMatrix(TrafficMatrix):
def __init__(self, problem, tm, date, time, seed=0, scale_factor=1.0):
super().__init__(problem, tm, seed, scale_factor=1.0)
self._date = date
self._time = time
def model(self):
return 'real'
def date(self):
return self._date
... |
class HParams(object):
def __init__(self, **kwargs):
self._items = {}
for (k, v) in kwargs.items():
self._set(k, v)
def _set(self, k, v):
self._items[k] = v
setattr(self, k, v)
def __getattr__(self, k):
if (not hasattr(self, k)):
return None
... |
def _generate_md_atari_batch(atari_envs):
for name in atari_envs:
subname = name[6:]
_generate_md_atari_single_env(filepath='envs/gym/atari/{}.md'.format(subname), env_title='atari-{}'.format(subname)) |
def inputs_to_tree_reps(args, dep_heads, l, prune, subj_pos=None, obj_pos=None):
maxlen = max(l)
dep_heads = dep_heads.cpu().numpy()
if subj_pos:
subj_pos = subj_pos.cpu().numpy()
if obj_pos:
obj_pos = obj_pos.cpu().numpy()
trees = [head_to_tree(dep_heads[i], l[i], prune, None, None)... |
def main(args):
args.distributed_world_size = torch.cuda.device_count()
port = random.randint(10000, 20000)
args.distributed_init_method = 'tcp://localhost:{port}'.format(port=port)
args.distributed_init_host = 'localhost'
args.distributed_port = (port + 1)
mp = torch.multiprocessing.get_context... |
def _depthwise_conv2d(inputs, kernel, strides, padding):
return jax.lax.conv_general_dilated(inputs, kernel, strides, padding, feature_group_count=inputs.shape[(- 1)], dimension_numbers=('NHWC', 'HWIO', 'NHWC')) |
class SubWithTorchFunction(torch.Tensor):
def __torch_function__(self, func, types, args=(), kwargs=None):
if (kwargs is None):
kwargs = {}
return super().__torch_function__(func, types, args, kwargs) |
def res_block(x):
inputs = x
x = conv_block(x, 16, 3, 1)
x = conv_block(x, 16, 3, 1, activation=None)
return layers.Add()([inputs, x]) |
def aa_to_rotmat(axis_angle: Union[(torch.Tensor, numpy.ndarray)]) -> Union[(torch.Tensor, numpy.ndarray)]:
if (axis_angle.shape[(- 1)] != 3):
raise ValueError(f'Invalid input axis angles shape f{axis_angle.shape}.')
t = Compose([axis_angle_to_matrix])
return t(axis_angle) |
def size(g, self, dim):
if _is_value(dim):
raise RuntimeError('ONNX export only supports constant dim values in .size()')
full_shape = g.op('Shape', self)
return select(g, full_shape, dim=0, index=dim) |
def filter_errors(errors, method, Estimator=None):
for (code, message) in errors:
if (code in ['RT02', 'GL01', 'GL02']):
continue
if (code in ['SA01', 'EX01']):
continue
if ((code == 'PR02') and (Estimator is not None) and (method is not None)):
method_obj... |
('Concat')
def TranslateConcat(layer, pretrained_blobs, is_test, **kwargs):
caffe_op = BaseTranslate(layer, 'Concat')
caffe_op.output.extend([(('_' + caffe_op.output[0]) + '_dims')])
AddArgument(caffe_op, 'order', 'NCHW')
return (caffe_op, []) |
class DetectionCheckpointer(Checkpointer):
def __init__(self, model, save_dir='', *, save_to_disk=None, **checkpointables):
is_main_process = comm.is_main_process()
super().__init__(model, save_dir, save_to_disk=(is_main_process if (save_to_disk is None) else save_to_disk), **checkpointables)
de... |
_args('v', 'v', 'i', 'i', 'i', 'none')
def topk(g, self, k, dim, largest, sorted, out=None):
return sym_help._topk_helper(g, self, k, dim, largest=largest, sorted=sorted, out=out) |
class UniqueAllResult(NamedTuple):
values: ArrayLike
indices: ArrayLike
inverse_indices: ArrayLike
counts: ArrayLike |
def code_eval(gold: Tuple[(str, Optional[Dict])], pred: str) -> float:
assert (gold[1] is not None)
return float(code_metrics_helper.check_correctness(gold[1], pred, 3.0)['passed']) |
def context(msg: str) -> Iterator[None]:
try:
(yield)
except Exception as e:
msg = textwrap.indent(msg, ' ')
msg = (f'''{e.args[0]}
{msg}''' if e.args else msg)
e.args = ((msg,) + e.args[1:])
raise |
class NERTransformer(BaseTransformer):
mode = 'token-classification'
def __init__(self, hparams):
if (type(hparams) == dict):
hparams = Namespace(**hparams)
module = import_module('tasks')
try:
token_classification_task_clazz = getattr(module, hparams.task_type)
... |
def compute_chunk_sizes(M, N, target_chunk_size):
nChunks_col = 1
nChunks_row = 1
rowChunk = int(np.ceil((M / nChunks_row)))
colChunk = int(np.ceil((N / nChunks_col)))
chunk_size = (((rowChunk * colChunk) * 8) * 1e-06)
while (chunk_size >= target_chunk_size):
if (rowChunk > colChunk):
... |
def agent(config: Config):
ai_name = 'Test AI'
memory = MagicMock()
next_action_count = 0
command_registry = MagicMock()
ai_config = AIConfig(ai_name=ai_name)
system_prompt = 'System prompt'
triggering_prompt = 'Triggering prompt'
workspace_directory = 'workspace_directory'
agent = A... |
def reorder_index(batch_indices, world_size):
mini_batchsize = (len(batch_indices) // world_size)
reorder_indices = []
for i in range(0, mini_batchsize):
for j in range(0, world_size):
reorder_indices.append(batch_indices[(i + (j * mini_batchsize))])
return reorder_indices |
class BytePairEncoding(Vocabulary):
def __init__(self, vocab_file, bpe_file, seq_postfix=None, **kwargs):
super(BytePairEncoding, self).__init__(vocab_file=vocab_file, seq_postfix=seq_postfix, **kwargs)
from returnn.util.bpe import StandardBytePairEncoder
self.bpe = StandardBytePairEncoder(b... |
class MD_G_multi(nn.Module):
def __init__(self, output_dim, c_dim=3, nz=8):
super(MD_G_multi, self).__init__()
self.nz = nz
ini_tch = 256
tch_add = ini_tch
tch = ini_tch
self.tch_add = tch_add
self.dec1 = MisINSResBlock(tch, tch_add)
self.dec2 = MisINS... |
class FunctionalBatchNorm(common.BaseSubstitution):
def __init__(self):
bn_node = NodeOperationMatcher(F.batch_norm)
super().__init__(matcher_instance=bn_node)
def get_attributes_from_inputs(self, graph: Graph, node: BaseNode) -> dict:
input_nodes = graph.get_prev_nodes(node, sink_index_... |
class Agent(object):
def __init__(self):
self.reset()
def action(self, state):
return NotImplementedError()
def actions(self, states, agent_indices):
return NotImplementedError()
def a_probs_from_action(action):
action_idx = Action.ACTION_TO_INDEX[action]
return n... |
def test_nd_array_initialize():
shape = [2, 3, 4]
a = nn.NdArray(shape)
ref_a = np.zeros(shape, dtype=np.float32)
assert (a.data == ref_a).all() |
def get_batch(iterable, n=1):
l = len(iterable)
for ndx in range(0, l, n):
(yield iterable[ndx:min((ndx + n), l)]) |
def parse():
parser = argparse.ArgumentParser()
parser.add_argument('--save-as', metavar='FOLDER_NAME', required=True)
args = parser.parse_args()
return args |
class TreeWalker(base.TreeWalker):
def __iter__(self):
previous = None
for event in self.tree:
if (previous is not None):
for token in self.tokens(previous, event):
(yield token)
previous = event
if (previous is not None):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.