code stringlengths 101 5.91M |
|---|
.gpu
def test_gpu_access_on_host_tasklet():
def tester(a: (dace.float64[20] dace.StorageType.GPU_Global)):
for i in (dace.map[0:20] dace.ScheduleType.CPU_Multicore):
a[i] = 1
with pytest.raises(InvalidSDFGEdgeError):
tester.to_sdfg(validate=True) |
def get_deepfashion_img_class_name(filename, mode):
img_class_name = deepfashion_name_parse(filename, mode)
return img_class_name |
def test_pickle_version_no_warning_is_issued_with_non_sklearn_estimator():
iris = datasets.load_iris()
tree = TreeNoVersion().fit(iris.data, iris.target)
tree_pickle_noversion = pickle.dumps(tree)
try:
module_backup = TreeNoVersion.__module__
TreeNoVersion.__module__ = 'notsklearn'
... |
class EvalLMConfig(FairseqDataclass):
output_word_probs: bool = field(default=False, metadata={'help': 'if set, outputs words and their predicted log probabilities to standard output'})
output_word_stats: bool = field(default=False, metadata={'help': 'if set, outputs word statistics such as word count, average ... |
def dma_gather_base(context, reg: DMA_gather_reg):
lane_mask = ((reg.localmem_mask_h32 * (2 ** 32)) + reg.localmem_mask_l32)
(c, h, w) = (reg[f'src_{d}size'] for d in 'chw')
d_h = reg.dst_hsize
if reg.nchw_copy:
d_h = h
stride = (((c * h) * w), (h * w), w, 1)
opd0 = dict(address=dma_addr... |
def evaluate_grasp() -> None:
device = ('cuda' if torch.cuda.is_available() else 'cpu')
(backbone, preprocess) = load('v-cond', device=device)
(output_resolution, upsample_stages) = (80, 4)
map_extractor_fn = instantiate_extractor(backbone, n_latents=int(((output_resolution ** 2) / (4 ** upsample_stages... |
class RunExpander(ABC):
name: str
def expand(self, run_spec: RunSpec) -> List[RunSpec]:
pass |
def test_init_with_env_updates(policy, envs):
task_sampler = EnvPoolSampler(envs)
envs = task_sampler.sample(N_TRAJ)
true_workers = WorkerFactory(seed=100, n_workers=N_TRAJ, max_path_length=MAX_PATH_LENGTH)
true_sampler = LocalSampler.from_worker_factory(true_workers, policy, envs)
vec_workers = Wor... |
def hack_trainer_type_to_gap_aware(args, stage_depth=None):
def hack():
args.trainer['type'] += '_gap_aware'
if hasattr(args, 'gap_aware'):
if (stage_depth is None):
is_zero_staleness_stage = (args.local_rank == (args.world_size - 1))
is_one_staleness_stage = (args.local_... |
def is_value_tok(t):
if t[0].isalpha():
return False
return (process_literal(t) != 'null') |
.parametrize('score', [AbsoluteConformityScore(), GammaConformityScore(), ResidualNormalisedScore()])
.parametrize('alpha', [[0.3], [0.5, 0.4]])
def test_intervals_shape_with_every_score(score: ConformityScore, alpha: Any) -> None:
mapie_reg = MapieRegressor(method='base', cv='split', conformity_score=score)
X ... |
def _get_lines(graph_parse, is_variable, a_key, b_key):
assert isinstance(graph_parse, GraphParse)
if graph_parse.line_graph.has_edge(a_key, b_key):
if is_variable:
line = graph_parse.line_graph[a_key][b_key]['variable']
else:
line = graph_parse.line_graph[a_key][b_key]['... |
class DebertaTokenizerFast(metaclass=DummyObject):
_backends = ['tokenizers']
def __init__(self, *args, **kwargs):
requires_backends(self, ['tokenizers']) |
class SGACellularBasis(CellularBasis):
def __init__(self, SGA):
CellularBasis.__init__(self, SGA, self._to_sga)
def _repr_(self):
return (self._name + ' basis of {}'.format(self._algebra))
_method
def one_basis(self):
la = _Partitions([self._algebra.n])
col = la.standard_... |
class iMAMLMetaLearner(GradBasedMetaLearner):
def __init__(self, model, optimizer=tf.keras.optimizers.Adam(learning_rate=0.001), lambda_reg=1.0, n_iters_optimizer=5, name='FOMAMLMetaLearner'):
self.model = model
self.optimizer = optimizer
self.lambda_reg = lambda_reg
self.n_iters_opt... |
class ConceptNetGenerationIteratorTrainer(base_train.AtomicGenerationIteratorTrainer):
def set_evaluator(self, opt, model, data_loader):
self.evaluator = evaluate.make_evaluator(opt, model, data_loader)
def set_generator(self, opt, model, data_loader):
self.generator = gen.make_generator(opt, mo... |
def p_list_maker(s):
pos = s.position()
s.next()
if (s.sy == ']'):
s.expect(']')
return ExprNodes.ListNode(pos, args=[])
expr = p_test_or_starred_expr(s)
if (s.sy in ('for', 'async')):
if expr.is_starred:
s.error('iterable unpacking cannot be used in comprehension... |
class FeatureHookNet(nn.ModuleDict):
def __init__(self, model, out_indices=(0, 1, 2, 3, 4), out_map=None, out_as_dict=False, no_rewrite=False, feature_concat=False, flatten_sequential=False, default_hook_type='forward'):
super(FeatureHookNet, self).__init__()
assert (not torch.jit.is_scripting())
... |
def _cos_n_atan(x, y, n):
assert n.is_integer
if (n < 0):
return _cos_n_atan(x, y, ((- 1) * n))
if (n == 0):
return 1
else:
r2 = ((x * x) + (y * y))
r = sqrt(r2)
return (((x * _cos_n_atan(x, y, (n - 1))) / r) - ((y * _sin_n_atan(x, y, (n - 1))) / r)) |
class TFWav2Vec2PreTrainedModel(metaclass=DummyObject):
_backends = ['tf']
def __init__(self, *args, **kwargs):
requires_backends(self, ['tf']) |
def get_file_handle(path_, r_w_a):
try:
fhand = open(path_, r_w_a)
except:
print('Cannot open file {}'.format(path_))
exit()
return fhand |
def densenet161(pretrained=False, **kwargs):
model = DenseNet(num_init_features=96, growth_rate=48, block_config=(6, 12, 36, 24), **kwargs)
if pretrained:
pattern = re.compile('^(.*denselayer\\d+\\.(?:norm|relu|conv))\\.((?:[12])\\.(?:weight|bias|running_mean|running_var))$')
state_dict = model_... |
class FantasizerModelStack(PredictJointModelStack, PredictYModelStack, ModelStack[FantasizerModelType]):
pass |
_test()
def test_reduce_sum_all_axis():
A = np.random.rand(4, 4).astype(np.float32)
B = np.random.rand(1).astype(np.float32)
sdfg = create_reduce_sdfg('lambda a,b: a+b', (0, 1), 'reduction_sum_all_axis', A, B, dace.float32)
from dace.libraries.standard import Reduce
Reduce.default_implementation = '... |
()
class IQNQFunctionFactory(QFunctionFactory):
n_quantiles: int = 64
n_greedy_quantiles: int = 32
embed_size: int = 64
def create_discrete(self, encoder: Encoder, hidden_size: int, action_size: int) -> Tuple[(DiscreteIQNQFunction, DiscreteIQNQFunctionForwarder)]:
q_func = DiscreteIQNQFunction(e... |
def explain_pickle_string(pickle, in_current_sage=False, default_assumptions=False, eval=False, preparse=True, pedantic=False):
sib = SageInputBuilder(preparse=preparse)
pe = PickleExplainer(sib, in_current_sage=in_current_sage, default_assumptions=default_assumptions, pedantic=pedantic)
v = pe.run_pickle(p... |
def sym_pp(W_list, funcs, var_names, threshold=0.01, n_double=0):
vars = []
for var in var_names:
if isinstance(var, str):
vars.append(sym.Symbol(var))
else:
vars.append(var)
expr = sym.Matrix(vars).T
W_list = np.asarray(W_list)
for W in W_list:
W = fi... |
class STN3d(nn.Module):
def __init__(self, n=4):
super(STN3d, self).__init__()
self.n = n
self.conv1 = torch.nn.Conv1d(n, 64, 1, bias=False)
self.conv2 = torch.nn.Conv1d(64, 128, 1, bias=False)
self.conv3 = torch.nn.Conv1d(128, 1024, 1, bias=False)
self.fc1 = nn.Linea... |
class VAEBaseline(nn.Module):
def __init__(self, latent_space_size=10):
super(VAEBaseline, self).__init__()
self.fc1 = nn.Linear(784, 400)
self.fc21 = nn.Linear(400, latent_space_size)
self.fc22 = nn.Linear(400, latent_space_size)
self.fc3 = nn.Linear(latent_space_size, 400)
... |
class TextPrint():
def __init__(self):
self.reset()
self.font = pygame.font.Font(None, 20)
def printf(self, screen, textString):
textBitmap = self.font.render(textString, True, BLACK)
screen.blit(textBitmap, [self.x, self.y])
self.y += self.line_height
def reset(self)... |
def get_available_detector_ids(detectors_path):
return [dir_name for dir_name in listdir(detectors_path) if isdir(join(detectors_path, dir_name))] |
def test_cast_tensor_type():
inputs = torch.rand(10)
if torch.cuda.is_available():
inputs = inputs.cuda()
with pytest.raises(AssertionError):
cast_tensor_type(inputs, src_type=None, dst_type=None)
out = cast_tensor_type(10.0, dst_type=torch.half)
assert ((out == 10.0) and isinstance(... |
def main():
parser = HfArgumentParser(ScriptArguments)
args = parser.parse_args_into_dataclasses()[0]
logger.info(f'Parse args: {args}')
(config_class, model_class, tokenizer_class) = MODEL_CLASSES[args.model_type]
if (args.model_type == 'bloom'):
args.use_fast_tokenizer = True
tokenizer... |
def LoadEdgeListStr(tspec, *args):
if (tspec == PUNGraph):
return LoadEdgeListStr_PUNGraph(*args)
if (tspec == PUndirNet):
return LoadEdgeListStr_PUndirNet(*args)
if (tspec == PDirNet):
return LoadEdgeListStr_PDirNet(*args)
if (tspec == PNGraph):
return LoadEdgeListStr_PN... |
def train(model, device, loader, loss_fun, optimizer):
model.train()
loss_accum = 0
for (step, batch) in enumerate(tqdm(loader, desc='Iteration')):
(x, y) = batch
y_pred = model(x.to(device))
if (y_pred.shape[1] == 1):
y_pred = y_pred.flatten()
loss = loss_fun(y_p... |
def skip_if_checkpoint_not_accessible(path: str):
def try_load_path(path):
try:
(fs, path_to_open) = _get_fs_and_plain_path(path)
fs.open(path_to_open, 'rb')
except Exception:
return False
else:
return True
return pytest.mark.skipif((not tr... |
.parametrize('forest_cls', FORESTS)
def test_predict_sparse(make_whas500, forest_cls):
seed = 42
whas500 = make_whas500(to_numeric=True)
(X, y) = (whas500.x, whas500.y)
X = np.random.RandomState(seed).binomial(n=5, p=0.1, size=X.shape)
(X_train, X_test, y_train, _) = train_test_split(X, y, random_st... |
def test_prune_sample(workspace_factory):
ws = workspace_factory()
sample = ws.samples[1]
with pytest.raises(pyhf.exceptions.InvalidWorkspaceOperation):
ws.prune(samples=sample)
new_ws = ws.prune(samples=[sample])
assert (sample not in new_ws.samples) |
class Plane3D(object):
def __init__(self, point=Point3D(0, 0, 0), normal=Vector3D(0, 0, 1)):
if (not isinstance(point, Point3D)):
raise NotImplementedError("Plane3D: invalid ``point'' argument")
if (not isinstance(normal, Vector3D)):
raise NotImplementedError("Plane3D: invali... |
class BitPreActivationBottleneckLayer(nn.Module):
def __init__(self, config, in_channels, out_channels=None, bottle_ratio=0.25, stride=1, dilation=1, first_dilation=None, groups=1, drop_path_rate=0.0, is_first_layer=False):
super().__init__()
first_dilation = (first_dilation or dilation)
out... |
def user_cache_dir(appname=None, appauthor=None, version=None, opinion=True):
if (system == 'win32'):
if (appauthor is None):
appauthor = appname
path = os.path.normpath(_get_win_folder('CSIDL_LOCAL_APPDATA'))
if appname:
if (appauthor is not False):
p... |
def find_next_example(example_id):
initial_example_id = example_id
example_id += 1
while (example_id != initial_example_id):
all_codes = get_example_topic_codes(example_id)
codes_found = sum([len(code_pr_infos) for (_, code_pr_infos) in all_codes])
if (codes_found > 0):
s... |
def g_path_regularize(fake_img, latents, mean_path_length, decay=0.01):
noise = (torch.randn_like(fake_img) / math.sqrt((fake_img.shape[2] * fake_img.shape[3])))
(grad,) = autograd.grad(outputs=(fake_img * noise).sum(), inputs=latents, create_graph=True)
path_lengths = torch.sqrt(grad.pow(2).sum(2).mean(1))... |
def test_pdf_integration_staterror(backend):
spec = {'channels': [{'name': 'firstchannel', 'samples': [{'name': 'mu', 'data': [10.0, 10.0], 'modifiers': [{'name': 'mu', 'type': 'normfactor', 'data': None}]}, {'name': 'bkg1', 'data': [50.0, 70.0], 'modifiers': [{'name': 'stat_firstchannel', 'type': 'staterror', 'dat... |
class cifar10(CIFAR10):
def __init__(self, root, classes=range(10), train=True, transform=None, target_transform=None, download=True):
super(cifar10, self).__init__(root, train=train, transform=transform, target_transform=target_transform, download=download)
np.random.seed(1993)
cls_list = [... |
def iod(det_x, det_y, gt_x, gt_y):
if (approx_area_of_intersection(det_x, det_y, gt_x, gt_y) > 1):
ymax = (np.maximum(np.max(det_y), np.max(gt_y)) + 1)
xmax = (np.maximum(np.max(det_x), np.max(gt_x)) + 1)
bin_mask = np.zeros((ymax, xmax))
det_bin_mask = np.zeros_like(bin_mask)
... |
class BigBirdTokenizerFast(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 = BigBirdTokenizer
model_input_names = ['input_ids', 'attention_mask'... |
class LlamaLoraKbitEngine(CausalLoraKbitEngine):
config_name: str = 'llama_lora_kbit_engine'
def __init__(self, weights_path: Optional[Union[(str, Path)]]=None):
model_name = 'decapoda-research/llama-7b-hf'
tokenizer = LlamaTokenizer.from_pretrained(model_name, add_bos_token=False)
token... |
def register_Ns3ObjectPtrContainerChecker_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::ObjectPtrContainerChecker const &', 'arg0')])
cls.add_method('GetItemTypeId', 'ns3::TypeId', [], is_pure_virtual=True, is_const=True, is_virtual=True)
return |
def rerank(args):
if (type(args.lenpen) is not list):
args.lenpen = [args.lenpen]
if (type(args.weight1) is not list):
args.weight1 = [args.weight1]
if (type(args.weight2) is not list):
args.weight2 = [args.weight2]
if (type(args.weight3) is not list):
args.weight3 = [arg... |
class DataCollatorForLanguageModeling():
def __init__(self, *args, **kwargs):
requires_pytorch(self)
def from_pretrained(self, *args, **kwargs):
requires_pytorch(self) |
class SimpleGaussianMLPModel(Model):
def __init__(self, output_dim, name='SimpleGaussianMLPModel', *args, **kwargs):
super().__init__(name)
self.output_dim = output_dim
def network_output_spec(self):
return ['mean', 'log_std', 'std_param', 'dist']
def _build(self, obs_input, name=Non... |
.datainstrument
def test_restore():
def tester(A: dace.float64[(20, 20)]):
return (A + 5)
sdfg = tester.to_sdfg(simplify=True)
_instrument(sdfg, dace.DataInstrumentationType.Save)
A = np.random.rand(20, 20)
acopy = np.copy(A)
result = sdfg(A)
assert np.allclose(result, (A + 5))
d... |
def coco_evaluation(dataset, predictions, output_folder, box_only, iou_types, expected_results, expected_results_sigma_tol):
if isinstance(dataset, COCODataset):
return do_orig_coco_evaluation(dataset=dataset, predictions=predictions, box_only=box_only, output_folder=output_folder, iou_types=iou_types, expe... |
class RandomRotate(object):
def __init__(self, degree):
self.degree = degree
def __call__(self, img, mask):
rotate_degree = (((random.random() * 2) * self.degree) - self.degree)
return (img.rotate(rotate_degree, Image.BILINEAR), mask.rotate(rotate_degree, Image.NEAREST)) |
class extractSDAE(nn.Module):
def __init__(self, dim, slope=0.0):
super(extractSDAE, self).__init__()
self.in_dim = dim[0]
self.nlayers = (len(dim) - 1)
self.reluslope = slope
(self.enc, self.dec) = ([], [])
for i in range(self.nlayers):
self.enc.append(nn... |
def train_intent_predictor(base_model: TypedModel, args, wandb, optimizer, scheduler, train_dataloader, dev_dataloader, epochs=10, gpus=[], max_grad_norm=1.0):
if (len(gpus) > 1):
parallel_model = nn.DataParallel(base_model, device_ids=gpus).cuda()
elif (len(gpus) == 1):
parallel_model = base_mo... |
def make_cnn(convs, padding, inpt, initializer=None):
if (initializer is None):
initializer = tf.orthogonal_initializer(np.sqrt(2.0))
out = inpt
with tf.variable_scope('convnet'):
for (num_outputs, kernel_size, stride) in convs:
out = layers.convolution2d(out, num_outputs=num_out... |
class Texture1D(object):
def __init__(self, levels, internalformat, W):
self.__id = np.empty(1, dtype=np.uint32)
glCreateTextures(GL_TEXTURE_1D, len(self.__id), self.__id)
glTextureStorage1D(self.__id[0], levels, internalformat, W)
self.__handle = None
def setFilter(self, min_fil... |
class GRUModel(Model):
def __init__(self, output_dim, hidden_dim, name=None, hidden_nonlinearity=tf.nn.tanh, hidden_w_init=tf.initializers.glorot_uniform(seed=deterministic.get_tf_seed_stream()), hidden_b_init=tf.zeros_initializer(), recurrent_nonlinearity=tf.nn.sigmoid, recurrent_w_init=tf.initializers.glorot_unif... |
def main(args):
args = parse_args(args)
if (args.eval and args.format_only):
raise ValueError('--eval and --format_only cannot be both specified')
if ((args.out is not None) and (not args.out.endswith(('.pkl', '.pickle')))):
raise ValueError('The output file must be a pkl file.')
cfg = m... |
def get_stats(lab_fp, score_fp, pred_thresh=None):
pred_thresh = (None if (pred_thresh is None) else float(pred_thresh))
(lab_with_pred_l, lab_pred_d, tot_pred_d, tot_insts) = read_file_multi_lab(lab_fp, score_fp, pred_thresh)
print('Number Instances:', tot_insts)
(max_lab, max_c) = max(collections.Coun... |
def get_num_layer_for_vit(var_name, num_max_layer):
if (('embedding' in var_name) or ('conv1' in var_name) or ('ln_pre' in var_name)):
return 0
elif ('resblocks' in var_name):
layer_id = int(var_name.split('.')[5])
return (layer_id + 1)
elif ('classifier' in var_name):
return... |
_method('Intracomm', 'Irecv')
def _intracomm_irecv(pv: 'ProgramVisitor', sdfg: SDFG, state: SDFGState, icomm: 'Intracomm', buffer: str, src: Union[(str, sp.Expr, Number)], tag: Union[(str, sp.Expr, Number)]):
from mpi4py import MPI
(icomm_name, icomm_obj) = icomm
if (icomm_obj != MPI.COMM_WORLD):
ra... |
def write(self, filename):
nodes = []
edges = []
options = {}
for (n, i) in enumerate(self.inputs()):
nodes.append({'id': i.unique(), 'label': 'input {}'.format(n), 'shape': 'square'})
existing = set()
def add_edge(i_, n):
i = (i_ if (i_.kind() != 'Select') else i_.input())
... |
def draw_rectangle():
root = Tk()
root.title('Rectangle Drawer')
drawer = RectangleDrawer(root)
def on_enter_press(event):
root.quit()
root.bind('<Return>', on_enter_press)
root.mainloop()
rectangles = drawer.get_rectangles()
new_rects = []
for r in rectangles:
new_re... |
def test_transformation_pipeline_is_lossy(named_tensor):
transformer1 = Float32NumpyArrayToBytes()
transformer2 = Float32NumpyArrayToBytes()
transformer2.lossy = True
tp = TransformationPipeline([transformer1, transformer2])
is_lossy = tp.is_lossy()
assert (is_lossy is True) |
def p_template_definition(s):
name = p_ident(s)
if (s.sy == '='):
s.expect('=')
s.expect('*')
required = False
else:
required = True
return (name, required) |
def count_elements(level):
golds = list()
for i in range(level.h):
for j in range(level.w):
if (level[(i, j)] == 'G'):
golds.append((i, j))
return golds |
def convert_dbpointer_to_text_nmatch(vect, goal, belief):
domain_in_pointer = ['restaurant', 'hotel', 'attraction', 'train']
restaurant_book_vec = vect[24:26]
hotel_book_vec = vect[26:28]
train_book_vec = vect[28:]
text = []
for idx in range(4):
domain = domains[idx]
if (domain n... |
class KeywordExtractor():
defaults: Dict[(str, Any)] = {'candidate_selection': 'ngram'}
def __init__(self, nlp: Language, **overrides):
self.nlp = nlp
self.cfg = self.defaults.copy()
self.cfg.update(overrides)
def __call__(self, doc: Doc) -> Doc:
self.init_component()
... |
class amsoftmax(nn.Module):
def __init__(self, input_size: int, output_size: int, margin: float=0.2, scale: float=30):
super().__init__()
self._indim = input_size
self._outdim = output_size
self.margin = margin
self.scale = scale
self.W = torch.nn.Parameter(torch.rand... |
def main(args, init_distributed=False):
utils.import_user_module(args)
assert ((args.max_tokens is not None) or (args.max_sentences is not None)), 'Must specify batch size either with --max-tokens or --max-sentences'
metrics.reset()
if (torch.cuda.is_available() and (not args.cpu)):
torch.cuda.s... |
def _add_ndarray(name: str, obj: ndarray, attributes: Dict[(str, Any)], ndarrays: Dict[(str, ndarray)], objects: Dict[(str, object)]) -> Tuple[(Dict, Dict, Dict)]:
ndarrays[name] = obj
return (attributes, ndarrays, objects) |
def get_distributed_sampler(trainer, dataset, train, **kwargs) -> torch.utils.data.sampler.Sampler:
world_size = {'ddp': (trainer.num_nodes * trainer.num_processes), 'ddp_spawn': (trainer.num_nodes * trainer.num_processes), 'ddp2': trainer.num_nodes, 'ddp_cpu': (trainer.num_processes * trainer.num_nodes)}
asser... |
def layer(x, block, ochannels, count, stride, cfg, test):
for i in range(count):
with nn.parameter_scope('layer{}'.format((i + 1))):
x = block(x, ochannels, (stride if (i == 0) else (1, 1)), cfg, test)
return x |
class MNIST_L2_DRP05(nn.Module):
def __init__(self, dropout=0.5):
super(MNIST_L2_DRP05, self).__init__()
self.dropout = dropout
self.conv1 = nn.Conv2d(1, 32, kernel_size=5)
self.conv2 = nn.Conv2d(32, 64, kernel_size=5)
self.relu = nn.ReLU(True)
self.pool = nn.MaxPool2... |
class DoubleConv(nn.Module):
def __init__(self, in_channels, out_channels, reverse=False):
super().__init__()
if reverse:
self.double_conv = nn.Sequential(Conv3x3BNReLU(in_channels, in_channels, stride=1), Conv3x3BNReLU(in_channels, out_channels, stride=1))
else:
self... |
def cosine_loss(p_logits, q_logits):
return torch.nn.CosineEmbeddingLoss()(q_logits, p_logits.detach(), torch.ones(p_logits.shape[0]).cuda()) |
class Partition9(nn.Module):
LAYER_SCOPES = ['T5ForConditionalGeneration/T5Stack[decoder]/ModuleList[block]/T5Block[3]', 'T5ForConditionalGeneration/T5Stack[decoder]/ModuleList[block]/T5Block[4]', 'T5ForConditionalGeneration/T5Stack[decoder]/ModuleList[block]/T5Block[5]']
TENSORS = []
def __init__(self, lay... |
def _repr_labellist(self) -> str:
items = [self[i] for i in range(min(1, len(self.items)))]
res = f'''{self.__class__.__name__} ({len(self.items)} items)
'''
res += f'''x: {self.x.__class__.__name__}
{show_some([i[0] for i in items], n_max=1)}
'''
res += f'''y: {self.y.__class__.__name__}
{show_some([i[... |
class SignatureEx(inspect.Signature):
def drop_arg(self, argname, raise_if_not_found=False):
ps = dict(self.parameters.items())
if (argname in ps):
del ps[argname]
elif raise_if_not_found:
raise KeyError(f"'{argname}' not found in {list(ps.keys())}")
return se... |
def prepare_params(kwargs):
ddpg_params = dict()
env_name = kwargs['env_name']
def make_env():
return gym.make(env_name)
kwargs['make_env'] = make_env
tmp_env = cached_make_env(kwargs['make_env'])
assert hasattr(tmp_env, '_max_episode_steps')
kwargs['T'] = tmp_env._max_episode_steps
... |
def register_Ns3SimpleRefCount__Ns3MmWaveHarqPhy_Ns3Empty_Ns3DefaultDeleter__lt__ns3MmWaveHarqPhy__gt___methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::SimpleRefCount< ns3::MmWaveHarqPhy, ns3::empty, ns3::DefaultDeleter< ns3::MmWaveHarqPhy > > const &', 'o')])
return |
_grad()
def eval(epoch, model, dataloader, cfg, logger, writer):
logger.info('Validation')
(pred_insts, gt_insts) = ([], [])
progress_bar = tqdm(total=len(dataloader))
val_dataset = dataloader.dataset
model.eval()
for batch in dataloader:
result = model(batch, mode='predict')
pre... |
def _copy_location(newnode, node):
return ast.fix_missing_locations(ast.copy_location(newnode, node)) |
def register_types(module):
root_module = module.get_root()
module.add_class('Address', import_from_module='ns.network')
module.add_enum('MaxSize_e', ['MAX_SIZE'], outer_class=root_module['ns3::Address'], import_from_module='ns.network')
module.add_class('ApplicationContainer', import_from_module='ns.ne... |
def make_fpga_state(sdfg):
state = sdfg.add_state('mm')
sdfg.add_stream('A_pipe', dace.float32, transient=True, shape=((P + 1),), storage=dace.dtypes.StorageType.FPGA_Local, buffer_size='P')
sdfg.add_stream('B_pipe', dace.float32, transient=True, shape=((P + 1),), storage=dace.dtypes.StorageType.FPGA_Local)... |
class Lexer(object):
lex = NotImplemented
def make_lexer_state(self, text):
line_ctr = LineCounter((b'\n' if isinstance(text, bytes) else '\n'))
return LexerState(text, line_ctr) |
def remove_index_types(data):
print('\tRemoving index types ...')
for i in range(len(data)):
for j in range(len(data[i])):
if ((re.match('<%ID> = extractelement', data[i][j]) is not None) or (re.match('<%ID> = insertelement', data[i][j]) is not None)):
data[i][j] = re.sub('i\... |
def prepare_resnet50_jit(bench_args):
model = resnet50()
inputs = (torch.randn(32, 3, 224, 224),)
model = torch.jit.trace(model, inputs)
return (inputs, model) |
def save_config(config_dict, fname=None):
with open(fname, mode='w', encoding='utf-8') as f:
json.dump(config_dict, f) |
def evalSymbReg(individual, points):
func = toolbox.compile(expr=individual)
with warnings.catch_warnings():
warnings.simplefilter('ignore')
try:
func_vals = np.array([func(x) for x in points])
sqerrors = ((func_vals - ref_vals) ** 2.0)
fitness = [np.real(np.m... |
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, in_planes, planes, stride=1):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(planes, planes, kernel_size... |
def recall(candidate, source, gold_edits, max_unchanged_words=2, beta=0.5, verbose=False):
return pre_rec_f1(candidate, source, gold_edits, max_unchanged_words, beta, verbose)[1] |
class CategoriesSampler():
def __init__(self, labels, frame_intervals, n_per):
self.frame_intervals = frame_intervals
self.n_sample = len(labels)
self.n_batch = (self.n_sample // n_per)
self.n_per = n_per
self.scenes = []
self.scene_id = {}
for (idx, label) in... |
def conv_5_3_hook(module, input, output):
global vgg_conv5_3
vgg_conv5_3 = output
return None |
def ReflectionGroup(*args, **kwds):
if (not is_chevie_available()):
raise ImportError("the GAP3 package 'chevie' is needed to work with (complex) reflection groups")
from sage.interfaces.gap3 import gap3
gap3.load_package('chevie')
error_msg = 'the input data (%s) is not valid for reflection gro... |
class AutoEncoderConfig(DetectorConfig, NormalizingConfig):
_default_threshold = AggregateAlarms(alm_threshold=2.5, abs_score=True)
def __init__(self, hidden_size: int=5, layer_sizes: Sequence[int]=(25, 10, 5), sequence_len: int=1, lr: float=0.001, batch_size: int=512, num_epochs: int=50, **kwargs):
sup... |
def test_duplicate_keys():
result = ak.operations.from_json(' [ { "x" :1 ,"y":1.1, "x": 999},{"y": 2.2, "y": 999, "x": 2}, {"x": 3, "x": 999, "y": 3.3}]', schema={'type': 'array', 'items': {'type': 'object', 'properties': {'x': {'type': 'integer'}, 'y': {'type': 'number'}}, 'required': ['x', 'y']}})
assert (res... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.