code stringlengths 101 5.91M |
|---|
def _process_file(wav_dir, txt_dir, base_filename, root_dir):
full_recording_path = os.path.join(root_dir, base_filename)
assert (os.path.exists(full_recording_path) and os.path.exists(root_dir))
wav_recording_path = os.path.join(wav_dir, base_filename.replace('.flac', '.wav'))
subprocess.call(['sox {} ... |
def init_array(imgIn, imgOut):
w = W.get()
h = H.get()
for i in range(w):
for j in range(h):
imgIn[(i, j)] = (datatype((((313 * i) + (991 * j)) % 65536)) / 65535.0) |
def get_axis_size(array: Union[(NDArray, Sequence[NDArray])], axis: int) -> int:
if isinstance(array, np.ndarray):
return int(array.shape[axis])
elif isinstance(array, (list, tuple)):
sizes = list(map((lambda v: v.shape[axis]), array))
size = sizes[axis]
assert np.all((np.array(s... |
def ep_req_func1(protocols, args: Arguments) -> 'BBPSSW':
remote0 = args['remote0']
remote1 = args['remote1']
_protocols = []
for protocol in protocols:
if (not isinstance(protocol, BBPSSW)):
continue
if (protocol.kept_memo.name == remote0):
_protocols.insert(0, p... |
class MaskLoss():
def __call__(self, proposals_with_gt: List[Instances], densepose_predictor_outputs: Any) -> torch.Tensor:
if (not len(proposals_with_gt)):
return self.fake_value(densepose_predictor_outputs)
with torch.no_grad():
mask_loss_data = extract_data_for_mask_loss_f... |
class LinearAnnealedWeight(Decay):
def __init__(self, init_val, end_val, max_epochs, sigma):
super(LinearAnnealedWeight, self).__init__(init_val, end_val, max_epochs, sigma)
self._count = 0.0
self._anneal_start = init_val
self._anneal_end = end_val
msg = "'init_val' must be >... |
def main(unused_argv=None):
dataset = FlowersData(subset=FLAGS.subset)
assert dataset.data_files()
if tf.gfile.Exists(FLAGS.eval_dir):
tf.gfile.DeleteRecursively(FLAGS.eval_dir)
tf.gfile.MakeDirs(FLAGS.eval_dir)
inception_eval.evaluate(dataset) |
def cache_glove(glove_prefix):
stoi = {}
itos = []
vectors = []
fname = (glove_prefix + '.txt')
with open(fname, 'rb') as f:
for l in f:
l = l.strip().split(b' ')
(word, vector) = (l[0], l[1:])
try:
word = word.decode()
except:
... |
def register_Ns3FfMacCschedSapUserCschedCellConfigCnfParameters_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::FfMacCschedSapUser::CschedCellConfigCnfParameters const &', 'arg0')])
cls.add_instance_attribute('m_result', 'ns3::Result_e', is_const=False)
cls.add_instan... |
class DocstringSignatureMixin():
_new_docstrings: List[List[str]] = None
_signatures: List[str] = None
def _find_signature(self) -> Tuple[(str, str)]:
valid_names = [self.objpath[(- 1)]]
if isinstance(self, ClassDocumenter):
valid_names.append('__init__')
if hasattr(s... |
class QDExperiment(object):
def __init__(self, config_filename, parallelism_type='concurrent', seed=None, base_config=None):
self._loadConfig(config_filename)
if (base_config is not None):
self.config = {**self.config, **base_config}
self.parallelism_type = parallelism_type
... |
class BinaryQuintic(AlgebraicForm):
def __init__(self, n, d, polynomial, *args):
assert ((n == 2) and (d == 5))
super().__init__(2, 5, polynomial, *args)
self._x = self._variables[0]
self._y = self._variables[1]
def from_invariants(cls, invariants, x, z, *args, **kwargs):
... |
def init_live_plot(dpi: int=400, figsize: Optional[tuple[(int, int)]]=None, xlabel: Optional[str]=None, ylabel: Optional[str]=None, title: Optional[str]=None, **kwargs):
color = kwargs.pop('color', '#0096FF')
xlabel = ('Step' if (xlabel is None) else xlabel)
(fig, ax) = plt.subplots(nrows=1, ncols=1, dpi=dp... |
def return_dataset_laion_all(img_path, config):
transform = transforms.Compose([transforms.RandomResizedCrop(size=256, scale=(0.9, 1.0)), transforms.ToTensor()])
dataset = capfilt_dataset(img_path, transform)
print(('%d sample in this dataset' % len(dataset)))
bs = config.data.params.batch_size
data... |
class JitDistAutogradTest(RpcAgentTestFixture):
_init
def test_get_gradients(self):
dst_rank = self.rank
.script
def dist_get_gradients(context_id: int) -> Dict[(Tensor, Tensor)]:
return dist_autograd.get_gradients(context_id)
FileCheck().check('get_gradients').run(st... |
def exp_backward(grad_inputs, inputs, input_shapes, outputs, output_shapes):
dy = grad_inputs[0]
x0 = inputs[0]
y0 = outputs[0]
return (dy * y0) |
def test_docstrings(doc):
assert (doc(UserType) == 'A `py::class_` type for testing')
assert (UserType.__name__ == 'UserType')
assert (UserType.__module__ == 'pybind11_tests')
assert (UserType.get_value.__name__ == 'get_value')
assert (UserType.get_value.__module__ == 'pybind11_tests')
assert (d... |
def get_tokenizer(flags):
if (flags.tokenizer.lower() == 'bpe'):
return nlc_data.bpe_tokenizer
elif (flags.tokenizer.lower() == 'char'):
return nlc_data.char_tokenizer
elif (flags.tokenizer.lower() == 'word'):
return nlc_data.basic_tokenizer
else:
raise
return tokeniz... |
def export_mol_highlight(mol, name, hatoms, hbonds, width=100, height=100, color=(0.925, 0.688, 0.355)):
from rdkit.Chem.Draw import rdMolDraw2D
import cairosvg
import io
d = rdMolDraw2D.MolDraw2DSVG(width, height)
rdMolDraw2D.PrepareAndDrawMolecule(d, mol, highlightAtoms=hatoms, highlightBonds=hbon... |
def test_fix_proj_example():
with tempfile.TemporaryDirectory(dir=TEST_WORKING_DIR) as tempdir:
test_name = os.path.join(tempdir, 'fix.xml')
with open(test_name, 'w', encoding='utf-8') as fout:
fout.write(NONPROJ_EXAMPLE)
sentences = convert_arboretum.read_xml_file(test_name)
... |
def simGetJointTargetPosition(jointHandle):
position = ffi.new('float *')
lib.simGetJointTargetPosition(jointHandle, position)
return position[0] |
def _get_column_names(output_format: str, split: bool) -> List[str]:
if (not split):
return [name.strip() for name in output_format.split('\t')]
output_tokens = output_format.split()
headers = []
for output_part in output_tokens:
for attr in KEYWORDS:
if (attr in output_part)... |
def make_plots(statistics_file):
print('\n Make Plots')
with open(statistics_file, 'r') as f:
stats = json.load(f)
output_folder = os.path.split(statistics_file)[0]
FILETYPE = 'eps'
latex = io.StringIO()
LATEX_SHOW_STD = False
numStepsizes = len(STEPSIZES)
numTFs = len(CONFIG_FIL... |
def main(parsed_args, **unused_kwargs):
assert (parsed_args.path is not None), '--path required for evaluation!'
if (torch.cuda.is_available() and (not parsed_args.cpu)):
torch.cuda.set_device(parsed_args.device_id)
utils.import_user_module(parsed_args)
logger.info(parsed_args)
use_cuda = (t... |
class AssertionGenerator(str, enum.Enum):
MUTATION_ANALYSIS = 'MUTATION_ANALYSIS'
CHECKED_MINIMIZING = 'CHECKED_MINIMIZING'
SIMPLE = 'SIMPLE'
NONE = 'NONE' |
def collect_params(model):
params = []
names = []
for (nm, m) in model.named_modules():
if isinstance(m, nn.BatchNorm2d):
for (np, p) in m.named_parameters():
if (np in ['weight', 'bias']):
params.append(p)
names.append(f'{nm}.{np}'... |
def _dml_disambiguate_direction_dependent_views(sdfg: dace.SDFG):
for (n, state) in sdfg.all_nodes_recursive():
if (isinstance(n, nd.AccessNode) and (type(n.desc(sdfg)) is dt.View)):
in_edges = state.in_edges(n)
out_edges = state.out_edges(n)
if ((len(in_edges) == 1) and ... |
def find_next_word(index, text, word, output):
idx = 0
word_sofar = ''
yeah = False
while ((index < len(text)) and (idx < len(word))):
if ((text[index] == '\n') and ((index + 1) < len(text)) and (text[(index + 1)] == '\n')):
if (len(word_sofar) > 0):
assert re.match('... |
def count_model_size(model):
return (np.sum((np.prod(v.size()) for (name, v) in model.named_parameters())) / 1000000.0) |
((not have_sympy), 'SymPy not installed')
def test_conv2():
x = Symbol('x')
y = Symbol('y')
z = Symbol('z')
e = (x * y)
assert (e._sympy_() == (sympy.Symbol('x') * sympy.Symbol('y')))
e = ((x * y) * z)
assert (e._sympy_() == ((sympy.Symbol('x') * sympy.Symbol('y')) * sympy.Symbol('z'))) |
class InttoptrInst(ConversionInst):
code = 'inttoptr'
def type_constraints(self, tcs):
tcs.integer(self.arg)
tcs.pointer(self)
tcs.specific(self.arg, self.src_ty)
tcs.specific(self, self.ty) |
def load_question_cache():
if os.path.exists(CACHE_FILE):
with open(CACHE_FILE, 'r') as f:
return json.load(f)
else:
return {} |
def get_cfg():
config = _C.clone()
parser = argparse.ArgumentParser()
parser.add_argument('--test', action='store_true')
parser.add_argument('--dist_init_method', type=str, default=None)
parser.add_argument('--dataset_root', type=str, default=None)
parser.add_argument('--output_root', type=str, ... |
def settings(*args, **kwargs):
if (('min_satisfying_examples' in kwargs) and (hypothesis.version.__version_info__ >= (3, 56, 0))):
kwargs.pop('min_satisfying_examples')
if (('deadline' in kwargs) and (hypothesis.version.__version_info__ < (4, 44, 0))):
kwargs.pop('deadline')
if (('timeout' i... |
(eq=False)
class Parameter():
definition: Any
def location(self) -> str:
raise NotImplementedError
def name(self) -> str:
raise NotImplementedError
def is_required(self) -> bool:
raise NotImplementedError
def example(self) -> Any:
raise NotImplementedError
def ser... |
def _att_dropout_broadcast_default() -> bool:
from returnn.config import get_global_config
from returnn.util.basic import BehaviorVersion
config = get_global_config(raise_exception=False)
if config:
opt = config.bool('rf_att_dropout_broadcast', None)
if (opt is not None):
ret... |
def add_argument(group):
with subgroup.SubGroup(group, 'general') as s:
s.add('--dpath', type=str, default=path.join('..', 'dataset'))
s.add('--dpath_test', type=str)
s.add('--dtrain', nargs='+', type=str, default=['sr.div2k.base'])
s.add('--dtest', nargs='+', type=str, default=['sr.... |
.parametrize('num_inducing_points', [(- 1), 0])
def test_build_sgpr_raises_for_invalid_num_inducing_points(num_inducing_points: int) -> None:
(qp, obs) = mock_data()
data = mk_dataset(qp, obs)
search_space = (Box([0.0], [1.0]) ** qp.shape[(- 1)])
with pytest.raises(TF_DEBUGGING_ERROR_TYPES):
bui... |
def spin_rec(t, nexts, current, part, weight, length):
if (not current):
return [parent(t).zero()]
tmp = []
partp = part[0].conjugate()
ell = len(partp)
for val in current:
perms = val[1]
perm = [(((partp[i] + ell) - (i + 1)) - perms[i]) for i in reversed(range(ell))]
... |
class MetricTestCase(unittest.TestCase):
def setUpClass(cls) -> None:
cls.paired_metric_dict = register_metrics(types=('ssim', 'psnr', 'lps'), device=DEVICE)
cls.unpaired_metric_dict = register_metrics(types=('is', 'fid', 'SSPE', 'OS-CS-reid', 'OS-freid'), device=DEVICE)
cls.face_metric_dict... |
class sage__rings__real_double(PythonModule):
def __init__(self):
PythonModule.__init__(self, 'sage.rings.real_double', type='standard') |
class Sampler_uni(torch.utils.data.sampler.Sampler):
def __init__(self, num1, num2, num3, batchsize, balance_id=None):
self.num1 = num1
self.num2 = num2
self.num3 = num3
self.batchsize = batchsize
self.balance_id = balance_id
def __iter__(self):
if (self.balance_i... |
class VNPRModel(keras.Model):
def __init__(self, num_users, num_items, embed_mf_size, l_w, l_v, mlp_hidden_size, dropout, learning_rate=0.01, num_image_feature=128, random_seed=42, name='VNPR', **kwargs):
super().__init__(name=name, **kwargs)
tf.random.set_seed(random_seed)
self.num_users = ... |
class Graph():
def __init__(self, image, objects, relationships, attributes):
self.image = image
self.objects = objects
self.relationships = relationships
self.attributes = attributes |
def get_loss(pred, label):
weight_decay_losses = tf.get_collection('losses')
weight_decay_loss = tf.reduce_sum(weight_decay_losses)
loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=pred, labels=label)
classify_loss = tf.reduce_mean(loss)
tf.summary.scalar('classify loss', classify_loss)
... |
def concat(x, axis):
if tf.__version__.startswith('0'):
return tf.concat(axis, x)
else:
return tf.concat(x, axis=axis) |
def load_datasets(data_dir: str) -> Tuple[(List[Annotation], List[Annotation], List[Annotation])]:
train_data = annotations_from_jsonl(os.path.join(data_dir, 'train.jsonl'))
val_data = annotations_from_jsonl(os.path.join(data_dir, 'val.jsonl'))
test_data = annotations_from_jsonl(os.path.join(data_dir, 'test... |
def structure_loss(pred, mask):
weit = (1 + (5 * torch.abs((F.avg_pool2d(mask, kernel_size=31, stride=1, padding=15) - mask))))
wbce = F.binary_cross_entropy_with_logits(pred, mask, reduce='none')
wbce = ((weit * wbce).sum(dim=(2, 3)) / weit.sum(dim=(2, 3)))
pred = torch.sigmoid(pred)
inter = ((pred... |
class UNetModule(nn.Module):
def __init__(self, in_planes, nblock, filter_size, dprob, in_dim, index, max_planes, atrous=0):
super(UNetModule, self).__init__()
self.nblock = nblock
self.in_dim = np.array(in_dim, dtype=float)
self.down = nn.ModuleList([])
self.up = nn.ModuleLi... |
class Partition0(nn.Module):
LAYER_SCOPES = ['T5ForConditionalGeneration/T5Stack[encoder]/StatelessEmbedding[embed_tokens]', 'T5ForConditionalGeneration/T5Stack[encoder]/Dropout[dropout]', 'T5ForConditionalGeneration/T5Stack[encoder]/T5Block[0]', 'T5ForConditionalGeneration/T5Stack[encoder]/T5Block[1]', 'T5ForCondi... |
def get_action(action_type, gt_graph, env, reward_config, strict):
action_type_str = (action_type + 'Action')
if (action_type_str in globals()):
action = globals()[action_type_str]
return action(gt_graph, env, reward_config[action_type_str], strict)
else:
raise Exception(('Invalid ac... |
def test_subscriptionWithWrongPayload():
url = (brokerIp + '/v2/subscriptions')
headers = {'Content-Type': 'application/json'}
r = requests.post(url, data=json.dumps(data.subscriptionWrongPaylaod), headers=headers)
assert (r.status_code == 500) |
def clean_padding_(tensor, length, len_dim=1, mask_value=0.0):
max_len = tensor.size(len_dim)
mask = length_to_mask((length * max_len), max_len).bool()
mask_unsq = mask[((...,) + ((None,) * (tensor.dim() - 2)))]
mask_t = mask_unsq.transpose(1, len_dim).expand_as(tensor)
tensor[(~ mask_t)] = mask_val... |
.skip(reason='This needs actual Atari 2600 environments.')
.parametrize('is_eval', [True])
def test_atari(is_eval: bool) -> None:
env = Atari(gym.make('BreakoutNoFrameskip-v4'), is_eval)
assert (env.observation_space.shape == (1, 84, 84))
(observation, _) = env.reset()
assert (observation.shape == (1, 8... |
.gpu
def test_gpu_vec():
sdfg: dace.SDFG = cudahello.to_sdfg()
sdfg.name = 'cuda_grid_gpu_vec'
assert (sdfg.apply_transformations([GPUTransformMap, Vectorization]) == 2)
_test(sdfg)
if (common.get_gpu_backend() == 'cuda'):
assert was_vectorized(sdfg) |
class Wikiextractor(PipelineJob):
def __init__(self, preprocess_jobs: Dict[(str, PipelineJob)], opts):
super().__init__(requires=[f'data/versions/{opts.data_version_name}/downloads/{opts.wiki_lang_version}/'], provides=[f'data/versions/{opts.data_version_name}/wikiextractor_out/{opts.wiki_lang_version}/'], ... |
class AudioCapsQADataset(AudioCapsDataset):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.add_binary = kwargs.get('add_binary', False)
self.binary_templates = ['do you hear {}?', 'is this {}?', 'does the audio contain {}?']
def __getitem__(self, index):
ann = copy... |
class TrainState(flax.struct.PyTreeNode):
step: int
apply_fn: Callable[(..., Any)] = nonpytree_field()
model_def: Any = nonpytree_field()
params: Params
tx: Optional[optax.GradientTransformation] = nonpytree_field()
opt_state: Optional[optax.OptState] = None
def create(cls, model_def: nn.Mod... |
_utils.test(arch=[ti.vulkan])
def test_devcap():
module = ti.aot.Module(ti.vulkan, caps=[ti.DeviceCapability.spirv_has_float16, ti.DeviceCapability.spirv_has_atomic_float16_minmax])
with tempfile.TemporaryDirectory() as tmpdir:
module.save(tmpdir)
with open((tmpdir + '/metadata.json')) as f:
... |
class Logger(object):
def __init__(self, log_dir):
self.writer = tf.summary.FileWriter(log_dir)
def scalar_summary(self, tag, value, step):
summary = tf.Summary(value=[tf.Summary.Value(tag=tag, simple_value=value)])
self.writer.add_summary(summary, step)
self.writer.flush()
d... |
class TestHyp1f1():
.parametrize('a, b, x', [(np.nan, 1, 1), (1, np.nan, 1), (1, 1, np.nan)])
def test_nan_inputs(self, a, b, x):
assert np.isnan(sc.hyp1f1(a, b, x))
def test_poles(self):
assert_equal(sc.hyp1f1(1, [0, (- 1), (- 2), (- 3), (- 4)], 0.5), np.inf)
.parametrize('a, b, x, resu... |
def get_windows_version(run_lambda):
return run_and_read_all(run_lambda, 'wmic os get Caption | findstr /v Caption') |
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('AttributeConstructionList', import_from_module='... |
def get_plot(q):
(eps, p) = (1e-08, 0)
(x, y) = ([(q[0] - np.abs((q[0] * 0.2)))], [0])
for i in range(0, len(q)):
x += [(q[i] - eps), q[i]]
y += [p, (p + (1 / len(q)))]
p += (1 / len(q))
x += [(q[i] + eps), (q[i] + np.abs((q[i] * 0.2)))]
y += [1.0, 1.0]
return (x, y) |
def main():
toolkits = []
for f in args.toolkits_paths:
toolkits.extend(read_file(f))
print(f'Loaded {len(toolkits)} toolkits')
existing_tool_names = set([t['toolkit'] for t in toolkits])
os.makedirs(args.dump_dir, exist_ok=True)
base_name = (args.gen_filename + ('_risky' if generator.ge... |
def sinc_backward(grad_inputs, inputs, input_shapes, outputs, output_shapes):
dy = grad_inputs[0]
x0 = inputs[0]
m0 = F.not_equal_scalar(x0, 0)
m0 = no_grad(m0)
y0 = outputs[0]
dx0 = ((dy * (F.cos(x0) - (F.sin(x0) / x0))) / x0)
c0 = F.constant(0, x0.shape)
dx0 = F.where(m0, dx0, c0)
... |
class OUStrategy(ExplorationStrategy):
def __init__(self, env_spec, mu=0, sigma=0.3, theta=0.15, dt=0.01, x0=None):
self._env_spec = env_spec
self._action_space = env_spec.action_space
self._action_dim = self._action_space.flat_dim
self._mu = mu
self._sigma = sigma
se... |
('clone_repository', 'Clone Repository', '"url": "<repository_url>", "clone_path": "<clone_path>"', (lambda config: (config.github_username and config.github_api_key)), 'Configure github_username and github_api_key.')
_url
def clone_repository(url: str, clone_path: str, agent: Agent) -> str:
split_url = url.split('... |
class DumpUnpickler(pickle._Unpickler):
def __init__(self, file, *, catch_invalid_utf8=False, **kwargs):
super().__init__(file, **kwargs)
self.catch_invalid_utf8 = catch_invalid_utf8
def find_class(self, module, name):
return FakeClass(module, name)
def persistent_load(self, pid):
... |
class GradientDescentL2():
def __init__(self, problem: L2Problem, variable: TensorList, step_length: float, momentum: float=0.0, debug=False, plotting=False, fig_num=(10, 11)):
self.problem = problem
self.x = variable
self.step_legnth = step_length
self.momentum = momentum
se... |
def frobenius_expansion_by_series(Q, p, M):
S = SpecialCubicQuotientRing(Q)
(x, _) = S.gens()
base_ring = S.base_ring()
x_to_p_less_1 = (x ** (p - 1))
x_to_p = (x_to_p_less_1 * x)
x_to_p_squared = (x_to_p * x_to_p)
x_to_p_cubed = (x_to_p_squared * x_to_p)
frobQ = ((x_to_p_cubed + (Q[1] *... |
class EmitTrmmUniversalInstance():
def __init__(self):
self.trmm_template = '\n// Trmm operator ${operation_name}\nusing Operation_${operation_name} = \n typename cutlass::gemm::device::Trmm<\n ${element_a}, ${layout_a},\n ${side_mode}, ${fill_mode}, ${diag_type}, \n ${element_b}, ${layout_b}, \n ... |
def set_cpus(local_rank, world_size):
local_size = min(world_size, 8)
curr_process = psutil.Process()
total_cpus = curr_process.cpu_affinity()
total_cpu_count = len(total_cpus)
if (total_cpu_count > (multiprocessing.cpu_count() / world_size)):
orig_cpus = total_cpus
total_cpus = []
... |
_ARCH_REGISTRY.register()
class PanopticFPN(nn.Module):
def __init__(self, cfg):
super().__init__()
self.instance_loss_weight = cfg.MODEL.PANOPTIC_FPN.INSTANCE_LOSS_WEIGHT
self.combine_on = cfg.MODEL.PANOPTIC_FPN.COMBINE.ENABLED
self.combine_overlap_threshold = cfg.MODEL.PANOPTIC_FPN... |
def _first_line_re():
if isinstance(first_line_re.pattern, str):
return first_line_re
return re.compile(first_line_re.pattern.decode()) |
class CocoClipDatasetMapper():
def __init__(self, is_train: bool, *, augmentations: List[Union[(T.Augmentation, T.Transform)]], image_format: str, use_instance_mask: bool=False, sampling_frame_num: int=2):
self.is_train = is_train
self.augmentations = T.AugmentationList(augmentations)
self.i... |
def get_comparison_dtype(a, b):
a_dtype = (torch.float32 if (a.dtype is torch.bfloat16) else a.dtype)
b_dtype = (torch.float32 if (b.dtype is torch.bfloat16) else b.dtype)
compare_dtype = torch.promote_types(a_dtype, b_dtype)
if ((compare_dtype is torch.float16) and ((a.device != b.device) or (a.device.... |
def expid2model(expr_dir):
from configer import Configer
if (not os.path.exists(expr_dir)):
raise ValueError(('Could not find the experiment directory: %s' % expr_dir))
best_model_fname = sorted(glob.glob(os.path.join(expr_dir, 'snapshots', '*.pt')), key=os.path.getmtime)[(- 1)]
try_num = os.pat... |
def dict_to_str(d: dict, grab: Optional[bool]=None) -> str:
if grab:
return '\n'.join([f'''{k}: {getattr(v, 'shape', None)} {getattr(v, 'dtype', None)}
{grab_tensor(v)}''' for (k, v) in d.items()])
return '\n'.join([f'{k}: {v}' for (k, v) in d.items()]) |
class TFAutoModelForMultipleChoice():
def __init__(self):
raise EnvironmentError('TFAutoModelForMultipleChoice is designed to be instantiated using the `TFAutoModelForMultipleChoice.from_pretrained(pretrained_model_name_or_path)` or `TFAutoModelForMultipleChoice.from_config(config)` methods.')
_list_opt... |
def decision_list(n_leaves):
def _list(leaves):
if (len(leaves) == 2):
return (leaves[0], leaves[1])
else:
return (leaves[0], _list(leaves[1:]))
return _list(np.arange(n_leaves)) |
class PositionalEncoding(nn.Module):
def __init__(self, dim, max_pos=512):
super().__init__()
pos = torch.arange(max_pos)
freq = (torch.arange((dim // 2)) / dim)
freq = (freq * torch.tensor(10000).log()).exp()
x = (rearrange(pos, 'L -> L 1') / freq)
x = rearrange(x, '... |
def create_collaborator(col, workspace_root, data_path, archive_name, fed_workspace):
col_path = (workspace_root / col)
shutil.rmtree(col_path, ignore_errors=True)
col_path.mkdir()
check_call(['fx', 'workspace', 'import', '--archive', (workspace_root / archive_name)], cwd=col_path)
check_call(['fx',... |
class AdminLanguage():
def __init__(self):
self.explicit_removal = ['Admission Date', 'Discharge Date', 'Date of Birth', 'Phone', 'Date/Time', 'ID', 'Completed by', 'Dictated By', 'Attending', 'Provider: ', 'Provider', 'Primary', 'Secondary', ' MD Phone', ' M.D. Phone', ' MD', ' PHD', ' X', ' IV', ' VI', ' ... |
class DataStore(object):
def __init__(self, ui):
self._files = {}
self._run_ids = {}
self._bench_cfgs = {}
self.ui = ui
def load_data(self, runs, discard_run_data):
for persistence in list(self._files.values()):
persistence.load_data(runs, discard_run_data)
... |
def parseArgs():
args = TestOptions().parse()
args.output_channels = OUTPUT_CHANNELS
args.img_width = IMG_WIDTH
args.img_height = IMG_HEIGHT
return args |
class LitePose(nn.Module):
def __init__(self, dictionary=None, model_cfg=None):
super().__init__()
self.dictionary = dictionary
self.model_cfg = model_cfg
self.input_size = [1024, 2048]
self.dummy_input = torch.zeros(1, 3, self.input_size[0], self.input_size[1])
self.... |
def searchForAnswer(answer, table, passages, mapping_entity):
(results, matched_cells) = ([], [])
loop_through_table(answer, table, results, matched_cells)
for (k, v) in passages.items():
if (k in mapping_entity):
if (((' ' + answer.lower()) + ' ') in ((' ' + v.lower()) + ' ')):
... |
.parametrize('ctx, func_name', ctxs)
.parametrize('seed', [313])
.parametrize('prob', [0.7, 1.0])
.parametrize('area_ratios', [(0.02, 0.04)])
.parametrize('aspect_ratios', [(0.3, 3.3333)])
.parametrize('replacements', [(2.0, 2.0), (3.0, 4.0)])
.parametrize('n', [1, 3])
.parametrize('share', [True, False])
.parametrize(... |
def dataio_prepare(hparams, tokenizer):
data_folder = hparams['data_folder']
train_data = sb.dataio.dataset.DynamicItemDataset.from_csv(csv_path=hparams['train_csv'], replacements={'data_root': data_folder})
if (hparams['sorting'] == 'ascending'):
train_data = train_data.filtered_sorted(sort_key='du... |
def put_acquire_arg_buffer(entry, code, pos):
buffer_aux = entry.buffer_aux
getbuffer = get_getbuffer_call(code, entry.cname, buffer_aux, entry.type)
code.putln('{')
code.putln(('__Pyx_BufFmt_StackElem __pyx_stack[%d];' % entry.type.dtype.struct_nesting_depth()))
code.putln(code.error_goto_if(('%s =... |
def uncertainty_sampling(model_instance, pool, size):
active_eval_loader = get_tr_set(train_examples=pool, batch_size=1, args=args)
(raw_prediction, turncate_list) = active_eval(active_eval_loader, model_instance)
word_prob = np.max(raw_prediction, axis=2)
sentence_uncertainty = []
for (i, sentence)... |
class ModelEMA():
def __init__(self, model, decay=0.9999, updates=0):
self.ema = deepcopy((model.module if is_parallel(model) else model)).eval()
self.updates = updates
self.decay = (lambda x: (decay * (1 - math.exp(((- x) / 2000)))))
for p in self.ema.parameters():
p.req... |
def mean(aList):
theSum = 0
count = 0
for x in aList:
theSum += x
count += 1
return (0 if (count == 0) else (theSum / count)) |
class CategoricalCrossEntropy(Layer):
def __init__(self, from_logits=False, **kwargs):
self._from_logits = from_logits
super().__init__(**kwargs)
def call(self, x):
return K.categorical_crossentropy(x[1], x[0], from_logits=self._from_logits) |
class EmbeddingWriterConfig(argparse.ArgumentParser):
def __init__(self):
super().__init__('Pre-compute embeddings for flashlight datasets')
kwargs = {'action': 'store', 'type': str, 'required': True}
self.add_argument('--input', '-i', help='Input Directory', **kwargs)
self.add_argum... |
def analyze_predictions(model, dataset, class_to_idx, pad_idx, device, args, out_file=None, visualize_output=True, tokenizer=None):
references = dataset.references
hardness = references.stimulus_id.apply((lambda x: decode_stimulus_string(x)[2]))
view_dep_mask = is_explicitly_view_dependent(references)
e... |
class RandomCrop_city_gnet(object):
def __init__(self, size, padding=0):
self.size = tuple(size)
self.padding = padding
def __call__(self, img, mask):
if (self.padding > 0):
img = ImageOps.expand(img, border=self.padding, fill=0)
mask = ImageOps.expand(mask, borde... |
def compute_score(hist, correct, labeled):
iu = (np.diag(hist) / ((hist.sum(1) + hist.sum(0)) - np.diag(hist)))
mean_IU = np.nanmean(iu)
mean_IU_no_back = np.nanmean(iu[1:])
freq = (hist.sum(1) / hist.sum())
freq_IU = (iu[(freq > 0)] * freq[(freq > 0)]).sum()
mean_pixel_acc = (correct / labeled)... |
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('_lsq', parent_package, top_path)
config.add_extension('givens_elimination', sources=['givens_elimination.c'])
return config |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.