code stringlengths 101 5.91M |
|---|
class ProxyException(Exception):
def __init__(self, tp_name, args):
self.tp_name = tp_name
self.args = args
def __repr__(self):
return ('%s%r' % (self.tp_name, self.args)) |
def shapes_equal(this: TensorType, that: TensorType) -> TensorType:
return ((tf.rank(this) == tf.rank(that)) and tf.reduce_all((tf.shape(this) == tf.shape(that)))) |
class BaseModel(object):
def __init__(self, hparams, mode, iterator, source_vocab_table, target_vocab_table, reverse_target_vocab_table=None, scope=None, extra_args=None):
assert isinstance(iterator, iterator_utils.BatchedInput)
self.iterator = iterator
self.mode = mode
self.src_voca... |
def write_cv_desc_df():
ls = glob.glob
records = []
for f in ls('*.json'):
d = {}
with open(f, 'rb') as fd:
r = json.load(fd)
d['name'] = f
d['alg'] = alg(f)
d['seed'] = r['config']['seed']
d['agg'] = r['config']['step_every']
... |
def plt_props():
plt.rcParams['font.size'] = 12
plt.rcParams['axes.labelsize'] = 12
plt.rcParams['font.family'] = 'serif'
plt.rcParams['font.style'] = 'normal'
plt.rcParams['font.variant'] = 'normal'
plt.rcParams['xtick.labelsize'] = 12
plt.rcParams['ytick.labelsize'] = 12
plt.rcParams['... |
def write_version_py():
content = "# GENERATED VERSION FILE\n# TIME: {}\n__version__ = '{}'\nshort_version = '{}'\nversion_info = ({})\n"
sha = get_hash()
with open('VERSION', 'r') as f:
SHORT_VERSION = f.read().strip()
VERSION_INFO = ', '.join([(x if x.isdigit() else f'"{x}"') for x in SHORT_VE... |
class ShareSubprocVecEnv(ShareVecEnv):
def __init__(self, env_fns, spaces=None):
self.waiting = False
self.closed = False
nenvs = len(env_fns)
(self.remotes, self.work_remotes) = zip(*[Pipe() for _ in range(nenvs)])
self.ps = [Process(target=shareworker, args=(work_remote, re... |
.skipif((not m.has_optional), reason='no <optional>')
def test_move_and_copy_load_optional():
cstats = m.move_and_copy_cstats()
(c_m, c_mc, c_c) = (cstats['MoveOnlyInt'], cstats['MoveOrCopyInt'], cstats['CopyOnlyInt'])
assert (m.move_optional(10) == 10)
assert (m.move_or_copy_optional(11) == 11)
ass... |
class SampleCountMetricPrinter(EventWriter):
def __init__(self):
self.logger = logging.getLogger(__name__)
def write(self):
storage = get_event_storage()
batch_stats_strs = []
for (key, buf) in storage.histories().items():
if key.startswith('batch/'):
... |
class GEGLU(nn.Module):
def forward(self, x: torch.Tensor) -> torch.Tensor:
assert ((x.shape[(- 1)] % 2) == 0)
(a, b) = x.chunk(2, dim=(- 1))
return (a * F.gelu(b)) |
_if_32bit
.parametrize('X_train, y_train, X_test', [[X, Y, T], [X2, Y2, T2], [X_blobs[:80], y_blobs[:80], X_blobs[80:]], [iris.data, iris.target, iris.data]])
.parametrize('kernel', ['linear', 'poly', 'rbf', 'sigmoid'])
.parametrize('sparse_container', (CSR_CONTAINERS + LIL_CONTAINERS))
def test_svc(X_train, y_train, X... |
.lower_builtin('begin_list', ArrayBuilderType)
def lower_beginlist(context, builder, sig, args):
(arraybuildertype,) = sig.args
(arraybuilderval,) = args
proxyin = context.make_helper(builder, arraybuildertype, arraybuilderval)
call(context, builder, libawkward.ArrayBuilder_beginlist, (proxyin.rawptr,))... |
_module()
class ADE20KDataset(CustomDataset):
CLASSES = ('wall', 'building', 'sky', 'floor', 'tree', 'ceiling', 'road', 'bed ', 'windowpane', 'grass', 'cabinet', 'sidewalk', 'person', 'earth', 'door', 'table', 'mountain', 'plant', 'curtain', 'chair', 'car', 'water', 'painting', 'sofa', 'shelf', 'house', 'sea', 'mir... |
class HybridRecommender(BaseRecommender, ABC):
def fit(self, log: SparkDataFrame, user_features: Optional[SparkDataFrame]=None, item_features: Optional[SparkDataFrame]=None) -> None:
self._fit_wrap(log=log, user_features=user_features, item_features=item_features)
def predict(self, log: SparkDataFrame, ... |
def get_detection_model(num_classes):
model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)
in_features = model.roi_heads.box_predictor.cls_score.in_features
model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes)
model.roi_heads.nms_thresh = 0.3
return mo... |
class VenmoWithdrawMoney(VirtualFunctionTool):
name = 'VenmoWithdrawMoney'
summary = "Withdraw money from the user's Venmo balance to a linked bank account."
parameters: List[ArgParameter] = [{'name': 'amount', 'type': 'number', 'description': 'The amount of money to withdraw, must be positive.', 'required'... |
class ASTResolver():
def resolve_to(node, wanted, scope):
if isinstance(node, ast.Name):
return (scope.get(node.id) is wanted)
if (not isinstance(node, ast.Attribute)):
return False
v = node.value
chain = [node.attr]
while isinstance(v, ast.Attribute):... |
_function_dispatch(_broadcast_arrays_dispatcher, module='numpy')
def broadcast_arrays(*args, **kwargs):
subok = kwargs.pop('subok', False)
if kwargs:
raise TypeError('broadcast_arrays() got an unexpected keyword argument {!r}'.format(list(kwargs.keys())[0]))
args = [np.array(_m, copy=False, subok=su... |
class SimpleLasagneModel(object):
def __init__(self, input_vars, target_vars, l_out, loss, optimizer, learning_rate=0.001, id=None):
if (not isinstance(input_vars, Sequence)):
raise ValueError(('input_vars should be a sequence, instead got %s' % (input_vars,)))
if (not isinstance(target_... |
class MacdonaldPolynomials_generic(sfa.SymmetricFunctionAlgebra_generic):
def __init__(self, macdonald):
s = self.__class__.__name__[21:].capitalize()
sfa.SymmetricFunctionAlgebra_generic.__init__(self, macdonald._sym, basis_name=(('Macdonald ' + s) + macdonald._name_suffix), prefix=('Mcd' + s))
... |
class TwoHyperplaneClassifier(nn.Module):
def __init__(self, x_dim, y_dim, P1, P2, a1=None, a2=None, b1=None, b2=None, ksig=5):
super(TwoHyperplaneClassifier, self).__init__()
if (a1 is None):
self.a1 = Parameter(torch.matmul(torch.randn(1, int(x_dim)), torch.t(P1)))
else:
... |
class Conv3dBenchmark(op_bench.TorchBenchmarkBase):
def init(self, IC, OC, kernel, stride, N, D, H, W, device):
self.input = torch.rand(N, IC, D, H, W, device=device)
self.conv3d = nn.Conv3d(IC, OC, kernel, stride=stride).to(device=device)
self.set_module_name('Conv3d')
def forward(self)... |
def ttoi(tensor):
tensor = tensor.squeeze()
img = tensor.cpu().numpy()
img = img.transpose(1, 2, 0)
return img |
class ProgressBarTransferHook(TransferHook):
def on_dispatch_start(self):
return
def __init__(self, dest_region_tags: List[str]):
self.spinner = Progress(SpinnerColumn(), TextColumn('Dispatching chunks...{task.description}'), BarColumn(), DownloadColumn(binary_units=True), transient=True)
... |
def test_reflection_coeffs():
random = np.random.RandomState(1234)
y_d = random.randn(10)
y_z = (random.randn(10) + 1j)
reflection_coeffs_d = [1]
reflection_coeffs_z = [1]
for i in range(2, 10):
reflection_coeffs_d.append(solve_toeplitz(y_d[:(i - 1)], b=y_d[1:i])[(- 1)])
reflecti... |
def BIBD_141_6_1():
from sage.sets.recursively_enumerated_set import RecursivelyEnumeratedSet
from .incidence_structures import IncidenceStructure
a = 'a'
inf = (None, None)
bibd = [((0, 0), (16, 0), (24, 0), (24, 1), (15, 2), (25, 2)), ((0, 0), (3, 0), (26, 0), (13, 1), (33, 1), (34, a)), ((0, 0), ... |
def conv_input_length(output_length, filter_size, padding, stride):
if (output_length is None):
return None
assert (padding in {'same', 'valid', 'full'})
if (padding == 'same'):
pad = (filter_size // 2)
elif (padding == 'valid'):
pad = 0
elif (padding == 'full'):
pad ... |
class EisensteinExtensionFieldCappedRelative(EisensteinExtensionGeneric, pAdicCappedRelativeFieldGeneric):
def __init__(self, exact_modulus, poly, prec, print_mode, shift_seed, names, implementation='NTL'):
unram_prec = (((prec + poly.degree()) - 1) // poly.degree())
ntl_poly = ntl_ZZ_pX([a.lift() f... |
def train_one_epoch(model: torch.nn.Module, criterion: torch.nn.Module, data_loader: Iterable, optimizer: torch.optim.Optimizer, device: torch.device, epoch: int, loss_scaler, max_norm: float=0, model_ema: Optional[ModelEma]=None, mixup_fn: Optional[Mixup]=None, log_writer=None, start_steps=None, lr_schedule_values=Non... |
def test_block8(module, name):
test_conv2d(module.branch0, (name + '/Branch_0/Conv2d_1x1'))
test_conv2d(module.branch1[0], (name + '/Branch_1/Conv2d_0a_1x1'))
test_conv2d(module.branch1[1], (name + '/Branch_1/Conv2d_0b_1x3'))
test_conv2d(module.branch1[2], (name + '/Branch_1/Conv2d_0c_3x1'))
test_co... |
class DepthConcat(Concat):
def windowNarrow(self, output, currentOutput, offset):
outputWindow = output.narrow(self.dimension, offset, currentOutput.size(self.dimension))
for dim in range(len(self.outputSize)):
currentSize = currentOutput.size(dim)
if ((dim != self.dimension)... |
class Module():
def __init__(self):
self.lrp_var = None
self.lrp_param = 1.0
def backward(self, DY):
return DY
def train(self, X, Y, *args, **kwargs):
def forward(self, X, lrp_aware=False):
return X
def update(self, lrate):
pass
def clean(self):
pa... |
def _jit_compile(name, sources, extra_cflags, extra_cuda_cflags, extra_ldflags, extra_include_paths, build_directory: str, verbose: bool, with_cuda: Optional[bool], is_python_module, keep_intermediates=True) -> None:
if (with_cuda is None):
with_cuda = any(map(_is_cuda_file, sources))
with_cudnn = any([... |
def send_to_servers(binary_image, url_face: str, url_age_gender: str) -> None:
data = {'image': binary_image}
logging.info(f'image loaded!')
logging.debug(f'sending image to server...')
data = jsonpickle.encode(data)
response = requests.post(url_face, json=data)
logging.info(f'got {response} fro... |
def make_session(config=None, num_cpu=None, make_default=False, graph=None):
if (num_cpu is None):
num_cpu = int(os.getenv('RCALL_NUM_CPU', multiprocessing.cpu_count()))
if (config is None):
config = tf.ConfigProto(allow_soft_placement=True, inter_op_parallelism_threads=num_cpu, intra_op_paralle... |
class TestSum(test_util.TestCase):
def setUp(self):
self.test_configs = [((1, 2, 3, 4), True), ((1, 2, 3, 4), False)]
def testSum(self):
for (input_size, in_place) in self.test_configs:
op = core.CreateOperator('Sum', ['X1', 'X2'], [('Y' if (not in_place) else 'X1')])
X1 ... |
def get_include_dir(module):
include_dir = osp.join(*module.split('.'), 'include')
if osp.exists(include_dir):
return [osp.abspath(include_dir)]
else:
return [] |
class WILDSAmazonProcessor(DataProcessor):
def get_train_examples(self, data_dir):
return self._create_examples(self._read_tsv(os.path.join(data_dir, 'amazon.train.tsv'), quotechar='"'), 'train')
def get_dev_examples(self, data_dir):
return self._create_examples(self._read_tsv(os.path.join(data_... |
class Waypoint():
def __init__(self, location, lane_node, lane_position):
self.location = (np.array(location) if (not isinstance(location, np.ndarray)) else location)
self.lane_node = lane_node
self.lane_position = lane_position
def next(self, step_size):
waypoint_next = []
... |
def load_pil(path, standardize=False):
if path.endswith('.png'):
return load_png(path, standardize=standardize)
elif (path.endswith('.jpeg') or path.endswith('.jpg')):
return load_jpeg(path, standardize=standardize)
return load_tiff(path, standardize=standardize) |
def test_hdbscan_no_clusters():
(labels, p, persist, ctree, ltree, mtree) = hdbscan(X, min_cluster_size=(len(X) + 1))
n_clusters_1 = (len(set(labels)) - int(((- 1) in labels)))
assert (n_clusters_1 == 0)
labels = HDBSCAN(min_cluster_size=(len(X) + 1)).fit(X).labels_
n_clusters_2 = (len(set(labels)) ... |
class Data2VecAudioForXVector(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
_builder('objaverse_mm_caption_instruct')
class ObjaverseCaptionInstructBuilder(ObjaverseCaptionBuilder):
train_dataset_cls = ObjaverseCaptionInstructDataset
eval_dataset_cls = ObjaverseCaptionEvalDataset
DATASET_CONFIG_DICT = {'default': 'configs/datasets/objaverse/defaults_mm_cap_instruct.yaml'} |
class AlignedModule(nn.Module):
def __init__(self, c1, c2, k=3):
super().__init__()
self.down_h = nn.Conv2d(c1, c2, 1, bias=False)
self.down_l = nn.Conv2d(c1, c2, 1, bias=False)
self.flow_make = nn.Conv2d((c2 * 2), 2, k, 1, 1, bias=False)
def forward(self, low_feature: Tensor, hi... |
class Identity(nn.Module):
def __init__(self, *args, **kwargs):
super().__init__()
def forward(self, input):
return input |
def register_Ns3PyVizLastPacketsSample_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::PyViz::LastPacketsSample const &', 'arg0')])
cls.add_instance_attribute('lastDroppedPackets', 'std::vector< ns3::PyViz::PacketSample >', is_const=False)
cls.add_instance_attribute('... |
_config
def task_finetune_irtr_msvd():
exp_name = 'finetune_irtr_msvd'
datasets = ['msvd']
loss_names = _loss_names({'ind_itc': 1, 'itm': 0.5, 'irtr': 1})
batch_size = 256
max_epoch = 50
max_steps = None
warmup_steps = 0.1
get_recall_metric = False
get_itc_recall_metric = False
g... |
class CustomAnomalyDataset(CustomDataset, TSADBaseDataset):
def __init__(self, rootdir, test_frac=0.5, assume_no_anomaly=False, time_col=None, time_unit='s', data_cols=None, index_cols=None):
self.assume_no_anomaly = assume_no_anomaly
super().__init__(rootdir=rootdir, test_frac=test_frac, time_col=t... |
class DataIterator():
def __init__(self, mode, data, batch_size=128, neg_sample=1, all_items=None, items_usr_clicked=None, shuffle=True):
self.mode = mode
self.data = data
self.datasize = data.shape[0]
self.neg_count = neg_sample
self.batch_size = batch_size
self.item... |
def get_collaborator(plan, name, model, aggregator):
plan = copy(plan)
return plan.get_collaborator(name, task_runner=model, client=aggregator) |
class UpstreamExpert(UpstreamBase):
def __init__(self, ckpt, **kwargs):
super().__init__(**kwargs)
locArgs = get_default_cpc_config()
checkpoint = torch.load(ckpt, map_location='cpu')
loadArgs(locArgs, argparse.Namespace(**checkpoint['config']))
encoderNet = getEncoder(locArg... |
def prepare_timit(data_folder, save_json_train, save_json_valid, save_json_test, phn_set=39, uppercase=False, skip_prep=False):
if skip_prep:
return
(dev_spk, test_spk) = _get_speaker()
avoid_sentences = ['sa1', 'sa2']
extension = ['.wav']
if uppercase:
avoid_sentences = [item.upper(... |
def get_args():
parser = argparse.ArgumentParser()
home = os.path.expanduser('~')
data_dir = os.path.join('data', 'semeval')
eval_dir = os.path.join('out/semeval', 'basic-class')
store_dir = os.path.join('semeval', 'store')
parser.add_argument('-d', '--data_dir', default=data_dir)
parser.add... |
class RobertaTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
tokenizer_class = RobertaTokenizer
def setUp(self):
super(RobertaTokenizationTest, self).setUp()
vocab = ['l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'G', 'Gl', 'Gn', 'Glo', 'Glow', 'er', 'Glowest', 'Gnewer', 'Gwider',... |
class TruncationOpManagerInference():
def __load_quantizer__(self, qtype, qparams):
qtype_name = qtype.rstrip('')
quant_params = (qparams[qtype_name] if (qtype_name in qparams) else {})
quantizer = qtypes.__dict__[(qtype_name + '_quantizer')](qtype, quant_params)
return (quantizer, q... |
def load_checkpoint(args, trainer, epoch_itr):
os.makedirs(args.save_dir, exist_ok=True)
checkpoint_path = os.path.join(args.save_dir, args.restore_file)
if os.path.isfile(checkpoint_path):
extra_state = trainer.load_checkpoint(checkpoint_path, args.reset_optimizer, args.reset_lr_scheduler, eval(arg... |
def get_backbone(backbone_arch='resnet50', backbone_config={}):
if ('resnet' in backbone_arch.lower()):
return backbones.ResNet(backbone_arch, **backbone_config)
elif ('dinov2' in backbone_arch.lower()):
return backbones.DINOv2(model_name=backbone_arch, **backbone_config) |
def test_ner():
from pycorrector.utils.tokenizer import segment
from pycorrector import Corrector
c = Corrector()
c.check_corrector_initialized()
c.check_detector_initialized()
error_sentences = ['', ',', ',', '', '', '', '', '', '', '', ',,', '', ',,,,']
for line in error_sentences:
... |
class MySQL(Estimator):
def __init__(self, table, bucket, seed):
super(MySQL, self).__init__(table=table, version=table.version, bucket=bucket, seed=seed)
self.conn = mysql.connector.connect(user=MYSQL_USER, password=MYSQL_PSWD, host=MYSQL_HOST, port=MYSQL_PORT, database=MYSQL_DB)
self.conn.... |
def build_ref_doc(args):
doc = args[0]
lang = args[1]
format = args[2]
kwds = args[3]
args = args[4:]
if (format == 'inventory'):
kwds['use_multidoc_inventory'] = False
getattr(ReferenceSubBuilder(doc, lang), format)(*args, **kwds) |
def evaluate(args, model, tokenizer, mode, prefix=''):
eval_task = args.task_name
eval_output_dir = args.output_dir
eval_dataset = load_and_cache_examples(args, eval_task, tokenizer, mode)
if ((not os.path.exists(eval_output_dir)) and (args.local_rank in [(- 1), 0])):
os.makedirs(eval_output_dir... |
def res_block(x_in):
x = Conv2D(x_in.shape[(- 1)], 3, padding='same', activation='relu')(x_in)
x = Conv2D(x_in.shape[(- 1)], 3, padding='same')(x)
x = Add()([x_in, x])
return x |
class TestPalmyraWindowService():
TEST_PROMPT_LENGTH: int = 51
TEST_TOKEN_IDS: List[int] = [464, 3337, 329, 4992, 319, 5693, 32329, 357, 9419, 23264, 8, 318, 281, 987, 40625, 10219, 4642, 503, 286, 262, 13863, 5136, 329, 5524, 12, 19085, 1068, 35941, 9345, 357, 7801, 40, 8, 326, 12031, 284, 787, 7531, 14901, 28... |
class LinearActivation(nn.Module):
def __init__(self, input_dim: int, output_dim: int, dropout_prob: Optional[float]=None, k_lipschitz: Optional[float]=None, activation: nn.Module=nn.ReLU(), bias: bool=True):
super().__init__()
self.dropout = nn.Identity()
if (dropout_prob is not None):
... |
.parametrize('value, expected_lines', [pytest.param(False, OrderedSet([21, 24])), pytest.param(True, OrderedSet([21, 22]))])
def test_tracking_covered_statements_bool_predicate(simple_module, value, expected_lines):
tracer = ExecutionTracer()
adapter = LineCoverageInstrumentation(tracer)
transformer = Instr... |
def get_extensions():
Extension = CppExtension
define_macros = []
libraries = []
extra_compile_args = {'cxx': []}
extra_link_args = []
info = parallel_info()
if (('parallel backend: OpenMP' in info) and ('OpenMP not found' not in info)):
extra_compile_args['cxx'] += ['-DAT_PARALLEL_O... |
def add_CombinerServicer_to_server(servicer, server):
rpc_method_handlers = {'ModelUpdateRequestStream': grpc.unary_stream_rpc_method_handler(servicer.ModelUpdateRequestStream, request_deserializer=fedn__pb2.ClientAvailableMessage.FromString, response_serializer=fedn__pb2.ModelUpdateRequest.SerializeToString), 'Mod... |
def mutually_orthogonal_latin_squares(k, n, partitions=False, check=True):
from sage.combinat.designs.orthogonal_arrays import orthogonal_array
from sage.matrix.constructor import Matrix
from .database import MOLS_constructions
if (k is None):
raise TypeError('k must be a positive integer')
... |
class BlockGroup(nn.Module):
num_channels: int = None
num_blocks: int = None
strides: int = None
def setup(self):
assert (self.num_blocks > 0)
self.blocks = ([Block(num_channels=self.num_channels, strides=self.strides)] + [Block(num_channels=self.num_channels, strides=1) for _ in range((... |
class RandomScaledBreakoutWorld(BreakoutWorld):
scale_range_start = 0.95
scale_range_end = 1.0
def reset_world(self):
super(RandomScaledBreakoutWorld, self).reset_world()
self.scale = self.np_random.uniform(self.scale_range_start, self.scale_range_end)
def parameters(self):
param... |
def main():
parser = argparse.ArgumentParser(description='Read discourse corpora (.dis, .rs3, .lisp(thiago)) and output desired files (discourse mrg files and edu files).')
parser.add_argument('--treebank', default='./DataSets/RST/RST_multilingual/gum/rst/rstweb', dest='treebank', action='st... |
def ground_truth(N, seq):
table = np.zeros((N, N), np.int32)
for i in range((N - 1), (- 1), (- 1)):
for j in range((i + 1), N):
if ((j - 1) >= 0):
table[(i, j)] = max(table[(i, j)], table[(i, (j - 1))])
if ((i + 1) < N):
table[(i, j)] = max(table[(... |
class Seq2Nugget(object):
def __init__(self, train_config, detection_config, boundary_config):
self.initialize(train_config, detection_config, boundary_config)
def initialize(self, train_config, detection_config, boundary_config):
for key in train_config:
self.__dict__[key] = train_c... |
def test_sorting(state: Dict) -> bool:
try:
correct_list = sorted(string_to_list(state['original']))
sorted_list = string_to_list(state['current'])
return (sorted_list == correct_list)
except:
return False |
class StringDeletion():
def __init__(self, old_token_idx, token_pos, tokenizer):
self.old_token_idx = int(old_token_idx)
self.old_token = tokenizer.decode(self.old_token_idx)
self.token_pos = int(token_pos)
def __str__(self):
prefix = f'{self.token_pos}{self.old_token_idx}-{self.... |
class BaseDataType(ABC):
def signed(self):
return (self.min() < 0)
def __eq__(self, other):
if isinstance(other, BaseDataType):
return (self.get_canonical_name() == other.get_canonical_name())
elif isinstance(other, str):
return (self.get_canonical_name() == other... |
def drop_blocks(drop_prob=0.0):
return [None, None, (partial(DropBlock2d, drop_prob=drop_prob, block_size=5, gamma_scale=0.25) if drop_prob else None), (partial(DropBlock2d, drop_prob=drop_prob, block_size=3, gamma_scale=1.0) if drop_prob else None)] |
class TestGroupedBatchSampler(unittest.TestCase):
def test_respect_order_simple(self):
drop_uneven = False
dataset = [i for i in range(40)]
group_ids = [(i // 10) for i in dataset]
sampler = SequentialSampler(dataset)
for batch_size in [1, 3, 5, 6]:
batch_sampler ... |
class SequenceFeatureExtractor(FeatureExtractionMixin):
def __init__(self, feature_size: int, sampling_rate: int, padding_value: float, **kwargs):
self.feature_size = feature_size
self.sampling_rate = sampling_rate
self.padding_value = padding_value
self.padding_side = kwargs.pop('pa... |
def generate_exp_directory(cfg, exp_name=None, expid=None, run_name=None, additional_id=None):
if (run_name is None):
if (expid is None):
expid = (time.strftime('%Y%m%d-%H%M%S-') + str(shortuuid.uuid()))
if (additional_id is not None):
expid += ('-' + str(additional_id))
... |
class TestCNN(TfGraphTestCase):
def setup_method(self):
super().setup_method()
self.batch_size = 5
self.input_width = 10
self.input_height = 10
self.obs_input = np.ones((self.batch_size, self.input_width, self.input_height, 3))
input_shape = self.obs_input.shape[1:]
... |
def test_arrow_coverage100():
a = ak.operations.from_iter([True, True, False, False, True, False, True, False]).layout
assert (a.to_arrow().to_pylist() == to_list(a))
a = ak.contents.ListOffsetArray(ak.index.Index32(np.array([0, 5, 10], 'i4')), ak.contents.NumpyArray(np.frombuffer(b'hellothere', 'u1'), para... |
def clip(x, min_value, max_value):
if ((max_value is not None) and (max_value < min_value)):
max_value = min_value
min_value = _to_tensor(min_value, x.dtype.base_dtype)
max_value = _to_tensor(max_value, x.dtype.base_dtype)
return tf.clip_by_value(x, min_value, max_value) |
class SqueezeExcite1d(nn.Module):
def __init__(self, channels, reduction=16):
super().__init__()
channels_reduced = (channels // reduction)
self.w1 = torch.nn.Parameter(torch.randn(channels_reduced, channels).unsqueeze(0))
self.w2 = torch.nn.Parameter(torch.randn(channels, channels_r... |
class HighResolutionNet(nn.Module):
def __init__(self, cfg, bn_type, bn_momentum, **kwargs):
self.inplanes = 64
self.drop_path_rate = cfg['DROP_PATH_RATE']
super(HighResolutionNet, self).__init__()
Norm = norm_dict[cfg.NORM]
Activation = activation_dict[cfg.ACTIVATION]
... |
def evaluate_lfw(distances, labels, num_folds=10, far_target=0.001):
thresholds_roc = np.arange(0, 4, 0.01)
(true_positive_rate, false_positive_rate, precision, recall, accuracy, best_distances) = calculate_roc_values(thresholds=thresholds_roc, distances=distances, labels=labels, num_folds=num_folds)
roc_au... |
.parametrize('ti_dtype', [ti.f32, ti.f64])
_utils.test(arch=[ti.cpu, ti.cuda, ti.vulkan], exclude=[vk_on_mac])
def test_matrixfree_cg(ti_dtype):
GRID = 32
Ax = ti.field(dtype=ti_dtype, shape=(GRID, GRID))
x = ti.field(dtype=ti_dtype, shape=(GRID, GRID))
b = ti.field(dtype=ti_dtype, shape=(GRID, GRID))
... |
def test_distributed(test_module, test_directory, options):
mpi_available = (subprocess.call('command -v mpiexec', shell=True) == 0)
if (options.verbose and (not mpi_available)):
print_to_stderr('MPI not available -- MPI backend tests will be skipped')
config = DISTRIBUTED_TESTS_CONFIG
for (back... |
def run_azimint_naive(device_type: dace.dtypes.DeviceType):
(N, npt) = (40000, 100)
(data, radius) = initialize(N)
if (device_type in {dace.dtypes.DeviceType.CPU, dace.dtypes.DeviceType.GPU}):
sdfg = dace_azimint_naive.to_sdfg()
sdfg = auto_optimize(sdfg, device_type)
val = sdfg(data... |
def set_logger_dir(dirname, action=None, prefix=''):
dirname = os.path.normpath(dirname)
global LOG_DIR, _FILE_HANDLER
if _FILE_HANDLER:
_logger.removeHandler(_FILE_HANDLER)
del _FILE_HANDLER
def dir_nonempty(dirname):
return (osp.isdir(dirname) and len([x for x in os.listdir(dir... |
def _mul(input, *args):
x = raw__sub__(input, *args)
if (not NET_INITTED):
return x
layer_name = log.add_layer(name='mul')
top_blobs = log.add_blobs([x], name='mul_blob')
layer = caffe_net.Layer_param(name=layer_name, type='Eltwise', bottom=[log.blobs(input), log.blobs(args[0])], top=top_blo... |
def get_device():
is_device_available = {'cuda': torch.cuda.is_available(), 'mlu': is_mlu_available()}
device_list = [k for (k, v) in is_device_available.items() if v]
return (device_list[0] if (len(device_list) == 1) else 'cpu') |
_REGISTRY.register()
class VisualClassify(nn.Module):
def __init__(self, cfg):
super(VisualClassify, self).__init__()
self.cfg = cfg
self.visual_conv = MODEL_REGISTRY.get(cfg.VIS.MODEL_NAME)(cfg)
init_weights(self, cfg.MODEL.FC_INIT_STD, cfg.MODEL.ZERO_INIT_FINAL_BN)
def forward(... |
def hierarchical_cnn_res_gate(rep_tensor, rep_mask, n_gram=5, layer_num=5, hn=None, scope=None, is_train=None, keep_prob=1.0, wd=0.0):
if ((n_gram % 2) == 1):
padding_front = padding_back = int(((n_gram - 1) / 2))
else:
padding_front = ((n_gram - 1) // 2)
padding_back = (padding_front + ... |
def main():
logger.info('Parsing Spec...')
spec = S.parse(toy_spec_str)
logger.info('Parsing succeeded')
logger.info('Building sample program...')
prog = D.Builder(spec).from_sexp_string(toy_dsl_sexp)
logger.info('Build program = {}'.format(prog))
interpreter = ToyInterpreter()
logger.in... |
def get_patient_list(min_patient, cad_prescription_taken_by_patient):
patients_list = set()
for (drug, patients) in cad_prescription_taken_by_patient.items():
if (len(patients) >= min_patient):
for patient in patients:
patients_list.add(patient)
return patients_list |
class ExampleModel(nn.Module):
def __init__(self):
super().__init__()
self.conv = nn.Linear(1, 1)
self.test_cfg = None
def forward(self, imgs, rescale=False, return_loss=False):
return imgs
def train_step(self, data_batch, optimizer, **kwargs):
outputs = {'loss': 0.5,... |
def test_Numpy_from_buffer():
def f5(debug=True):
growablebuffer = ak.numba.GrowableBuffer(np.float64)
growablebuffer.append(66.6)
growablebuffer.append(77.7)
return growablebuffer
out = f5()
assert (out.snapshot().tolist() == [66.6, 77.7])
def f6():
growablebuffe... |
class BaseModel(torch.nn.Module):
def load(self, path):
parameters = torch.load(path, map_location=torch.device('cpu'))
if ('optimizer' in parameters):
parameters = parameters['model']
self.load_state_dict(parameters) |
def get_parameter_widgets(param_dict):
param_names = []
widget_list = []
test_related = []
for key in param_dict.keys():
if (key == 'output_path'):
widget_list.append(wg.Text(description='Output Path:', value=param_dict[key], style=style))
param_names.append(('--' + key))... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.