code stringlengths 101 5.91M |
|---|
def run_filter(mode):
tf.keras.backend.clear_session()
dim_x = 10
if (mode == True):
batch_size = 64
num_ensemble = 32
dropout_rate = 0.1
model = diff_enKF.enKFMLP(batch_size, num_ensemble, dropout_rate)
optimizer = tf.keras.optimizers.Adam(learning_rate=0.0001)
... |
def test_keyword_only_args(msg):
assert (m.kw_only_all(i=1, j=2) == (1, 2))
assert (m.kw_only_all(j=1, i=2) == (2, 1))
with pytest.raises(TypeError) as excinfo:
assert (m.kw_only_all(i=1) == (1,))
assert ('incompatible function arguments' in str(excinfo.value))
with pytest.raises(TypeError) ... |
class ShuffleMomentumSiameseBaseModel(MomentumSiameseBaseModel, ABC):
def __init__(self, trunk: DictConfig, optimizer: DictConfig, projector: Optional[DictConfig]=None, predictor: Optional[DictConfig]=None, train_transform: Optional[DictConfig]=None, val_transform: Optional[DictConfig]=None, test_transform: Optiona... |
def psi_prior(samples, min_value=0.0, max_value=(2 * np.pi)):
lower = (samples['psi'] > min_value)
upper = (samples['psi'] < max_value)
return np.logical_and(lower, upper) |
def dump_data(data, fn, mode='w'):
if (not isinstance(fn, Path)):
fn = Path(fn)
fp = fn.parent
if (not os.path.exists(fp)):
os.makedirs(fp, exist_ok=True)
with open(fn, mode) as f:
f.writelines(data) |
def convert_normal_to_point_form_of_line(rho, theta):
points = []
for x in [0, 1920]:
points.append(np.array([x, ((rho - (x * np.cos(theta))) / np.sin(theta))]))
return points |
def check_uniques(example, uniques):
if (example['hash'] in uniques):
uniques.remove(example['hash'])
return True
else:
return False |
class TestGaussianFocalLoss(unittest.TestCase):
def test_forward(self):
pred = torch.rand((10, 4))
target = torch.rand((10, 4))
gaussian_focal_loss = GaussianFocalLoss()
loss1 = gaussian_focal_loss(pred, target)
self.assertIsInstance(loss1, torch.Tensor)
loss2 = gauss... |
def build_reverse_dictionary(word_to_id):
reverse_dictionary = dict(zip(word_to_id.values(), word_to_id.keys()))
return reverse_dictionary |
def test_generate_shapes():
poly = Polygon(create_star_polygon(15, 8, 5, 1.5))
transform = SE2_from_xytheta((3, 3, deg2rad(5)))
viz = ShapelyViz()
arena_size = 100
boundary = LinearRing([[0, 0], [arena_size, 0], [arena_size, arena_size], [0, arena_size]])
viz.add_shape(boundary, color='r')
g... |
class LinearFloatParam(RandomHyperparameter):
def __init__(self, name, min_value, max_value):
super(LinearFloatParam, self).__init__(name)
self._min = min_value
self._delta = (max_value - min_value)
def generate_next_value(self):
return ((random.random() * self._delta) + self._mi... |
def dowmsampleBottleneck(channel_in, channel_out, stride=2):
return nn.Sequential(nn.Conv2d(channel_in, 128, kernel_size=1, stride=1), nn.BatchNorm2d(128), nn.ReLU(), nn.Conv2d(128, 128, kernel_size=3, stride=stride, padding=1), nn.BatchNorm2d(128), nn.ReLU(), nn.Conv2d(128, channel_out, kernel_size=1, stride=1), n... |
def write_cameras_binary(cameras, path_to_model_file):
with open(path_to_model_file, 'wb') as fid:
write_next_bytes(fid, len(cameras), 'Q')
for (_, cam) in cameras.items():
model_id = CAMERA_MODEL_NAMES[cam.model].model_id
camera_properties = [cam.id, model_id, cam.width, cam... |
def make_loss_report(exp_list, title, path_fig):
fig = plt.figure(dpi=150)
plt.title(title)
for (idx, (exp, exp_label)) in enumerate(exp_list):
path_log = os.path.join(exp, 'log_value.txt')
(data_val, data_tra) = load_loss(path_log)
plt.plot(data_val['step'], data_val['vals'], label=... |
class RandomHorizontalFlip(RecursiveTransform):
def __init__(self, p=0.5):
self.p = p
def __call__(self, x, flip=None):
flip = ((random.random() < self.p) if (flip is None) else flip)
if (not flip):
return x
if isinstance(x, (list, tuple)):
x = [self.__cal... |
class InnerProductDecoder(nn.Module):
def __init__(self, act=torch.sigmoid, dropout=0.0):
super(InnerProductDecoder, self).__init__()
self.act = act
self.dropout = dropout
def forward(self, inp):
inp = F.dropout(inp, self.dropout, training=self.training)
x = torch.transpo... |
def get_prediction(model, tokenizer, premise, hypothesis, max_len=50):
def softmax(x):
return (np.exp(x) / np.sum(np.exp(x), axis=(- 1), keepdims=True))
data = {'premise': premise, 'hypothesis': hypothesis, 'label': ([1] * len(premise))}
m_input = create_data_matrices(tokenizer, data, max_len=max_le... |
def rasterize_gaussians(means3D, means2D, sh, colors_precomp, opacities, scales, rotations, aos, transforms, cov3Ds_precomp, raster_settings):
return _RasterizeGaussians.apply(means3D, means2D, sh, colors_precomp, opacities, scales, rotations, aos, transforms, cov3Ds_precomp, raster_settings) |
class ConvBlock(nn.Module):
def __init__(self, f1, f2, kernel_size=3, padding=1, use_groupnorm=True, groups=8, dilation=1, transpose=False):
super().__init__()
self.transpose = transpose
self.conv = nn.Conv2d(f1, f2, (kernel_size, kernel_size), dilation=dilation, padding=(padding * dilation)... |
class DarkNetBlock(nn.Module):
expansion = 2
def __init__(self, in_channels, channels):
super().__init__()
self.conv1 = darknetconvlayer(in_channels, channels, kernel_size=1)
self.conv2 = darknetconvlayer(channels, (channels * self.expansion), kernel_size=3, padding=1)
def forward(se... |
def train_model(model, criterion, optimizer, scheduler, num_epochs=25, print_freq=500):
since = time.time()
best_model_wts = copy.deepcopy(model.state_dict())
best_acc = 0.0
for epoch in range(num_epochs):
if ((epoch % print_freq) == 0):
print(('-' * 10))
print(f'Epoch {e... |
def list_files(path):
files = [os.path.join(root, f) for (root, dirs, files) in os.walk(path) for f in files]
return files |
_module()
class DDOD(SingleStageDetector):
def __init__(self, backbone: ConfigType, neck: ConfigType, bbox_head: ConfigType, train_cfg: OptConfigType=None, test_cfg: OptConfigType=None, data_preprocessor: OptConfigType=None, init_cfg: OptMultiConfig=None) -> None:
super().__init__(backbone=backbone, neck=ne... |
def get_train_iterator(options, dataset):
return make_batch_iterator(options, dataset, shuffle=True, include_partial=False, filter_length=options.train_filter_length, batch_size=options.batch_size, length_to_size=options.length_to_size) |
_model('masked_lm')
class MaskedLMModel(BaseFairseqModel):
def __init__(self, args, encoder):
super().__init__()
self.args = args
self.encoder = encoder
if getattr(args, 'apply_bert_init', False):
self.apply(init_bert_params)
def add_args(parser):
parser.add_a... |
def is_ngram_content(ngram):
for gram in ngram:
if (not (gram in stopset)):
return True
return False |
class HelenDataset(BaseDataset):
def modify_commandline_options(parser, is_train):
return parser
def initialize(self, opt):
self.opt = opt
self.root = opt.dataroot
self.path = make_dataset(os.path.join(opt.dataroot))
self.path = sorted(self.path)
self.size = len(s... |
_traceback
def handle_dm_reply(cpu, data, size):
t4 = time.time()
def ieee_to_float(sec, nsec):
val = float(socket.ntohl(sec))
val += (float(socket.ntohl(nsec)) / (10 ** 9))
return val
dm = ct.cast(data, ct.POINTER(DM_TLV)).contents
if (not (dm.session_id in Link.dm_sessions)):
... |
def build_stats(counts):
stats = {'status': 0, 'reportnum': counts['reportnum'], 'title': counts['title'], 'author': counts['auth_group'], 'url': counts['url'], 'doi': counts['doi'], 'misc': counts['misc']}
stats_str = ('%(status)s-%(reportnum)s-%(title)s-%(author)s-%(url)s-%(doi)s-%(misc)s' % stats)
stats[... |
def decode_ans(ans_json, px='p1'):
ans = json.loads(ans_json)[0]
ans1 = [ans[key]['on'] for key in [(px + '1a'), (px + '1b'), (px + '1c')]]
if any(ans1):
x = ans1.index(True)
else:
x = (- 1)
ans2 = [ans[key]['on'] for key in [(px + '2a'), (px + '2b'), (px + '2c')]]
if any(ans2):
... |
def collect_words(path, lower):
word_set = set()
with jsonlines.open(path, 'r') as reader:
for obj in reader:
for key in ['sentence1', 'sentence2']:
sentence = obj[key]
if lower:
sentence = sentence.lower()
words = word_toke... |
def process(sentence, frames, elements, tokenizer, frame_vocabulary, element_vocabulary, max_length):
(input_ids, is_heads) = ([], [])
sentence = ((['[CLS]'] + sentence) + ['[SEP]'])
frame_label = (['<unk>'] * len(sentence))
element_id = []
for word in sentence:
token = (tokenizer.tokenize(w... |
class SensorManager(Singleton):
def __init__(self, world, blueprint, vehicle, param_dict):
self.world = world
self.blueprint = blueprint
self.vehicle = vehicle
self.param_dict = param_dict
self.sensor_dict = {}
self.known_sensors = ['camera', 'lidar', 'imu', 'gnss', '... |
class TestBatchNormalization(object):
def test_batch_normalization(self):
input_shape = [1, 3, 224, 224]
output_shape = [1, 3, 224, 224]
X = onnx.helper.make_tensor_value_info('X', onnx.TensorProto.FLOAT, input_shape)
scale = onnx.helper.make_tensor_value_info('scale', onnx.TensorPro... |
class TaggedValueMeta(type):
def __init__(cls, name, bases, dict):
for fn_name in cls._proxies.keys():
try:
dummy = getattr(cls, fn_name)
except AttributeError:
setattr(cls, fn_name, ProxyDelegate(fn_name, cls._proxies[fn_name])) |
def get_midpoint(tuple_1, tuple_2):
return tuple([(sum(_) / 2.0) for _ in zip(tuple_1, tuple_2)]) |
class GLPNForDepthEstimation(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def create_dummy_class(klass, dependency, message=''):
err = "Cannot import '{}', therefore '{}' is not available.".format(dependency, klass)
if message:
err = ((err + ' ') + message)
class _DummyMetaClass(type):
def __getattr__(_, __):
raise ImportError(err)
class _Dummy(obj... |
def build_sampler(cfg, **kwargs):
if isinstance(cfg, samplers.BaseSampler):
return cfg
elif isinstance(cfg, dict):
return mmcv.runner.obj_from_dict(cfg, samplers, default_args=kwargs)
else:
raise TypeError('Invalid type {} for building a sampler'.format(type(cfg))) |
class MultivariateEuclideanNormal(torch.distributions.MultivariateNormal, VaeDistribution):
def log_prob(self, value):
return super().log_prob(value).sum(dim=(- 1)) |
def main(unused_argv):
tf.logging.info('Reading list of images...')
image_paths = _ReadImageList(cmd_args.list_images_path)
batch_get_feature(image_paths, cmd_args.config_path, cmd_args.output_dir) |
def test_interpolation_potential_dvcircdR():
rzpot = potential.interpRZPotential(RZPot=potential.MWPotential, rgrid=(0.01, 2.0, 201), logR=False, interpdvcircdr=True, zsym=True)
rs = numpy.linspace(0.01, 2.0, 21)
for r in rs:
assert (numpy.fabs(((rzpot.dvcircdR(r) - potential.dvcircdR(potential.MWPo... |
def osnet_x1_0_efdmix23_a0d1(num_classes=1000, pretrained=True, loss='softmax', **kwargs):
model = OSNet(num_classes, blocks=[OSBlock, OSBlock, OSBlock], layers=[2, 2, 2], channels=[64, 256, 384, 512], loss=loss, efdmix_layers=['conv2', 'conv3'], efdmix_alpha=0.1, **kwargs)
if pretrained:
init_pretraine... |
class TreeLSTMNode():
def __init__(self, h=None, c=None, parent=None, children=[], num=0):
self.label = None
self.h = h
self.c = c
self.parent = parent
self.children = children
self.num = num |
class STResUNetBase(ResUNetBase):
CONV_TYPE = ConvType.SPATIAL_HYPERCUBE_TEMPORAL_HYPERCROSS
def __init__(self, in_channels, out_channels, config, D=4, **kwargs):
super(STResUNetBase, self).__init__(in_channels, out_channels, config, D, **kwargs) |
class DotProduct_Classifier(nn.Module):
def __init__(self, num_classes=1000, feat_dim=2048, *args):
super(DotProduct_Classifier, self).__init__()
self.fc = nn.Linear(feat_dim, num_classes)
def forward(self, x, *args):
x = self.fc(x)
return (x, None) |
def __name_getter(dictionary: mapType, previous_name, previous_names):
for (k, v) in dictionary.items():
if (previous_name == ''):
previous_names.append(k)
else:
previous_names.append(((str(previous_name) + '.') + str(k)))
for (k, v) in dictionary.items():
if isin... |
_vision
class AlignProcessorTest(unittest.TestCase):
def setUp(self):
self.tmpdirname = tempfile.mkdtemp()
vocab_tokens = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest']
self.vocab_file = os.path.join(self.tmpdirname... |
def _match_checkpoint_pattern(name):
pattern = _checkpoint_pattern()
return pattern.match(name) |
class ToLabel(object):
def __call__(self, image):
return torch.from_numpy(np.array(image)).long().unsqueeze(0) |
_registry(operator_type='StopGradient')
class StopGradient(Operator):
def __init__(self):
super().__init__() |
class LocalResNetEncoderGroupNorm(Encoder):
def __init__(self, levels, in_planes, out_planes, hidden_planes, activation, num_groups):
super(LocalResNetEncoderGroupNorm, self).__init__()
layers = list()
assert (len(hidden_planes) == levels)
assert (len(num_groups) == levels)
f... |
def evaluate(encoder, args, batch_trains, classifier, classifiers, eval_sents, domain_encs):
good_sent = bad_sent = good = bad = 0.0
for sent in eval_sents:
(words, golds) = zip(*sent)
probs = [classifier(encoder(words, volatile=True)) for ath in classifiers]
outputs = sum(probs)
... |
class HyperOptimizer(PathOptimizer):
compressed = False
multicontraction = False
def __init__(self, methods=None, minimize='flops', max_repeats=128, max_time=None, parallel='auto', slicing_opts=None, slicing_reconf_opts=None, reconf_opts=None, optlib=None, space=None, score_compression=0.75, on_trial_error=... |
.parametrize('input_data,expected', testdata)
def test_sieve(input_data, expected):
assert (sieve(*input_data) == expected) |
class InputFeatures(object):
def __init__(self, example_id, choices_features, label):
self.example_id = example_id
self.choices_features = [{'input_ids': input_ids, 'input_mask': input_mask, 'segment_ids': segment_ids} for (_, input_ids, input_mask, segment_ids) in choices_features]
self.lab... |
def inference_prob_recurrent(images, cams, depth_num, depth_start, depth_interval, is_master_gpu=True):
depth_end = (depth_start + ((tf.cast(depth_num, tf.float32) - 1) * depth_interval))
ref_image = tf.squeeze(tf.slice(images, [0, 0, 0, 0, 0], [(- 1), 1, (- 1), (- 1), 3]), axis=1)
ref_cam = tf.squeeze(tf.s... |
def ade_palette():
return [[120, 120, 120], [180, 120, 120], [6, 230, 230], [80, 50, 50], [4, 200, 3], [120, 120, 80], [140, 140, 140], [204, 5, 255], [230, 230, 230], [4, 250, 7], [224, 5, 255], [235, 255, 7], [150, 5, 61], [120, 120, 70], [8, 255, 51], [255, 6, 82], [143, 255, 140], [204, 255, 4], [255, 51, 7], [... |
class NoamScheduler(BaseScheduler):
def __init__(self, hidden_size: int, optimizer: torch.optim.Optimizer, factor: float=1.0, warmup: int=4000):
super().__init__(optimizer)
self.warmup = warmup
self.factor = factor
self.hidden_size = hidden_size
def _compute_rate(self):
s... |
def find_lr(init_value=1e-06, final_value=0.001, beta=0.7):
num = (len(trainset_loader) - 1)
mult = ((final_value / init_value) ** (1 / num))
lr = init_value
optimizer.param_groups[0]['lr'] = lr
avg_loss = 0.0
best_loss = 0.0
batch_num = 0
losses = []
log_lrs = []
for (imgs, dict... |
def test_get_by_dotted_path():
assert (get_by_dotted_path({'a': 12}, 'a') == 12)
assert (get_by_dotted_path({'a': 12}, '') == {'a': 12})
assert (get_by_dotted_path({'foo': {'a': 12}}, 'foo.a') == 12)
assert (get_by_dotted_path({'foo': {'a': 12}}, 'foo.b') is None) |
def get_repo(path=PROJECT_PATH, search_parent_directories=True):
repo = git.Repo(path, search_parent_directories=search_parent_directories)
return repo |
def _assert_tensors_equal(a, b, atol=1e-12, prefix=''):
if ((a is None) and (b is None)):
return True
try:
if torch.allclose(a, b, atol=atol):
return True
raise
except Exception:
msg = '{} != {}'.format(a, b)
if prefix:
msg = ((prefix + ': ') +... |
def clean_custom_task(task_info):
import transformers
if ('impl' not in task_info):
raise RuntimeError('This model introduces a custom pipeline without specifying its implementation.')
pt_class_names = task_info.get('pt', ())
if isinstance(pt_class_names, str):
pt_class_names = [pt_class... |
def query_environment(name):
env = gym.make(name)
spec = gym.spec(name)
print(f'Action Space: {env.action_space}')
print(f'Observation Space: {env.observation_space}')
print(f'Max Episode Steps: {spec.max_episode_steps}')
print(f'Nondeterministic: {spec.nondeterministic}')
print(f'Reward Ran... |
def _goes_first(is_main):
if (is_main is False):
wait_for_everyone()
(yield)
if (is_main is True):
wait_for_everyone() |
def initialize_replay_buffer(self, examples, batch_spec, async_=False):
example_to_buffer = SamplesToBuffer(observation=examples['observation'], action=examples['action'], reward=examples['reward'], done=examples['done'])
replay_kwargs = dict(example=example_to_buffer, size=self.replay_size, B=batch_spec.B, rnn... |
def create_visdom(session_name, configuration):
if ((configuration is None) or (configuration.server is None)):
return None
from visdom import Visdom
return Visdom(env=session_name, **configuration.as_dict()) |
_module()
class COCOStuffDataset(CustomDataset):
CLASSES = ('person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backpack'... |
def spotifyShuffle(songs_list, artists_list):
artist2songs = defaultdict(list)
for (artist, song) in zip(artists_list, songs_list):
artist2songs[artist].append(song)
songList = []
songsLocs = []
for (artist, songs) in artist2songs.items():
songs = fisherYatesShuffle(songs)
so... |
def main():
desc_dict = datasets.load_code_descriptions()
print('loading attn windows')
attn_windows = {}
attn_window_szs = {}
with open(ATTN_FILENAME, 'r') as f:
r = csv.reader(f)
next(r)
for row in r:
attn_windows[(int(row[0]), row[1])] = int(row[2])
... |
class AlexNet(nn.Module):
def __init__(self, num_classes=(- 1)):
super(AlexNet, self).__init__()
self.num_classes = num_classes
self.features = nn.Sequential(nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=3, stride=2), nn.Conv2d(64, 192... |
def generator_loss(loss_func, fake):
loss = []
fake_loss = 0
for i in range(2):
if loss_func.__contains__('wgan'):
fake_loss = (- tf.reduce_mean(fake[i]))
if (loss_func == 'lsgan'):
fake_loss = tf.reduce_mean(tf.squared_difference(fake[i], 1.0))
if ((loss_func... |
def print_usage():
usageStr = '\n Make sure to keep the terminal window in focus!\r\n \n Use the following keys to drive the robot:\r\n\n \tW: Increase speed\r\n \tS: Decrease speed\r\n \tA: Turn more left\r\n \tD: Turn more right\r\n \tR: Reset controls\r\... |
def mlp(sizes, activation, output_activation=nn.Identity):
layers = []
for j in range((len(sizes) - 1)):
act = (activation if (j < (len(sizes) - 2)) else output_activation)
layers += [nn.Linear(sizes[j], sizes[(j + 1)]), act()]
return nn.Sequential(*layers) |
def test_tetris_env_step(tetris_env: Tetris) -> None:
chex.clear_trace_counter()
step_fn = jax.jit(chex.assert_max_traces(tetris_env.step, n=1))
key = jax.random.PRNGKey(0)
(state, timestep) = tetris_env.reset(key)
action = (0, 4)
step_fn(state, action)
step_fn(state, action)
step_fn(sta... |
class XFMREncoder(nn.Module):
def __init__(self, d_model, num_layers, self_attn, feed_forward, use_residual=False, dropout=0.1):
super(XFMREncoder, self).__init__()
self.layers = nn.ModuleList([EncoderLayer(d_model, self_attn, feed_forward, use_residual, dropout) for _ in range(num_layers)])
... |
class handpose_model(nn.Module):
def __init__(self):
super(handpose_model, self).__init__()
no_relu_layers = ['conv6_2_CPM', 'Mconv7_stage2', 'Mconv7_stage3', 'Mconv7_stage4', 'Mconv7_stage5', 'Mconv7_stage6']
block1_0 = OrderedDict([('conv1_1', [3, 64, 3, 1, 1]), ('conv1_2', [64, 64, 3, 1, ... |
def set_parser():
parser = argparse.ArgumentParser(description='')
parser.add_argument('-d', '--data', type=str, required=True, help='path to a folder containing days to be predicted (e.g. the test folder of the test dataset)')
parser.add_argument('-r', '--region', type=str, required=False, default='R1', he... |
class Wav2Vec2ForXVector(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class SGDP(Optimizer):
def __init__(self, params, lr=required, momentum=0, dampening=0, weight_decay=0, nesterov=False, eps=1e-08, delta=0.1, wd_ratio=0.1):
defaults = dict(lr=lr, momentum=momentum, dampening=dampening, weight_decay=weight_decay, nesterov=nesterov, eps=eps, delta=delta, wd_ratio=wd_ratio)
... |
def get_n_params(model):
return (str(np.round((np.array([p.numel() for p in model.parameters()]).sum() / 1000000.0), 3)) + ' M params') |
def test_dev_vis():
r = MPRenderer()
scenario_name = 'USA_Lanker-1_1_T-1'
(scenario, _) = load_commonroad_scenario(scenario_name)
draw_params = MPDrawParams()
fn = os.path.join(OUT_TESTS_DIR, 'default_params.yaml')
draw_params.save(fn)
lanelet_net_params = LaneletNetworkParams()
lanelet_... |
def PrintIndentifiers(filename, should_print):
source = utils.ReadFile(filename, False)
if (source is None):
sys.stderr.write(('Unable to find: %s\n' % filename))
return
builder = BuilderFromSource(source, filename)
try:
for node in builder.Generate():
if should_print... |
class CTRLConfig(PretrainedConfig):
pretrained_config_archive_map = CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP
model_type = 'ctrl'
def __init__(self, vocab_size=246534, n_positions=256, n_ctx=256, n_embd=1280, dff=8192, n_layer=48, n_head=16, resid_pdrop=0.1, embd_pdrop=0.1, attn_pdrop=0.1, layer_norm_epsilon=1e-06... |
def packed_dtype_fmt():
from sys import byteorder
return "[('bool_', '?'), ('uint_', '{e}u4'), ('float_', '{e}f4'), ('ldbl_', '{e}f{}')]".format(np.dtype('longdouble').itemsize, e=('<' if (byteorder == 'little') else '>')) |
def decode_tf(FILENAME):
basename = os.path.basename(FILENAME)[:(- 9)]
if (not os.path.exists((('./waymo_decode_val/' + basename) + '/intrinsic/'))):
os.makedirs((('./waymo_decode_val/' + basename) + '/intrinsic/'))
dataset = tf.data.TFRecordDataset(FILENAME, compression_type='')
count = 0
f... |
class MobileNetV2(nn.Module):
def __init__(self, num_classes=1000, width_mult=1.0, inverted_residual_setting=None, round_nearest=8):
super(MobileNetV2, self).__init__()
block = InvertedResidual
input_channel = 32
last_channel = 1280
if (inverted_residual_setting is None):
... |
_module()
class OBBDoubleConvFCBBoxHead(OBBoxHead):
def __init__(self, num_convs=0, num_fcs=0, conv_out_channels=1024, fc_out_channels=1024, conv_cfg=None, norm_cfg=dict(type='BN'), **kwargs):
kwargs.setdefault('with_avg_pool', True)
super(OBBDoubleConvFCBBoxHead, self).__init__(**kwargs)
as... |
def load_model(model_name, tokenizer_name, device='cpu', use_hpu_graphs=False, cpu_jit=False, ipex_int8=False, use_cache=True, peft_path=None, use_deepspeed=False, optimization_config=None, hf_access_token=None, use_llm_runtime=False, assistant_model=None):
print('Loading model {}'.format(model_name))
if (devic... |
def test_fetch_metadata_function_with_exp_name(tmpdir):
root = tmpdir.strpath
run_test_experiment(exp_name='experiment 1 alpha', exp_id='1234', root_dir=root)
run_test_experiment(exp_name='experiment 2 beta', exp_id='5678', root_dir=root)
run_test_experiment(exp_name='experiment 3 alpha', exp_id='9990',... |
def convert_data():
datasets = [x for x in os.listdir(RAW_DIR) if ('.' not in x)]
for dataset in tqdm(datasets):
save_loc = ((PROCESSED_DIR + '/') + dataset)
if os.path.exists(save_loc):
print('Skipping {} as folder exists at {}. Remove it to reconvert.'.format(dataset, save_loc))
... |
def tokenize(key_to_word):
key_to_sentence = {}
for (k, v) in key_to_word.items():
key_to_sentence[k] = [clean(w) for w in v if (clean(w) != '')]
return key_to_sentence |
def build_fake_yaml():
fake_yaml = '\n model:\n name: fake_yaml\n framework: tensorflow\n inputs: input\n outputs: op_to_store\n device: cpu\n quantization:\n model_wise:\n weight:\n granularity: per_tensor\n ... |
(sample=sampled_from([(((- 1), 10), (5, 2, 10), (5, 10), (5, 10)), (((- 1), 10), (5, 4, 2, 10), (5, 4, 10), (20, 10)), ((10, 2, 10), (20, 2, 10), (20, 10), (10, 2, 10)), (((- 1), 10), (2, 5), (5,), RuntimeError), ((2, 10), (5, 2, 10), (5, 10), RuntimeError)]))
def test_reshape(sample):
(target_shape, input_data_sha... |
class PipelineChunkIterator(PipelineIterator):
def __init__(self, loader, infer, params, loader_batch_size=None):
super().__init__(loader, infer, params)
def __iter__(self):
self.iterator = iter(self.loader)
self.subiterator = None
return self
def __next__(self):
if (... |
def evaluate_metrics_from_lists(predictions: List[str], ground_truths: List[List[str]], ids: Union[(List[int], None)]=None) -> Tuple[(Dict[(str, float)], Dict[(int, Dict[(str, float)])])]:
assert (len(predictions) == len(ground_truths))
assert all([(len(i) == 1) for i in ground_truths])
if (ids is None):
... |
class PeriodicBoxingDynamics(PeriodicVelocityVerlet):
def __init__(self, Force_, BoxingLatp_=np.eye(3), name_='PdicBoxMD', BoxingT_=400):
self.PForce = Force_
self.BoxingLat0 = Force_.lattice.lattice.copy()
self.BoxingLatp = BoxingLatp_.copy()
self.BoxingT = BoxingT_
Velocity... |
def roc(tests=[]):
x = FPR = (lambda TP, TN, FP, FN: (float(FP) / ((FP + TN) or 1)))
y = TPR = (lambda TP, TN, FP, FN: (float(TP) / ((TP + FN) or 1)))
return sorted(([(0.0, 0.0), (1.0, 1.0)] + [(x(*m), y(*m)) for m in tests])) |
class TFParkSampleToMiniBatch(Preprocessing):
def __init__(self, batch_size, drop_remainder, bigdl_type='float'):
super(TFParkSampleToMiniBatch, self).__init__(bigdl_type, batch_size, drop_remainder) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.