code stringlengths 101 5.91M |
|---|
_module()
class ClevrDataset(MInstrDataset):
def __init__(self, *args, scene_graph_file, version, **kwargs):
super().__init__(*args, **kwargs, placeholders=(IMAGE_PLACEHOLDER, QUESTION_PLACEHOLDER))
self.scene_graph_file = scene_graph_file
self.version = version
(qtype, atype) = vers... |
def set_device(model, device):
if (type(device) is int):
if (device > 0):
torch.cuda.set_device((device - 1))
model.cuda((device - 1))
floatTensor = torch.cuda.FloatTensor
longTensor = torch.cuda.LongTensor
elif (type(device) is list):
devices = [(... |
class Ticktock(MutableSequence):
_keylist = ['UTC', 'TAI', 'ISO', 'JD', 'MJD', 'UNX', 'RDT', 'CDF', 'GPS', 'DOY', 'eDOY', 'leaps']
if HAVE_ASTROPY:
_keylist.append('APT')
_keylist_upper = [key.upper() for key in _keylist]
_isoformatstr = {'seconds': '%Y-%m-%dT%H:%M:%S', 'microseconds': '%Y-%m-%d... |
class ShowInterfaceStatistics(InformationWindow):
(COLUMN_INTERFACE, COLUMN_TX_PACKETS, COLUMN_TX_BYTES, COLUMN_TX_PACKET_RATE, COLUMN_TX_BIT_RATE, COLUMN_RX_PACKETS, COLUMN_RX_BYTES, COLUMN_RX_PACKET_RATE, COLUMN_RX_BIT_RATE) = range(9)
def __init__(self, visualizer, node_index, statistics_collector):
... |
class DQN(RLAlgorithm):
def __init__(self, env_spec, policy, qf, replay_buffer, exploration_policy=None, steps_per_epoch=20, min_buffer_size=int(10000.0), buffer_batch_size=64, rollout_batch_size=1, n_train_steps=50, max_path_length=None, max_eval_path_length=None, qf_lr=_Default(0.001), qf_optimizer=tf.compat.v1.t... |
def read_in_data(f):
df = pd.read_csv(f)
df['timestamp'] = pd.to_datetime(df['timestamp'], infer_datetime_format=True)
return df |
def network_score(model, sess, encoder_output, target_tokens):
score = 0.0
states = None
cnt = 0
for (feed, pick) in zip(list(target_tokens)[:(- 1)], list(target_tokens)[1:]):
(scores, _, states) = model.decode(sess, encoder_output, np.array([feed]), None, states)
score += float(scores[(... |
class TestUtilFactorize(unittest.TestCase):
def test_prod(self):
for fs in util.factorize(24, 3):
self.assertEqual(util.prod(fs), 24)
for fs in util.factorize(1024, 3):
self.assertEqual(util.prod(fs), 1024)
def test_limits(self):
for fs in util.factorize(1024, 3, ... |
def _get_thread_context():
context = [threading.current_thread()]
if greenlet:
context.append(greenlet.getcurrent())
return hash(tuple(context)) |
def _solve_gbuf_reside(nested_loop_desc, resource, reside_dce):
ldce = [reside_dce]
llpe = []
lfacc = []
if (ldce[0] == de.FIL):
llpe += [le.IFM, le.OFM, le.BAT]
ldce += [de.OFM, de.IFM]
lfacc += [1.0, 2.0, 1.0]
elif (ldce[0] == de.IFM):
llpe += [le.IFM, le.BAT, le.OF... |
class SentenceRE(nn.Module):
def __init__(self, model, train_loader, val_loader, test_loader, ckpt, max_epoch=100, lr=0.1, weight_decay=1e-05, opt='sgd', add_subject_loss=False, loss_func=PARALoss(), metric=F1Metric()):
super().__init__()
self.metric = metric
self.add_subject_loss = add_subj... |
def get_thread_siblings_list():
path = '/sys/devices/system/cpu/cpu*/topology/thread_siblings_list'
thread_siblings_list = []
pattern = re.compile('(\\d+)\\D(\\d+)')
for fname in pathlib.Path(path[0]).glob(path[1:]):
with open(fname) as f:
content = f.read().strip()
res =... |
class UnramifiedExtensionFieldFloatingPoint(UnramifiedExtensionGeneric, pAdicFloatingPointFieldGeneric):
def __init__(self, exact_modulus, poly, prec, print_mode, shift_seed, names, implementation='FLINT'):
self._shift_seed = None
self._exact_modulus = exact_modulus
self._implementation = im... |
.parametrize('seed', [311])
.parametrize('clear_buffer', [True, False])
def test_graph_forward_clear_buffer(seed, clear_buffer):
nn.clear_parameters()
x = nn.Variable((2, 10))
h = PF.affine(x, 10, name='hidden')
y1 = PF.affine(h, 10, name='out1')
y2 = PF.affine(h, 10, name='out2')
rng = np.rando... |
class RootCauseDetector():
def __init__(self, data_obj: TabularData, var_names: List[str], time_metric_name: str='time', prior_knowledge: Optional[PriorKnowledge]=None):
assert (time_metric_name in var_names), 'Time metric not found in the data!'
self.data_obj = data_obj
self.var_names = var... |
def check_module_initialized(mod):
assert isinstance(mod, torch.nn.Module)
if (not hasattr(mod, '_parameters')):
raise RuntimeError("'{}' has not been initialized, did you forget to call 'super()'?".format(torch.typename(type(mod)))) |
def Dsk(k, y, tol=1.49e-08, rtol=1.49e-08, maxiter=50, miniter=1):
if (y > 1):
raise ValueError('sk(k,y) called with y={:f}.Value of y must be less than 1.')
maxiter = max((miniter + 1), maxiter)
val = np.inf
err = np.inf
for n in xrange(miniter, (maxiter + 1)):
newval = _Dsk_integra... |
class Berkovich_Cp_Projective(Berkovich_Cp):
Element = Berkovich_Element_Cp_Projective
def __init__(self, base, ideal=None):
if (base in ZZ):
if base.is_prime():
from sage.rings.padics.factory import Qp
base = ProjectiveSpace(Qp(base), 1)
else:
... |
()
('workspace', default='-')
('--output-file', help='The location of the output json file. If not specified, prints to screen.', default=None)
('-c', '--channel', default=[], multiple=True, type=click.Tuple([str, str]), metavar='<PATTERN> <REPLACE>...')
('-s', '--sample', default=[], multiple=True, type=click.Tuple([s... |
def collect_segments(beat_df, beat_dict):
cur_seg = 'NA'
for (i, beat) in beat_df.iterrows():
if ((beat['form'] != cur_seg) and (i != (len(beat_df) - 1))):
beat_key = (int(beat['bar']), int(beat['beat']))
if (cur_seg != 'NA'):
beat_dict[beat_key].patch_segment_tag... |
def test_str():
stream = io.StringIO()
ak.Array(['hello', 'world']).show(stream=stream, formatter={'str': '<STRING {!r}>'.format})
assert (stream.getvalue() == "[<STRING 'hello'>,\n <STRING 'world'>]\n")
stream.seek(0)
ak.Array(['hello', 'world']).show(stream=stream, formatter={'str_kind': '<STRING ... |
def unique_pitch(pianoroll):
total_num = pianoroll.shape[0]
count = 0
num_bar = 8
num_note = 16
for i in range(total_num):
count_per_bar = 0
for j in range(num_bar):
bar = pianoroll[i][(j * num_note):((j + 1) * num_note)]
count_per_bar += np.unique(np.where((b... |
class Music(SequenceDataset):
_name_ = 'music'
def d_input(self):
return 1
def d_output(self):
return 256
def l_output(self):
return (self.sample_rate * self.sample_len)
def n_tokens(self):
return (256 if self.discrete_input else None)
def init_defaults(self):
... |
def refillPointsOnOneBoundary(boundary, index):
pointsNumber = screen[0]
if ((boundary == 0) or (boundary == 2)):
pointsNumber = screen[1]
for i in range(pointsNumber):
found = False
for _ in range(maxPoints):
if (points[index][0] == (- 100)):
found = True... |
def resize_and_convert(img, size, format, resample):
img = trans_fn.resize(img, size, resample)
img = trans_fn.center_crop(img, size)
buffer = BytesIO()
img.save(buffer, format=format, quality=100)
val = buffer.getvalue()
return val |
def test_named_record_fields_int32_float64_parameters():
t = RecordType([NumpyType('int32'), NumpyType('float64')], ['one', 't w o'], parameters={'__record__': 'Name', 'p': [123]})
assert (str(ak.types.from_datashape(str(t), highlevel=False)) == str(t)) |
def gen_graph(branches, g=None, init_root=0, pre=''):
num_branches = [branch2num(i, init_root) for i in branches]
all_nodes = [j for branch in num_branches for j in branch]
all_nodes = np.unique(all_nodes)
all_nodes = all_nodes.tolist()
if (g is None):
g = ig.Graph()
for k in all_nodes:
... |
class FullTensorProductOfSuperCrystals(FullTensorProductOfCrystals):
class Element(TensorProductOfSuperCrystalsElement):
pass |
def reconstruct_tree(tree, sequence, transition_scheme=TransitionScheme.IN_ORDER, unary_limit=UNARY_LIMIT, reverse=False):
model = SimpleModel(transition_scheme=transition_scheme, unary_limit=unary_limit, reverse_sentence=reverse)
states = model.initial_state_from_gold_trees([tree])
assert (len(states) == 1... |
def read_pfm(filename):
file = open(filename, 'rb')
color = None
width = None
height = None
scale = None
endian = None
header = file.readline().decode('utf-8').rstrip()
if (header == 'PF'):
color = True
elif (header == 'Pf'):
color = False
else:
raise Exce... |
class MaskMapper():
def __init__(self):
self.labels = []
self.remappings = {}
self.coherent = True
def clear_labels(self):
self.labels = []
self.remappings = {}
self.coherent = True
def convert_mask(self, mask, exhaustive=False):
labels = np.unique(mas... |
class FlaxAutoModelForVision2Seq(metaclass=DummyObject):
_backends = ['flax']
def __init__(self, *args, **kwargs):
requires_backends(self, ['flax']) |
_start_docstrings('CamemBERT Model with a span classification head on top for extractive question-answering tasks like SQuAD\n (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits` ', CAMEMBERT_START_DOCSTRING)
class CamembertForQuestionAnswering(RobertaForQuestionA... |
class ResNeXt(nn.Module):
def __init__(self, last_stride, bn_norm, with_ibn, with_nl, block, layers, non_layers, baseWidth=4, cardinality=32):
super(ResNeXt, self).__init__()
self.cardinality = cardinality
self.baseWidth = baseWidth
self.inplanes = 64
self.output_size = 64
... |
class DistroConfigNode(TreeConfigNode):
def init2(self, node_name):
self.props['distro_name'] = node_name
def child_constructor(self):
distro = self.find_prop('distro_name')
next_nodes = {'xenial': XenialCompilerConfigNode, 'bionic': BionicCompilerConfigNode}
return next_nodes[di... |
def add_wsl_losses(model, prefix=''):
add_cls_pred((prefix + 'rois_pred'), (prefix + 'cls_prob'), model, prefix='')
classes_weight = None
cpg = None
if (cfg.WSL.CPG or cfg.WSL.CSC):
cpg_args = {}
cpg_args['tau'] = cfg.WSL.CPG_TAU
cpg_args['max_iter'] = max(cfg.WSL.CPG_MAX_ITER, c... |
def keyword_none(A: dace.float32[N], B: dace.float32[N], C: dace.pointer(dace.int32)):
if (C is None):
B[:] = A[:] |
.parametrize('name,dataset_class', [('sinusoid', Sinusoid), ('harmonic', Harmonic)])
def test_toy_helpers(name, dataset_class):
dataset_fn = getattr(helpers, name)
dataset = dataset_fn(shots=5, test_shots=15)
assert isinstance(dataset, dataset_class)
task = dataset[0]
assert isinstance(task, Ordered... |
('version', add_help_option=False)
_context
def version_command(ctx):
ctx.obj.process_input_flag = False
click.echo(click.style(('PySceneDetect %s' % scenedetect.__version__), fg='yellow'))
ctx.exit() |
_spec([HookScope.GLOBAL])
def process_call_kwargs(context: HookContext, case: Case, kwargs: dict[(str, Any)]) -> None: |
def split_data(data, max_len):
new_x = []
new_y = []
for v in data:
x = v[:(- 1)]
y = v[1:]
if (len(x) < 1):
continue
padded_len = (max_len - len(x))
if (padded_len > 0):
x.extend(([0] * padded_len))
y.extend(([0] * padded_len))
... |
def test_validate_series(df_phone: pd.DataFrame) -> None:
srs_valid = validate_phone(df_phone['messy_phone'])
srs_check = pd.Series([True, True, True, True, True, True, True, True, True, True, True, True, False, False, False, False, False], name='messy_phone')
assert srs_check.equals(srs_valid) |
def program_generator(size: int, factor: float) -> DaceProgram:
(dace.float64[size], dace.float64[size], size=size, factor=factor)
def lib_reuse(input, output):
(_[0:size])
def tasklet(i):
(a << input[i])
(b >> output[i])
b = (a * factor)
return lib_reuse |
def stylize():
device = ('cuda' if torch.cuda.is_available() else 'cpu')
net = transformer.TransformerNetwork()
net.load_state_dict(torch.load(STYLE_TRANSFORM_PATH))
net = net.to(device)
with torch.no_grad():
while 1:
torch.cuda.empty_cache()
print('Stylize Image~ Pre... |
class SymlinkLockFile(LockBase):
def __init__(self, path, threaded=True, timeout=None):
LockBase.__init__(self, path, threaded, timeout)
self.unique_name = os.path.split(self.unique_name)[1]
def acquire(self, timeout=None):
timeout = (timeout if (timeout is not None) else self.timeout)
... |
def openpose():
print('Starting OpenPose')
os.chdir('bin\\openpose')
subprocess.Popen('bin\\OpenPoseDemo.exe --hand --write_json ..\\..\\Keypoints --net_resolution 128x128 --number_people_max 1', shell=True)
os.chdir('..\\..')
dirName = 'Keypoints'
fileName = 'PSL\\_keypoints.json'
try:
... |
class GPT3(LM):
def __init__(self, model: str='gpt-3.5-turbo-instruct', api_key: Optional[str]=None, api_provider: Literal[('openai', 'azure')]='openai', api_base: Optional[str]=None, model_type: Literal[('chat', 'text')]=None, **kwargs):
super().__init__(model)
self.provider = 'openai'
defa... |
class FeatureFunction():
def __init__(self):
pass
def inform(self, train, dev, test):
raise NotImplementedError('Not Implemented Here')
def lookup(self, data):
return self.process(data)
def process(self, data):
pass
def load_vocab(self, mname):
pass
def sa... |
def move_to(obj, old_pt, pt):
dx = (pt.getX() - old_pt.getX())
dy = (pt.getY() - old_pt.getY())
obj.move(dx, dy) |
def CheckComment(comment, filename, linenum, error):
match = _RE_PATTERN_TODO.match(comment)
if match:
leading_whitespace = match.group(1)
if (len(leading_whitespace) > 1):
error(filename, linenum, 'whitespace/todo', 2, 'Too many spaces before TODO')
username = match.group(2)... |
def load_checkpoint(model, filename, map_location=None, strict=False, logger=None):
checkpoint = _load_checkpoint(filename, map_location)
if isinstance(checkpoint, OrderedDict):
state_dict = checkpoint
elif (isinstance(checkpoint, dict) and ('state_dict' in checkpoint)):
state_dict = checkpo... |
def run_cython_lint(files):
if (not files):
return (0, '')
res = subprocess.run((['cython-lint', '--no-pycodestyle'] + list(files)), stdout=subprocess.PIPE, encoding='utf-8')
return (res.returncode, res.stdout) |
def fix_random_seeds(seed: int=1337) -> None:
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = Tru... |
class MPNetForTokenClassification(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def assert_install_itrex():
assert is_itrex_available(), 'To run int8 or k-bits model on cpu, please install the `intel-extension-for-transformers` package.You can install it with `pip install intel-extension-for-transformers`.' |
class LinearMasked(torch.nn.Module):
def __init__(self, adj):
super(LinearMasked, self).__init__()
self.weights = torch.nn.Parameter(torch.Tensor(np.zeros_like(adj)))
self.adj = torch.Tensor(adj)
def forward(self, data, mask):
out = torch.matmul(data, (self.adj * self.weights))
... |
def resnet101(pretrained=False, **kwargs):
model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs)
if pretrained:
model.load_state_dict(torch.load(model_urls['resnet101'], map_location='cpu'))
return model |
def _vi_tables(im_true, im_test, table=None, ignore_labels=()):
check_shape_equality(im_true, im_test)
if (table is None):
pxy = contingency_table(im_true, im_test, ignore_labels=ignore_labels, normalize=True)
else:
pxy = table
px = np.ravel(pxy.sum(axis=1))
py = np.ravel(pxy.sum(axi... |
class ApplyResultObj(ctypes.c_void_p):
def __init__(self, obj):
self._as_parameter_ = obj
def from_param(obj):
return obj |
class DAVIS_Test(data.Dataset):
def __init__(self, root, output_size=None, img_set='2017/val.txt', max_obj_n=11, single_obj=False):
self.root = root
self.single_obj = single_obj
dataset_path = os.path.join(root, 'ImageSets', img_set)
self.dataset_list = list()
self.output_siz... |
def get_all_csv(base_dir, verbose=False):
data = []
delimiter = ','
for dir_name in get_dirs(base_dir):
for data_file_name in os.listdir(dir_name):
if data_file_name.endswith('.csv'):
full_path = os.path.join(dir_name, data_file_name)
if verbose:
... |
def replace_math_functions(input_string):
output_string = input_string
for func in MATH_TRANSPILATIONS:
output_string = output_string.replace('{}('.format(func), '{}('.format(MATH_TRANSPILATIONS[func]))
return output_string |
class AnnotatedObjectsOpenImages(AnnotatedObjectsDataset):
def __init__(self, use_additional_parameters: bool, **kwargs):
super().__init__(**kwargs)
self.use_additional_parameters = use_additional_parameters
self.categories = load_categories(self.paths['class_descriptions'])
self.fil... |
def pod_requests_sgx(pod: V1Pod) -> bool:
for container in pod.spec.containers:
for demands in (container.resources.limits, container.resources.requests):
if (isinstance(demands, dict) and ('intel.com/sgx' in demands.keys())):
return True
return False |
class LogFloatParam(RandomHyperparameter):
def __init__(self, name, min_value, max_value, *, offset=0):
super(LogFloatParam, self).__init__(name)
self._linear_float_param = LinearFloatParam(('log_' + name), math.log(min_value), math.log(max_value))
self.offset = offset
def generate_next_... |
class Log():
def __init__(self, verbose: bool=False):
self.verbose = verbose
self.log = ''
def print_log(self, *args):
if self.verbose:
print(*args)
self.log += (' '.join(map(str, args)) + '\n') |
def get_boxes_idx(boxes_list, refs):
def get_idx(boxes_list, box):
if (box in boxes_list):
return boxes_list.index(box)
else:
boxes_list.append(box)
return (len(boxes_list) - 1)
idx = [get_idx(boxes_list, box) for box in refs]
return idx |
class Response():
def __init__(self, template: str, task_config: TaskConfig, bot_config: BotConfig, entity_manager: EntityManager, user_name=''):
self._responses = load_response(template)
self.bot_name = bot_config.bot_name
self.user_name = user_name
self.personality = None
s... |
class _WordRegex(Word):
def parseImpl(self, instring, loc, doActions=True):
result = self.re_match(instring, loc)
if (not result):
raise ParseException(instring, loc, self.errmsg, self)
loc = result.end()
return (loc, result.group()) |
class ThePileScenario(Scenario):
name = 'the_pile'
description = 'The Pile'
tags = ['language_modeling']
def __init__(self, subset: str):
super().__init__()
self.pile_subsets = {'ArXiv', 'BookCorpus2', 'Books3', 'DM Mathematics', 'Enron Emails', 'EuroParl', 'FreeLaw', 'Github', 'Gutenber... |
class SchemaInteractionATISModel(ATISModel):
def __init__(self, params, input_vocabulary, output_vocabulary, output_vocabulary_schema, anonymizer):
ATISModel.__init__(self, params, input_vocabulary, output_vocabulary, output_vocabulary_schema, anonymizer)
if self.params.use_schema_encoder:
... |
class StringToken(ProgramToken):
def __init__(self, s):
assert isinstance(s, unicode)
self._string = s
def execute(self, env):
return self._string
def return_type(self):
return unicode
def __str__(self):
return 'String({})'.format(repr(self._string))
__repr__ ... |
class GPTNeoXForSequenceClassification(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class NewtonMethod(optimization_algorithm.OptimizationAlgorithm):
def __init__(self, db: database.Database, optimization_problem: _typing.OptimizationProblem, line_search: ls.LineSearch) -> None:
super().__init__(db, optimization_problem, line_search)
self.hessian_problem = optimization_problem.hess... |
class KnnSampler(_BasicSampler):
def __init__(self, dataset, params, is_training=True, seed=0, return_index=False):
self.num_points_per_sample = 0
self.knn_module = ''
self.max_workers = 64
self.overlap_ratio = 1.0
self.modify_type = None
super(KnnSampler, self).__ini... |
class Session():
session_id: str
start_time: str
scene: str
chat_history_for_llm: list[tuple]
chat_history_for_display: list[tuple]
chat_counter: int
image_id_to_path: dict[(int, str)] = field(factory=dict)
grounding_result_mesh_path: (str | None) = None
ground_result: (list[tuple[fl... |
def random_split(dataset, lengths):
if (sum(lengths) != len(dataset)):
raise ValueError('Sum of input lengths does not equal the length of the input dataset!')
indices = randperm(sum(lengths))
return [Subset(dataset, indices[(offset - length):offset]) for (offset, length) in zip(_accumulate(lengths)... |
class SpatialAveragePooling(Module):
def __init__(self, kW, kH, dW=1, dH=1, padW=0, padH=0):
super(SpatialAveragePooling, self).__init__()
self.kW = kW
self.kH = kH
self.dW = dW
self.dH = dH
self.padW = padW
self.padH = padH
self.ceil_mode = False
... |
def generate_type_hints(fname, decls, namedtuples, is_tensor=False):
if (fname in blocklist):
return []
type_hints = []
dnames = [d['name'] for d in decls]
has_out = ((fname + '_out') in dnames)
if has_out:
decls = [d for d in decls if (d['name'] != (fname + '_out'))]
for decl in... |
class ParallelTextAndMaskCopyingPipeline(ParallelTextAndMaskInputPipeline):
def make_data_provider(self, **kwargs):
target_files = self.params['target_files']
if (not target_files):
target_files = None
return self._get_copying_data_provider(target_files, **kwargs)
def _get_co... |
def display_report_metadata(meta: service.Metadata) -> None:
if (meta.ci_environment is not None):
click.secho(f'{meta.ci_environment.verbose_name} detected:', bold=True)
for (key, value) in meta.ci_environment.as_env().items():
if (value is not None):
click.secho(f' -> ... |
class SigmoidFocalLoss(nn.Module):
def __init__(self, gamma, alpha):
super(SigmoidFocalLoss, self).__init__()
self.gamma = gamma
self.alpha = alpha
def forward(self, logits, targets, weight=None):
if logits.is_cuda:
loss_func = sigmoid_focal_loss_cuda
else:
... |
class UnusedPrimitiveOrCollectionStatementVisitor(StatementVisitor):
def __init__(self):
self._used_references = set()
self._deleted_statement_indexes: set[int] = set()
def deleted_statement_indexes(self) -> set[int]:
return self._deleted_statement_indexes
def _handle_collection_or_p... |
def main():
parser = get_parser()
args = parser.parse_args()
sil_prob = args.sil_prob
surround = args.surround
sil = '<SIL>'
wrd_to_phn = {}
with open(args.lexicon, 'r') as lf:
for line in lf:
items = line.rstrip().split()
assert (len(items) > 1), line
... |
def debug_training(dataset_path, config_path=None):
with Path(dataset_path).open('r', encoding='utf8') as f:
dataset = json.load(f)
config = None
if (config_path is not None):
with Path(config_path).open('r', encoding='utf8') as f:
config = NLUEngineConfig.from_dict(json.load(f))... |
def get_system_metadata(repo_root):
import git
return dict(helsinki_git_sha=git.Repo(path=repo_root, search_parent_directories=True).head.object.hexsha, transformers_git_sha=git.Repo(path='', search_parent_directories=True).head.object.hexsha, port_machine=socket.gethostname(), port_time=time.strftime('%Y-%m-%d... |
class LALR_TraditionalLexer(LALR_WithLexer):
def init_lexer(self):
self.init_traditional_lexer() |
def gen_random_dataframe(nrows: int=30, ncols: int=30, na_ratio: float=0.0, str_col_name_max_len: int=100, random_state: Union[(int, np.random.RandomState)]=0) -> pd.DataFrame:
rand = _resolve_random_state(random_state)
dtypes = ['int', 'float', 'boolean', 'datetime', 'string', 'object']
col_types = rand.ch... |
def dataio_prep(hparams):
data_folder = hparams['data_folder']
train_data = sb.dataio.dataset.DynamicItemDataset.from_json(json_path=hparams['train_annotation'], replacements={'data_root': data_folder})
if (hparams['sorting'] == 'ascending'):
train_data = train_data.filtered_sorted(sort_key='duratio... |
def test_ListOffsetArray_RecordArray_NumpyArray():
a = ak.contents.listoffsetarray.ListOffsetArray(ak.index.Index(np.array([1, 4, 4, 6])), ak.contents.recordarray.RecordArray([ak.contents.numpyarray.NumpyArray(np.array([6.6, 1.1, 2.2, 3.3, 4.4, 5.5, 7.7]))], ['nest']))
assert (a.to_typetracer().form == a.form)
... |
class AdamP(optimizer_v2.OptimizerV2):
_HAS_AGGREGATE_GRAD = True
def __init__(self, learning_rate=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, weight_decay=0.0, delta=0.1, wd_ratio=0.1, nesterov=False, name='AdamP', **kwargs):
super(AdamP, self).__init__(name, **kwargs)
self._set_hyper('lear... |
_numpy_output(check_dtype=True)
def test_ufunc_fmax_ff(A: dace.float32[10], B: dace.float32[10]):
return np.fmax(A, B) |
def test_montage_simple_padding_gray():
(n_images, n_rows, n_cols) = (2, 2, 2)
arr_in = np.arange(((n_images * n_rows) * n_cols))
arr_in = arr_in.reshape(n_images, n_rows, n_cols)
arr_out = montage(arr_in, padding_width=1)
arr_ref = np.array([[3, 3, 3, 3, 3, 3, 3], [3, 0, 1, 3, 4, 5, 3], [3, 2, 3, 3... |
class SampledFeatures(Features):
sampling_strategy: SampleAveragingStrategy
_samples: List[FeaturesValuesLike]
def __init__(self, sampling_strategy: SampleAveragingStrategy=ExplicitSampleAveragingStrategy(), *args, **kwargs) -> None:
self.sampling_strategy = sampling_strategy
self._samples =... |
class TestReadValuesPlainSingle(ReadValuesPlain):
_descr = Pdescr
multiple_rows = 0
_buffer = PbufferT[0] |
.parametrize('lr', [0.0001])
.parametrize('module', [torch.nn.Linear(2, 3)])
def test_adam_factory(lr: float, module: torch.nn.Module) -> None:
factory = AdamFactory()
optim = factory.create(module.named_modules(), lr)
assert isinstance(optim, Adam)
assert (optim.defaults['lr'] == lr)
AdamFactory.de... |
class DynamicGlobalWindowTransformer(nn.Module):
def __init__(self, dim, head, FFNdim) -> None:
super(DynamicGlobalWindowTransformer, self).__init__()
self.MHSA = GlobalMHA(dim, head)
self.FFN = FeedForwardNetwork(dim, FFNdim)
self.ln1 = nn.LayerNorm(dim, eps=1e-05)
self.ln2 ... |
def render_bboxes_to_img(image, bboxes, color=(255, 0, 0), thickness=5):
im = image.copy()
for bbox in bboxes:
pt1 = (int(bbox[0]), int(bbox[1]))
pt2 = (int(bbox[2]), int(bbox[3]))
cv2.rectangle(im, pt1, pt2, color, thickness)
return im |
class ChannelGate(nn.Module):
def __init__(self, gate_channels, reduction_ratio=16, pool_types=['avg', 'max']):
super(ChannelGate, self).__init__()
self.gate_channels = gate_channels
self.mlp = nn.Sequential(Flatten(), nn.Linear(gate_channels, (gate_channels // reduction_ratio)), nn.ReLU(), ... |
class XLNetConfig(PretrainedConfig):
model_type = 'xlnet'
keys_to_ignore_at_inference = ['mems']
attribute_map = {'n_token': 'vocab_size', 'hidden_size': 'd_model', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer'}
def __init__(self, vocab_size=32000, d_model=1024, n_layer=24, n_head=16, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.