code stringlengths 101 5.91M |
|---|
class ImageEncoder(nn.Module):
def __init__(self):
super(ImageEncoder, self).__init__()
self.backbone = resnet34(in_channels=3, pretrained=False, progress=True)
def forward(self, x):
resnet_out = self.backbone(x)
return resnet_out |
def get_loading_backend():
if _torchaudio_available():
return torchaudio_loader
if _sndfile_available():
return soundfile_loader |
def create_RealField(prec=53, type='MPFR', rnd='RNDN', sci_not=0):
if (type == 'RDF'):
from .real_double import RDF
return RDF
elif (type == 'Interval'):
from .real_mpfi import RealIntervalField
return RealIntervalField(prec, sci_not)
elif (type == 'Ball'):
from .real... |
def find_lcmtypes_dirs(root_path, excluded_paths=None):
remaining_excluded_paths = set((excluded_paths or []))
for (dirpath, dirnames, _) in os.walk(root_path, topdown=True, followlinks=False):
rel_dir = os.path.relpath(dirpath, root_path)
if (rel_dir in remaining_excluded_paths):
re... |
class ExplorationStrategy():
def get_action(self, t, observation, policy, **kwargs):
raise NotImplementedError
def get_actions(self, t, observations, policy, **kwargs):
raise NotImplementedError
def reset(self):
pass |
def test_train(train_data_fx, model_fx):
h = model_fx.train(train_data_fx[0], train_data_fx[1], epochs=10) |
def _iter_optplan_fields(model: models.Model, visited: Set[int], process_field: Callable[([models.Model, Union[(str, optplan.ProblemGraphNode)]], None)], pass_field_info: bool=False) -> None:
if (not isinstance(model, models.Model)):
return
if (id(model) in visited):
return
visited.add(id(mo... |
def schur(ambient_dim=None, lattice=None):
from sage.geometry.cone import Cone
from sage.matrix.constructor import matrix
from sage.rings.integer_ring import ZZ
(ambient_dim, lattice) = _preprocess_args(ambient_dim, lattice)
def _f(i, j):
if (i == j):
return 1
elif ((j - ... |
def parallel_self_attention(model_parallel_size, num_att_heads_per_partition, hidden_size_per_att_head, dropout_prob, batch_size, sequence_length):
mpu.initialize_model_parallel(model_parallel_size)
model_parallel_size = mpu.get_model_parallel_world_size()
seed = 12345
set_random_seed(seed)
num_att_... |
def _impl(arrays, axis, nested, parameters, with_name, highlevel, behavior, attrs):
axis = regularize_axis(axis)
if isinstance(arrays, Mapping):
index_arrays = {n: ak.local_index(x, axis) for (n, x) in arrays.items()}
else:
index_arrays = [ak.local_index(x) for x in arrays]
if (with_name... |
class TorchFixedNormalizer(FixedNormalizer):
def normalize(self, v, clip_range=None):
if (clip_range is None):
clip_range = self.default_clip_range
mean = ptu.np_to_var(self.mean, requires_grad=False)
std = ptu.np_to_var(self.std, requires_grad=False)
if (v.dim() == 2):
... |
def ud_scores(gold_conllu_file, system_conllu_file):
gold_ud = ud_eval.load_conllu_file(gold_conllu_file)
system_ud = ud_eval.load_conllu_file(system_conllu_file)
evaluation = ud_eval.evaluate(gold_ud, system_ud)
return evaluation |
def initialize_latent_search(agent, latent_search_policy, max_search_steps=10):
agent.initialize_search(latent_search_policy.rb_vec, max_search_steps=max_search_steps) |
class RandomForestForecaster(SKLearnForecaster):
config_class = RandomForestForecasterConfig
def __init__(self, config: RandomForestForecasterConfig):
super().__init__(config)
self.model = RandomForestRegressor(n_estimators=self.config.n_estimators, max_depth=self.config.max_depth, min_samples_s... |
def to_string(instring, tokensStart, retTokens):
val = retTokens[0]
val = (("'" + val[1:(- 1)].replace("''", "\\'")) + "'")
return {'literal': ast.literal_eval(val)} |
_model
def SReT_LT_wo_slice_distill(pretrained=False, **kwargs):
model = DistilledRecursiveTransformer(image_size=224, patch_size=16, stride=8, base_dims=[32, 32, 32], depth=[4, 10, 6], recursive_num=[2, 5, 3], heads=[2, 4, 8], mlp_ratio=4, np_mlp_ratio=1, **kwargs)
if pretrained:
state_dict = torch.loa... |
def assert_incompatible_shapes_raise(input_shapes):
inarrays = [np.zeros(s) for s in input_shapes]
assert_raises(ValueError, broadcast_arrays, *inarrays) |
def print_memory_stats(message=''):
return
import psutil
global_info = psutil.virtual_memory()
(total, available, used, free) = (global_info.total, global_info.available, global_info.used, global_info.free)
info = psutil.Process().memory_info()
(rss, vms, shared) = (info.rss, info.vms, info.shar... |
class MiniProduction(object):
def __init__(self, str, name, len, func, file, line):
self.name = name
self.len = len
self.func = func
self.callable = None
self.file = file
self.line = line
self.str = str
def __str__(self):
return self.str
def __... |
class PourFromCupToCup(Task):
def init_task(self) -> None:
self.drops = []
self.cup_target_base = Dummy('cup_target_base')
self.cup_source = Shape('cup_source')
self.cup_target = Shape('cup_target')
self.cup_source_visual = Shape('cup_source_visual')
self.cup_target_v... |
def process(queryPack, response):
output = ''
for i in range(len(queryPack)):
output += '{}\t'.format(queryPack[i])
for j in range(len(response[i])):
output += '{} '.format(response[i][j])
output += '\n'
return output |
def save_config_to_file(config, config_file):
with open(config_file, 'w') as fp:
return json.dump(config, fp, indent='\t') |
def report_coverage() -> None:
start_time = time.time()
(options, test_list, interested_folders) = initialization()
get_json_report(test_list, options)
if options.need_summary:
summarize_jsons(test_list, interested_folders, [''], TestPlatform.OSS)
print_time('Program Total Time: ', start_tim... |
class StreamingSupport(object):
def supports_streaming(self):
return False
def add_samples(self, X, current=True):
raise NotImplementedError('add_samples() has not been implemented.')
def update_model_from_stream_buffer(self):
raise NotImplementedError('update_model_from_stream_buffe... |
def to_bio2(tags):
new_tags = []
for (i, tag) in enumerate(tags):
if (tag in EMPTY_OR_O_TAG):
new_tags.append(tag)
elif (tag[0] == 'I'):
if ((i == 0) or (tags[(i - 1)] == 'O') or (tags[(i - 1)][1:] != tag[1:])):
new_tags.append(('B' + tag[1:]))
... |
class RandomSearchMutGaussian(Evolution):
sel_pb: float
init_pb: float
mut_pb: float
mu: float
sigma: float
def __init__(self, container: Container, budget: int, dimension: int, sel_pb: float=0.5, init_pb: float=0.5, mut_pb: float=0.2, mu: float=0.0, sigma: float=1.0, **kwargs):
self.sel... |
def create_tmp_tables_guard(selects, datasource):
if isinstance(selects, six.string_types):
tables = create_tmp_table_from_select(selects, datasource)
drop_table_list = [tables]
elif isinstance(selects, (list, tuple)):
tables = [create_tmp_table_from_select(s, datasource) for s in select... |
def enqueue(net, queue, data_blobs, status=None):
if (status is None):
status = net.NextName('status')
queue_blobs = []
for blob in data_blobs:
if (blob not in queue_blobs):
queue_blobs.append(blob)
else:
logger.warning('Need to copy blob {} to enqueue'.format... |
class LrUpdaterHook(Hook):
def __init__(self, by_epoch=True, warmup=None, warmup_iters=0, warmup_ratio=0.1, warmup_by_epoch=False, **kwargs):
if (warmup is not None):
if (warmup not in ['constant', 'linear', 'exp']):
raise ValueError('"{}" is not a supported type for warming up, ... |
def find_color_scalar(color_string):
color_dict = {'purple': (255, 0, 255), 'yellow': (0, 255, 255), 'blue': (255, 0, 0), 'green': (0, 255, 0), 'red': (0, 0, 255), 'skyblue': (235, 206, 135), 'navyblue': (128, 0, 0), 'azure': (255, 255, 240), 'slate': (255, 0, 127), 'chocolate': (30, 105, 210), 'olive': (112, 255, ... |
class APrioriMeshTester():
def __init__(self, mesh: fenics.Mesh):
self.mesh = mesh
dg_function_space = fenics.FunctionSpace(self.mesh, 'DG', 0)
vector_cg_space = fenics.VectorFunctionSpace(self.mesh, 'CG', 1)
dx = fenics.Measure('dx', domain=mesh)
self.transformation_containe... |
def get_instruct_adapter_spec(num_outputs: int=1, max_tokens: int=512, temperature: float=0.7) -> AdapterSpec:
return AdapterSpec(method=ADAPT_GENERATION, instructions='', input_prefix='', input_suffix='\n', output_prefix='', output_suffix='', max_train_instances=0, num_outputs=num_outputs, max_tokens=max_tokens, t... |
def test_metric_evaluate_y_pred_zeros():
metrics = create_metric_list(k, np.ones(3))
y_pred = torch.from_numpy(np.zeros((2, 3)))
for metric in metrics:
assert (metric.evaluate(y_true, y_pred) == 0.0) |
def validate_files(file_dict, data_home, verbose):
missing = {}
invalid = {}
for (file_id, file) in tqdm.tqdm(file_dict.items(), disable=(not verbose)):
for clips in file.keys():
if (clips == 'clips'):
continue
else:
filepath = file[clips][0]
... |
def split_text(text: str, n=100, character=' ') -> List[str]:
text = text.split(character)
return [character.join(text[i:(i + n)]).strip() for i in range(0, len(text), n)] |
def test_nullable_ref(testdir):
testdir.make_test('\(method="POST")\(max_examples=1)\ndef test_(request, case):\n request.config.HYPOTHESIS_CASES += 1\n assert case.path == "/users"\n assert case.method == "POST"\n assert case.body is None\n', paths={'/users': {'post': {'parameters': [{'in': 'body', 'na... |
class VermaModuleMorphism(Morphism):
def __init__(self, parent, scalar):
self._scalar = scalar
Morphism.__init__(self, parent)
def _repr_type(self):
return 'Verma module'
def _repr_defn(self):
v = self.domain().highest_weight_vector()
if (not self._scalar):
... |
class rdist_gen(rv_continuous):
def _shape_info(self):
return [_ShapeInfo('c', False, (0, np.inf), (False, False))]
def _pdf(self, x, c):
return np.exp(self._logpdf(x, c))
def _logpdf(self, x, c):
return ((- np.log(2)) + beta._logpdf(((x + 1) / 2), (c / 2), (c / 2)))
def _cdf(sel... |
_config
def fixed_mdp_rnd_init():
LOCAL_TESTING = False
fixed_mdp = True
layout_name = 'scenario2'
sim_threads = (10 if LOCAL_TESTING else 50)
PPO_RUN_TOT_TIMESTEPS = 24000
TOTAL_BATCH_SIZE = 8000
STEPS_PER_UPDATE = 4
MINIBATCHES = 4
LR = 0.0005 |
def interpolate_3D(input, size=None, scale_factor=None, interpolation='trilinear'):
assert (input.dim() == 5), 'input must be 5D'
scaled = F.interpolate(input, size=size, scale_factor=scale_factor, mode=interpolation, align_corners=True)
return scaled |
class Function_psi2(GinacFunction):
def __init__(self):
GinacFunction.__init__(self, 'psi', nargs=2, latex_name='\\psi', conversions=dict(mathematica='PolyGamma', sympy='polygamma', maple='Psi', giac='Psi', fricas='polygamma'))
def _maxima_init_evaled_(self, *args):
args_maxima = []
for ... |
class TestKerasBaseActivationsQuantizer(BaseKerasTrainableInfrastructureTest):
def __init__(self, unit_test):
super().__init__(unit_test)
def get_activation_quantization_config(self):
return TrainableQuantizerActivationConfig(activation_quantization_method=QuantizationMethod.UNIFORM, activation_... |
def cython_compile(path_pattern, options):
pool = None
all_paths = map(os.path.abspath, extended_iglob(path_pattern))
try:
for path in all_paths:
if options.build_inplace:
base_dir = path
while ((not os.path.isdir(base_dir)) or is_package_dir(base_dir)):
... |
class BiasedMF(RecModel):
def _init_weights(self):
self.uid_embeddings = torch.nn.Embedding(self.user_num, self.ui_vector_size)
self.iid_embeddings = torch.nn.Embedding(self.item_num, self.ui_vector_size)
self.user_bias = torch.nn.Embedding(self.user_num, 1)
self.item_bias = torch.nn... |
def test_edge_bundling():
params = {'model': 'SIS', 'b': 0.00208, 'd': 0.01, 'c': 1, 'runs': 10, 'steps': 500, 'seed': 1, 'diffusion': 'max', 'method': 'add_edge_random', 'k': 15, 'edge_style': 'bundled', 'node_style': 'force_atlas', 'fa_iter': 200, 'plot_transition': True, 'gif_animation': False}
run_test(para... |
_node_type()
class DipoleSource(optplan.EmSource):
type = schema_utils.polymorphic_model_type('source.dipole_source')
position = optplan.vec3d()
axis = types.IntType()
phase = types.FloatType()
power = types.FloatType()
normalize_by_sim = types.BooleanType(default=False) |
class Baseline(abc.ABC):
def __init__(self, env_spec):
self._mdp_spec = env_spec
def get_param_values(self):
def set_param_values(self, flattened_params):
def fit(self, paths):
def predict(self, path):
def log_diagnostics(self, paths): |
class BaseWaterRetention(NonLinearModel):
def plot(self, ax=None):
import matplotlib.pyplot as plt
if (ax is None):
plt.figure()
ax = plt.subplot(111)
h = (- np.logspace((- 2), 3, 1000))
ax.semilogx((- h), self(h))
ax.set_title('Water retention curve')... |
def getEncryptionKey(data, key):
cipher = AES.new(key, AES.MODE_CBC, IV)
return cipher.encrypt(pad(data, AES.block_size)) |
def mp_fn(_: int, cfg: PretrainConfig) -> None:
torch.set_default_tensor_type('torch.FloatTensor')
xpretrain(cfg) |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--model_type', default=None, type=str, required=True, help=('Model type selected in the list: ' + ', '.join(MODEL_CLASSES.keys())))
parser.add_argument('--model_name_or_path', default=None, type=str, required=True, help=('Path to pre-traine... |
def load_i3d_pretrained(device=torch.device('cpu')):
from fvd.pytorch_i3d import InceptionI3d
i3d = InceptionI3d(400, in_channels=3).to(device)
filepath = download(_I3D_PRETRAINED_ID, 'i3d_pretrained_400.pt')
i3d.load_state_dict(torch.load(filepath, map_location=device))
i3d.eval()
return i3d |
class Conv2d(_ConvNd):
__doc__ = (('Applies a 2D convolution over an input signal composed of several input\n planes.\n\n In the simplest case, the output value of the layer with input size\n :math:`(N, C_{\\text{in}}, H, W)` and output :math:`(N, C_{\\text{out}}, H_{\\text{out}}, W_{\\text{out}})`\n ca... |
def test_drop_overlapping_pitch_bends() -> None:
note_events_with_pitch_bends = [(0.0, 0.1, 60, 1.0, None), (2.0, 2.1, 62, 1.0, [0, 1, 2]), (2.0, 2.1, 64, 1.0, [0, 1, 2]), (1.0, 1.1, 65, 1.0, [0, 1, 2]), (1.1, 1.2, 67, 1.0, [0, 1, 2]), (3.0, 3.2, 69, 1.0, [0, 1, 2]), (3.1, 3.3, 71, 1.0, [0, 1, 2]), (5.0, 5.1, 72, 1... |
class TestBloomWindowService():
TEST_TOKEN_IDS: List[int] = [2175, 27149, 613, 30469, 664, 16289, 168358, 375, 12990, 76143, 12, 632, 660, 168734, 1912, 51298, 34181, 1800, 461, 368, 112640, 31036, 613, 22256, 7833, 21830, 376, 200008, 116891, 375, 43, 19540, 12, 861, 83174, 427, 5219, 20079, 136458, 361, 368, 1258... |
def filter_collate(batch):
if isinstance(batch, list):
batch = [i for i in batch if (i is not None)]
elem_type = type(batch[0])
if isinstance(batch[0], torch.Tensor):
out = None
if _use_shared_memory:
numel = sum([x.numel() for x in batch])
storage = batch[0].... |
def register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Packet__gt___Ns3Ipv6Address_Ns3Ipv6Address_Unsigned_char_Ns3Ptr__lt__ns3Ipv6Route__gt___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::CallbackImpl< void, ns3::Ptr< ns3::Packet >, ns3::Ipv6... |
class CosineAnnealingWarmRestarts(_LRScheduler):
def __init__(self, optimizer, T_0, T_mult=1, eta_min=0, last_epoch=(- 1), verbose=False):
if ((T_0 <= 0) or (not isinstance(T_0, int))):
raise ValueError('Expected positive integer T_0, but got {}'.format(T_0))
if ((T_mult < 1) or (not isi... |
_function_dispatch(_pv_dispatcher)
def pv(rate, nper, pmt, fv=0, when='end'):
when = _convert_when(when)
(rate, nper, pmt, fv, when) = map(np.asarray, [rate, nper, pmt, fv, when])
temp = ((1 + rate) ** nper)
fact = np.where((rate == 0), nper, (((1 + (rate * when)) * (temp - 1)) / rate))
return ((- (... |
def standard_confusion_matrix(y_test, y_test_pred):
[[tn, fp], [fn, tp]] = confusion_matrix(y_test.cpu().numpy(), y_test_pred)
return np.array([[tp, fp], [fn, tn]]) |
def _handle_boundaries(schema: dict[(str, Any)]) -> dict[(str, Any)]:
for (boundary_name, boundary_exclusive_name) in (('maximum', 'exclusiveMaximum'), ('minimum', 'exclusiveMinimum')):
value = schema.get(boundary_exclusive_name)
if (isinstance(value, (int, float)) and (not isinstance(value, bool)))... |
def weighted_signal_distortion_ratio_loss(output, bd):
y = bd['y']
z = bd['z']
y_hat = output
z_hat = (bd['x'] - y_hat)
y_norm = torch.norm(y, dim=(- 1)).squeeze(1)
z_norm = torch.norm(z, dim=(- 1)).squeeze(1)
y_hat_norm = torch.norm(y_hat, dim=(- 1)).squeeze(1)
z_hat_norm = torch.norm(z... |
class StarReLU(nn.Module):
def __init__(self, scale_value=1.0, bias_value=0.0, scale_learnable=True, bias_learnable=True, mode=None, inplace=False):
super().__init__()
self.inplace = inplace
self.relu = nn.ReLU(inplace=inplace)
self.scale = nn.Parameter((scale_value * torch.ones(1)),... |
def get_dataset(imagenet_stats=False, resize=224, scale=None, offset=None):
if imagenet_stats:
norm_layer = get_normalization_layer(imagenet_stats)
elif (scale and offset):
norm_layer = get_normalization_layer(imagenet_stats, scale, offset)
else:
norm_layer = get_normalization_layer(... |
def print_perform(ref, pred):
print('BLEU: {:.3f}, F1: {:.2f}, Distinct-1: {:.2f}, Distinct-2: {:.2f}'.format(eval_bleu(ref, pred), (eval_f1(ref, pred) * 100), eval_distinct(pred, 1), eval_distinct(pred, 2)), end=' ')
print('BLEU 1, 2, 3, 4: {}'.format(eval_bleu_detail(ref, pred)), end=' ')
print('Entropy-1... |
class AttentionBlock(nn.Module):
def __init__(self, channels: int, num_head_channels: Optional[int]=None, num_groups: int=32, rescale_output_factor: float=1.0, eps: float=1e-05):
super().__init__()
self.channels = channels
self.num_heads = ((channels // num_head_channels) if (num_head_channe... |
def dropnoise(fd):
foutt2s = []
for d in fd:
diffi = d.strip().split()
winsize = 1
ndups = ((len(diffi) // 8) if (winsize == 1) else (len(diffi) // 11))
if ((ndups != 0) and (len(diffi) != 0)):
idces = set(np.random.choice(len(diffi), size=(ndups,), replace=False))
... |
def save_model(model, directory, metadata=None, filename=MODEL_FILENAME):
device = next(model.parameters()).device
model.cpu()
if (metadata is None):
metadata = dict(img_size=model.img_size, latent_dim=model.latent_dim, model_type=model.model_type)
save_metadata(metadata, directory)
path_to_... |
def save_chunks_speaker(spkr):
print(spkr)
audio = combine((__CORPUSPATH__ + spkr))
chunks = split(audio)
save_chunks(chunks, (__OUTPATH__ + spkr)) |
class ScionRouter(Router):
__interfaces: Dict[(int, Dict)]
__next_port: int
def __init__(self):
super().__init__()
self.initScionRouter()
def initScionRouter(self):
self.__interfaces = {}
self.__next_port = 50000
def addScionInterface(self, ifid: int, iface: Dict) -> ... |
class RandomShortPoleCartPole(ModifiableCartPoleEnv):
def __init__(self):
super(RandomShortPoleCartPole, self).__init__()
self.length = uniform_exclude_inner(self.np_random.uniform, self.EXTREME_LOWER_LENGTH, self.EXTREME_UPPER_LENGTH, self.RANDOM_LOWER_LENGTH, self.RANDOM_UPPER_LENGTH)
self... |
class StringMatchToken(ElementSetToken):
def __init__(self, token, classes=None):
super(StringMatchToken, self).__init__(classes)
assert (token.return_type == unicode)
self._token = token
def _execute(self, env):
s = self._token.execute(env)
processed_s = strip_whitespace... |
def main(args):
print('Loading models...')
TOKENIZER_GPT2 = load_tokenizer_for_causal_lm('gpt2')
MODEL_GPT2 = load_model_for_causal_lm('gpt2', device)
MODEL_GPT2_XL = load_model_for_causal_lm('gpt2-xl', device)
print('GPT2 and GPT2-XL models loaded!')
seq_len = 256
logits_warper = LogitsProc... |
def CreateGemmPlanarComplexOperator(manifest, layouts, tile_descriptions, data_type, alignment_constraints, complex_transforms):
if (complex_transforms is None):
complex_transforms = [(ComplexTransform.none, ComplexTransform.none)]
(element_a, element_b, element_c, element_epilogue) = data_type
gemm... |
class BaseImagePipeline(ABC):
def __init__(self, output_image_size: int, extra_pixels: int=0):
self.output_image_size = output_image_size
self.extra_pixels = extra_pixels
def get_image_input_size(self) -> int:
raise NotImplemented
def image_input_manipulation(self, images: Any) -> An... |
class Semeval2016Dataset(datasets.GeneratorBasedBuilder):
VERSION = datasets.Version('1.1.0')
BUILDER_CONFIGS = [datasets.BuilderConfig(name='semeval2016', version=VERSION, description='Trinary sentiment task on English Twitter data.')]
def _info(self):
return datasets.DatasetInfo(description=_DESCR... |
class Test__StripWhitespace(unittest.TestCase):
sql = 'INSERT INTO dir_entries(type)VALUES(:type);\n\n INSERT INTO directories(inode)\n VALUES(:inode)\n LIMIT 1'
sql2 = 'SELECT child_entry,asdf AS inode, creation\n FROM links\n WHERE par... |
def get_data_loader(train_examples, label_list, max_seq_length, tokenizer, batch_size, sampler):
train_features = convert_examples_to_features(train_examples, label_list, max_seq_length, tokenizer)
all_input_ids = torch.tensor([f.input_ids for f in train_features], dtype=torch.long)
all_input_mask = torch.t... |
class ResnetGenerator(nn.Module):
def __init__(self, input_nc, output_nc, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False, n_blocks=6, padding_type='reflect'):
assert (n_blocks >= 0)
super(ResnetGenerator, self).__init__()
if (type(norm_layer) == functools.partial):
use_bias... |
('pb_scaffold')
class PropBankScaffoldSpanSrl(Model):
def __init__(self, vocab: Vocabulary, text_field_embedder: TextFieldEmbedder, stacked_encoder: Seq2SeqEncoder, span_feedforward: FeedForward, binary_feature_dim: int, max_span_width: int, binary_feature_size: int, distance_feature_size: int, embedding_dropout: f... |
class RobertaForSequenceClassification(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class FederatedFastEstimator():
def __init__(self, estimator, override_config: dict=None, **kwargs):
self.estimator = estimator
self.logger = getLogger(__name__)
fx.init(**kwargs)
if override_config:
fx.update_plan(override_config)
def fit(self):
import fastes... |
class CGP(object):
def __init__(self, net_info, eval_func, lam=4, imgSize=32, init=False):
self.lam = lam
self.pop = [Individual(net_info, init) for _ in range((1 + self.lam))]
self.eval_func = eval_func
self.num_gen = 0
self.num_eval = 0
self.max_pool_num = int((math... |
def _and_then(t1, t2, ctx=None):
t1 = _to_tactic(t1, ctx)
t2 = _to_tactic(t2, ctx)
if z3_debug():
_z3_assert((t1.ctx == t2.ctx), 'Context mismatch')
return Tactic(Z3_tactic_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx) |
_class
class VELoss():
def __init__(self, sigma_min=0.02, sigma_max=100, warmup_ite=None):
self.sigma_min = sigma_min
self.sigma_max = sigma_max
self.warmup_ite = warmup_ite
self.clamp_cur = 5.0
self.clamp_max = 500.0
if self.warmup_ite:
self.warmup_step =... |
def one_direction_rnn(tensor_rep, mask_rep, hn, cell_type, only_final=False, wd=0.0, keep_prob=1.0, is_train=None, is_forward=True, scope=None):
assert (not is_forward)
with tf.variable_scope(((scope or ('%s_rnn' % 'forward')) if is_forward else 'backward')):
reuse = (None if (not tf.get_variable_scope(... |
def r_repeat(t):
(cste, stmt) = (t[1], t[3])
def fn(world, n):
if (n > MAX_FUNC_CALL):
return (world, n, False)
n += 1
s = True
for _ in range(cste()):
(world, n, s) = stmt(world, n)
if (not s):
return (world, n, s)
retu... |
class ProbeObj(ctypes.c_void_p):
def __init__(self, probe):
self._as_parameter_ = probe
def from_param(obj):
return obj |
def saveVocabulary(name, vocab, file):
print((((('Saving ' + name) + " vocabulary to '") + file) + "'..."))
vocab.writeFile(file) |
(repr=False)
class GraphQLCase(Case):
def as_requests_kwargs(self, base_url: (str | None)=None, headers: (dict[(str, str)] | None)=None) -> dict[(str, Any)]:
final_headers = self._get_headers(headers)
base_url = self._get_base_url(base_url)
kwargs: dict[(str, Any)] = {'method': self.method, ... |
def variableFromSentence(lang, sentence):
indexes = indexesFromSentence(lang, sentence)
indexes.append(EOS_token)
result = Variable(torch.LongTensor(indexes).view((- 1), 1))
if use_cuda:
return result.cuda()
else:
return result |
def mutual_info(prob):
m1 = np.sum(prob, axis=0, keepdims=True)
m2 = np.sum(prob, axis=1, keepdims=True)
m = (m1 * m2)
return np.sum((prob * np.log(((prob / (m + EPS)) + EPS)))) |
def init_process(backend='nccl'):
print(f'Starting process with rank {ptu.dist_rank}...', flush=True)
dist.init_process_group(backend, rank=ptu.dist_rank, world_size=ptu.world_size)
print(f'Process {ptu.dist_rank} is connected.', flush=True)
dist.barrier()
silence_print((ptu.dist_rank == 0))
if ... |
def add_params(size, name=''):
if (len(size) == 1):
print((((('vector ' + name) + ': ') + str(size[0])) + '; uniform in [-0.1, 0.1]'))
else:
print((((((('matrix ' + name) + ': ') + str(size[0])) + ' x ') + str(size[1])) + '; uniform in [-0.1, 0.1]'))
size_int = tuple([int(ss) for ss in size]... |
def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
return attention_mask |
def setup_very_basic_config(color=True):
plain_formatter = logging.Formatter('%(asctime)s | %(levelname)s | %(name)s : %(message)s', datefmt='%Y-%m-%dT%H:%M:%S')
ch = logging.StreamHandler(stream=sys.stdout)
ch.setLevel(logging.INFO)
if color:
formatter = ColorfulFormatter((colored('%(asctime)s ... |
def write_planar(img, planar_path):
planar_file = open(planar_path, 'wb')
for cha in img:
(h, w) = cha.shape
for ih in range(h):
for iw in range(w):
planar_file.write(cha[(ih, iw)])
planar_file.close() |
def update_flags(flags):
if (flags.input_width is None):
flags.input_width = flags.input_height
if (flags.output_width is None):
flags.output_width = flags.output_height
flags.batch_size = 1
path = os.path.join(flags.outputsroot, flags.name)
setattr(flags, 'checkpoint_dir', os.path.j... |
def test_reset(objectives):
archive = CoverageArchive(objectives)
archive.reset()
assert (archive.uncovered_goals == objectives)
assert (archive.covered_goals == OrderedSet())
assert (archive.solutions == OrderedSet()) |
class FreezeWeights(Layer):
def call(self, inputs):
inputs['encoder_output'] = K.stop_gradient(inputs['encoder_output'])
return inputs |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.