code stringlengths 101 5.91M |
|---|
def test_gh_9608_preserve_array_shape():
def f(x):
return (x ** 2)
def fp(x):
return (2 * x)
def fpp(x):
return 2
x0 = np.array([(- 2)], dtype=np.float32)
(rt, r) = newton(f, x0, fprime=fp, fprime2=fpp, full_output=True)
assert r.converged
x0_array = np.array([(- 2), ... |
class SubsetRandomSampler(Sampler[int]):
indices: Sequence[int]
def __init__(self, indices: Sequence[int], generator=None) -> None:
self.indices = indices
self.generator = generator
def __iter__(self) -> Iterator[int]:
for i in torch.randperm(len(self.indices), generator=self.generat... |
def _compute_support_files(db_dir, tile_id_column, tile_geometry, oa_id_column, oa_geometry, flow_origin_column, flow_destination_column, flow_flows_column):
_check_base_files(db_dir)
print('Generating the processed files - it may take a while....')
print('Reading tessellation....')
try:
tessell... |
class DataLoader(object):
def __init__(self, data_path, tokenizer, args, test=False, cuda=True, batch_size=64):
self.cuda = cuda
self.batch_size = batch_size
self.tokenizer = tokenizer
self.max_len = args.max_len
self.evi_num = args.evi_num
self.threshold = args.thres... |
class LisaCNNModel():
def __new__(self, **kwargs):
return self.build(**kwargs)
def build(img_rows=32, img_cols=32, num_channels=3, n_classes=18, nb_filters=64, input_layer_name=None, custom_input=None):
if (custom_input is not None):
inputs = tf.keras.layers.Input(shape=(img_rows, im... |
def handler(event):
request_id = event['request-id']
address = event['server-address']
port = event['server-port']
repetitions = event['repetitions']
output_bucket = event.get('output-bucket')
times = []
i = 0
socket.setdefaulttimeout(3)
server_socket = socket.socket(socket.AF_INET, ... |
class PreActivationBasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(PreActivationBasicBlock, self).__init__()
self.bn1 = nn.BatchNorm3d(inplanes)
self.conv1 = conv3x3x3(inplanes, planes, stride)
self.bn2 = nn.BatchNorm3d(... |
def p_arg2(p):
(startl, endl) = p.linespan(1)
(startc, endc) = p.lexspan(1)
di = dace.dtypes.DebugInfo(startl, startc, endl, endc)
p[0] = AST_Constant(di, p[1]) |
class WithTransform(CythonTransform, SkipDeclarations):
def visit_WithStatNode(self, node):
self.visitchildren(node, 'body')
pos = node.pos
is_async = node.is_async
(body, target, manager) = (node.body, node.target, node.manager)
node.enter_call = ExprNodes.SimpleCallNode(pos... |
def align(input_file, output_file):
for line in input_file:
fields = line.rstrip().split('\t')
target_chars = ' '.join((str(c) for c in fields[1]))
output_file.write(((fields[0] + '\t') + target_chars))
if (len(fields) == 3):
output_file.write(('\t' + fields[2]))
... |
def Vamos():
E = 'abcdefgh'
CC = {3: ['abcd', 'abef', 'cdef', 'abgh', 'efgh'], 4: [E]}
M = CircuitClosuresMatroid(groundset=E, circuit_closures=CC)
M.rename(('Vamos: ' + repr(M)))
return M |
class CTRLPreTrainedModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def create_arguments(callable: Callable, parser: ArgumentParser, exclude: list=[], prefix: str=''):
arguments_added = [action.dest for action in parser._actions]
parameters = inspect.signature(callable).parameters
for (param_name, param_obj) in parameters.items():
arg_name = (prefix + param_name)
... |
def retrieve_performance(conn):
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cursor.execute(' select *, \n 100 * success / total as success_rate,\n 100 * intent / total as intent_rate,\n 100 * ner / total as ner_rate,\n ... |
class TestGenerator(TestCase):
def _fake_dataset_load(self, tasks, examples):
fake_folder = os.path.join(os.path.dirname(os.path.realpath(__file__)), '../test_data', 'test_task')
data = [[{'image_files': fake_folder, 'states': np.ones((TIME_HORIZON, STATE_SIZE)), 'actions': np.ones((TIME_HORIZON, OU... |
class OpenAIGPTPreTrainedModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class BitMasked(LayoutBuilder):
def __init__(self, dtype, content, valid_when, lsb_order, *, parameters=None, initial=1024, resize=8.0):
self._mask = ak.numba.GrowableBuffer(dtype=dtype, initial=initial, resize=resize)
self._content = content
self._valid_when = valid_when
self._lsb_o... |
class _SimpleDistributionMixin():
def log_prob(self, value):
return self._pdf.log_prob(value)
def expected_data(self):
return self._pdf.expected_data()
def sample(self, sample_shape=()):
return self._pdf.sample(sample_shape) |
def merge_hparams(p1, p2):
params = HParams()
v1 = p1.values()
v2 = p2.values()
for (k, v) in v1.items():
params.add_hparam(k, v)
for (k, v) in v2.items():
params.add_hparam(k, v)
return params |
def element2Object(element):
ctxObj = {}
for key in element:
ctxObj[key] = element[key]
return ctxObj |
def test_load_annotation():
annotation_path = 'tests/resources/sound_datasets/dataset/annotation/some_id.pv'
annotation_data = example.load_annotation(annotation_path)
assert (type(annotation_data) == 'some_annotation_type')
assert (type(annotation_data.times) is np.ndarray)
assert np.array_equal(an... |
def load_dataset(args, **kwargs):
if (args.dataset == 'mnist'):
(train_loader, val_loader, test_loader, args) = load_static_mnist(args, **kwargs)
elif (args.dataset == 'caltech'):
(train_loader, val_loader, test_loader, args) = load_caltech101silhouettes(args, **kwargs)
elif (args.dataset ==... |
class AutoModelForTokenClassification():
def __init__(self, *args, **kwargs):
requires_pytorch(self)
def from_pretrained(self, *args, **kwargs):
requires_pytorch(self) |
def train_step():
model.train()
model.zero_grad()
(data, label) = data_call(args.batch_size, args.gt_rules, args.data_seed)
data = torch.Tensor(data).to(device)
label = torch.Tensor(label).to(device)
(out, score) = model(data)
loss = criterion(out, label)
loss.backward()
optimizer.st... |
def _leading_trailing(a, edgeitems, index=()):
axis = len(index)
if (axis == a.ndim):
return a[index]
if (a.shape[axis] > (2 * edgeitems)):
return concatenate((_leading_trailing(a, edgeitems, (index + np.index_exp[:edgeitems])), _leading_trailing(a, edgeitems, (index + np.index_exp[(- edgeit... |
class LeanDescContext():
simplifier: Optional[LeanExprSimplifier]
cairo_type: Optional[CairoType]
struct_defs: LeanStructDefs
identifiers: IdentifierManager
func_scope: Optional[ScopedName]
open_namespaces: List[ScopedName]
div_var_basename: str = '0_'
div_var_startnum: int = 0
local... |
class TestIf(test_util.TestCase):
def testIf(self):
W_a_values = [2.0, 1.5]
B_a_values = [0.5]
W_b_values = [7.0, 3.5]
B_b_values = [1.5]
with NetBuilder(_use_control_ops=True) as init_nb:
W_a = ops.UniformFill([], 'W_a', shape=[1, 2], min=(- 1.0), max=1.0)
... |
.parametrize('tdf', [tdf_test])
def test_plot_stops_tdf(tdf):
map_f = tdf.plot_trajectory()
stdf = detection.stay_locations(tdf)
map_f = stdf.plot_stops(map_f=map_f)
assert isinstance(map_f, folium.folium.Map) |
def calc_scoot(real, fake, level=6, N_blocks=4):
assert (real.size == fake.size)
x_dim = np.floor((real.size[0] / 4)).astype(int)
y_dim = np.floor((real.size[1] / 4)).astype(int)
real_patches = []
fake_patches = []
for i in range(N_blocks):
for j in range(N_blocks):
real_patc... |
def load_reuters():
data_home = get_data_home()
train_file = os.path.join(data_home, 'reuters', 'money-fx.trn')
test_file = os.path.join(data_home, 'reuters', 'money-fx.tst')
return _load(train_file, test_file, 'reuters') |
class WasserstienGAN(GAN):
def __init__(self, z_dim, crop_image_size, resized_image_size, batch_size, data_dir, clip_values=((- 0.01), 0.01), critic_iterations=5):
self.critic_iterations = critic_iterations
self.clip_values = clip_values
GAN.__init__(self, z_dim, crop_image_size, resized_ima... |
class TestSequenceBatch(object):
def sequences(self):
return [['a', 'b', 'b', 'c'], ['c'], []]
def vocab(self):
return SimpleVocab(['<unk>', 'a', 'b', 'c', '<start>', '<stop>'])
def test_from_sequences(self, sequences, vocab):
seq_batch = SequenceBatch.from_sequences(sequences, vocab... |
('mmdet.apis.single_gpu_test', MagicMock)
('mmdet.apis.multi_gpu_test', MagicMock)
.parametrize('EvalHookParam', (EvalHook, DistEvalHook))
def test_evaluation_hook(EvalHookParam):
dataloader = DataLoader(torch.ones((5, 2)))
with pytest.raises(TypeError):
EvalHookParam(dataloader=MagicMock(), interval=(-... |
class DataType(Enum, metaclass=DataTypeMeta):
def get_accumulator_dt_cands():
cands = ['BINARY']
cands += [('UINT%d' % (x + 1)) for x in range(64)]
cands += ['BIPOLAR', 'TERNARY']
cands += [('INT%d' % (x + 1)) for x in range(64)]
return cands
def get_smallest_possible(val... |
def handle_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument('--config_file', type=str, default=None, help='Configuration file for the experiment.')
args = parser.parse_args()
if (args.config_file is None):
raise ValueError('Configuration file must be provided.... |
def get_barren_plot_from_model(model, plt):
y = np.exp(model.predict(model.x_val))
handle = []
handle.append(plt.semilogy(model.x_val, y))
handle.append(plt.semilogy(model.x_val, np.exp(model.y_val)))
return handle |
class CaffeVendor(object):
def __init__(self, net_name, weight_name, version=2):
print('loading model spec...')
self._net_pb = caffe_pb2.NetParameter()
text_format.Merge(open(net_name).read(), self._net_pb)
self._weight_dict = {}
self._init_dict = []
if (weight_name i... |
def BHfilter(pval, q=0.2):
pval = np.asarray(pval)
pval_sort = np.sort(pval)
comparison = ((q * np.arange(1, (pval.shape[0] + 1.0))) / pval.shape[0])
passing = (pval_sort < comparison)
if passing.sum():
thresh = comparison[np.nonzero(passing)[0].max()]
return np.nonzero((pval <= thre... |
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,... |
class CAddTable(Module):
def __init__(self, inplace=False):
super(CAddTable, self).__init__()
self.inplace = inplace
self.gradInput = []
def updateOutput(self, input):
if self.inplace:
self.output.set_(input[0])
else:
self.output.resize_as_(input[0... |
class TestTarOperator(unittest.TestCase):
def test_tar(self):
with temp_file.TemporaryDirectory(as_cwd=True):
test_dir = 'sqlflow_tar'
test_sub_dir = 'sqlflow_sub_dir'
test_py_file = 'hello.py'
test_py_content = "print('hello SQLFlow!')"
fullpath =... |
class ResidualBlockWithCustomJacobian(ResidualBlock):
custom_jacobians: T.Dict[(T.Element, sf.Matrix)] = field(default_factory=dict)
def compute_jacobians(self, inputs: T.Sequence[T.Element], residual_name: str=None, key_names: T.Sequence[str]=None) -> T.Sequence[sf.Matrix]:
residual_jacobians = []
... |
class KLSchedule(Callback):
def __init__(self, start_epoch: int, end_epoch: int, max_kl_beta: float):
self.start_epoch = start_epoch
self.end_epoch = end_epoch
self.max_kl_beta = max_kl_beta
def on_train_epoch_start(self, trainer: Trainer, pl_module: LightningModule) -> None:
epo... |
def mk_parser():
psr = argparse.ArgumentParser(add_help=False)
psr.add_argument('--seed', type=int, default=42)
psr.add_argument('--prompt_version', type=str, default='v1')
psr.add_argument('--dataset', type=str, choices=task_mapper.keys())
psr.add_argument('--data_file', type=str)
psr.add_argum... |
def get_layers_from_model_by_type(model: keras.Model, layer_type: type, include_wrapped_layers: bool=True):
if include_wrapped_layers:
return [layer for layer in model.layers if ((type(layer) == layer_type) or (isinstance(layer, KerasQuantizationWrapper) and (type(layer.layer) == layer_type)))]
return [... |
def evaluation(source_dir):
data_type = 'train'
data_list = pd.read_csv(f'{source_dir}/{data_type}.csv', header=None)
train_file_list = []
for (idx, item) in data_list.iterrows():
file_path = os.path.join(source_dir, data_type, item[3], item[0])
if (not os.path.exists(file_path)):
... |
class TestDeprecatedJitQuantized(JitTestCase):
def test_rnn_cell_quantized(self):
(d_in, d_hid) = (2, 2)
for cell in [torch.nn.LSTMCell(d_in, d_hid).float(), torch.nn.GRUCell(d_in, d_hid).float(), torch.nn.RNNCell(d_in, d_hid).float()]:
if isinstance(cell, torch.nn.LSTMCell):
... |
class TestSubtract(object):
def test_exceptions(self):
a = np.ones((), dtype=np.bool_)[()]
assert_raises(TypeError, operator.sub, a, a)
def test_result(self):
types = (np.typecodes['AllInteger'] + np.typecodes['AllFloat'])
with suppress_warnings() as sup:
sup.filter(R... |
def hash_sketch(sketch, ext):
hash_str = ((sha256(np.ascontiguousarray(sketch).flatten()).hexdigest() + '_') + sha256(np.ascontiguousarray(ext).flatten()).hexdigest())
return hash_str |
def load_tf2_weights_in_pytorch_model(pt_model, tf_weights, allow_missing_keys=False):
try:
import tensorflow as tf
import torch
except ImportError as e:
logger.error('Loading a TensorFlow model in PyTorch, requires both PyTorch and TensorFlow to be installed. Please see and for instal... |
(scope='module')
def functional_gxy(variable_x, variable_y):
return sn.Functional('gxy', [variable_x, variable_y], (2 * [10]), 'tanh') |
class MinMaxScaleTransformer(BaseEstimator, TransformerMixin):
def __init__(self, column):
self.column = column
self.mm = None
def fit(self, X, *args):
self.mm = MinMaxScaler().fit(X[[self.column]])
return self
def transform(self, X):
X[self.column] = self.mm.transfor... |
def stringify_throughputs(throughputs):
stringified_throughputs = {}
for worker_type in throughputs:
stringified_throughputs[worker_type] = {}
for key in throughputs[worker_type]:
stringified_throughputs[worker_type][str(key)] = {}
for other_key in throughputs[worker_type... |
class CityscapesData(Data):
dirs = ['cs']
def __init__(self, data_dir, stat_log_dir=None, development=True, fast_dir=None):
super().__init__(data_dir, stat_log_dir, development=development, fast_dir=fast_dir)
def _fetch_if_missing(self):
pass
def get_raw_dirs(self):
top_dir = os.... |
def test_assign_dev_data():
config = Config()
config.update(dummyconfig_dict)
print('Create ExternSprintDataset')
dataset = ExternSprintDataset([sys.executable, sprintExecPath], '--*.feature-dimension=2 --*.trainer-output-dimension=3 --*.crnn-dataset=DummyDataset(2,3,num_seqs=4,seq_len=10)')
dataset... |
def interactions_pandas():
columns = ['user_id', 'item_id']
data = [(1, 1), (2, 1), (2, 2), (3, 1), (3, 3), (3, 4), (4, 1), (4, 3), (4, 4)]
return PandasDataFrame(data, columns=columns) |
def _check_pydot():
try:
pydot.Dot.create(pydot.Dot())
except Exception:
raise ImportError('Failed to import pydot. You must install pydot and graphviz for `pydotprint` to work.') |
def process_mathtt(s):
while True:
start = s.find('\\mathtt{')
end = s.find('}', start)
if ((start == (- 1)) or (end == (- 1))):
break
s = ((s[:start] + s[(start + 8):end]) + s[(end + 1):])
return s |
def test_join_items_right_outer_deep(join_items):
(left_items, right_items) = join_items
joined = pyhf.workspace._join_items('right outer', left_items, right_items, key='name', deep_merge_key='deep')
assert (next((k['deep'] for k in joined if (k['name'] == 'common'))) == [{'name': 2}, {'name': 1}]) |
class FixLTUNet(nn.Module):
def __init__(self, num_inputs=20, num_features=80, beta=0.75):
super(FixLTUNet, self).__init__()
self.num_inputs = num_inputs
self.num_features = num_features
self.num_outputs = 1
self.beta = beta
self.layers = nn.ModuleList()
self.... |
class GPT2Model(torch.nn.Module):
def __init__(self, num_layers, vocab_size, hidden_size, num_attention_heads, embedding_dropout_prob, attention_dropout_prob, output_dropout_prob, max_sequence_length, checkpoint_activations, checkpoint_num_layers=1, parallel_output=True):
super(GPT2Model, self).__init__()
... |
class ETD(ETDLB):
def __init__(self, task, **kwargs):
super().__init__(task, **kwargs)
self.beta = self.task.GAMMA
def related_parameters():
return ['alpha', 'lmbda'] |
def top_Augmentation(d, nums=1):
from scipy.sparse import coo_matrix
from ogb.nodeproppred import DglNodePropPredDataset
import dgl
import time
dataset = DglNodePropPredDataset('ogbn-arxiv', root=d.raw_data_path)
(g, _) = dataset[0]
g = dgl.to_bidirected(g)
sampler = dgl.dataloading.Mult... |
def find_reachable_nodes(nodes, output_id, keep_tensors=False):
open = {nodes[output_id]}
reachable = set()
while open:
node = open.pop()
if (node in reachable):
continue
open.update(node.in_edges)
for n in node.out_edges:
if (('__i' in n.scope) or ((n... |
class Correlation():
def compute_crossscale_correlation(cls, _src_feats, _trg_feats, origin_resolution):
eps = 1e-08
(bsz, ha, wa, hb, wb) = origin_resolution
corr6d = []
for src_feat in _src_feats:
ch = src_feat.size(1)
(sha, swa) = (src_feat.size((- 2)), src... |
class ExtendedFrameSummary(FrameSummary):
def __init__(self, frame, **kwargs):
super(ExtendedFrameSummary, self).__init__(**kwargs)
self.tb_frame = frame |
class RoadLaneJunctionGraphPartition():
def __init__(self, graph):
self.roads: Dict[(str, RoadNode)] = {}
self.lanes: Dict[(str, LaneNode)] = {}
self.junctions: Dict[(str, JunctionNode)] = {}
for (road_id, road) in graph.roads.items():
if road.is_part_route:
... |
def _fill_missing_operator_names(ops):
seen = set()
for op in ops:
seen.update(op.input)
seen.update(op.output)
for op in ops:
if op.name:
name = op.name
elif (op.output or op.input):
l = [os.path.dirname(name) for name in (op.output or op.input)]
... |
class MosesTokenizerConfig(FairseqDataclass):
source_lang: str = field(default='en', metadata={'help': 'source language'})
target_lang: str = field(default='en', metadata={'help': 'target language'})
moses_no_dash_splits: bool = field(default=False, metadata={'help': "don't apply dash split rules"})
mos... |
class EnumeratedSetFromIterator_method_decorator():
def __init__(self, f=None, **options):
if (f is not None):
self.f = f
if hasattr(f, '__name__'):
self.__name__ = f.__name__
self.__module__ = f.__module__
else:
if hasattr(... |
def compare_overlap(dpr_dict_rel, bm25_dict_rel):
intersection_bm25 = []
intersection_dpr = []
for query_id in dpr_dict_rel.keys():
dpr_rel_doc = set(dpr_dict_rel.get(query_id).keys())
bm25_rel_doc = set(bm25_dict_rel.get(query_id).keys())
print(query_id)
if bm25_rel_doc:
... |
class PermutationGroup_action(PermutationGroup_generic):
def __init__(self, gens, action, domain, gap_group=None, category=None, canonicalize=None):
from sage.combinat.cyclic_sieving_phenomenon import orbit_decomposition
from sage.sets.disjoint_set import DisjointSet
if (gap_group is not Non... |
def load_mp():
fname = 'datasets/canVote_processed/mp_dict.pkl'
MP_dict = normal_util.load_object(fname)
return MP_dict |
.cpublas
def test_bert_full(gpu, default_implementation, sdfg_name):
bert_tiny_root = '
get_data_file((bert_tiny_root + '/config.json'), directory_name='bert-tiny')
vocab = get_data_file((bert_tiny_root + '/vocab.txt'), directory_name='bert-tiny')
bert_path = get_data_file((bert_tiny_root + '/bert-tiny.... |
class VGG19(torch.nn.Module):
def __init__(self, requires_grad=False):
super().__init__()
vgg_pretrained_features = torchvision.models.vgg19(pretrained=True).features
self.slice1 = torch.nn.Sequential()
self.slice2 = torch.nn.Sequential()
self.slice3 = torch.nn.Sequential()
... |
def get_model(transform=None):
if (transform is not None):
transform = TransformSequence([TemporalResample(), transform])
prophet = Prophet(ProphetConfig(add_seasonality='auto', transform=transform))
return prophet |
def not_so_slow(response, case):
assert (response.elapsed < timedelta(milliseconds=100)), 'Response is slow!' |
def generate_value(type, dims, data_type, multiplier):
d = TENSOR_TYPE_TO_DTYPE[data_type]
if (type == 'Normal'):
ret = (np.random.randn(*dims) * multiplier)
elif (type == 'Uniform'):
ret = np.random.uniform((- multiplier), multiplier, size=dims)
elif (type == 'Constant'):
ret = ... |
def _add_category_whitelists_to_metadata(cfg: CfgNode):
for (dataset_name, whitelisted_cat_ids) in cfg.DATASETS.WHITELISTED_CATEGORIES.items():
meta = MetadataCatalog.get(dataset_name)
meta.whitelisted_categories = whitelisted_cat_ids
logger = logging.getLogger(__name__)
logger.info(... |
def deprecated_version_of(f, oldname, newname=None):
if (newname is None):
newname = f.__name__
warning = ('The function ``%s`` is deprecated and is kept temporarily for backwards compatibility.\nPlease use the new name, ``%s``, instead.' % (oldname, newname))
def fdepr(*a, **kw):
warnings.w... |
def _get_rllib_config(path):
jsonfile = (path / 'params.json')
jsondata = json.loads(open(jsonfile).read())
pklfile = (path / 'params.pkl')
with open(pklfile, 'rb') as file:
pkldata = cloudpickle.load(file)
return (jsondata, pkldata) |
class Speech2TextConfig(PretrainedConfig):
model_type = 'speech_to_text'
keys_to_ignore_at_inference = ['past_key_values']
attribute_map = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'}
def __init__(self, vocab_size=10000, encoder_layers=12, encoder_ffn_dim=2048, encoder_at... |
def setup_grad_values(backward_result: BackwardResult, sdfg: dace.SDFG, outputs: List[str]) -> str:
code = '// input grads'
for (param_name, grad_name) in sorted(backward_result.required_grad_names.items()):
zero_init = backward_result.zero_init.get(param_name, True)
code += ('\n' + tensor_init_... |
class TestNormalizedEnv():
def test_pickleable(self):
inner_env = PointEnv(goal=(1.0, 2.0))
env = NormalizedEnv(inner_env, scale_reward=10.0)
round_trip = pickle.loads(pickle.dumps(env))
assert round_trip
assert (round_trip._scale_reward == env._scale_reward)
assert n... |
def scaled_gradient(source: Tensor, scale: Union[(float, Tensor)]) -> Tensor:
if ((not isinstance(scale, Tensor)) and (scale == 0.0)):
return stop_gradient(source)
return source._raw_backend.scaled_gradient(source, scale) |
class J2Grande(AI21TextGenerationAPI):
config_name = 'ai21_j2_grande'
def __init__(self, api_key):
super().__init__(engine='j2-grande', api_key=api_key) |
def test_clean_input_format(df_countries: pd.DataFrame) -> None:
df_clean_name = clean_country(df_countries, 'messy_country', input_format='name')
df_clean_official = clean_country(df_countries, 'messy_country', input_format='official')
df_clean_alpha2 = clean_country(df_countries, 'messy_country', input_fo... |
class PreBasicBlock(nn.Module):
expansion = 1
bias = False
def __init__(self, inplanes, planes, stride=1, ptype='preact'):
super(PreBasicBlock, self).__init__()
if (ptype != 'no_preact'):
self.preact = nn.Sequential(nn.BatchNorm2d(inplanes), nn.ReLU(inplace=True))
self.co... |
class Vertex(object):
def __init__(self, label, ip='', netmask='', mac='', cpu_alloc=0.0):
self.label = label
self.ip = ip
self.netmask = netmask
self.mac = mac
self.cpu_alloc = cpu_alloc
def get_params(self):
return self.__dict__ |
def _set_socket_options(sock, options):
if (options is None):
return
for opt in options:
sock.setsockopt(*opt) |
(frozen=True)
class Prediction(HalfFrozenObject):
soft: torch.Tensor = attr.ib(default=None)
log_soft: torch.Tensor = attr.ib(default=None)
aux_soft: torch.Tensor = attr.ib(default=None)
aux_log_soft: torch.Tensor = attr.ib(default=None)
hard: torch.Tensor = attr.ib(default=None)
alpha: torch.Te... |
def collect_class_methods(cls, methods):
if isinstance(methods, (list, tuple)):
return [(getattr(cls, m) if isinstance(m, str) else m) for m in methods]
methods = []
for (_, method) in inspect.getmembers(cls, predicate=inspect.isroutine):
if ((method.__name__[0] == '_') or (method.__name__ i... |
class ExpansionPerturbation(TextPerturbation):
name: str = 'expansion'
def __init__(self):
self.contraction_map: Dict[(str, str)] = CONTRACTION_MAP
self.contraction_pattern = re.compile('\\b({})\\b'.format('|'.join(self.contraction_map.keys())), flags=(re.IGNORECASE | re.DOTALL))
def descrip... |
class TokenVocab(BaseVocab):
def __init__(self, *args, **kwargs):
recount = kwargs.pop('recount', False)
initialize_zero = kwargs.pop('initialize_zero', True)
super(TokenVocab, self).__init__(*args, **kwargs)
if recount:
self.count()
elif os.path.isfile(self.filen... |
class ActionConfig():
space: ActionSpace = MISSING
extended_road_options: bool = False
cont_normalized_actions: bool = True
disc_dimensions: Tuple[(int, int)] = (5, 5)
hie_num_target_speeds: int = 5
hie_accel: bool = False
disc_hie_cross_prod: bool = False |
def polymorphic_model(type_list: Optional[Union[(List, Tuple[List])]]=None):
def decorator(cls):
if isinstance(type_list, tuple):
for type_list_ in type_list:
type_list_.append(cls)
elif (type_list is not None):
type_list.append(cls)
assert (len(cls._s... |
def process_video_mat(video_mat):
result = []
for shot_vec in video_mat:
shot_vec = shot_vec[0][0]
result.append(shot_vec)
result = np.array(result)
return result |
def main(args):
aishell1_dir = args.aishell1_dir
aishell1_md_dir = os.path.join(aishell1_dir, 'metadata')
os.makedirs(aishell1_md_dir, exist_ok=True)
create_aishell1_metadata(aishell1_dir, aishell1_md_dir) |
def build_resnet18(num_classes: int, norm_layer):
return ResNet(BasicBlock, layers=[2, 2, 2, 2], norm_layer=norm_layer, num_classes=num_classes) |
def segment_ids(size, is_sorted):
if (size == 0):
return st.just(np.empty(shape=[0], dtype=np.int32))
if is_sorted:
return arrays([size], dtype=np.int32, elements=st.booleans()).map((lambda x: (np.cumsum(x, dtype=np.int32) - x[0])))
else:
return arrays([size], dtype=np.int32, element... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.