code stringlengths 101 5.91M |
|---|
class IntLayerNorm(nn.Module):
def __init__(self, normalized_shape, eps, output_bit=8, quant_mode=False, force_dequant='none'):
super().__init__()
self.normalized_shape = normalized_shape
self.eps = eps
self.weight = nn.Parameter(torch.zeros(normalized_shape))
self.bias = nn.... |
class ChunkingIterDataPipe(torch.utils.data.IterDataPipe):
def __init__(self, dataset: torch.utils.data.IterableDataset, chunking, *, min_chunk_size=0):
super().__init__()
from returnn.datasets.basic import Dataset as ReturnnDataset
self._dataset = dataset
(self._chunk_size, self._ch... |
def convert_3d_images_to_uint8(images, drange=[(- 1), 1], nchwd_to_nhwdc=False, shrink=1):
images = tf.cast(images, tf.float32)
if (shrink > 1):
ksize = [1, 1, shrink, shrink, shrink]
images = tf.nn.avg_pool(images, ksize=ksize, strides=ksize, padding='VALID', data_format='NCHWD')
if nchwd_t... |
class AttnPlainNet(nn.Module):
def __init__(self, feat_len, num_class, hidden=[10, 10], dropout=[0, 0]):
super(AttnPlainNet, self).__init__()
self.feat1 = FeatBrd1d(in_channels=1, out_channels=hidden[0])
self.acvt1 = nn.Sequential(nn.BatchNorm1d(hidden[0]), nn.Softsign(), nn.Dropout(dropout[... |
def support_sz(sz):
def wrapper(f):
f.support_sz = sz
return f
return wrapper |
def parse_memlet_subset(array: data.Data, node: Union[(ast.Name, ast.Subscript)], das: Dict[(str, Any)], parsed_slice: Any=None) -> Tuple[(subsets.Range, List[int], List[int])]:
ndslice = [(0, (s - 1), 1) for s in array.shape]
extra_dims = []
arrdims: Dict[(int, str)] = {}
if isinstance(node, ast.Subscr... |
def torch_nn_conv1d(self, input):
l_in = input.shape[(- 1)]
shape = None
padding = self.padding
if (padding == 'valid'):
padding = (0, 0)
if (padding == 'same'):
shape = list(input.shape)
if (shape is None):
shape = list(input.shape)
l_out = math.floor((((((l_in +... |
def parse_options(option, name, value, parser):
dest = option.dest
options = dict(getattr(parser.values, dest, {}))
for opt in value.split(','):
if ('=' in opt):
(n, v) = opt.split('=', 1)
v = (v.lower() not in ('false', 'f', '0', 'no'))
else:
(n, v) = (op... |
class TestF77ReturnInteger(TestReturnInteger):
code = '\n function t0(value)\n integer value\n integer t0\n t0 = value\n end\n function t1(value)\n integer*1 value\n integer*1 t1\n t1 = value\n end\n function t2(value)\n integer*2... |
def evaluate_weighting(dpr_dict, bm25_dict, qrels, output_dir, output_file, weight_dpr, weight_bm25, measurements):
run = {}
for query_id in dpr_dict.keys():
run.update({query_id: {}})
for doc in dpr_dict.get(query_id).keys():
run.get(query_id).update({doc: (weight_dpr * dpr_dict.get... |
class Normalize(nn.Module):
def __init__(self):
super(Normalize, self).__init__()
def forward(self, input):
return ((input - 0.5) / 0.5) |
def _impl(x, weight, ddof, axis, keepdims, mask_identity, highlevel, behavior, attrs):
axis = regularize_axis(axis)
with HighLevelContext(behavior=behavior, attrs=attrs) as ctx:
(x_layout, weight_layout) = ensure_same_backend(ctx.unwrap(x, allow_record=False, primitive_policy='error'), ctx.unwrap(weight... |
class CaffeTransformer(ModelTransformer):
def __init__(self, model_name, model_def, model_data, input_shapes: list=[], output_names: list=[], preprocessor: dict={}):
super().__init__(model_name, model_def)
self.model_data = model_data
from transform.CaffeConverter import CaffeConverter
... |
def get_fuzzer_files(fuzzer: Fuzzer) -> Tuple[(List[Path], List[Path])]:
global ARGS
coverage_files = []
crash_files = []
fuzzer_root_dir = get_fuzzer_root(fuzzer)
assert fuzzer_root_dir
if (not fuzzer_root_dir.exists()):
return ([], [])
assert fuzzer_root_dir
if utils.fuzzer_has... |
class Payload(object):
def __init__(self, msg):
self._msg = msg
def raw(self):
return self._msg.payloadBytes[:]
def mic(self):
return None
def _calculateMIC(self):
return None
def verifyMIC(self):
currentMIC = self.mic
if (currentMIC is None):
... |
class PAM_Module(nn.Module):
def __init__(self, in_dim):
super(PAM_Module, self).__init__()
self.chanel_in = in_dim
self.query_conv = nn.Conv2d(in_channels=in_dim, out_channels=(in_dim // 8), kernel_size=1)
self.key_conv = nn.Conv2d(in_channels=in_dim, out_channels=(in_dim // 8), ker... |
def make_open3d_registration_feature(data):
feats = o3d.pipelines.registration.Feature()
feats.data = data.T
return feats |
def get_vmaf_test_sequence(frame_numbers: List[int]):
assert (len(camera_configs['siggraph_vmaf']) == 1)
return list(zip(itertools.repeat(camera_configs['siggraph_vmaf'][0]), frame_numbers[::3])) |
def load_data(args):
questions = []
answers = []
decoder = json.JSONDecoder()
if (args.dataset == 'gsm8k'):
with open(args.dataset_path) as f:
lines = f.readlines()
for line in lines:
json_res = decoder.raw_decode(line)[0]
questions.append(... |
class RAFT(nn.Module):
def __init__(self, args):
super(RAFT, self).__init__()
self.args = args
if args.small:
self.hidden_dim = hdim = 96
self.context_dim = cdim = 64
args.corr_levels = 4
args.corr_radius = 3
else:
self.hidd... |
class FixedBatchSizeBatchSampler():
def __init__(self, data_source, batch_size: int, shuffle: bool=False, seed: int=) -> None:
self.batch_size = batch_size
self.seed = seed
self.shuffle = shuffle
if shuffle:
self.generator = torch.Generator()
self.sampler = Ra... |
def read_answers(gold_file):
answers = {}
with tf.io.gfile.GFile(gold_file, 'r') as f:
for (i, line) in enumerate(f):
example = json.loads(line)
if ((i == 0) and ('header' in example)):
continue
for qa in example['qas']:
answers[qa['qid... |
_utils.test(arch=supported_archs_taichi_ndarray)
def test_different_shape():
n1 = 4
x = ti.ndarray(dtype=ti.f32, shape=(n1, n1))
def init(d: ti.i32, arr: ti.types.ndarray()):
for (i, j) in arr:
arr[(i, j)] = d
init(2, x)
assert (x.to_numpy() == (np.ones(shape=(n1, n1)) * 2)).all(... |
def imconvert(img, src, dst):
code = getattr(cv2, f'COLOR_{src.upper()}2{dst.upper()}')
out_img = cv2.cvtColor(img, code)
return out_img |
class TestLeftMatrixMinimization(unittest.TestCase):
def test_minimize(self):
power_signals_d = np.array([[0.0, 0.0, 0.0, 0.0], [1., 1., 0., 0.], [1., 1., 1., 1.], [1., 1., 1., 0.]])
rank_k = 4
weights = np.array([0.0, 0.0, 0., 0.])
tau = 0.9
mu_l = 500.0
initial_l_cs... |
class PQLinear(nn.Module):
def __init__(self, centroids, assignments, bias, in_features, out_features):
super(PQLinear, self).__init__()
self.block_size = centroids.size(1)
self.n_centroids = centroids.size(0)
self.in_features = in_features
self.out_features = out_features
... |
class InventoryManagementSystemTrackInventory(VirtualFunctionTool):
name = 'InventoryManagementSystemTrackInventory'
summary = 'Track inventory levels and receive notifications when stock levels are low.'
parameters: List[ArgParameter] = [{'name': 'threshold', 'type': 'integer', 'description': 'The stock le... |
def mutate_size_func(info):
def mutate_size_func(parent_arch):
child_arch = deepcopy(parent_arch)
child_arch = child_arch.split(':')
index = random.randint(0, (len(child_arch) - 1))
child_arch[index] = str(random.choice(info['candidates']))
return ':'.join(child_arch)
ret... |
class CompositionFilter(Filter):
def __init__(self, fs):
self.fs = fs
def __call__(self, x, update=True):
for f in self.fs:
x = f(x)
return x
def output_shape(self, input_space):
out = input_space.shape
for f in self.fs:
out = f.output_shape(ou... |
def Conv1x1BNReLU(in_channels, out_channels):
return nn.Sequential(nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=1), nn.BatchNorm2d(out_channels), nn.ReLU(inplace=True)) |
def _read_fmt_chunk(fid, is_big_endian):
if is_big_endian:
fmt = '>'
else:
fmt = '<'
size = res = struct.unpack((fmt + 'I'), fid.read(4))[0]
bytes_read = 0
if (size < 16):
raise ValueError('Binary structure of wave file is not compliant')
res = struct.unpack((fmt + 'HHIIH... |
def evaluate_model(model, config, _logger, cuda_device, eval_tsv, eval_batch_count, use_cache=False):
model.eval()
validation_results = {}
fill_cache = False
cached_batches = None
try:
if use_cache:
global evaluate_cache
if (eval_tsv not in evaluate_cache):
... |
('grammar', 'idiom_ast')
class IdiomAstGrammar():
def __init__(self, base_grammar, template_file, root_type=None, all_sections_rewritten=False):
self.base_grammar = registry.construct('grammar', base_grammar)
self.templates = json.load(open(template_file))
self.all_sections_rewritten = all_s... |
class SAUNet(nn.Module):
def __init__(self, num_classes=4, num_filters=32, pretrained=True, is_deconv=True):
super(SAUNet, self).__init__()
self.num_classes = num_classes
print('SAUNet w/ Shape Stream')
self.pool = nn.MaxPool2d(2, 2)
self.encoder = torchvision.models.densenet... |
def log_agent(agent, file_path):
question = agent.question
g_truth = agent.key
correct = agent.is_correct()
reward = agent.reward()[0]
halted = agent.is_halted()
error = agent.run_error
prompt = agent._build_agent_prompt()
save_dict = {'question': question, 'answer': g_truth, 'correct': ... |
def _format(val: Any, output_format: str='standard', split: bool=False, errors: str='coarse') -> Any:
val = str(val)
result: Any = []
if (val in NULL_VALUES):
return [np.nan]
if (not validate_ean(val)):
if (errors == 'raise'):
raise ValueError(f'Unable to parse value {val}')
... |
def DFG_python(root_node, index_to_code, states):
assignment = ['assignment', 'augmented_assignment', 'for_in_clause']
if_statement = ['if_statement']
for_statement = ['for_statement']
while_statement = ['while_statement']
do_first_statement = ['for_in_clause']
def_statement = ['default_paramete... |
class CustomModel(torch.nn.Module):
def __init__(self, input_size, rnn_size=256, projection=128, layers=2):
super().__init__()
self.layers = torch.nn.ModuleList()
for i in range(layers):
self.layers.append(torch.nn.LSTM(input_size=(input_size if (i == 0) else projection), hidden_... |
def UniversalTransformerEncoderWithLayer(layer=TransformerEncoderLayer):
return (lambda *args, **kwargs: UniversalTransformerEncoder(layer, *args, **kwargs)) |
class _Simplex(Constraint):
def check(self, value):
return ((value >= 0).all() & ((value.sum((- 1), True) - 1).abs() < 1e-06).all()) |
class cd():
def __init__(self, newPath):
self.newPath = newPath
def __enter__(self):
self.savedPath = os.getcwd()
os.chdir(self.newPath)
def __exit__(self, etype, value, traceback):
os.chdir(self.savedPath) |
def QDM_45_7_1_1_9():
from sage.rings.finite_rings.integer_mod_ring import IntegerModRing as AdditiveCyclic
G = AdditiveCyclic(45)
M = [[None, None, None, None, None, None, None, None, None], [0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 27, 16, 7, (- 1), (- 27), (- 16), (- 7), 3], [24, 40, 1, 35, (- 24), (- 40), (- 1),... |
def superconduct(wd):
df = pd.read_csv((wd + 'superconduct.csv'), header=None)
df.columns = ([('X_' + str(i)) for i in range((len(df.columns) - 1))] + ['y'])
return df |
def check_sampling_strategy(sampling_strategy, y, sampling_type, **kwargs):
if (sampling_type not in SAMPLING_KIND):
raise ValueError(f"'sampling_type' should be one of {SAMPLING_KIND}. Got '{sampling_type} instead.")
if (np.unique(y).size <= 1):
raise ValueError(f"The target 'y' needs to have m... |
def test_landscape():
bds = np.array([[1, 1], [1, 2]])
ldsp = PersImage.to_landscape(bds)
np.testing.assert_array_equal(ldsp, [[1, 0], [1, 1]]) |
class OnsagerAlgebra(LieAlgebraWithGenerators, IndexedGenerators):
def __init__(self, R):
cat = LieAlgebras(R).WithBasis()
from sage.sets.finite_enumerated_set import FiniteEnumeratedSet
IndexedGenerators.__init__(self, FiniteEnumeratedSet([0, 1]))
LieAlgebraWithGenerators.__init__(s... |
def simGetObjectMatrix(objectHandle, relativeToObjectHandle):
matrix = ffi.new('float[12]')
ret = lib.simGetObjectMatrix(objectHandle, relativeToObjectHandle, matrix)
_check_return(ret)
return list(matrix) |
class TestCaseCoverageFunction(TestCaseChromosomeComputation, CoverageFunction, metaclass=abc.ABCMeta): |
def test_gaussian_filter():
data = numpy.array([1], dtype=numpy.float16)
sigma = 1.0
with assert_raises(RuntimeError):
ndimage.gaussian_filter(data, sigma) |
def ttest(A: dace.float32[(M, N, K)], B: dace.float32[(M, N, K)]):
s = np.ndarray(shape=(K, N, M), dtype=np.int32)
t = np.ndarray(A.shape, A.dtype)
for i in dace.map[0:M]:
for j in dace.map[0:N]:
for k in dace.map[0:K]:
s[(k, j, i)] = t[(i, j, k)]
t[(i, j,... |
def preprocess_for_lm(sources: Sequence[str], tokenizer: transformers.PreTrainedTokenizer) -> Dict:
assert (conversation_lib.default_conversation.version not in ('v1', 'mpt'))
conversations = []
for source in sources:
header = DEFAULT_CONVERSATION_HEADER
conversation = sentences_to_formatted... |
def print_hparams(hparams, skip_patterns=None, header=None):
if header:
print_out(('%s' % header))
values = hparams.values()
for key in sorted(values.keys()):
if ((not skip_patterns) or all([(skip_pattern not in key) for skip_pattern in skip_patterns])):
print_out((' %s=%s' % (k... |
def _minimize_level(G):
from sage.groups.matrix_gps.finitely_generated import MatrixGroup
from .congroup_gamma import Gamma_constructor as Gamma
Glist = list(G)
N = G.base_ring().characteristic()
i = Gamma(N).index()
for d in N.divisors()[:(- 1)]:
j = Gamma(d).index()
k = len([g ... |
def check_readme(overwrite=False):
info = LOCALIZED_READMES['README.md']
(models, start_index, end_index, lines) = _find_text_in_file(os.path.join(REPO_PATH, 'README.md'), info['start_prompt'], info['end_prompt'])
models_in_readme = [re.search('\\*\\*\\[([^\\]]*)', line).groups()[0] for line in models.strip... |
class MetaLearner(BaseMetaLearner):
def __init__(self, sampler, policy, baseline, optimizer, gamma=0.95, fast_lr=0.5, tau=1.0):
self.sampler = sampler
self.policy = policy
self.baseline = baseline
self.gamma = gamma
self.fast_lr = fast_lr
self.tau = tau
self.o... |
def plot_SP_histogram_by_class(ax, spcorr, yhat, bins=30):
sprho = np.array([x[0] for x in spcorr])
sppval = np.array([x[1] for x in spcorr])
measures = {'pval_sig': {}, 'mean': {}, 'std': {}}
measures['pval_sig']['Overall'] = '{:.2f}'.format(((sppval <= 0.05).sum() / len(sppval)))
measures['mean'][... |
def _expand_onehot_labels(labels, label_weights, label_channels, ignore_index):
bin_labels = labels.new_full((labels.size(0), label_channels), 0)
valid_mask = ((labels >= 0) & (labels != ignore_index))
inds = torch.nonzero((valid_mask & (labels < label_channels)), as_tuple=False)
if (inds.numel() > 0):
... |
def parse_sql(toks, start_idx, tables_with_alias, schema):
isBlock = False
len_ = len(toks)
idx = start_idx
sql = {}
if (toks[idx] == '('):
isBlock = True
idx += 1
(from_end_idx, table_units, conds, default_tables) = parse_from(toks, start_idx, tables_with_alias, schema)
sql[... |
def convex_combination(classes, TP, TOP, P, class_name, modified=False):
try:
class_number = len(classes)
alpha = 1
if (class_number == 2):
alpha = 0
matrix_sum = sum(list(TOP.values()))
TP_sum = sum(list(TP.values()))
up = (TOP[class_name] + P[class_name]... |
class OAuth2ClientCredentialsAuthorizationDef(BaseDef):
type: str = Field('OAuth2', const=True)
grant_type: str = Field('ClientCredentials', const=True)
token_server_url: str
def build(self, req_data: Dict[(str, Any)], params: Dict[(str, Any)], storage: Optional[Dict[(str, Any)]]=None) -> None:
... |
def get_erased_3D_path_blocks(path, item=AIR):
return {(pos[0], pos[2], pos[1]): item for pos in path} |
def reset_session():
if _is_tf_1():
K.clear_session()
else:
tf.keras.backend.clear_session() |
class PermissionsException(SkyplaneException):
def pretty_print_str(self):
err = f'[bold][red]PermissionsException: {str(self)}[/red][/bold]'
return err |
def extract_ljspeech(data_folder, splits, kmeans_folder, encoder, layer, save_folder, sample_rate=16000, skip_extract=False):
logger = setup_logger()
if skip_extract:
return
conf = {'data_folder': data_folder, 'splits': splits, 'save_folder': save_folder, 'kmeans_folder': kmeans_folder, 'encoder': e... |
def test__reset_cache_for_result():
test_case = MagicMock()
result = MagicMock(test_case_chromosomes=[test_case])
with mock.patch.object(test_case, 'invalidate_cache') as test_case_cache_mock:
with mock.patch.object(test_case, 'remove_last_execution_result') as test_case_result_mock:
wit... |
def save_dataset(dataset: xr.Dataset, outdir: os.PathLike, use_hdf5: Optional[bool]=True, job_type: Optional[str]=None, **kwargs) -> Path:
if use_hdf5:
fname = ('dataset.h5' if (job_type is None) else f'{job_type}_data.h5')
outfile = Path(outdir).joinpath(fname)
try:
dataset_to_h... |
def lower_abbreviation_in_string(string_to_format: str):
tokens_opening = string_to_format.split('[')
valid_string = True
final_string = tokens_opening[0]
for tok in tokens_opening[1:]:
if (len(tok) > 1):
token_closing = tok.split(']')
if (len(token_closing) == 2):
... |
class SENet(nn.Module):
def __init__(self, channel, type_of_connection=BasicLearningBlock):
super(SENet, self).__init__()
self.attention = SEBlock(channel, 16)
def forward(self, feature, mask):
(_, _, w, _) = feature.size()
(_, _, mw, _) = mask.size()
mask = torch.round(F... |
class RouterNetTopo(Topo):
ALL_GROUP = 'groups'
ASYNC = 'async'
BSM_NODE = 'BSMNode'
GROUP = 'group'
IP = 'ip'
IS_PARALLEL = 'is_parallel'
LOOKAHEAD = 'lookahead'
MEET_IN_THE_MID = 'meet_in_the_middle'
MEMO_ARRAY_SIZE = 'memo_size'
PORT = 'port'
PROC_NUM = 'process_num'
Q... |
def __getattr__(name):
return _sub_module_deprecation(sub_package='constants', module='codata', private_modules=['_codata'], all=__all__, attribute=name) |
def test_Interval():
assert (Interval(0, oo) == Interval(0, oo, False, True))
assert (Interval((- oo), 0) == Interval((- oo), 0, True, False))
assert (Interval(oo, (- oo)) == EmptySet())
assert (Interval(oo, oo) == EmptySet())
assert (Interval((- oo), (- oo)) == EmptySet())
assert isinstance(Int... |
class MLP(torch.nn.Module):
def __init__(self, num_mlp_layers=5, emb_dim=300, drop_ratio=0):
super(MLP, self).__init__()
self.num_mlp_layers = num_mlp_layers
self.emb_dim = emb_dim
self.drop_ratio = drop_ratio
module_list = [torch.nn.Linear(2048, self.emb_dim), torch.nn.Batch... |
def printHistogram(items, title='Items'):
items.sort(key=(lambda item: item[1]))
maxValue = max([v for (_, v) in items])
power = int(math.ceil(math.log(maxValue, 10)))
for inc in itertools.cycle((5, 2, 2.5, 1)):
barH = (inc * (10 ** power))
N = int(math.ceil((maxValue / barH)))
i... |
('/data/<id>', methods=['GET'])
def get_item(id):
response = table.get_item(Key={'id': id})
if ('Item' in response):
return jsonify(response['Item'])
else:
return ('Item not found', 404) |
def dump_candidates_file_for_split(split):
CacheBackend.init_cache_backend('webqsp')
OntologyInfo.init_ontology_info()
if (split == 'test'):
generate_candidate_file('test')
elif (split == 'pdev'):
generate_candidate_file('pdev', use_gt_entities=False, lnk_split='train')
elif (split =... |
def DFG_go(root_node, index_to_code, states):
assignment = ['assignment_statement']
def_statement = ['var_spec']
increment_statement = ['inc_statement']
if_statement = ['if_statement', 'else']
for_statement = ['for_statement']
enhanced_for_statement = []
while_statement = []
do_first_sta... |
def convert_trax_checkpoint_to_pytorch(trax_model_pkl_path, config_file, pytorch_dump_path):
config = ReformerConfig.from_json_file(config_file)
print(f'Building PyTorch model from configuration: {config}')
model = ReformerModelWithLMHead(config)
with open(trax_model_pkl_path, 'rb') as f:
model_... |
_seed
.slow
.parametrize('num_steps, acquisition_rule', [pytest.param(25, DiscreteThompsonSampling(1000, 8), id='DiscreteThompsonSampling'), pytest.param(25, EfficientGlobalOptimization(ParallelContinuousThompsonSampling(), num_query_points=4), id='ParallelContinuousThompsonSampling'), pytest.param(12, EfficientGlobalO... |
def read_train_test_directory_to_image(directory, image_shape=(128, 64)):
reshape_fn = ((lambda x: x) if (image_shape == IMAGE_SHAPE[:2]) else (lambda x: cv2.resize(x, image_shape[::(- 1)])))
(filenames, ids, camera_indices, tracklet_indices) = read_train_test_directory_to_str(directory)
images = np.zeros((... |
class MyDataset(Dataset):
def __init__(self, data, label):
self.data = data
self.label = label
def __getitem__(self, index):
return (torch.tensor(self.data[index], dtype=torch.float), torch.tensor(self.label[index], dtype=torch.long))
def __len__(self):
return len(self.data) |
_module()
class TPNHead(TSNHead):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if (self.spatial_type == 'avg'):
self.avg_pool3d = nn.AdaptiveAvgPool3d((1, 1, 1))
else:
self.avg_pool3d = None
self.avg_pool2d = None
self.new_cls... |
class ResNet(nn.Module):
def __init__(self, block, num_blocks, num_classes=10):
super(ResNet, self).__init__()
self.in_planes = 64
self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.layer1 = self._make_layer(block,... |
def calc_same_padding(kernel_size):
pad = (kernel_size // 2)
return (pad, (pad - ((kernel_size + 1) % 2))) |
def load_original_image(path_images, filename):
jpg_name = Path((str(filename)[:(- 4)] + '.jpg'))
x = open_image((path_images / jpg_name))
return x |
class TFSeq2SeqSequenceClassifierOutput(ModelOutput):
loss: Optional[tf.Tensor] = None
logits: tf.Tensor = None
past_key_values: Optional[List[tf.Tensor]] = None
decoder_hidden_states: Optional[Tuple[tf.Tensor]] = None
decoder_attentions: Optional[Tuple[tf.Tensor]] = None
encoder_last_hidden_sta... |
.skipif(longdouble_longer_than_double, reason='BUG #2376')
.skipif(string_to_longdouble_inaccurate, reason='Need strtold_l')
def test_format():
o = (1 + LD_INFO.eps)
assert_(('{0:.40g}'.format(o) != '1')) |
def build_variated_query(string, ranges_and_utterances):
variated_string = ''
current_ix = 0
for (rng, u) in ranges_and_utterances:
start = rng[START]
end = rng[END]
variated_string += string[current_ix:start]
variated_string += u
current_ix = end
variated_string ... |
.parametrize('value, expected', (('On', True), ('F', False), ('/tmp/cert.pem', '/tmp/cert.pem')))
def test_convert_request_tls_verify(value, expected):
assert (callbacks.convert_boolean_string(None, None, value) == expected) |
class SSLViT(nn.Module):
def __init__(self, cfg):
super(SSLViT, self).__init__()
if ('prompt' in cfg.MODEL.TRANSFER_TYPE):
prompt_cfg = cfg.MODEL.PROMPT
else:
prompt_cfg = None
if ((cfg.MODEL.TRANSFER_TYPE != 'end2end') and ('prompt' not in cfg.MODEL.TRANSFER_... |
def test_sac():
config = make_sac_agent(args=Namespace(env='InvertedPendulum-v2', tb='', parent_folder='/tmp/mrl', layers=(32, 1), num_envs=1, num_eval_envs=1, device='cpu'))
agent = mrl.config_to_agent(config)
agent.train(num_steps=1)
assert (len(agent.eval(num_episodes=1).rewards) == 1) |
def register_conv_template(template: Conversation, override: bool=False):
if (not override):
assert (template.name not in conv_templates), f'{template.name} has been registered.'
conv_templates[template.name] = template |
(gxpacket_spec)
class GXPacket(object):
def __init__(self, location, direction, energy_rf, energy_cmf, nu_rf, nu_cmf, status, shell, time_current):
self.location = location
self.direction = direction
self.energy_rf = energy_rf
self.energy_cmf = energy_cmf
self.nu_rf = nu_rf
... |
def update_config_with_experiment_setting(config: OmegaConf, **kwargs) -> OmegaConf:
if ('k_shots' in kwargs.keys()):
config.project.k_shots = kwargs['k_shots']
if ('runs' in kwargs.keys()):
config.project.runs = kwargs['runs']
if (('coreset_ratio' in kwargs.keys()) and (kwargs['coreset_rati... |
def get_nonspade_norm_layer(opt, norm_type='instance'):
def get_out_channel(layer):
if hasattr(layer, 'out_channels'):
return getattr(layer, 'out_channels')
return layer.weight.size(0)
def add_norm_layer(layer):
nonlocal norm_type
if norm_type.startswith('spectral'):
... |
def save(w, file_name=None, file_write_mode='w', L2norm_fractional_tolerance=1e-10, log_frame=None, shuffle_widths=default_shuffle_widths):
return rpdmb.save(w, file_name=file_name, file_write_mode=file_write_mode, L2norm_fractional_tolerance=L2norm_fractional_tolerance, log_frame=log_frame, shuffle_widths=shuffle_... |
def test_combine_mul_float_tensors():
a_raw = torch.tensor([2.0, 2.0, 2.0])
b_raw = torch.tensor([1.0, 2.0, 3.0])
feature_dim = Dim(3)
a = Tensor(name='a', raw_tensor=a_raw, dims=[feature_dim], dtype='float32')
b = Tensor(name='b', raw_tensor=b_raw, dims=[feature_dim], dtype='float32')
result = ... |
def get_mask_fast(inp: str, bad_words=neg_complex_tokens, min_bad_score=0, aggressive=True):
sentences = [tokenizer.encode(inp, add_special_tokens=True)]
sentences_torch = torch.tensor(sentences)
masks = torch.zeros_like(sentences_torch)
for (sent_id, sent) in enumerate(sentences):
for (first_to... |
_utils.test()
def test_redefining_template_args():
def foo(a: ti.template()):
a = 5
with pytest.raises(ti.TaichiSyntaxError, match='Kernel argument "a" is immutable in the kernel'):
foo(1) |
class NoMask(Layer):
def __init__(self, **kwargs):
super(NoMask, self).__init__(**kwargs)
def build(self, input_shape):
super(NoMask, self).build(input_shape)
def call(self, x, mask=None, **kwargs):
return x
def compute_mask(self, inputs, mask):
return None |
def fht(a, dln, mu, offset=0.0, bias=0.0):
xp = array_namespace(a)
n = a.shape[(- 1)]
if (bias != 0):
j_c = ((n - 1) / 2)
j = xp.arange(n, dtype=xp.float64)
a = (a * xp.exp((((- bias) * (j - j_c)) * dln)))
u = xp.asarray(fhtcoeff(n, dln, mu, offset=offset, bias=bias))
A = _fh... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.