code stringlengths 101 5.91M |
|---|
def eval_expr(interpreter: Interpreter, in_values: List[Any], out_value: Any, expr: Expr):
return ExprVisitor(interpreter, in_values, out_value).visit(expr) |
class AudioVarianceScaling(Initializer):
def __init__(self, scale=1.0, mode='fan_in', distribution='truncated_normal', seed=None, dtype=tf.float32):
if (scale <= 0.0):
raise ValueError('`scale` must be positive float.')
if (mode not in {'fan_in', 'fan_out', 'fan_avg'}):
raise ValueError('Invalid `mode` argument:', mode)
distribution = distribution.lower()
if (distribution not in {'uniform', 'truncated_normal', 'untruncated_normal'}):
raise ValueError('Invalid `distribution` argument:', distribution)
self.scale = scale
self.mode = mode
self.distribution = distribution
self.seed = seed
self.dtype = tf.as_dtype(dtype)
def __call__(self, shape, dtype=None, partition_info=None):
if (dtype is None):
dtype = self.dtype
scale = self.scale
scale_shape = shape
if (partition_info is not None):
scale_shape = partition_info.full_shape
(fan_in, fan_out) = _compute_audio_fans(scale_shape)
if (self.mode == 'fan_in'):
scale /= max(1.0, fan_in)
elif (self.mode == 'fan_out'):
scale /= max(1.0, fan_out)
else:
scale /= max(1.0, ((fan_in + fan_out) / 2.0))
if ((self.distribution == 'normal') or (self.distribution == 'truncated_normal')):
stddev = (math.sqrt(scale) / 0.)
return tf.truncated_normal(shape, 0.0, stddev, dtype, seed=self.seed)
elif (self.distribution == 'untruncated_normal'):
stddev = math.sqrt(scale)
return tf.random_normal(shape, 0.0, stddev, dtype, seed=self.seed)
else:
limit = math.sqrt((3.0 * scale))
return tf.random_uniform(shape, (- limit), limit, dtype, seed=self.seed)
def get_config(self):
return {'scale': self.scale, 'mode': self.mode, 'distribution': self.distribution, 'seed': self.seed, 'dtype': self.dtype.name} |
def handle_propagation_add_coeff(weights, additional_coeffs, lower_bounds):
mus = []
final_lay_idx = len(weights)
if (final_lay_idx in additional_coeffs):
mu = (- additional_coeffs[final_lay_idx])
lay_idx = final_lay_idx
else:
add_coeff = next(iter(additional_coeffs.values()))
batch_size = add_coeff.shape[:2]
device = lower_bounds[(- 1)].device
lay_idx = (final_lay_idx - 1)
while (lay_idx not in additional_coeffs):
lay_shape = lower_bounds[lay_idx].shape[1:]
mus.append(torch.zeros(((*batch_size,) + lay_shape), device=device))
lay_idx -= 1
mu = (- additional_coeffs[lay_idx])
mus.append(torch.zeros_like(mu))
lay_idx -= 1
return (mus, mu, lay_idx) |
class Rprop(Optimizer):
def __init__(self, params, lr=0.01, etas=(0.5, 1.2), step_sizes=(1e-06, 50)):
if (not (0.0 <= lr)):
raise ValueError('Invalid learning rate: {}'.format(lr))
if (not (0.0 < etas[0] < 1.0 < etas[1])):
raise ValueError('Invalid eta values: {}, {}'.format(etas[0], etas[1]))
defaults = dict(lr=lr, etas=etas, step_sizes=step_sizes)
super(Rprop, self).__init__(params, defaults)
_grad()
def step(self, closure=None):
loss = None
if (closure is not None):
with torch.enable_grad():
loss = closure()
grads = []
states = []
params_with_grad = []
step_sizes = []
for group in self.param_groups:
for p in group['params']:
(etaminus, etaplus) = group['etas']
(step_size_min, step_size_max) = group['step_sizes']
if (p.grad is not None):
if p.grad.is_sparse:
raise RuntimeError('RMSprop does not support sparse gradients')
grads.append(p.grad)
params_with_grad.append(p)
state = self.state[p]
if (len(state) == 0):
state['step'] = 0
state['prev'] = torch.zeros_like(p, memory_format=torch.preserve_format)
state['step_size'] = p.grad.new().resize_as_(p.grad).fill_(group['lr'])
state['step'] += 1
states.append(state)
step_sizes.append(state['step_size'])
signs = torch._foreach_mul(grads, [s['prev'] for s in states])
signs = [s.sign() for s in signs]
for sign in signs:
sign[sign.gt(0)] = etaplus
sign[sign.lt(0)] = etaminus
sign[sign.eq(0)] = 1
torch._foreach_mul_(step_sizes, signs)
for step_size in step_sizes:
step_size.clamp_(step_size_min, step_size_max)
for i in range(len(grads)):
grads[i] = grads[i].clone(memory_format=torch.preserve_format)
grads[i][signs[i].eq(etaminus)] = 0
grad_signs = [grad.sign() for grad in grads]
torch._foreach_addcmul_(params_with_grad, grad_signs, step_sizes, value=(- 1))
for i in range(len(states)):
states[i]['prev'].copy_(grads[i])
return loss
def zero_grad(self, set_to_none: bool=False):
per_device_and_dtype_grads = defaultdict((lambda : defaultdict(list)))
for group in self.param_groups:
for p in group['params']:
if (p.grad is not None):
if set_to_none:
p.grad = None
else:
if (p.grad.grad_fn is not None):
p.grad.detach_()
else:
p.grad.requires_grad_(False)
if p.grad.is_sparse:
p.grad.zero_()
else:
per_device_and_dtype_grads[p.grad.device][p.grad.dtype].append(p.grad)
for (_, per_dtype_grads) in per_device_and_dtype_grads.items():
for grads in per_dtype_grads.values():
torch._foreach_zero_(grads) |
class ConvLayer(My2DLayer):
def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, dilation=1, groups=1, bias=False, has_shuffle=False, use_bn=True, act_func='relu', dropout_rate=0, ops_order='weight_bn_act'):
self.kernel_size = kernel_size
self.stride = stride
self.dilation = dilation
self.groups = groups
self.bias = bias
self.has_shuffle = has_shuffle
super(ConvLayer, self).__init__(in_channels, out_channels, use_bn, act_func, dropout_rate, ops_order)
def weight_op(self):
padding = get_same_padding(self.kernel_size)
if isinstance(padding, int):
padding *= self.dilation
else:
padding[0] *= self.dilation
padding[1] *= self.dilation
weight_dict = OrderedDict()
weight_dict['conv'] = nn.Conv2d(self.in_channels, self.out_channels, kernel_size=self.kernel_size, stride=self.stride, padding=padding, dilation=self.dilation, groups=self.groups, bias=self.bias)
if (self.has_shuffle and (self.groups > 1)):
weight_dict['shuffle'] = ShuffleLayer(self.groups)
return weight_dict
def module_str(self):
if isinstance(self.kernel_size, int):
kernel_size = (self.kernel_size, self.kernel_size)
else:
kernel_size = self.kernel_size
if (self.groups == 1):
if (self.dilation > 1):
return ('%dx%d_DilatedConv' % (kernel_size[0], kernel_size[1]))
else:
return ('%dx%d_Conv' % (kernel_size[0], kernel_size[1]))
elif (self.dilation > 1):
return ('%dx%d_DilatedGroupConv' % (kernel_size[0], kernel_size[1]))
else:
return ('%dx%d_GroupConv' % (kernel_size[0], kernel_size[1]))
def config(self):
return {'name': ConvLayer.__name__, 'kernel_size': self.kernel_size, 'stride': self.stride, 'dilation': self.dilation, 'groups': self.groups, 'bias': self.bias, 'has_shuffle': self.has_shuffle, **super(ConvLayer, self).config}
def build_from_config(config):
return ConvLayer(**config)
def get_flops(self, x):
return (count_conv_flop(self.conv, x), self.forward(x)) |
def test_serialization_image_masker_inpaint_ns():
test_image_height = 500
test_image_width = 500
test_data = (np.ones((test_image_height, test_image_width, 3)) * 50)
test_shape = (test_image_height, test_image_width, 3)
original_image_masker = shap.maskers.Image('inpaint_ns', test_shape)
with tempfile.TemporaryFile() as temp_serialization_file:
original_image_masker.save(temp_serialization_file)
temp_serialization_file.seek(0)
new_image_masker = shap.maskers.Image.load(temp_serialization_file)
mask = np.ones((test_image_height, test_image_width, 3))
mask = mask.astype(int)
mask[0][0] = 0
mask[4][0] = 0
assert np.array_equal(original_image_masker(mask, test_data), new_image_masker(mask, test_data)) |
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):
return (self.indices[i] for i in torch.randperm(len(self.indices), generator=self.generator))
def __len__(self):
return len(self.indices) |
def clean_up(text):
text = text.replace('<pad>', '')
text = text.replace('</s>', '')
text = text.replace('.', '')
text = text.replace(',', '')
text = text.replace("'", '')
text = text.replace('"', '')
return text |
def add_predictor(decoder):
p = DummyPredictor(vocab_size=20)
decoder.add_predictor('dummy', p) |
def get_emdedding_layer():
return Embedding(MAX_NUM_WORDS, EMBEDDING_DIM, weights=[embedding_matrix], input_length=MAX_SEQUENCE_LENGTH, trainable=False) |
def main():
args = arg_parser()
print('')
print(args)
print('')
print(f'API_KEY: {API_KEY}')
set_random_seed(args.random_seed)
dataloader = create_dataloader(args)
if (args.dataset_size > 1000):
dataloader = dataloader[:1000]
print(f'Dataloader size: {len(dataloader)}')
if (args.qes_limit == 0):
args.qes_limit = len(dataloader)
start = time.time()
result = create_uncertainty(args, dataloader)
end = time.time()
print('Total Execution Time: ', (end - start), ' seconds')
path = f'{args.output_dir}/uncertainty_result_{args.dataset}_k{args.num_trails}.txt'
with open(path, 'w') as f:
try:
f.write(json.dumps(result, indent=4))
except:
for item in result:
try:
if (args.dataset in ('gsm8k', 'asdiv', 'svamp', 'singleeq', 'addsub', 'multiarith')):
f.write(f'''{item}, uncertainty: {len(item[(- 1)])}, variance: {item[1]}
''')
else:
f.write(f'''{item}, uncertainty: {len(item[(- 1)])}
''')
except:
pass |
class HDict(MDict):
I = Inherit
def set_parent(self, parent):
self.__dict__['_parent'] = parent
return self
def get_parent(self):
return self.__dict__.get('_parent', None)
def __call__(self, parent):
return self.set_parent(parent)
def get_dict(self):
ret = super().get_dict()
for (key, value) in ret.items():
if isinstance(value, HDict):
ret.update({key: value.get_dict()})
return ret |
def replace_properties(node: Any, symrepl: Dict[(symbolic.symbol, symbolic.SymbolicType)], name: str, new_name: str):
replace_properties_dict(node, {name: new_name}, symrepl) |
def nullspace_GF(n=300, p=16411, system='sage'):
if (system == 'sage'):
A = random_matrix(GF(p), n, (n + 1))
t = cputime()
v = A.kernel()
return cputime(t)
elif (system == 'magma'):
code = ('\nn := %s;\nA := Random(RMatrixSpace(GF(%s), n, n+1));\nt := Cputime();\nK := Kernel(A);\ns := Cputime(t);\n' % (n, p))
if verbose:
print(code)
magma.eval(code)
return magma.eval('s')
else:
raise ValueError(('unknown system "%s"' % system)) |
class TestDynamicQuantizedLinear(TestCase):
_qengines
(batch_size=st.integers(1, 4), input_channels=st.integers(16, 32), output_channels=st.integers(4, 8), use_bias=st.booleans(), use_relu=st.booleans(), use_multi_dim_input=st.booleans(), use_channelwise=st.booleans(), reduce_range=st.booleans())
def test_qlinear(self, batch_size, input_channels, output_channels, use_bias, use_relu, use_multi_dim_input, use_channelwise, reduce_range):
if (torch.backends.quantized.engine == 'qnnpack'):
use_relu = False
reduce_range = False
qlinear_prepack = torch.ops.quantized.linear_prepack
if use_relu:
qlinear_dynamic = torch.ops.quantized.linear_relu_dynamic
else:
qlinear_dynamic = torch.ops.quantized.linear_dynamic
if use_multi_dim_input:
batch_size *= 3
X_scale = 1.0
X_zp = 0
X_value_min = 0
X_value_max = 255
if reduce_range:
X_value_max = 127
X_q0 = np.round(((np.random.rand(batch_size, input_channels) * (X_value_max - X_value_min)) + X_value_min)).astype(np.uint8)
X_q0[(0, 0)] = X_value_min
X_q0[(0, 1)] = X_value_max
W_scales = np.ones(output_channels)
W_zps = np.zeros(output_channels).astype(np.int)
W_value_min = (- 128)
W_value_max = 127
W_q0 = np.round(((np.random.rand(output_channels, input_channels) * (W_value_max - W_value_min)) + W_value_min)).astype(np.int8)
W_q0[(0, 0)] = W_value_min
W_q0[(1, 0)] = W_value_max
b_value_min = (- 10)
b_value_max = 10
b_q0 = (np.round(((np.random.rand(output_channels) * (b_value_max - b_value_min)) + b_value_min)).astype(np.int32) if use_bias else None)
if (torch.backends.quantized.engine == 'fbgemm'):
avoid_vpmaddubsw_overflow_linear(batch_size, input_channels, output_channels, X_q0, X_value_min, X_value_max, W_q0, W_value_min, W_value_max)
X_fp32 = torch.from_numpy(_dequantize(X_q0, X_scale, X_zp)).to(dtype=torch.float)
if use_multi_dim_input:
X_fp32 = X_fp32.view(3, int((batch_size / 3)), input_channels)
if use_channelwise:
W_fp32 = torch.from_numpy(_dequantize(W_q0, W_scales.reshape(((- 1), 1)), W_zps.reshape(((- 1), 1)))).to(dtype=torch.float)
W_q = torch.quantize_per_channel(W_fp32, scales=torch.from_numpy(W_scales), zero_points=torch.from_numpy(W_zps), axis=0, dtype=torch.qint8)
b_fp32 = (torch.from_numpy(_dequantize(b_q0, (X_scale * W_scales), 0)).to(dtype=torch.float) if use_bias else None)
else:
W_fp32 = torch.from_numpy(_dequantize(W_q0, W_scales[0], W_zps[0])).to(dtype=torch.float)
W_q = torch.quantize_per_tensor(W_fp32, scale=W_scales[0], zero_point=W_zps[0].astype(int).item(), dtype=torch.qint8)
b_fp32 = (torch.from_numpy(_dequantize(b_q0, (X_scale * int(W_scales[0].item())), 0)).to(dtype=torch.float) if use_bias else None)
(X_scale, X_zp) = _calculate_dynamic_qparams(X_fp32, torch.quint8, reduce_range)
X_q = torch.quantize_per_tensor(X_fp32, scale=X_scale, zero_point=X_zp, dtype=torch.quint8)
W_prepack = qlinear_prepack(W_q, b_fp32)
Y_fp32 = qlinear_dynamic(X_q.dequantize(), W_prepack, reduce_range)
Y_fp32_ref = F.linear(X_q.dequantize(), W_q.dequantize(), b_fp32)
if use_relu:
Y_fp32_ref[(Y_fp32_ref < 0.0)] = 0.0
self.assertEqual(Y_fp32, Y_fp32_ref, msg='torch.ops.quantized.linear_dynamic results are off')
(batch_size=st.integers(1, 4), input_channels=st.integers(16, 32), output_channels=st.integers(4, 8))
def test_qlinear_legacy(self, batch_size, input_channels, output_channels):
X_scale = 1.0
X_zp = 0
X_value_min = 0
X_value_max = 255
X_q0 = np.round(((np.random.rand(batch_size, input_channels) * (X_value_max - X_value_min)) + X_value_min)).astype(np.uint8)
X_q0[(0, 0)] = X_value_min
X_q0[(0, 1)] = X_value_max
W_scale = 1.0
W_zp = 0
W_value_min = (- 128)
W_value_max = 127
W_q0 = np.round(((np.random.rand(output_channels, input_channels) * (W_value_max - W_value_min)) + W_value_min)).astype(np.int8)
W_q0[(0, 0)] = W_value_min
W_q0[(1, 0)] = W_value_max
b_value_min = (- 10)
b_value_max = 10
b_q0 = np.round(((np.random.rand(output_channels) * (b_value_max - b_value_min)) + b_value_min)).astype(np.int32)
avoid_vpmaddubsw_overflow_linear(batch_size, input_channels, output_channels, X_q0, X_value_min, X_value_max, W_q0, W_value_min, W_value_max)
X_fp32 = torch.from_numpy(_dequantize(X_q0, X_scale, X_zp)).to(dtype=torch.float)
W_fp32 = torch.from_numpy(_dequantize(W_q0, W_scale, W_zp)).to(dtype=torch.float)
b_fp32 = torch.from_numpy(_dequantize(b_q0, (X_scale * W_scale), 0)).to(dtype=torch.float)
(W_scale, W_zp) = _calculate_dynamic_qparams(W_fp32, torch.qint8)
W_q = torch.quantize_per_tensor(W_fp32, scale=W_scale, zero_point=W_zp, dtype=torch.qint8)
(X_scale, X_zp) = _calculate_dynamic_qparams(X_fp32, torch.quint8)
X_q = torch.quantize_per_tensor(X_fp32, scale=X_scale, zero_point=X_zp, dtype=torch.quint8)
(W_int8, col_offsets, W_scale, W_zp) = torch.fbgemm_linear_quantize_weight(W_q.dequantize())
W_prepack = torch.fbgemm_pack_quantized_matrix(W_int8.clone(), W_int8.size(1), W_int8.size(0))
Y_fp32 = torch.fbgemm_linear_int8_weight(X_q.dequantize(), W_q.dequantize(), W_prepack, col_offsets, W_scale, W_zp, b_fp32)
Y_fp32_ref = F.linear(X_q.dequantize(), W_q.dequantize(), b_fp32)
self.assertEqual(Y_fp32, Y_fp32_ref, msg='torch.ops.quantized.fbgemm_linear_dynamic results are off') |
def split_mixture_params(params, output_dim, num_mixes):
mus = params[:(num_mixes * output_dim)]
sigs = params[(num_mixes * output_dim):((2 * num_mixes) * output_dim)]
pi_logits = params[(- num_mixes):]
return (mus, sigs, pi_logits) |
class EpochBatchIterator(EpochBatchIterating):
def __init__(self, dataset, collate_fn, batch_sampler, seed=1, num_shards=1, shard_id=0, num_workers=0, epoch=0):
assert isinstance(dataset, torch.utils.data.Dataset)
self.dataset = dataset
self.collate_fn = collate_fn
self.frozen_batches = tuple(batch_sampler)
self.seed = seed
self.num_shards = num_shards
self.shard_id = shard_id
self.num_workers = num_workers
self.epoch = epoch
self.shuffle = True
self._cur_epoch_itr = None
self._next_epoch_itr = None
self._supports_prefetch = getattr(dataset, 'supports_prefetch', False)
def __len__(self):
return len(self.frozen_batches)
def next_epoch_itr(self, shuffle=True, fix_batches_to_gpus=False):
if (self._next_epoch_itr is not None):
self._cur_epoch_itr = self._next_epoch_itr
self._next_epoch_itr = None
else:
self.epoch += 1
self._cur_epoch_itr = self._get_iterator_for_epoch(self.epoch, shuffle, fix_batches_to_gpus=fix_batches_to_gpus)
self.dataset.set_epoch(self.epoch)
self.shuffle = shuffle
return self._cur_epoch_itr
def end_of_epoch(self) -> bool:
return (not self._cur_epoch_itr.has_next())
def iterations_in_epoch(self):
if (self._cur_epoch_itr is not None):
return self._cur_epoch_itr.count
elif (self._next_epoch_itr is not None):
return self._next_epoch_itr.count
return 0
def state_dict(self):
return {'epoch': self.epoch, 'iterations_in_epoch': self.iterations_in_epoch, 'shuffle': self.shuffle}
def load_state_dict(self, state_dict):
self.epoch = state_dict['epoch']
itr_pos = state_dict.get('iterations_in_epoch', 0)
if (itr_pos > 0):
self._next_epoch_itr = self._get_iterator_for_epoch(self.epoch, shuffle=state_dict.get('shuffle', True), offset=itr_pos)
def _get_iterator_for_epoch(self, epoch, shuffle, fix_batches_to_gpus=False, offset=0):
def shuffle_batches(batches, seed):
with data_utils.numpy_seed(seed):
np.random.shuffle(batches)
return batches
if self._supports_prefetch:
batches = self.frozen_batches
if (shuffle and (not fix_batches_to_gpus)):
batches = shuffle_batches(list(batches), (self.seed + epoch))
batches = list(ShardedIterator(batches, self.num_shards, self.shard_id, fill_value=[]))
self.dataset.prefetch([i for s in batches for i in s])
if (shuffle and fix_batches_to_gpus):
batches = shuffle_batches(batches, ((self.seed + epoch) + self.shard_id))
else:
if shuffle:
batches = shuffle_batches(list(self.frozen_batches), (self.seed + epoch))
else:
batches = self.frozen_batches
batches = list(ShardedIterator(batches, self.num_shards, self.shard_id, fill_value=[]))
if ((offset > 0) and (offset >= len(batches))):
return None
if (self.num_workers > 0):
os.environ['PYTHONWARNINGS'] = 'ignore:semaphore_tracker:UserWarning'
return CountingIterator(torch.utils.data.DataLoader(self.dataset, collate_fn=self.collate_fn, batch_sampler=batches[offset:], num_workers=self.num_workers), start=offset) |
def pickle_complex_array_and_return_form(pickler_source, tmp_path):
with ProcessPoolExecutor(1, initializer=_init_process_with_pickler, initargs=(pickler_source, tmp_path), mp_context=multiprocessing.get_context('spawn')) as executor:
pickle_future = executor.submit(_pickle_complex_array_and_return_form_impl)
return pickle_future.result() |
class EmitConv2dInstance():
def __init__(self, operation_suffix=''):
self.operation_suffix = operation_suffix
self.includes = ['cutlass/cutlass.h', 'cutlass/conv/kernel/default_conv2d_fprop.h', 'cutlass/conv/kernel/default_conv2d_dgrad.h', 'cutlass/conv/kernel/default_conv2d_wgrad.h']
self.template = '\n// Conv2d${conv_kind_name} ${iterator_algorithm_name} kernel instance "${operation_name}"\nusing ${operation_name}_base = \ntypename cutlass::conv::kernel::DefaultConv2d${conv_kind_name}<\n ${element_a}, \n ${layout_a},\n ${element_b}, \n ${layout_b},\n ${element_c}, \n ${layout_c},\n ${element_accumulator},\n ${opcode_class},\n ${arch},\n cutlass::gemm::GemmShape<${threadblock_shape_m}, ${threadblock_shape_n}, ${threadblock_shape_k}>,\n cutlass::gemm::GemmShape<${warp_shape_m}, ${warp_shape_n}, ${warp_shape_k} >,\n cutlass::gemm::GemmShape<${instruction_shape_m}, ${instruction_shape_n}, ${instruction_shape_k}>,\n ${epilogue_functor},\n ${swizzling_functor}, // cutlass::gemm::threadblock::GemmSplitKIdentityThreadblockSwizzle<>,\n ${stages},\n ${math_operator},\n ${iterator_algorithm},\n ${stride_support},\n ${align_a},\n ${align_b}\n>::Kernel;\n\nstruct ${operation_name}${operation_suffix}:\n public ${operation_name}_base { };\n\n'
def emit(self, operation):
warp_shape = [int((operation.tile_description.threadblock_shape[idx] / operation.tile_description.warp_count[idx])) for idx in range(3)]
epilogue_vector_length = int((min((operation.C.alignment * DataTypeSize[operation.C.element]), 128) / DataTypeSize[operation.C.element]))
values = {'operation_name': operation.procedural_name(), 'operation_suffix': self.operation_suffix, 'conv_kind': ConvKindTag[operation.conv_kind], 'conv_kind_name': ConvKindNames[operation.conv_kind].capitalize(), 'element_a': DataTypeTag[operation.A.element], 'layout_a': LayoutTag[operation.A.layout], 'element_b': DataTypeTag[operation.B.element], 'layout_b': LayoutTag[operation.B.layout], 'element_c': DataTypeTag[operation.C.element], 'layout_c': LayoutTag[operation.C.layout], 'element_accumulator': DataTypeTag[operation.accumulator_type()], 'opcode_class': OpcodeClassTag[operation.tile_description.math_instruction.opcode_class], 'arch': ('cutlass::arch::Sm%d' % operation.arch), 'threadblock_shape_m': str(operation.tile_description.threadblock_shape[0]), 'threadblock_shape_n': str(operation.tile_description.threadblock_shape[1]), 'threadblock_shape_k': str(operation.tile_description.threadblock_shape[2]), 'warp_shape_m': str(warp_shape[0]), 'warp_shape_n': str(warp_shape[1]), 'warp_shape_k': str(warp_shape[2]), 'instruction_shape_m': str(operation.tile_description.math_instruction.instruction_shape[0]), 'instruction_shape_n': str(operation.tile_description.math_instruction.instruction_shape[1]), 'instruction_shape_k': str(operation.tile_description.math_instruction.instruction_shape[2]), 'epilogue_vector_length': str(epilogue_vector_length), 'epilogue_functor': operation.epilogue_functor.emit(), 'swizzling_functor': operation.swizzling_functor.tag(), 'stages': str(operation.tile_description.stages), 'iterator_algorithm': IteratorAlgorithmTag[operation.iterator_algorithm], 'iterator_algorithm_name': IteratorAlgorithmNames[operation.iterator_algorithm].capitalize(), 'stride_support': StrideSupportTag[operation.stride_support], 'math_operator': ('cutlass::arch::OpMultiplyAddComplex' if operation.is_complex() else MathOperationTag[operation.tile_description.math_instruction.math_operation]), 'align_a': str(operation.A.alignment), 'align_b': str(operation.B.alignment)}
return SubstituteTemplate(self.template, values) |
class FlaxAutoModelForNextSentencePrediction(_BaseAutoModelClass):
_model_mapping = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING |
def set_seed(args):
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
torch.cuda.manual_seed_all(args.seed) |
class GeneratedResidualCache():
def __init__(self) -> None:
self._dict: T.Dict[(_GRCKey, T.Callable)] = {}
def get_residual(self, index: SimilarityIndex, optimized_keys: T.Iterable[str], output_dir: T.Optional[T.Openable], namespace: T.Optional[str], sparse_linearization: bool) -> T.Optional[T.Callable]:
return self._dict.get(_GRCKey(index=index, optimized_keys=tuple(optimized_keys), output_dir=output_dir, namespace=namespace, sparse_linearization=sparse_linearization), None)
def cache_residual(self, index: SimilarityIndex, optimized_keys: T.Iterable[str], output_dir: T.Optional[T.Openable], namespace: T.Optional[str], sparse_linearization: bool, residual: T.Callable) -> None:
self._dict[_GRCKey(index=copy.deepcopy(index), optimized_keys=tuple(optimized_keys), output_dir=output_dir, namespace=namespace, sparse_linearization=sparse_linearization)] = residual
def __len__(self) -> int:
return len(self._dict) |
def frechet_inception_distance():
filenames = glob(os.path.join('./real_target', '*.*'))
real_images = [get_images(filename) for filename in filenames]
real_images = np.transpose(real_images, axes=[0, 3, 1, 2])
filenames = glob(os.path.join('./fake', '*.*'))
fake_images = [get_images(filename) for filename in filenames]
fake_images = np.transpose(fake_images, axes=[0, 3, 1, 2])
BATCH_SIZE = 1
inception_images = tf.placeholder(tf.float32, [BATCH_SIZE, 3, None, None])
real_activation = tf.placeholder(tf.float32, [None, None], name='activations1')
fake_activation = tf.placeholder(tf.float32, [None, None], name='activations2')
fcd = frechet_classifier_distance_from_activations(real_activation, fake_activation)
activations = inception_activations(inception_images)
FID = get_fid(fcd, BATCH_SIZE, real_images, fake_images, inception_images, real_activation, fake_activation, activations)
print()
print('FID : ', (FID / 100)) |
def type_to_pack_format(typestring):
fmt = None
if (typestring == 'bool'):
fmt = 'B'
elif ((typestring == 'double') or (typestring == 'float')):
fmt = 'f'
elif (typestring == 'int64'):
fmt = 'i'
elif ((typestring == 'repeated int64') or (typestring == 'Shape')):
fmt = 'iI'
elif (typestring == 'repeated float'):
fmt = 'fF'
elif (typestring == 'string'):
fmt = 'i'
elif (typestring == 'Communicator'):
fmt = 'C'
else:
raise ValueError('{} is not defined.'.format(typestring))
return fmt |
def skip(splits, save_folder, conf):
skip = True
split_files = {'train': TRAIN_CSV, 'dev': DEV_CSV, 'test': TEST_CSV, 'enrol': ENROL_CSV}
for split in splits:
if (not os.path.isfile(os.path.join(save_folder, split_files[split]))):
skip = False
save_opt = os.path.join(save_folder, OPT_FILE)
if (skip is True):
if os.path.isfile(save_opt):
opts_old = load_pkl(save_opt)
if (opts_old == conf):
skip = True
else:
skip = False
else:
skip = False
return skip |
class OnlineCSB2Classifier(BaseSKMObject, ClassifierMixin, MetaEstimatorMixin):
def __init__(self, base_estimator=KNNADWINClassifier(), n_estimators=10, cost_positive=1, cost_negative=0.1, drift_detection=True, random_state=None):
super().__init__()
self.ensemble = None
self.actual_n_estimators = None
self.classes = None
self._random_state = None
self.base_estimator = base_estimator
self.n_estimators = n_estimators
self.cost_positive = cost_positive
self.cost_negative = cost_negative
self.drift_detection = drift_detection
self.random_state = random_state
self.adwin_ensemble = None
self.lam_fn = None
self.lam_fp = None
self.lam_sum = None
self.lam_sw = None
self.werr = None
self.epsilon = None
def __configure(self):
if hasattr(self.base_estimator, 'reset'):
self.base_estimator.reset()
self.actual_n_estimators = self.n_estimators
self.adwin_ensemble = []
for i in range(self.actual_n_estimators):
self.adwin_ensemble.append(ADWIN())
self.ensemble = [cp.deepcopy(self.base_estimator) for _ in range(self.actual_n_estimators)]
self._random_state = check_random_state(self.random_state)
self.lam_fn = np.zeros(self.actual_n_estimators)
self.lam_fp = np.zeros(self.actual_n_estimators)
self.lam_sum = np.zeros(self.actual_n_estimators)
self.werr = np.zeros(self.actual_n_estimators)
self.lam_sw = np.zeros(self.actual_n_estimators)
self.epsilon = np.zeros(self.actual_n_estimators)
def reset(self):
self.__configure()
def partial_fit(self, X, y, classes=None, sample_weight=None):
if (self.ensemble is None):
self.__configure()
if (self.classes is None):
if (classes is None):
raise ValueError('The first partial_fit call should pass all the classes.')
else:
self.classes = classes
if ((self.classes is not None) and (classes is not None)):
if (set(self.classes) == set(classes)):
pass
else:
raise ValueError('The classes passed to the partial_fit function differ from those passed earlier.')
self.__adjust_ensemble_size()
(r, _) = get_dimensions(X)
for j in range(r):
change_detected = False
lam = 1
for i in range(self.actual_n_estimators):
self.lam_sum[i] += lam
k = self._random_state.poisson(lam)
if (k > 0):
for b in range(k):
self.ensemble[i].partial_fit([X[j]], [y[j]], classes, sample_weight)
if (self.ensemble[i].predict([X[j]])[0] == y[j]):
self.epsilon[i] = (self.lam_sw[i] / self.lam_sum[i])
self.werr[i] = ((self.lam_fp[i] + self.lam_fn[i]) / self.lam_sum[i])
if (((self.epsilon[i] + self.werr[i]) != 0) and (self.epsilon[i] != 1)):
lam = (self.epsilon[i] / ((1 - self.epsilon[i]) * (self.epsilon[i] + self.werr[i])))
elif ((self.ensemble[i].predict([X[j]])[0] == 0) and (y[j] == 1)):
self.lam_fp[i] += (self.cost_positive * lam)
self.lam_sw[i] += lam
self.epsilon[i] = (self.lam_sw[i] / self.lam_sum[i])
self.werr[i] = ((self.lam_fp[i] + self.lam_fn[i]) / self.lam_sum[i])
lam = ((self.cost_positive * lam) / (self.epsilon[i] + self.werr[i]))
else:
self.lam_fn[i] += (self.cost_positive * lam)
self.lam_sw[i] += lam
self.epsilon[i] = (self.lam_sw[i] / self.lam_sum[i])
self.werr[i] = ((self.lam_fp[i] + self.lam_fn[i]) / self.lam_sum[i])
lam = ((self.cost_negative * lam) / (self.epsilon[i] + self.werr[i]))
if self.drift_detection:
try:
pred = self.ensemble[i].predict(X)
error_estimation = self.adwin_ensemble[i].estimation
for k in range(r):
if (pred[k] is not None):
self.adwin_ensemble[i].add_element(int((pred[k] == y[k])))
if self.adwin_ensemble[i].detected_change():
if (self.adwin_ensemble[i].estimation > error_estimation):
change_detected = True
except ValueError:
change_detected = False
pass
if (change_detected and self.drift_detection):
max_threshold = 0.0
i_max = (- 1)
for i in range(self.actual_n_estimators):
if (max_threshold < self.adwin_ensemble[i].estimation):
max_threshold = self.adwin_ensemble[i].estimation
i_max = i
if (i_max != (- 1)):
self.ensemble[i_max].reset()
self.adwin_ensemble[i_max] = ADWIN()
return self
def __adjust_ensemble_size(self):
if (len(self.classes) != len(self.ensemble)):
if (len(self.classes) > len(self.ensemble)):
for i in range(len(self.ensemble), len(self.classes)):
self.ensemble.append(cp.deepcopy(self.base_estimator))
self.actual_n_estimators += 1
self.adwin_ensemble.append(ADWIN())
self.lam_fn = np.zeros(self.actual_n_estimators)
self.lam_fp = np.zeros(self.actual_n_estimators)
self.lam_sum = np.zeros(self.actual_n_estimators)
self.lam_sw = np.zeros(self.actual_n_estimators)
self.epsilon = np.zeros(self.actual_n_estimators)
self.werr = np.zeros(self.actual_n_estimators)
def predict(self, X):
(r, c) = get_dimensions(X)
proba = self.predict_proba(X)
predictions = []
if (proba is None):
return None
for i in range(r):
predictions.append(np.argmax(proba[i]))
return np.asarray(predictions)
def predict_proba(self, X):
proba = []
(r, c) = get_dimensions(X)
if (self.ensemble is None):
return np.zeros((r, 1))
with warnings.catch_warnings():
warnings.filterwarnings('error')
try:
for i in range(self.actual_n_estimators):
partial_proba = self.ensemble[i].predict_proba(X)
if (len(partial_proba[0]) > (max(self.classes) + 1)):
raise ValueError('The number of classes in the base learner is larger than in the ensemble.')
if (len(proba) < 1):
for n in range(r):
proba.append([0.0 for _ in partial_proba[n]])
for n in range(r):
for k in range(len(partial_proba[n])):
try:
proba[n][k] += (np.log(((1 - self.epsilon[i]) / self.epsilon[i])) * partial_proba[n][k])
except IndexError:
proba[n].append(partial_proba[n][k])
except RuntimeWarning:
continue
except ValueError:
return np.zeros((r, 1))
except TypeError:
return np.zeros((r, 1))
sum_proba = []
for k in range(r):
sum_proba.append(np.sum(proba[k]))
aux = []
for i in range(len(proba)):
if (sum_proba[i] > 0.0):
aux.append([(x / sum_proba[i]) for x in proba[i]])
else:
aux.append(proba[i])
return np.asarray(aux) |
class BDD100KUniformWithPos(data.Dataset):
def __init__(self, mode, maxSkip=0, joint_transform_list=None, sliding_crop=None, transform=None, target_transform=None, target_aux_transform=None, dump_images=False, cv_split=None, class_uniform_pct=0.5, class_uniform_tile=1024, test=False, coarse_boost_classes=None, pos_rfactor=8):
self.mode = mode
self.maxSkip = maxSkip
self.joint_transform_list = joint_transform_list
self.sliding_crop = sliding_crop
self.transform = transform
self.target_transform = target_transform
self.target_aux_transform = target_aux_transform
self.dump_images = dump_images
self.class_uniform_pct = class_uniform_pct
self.class_uniform_tile = class_uniform_tile
self.coarse_boost_classes = coarse_boost_classes
self.pos_rfactor = pos_rfactor
self.pos_h = (torch.arange(0, 1024).unsqueeze(0).unsqueeze(2).expand((- 1), (- 1), 2048) // 8)
self.pos_w = (torch.arange(0, 2048).unsqueeze(0).unsqueeze(1).expand((- 1), 1024, (- 1)) // 16)
self.pos_h = self.pos_h[0].byte().numpy()
self.pos_w = self.pos_w[0].byte().numpy()
self.pos_h = Image.fromarray(self.pos_h, mode='L')
self.pos_w = Image.fromarray(self.pos_w, mode='L')
if cv_split:
self.cv_split = cv_split
assert (cv_split < cfg.DATASET.CV_SPLITS), 'expected cv_split {} to be < CV_SPLITS {}'.format(cv_split, cfg.DATASET.CV_SPLITS)
else:
self.cv_split = 0
(self.imgs, self.aug_imgs) = make_dataset(mode, self.maxSkip, cv_split=self.cv_split)
assert len(self.imgs), 'Found 0 images, please check the data set'
json_fn = 'bdd100k_{}_cv{}_tile{}.json'.format(self.mode, self.cv_split, self.class_uniform_tile)
if os.path.isfile(json_fn):
with open(json_fn, 'r') as json_data:
centroids = json.load(json_data)
self.centroids = {int(idx): centroids[idx] for idx in centroids}
else:
self.centroids = uniform.class_centroids_all(self.imgs, num_classes, id2trainid=trainid_to_trainid, tile_size=class_uniform_tile)
with open(json_fn, 'w') as outfile:
json.dump(self.centroids, outfile, indent=4)
self.fine_centroids = self.centroids.copy()
self.build_epoch()
def cities_uniform(self, imgs, name):
cities = {}
for item in imgs:
img_fn = item[0]
img_fn = os.path.basename(img_fn)
city = img_fn.split('_')[0]
cities[city] = 1
city_names = cities.keys()
logging.info(('Cities for {} '.format(name) + str(sorted(city_names))))
def build_epoch(self, cut=False):
if (self.class_uniform_pct > 0):
if cut:
self.imgs_uniform = uniform.build_epoch(self.imgs, self.fine_centroids, num_classes, cfg.CLASS_UNIFORM_PCT)
else:
self.imgs_uniform = uniform.build_epoch((self.imgs + self.aug_imgs), self.centroids, num_classes, cfg.CLASS_UNIFORM_PCT)
else:
self.imgs_uniform = self.imgs
def __getitem__(self, index):
elem = self.imgs_uniform[index]
centroid = None
if (len(elem) == 4):
(img_path, mask_path, centroid, class_id) = elem
else:
(img_path, mask_path) = elem
(img, mask) = (Image.open(img_path).convert('RGB'), Image.open(mask_path))
img_name = os.path.splitext(os.path.basename(img_path))[0]
mask = np.array(mask)
mask_copy = mask.copy()
for (k, v) in trainid_to_trainid.items():
mask_copy[(mask == k)] = v
mask = Image.fromarray(mask_copy.astype(np.uint8))
pos_h = self.pos_h
pos_w = self.pos_w
if (self.joint_transform_list is not None):
for (idx, xform) in enumerate(self.joint_transform_list):
if ((idx == 0) and (centroid is not None)):
(img, mask, (pos_h, pos_w)) = xform(img, mask, centroid, pos=(pos_h, pos_w))
else:
(img, mask, (pos_h, pos_w)) = xform(img, mask, pos=(pos_h, pos_w))
if (self.dump_images and (centroid is not None)):
outdir = '../../dump_imgs_{}'.format(self.mode)
os.makedirs(outdir, exist_ok=True)
dump_img_name = ((trainid_to_name[class_id] + '_') + img_name)
out_img_fn = os.path.join(outdir, (dump_img_name + '.png'))
out_msk_fn = os.path.join(outdir, (dump_img_name + '_mask.png'))
mask_img = colorize_mask(np.array(mask))
img.save(out_img_fn)
mask_img.save(out_msk_fn)
if (self.transform is not None):
img = self.transform(img)
if (self.target_aux_transform is not None):
mask_aux = self.target_aux_transform(mask)
else:
mask_aux = torch.tensor([0])
if (self.target_transform is not None):
mask = self.target_transform(mask)
pos_h = torch.from_numpy(np.array(pos_h, dtype=np.uint8))
pos_w = torch.from_numpy(np.array(pos_w, dtype=np.uint8))
return (img, mask, img_name, mask_aux, (pos_h, pos_w))
def __len__(self):
return len(self.imgs_uniform) |
def generate_solver_python_interface(solver_info):
utils.generate_from_template(join(base, 'python/src/nnabla/solver.pyx.tmpl'), solver_info=solver_info)
utils.generate_from_template(join(base, 'python/src/nnabla/solver.pxd.tmpl'), solver_info=solver_info) |
def integrated_bn(fms, bn):
sizes = [p.shape[2:] for p in fms]
(n, c) = (fms[0].shape[0], fms[0].shape[1])
fm = torch.cat([p.view(n, c, 1, (- 1)) for p in fms], dim=(- 1))
fm = bn(fm)
fm = torch.split(fm, [(s[0] * s[1]) for s in sizes], dim=(- 1))
return [p.view(n, c, s[0], s[1]) for (p, s) in zip(fm, sizes)] |
(scope='module')
.usefixtures('columns_target_list_len')
def simple_dataframe_target_ordered_list_len_pandas(columns_target_list_len):
data_target_ordered_list_len = [(1, 2, 19842, [1], [19841], 1), (1, 3, 19843, [1, 2], [19841, 19842], 2), (1, 4, 19844, [1, 2, 3], [19841, 19842, 19843], 3), (1, 5, 19845, [1, 2, 3, 4], [19841, 19842, 19843, 19844], 4), (1, 6, 19846, [1, 2, 3, 4, 5], [19841, 19842, 19843, 19844, 19845], 5), (1, 7, 19847, [2, 3, 4, 5, 6], [19842, 19843, 19844, 19845, 19846], 5), (2, 2, 19842, [1], [19841], 1), (2, 3, 19843, [1, 2], [19841, 19842], 2), (2, 4, 19844, [1, 2, 3], [19841, 19842, 19843], 3), (4, 12, 19845, [11], [19843], 1)]
return pd.DataFrame(data_target_ordered_list_len, columns=columns_target_list_len) |
class WSHandler(tornado.websocket.WebSocketHandler):
def __init__(self, application, request, **kwargs):
super(WSHandler, self).__init__(application, request, **kwargs)
self.sending = False
def open(self):
print(('New connection opened from ' + self.request.remote_ip))
clients.append(self)
print(('%d clients connected' % len(clients)))
def on_message(self, message):
print(('message received: %s' % message))
if (message == 'StartData'):
self.sending = True
if (message == 'StopData'):
self.sending = False
def on_close(self):
self.sending = False
clients.remove(self)
print(('Connection closed from ' + self.request.remote_ip))
print(('%d clients connected' % len(clients)))
def check_origin(self, origin):
return True |
class LifelongAntEnv(mujoco_env.MujocoEnv, utils.EzPickle):
def __init__(self, xml_file='ant.xml', gear_ratio=30, ctrl_cost_weight=0.01, contact_cost_weight=0.0005, healthy_reward=1.0, terminate_when_unhealthy=True, healthy_z_range=(0.2, 1.2), contact_force_range=((- 1.0), 1.0), reset_noise_scale=0.1, exclude_current_positions_from_observation=True, target_vel=DEFAULT_VEL, height_cost=3, target_height=0.7, rgb_rendering_tracking=True, action_noise=0.0):
utils.EzPickle.__init__(**locals())
self._ctrl_cost_weight = ctrl_cost_weight
self._contact_cost_weight = contact_cost_weight
self._healthy_reward = healthy_reward
self._terminate_when_unhealthy = terminate_when_unhealthy
self._healthy_z_range = healthy_z_range
self._contact_force_range = contact_force_range
self._reset_noise_scale = reset_noise_scale
self._exclude_current_positions_from_observation = exclude_current_positions_from_observation
self._target_vel = target_vel
self._target_vel_reward_weight = 1
self._height_cost = height_cost
self._target_height = target_height
self.action_noise = action_noise
xml_path = 'lifelong_rl/envs/environments/assets/'
model_path = os.path.abspath(os.path.join(xml_path, xml_file))
mujoco_env.MujocoEnv.__init__(self, model_path, 5)
'\n Required for compatibility with lifelong_rl lifelong environment setting\n '
def get_env_state(self):
return self.sim.get_state()
def set_env_state(self, state):
self.sim.set_state(state)
'\n \n '
def healthy_reward(self):
return (float((self.is_healthy or self._terminate_when_unhealthy)) * self._healthy_reward)
def control_cost(self, action):
control_cost = (self._ctrl_cost_weight * np.sum(np.square(action)))
return control_cost
def contact_forces(self):
raw_contact_forces = self.sim.data.cfrc_ext
(min_value, max_value) = self._contact_force_range
contact_forces = np.clip(raw_contact_forces, min_value, max_value)
return contact_forces
def contact_cost(self):
contact_cost = (self._contact_cost_weight * np.sum(np.square(self.contact_forces)))
return contact_cost
def set_target_vel(self, vel):
self._target_vel = vel
def get_target_vel(self):
if (self._target_vel is not None):
return self._target_vel
else:
return DEFAULT_VEL
def is_healthy(self):
state = self.state_vector()
(min_z, max_z) = self._healthy_z_range
is_healthy = (np.isfinite(state).all() and (min_z <= state[2] <= max_z))
return is_healthy
def done(self):
done = ((not self.is_healthy) if self._terminate_when_unhealthy else False)
return done
def step(self, action):
action += (np.random.randn(*action.shape) * self.action_noise)
action = action.clip((- 1.0), 1.0)
xy_position_before = self.get_body_com('torso')[:2].copy()
self.do_simulation(action, self.frame_skip)
xy_position_after = self.get_body_com('torso')[:2].copy()
xy_velocity = ((xy_position_after - xy_position_before) / self.dt)
(x_velocity, y_velocity) = xy_velocity
z = self.state_vector()[2]
rewards = self.get_target_vel()
vel_cost = abs((x_velocity - self.get_target_vel()))
height_cost = (self._height_cost * ((z - self._target_height) ** 2))
action_cost = (0.01 * np.sum((action ** 2)))
costs = ((vel_cost + height_cost) + action_cost)
reward = (rewards - costs)
done = (not self.is_healthy)
observation = self._get_obs()
info = {'x velocity': x_velocity, 'target velocity': self.get_target_vel(), 'z': z, 'x': self.state_vector()[0], 'y': self.state_vector()[1], 'height cost': height_cost}
return (observation, reward, done, info)
def _get_obs(self):
if self._exclude_current_positions_from_observation:
return np.concatenate([self.sim.data.qpos.flat[2:], self.sim.data.qvel.flat])
else:
return np.concatenate([self.sim.data.qpos.flat, self.sim.data.qvel.flat])
def get_obs(self):
return self._get_obs()
def reset_model(self):
noise_low = (- self._reset_noise_scale)
noise_high = self._reset_noise_scale
qpos = (self.init_qpos + self.np_random.uniform(low=noise_low, high=noise_high, size=self.model.nq))
qvel = (self.init_qvel + (self._reset_noise_scale * self.np_random.randn(self.model.nv)))
self.set_state(qpos, qvel)
observation = self._get_obs()
return observation
def viewer_setup(self):
for (key, value) in DEFAULT_CAMERA_CONFIG.items():
if isinstance(value, np.ndarray):
getattr(self.viewer.cam, key)[:] = value
else:
setattr(self.viewer.cam, key, value) |
def map_brackets_fw(t):
if (t == '('):
return '-lrb-'
if (t == ')'):
return '-rrb-'
return t |
class _Classifier(nn.Module):
def __init__(self, feat_dim=None, num_classes=None, dtype=None):
super().__init__()
self.weight = nn.Parameter(torch.empty(num_classes, feat_dim, dtype=dtype))
self.weight.data.uniform_((- 1), 1).renorm_(2, 0, 1e-05).mul_(100000.0)
def dtype(self):
return self.weight.dtype
def forward(self, x):
raise NotImplementedError
def apply_weight(self, weight):
self.weight.data = weight.clone() |
def main():
parser = argparse.ArgumentParser(description='Convert keys in timm pretrained vit models to MMSegmentation style.')
parser.add_argument('src', help='src model path or url')
parser.add_argument('dst', help='save path')
parser.add_argument('model', help='model: pcpvt or svt')
args = parser.parse_args()
checkpoint = CheckpointLoader.load_checkpoint(args.src, map_location='cpu')
if ('state_dict' in checkpoint):
state_dict = checkpoint['state_dict']
else:
state_dict = checkpoint
weight = convert_twins(args, state_dict)
mmcv.mkdir_or_exist(osp.dirname(args.dst))
torch.save(weight, args.dst) |
class Cell(VertexGroup):
def __init__(self, p_gen, p_hgr, origin, supremum):
super(Cell, self).__init__(p_gen, p_hgr)
self.origin = origin
self.supremum = supremum
self.centroid = None |
def gl_maker(file_name, min_weight, max_weight, vertices, min_edge, max_edge, sign, direct, self_loop, multigraph):
(edge_dic, weight_dic, edge_number) = edge_gen(vertices, min_weight, max_weight, min_edge, max_edge, sign, direct, self_loop, multigraph)
with open((file_name + '.gl'), 'w') as buf:
for (key, edge_val) in edge_dic.items():
line_data = str(key)
write_flag = False
for (j, value) in enumerate(edge_val):
write_flag = True
line_data += (((' ' + str(value)) + ':') + str(weight_dic[key][j]))
if write_flag:
buf.write((line_data + '\n'))
return edge_number |
class FolderDataset(AnomalibDataset):
def __init__(self, task: TaskType, transform: A.Compose, normal_dir: (str | Path), root: ((str | Path) | None)=None, abnormal_dir: ((str | Path) | None)=None, normal_test_dir: ((str | Path) | None)=None, mask_dir: ((str | Path) | None)=None, split: ((str | Split) | None)=None, extensions: (tuple[(str, ...)] | None)=None) -> None:
super().__init__(task, transform)
self.split = split
self.root = root
self.normal_dir = normal_dir
self.abnormal_dir = abnormal_dir
self.normal_test_dir = normal_test_dir
self.mask_dir = mask_dir
self.extensions = extensions
def _setup(self) -> None:
self.samples = make_folder_dataset(root=self.root, normal_dir=self.normal_dir, abnormal_dir=self.abnormal_dir, normal_test_dir=self.normal_test_dir, mask_dir=self.mask_dir, split=self.split, extensions=self.extensions) |
class GNN(nn.Module):
def __init__(self, dim_in, dim_out, **kwargs):
super(GNN, self).__init__()
GNNStage = stage_dict[cfg.gnn.stage_type]
GNNHead = head_dict[cfg.dataset.task]
if cfg.dataset.node_encoder:
NodeEncoder = node_encoder_dict[cfg.dataset.node_encoder_name]
self.node_encoder = NodeEncoder(cfg.dataset.encoder_dim)
if cfg.dataset.node_encoder_bn:
self.node_encoder_bn = BatchNorm1dNode(cfg.dataset.encoder_dim)
dim_in = cfg.dataset.encoder_dim
if cfg.dataset.edge_encoder:
EdgeEncoder = edge_encoder_dict[cfg.dataset.edge_encoder_name]
self.edge_encoder = EdgeEncoder(cfg.dataset.encoder_dim)
if cfg.dataset.edge_encoder_bn:
self.edge_encoder_bn = BatchNorm1dEdge(cfg.dataset.edge_dim)
self.preprocess = Preprocess(dim_in)
d_in = self.preprocess.dim_out
if (cfg.gnn.layers_pre_mp > 0):
self.pre_mp = GNNPreMP(d_in, cfg.gnn.dim_inner)
d_in = cfg.gnn.dim_inner
if (cfg.gnn.layers_mp > 1):
self.mp = GNNStage(dim_in=d_in, dim_out=cfg.gnn.dim_inner, num_layers=cfg.gnn.layers_mp)
d_in = self.mp.dim_out
self.post_mp = GNNHead(dim_in=d_in, dim_out=dim_out)
self.apply(init_weights)
def forward(self, batch):
for module in self.children():
batch = module(batch)
return batch |
def ndcg_at_k(r, k, method=0):
dcg_max = dcg_at_k(sorted(r, reverse=True), k, method)
if (not dcg_max):
return 0.0
return (dcg_at_k(r, k, method) / dcg_max) |
class ICLLoss(nn.Module):
def __init__(self, device, temperature=0.05, alpha=0.5):
super(ICLLoss, self).__init__()
self.temp = 0.1
self.alpha = alpha
self.device = device
def forward(self, emb, data_dict):
emb = F.normalize(emb, dim=1)
e1i = emb[data_dict['e1i']]
e2i = emb[data_dict['e2i']]
e1j = emb[data_dict['e1j']]
e2j = emb[data_dict['e2j']]
qm_e1i_e2i = calculate_prob_dist(e1i, e2i, e1j, e2j, self.temp)
qm_e2i_e1i = calculate_prob_dist(e2i, e1i, e2j, e1j, self.temp)
lossA = qm_e1i_e2i
lossB = qm_e2i_e1i
loss = ((self.alpha * lossA) + ((1 - self.alpha) * lossB))
loss = (- torch.log(loss).mean())
return loss |
class NTLMConnectionPool(HTTPSConnectionPool):
scheme = '
def __init__(self, user, pw, authurl, *args, **kwargs):
super(NTLMConnectionPool, self).__init__(*args, **kwargs)
self.authurl = authurl
self.rawuser = user
user_parts = user.split('\\', 1)
self.domain = user_parts[0].upper()
self.user = user_parts[1]
self.pw = pw
def _new_conn(self):
self.num_connections += 1
log.debug('Starting NTLM HTTPS connection no. %d: self.num_connections, self.host, self.authurl)
headers = {'Connection': 'Keep-Alive'}
req_header = 'Authorization'
resp_header = 'www-authenticate'
conn = HTTPSConnection(host=self.host, port=self.port)
headers[req_header] = ('NTLM %s' % ntlm.create_NTLM_NEGOTIATE_MESSAGE(self.rawuser))
log.debug('Request headers: %s', headers)
conn.request('GET', self.authurl, None, headers)
res = conn.getresponse()
reshdr = dict(res.getheaders())
log.debug('Response status: %s %s', res.status, res.reason)
log.debug('Response headers: %s', reshdr)
log.debug('Response data: %s [...]', res.read(100))
res.fp = None
auth_header_values = reshdr[resp_header].split(', ')
auth_header_value = None
for s in auth_header_values:
if (s[:5] == 'NTLM '):
auth_header_value = s[5:]
if (auth_header_value is None):
raise Exception(('Unexpected %s response header: %s' % (resp_header, reshdr[resp_header])))
(ServerChallenge, NegotiateFlags) = ntlm.parse_NTLM_CHALLENGE_MESSAGE(auth_header_value)
auth_msg = ntlm.create_NTLM_AUTHENTICATE_MESSAGE(ServerChallenge, self.user, self.domain, self.pw, NegotiateFlags)
headers[req_header] = ('NTLM %s' % auth_msg)
log.debug('Request headers: %s', headers)
conn.request('GET', self.authurl, None, headers)
res = conn.getresponse()
log.debug('Response status: %s %s', res.status, res.reason)
log.debug('Response headers: %s', dict(res.getheaders()))
log.debug('Response data: %s [...]', res.read()[:100])
if (res.status != 200):
if (res.status == 401):
raise Exception('Server rejected request: wrong username or password')
raise Exception(('Wrong server response: %s %s' % (res.status, res.reason)))
res.fp = None
log.debug('Connection established')
return conn
def urlopen(self, method, url, body=None, headers=None, retries=3, redirect=True, assert_same_host=True):
if (headers is None):
headers = {}
headers['Connection'] = 'Keep-Alive'
return super(NTLMConnectionPool, self).urlopen(method, url, body, headers, retries, redirect, assert_same_host) |
def load_metadata(args, shard_paths):
(metadata, _, shards_size_dt) = _load_metadata(args, shard_paths)
return (metadata, shards_size_dt) |
class Elliott_VGG(nn.Module):
def __init__(self, vgg_name):
super(Elliott_VGG, self).__init__()
self.features = self._make_layers(cfg[vgg_name])
self.classifier = nn.Linear(512, 100)
def forward(self, x):
out = self.features(x)
out = out.view(out.size(0), (- 1))
out = self.classifier(out)
return out
def _make_layers(self, cfg):
layers = []
in_channels = 3
for x in cfg:
if (x == 'M'):
layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
else:
layers += [nn.Conv2d(in_channels, x, kernel_size=3, padding=1), Elliott(), nn.BatchNorm2d(x)]
in_channels = x
layers += [nn.AvgPool2d(kernel_size=1, stride=1)]
return nn.Sequential(*layers) |
def gen_partition(layer, batch_size, dim_nodes, options, guaranteed=False):
yielded = False
for (ph, pw) in itertools.product(util.factorize(dim_nodes.h, pe.NUM), util.factorize(dim_nodes.w, pe.NUM)):
pdims = [PhyDim2(h, w) for (h, w) in zip(ph, pw)]
if ((not options.partition_batch) and (pdims[pe.BATP].size() > 1)):
continue
if ((batch_size % pdims[pe.BATP].size()) != 0):
continue
if any((((1 < pd.h < dim_nodes.h) and (1 < pd.w < dim_nodes.w) and (pae != pe.OFMP)) for (pae, pd) in enumerate(pdims))):
continue
if options.partition_hybrid:
if (not util.approx_dividable(layer.nofm, pdims[pe.OUTP].size())):
continue
if ((not util.approx_dividable(layer.hofm, pdims[pe.OFMP].h)) or (not util.approx_dividable(layer.wofm, pdims[pe.OFMP].w))):
continue
if ((not options.partition_ifmaps) and (pdims[pe.INPP].size() > 1)):
continue
if isinstance(layer, ConvLayer):
if (not util.approx_dividable(layer.nifm, pdims[pe.INPP].size())):
continue
elif isinstance(layer, LocalRegionLayer):
if (pdims[pe.INPP].size() > 1):
continue
else:
assert (not options.partition_ifmaps)
if (pdims[pe.INPP].size() != 1):
continue
if ((layer.hofm == 1) and (layer.wofm == 1)):
if (pdims[pe.OFMP].size() != 1):
continue
elif (pdims[pe.OUTP].size() != 1):
continue
if ((pdims[pe.OFMP].size() == 1) and all((((pd.h == 1) or (pd.w == 1)) for pd in pdims))):
(pdhs, pdws) = zip(*pdims)
if (pdhs > pdws):
continue
for order in itertools.permutations(range(pe.NUM)):
skip = False
for idx in range((pe.NUM - 1)):
pae1 = order[idx]
pae2 = order[(idx + 1)]
pdim1 = pdims[pae1]
pdim2 = pdims[pae2]
if ((pdim1.size() == 1) and (pdim2.size() == 1) and (pae1 > pae2)):
skip = True
break
if ((pdim1.size() > 1) and (pdim2.size() == 1)):
skip = True
break
if ((pae1 != pe.BATP) and (pdim2.h == 1) and (pdim2.w > 1) and (pdim1.h > 1) and (pdim1.w == 1)):
skip = True
break
if skip:
continue
no_part = [pae for pae in range(pe.NUM) if (pdims[pae].size() == 1)]
if ((pe.BATP not in no_part) and (order[len(no_part)] != pe.BATP)):
continue
part = PartitionScheme(order, pdims)
assert (part.dim() == dim_nodes)
(yield part)
yielded = True
if (guaranteed and (not yielded)):
pdims = ([PhyDim2(1, 1)] * pe.NUM)
order = range(pe.NUM)
if ((layer.hofm == 1) and (layer.wofm == 1)):
pdims[pe.OUTP] = dim_nodes
else:
pdims[pe.OFMP] = dim_nodes
part = PartitionScheme(order, pdims)
assert (part.dim() == dim_nodes)
(yield part) |
def not_modifier(anaphor, antecedent):
if ((anaphor.attributes['type'] == 'NAM') and (antecedent.attributes['type'] == 'NAM')):
return False
elif ((anaphor.attributes['type'] in ['PRO', 'DEM', 'VRB']) or (antecedent.attributes['type'] in ['PRO', 'DEM', 'VRB'])):
return False
else:
return (not get_modifier(anaphor).issubset(get_modifier(antecedent))) |
def test_validate_params_missing_params():
_params({'a': [int]}, prefer_skip_nested_validation=True)
def func(a, b):
pass
func(1, 2) |
class LoginUserOracleProgramPolicy(LinearProgramPolicy):
def __init__(self, config):
labeled_demos = [LabeledDemonstration.from_oracle_programs([[WeightedProgram(FocusAndTypeToken(NearToken(LikeToken(StringToken(u'Username'))), UtteranceSelectorToken(4, 5)), 1)], [WeightedProgram(FocusAndTypeToken(NearToken(LikeToken(StringToken(u'Password'))), UtteranceSelectorToken(10, 11)), 1)], [WeightedProgram(ClickToken(LikeToken(StringToken(u'Login'))), 1)]], 'Enter the username "blah" and the password "blah" into the text fields and press login.', Fields({'username': 'blah', 'password': 'blah'}))]
super(LoginUserOracleProgramPolicy, self).__init__(labeled_demos, config) |
def test_get_parameter_list():
data = {constants.LOGLINE_NAME: ['This is a dataset structure logline', 'This is a dataset structure logline'], constants.PARSED_LOGLINE_NAME: ['This is a * logline', 'This is a * logline']}
df = pd.DataFrame.from_dict(data)
para_list = df.apply(get_parameter_list, axis=1)
assert (len(para_list) == 2), 'parameter list length should be 2'
assert (para_list[0][0] == 'dataset structure'), 'parameter list should contain the right terms' |
class HomologyGroup_class(AdditiveAbelianGroup_fixed_gens):
def __init__(self, n, invfac):
n = len(invfac)
A = (ZZ ** n)
B = A.span([(A.gen(i) * invfac[i]) for i in range(n)])
AdditiveAbelianGroup_fixed_gens.__init__(self, A, B, A.gens())
self._original_invts = invfac
def _repr_(self):
eldv = self._original_invts
if (len(eldv) == 0):
return '0'
rank = len([x for x in eldv if (x == 0)])
torsion = sorted((x for x in eldv if x))
if (rank > 4):
g = [('Z^%s' % rank)]
else:
g = (['Z'] * rank)
if (len(torsion) != 0):
printed = []
for t in torsion:
numfac = torsion.count(t)
too_many = (numfac > 4)
if too_many:
if (t not in printed):
g.append('C{}^{}'.format(t, numfac))
printed.append(t)
else:
g.append(('C%s' % t))
times = ' x '
return times.join(g)
def _latex_(self):
eldv = self._original_invts
if (len(eldv) == 0):
return '0'
rank = len([x for x in eldv if (x == 0)])
torsion = sorted((x for x in eldv if x))
if (rank > 4):
g = ['\\ZZ^{{{}}}'.format(rank)]
else:
g = (['\\ZZ'] * rank)
if torsion:
printed = []
for t in torsion:
numfac = torsion.count(t)
too_many = (numfac > 4)
if too_many:
if (t not in printed):
g.append('C_{{{}}}^{{{}}}'.format(t, numfac))
printed.append(t)
else:
g.append('C_{{{}}}'.format(t))
times = ' \\times '
return times.join(g) |
_KEYPOINT_OUTPUTS.register('keypoint_output')
class Keypoint_output(nn.Module):
def __init__(self, dim_in):
super(Keypoint_output, self).__init__()
num_keypoints = cfg.KRCNN.NUM_CLASSES
assert ((cfg.KRCNN.RESOLUTION[0] // cfg.KRCNN.ROI_XFORM_RESOLUTION[0]) == (cfg.KRCNN.RESOLUTION[1] // cfg.KRCNN.ROI_XFORM_RESOLUTION[1]))
self.up_scale = (cfg.KRCNN.RESOLUTION[0] // (cfg.KRCNN.ROI_XFORM_RESOLUTION[0] * 2))
deconv_kernel = 4
self.kps_score_lowres = nn.ConvTranspose2d(dim_in, num_keypoints, deconv_kernel, stride=2, padding=((deconv_kernel // 2) - 1))
nn.init.kaiming_normal_(self.kps_score_lowres.weight, mode='fan_out', nonlinearity='relu')
nn.init.constant_(self.kps_score_lowres.bias, 0)
self.dim_out = num_keypoints
def forward(self, x):
x = self.kps_score_lowres(x)
if (self.up_scale > 1):
x = F.interpolate(x, scale_factor=self.up_scale, mode='bilinear', align_corners=False)
return x |
def all_consecutive(x: List[str]):
return np.all((np.diff([get_frame_number(i) for i in x]) == 1)) |
_utils.test()
def test_indices_with_matrix():
grid_m = ti.field(dtype=ti.i32, shape=(10, 10))
def build_grid():
base = int(ti.Vector([2, 4]))
grid_m[base] = 100
grid_m[int(ti.Vector([1, 1]))] = 10
build_grid()
assert (grid_m[(1, 1)] == 10)
assert (grid_m[(2, 4)] == 100) |
def test__dtw_error():
y = np.array([0.0, 0.1, 1.0, 0.5])
y_hat = np.array([0.1, 2.0, 0.5, 0.0])
score_window = 2
expected = np.array([0.0, 1.9, 0.0, 0.0])
returned = _dtw_error(y, y_hat, score_window)
assert_allclose(returned, expected) |
.ort
def test_save_transients(gpu, sdfg_name):
model = onnx.load(os.path.join(data_directory, 'reshape.onnx'))
transients = {}
dace_model = ONNXModel(sdfg_name, model, save_transients=transients, cuda=gpu, onnx_simplify=False)
dace_model()
assert torch.allclose(transients['bertSLASHembeddingsSLASHReshape_4__42COLON0'].type(torch.int32).cpu(), dace_model.weights['bert/embeddings/Reshape_4/shape:0']) |
def clean_polys_pre(I):
wrap = (Polynomial(p) for p in I)
return (list(set((p for p in wrap if (not p.is_zero())))), None) |
def pearson_corr(y_true, y_pred):
fsp = (y_pred - K.mean(y_pred))
fst = (y_true - K.mean(y_true))
devP = K.std(y_pred)
devT = K.std(y_true)
return (K.mean((fsp * fst)) / (devP * devT)) |
_if_no_torch
def test_hf_gpt2_roundtrip_fa():
hf_config = HfGpt2Config.from_pretrained('gpt2')
config = Gpt2Config.from_hf_config(hf_config)
config = dataclasses.replace(config, use_flash_attention=True, flash_attention_block_size=128)
_roundtrip_compare_gpt2_checkpoint('gpt2', None, config=config) |
def features_to_string(features):
if (not features):
return None
if (len(features.key) == 0):
return None
return '|'.join((('%s=%s' % (key, value)) for (key, value) in zip(features.key, features.value))) |
def report_detail(hds, nlu, g_sc, g_sa, g_wn, g_wc, g_wo, g_wv, g_wv_str, g_sql_q, g_ans, pr_sc, pr_sa, pr_wn, pr_wc, pr_wo, pr_wv_str, pr_sql_q, pr_ans, cnt_list, current_cnt):
(cnt_tot, cnt, cnt_sc, cnt_sa, cnt_wn, cnt_wc, cnt_wo, cnt_wv, cnt_wvi, cnt_lx, cnt_x) = current_cnt
print(f'cnt = {cnt} / {cnt_tot} ')
print(f'headers: {hds}')
print(f'nlu: {nlu}')
print(f'')
print(f'g_sc : {g_sc}')
print(f'pr_sc: {pr_sc}')
print(f'g_sa : {g_sa}')
print(f'pr_sa: {pr_sa}')
print(f'g_wn : {g_wn}')
print(f'pr_wn: {pr_wn}')
print(f'g_wc : {g_wc}')
print(f'pr_wc: {pr_wc}')
print(f'g_wo : {g_wo}')
print(f'pr_wo: {pr_wo}')
print(f'g_wv : {g_wv}')
print('g_wv_str:', g_wv_str)
print('p_wv_str:', pr_wv_str)
print(f'g_sql_q: {g_sql_q}')
print(f'pr_sql_q: {pr_sql_q}')
print(f'g_ans: {g_ans}')
print(f'pr_ans: {pr_ans}')
print(f'')
print(cnt_list)
print(f'''acc_lx = {(cnt_lx / cnt):.3f}, acc_x = {(cnt_x / cnt):.3f}
''', f'''acc_sc = {(cnt_sc / cnt):.3f}, acc_sa = {(cnt_sa / cnt):.3f}, acc_wn = {(cnt_wn / cnt):.3f}
''', f'acc_wc = {(cnt_wc / cnt):.3f}, acc_wo = {(cnt_wo / cnt):.3f}, acc_wv = {(cnt_wv / cnt):.3f}')
print(f'') |
def vec_gradient(l):
gradient = tf.gradients(l, tf.trainable_variables())
vec_grads = [tf.reshape(grad, [(- 1)]) for grad in gradient]
z = tf.concat(vec_grads, 0)
return z |
def some_query_exact_entity_pair(triple, hits, es, INDEX_NAME, filter_stopwords, entity_mentions_map_filtered_low_count_implicits_dict):
def _internal_func(q1, q2):
result = es.search(index=INDEX_NAME, size=hits, body={'query': {'bool': {'must': [{'term': {'subject_mention_exact': q1}}, {'term': {'object_mention_exact': q2}}]}}})
return [(h['_source']['subject_mention'], h['_source']['relation'], h['_source']['object_mention'], h['_source']['triple_id']) for h in sorted(result['hits']['hits'], key=(lambda x: x['_score']), reverse=True)]
q1 = triple[0][0]
r = triple[0][1]
q2 = triple[0][2]
all_pairs = []
q1_stack = [q1]
q2_stack = [q2]
if ((triple[1][0] is not None) and (triple[1][0] in entity_mentions_map_filtered_low_count_implicits_dict)):
q1_stack.extend(entity_mentions_map_filtered_low_count_implicits_dict[triple[1][0]])
if ((triple[1][1] is not None) and (triple[1][1] in entity_mentions_map_filtered_low_count_implicits_dict)):
q2_stack.extend(entity_mentions_map_filtered_low_count_implicits_dict[triple[1][1]])
for q1_mention in q1_stack:
for q2_mention in q2_stack:
all_pairs.append((' '.join(filter_stopwords(q1_mention)), ' '.join(filter_stopwords(q2_mention))))
all_pairs.append((' '.join(filter_stopwords(q2_mention)), ' '.join(filter_stopwords(q1_mention))))
all_pairs = set(all_pairs)
result = list()
for (q1, q2) in all_pairs:
_inter_func_res = _internal_func(q1, q2)
if (len(_inter_func_res) > 0):
result.extend(_inter_func_res)
return set(result) |
def decorator_keywords(func):
_wraps(func)
def wrapped(f=None, **kwargs):
if (f is None):
return sage_wraps(func)((lambda f: func(f, **kwargs)))
else:
return func(f, **kwargs)
return wrapped |
def correctThiago(allnodes, verbose=False):
if verbose:
print('\n', ('-' * 30))
for t in allnodes:
print(t.eduspan, t.prop, t.relation, [r.eduspan for r in t.nodelist])
print('\n', ('-' * 30))
allnodes = findDuplicate(allnodes)
if verbose:
print('\n', ('-' * 30))
for t in allnodes:
print(t.eduspan, t.prop, t.relation, [r.eduspan for r in t.nodelist])
print('\n', ('-' * 30))
allnodes = cleanChildren(allnodes)
if verbose:
print('\n', ('-' * 30))
for t in allnodes:
print(t.eduspan, t.prop, t.relation, [r.eduspan for r in t.nodelist])
print('\n', ('-' * 30))
return allnodes |
class TinyImageNet(Dataset):
def __init__(self, root, split='train', transform=None, target_transform=None):
NUM_IMAGES_PER_CLASS = 500
self.root = os.path.expanduser(root)
self.transform = transform
self.target_transform = target_transform
self.split_dir = os.path.join(self.root, split)
self.image_paths = sorted(glob.iglob(os.path.join(self.split_dir, '**', '*.JPEG'), recursive=True))
self.labels = {}
with open(os.path.join(self.root, 'wnids.txt'), 'r') as fp:
self.label_texts = sorted([text.strip() for text in fp.readlines()])
self.label_text_to_number = {text: i for (i, text) in enumerate(self.label_texts)}
if (split == 'train'):
for (label_text, i) in self.label_text_to_number.items():
for cnt in range(NUM_IMAGES_PER_CLASS):
self.labels[f'{label_text}_{cnt}.JPEG'] = i
elif (split == 'val'):
with open(os.path.join(self.split_dir, 'val_annotations.txt'), 'r') as fp:
for line in fp.readlines():
terms = line.split('\t')
(file_name, label_text) = (terms[0], terms[1])
self.labels[file_name] = self.label_text_to_number[label_text]
def __len__(self):
return len(self.image_paths)
def __getitem__(self, index):
file_path = self.image_paths[index]
label = self.labels[os.path.basename(file_path)]
label = (self.target_transform(label) if self.target_transform else label)
return (self.read_image(file_path), label)
def read_image(self, path):
img = Image.open(path)
return (self.transform(img) if self.transform else img) |
def convert_detectron2_names(weights):
logger = logging.getLogger(__name__)
logger.info('Remapping Detectrons weights ......')
original_keys = sorted(weights.keys())
layer_keys = copy.deepcopy(original_keys)
layer_keys = [k.replace('proposal_generator.rpn_head.conv', 'proposal_generator.rpn_head.object_conv') for k in layer_keys]
layer_keys = [k.replace('proposal_generator.rpn_head.anchor_deltas', 'proposal_generator.rpn_head.object_deltas') for k in layer_keys]
assert (len(set(layer_keys)) == len(layer_keys))
assert (len(original_keys) == len(layer_keys))
new_weights = {}
new_keys_to_original_keys = {}
for (orig, renamed) in zip(original_keys, layer_keys):
new_keys_to_original_keys[renamed] = orig
if (renamed.startswith('bbox_pred.') or renamed.startswith('mask_head.predictor.')):
new_start_idx = (4 if renamed.startswith('bbox_pred.') else 1)
new_weights[renamed] = weights[orig][new_start_idx:]
logger.info('Remove prediction weight for background class in {}. The shape changes from {} to {}.'.format(renamed, tuple(weights[orig].shape), tuple(new_weights[renamed].shape)))
elif renamed.startswith('cls_score.'):
logger.info('Move classification weights for background class in {} from index 0 to index {}.'.format(renamed, (weights[orig].shape[0] - 1)))
new_weights[renamed] = torch.cat([weights[orig][1:], weights[orig][:1]])
else:
new_weights[renamed] = weights[orig]
return (new_weights, new_keys_to_original_keys) |
def main():
start_time = time.time()
dataset = []
sys.stderr.write((str(datetime.datetime.now()) + '\n'))
book_index = 0
for (i, s_url) in enumerate(ProgressBar()(search_urls)):
time.sleep(SLEEP_SEC)
for try_count in range(MAX_OPEN_COUNT):
try:
response = opener.open(s_url)
if (try_count >= 1):
sys.stderr.write('Succeeded in opening {}\n'.format(s_url))
break
except Exception as e:
sys.stderr.write('Failed to open {}\n'.format(s_url))
sys.stderr.write('{}: {}\n'.format(type(e).__name__, str(e)))
time.sleep(RETRY_SLEEP_SEC)
else:
sys.stderr.write(' Gave up to open {}\n'.format(s_url))
body = response.read()
soup = BeautifulSoup(body, 'lxml')
book_links = soup.find_all(class_='library-title')
for b_link in book_links:
book_index += 1
b_url = b_link.get('href')
for try_count in range(MAX_OPEN_COUNT):
try:
response = opener.open(b_url)
if (try_count >= 1):
sys.stderr.write('Succeeded in opening {}\n'.format(b_url))
break
except Exception as e:
sys.stderr.write('Failed to open {}\n'.format(b_url))
sys.stderr.write('{}: {}\n'.format(type(e).__name__, str(e)))
time.sleep(RETRY_SLEEP_SEC)
else:
sys.stderr.write(' Gave up to open {}\n'.format(b_url))
body = response.read()
soup = BeautifulSoup(body, 'lxml')
meta_infos = soup.find_all(class_='col-md-3')
if (not meta_infos):
sys.stderr.write('Failed: meta_info {}\n'.format(b_url))
continue
meta_txts = [m.text for m in meta_infos if ('Language: English' in m.text)]
is_english = (len(meta_txts) >= 1)
if (not is_english):
continue
meta_txt = meta_txts[0].replace(',', '')
match = num_words_pt.search(meta_txt)
if match:
num_words = int(match.group(1))
elif ('num_words' in REQUIRED):
sys.stderr.write('Failed: num_words {}\n'.format(b_url))
continue
else:
num_words = 0
meta_txt = meta_txts[0]
match = pub_date_pt.search(meta_txt)
if match:
pub_date = match.group(1)
elif ('publish' in REQUIRED):
sys.stderr.write('Failed: publish {}\n'.format(b_url))
continue
else:
pub_data = ''
genre_txts = soup.find_all(class_='category')
if genre_txts:
genres = [g.text.replace('\xa0\xa0', '\t').strip() for g in genre_txts]
elif ('genres' in REQUIRED):
sys.stderr.write('Failed: genre {}\n'.format(b_url))
continue
else:
genres = []
title = soup.find('h1')
if title:
title = title.text
elif ('title' in REQUIRED):
sys.stderr.write('Failed: title {}\n'.format(b_url))
continue
else:
title = ''
author = soup.find(itemprop='author')
if author:
author = author.text
elif ('author' in REQUIRED):
sys.stderr.write('Failed: author {}\n'.format(b_url))
continue
else:
author = ''
epub_links = soup.find_all(title='Supported by many apps and devices (e.g., Apple Books, Barnes and Noble Nook, Kobo, Google Play, etc.)')
if epub_links:
epub_url = epub_links[0].get('href')
if epub_url:
epub_url = (' + epub_url)
elif ('epub' in REQUIRED):
sys.stderr.write('Failed: epub2 {}\n'.format(b_url))
continue
else:
epub_url = ''
elif ('epub' in REQUIRED):
sys.stderr.write('Failed: epub1 {}\n'.format(b_url))
continue
else:
epub_url = ''
txt_links = soup.find_all(title='Plain text; contains no formatting')
if (not txt_links):
txt_url = ''
else:
txt_url = txt_links[0].get('href')
if (not txt_url):
txt_url = ''
else:
txt_url = (' + txt_url)
if ((not epub_url) and (not txt_url)):
sys.stderr.write('Failed: epub and txt {}\n'.format(b_url))
continue
data = {'page': b_url, 'epub': epub_url, 'txt': txt_url, 'title': title, 'author': author, 'genres': genres, 'publish': pub_date, 'num_words': num_words, 'b_idx': book_index}
print(json.dumps(data)) |
class NegativeLog(Flow):
def __init__(self):
super().__init__()
self.eps = torch.finfo(torch.get_default_dtype()).eps
def forward(self, x):
y = (- torch.log(clamp_preserve_gradients(x, min=self.eps, max=(1.0 - self.eps))))
log_det_jac = y
return (y, log_det_jac)
.export
def inverse(self, y):
x = torch.exp((- y))
inv_log_det_jac = (- y)
return (x, inv_log_det_jac) |
class Macdonald(UniqueRepresentation):
def __repr__(self):
return self._name
def __init__(self, Sym, q='q', t='t'):
self._sym = Sym
self._s = Sym.s()
self.q = Sym.base_ring()(q)
self.t = Sym.base_ring()(t)
self._name_suffix = ''
if (str(q) != 'q'):
self._name_suffix += (' with q=%s' % q)
if (str(t) != 't'):
self._name_suffix += ' and '
if (str(t) != 't'):
if (str(q) == 'q'):
self._name_suffix += ' with '
self._name_suffix += ('t=%s' % t)
self._name = ((('Macdonald polynomials' + self._name_suffix) + ' over ') + repr(Sym.base_ring()))
def base_ring(self):
return self._sym.base_ring()
def symmetric_function_ring(self):
return self._sym
def P(self):
return MacdonaldPolynomials_p(self)
def Q(self):
return MacdonaldPolynomials_q(self)
def J(self):
return MacdonaldPolynomials_j(self)
def H(self):
return MacdonaldPolynomials_h(self)
def Ht(self):
return MacdonaldPolynomials_ht(self)
def S(self):
return MacdonaldPolynomials_s(self) |
class Dataset(object):
def __init__(self, path=None, prefix=None):
if (path is not None):
self.init_from_path(path)
else:
self.data = pd.DataFrame([], columns=['path', 'abspath', 'label', 'name'])
self.prefix = prefix
self.base_seed = 0
self.batch_queue = None
self.batch_workers = None
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, value):
self.data[key] = value
return self.data[key]
def _delitem(self, key):
self.data.__delitem__(key)
def num_classes(self):
return len(self.data['label'].unique())
def classes(self):
return self.data['label'].unique()
def size(self):
return self.data.shape[0]
def loc(self):
return self.data.loc
def iloc(self):
return self.data.iloc
def init_from_path(self, path):
path = os.path.expanduser(path)
(_, ext) = os.path.splitext(path)
if os.path.isdir(path):
self.init_from_folder(path)
elif (ext == '.txt'):
self.init_from_list(path)
else:
raise ValueError(('Cannot initialize dataset from path: %s\n It should be either a folder, .txt or .hdf5 file' % path))
def init_from_folder(self, folder):
folder = os.path.abspath(os.path.expanduser(folder))
class_names = os.listdir(folder)
class_names.sort()
paths = []
labels = []
names = []
for (label, class_name) in enumerate(class_names):
classdir = os.path.join(folder, class_name)
if os.path.isdir(classdir):
images_class = os.listdir(classdir)
images_class.sort()
images_class = [os.path.join(class_name, img) for img in images_class]
paths.extend(images_class)
labels.extend((len(images_class) * [label]))
names.extend((len(images_class) * [class_name]))
abspaths = [os.path.join(folder, p) for p in paths]
self.data = pd.DataFrame({'path': paths, 'abspath': abspaths, 'label': labels, 'name': names})
self.prefix = folder
def init_from_list(self, filename, folder_depth=2):
with open(filename, 'r') as f:
lines = f.readlines()
lines = [line.strip().split(' ') for line in lines]
abspaths = [os.path.abspath(line[0]) for line in lines]
paths = ['/'.join(p.split('/')[(- folder_depth):]) for p in abspaths]
if (len(lines[0]) == 2):
labels = [int(line[1]) for line in lines]
names = [str(lb) for lb in labels]
elif (len(lines[0]) == 1):
names = [p.split('/')[(- folder_depth)] for p in abspaths]
(_, labels) = np.unique(names, return_inverse=True)
else:
raise ValueError('List file must be in format: "fullpath(str) label(int)" or just "fullpath(str)"')
self.data = pd.DataFrame({'path': paths, 'abspath': abspaths, 'label': labels, 'name': names})
self.prefix = abspaths[0].split('/')[:(- folder_depth)]
def set_base_seed(self, base_seed=0):
self.base_seed = base_seed
def random_samples_from_class(self, label, num_samples, exception=None):
indices_temp = list(np.where((self.data['label'].values == label))[0])
if (exception is not None):
indices_temp.remove(exception)
assert (len(indices_temp) > 0)
indices = []
iterations = int(np.ceil(((1.0 * num_samples) / len(indices_temp))))
for i in range(iterations):
sample_indices = np.random.permutation(indices_temp)
indices.append(sample_indices)
indices = list(np.concatenate(indices, axis=0)[:num_samples])
return indices
def get_batch_indices(self, batch_format):
indices_batch = []
batch_size = batch_format['size']
num_classes = batch_format['num_classes']
assert ((batch_size % num_classes) == 0)
num_samples_per_class = (batch_size // num_classes)
idx_classes = np.random.permutation(self.classes)[:num_classes]
indices_batch = []
for c in idx_classes:
indices_batch.extend(self.random_samples_from_class(c, num_samples_per_class))
return indices_batch
def get_batch(self, batch_format):
indices = self.get_batch_indices(batch_format)
batch = {}
for column in self.data.columns:
batch[column] = self.data[column].values[indices]
return batch
def start_batch_queue(self, batch_format, proc_func=None, maxsize=1, num_threads=3):
self.batch_queue = Queue(maxsize=maxsize)
def batch_queue_worker(seed):
np.random.seed((seed + self.base_seed))
while True:
batch = self.get_batch(batch_format)
if (proc_func is not None):
batch['image'] = proc_func(batch['abspath'])
self.batch_queue.put(batch)
self.batch_workers = []
for i in range(num_threads):
worker = Process(target=batch_queue_worker, args=(i,))
worker.daemon = True
worker.start()
self.batch_workers.append(worker)
def pop_batch_queue(self, timeout=queue_timeout):
return self.batch_queue.get(block=True, timeout=timeout)
def release_queue(self):
if (self.index_queue is not None):
self.index_queue.close()
if (self.batch_queue is not None):
self.batch_queue.close()
if (self.index_worker is not None):
self.index_worker.terminate()
del self.index_worker
self.index_worker = None
if (self.batch_workers is not None):
for w in self.batch_workers:
w.terminate()
del w
self.batch_workers = None |
class Experience(object):
envt: Optional[Environment] = None
def __init__(self, agents: List[LearningAgent], feasible_actions_all_agents: List[List[Action]], time: float, num_requests: int):
super(Experience, self).__init__()
self.agents = agents
self.feasible_actions_all_agents = feasible_actions_all_agents
self.time = time
self.num_requests = num_requests
assert (self.envt is not None)
assert (len(agents) == self.envt.NUM_AGENTS)
assert (len(feasible_actions_all_agents) == self.envt.NUM_AGENTS)
self.representation: Dict[(str, Any)] = {} |
class Processor():
def __init__(self, arg):
arg.model_saved_name = ('./save_models/' + arg.Experiment_name)
arg.work_dir = ('./work_dir/' + arg.Experiment_name)
self.arg = arg
self.save_arg()
if (arg.phase == 'train'):
if (not arg.train_feeder_args['debug']):
if os.path.isdir(arg.model_saved_name):
self.global_step = 0
self.load_model()
self.load_optimizer()
self.load_data()
self.lr = self.arg.base_lr
self.best_acc = 0
def load_data(self):
Feeder = import_class(self.arg.feeder)
self.data_loader = dict()
if (self.arg.phase == 'train'):
self.data_loader['train'] = torch.utils.data.DataLoader(dataset=Feeder(**self.arg.train_feeder_args), batch_size=self.arg.batch_size, shuffle=True, num_workers=self.arg.num_worker, drop_last=True, worker_init_fn=init_seed)
self.data_loader['test'] = torch.utils.data.DataLoader(dataset=Feeder(**self.arg.test_feeder_args), batch_size=self.arg.test_batch_size, shuffle=False, num_workers=self.arg.num_worker, drop_last=False, worker_init_fn=init_seed)
def load_model(self):
output_device = (self.arg.device[0] if (type(self.arg.device) is list) else self.arg.device)
self.output_device = output_device
Model = import_class(self.arg.model)
shutil.copy2(inspect.getfile(Model), self.arg.work_dir)
self.model = Model(**self.arg.model_args).cuda(output_device)
self.loss = nn.CrossEntropyLoss().cuda(output_device)
if self.arg.weights:
self.print_log('Load weights from {}.'.format(self.arg.weights))
if ('.pkl' in self.arg.weights):
with open(self.arg.weights, 'r') as f:
weights = pickle.load(f)
else:
weights = torch.load(self.arg.weights)
weights = OrderedDict([[k.split('module.')[(- 1)], v.cuda(output_device)] for (k, v) in weights.items()])
for w in self.arg.ignore_weights:
if (weights.pop(w, None) is not None):
self.print_log('Sucessfully Remove Weights: {}.'.format(w))
else:
self.print_log('Can Not Remove Weights: {}.'.format(w))
try:
self.model.load_state_dict(weights)
except:
state = self.model.state_dict()
diff = list(set(state.keys()).difference(set(weights.keys())))
print('Can not find these weights:')
for d in diff:
print((' ' + d))
state.update(weights)
self.model.load_state_dict(state)
if (type(self.arg.device) is list):
if (len(self.arg.device) > 1):
self.model = nn.DataParallel(self.model, device_ids=self.arg.device, output_device=output_device)
def load_optimizer(self):
if (self.arg.optimizer == 'SGD'):
params_dict = dict(self.model.named_parameters())
params = []
for (key, value) in params_dict.items():
decay_mult = (0.0 if ('bias' in key) else 1.0)
lr_mult = 1.0
weight_decay = 0.0001
if ('Linear_weight' in key):
weight_decay = 0.001
elif ('Mask' in key):
weight_decay = 0.0
params += [{'params': value, 'lr': self.arg.base_lr, 'lr_mult': lr_mult, 'decay_mult': decay_mult, 'weight_decay': weight_decay}]
self.optimizer = optim.SGD(params, momentum=0.9, nesterov=self.arg.nesterov)
elif (self.arg.optimizer == 'Adam'):
self.optimizer = optim.Adam(self.model.parameters(), lr=self.arg.base_lr, weight_decay=self.arg.weight_decay)
else:
raise ValueError()
self.lr_scheduler = ReduceLROnPlateau(self.optimizer, mode='min', factor=0.5, patience=5, verbose=True, threshold=0.0001, threshold_mode='rel', cooldown=0)
def save_arg(self):
arg_dict = vars(self.arg)
if (not os.path.exists(self.arg.work_dir)):
os.makedirs(self.arg.work_dir)
os.makedirs((self.arg.work_dir + '/eval_results'))
with open('{}/config.yaml'.format(self.arg.work_dir), 'w') as f:
yaml.dump(arg_dict, f)
def adjust_learning_rate(self, epoch):
if ((self.arg.optimizer == 'SGD') or (self.arg.optimizer == 'Adam')):
if (epoch < self.arg.warm_up_epoch):
lr = ((self.arg.base_lr * (epoch + 1)) / self.arg.warm_up_epoch)
else:
lr = (self.arg.base_lr * (0.1 ** np.sum((epoch >= np.array(self.arg.step)))))
for param_group in self.optimizer.param_groups:
param_group['lr'] = lr
return lr
else:
raise ValueError()
def print_time(self):
localtime = time.asctime(time.localtime(time.time()))
self.print_log(('Local current time : ' + localtime))
def print_log(self, str, print_time=True):
if print_time:
localtime = time.asctime(time.localtime(time.time()))
str = ((('[ ' + localtime) + ' ] ') + str)
print(str)
if self.arg.print_log:
with open('{}/log.txt'.format(self.arg.work_dir), 'a') as f:
print(str, file=f)
def record_time(self):
self.cur_time = time.time()
return self.cur_time
def split_time(self):
split_time = (time.time() - self.cur_time)
self.record_time()
return split_time
def train(self, epoch, save_model=False):
self.model.train()
self.print_log('Training epoch: {}'.format((epoch + 1)))
loader = self.data_loader['train']
self.adjust_learning_rate(epoch)
loss_value = []
acc_value = []
self.record_time()
timer = dict(dataloader=0.001, model=0.001, statistics=0.001)
process = tqdm(loader)
if (epoch >= self.arg.only_train_epoch):
for (key, value) in self.model.named_parameters():
if ('PA' in key):
value.requires_grad = True
print((key + '-require grad'))
else:
for (key, value) in self.model.named_parameters():
if ('PA' in key):
value.requires_grad = False
print((key + '-not require grad'))
for (batch_idx, (data, label, index)) in enumerate(process):
self.global_step += 1
data = Variable(data.float().cuda(self.output_device), requires_grad=False)
label = Variable(label.long().cuda(self.output_device), requires_grad=False)
timer['dataloader'] += self.split_time()
start = time.time()
output = self.model(data)
network_time = (time.time() - start)
loss = self.loss(output, label)
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
loss_value.append(loss)
timer['model'] += self.split_time()
(value, predict_label) = torch.max(output.data, 1)
acc = torch.mean((predict_label == label.data).float())
acc_value.append(acc)
self.lr = self.optimizer.param_groups[0]['lr']
if ((self.global_step % self.arg.log_interval) == 0):
self.print_log('\tBatch({}/{}) done. Loss: {:.4f} lr:{:.6f} network_time: {:.4f}'.format(batch_idx, len(loader), loss.data, self.lr, network_time))
timer['statistics'] += self.split_time()
proportion = {k: '{:02d}%'.format(int(round(((v * 100) / sum(timer.values()))))) for (k, v) in timer.items()}
if save_model:
state_dict = self.model.state_dict()
weights = OrderedDict([[k.split('module.')[(- 1)], v.cpu()] for (k, v) in state_dict.items()])
torch.save(weights, (((((self.arg.model_saved_name + '-') + str(epoch)) + '-') + str(int(self.global_step))) + '.pt'))
avg_loss = torch.mean(torch.stack(loss_value))
avg_acc = torch.mean(torch.stack(acc_value))
med_loss = torch.median(torch.stack(loss_value))
med_acc = torch.median(torch.stack(acc_value))
return (avg_loss, med_loss, avg_acc, med_acc)
def calc_mad(self, acc_values):
med_acc_values = torch.median(torch.stack(acc_values))
abs_dev_med = []
for ind in range(len(acc_values)):
abs_dev_med.append(torch.abs((acc_values[ind] - med_acc_values)))
med_abs_dev = torch.median(torch.stack(abs_dev_med))
return med_abs_dev
def eval(self, epoch, save_score=False, loader_name=['test'], wrong_file=None, result_file=None):
if (wrong_file is not None):
f_w = open(wrong_file, 'w')
if (result_file is not None):
f_r = open(result_file, 'w')
self.model.eval()
self.print_log('Eval epoch: {}'.format((epoch + 1)))
for ln in loader_name:
loss_value = []
acc_value = []
score_frag = []
right_num_total = 0
total_num = 0
loss_total = 0
step = 0
process = tqdm(self.data_loader[ln])
for (batch_idx, (data, label, index)) in enumerate(process):
data = Variable(data.float().cuda(self.output_device), requires_grad=False, volatile=True)
label = Variable(label.long().cuda(self.output_device), requires_grad=False, volatile=True)
with torch.no_grad():
output = self.model(data)
loss = self.loss(output, label)
score_frag.append(output.data.cpu().numpy())
loss_value.append(loss.data.cpu().numpy())
(_, predict_label) = torch.max(output.data, 1)
acc = torch.mean((predict_label == label.data).float())
acc_value.append(acc)
step += 1
if ((wrong_file is not None) or (result_file is not None)):
predict = list(predict_label.cpu().numpy())
true = list(label.data.cpu().numpy())
for (i, x) in enumerate(predict):
if (result_file is not None):
f_r.write((((str(x) + ',') + str(true[i])) + '\n'))
if ((x != true[i]) and (wrong_file is not None)):
f_w.write((((((str(index[i]) + ',') + str(x)) + ',') + str(true[i])) + '\n'))
score = np.concatenate(score_frag)
accuracy = self.data_loader[ln].dataset.top_k(score, 1)
if (accuracy > self.best_acc):
self.best_acc = accuracy
score_dict = dict(zip(self.data_loader[ln].dataset.sample_name, score))
with open(((('./work_dir/' + arg.Experiment_name) + '/eval_results/best_acc') + '.pkl'.format(epoch, accuracy)), 'wb') as f:
pickle.dump(score_dict, f)
print('Eval Accuracy: ', accuracy, ' model: ', self.arg.model_saved_name)
score_dict = dict(zip(self.data_loader[ln].dataset.sample_name, score))
self.print_log('\tMean {} loss of {} batches: {}.'.format(ln, len(self.data_loader[ln]), np.mean(loss_value)))
for k in self.arg.show_topk:
self.print_log('\tTop{}: {:.2f}%'.format(k, (100 * self.data_loader[ln].dataset.top_k(score, k))))
with open((((((('./work_dir/' + arg.Experiment_name) + '/eval_results/epoch_') + str(epoch)) + '_') + str(accuracy)) + '.pkl'.format(epoch, accuracy)), 'wb') as f:
pickle.dump(score_dict, f)
std_acc = torch.std(torch.stack(acc_value))
med_abs_dev = self.calc_mad(acc_value)
avg_loss = np.mean(loss_value)
avg_acc = torch.mean(torch.stack(acc_value))
med_loss = np.median(loss_value)
med_acc = torch.median(torch.stack(acc_value))
return (avg_loss, med_loss, avg_acc, med_acc, std_acc, med_abs_dev)
def start(self):
if (self.arg.phase == 'train'):
self.print_log('Parameters:\n{}\n'.format(str(vars(self.arg))))
self.global_step = ((self.arg.start_epoch * len(self.data_loader['train'])) / self.arg.batch_size)
for epoch in range(self.arg.start_epoch, self.arg.num_epoch):
(avg_train_loss, med_train_loss, avg_train_acc, med_train_acc) = self.train(epoch, save_model=True)
(avg_val_loss, med_val_loss, avg_val_acc, med_val_acc, std_dev_acc, med_abs_dev) = self.eval(epoch, save_score=self.arg.save_score, loader_name=['test'])
self.lr_scheduler.step(avg_val_loss)
writer.add_scalars('Average Accuracies', {'Average training accuracy': avg_train_acc, 'Average Validation accuracy': avg_val_acc, 'Median training accuracy': med_train_acc, 'Median Validation accuracy': med_val_acc}, (epoch + 1))
loss_writer.add_scalars('Average Losses', {'Average training loss': avg_train_loss, 'Average Validation loss': avg_val_loss, 'Median training loss': med_train_loss, 'Median Validation loss': med_val_loss}, (epoch + 1))
train_logger.info('Average training loss after {0} epochs is {1}'.format((epoch + 1), avg_train_loss))
train_logger.info('Average training accuracy after {0} epochs is {1}'.format((epoch + 1), avg_train_acc))
train_logger.info('Median training loss after {0} epochs is {1}'.format((epoch + 1), med_train_loss))
train_logger.info('Median training accuracy after {0} epochs is {1}'.format((epoch + 1), med_train_acc))
eval_logger.info('Average validation loss after {0} epochs is {1}'.format((epoch + 1), avg_val_loss))
eval_logger.info('Average validation accuracy after {0} epochs is {1}'.format((epoch + 1), avg_val_acc))
eval_logger.info('Median validation loss after {0} epochs is {1}'.format((epoch + 1), med_val_loss))
eval_logger.info('Median validation accuracy after {0} epochs is {1}'.format((epoch + 1), med_val_acc))
eval_logger.info('Standard deviation of validation accuracy after {0} epochs is {1}'.format((epoch + 1), std_dev_acc))
eval_logger.info('Median absolute deviation of validation accuracy after {0} epochs is {1}'.format((epoch + 1), med_abs_dev))
print('best accuracy: ', self.best_acc, ' model_name: ', self.arg.model_saved_name)
elif (self.arg.phase == 'test'):
if (not self.arg.test_feeder_args['debug']):
wf = (self.arg.model_saved_name + '_wrong.txt')
rf = (self.arg.model_saved_name + '_right.txt')
else:
wf = rf = None
if (self.arg.weights is None):
raise ValueError('Please appoint --weights.')
self.arg.print_log = False
self.print_log('Model: {}.'.format(self.arg.model))
self.print_log('Weights: {}.'.format(self.arg.weights))
self.eval(epoch=0, save_score=self.arg.save_score, loader_name=['test'], wrong_file=wf, result_file=rf)
self.print_log('Done.\n') |
def wronskian(*args):
if (not args):
raise TypeError('wronskian() takes at least one argument (0 given)')
elif (len(args) == 1):
return args[0]
else:
if (isinstance(args[(- 1)], Expression) and args[(- 1)].is_symbol()):
v = args[(- 1)]
fs = args[0:(- 1)]
def row(n):
return [diff(f, v, n) for f in fs]
else:
fs = args
def row(n):
return [diff(f, n) for f in fs]
return matrix([row(r) for r in range(len(fs))]).determinant() |
class ConsoleStatisticsWriter(Writer):
def __init__(self, precision: int=3, use_logging: bool=False, functions: dict=None):
super().__init__()
self.aggregator = StatisticsAggregator(functions)
self.write_helper = ConsoleWriterHelper(use_logging)
self.precision = precision
def write(self, results: typing.List[evaluator.Result], **kwargs):
aggregated_results = self.aggregator.calculate(results)
lines = [['LABEL', 'METRIC', 'STATISTIC', 'VALUE']]
for result in aggregated_results:
lines.append([result.label, result.metric, result.id_, (result.value if isinstance(result.value, str) else f'{result.value:.{self.precision}f}')])
self.write_helper.format_and_write(lines) |
def test_bernoulli_ts_zozotown_prior():
with pytest.raises(Exception):
BernoulliTS(n_actions=2, is_zozotown_prior=True)
policy_all = BernoulliTS(n_actions=2, is_zozotown_prior=True, campaign='all')
assert (len(np.unique(policy_all.alpha)) != 1)
assert (len(np.unique(policy_all.beta)) != 1)
policy_men = BernoulliTS(n_actions=2, is_zozotown_prior=True, campaign='men')
assert (len(np.unique(policy_men.alpha)) != 1)
assert (len(np.unique(policy_men.beta)) != 1)
policy_women = BernoulliTS(n_actions=2, is_zozotown_prior=True, campaign='women')
assert (len(np.unique(policy_women.alpha)) != 1)
assert (len(np.unique(policy_women.beta)) != 1) |
class InvalidSyscall(UnsupportedSyscall):
def __init__(self, x86=None, x64=None):
UnsupportedSyscall.__init__(self, x86=x86, x64=x64) |
def compute_time(func):
(func)
def wrapper(*args, **kwargs):
begin = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f'function: {func} computation time: {round((end - begin))}s')
return result
return wrapper |
_module()
class SegFormerHead(BaseDecodeHead):
def __init__(self, feature_strides, embedding_dim, **kwargs):
super(SegFormerHead, self).__init__(input_transform='multiple_select', **kwargs)
assert (len(feature_strides) == len(self.in_channels))
assert (min(feature_strides) == feature_strides[0])
self.feature_strides = feature_strides
(c1_in_channels, c2_in_channels, c3_in_channels, c4_in_channels) = self.in_channels
self.linear_c4 = MLP(input_dim=c4_in_channels, embed_dim=embedding_dim)
self.linear_c3 = MLP(input_dim=c3_in_channels, embed_dim=embedding_dim)
self.linear_c2 = MLP(input_dim=c2_in_channels, embed_dim=embedding_dim)
self.linear_c1 = MLP(input_dim=c1_in_channels, embed_dim=embedding_dim)
self.linear_fuse = ConvModule(in_channels=(embedding_dim * 4), out_channels=embedding_dim, kernel_size=1, norm_cfg=dict(type='SyncBN', requires_grad=True))
self.linear_pred = nn.Conv2d(embedding_dim, self.num_classes, kernel_size=1)
def forward(self, inputs):
x = self._transform_inputs(inputs)
(c1, c2, c3, c4) = x
(n, _, h, w) = c4.shape
_c4 = self.linear_c4(c4).permute(0, 2, 1).reshape(n, (- 1), c4.shape[2], c4.shape[3])
_c4 = resize(_c4, size=c1.size()[2:], mode='bilinear', align_corners=False)
_c3 = self.linear_c3(c3).permute(0, 2, 1).reshape(n, (- 1), c3.shape[2], c3.shape[3])
_c3 = resize(_c3, size=c1.size()[2:], mode='bilinear', align_corners=False)
_c2 = self.linear_c2(c2).permute(0, 2, 1).reshape(n, (- 1), c2.shape[2], c2.shape[3])
_c2 = resize(_c2, size=c1.size()[2:], mode='bilinear', align_corners=False)
_c1 = self.linear_c1(c1).permute(0, 2, 1).reshape(n, (- 1), c1.shape[2], c1.shape[3])
_c = self.linear_fuse(torch.cat([_c4, _c3, _c2, _c1], dim=1))
x = self.dropout(_c)
x = self.linear_pred(x)
return x |
def normalize_shape(caffenet_weights):
for layer in caffenet_weights.layer:
for blob in layer.blobs:
shape = (blob.num, blob.channels, blob.height, blob.width)
if (len(blob.data) != np.prod(shape)):
shape = tuple(blob.shape.dim)
if (len(shape) == 1):
shape = (1, 1, 1, shape[0])
if (len(shape) == 2):
shape = (1, 1, shape[0], shape[1])
assert (len(shape) == 4)
(blob.num, blob.channels, blob.height, blob.width) = shape |
def aggregate_mode(mode):
bm25_folder = '/mnt/c/Users/salthamm/Documents/phd/data/coliee2021/task1/bm25/search/{}/separately_para_w_summ_intro/'.format(mode[0])
output_dir = '/mnt/c/Users/salthamm/Documents/phd/data/coliee2021/task1/bm25/aggregate/{}/separately_para_w_summ_intro/'.format(mode[0])
run = read_run_separate_aggregate(bm25_folder, mode[2])
with open(os.path.join(output_dir, 'run_aggregated_{}_{}.pickle'.format(mode[0], mode[2])), 'wb') as f:
pickle.dump(run, f)
return run |
def get_state_dict(net_type: str='alex', version: str='0.1'):
url = (' + f'master/lpips/weights/v{version}/{net_type}.pth')
old_state_dict = torch.hub.load_state_dict_from_url(url, progress=True, map_location=(None if torch.cuda.is_available() else torch.device('cpu')))
new_state_dict = OrderedDict()
for (key, val) in old_state_dict.items():
new_key = key
new_key = new_key.replace('lin', '')
new_key = new_key.replace('model.', '')
new_state_dict[new_key] = val
return new_state_dict |
def get_args():
ap = argparse.ArgumentParser()
ap.add_argument('--scale', dest='scale', type=int, default=224, help='Scale (e.g. 224) for image')
ap.add_argument('--model', dest='model', default='testmodel', help='Model name to load')
ap.add_argument('--port', dest='port', type=int, default=9001, help='Port to listen on')
ap.add_argument('--cores', dest='cores', type=int, default=1, help='Number of neuron cores to use. Must be within [1, 4]. Default=1')
return ap.parse_args() |
def algo_tester(algo: TransformerAlgoBase[(TransformerAlgoImplBase, TransformerConfig)], observation_shape: Shape, action_size: int=2) -> None:
fit_tester(algo, observation_shape, action_size)
from_json_tester(algo, observation_shape, action_size)
load_learnable_tester(algo, observation_shape, action_size)
predict_tester(algo, observation_shape, action_size)
save_and_load_tester(algo, observation_shape, action_size)
update_tester(algo, observation_shape, action_size)
stateful_wrapper_tester(algo, observation_shape, action_size) |
def parse_file(task_name, log_dir, foldername):
path = os.path.join(log_dir, foldername)
if (task_name in ('allreduce', 'allgather')):
return parse_all_ranks(path)
elif (task_name == 'multicast'):
return parse_all_ranks(path, with_rank0=False)
elif (task_name in ('roundtrip', 'reduce', 'gather', 'subset_reduce')):
return result_parser_utils.default_parse_file(task_name, log_dir, foldername)
else:
raise ValueError('Unknown task', task_name) |
class ReparametrizationSampler(ABC, Generic[ProbabilisticModelType]):
def __init__(self, sample_size: int, model: ProbabilisticModelType):
tf.debugging.assert_positive(sample_size)
self._sample_size = sample_size
self._model = model
self._initialized = tf.Variable(False)
def __repr__(self) -> str:
return f'{self.__class__.__name__}({self._sample_size!r}, {self._model!r})'
def sample(self, at: TensorType, *, jitter: float=DEFAULTS.JITTER) -> TensorType:
raise NotImplementedError
def reset_sampler(self) -> None:
self._initialized.assign(False) |
class DynamicShapesDataset():
def __init__(self, length=64, seed=42, batch_size=8):
self.length = length
np.random.seed(seed)
sizes = np.random.randint(1, 20, ((length // batch_size),))
self.xs = [np.random.normal(size=(s,)) for s in sizes.repeat(batch_size)]
self.ys = [np.random.normal(size=(s,)) for s in sizes.repeat(batch_size)]
def __len__(self):
return self.length
def __getitem__(self, i):
return {'input_x': self.xs[i], 'labels': self.ys[i]} |
def is_ninja_available():
try:
subprocess.check_output('ninja --version'.split())
except Exception:
return False
else:
return True |
def main(args):
if (args.buffer_size < 1):
args.buffer_size = 1
if ((args.max_tokens is None) and (args.max_sentences is None)):
args.max_sentences = 1
assert ((not args.sampling) or (args.nbest == args.beam)), '--sampling requires --nbest to be equal to --beam'
assert ((not args.max_sentences) or (args.max_sentences <= args.buffer_size)), '--max-sentences/--batch-size cannot be larger than --buffer-size'
print(args)
use_cuda = (torch.cuda.is_available() and (not args.cpu))
task = tasks.setup_task(args)
print('| loading model(s) from {}'.format(args.path))
model_paths = args.path.split(':')
(models, model_args) = utils.load_ensemble_for_inference(model_paths, task, model_arg_overrides=eval(args.model_overrides))
tgt_dict = task.target_dictionary
for model in models:
model.make_generation_fast_(beamable_mm_beam_size=(None if args.no_beamable_mm else args.beam), need_attn=args.print_alignment)
if args.fp16:
model.half()
translator = SequenceGenerator(models, tgt_dict, beam_size=args.beam, minlen=args.min_len, stop_early=(not args.no_early_stop), normalize_scores=(not args.unnormalized), len_penalty=args.lenpen, unk_penalty=args.unkpen, sampling=args.sampling, sampling_topk=args.sampling_topk, sampling_temperature=args.sampling_temperature, diverse_beam_groups=args.diverse_beam_groups, diverse_beam_strength=args.diverse_beam_strength)
if use_cuda:
translator.cuda()
align_dict = utils.load_align_dict(args.replace_unk)
def make_result(src_str, hypos):
result = Translation(src_str='O\t{}'.format(src_str), hypos=[], pos_scores=[], alignments=[])
for hypo in hypos[:min(len(hypos), args.nbest)]:
(hypo_tokens, hypo_str, alignment) = utils.post_process_prediction(hypo_tokens=hypo['tokens'].int().cpu(), src_str=src_str, alignment=(hypo['alignment'].int().cpu() if (hypo['alignment'] is not None) else None), align_dict=align_dict, tgt_dict=tgt_dict, remove_bpe=args.remove_bpe)
result.hypos.append('H\t{}\t{}'.format(hypo['score'], hypo_str))
result.pos_scores.append('P\t{}'.format(' '.join(map((lambda x: '{:.4f}'.format(x)), hypo['positional_scores'].tolist()))))
result.alignments.append(('A\t{}'.format(' '.join(map((lambda x: str(utils.item(x))), alignment))) if args.print_alignment else None))
return result
def process_batch(batch):
tokens = batch.tokens
lengths = batch.lengths
if use_cuda:
tokens = tokens.cuda()
lengths = lengths.cuda()
encoder_input = {'src_tokens': tokens, 'src_lengths': lengths}
translations = translator.generate(encoder_input, maxlen=int(((args.max_len_a * tokens.size(1)) + args.max_len_b)))
return [make_result(batch.srcs[i], t) for (i, t) in enumerate(translations)]
max_positions = utils.resolve_max_positions(task.max_positions(), *[model.max_positions() for model in models])
if (args.buffer_size > 1):
print('| Sentence buffer size:', args.buffer_size)
print('| Type the input sentence and press return:')
for inputs in buffered_read(args.buffer_size):
indices = []
results = []
for (batch, batch_indices) in make_batches(inputs, args, task, max_positions):
indices.extend(batch_indices)
results += process_batch(batch)
for i in np.argsort(indices):
result = results[i]
print(result.src_str)
for (hypo, pos_scores, align) in zip(result.hypos, result.pos_scores, result.alignments):
print(hypo)
print(pos_scores)
if (align is not None):
print(align) |
class Trainer(object):
def __init__(self, cfg: FairseqConfig, task, model, criterion, quantizer=None):
if isinstance(cfg, Namespace):
logger.warning('argparse.Namespace configuration is deprecated! Automatically converting to OmegaConf')
cfg = convert_namespace_to_omegaconf(cfg)
self.cfg = cfg
self.task = task
shared_params = _catalog_shared_params(model)
self.tpu = cfg.common.tpu
self.cuda = (torch.cuda.is_available() and (not cfg.common.cpu) and (not self.tpu))
if self.cuda:
self.device = torch.device('cuda')
elif self.tpu:
self.device = utils.get_tpu_device()
else:
self.device = torch.device('cpu')
if self.is_fsdp:
import fairscale
if self.cfg.common.bf16:
raise ValueError('FullyShardedDataParallel is not compatible with --bf16 or --memory-efficient-bf16')
if (self.cfg.distributed_training.zero_sharding != 'none'):
raise ValueError("FullyShardedDataParallel is not compatible with --zero-sharding option (it's already built in)")
if ((max(self.cfg.optimization.update_freq) > 1) and (fairscale.__version__ < '0.4.0')):
raise RuntimeError('Please update to fairscale 0.4.0 or newer when combining --update-freq with FullyShardedDataParallel')
elif (hasattr(self.cfg.distributed_training, 'cpu_offload') and self.cfg.distributed_training.cpu_offload):
raise ValueError('--cpu-offload requires --ddp-backend=fully_sharded')
self._criterion = criterion
self._model = model
if (not self.is_fsdp):
if cfg.common.fp16:
assert (not cfg.common.amp), 'Cannot use fp16 and AMP together'
self._criterion = self._criterion.half()
self._model = self._model.half()
elif cfg.common.bf16:
self._criterion = self._criterion.to(dtype=torch.bfloat16)
self._model = self._model.to(dtype=torch.bfloat16)
elif cfg.common.amp:
self._amp_retries = 0
if ((not cfg.distributed_training.pipeline_model_parallel) and (not self.use_distributed_wrapper)):
self._criterion = self._criterion.to(device=self.device)
self._model = self._model.to(device=self.device)
self.pipeline_model_parallel = cfg.distributed_training.pipeline_model_parallel
self.last_device = None
if (self.cuda and self.pipeline_model_parallel):
self.last_device = torch.device(cfg.distributed_training.pipeline_devices[(- 1)])
for shared_param in shared_params:
ref = _get_module_by_path(self._model, shared_param[0])
for path in shared_param[1:]:
logger.info('detected shared parameter: {} <- {}'.format(shared_param[0], path))
_set_module_by_path(self._model, path, ref)
self._dummy_batch = None
self._lr_scheduler = None
self._num_updates = 0
self._num_xla_compiles = 0
self._optim_history = None
self._optimizer = None
self._warn_once = set()
self._wrapped_criterion = None
self._wrapped_model = None
self._ema = None
if (self.cuda and (self.data_parallel_world_size > 1)):
self._grad_norm_buf = torch.cuda.DoubleTensor(self.data_parallel_world_size)
else:
self._grad_norm_buf = None
self.quantizer = quantizer
if (self.quantizer is not None):
self.quantizer.set_trainer(self)
if self.cuda:
self.cuda_env = utils.CudaEnvironment()
if (self.data_parallel_world_size > 1):
self.cuda_env_arr = distributed_utils.all_gather_list(self.cuda_env, group=distributed_utils.get_global_group())
else:
self.cuda_env_arr = [self.cuda_env]
if (self.data_parallel_rank == 0):
utils.CudaEnvironment.pretty_print_cuda_env_list(self.cuda_env_arr)
else:
self.cuda_env = None
self.cuda_env_arr = None
metrics.log_start_time('wall', priority=790, round=0)
self._start_time = time.time()
self._previous_training_time = 0
self._cumulative_training_time = None
def reinitialize(self):
self._lr_scheduler = None
self._optimizer = None
self._wrapped_criterion = None
self._wrapped_model = None
def data_parallel_world_size(self):
if (self.cfg.distributed_training.distributed_world_size == 1):
return 1
return distributed_utils.get_data_parallel_world_size()
def data_parallel_process_group(self):
return distributed_utils.get_data_parallel_group()
def data_parallel_rank(self):
if (self.cfg.distributed_training.distributed_world_size == 1):
return 0
return distributed_utils.get_data_parallel_rank()
def is_data_parallel_master(self):
return (self.data_parallel_rank == 0)
def use_distributed_wrapper(self) -> bool:
return (((self.data_parallel_world_size > 1) and (not self.cfg.optimization.use_bmuf)) or (self.is_fsdp and self.cfg.distributed_training.cpu_offload))
def should_save_checkpoint_on_current_rank(self) -> bool:
if ((self.is_fsdp and self.cfg.distributed_training.use_sharded_state) or (getattr(self.cfg.model, 'base_layers', 0) > 0)):
return True
else:
return self.is_data_parallel_master
def always_call_state_dict_during_save_checkpoint(self) -> bool:
if (self.is_fsdp and (not self.cfg.distributed_training.use_sharded_state)):
return True
else:
return False
def checkpoint_suffix(self) -> str:
if (self.is_fsdp and self.cfg.distributed_training.use_sharded_state):
return (self.cfg.checkpoint.checkpoint_suffix + '-shard{0}'.format(self.data_parallel_rank))
else:
return (self.cfg.checkpoint.checkpoint_suffix or '')
def criterion(self):
if (self._wrapped_criterion is None):
if (utils.has_parameters(self._criterion) and self.use_distributed_wrapper):
self._wrapped_criterion = models.DistributedFairseqModel(self.cfg.distributed_training, self._criterion, process_group=self.data_parallel_process_group, device=self.device)
else:
self._wrapped_criterion = self._criterion
return self._wrapped_criterion
def model(self):
if (self._wrapped_model is None):
if self.use_distributed_wrapper:
self._wrapped_model = models.DistributedFairseqModel(self.cfg.distributed_training, self._model, process_group=self.data_parallel_process_group, device=self.device)
else:
self._wrapped_model = self._model
return self._wrapped_model
def ema(self):
if (self._ema is None):
self._build_ema()
return self._ema
def _build_ema(self):
if self.cfg.ema.store_ema:
self._ema = build_ema(self._model, self.cfg.ema, self.device)
logger.info('Exponential Moving Average Shadow Model is initialized.')
def optimizer(self):
if (self._optimizer is None):
self._build_optimizer()
return self._optimizer
def lr_scheduler(self):
if (self._lr_scheduler is None):
self._build_optimizer()
return self._lr_scheduler
def _build_optimizer(self):
params = list(filter((lambda p: p.requires_grad), chain(self.model.parameters(), self.criterion.parameters())))
if (self.is_fsdp and self.cfg.common.fp16):
allow_unsupported = (not self.cfg.common.memory_efficient_fp16)
self._optimizer = optim.MemoryEfficientFP16Optimizer.build_optimizer(self.cfg, params, allow_unsupported=allow_unsupported)
elif (self.cfg.common.fp16 or self.cfg.common.bf16 or self.cfg.common.amp):
if (self.cuda and (torch.cuda.get_device_capability(0)[0] < 7)):
logger.info('NOTE: your device does NOT support faster training with --fp16 or --amp, please switch to FP32 which is likely to be faster')
if (self.cfg.common.memory_efficient_fp16 or self.cfg.common.memory_efficient_bf16):
self._optimizer = optim.MemoryEfficientFP16Optimizer.build_optimizer(self.cfg, params)
elif self.cfg.common.amp:
self._optimizer = optim.AMPOptimizer.build_optimizer(self.cfg, params)
else:
self._optimizer = optim.FP16Optimizer.build_optimizer(self.cfg, params)
else:
if (self.cuda and (torch.cuda.get_device_capability(0)[0] >= 7)):
logger.info('NOTE: your device may support faster training with --fp16 or --amp')
self._optimizer = optim.build_optimizer(self.cfg.optimizer, params)
if self.is_fsdp:
assert (not self.cfg.optimization.use_bmuf), '--ddp-backend=fully_sharded is not compatible with BMUF'
assert self._optimizer.supports_flat_params, '--ddp-backend=fully_sharded is only compatible with pointwise optimizers (e.g., Adam, AdamW, Adadelta, Adamax, SGD, etc.). However, the sharding will result in slightly different results when using non-pointwise optimizers (e.g., Adagrad, Adafactor, LAMB)'
if self.cfg.optimization.use_bmuf:
self._optimizer = optim.FairseqBMUF(self.cfg.bmuf, self._optimizer)
if (self.cfg.distributed_training.zero_sharding == 'os'):
if ((self.cfg.common.fp16 and (not self.cfg.common.memory_efficient_fp16) and (not self.cfg.common.memory_efficient_bf16)) and (not self.cfg.common.fp16_no_flatten_grads)):
raise ValueError('ZeRO is incomptabile with fp16 and flattened grads. Please use --fp16-no-flatten-grads')
else:
optim.shard_(self._optimizer, self.data_parallel_process_group)
self._lr_scheduler = lr_scheduler.build_lr_scheduler(self.cfg.lr_scheduler, self.optimizer)
self._lr_scheduler.step_update(0)
def is_fsdp(self):
return (self.cfg.distributed_training.ddp_backend == 'fully_sharded')
def consolidate_optimizer(self):
if self.cfg.checkpoint.no_save_optimizer_state:
return
self._gathered_optim_state = None
if hasattr(self.optimizer.optimizer, 'consolidate_state_dict'):
self.optimizer.optimizer.consolidate_state_dict()
elif (self.is_fsdp and (not self.model.use_sharded_state)):
st = self.model.gather_full_optim_state_dict(self.optimizer)
self._gathered_optim_state = st
def state_dict(self):
state_dict = {'args': None, 'cfg': (OmegaConf.to_container(self.cfg, resolve=True, enum_to_str=True) if OmegaConf.is_config(self.cfg) else self.cfg), 'model': self.model.state_dict(), 'criterion': (self.criterion.state_dict() if utils.has_parameters(self.criterion) else None), 'optimizer_history': ((self._optim_history or []) + [{'criterion_name': self.get_criterion().__class__.__name__, 'optimizer_name': self.optimizer.__class__.__name__, 'lr_scheduler_state': self.lr_scheduler.state_dict(), 'num_updates': self.get_num_updates()}]), 'task_state': (self.task.state_dict() if (self.task is not None) else {}), 'extra_state': {'metrics': metrics.state_dict(), 'previous_training_time': self.cumulative_training_time()}}
if self.cfg.ema.store_ema:
state_dict['extra_state']['ema'] = self.ema.get_model().state_dict()
if self.cfg.ema.ema_fp32:
state_dict['extra_state']['ema_fp32_params'] = self.ema.fp32_params
if (not self.cfg.checkpoint.no_save_optimizer_state):
if (self._gathered_optim_state is not None):
state_dict['last_optimizer_state'] = self._gathered_optim_state
self._gathered_optim_state = None
else:
state_dict['last_optimizer_state'] = self.optimizer.state_dict()
if self.is_fsdp:
state_dict['fsdp_metadata'] = self.model.local_metadata_dict()
return state_dict
def save_checkpoint(self, filename, extra_state):
logger.info(f'Saving checkpoint to {filename}')
state_dict = utils.move_to_cpu(self.state_dict())
state_dict['extra_state'].update(extra_state)
if self.should_save_checkpoint_on_current_rank:
checkpoint_utils.torch_persistent_save(state_dict, filename, async_write=self.cfg.checkpoint.write_checkpoints_asynchronously)
logger.info(f'Finished saving checkpoint to {filename}')
def load_checkpoint(self, filename, reset_optimizer=False, reset_lr_scheduler=False, optimizer_overrides=None, reset_meters=False):
(extra_state, self._optim_history, last_optim_state) = (None, [], None)
logger.info(f'Preparing to load checkpoint {filename}')
is_distributed = (self.data_parallel_world_size > 1)
bexists = PathManager.isfile(filename)
if bexists:
load_on_all_ranks = (self.cfg.checkpoint.load_checkpoint_on_all_dp_ranks or self.tpu or (self.is_fsdp and self.cfg.distributed_training.use_sharded_state) or (getattr(self.cfg.model, 'base_layers', 0) > 0))
if (load_on_all_ranks or (self.data_parallel_rank == 0)):
state = checkpoint_utils.load_checkpoint_to_cpu(filename, load_on_all_ranks=load_on_all_ranks)
last_optim_state = state.get('last_optimizer_state', None)
if ((not load_on_all_ranks) and (self.cfg.distributed_training.zero_sharding == 'os') and ('last_optimizer_state' in state) and is_distributed):
state['last_optimizer_state'] = 'SHARDED'
else:
last_optim_state = None
state = None
if (is_distributed and (not load_on_all_ranks)):
state = distributed_utils.broadcast_object(state, src_rank=0, group=self.data_parallel_process_group, dist_device=self.device)
if (self.data_parallel_rank > 0):
last_optim_state = state.get('last_optimizer_state', None)
try:
if (self.cfg.checkpoint.use_ema_weights_to_init_param and ('extra_state' in state) and ('ema' in state['extra_state'])):
logger.info('use_ema_weights_to_init_param = True, will use EMA weights in the ckpt to init the model param...')
ema_state_dict = (state['extra_state']['ema_fp32_params'] if ('ema_fp32_params' in state['extra_state']) else state['extra_state']['ema'])
self.model.load_state_dict(ema_state_dict, strict=True, model_cfg=self.cfg.model)
else:
self.model.load_state_dict(state['model'], strict=True, model_cfg=self.cfg.model)
if (not (self.cfg.ema.store_ema and (self.cfg.checkpoint.use_latest_weights_to_init_ema or (not (('extra_state' in state) and ('ema' in state['extra_state'])))))):
del state['model']
if utils.has_parameters(self.get_criterion()):
self.get_criterion().load_state_dict(state['criterion'], strict=True)
del state['criterion']
except Exception:
raise Exception('Cannot load model parameters from checkpoint {}; please ensure that the architectures match.'.format(filename))
extra_state = state['extra_state']
self._optim_history = state['optimizer_history']
if ((last_optim_state is not None) and (not reset_optimizer)):
self._build_optimizer()
last_optim = self._optim_history[(- 1)]
assert (last_optim['criterion_name'] == self.get_criterion().__class__.__name__), f"Criterion does not match; please reset the optimizer (--reset-optimizer). {last_optim['criterion_name']} vs {self.get_criterion().__class__.__name__}"
assert (last_optim['optimizer_name'] == self.optimizer.__class__.__name__), f"Optimizer does not match; please reset the optimizer (--reset-optimizer). {last_optim['optimizer_name']} vs {self.optimizer.__class__.__name__}"
if (not reset_lr_scheduler):
self.lr_scheduler.load_state_dict(last_optim['lr_scheduler_state'])
if (self.is_fsdp and (not self.model.use_sharded_state)):
last_optim_state = self.model.get_shard_from_optim_state_dict(last_optim_state)
elif ((not load_on_all_ranks) and is_distributed):
last_optim_state = self.optimizer.broadcast_global_state_dict(last_optim_state)
self.optimizer.load_state_dict(last_optim_state, optimizer_overrides)
self.set_num_updates(last_optim['num_updates'])
if (extra_state is not None):
itr_state = extra_state['train_iterator']
epoch = itr_state['epoch']
if ('previous_training_time' in extra_state):
self._previous_training_time = extra_state['previous_training_time']
self._start_time = time.time()
self.lr_step(epoch)
if ((itr_state.get('version', 1) >= 2) and (itr_state['iterations_in_epoch'] == 0)):
reset_meters = True
if (('metrics' in extra_state) and (not reset_meters)):
metrics.load_state_dict(extra_state['metrics'])
for meter in metrics.get_meters('default'):
if isinstance(meter, meters.TimeMeter):
meter.reset()
if self.cfg.ema.store_ema:
if (self.cfg.checkpoint.use_latest_weights_to_init_ema or ('ema' not in extra_state)):
if ('ema' not in extra_state):
logger.warn('EMA not found in checkpoint. But store_ema is True. EMA is re-initialized from checkpoint.')
elif self.cfg.checkpoint.use_latest_weights_to_init_ema:
logger.info('use_latest_weights_to_init_ema = True. EMA is re-initialized from checkpoint.')
self.ema.restore(state['model'], build_fp32_params=self.cfg.ema.ema_fp32)
del state['model']
else:
logger.info('Loading EMA from checkpoint')
self.ema.restore(extra_state['ema'], build_fp32_params=False)
if self.cfg.ema.ema_fp32:
if ('ema_fp32_params' in extra_state):
logger.info('Loading EMA fp32 params from checkpoint')
self.ema.build_fp32_params(extra_state['ema_fp32_params'])
else:
logger.info('Building EMA fp32 params from EMA model in checkpoint')
self.ema.build_fp32_params()
logger.info('Loaded checkpoint {} (epoch {} {} updates)'.format(filename, epoch, self.get_num_updates()))
else:
logger.info('No existing checkpoint found {}'.format(filename))
return extra_state
def get_train_iterator(self, epoch, combine=True, load_dataset=True, data_selector=None, shard_batch_itr=True, disable_iterator_cache=False):
if load_dataset:
logger.info('loading train data for epoch {}'.format(epoch))
self.task.load_dataset(self.cfg.dataset.train_subset, epoch=epoch, combine=combine, data_selector=data_selector, tpu=self.tpu)
batch_iterator = self.task.get_batch_iterator(dataset=self.task.dataset(self.cfg.dataset.train_subset), max_tokens=self.cfg.dataset.max_tokens, max_sentences=self.cfg.dataset.batch_size, max_positions=utils.resolve_max_positions(self.task.max_positions(), self.model.max_positions(), self.cfg.dataset.max_tokens), ignore_invalid_inputs=True, required_batch_size_multiple=self.cfg.dataset.required_batch_size_multiple, seed=self.cfg.common.seed, num_shards=(self.data_parallel_world_size if shard_batch_itr else 1), shard_id=(self.data_parallel_rank if shard_batch_itr else 0), num_workers=self.cfg.dataset.num_workers, epoch=epoch, data_buffer_size=self.cfg.dataset.data_buffer_size, disable_iterator_cache=disable_iterator_cache)
self.reset_dummy_batch(batch_iterator.first_batch)
batch_iterator.dataset.dataset._seek()
return batch_iterator
def get_valid_iterator(self, subset, disable_iterator_cache=False):
self.task.dataset(subset).dataset._seek()
batch_iterator = self.task.get_batch_iterator(dataset=self.task.dataset(subset), max_tokens=self.cfg.dataset.max_tokens_valid, max_sentences=self.cfg.dataset.batch_size_valid, max_positions=utils.resolve_max_positions(self.task.max_positions(), self.model.max_positions()), ignore_invalid_inputs=self.cfg.dataset.skip_invalid_size_inputs_valid_test, required_batch_size_multiple=self.cfg.dataset.required_batch_size_multiple, seed=self.cfg.common.seed, num_shards=self.data_parallel_world_size, shard_id=self.data_parallel_rank, num_workers=self.cfg.dataset.num_workers, epoch=1, data_buffer_size=self.cfg.dataset.data_buffer_size, disable_iterator_cache=disable_iterator_cache)
self.reset_dummy_batch(batch_iterator.first_batch)
batch_iterator.dataset.dataset._seek()
return batch_iterator
def begin_epoch(self, epoch):
logger.info('begin training epoch {}'.format(epoch))
self.lr_step_begin_epoch(epoch)
if (self.quantizer is not None):
self.quantizer.begin_epoch(epoch)
self.task.begin_epoch(epoch, self.get_model())
if self.tpu:
import torch_xla.core.xla_model as xm
xm.rendezvous('begin_epoch')
xm.mark_step()
def begin_valid_epoch(self, epoch):
self.task.begin_valid_epoch(epoch, self.get_model())
def reset_dummy_batch(self, batch):
self._dummy_batch = batch
('train')
def train_step(self, samples, raise_oom=False):
self._set_seed()
self.model.train()
self.criterion.train()
self.zero_grad()
metrics.log_start_time('train_wall', priority=800, round=0)
extra_kwargs = {}
if (self.cfg.ema.store_ema and getattr(self.task, 'uses_ema', False)):
extra_kwargs['ema_model'] = self.ema.get_model()
(logging_outputs, sample_size, ooms) = ([], 0, 0)
for (i, sample) in enumerate(samples):
(sample, is_dummy_batch) = self._prepare_sample(sample)
def maybe_no_sync():
if ((self.data_parallel_world_size > 1) and hasattr(self.model, 'no_sync') and (i < (len(samples) - 1)) and (not self.is_fsdp)):
return self.model.no_sync()
else:
return contextlib.ExitStack()
try:
with maybe_no_sync():
(loss, sample_size_i, logging_output) = self.task.train_step(sample=sample, model=self.model, criterion=self.criterion, optimizer=self.optimizer, update_num=self.get_num_updates(), ignore_grad=is_dummy_batch, **extra_kwargs)
del loss
logging_outputs.append(logging_output)
sample_size += sample_size_i
if (self.cuda and (self.get_num_updates() == 0)):
torch.cuda.empty_cache()
except RuntimeError as e:
if ('out of memory' in str(e)):
self._log_oom(e)
if raise_oom:
raise e
logger.warning('attempting to recover from OOM in forward/backward pass')
ooms += 1
self.zero_grad()
if self.cuda:
torch.cuda.empty_cache()
if (self.cfg.distributed_training.distributed_world_size == 1):
return None
else:
raise e
if (self.tpu and (i < (len(samples) - 1))):
self._xla_markstep_and_send_to_cpu()
if is_dummy_batch:
if torch.is_tensor(sample_size):
sample_size.zero_()
else:
sample_size *= 0.0
if torch.is_tensor(sample_size):
sample_size = sample_size.float()
else:
sample_size = float(sample_size)
if self._sync_stats():
train_time = self._local_cumulative_training_time()
(logging_outputs, (sample_size, ooms, total_train_time)) = self._aggregate_logging_outputs(logging_outputs, sample_size, ooms, train_time, ignore=is_dummy_batch)
self._cumulative_training_time = (total_train_time / self.data_parallel_world_size)
overflow = False
try:
with torch.autograd.profiler.record_function('reduce-grads'):
self.optimizer.all_reduce_grads(self.model)
if utils.has_parameters(self.criterion):
self.optimizer.all_reduce_grads(self.criterion)
with torch.autograd.profiler.record_function('multiply-grads'):
numer = (self.data_parallel_world_size if ((not self.cfg.optimization.use_bmuf) or self._sync_stats()) else 1)
self.optimizer.multiply_grads((numer / (sample_size or 1.0)))
with torch.autograd.profiler.record_function('clip-grads'):
grad_norm = self.clip_grad_norm(self.cfg.optimization.clip_norm)
if (not self.tpu):
if ((not self.cfg.optimization.use_bmuf) and (self.cfg.distributed_training.ddp_backend != 'slow_mo')):
self._check_grad_norms(grad_norm)
if (not torch.isfinite(grad_norm).all()):
if self.cfg.common.amp:
overflow = True
else:
raise FloatingPointError('gradients are Nan/Inf')
with torch.autograd.profiler.record_function('optimizer'):
self.task.optimizer_step(self.optimizer, model=self.model, update_num=self.get_num_updates())
if (self.cfg.common.amp and overflow):
if (self._amp_retries == self.cfg.common.amp_batch_retries):
logger.info('AMP: skipping this batch.')
self._amp_retries = 0
else:
self._amp_retries += 1
return self.train_step(samples, raise_oom)
except FloatingPointError:
self.zero_grad()
with NanDetector(self.get_model()):
for (_, sample) in enumerate(samples):
(sample, _) = self._prepare_sample(sample)
self.task.train_step(sample, self.model, self.criterion, self.optimizer, self.get_num_updates(), ignore_grad=False, **extra_kwargs)
raise
except OverflowError as e:
overflow = True
logger.info(f'NOTE: gradient overflow detected, ignoring gradient, {str(e)}')
grad_norm = torch.tensor(0.0).cuda()
self.zero_grad()
except RuntimeError as e:
if ('out of memory' in str(e)):
self._log_oom(e)
logger.error('OOM during optimization, irrecoverable')
raise e
if hasattr(self.model, 'perform_additional_optimizer_actions'):
if hasattr(self.optimizer, 'fp32_params'):
self.model.perform_additional_optimizer_actions(self.optimizer.optimizer, self.optimizer.fp32_params)
else:
self.model.perform_additional_optimizer_actions(self.optimizer.optimizer)
logging_output = None
if ((not overflow) or (self.cfg.distributed_training.ddp_backend == 'slow_mo')):
self.set_num_updates((self.get_num_updates() + 1))
if self.cfg.ema.store_ema:
self.ema.step(self.get_model(), self.get_num_updates())
metrics.log_scalar('ema_decay', self.ema.get_decay(), priority=10000, round=5, weight=0)
if self.tpu:
import torch_xla.core.xla_model as xm
self._xla_markstep_and_send_to_cpu()
logging_output = {}
if ((self.get_num_updates() % self.cfg.common.log_interval) == 0):
mem_info = xm.get_memory_info(self.device)
gb_free = ((mem_info['kb_free'] / 1024) / 1024)
gb_total = ((mem_info['kb_total'] / 1024) / 1024)
metrics.log_scalar('gb_free', gb_free, priority=1500, round=1, weight=0)
metrics.log_scalar('gb_total', gb_total, priority=1600, round=1, weight=0)
logging_outputs = self._xla_markstep_and_send_to_cpu(logging_outputs)
logging_output = self._reduce_and_log_stats(logging_outputs, sample_size, grad_norm)
self._check_xla_compilation()
else:
if (self.cuda and (self.cuda_env is not None)):
gb_used = (((torch.cuda.max_memory_allocated() / 1024) / 1024) / 1024)
torch.cuda.reset_peak_memory_stats()
gb_free = (self.cuda_env.total_memory_in_GB - gb_used)
metrics.log_scalar('gb_free', gb_free, priority=1500, round=1, weight=0)
logging_output = self._reduce_and_log_stats(logging_outputs, sample_size, grad_norm)
if (self.cuda and (self.cfg.common.empty_cache_freq > 0) and ((((self.get_num_updates() + self.cfg.common.empty_cache_freq) - 1) % self.cfg.common.empty_cache_freq) == 0)):
torch.cuda.empty_cache()
if (self.cfg.common.fp16 or self.cfg.common.amp):
metrics.log_scalar('loss_scale', (self.optimizer.scaler.loss_scale if self.cfg.common.fp16 else self.optimizer.scaler.get_scale()), priority=700, round=4, weight=0)
metrics.log_stop_time('train_wall')
return logging_output
('valid')
def valid_step(self, sample, raise_oom=False):
if self.tpu:
import torch_xla.core.xla_model as xm
xm.rendezvous('valid_step')
extra_kwargs = {}
if (self.cfg.ema.store_ema and getattr(self.task, 'uses_ema', False)):
extra_kwargs['ema_model'] = self.ema.get_model()
with torch.no_grad():
self.model.eval()
self.criterion.eval()
(sample, is_dummy_batch) = self._prepare_sample(sample)
try:
(_loss, sample_size, logging_output) = self.task.valid_step(sample, self.model, self.criterion, **extra_kwargs)
except RuntimeError as e:
if ('out of memory' in str(e)):
self._log_oom(e)
if (not raise_oom):
logger.warning('ran out of memory in validation step, retrying batch')
for p in self.model.parameters():
if (p.grad is not None):
p.grad = None
if self.cuda:
torch.cuda.empty_cache()
return self.valid_step(sample, raise_oom=True)
raise e
logging_outputs = [logging_output]
if is_dummy_batch:
if torch.is_tensor(sample_size):
sample_size.zero_()
else:
sample_size *= 0.0
if (self.data_parallel_world_size > 1):
(logging_outputs, (sample_size,)) = self._aggregate_logging_outputs(logging_outputs, sample_size, ignore=is_dummy_batch)
if self.tpu:
logging_outputs = self._xla_markstep_and_send_to_cpu(logging_outputs)
logging_output = self._reduce_and_log_stats(logging_outputs, sample_size)
return logging_output
def zero_grad(self):
self.optimizer.zero_grad()
def lr_step_begin_epoch(self, epoch):
self.lr_scheduler.step_begin_epoch(epoch)
return self.lr_step_update()
def lr_reinit(self, total_updates, num_updates):
self.lr_scheduler.reinit(total_updates, num_updates)
def lr_step(self, epoch, val_loss=None):
self.lr_scheduler.step(epoch, val_loss)
return self.lr_step_update()
def lr_step_update(self):
new_lr = self.lr_scheduler.step_update(self.get_num_updates())
if isinstance(new_lr, dict):
for (k, v) in new_lr.items():
metrics.log_scalar(f'lr_{k}', v, weight=0, priority=300)
new_lr = new_lr.get('default', next(iter(new_lr.values())))
else:
metrics.log_scalar('lr', new_lr, weight=0, priority=300)
return new_lr
def get_lr(self):
return self.optimizer.get_lr()
def get_model(self):
return self._model
def get_criterion(self):
return self._criterion
def get_meter(self, name):
from fairseq import meters
if ('get_meter' not in self._warn_once):
self._warn_once.add('get_meter')
utils.deprecation_warning('Trainer.get_meter is deprecated. Please use fairseq.metrics instead.')
train_meters = metrics.get_meters('train')
if (train_meters is None):
train_meters = {}
if ((name == 'train_loss') and ('loss' in train_meters)):
return train_meters['loss']
elif (name == 'train_nll_loss'):
m = train_meters.get('nll_loss', None)
return (m or meters.AverageMeter())
elif (name == 'wall'):
m = metrics.get_meter('default', 'wall')
return (m or meters.TimeMeter())
elif (name == 'wps'):
m = metrics.get_meter('train', 'wps')
return (m or meters.TimeMeter())
elif (name in {'valid_loss', 'valid_nll_loss'}):
k = name[len('valid_'):]
m = metrics.get_meter('valid', k)
return (m or meters.AverageMeter())
elif (name == 'oom'):
return meters.AverageMeter()
elif (name in train_meters):
return train_meters[name]
return None
def get_num_updates(self):
return self._num_updates
def set_num_updates(self, num_updates):
self._num_updates = num_updates
self.lr_step_update()
if self.quantizer:
self.quantizer.step_update(self._num_updates)
metrics.log_scalar('num_updates', self._num_updates, weight=0, priority=200)
def clip_grad_norm(self, clip_norm):
def agg_norm_fn(total_norm):
total_norm = (total_norm.cuda().float() ** 2)
total_norm = distributed_utils.all_reduce(total_norm, group=self.data_parallel_process_group)
return (total_norm ** 0.5)
should_agg_norm = (self.is_fsdp and ((self.data_parallel_process_group is not None) or torch.distributed.is_initialized()))
return self.optimizer.clip_grad_norm(clip_norm, aggregate_norm_fn=(agg_norm_fn if should_agg_norm else None))
def cumulative_training_time(self):
if (self._cumulative_training_time is None):
return self._local_cumulative_training_time()
else:
return self._cumulative_training_time
def _local_cumulative_training_time(self):
return ((time.time() - self._start_time) + self._previous_training_time)
def _fp_convert_sample(self, sample):
def apply_half(t):
if (t.dtype is torch.float32):
return t.to(dtype=torch.half)
return t
def apply_bfloat16(t):
if (t.dtype is torch.float32):
return t.to(dtype=torch.bfloat16)
return t
if self.cfg.common.fp16:
sample = utils.apply_to_sample(apply_half, sample)
if self.cfg.common.bf16:
sample = utils.apply_to_sample(apply_bfloat16, sample)
return sample
def _prepare_sample(self, sample, is_dummy=False):
if (sample == 'DUMMY'):
raise Exception("Trying to use an uninitialized 'dummy' batch. This usually indicates that the total number of batches is smaller than the number of participating GPUs. Try reducing the batch size or using fewer GPUs.")
if ((sample is None) or (len(sample) == 0)):
assert ((self._dummy_batch is not None) and (len(self._dummy_batch) > 0)), 'Invalid dummy batch: {}'.format(self._dummy_batch)
(sample, _) = self._prepare_sample(self._dummy_batch, is_dummy=True)
return (sample, True)
if self.cfg.common.on_cpu_convert_precision:
sample = self._fp_convert_sample(sample)
if self.cuda:
if self.pipeline_model_parallel:
if ('target' in sample):
sample['target'] = utils.move_to_cuda(sample['target'], device=self.last_device)
else:
sample = utils.move_to_cuda(sample)
elif (self.tpu and is_dummy):
sample = utils.move_to_cuda(sample, device=self.device)
if (not self.cfg.common.on_cpu_convert_precision):
sample = self._fp_convert_sample(sample)
if (self._dummy_batch == 'DUMMY'):
self._dummy_batch = sample
return (sample, False)
def _set_seed(self):
seed = (self.cfg.common.seed + self.get_num_updates())
utils.set_torch_seed(seed)
def _sync_stats(self):
if (self.data_parallel_world_size == 1):
return False
elif self.cfg.optimization.use_bmuf:
return ((((self.get_num_updates() + 1) % self.cfg.bmuf.global_sync_iter) == 0) and ((self.get_num_updates() + 1) > self.cfg.bmuf.warmup_iterations))
else:
return True
def _log_oom(self, exc):
msg = 'OOM: Ran out of memory with exception: {}'.format(exc)
logger.warning(msg)
if (torch.cuda.is_available() and hasattr(torch.cuda, 'memory_summary')):
for device_idx in range(torch.cuda.device_count()):
logger.warning(torch.cuda.memory_summary(device=device_idx))
sys.stderr.flush()
def _aggregate_logging_outputs(self, logging_outputs: List[Dict[(str, Any)]], *extra_stats_to_sum, ignore=False):
if self.task.__class__.logging_outputs_can_be_summed(self.get_criterion()):
return self._fast_stat_sync_sum(logging_outputs, *extra_stats_to_sum, ignore=ignore)
else:
return self._all_gather_list_sync(logging_outputs, *extra_stats_to_sum, ignore=ignore)
def _all_gather_list_sync(self, logging_outputs: List[Dict[(str, Any)]], *extra_stats_to_sum, ignore=False):
if self.tpu:
raise NotImplementedError
if ignore:
logging_outputs = []
results = list(zip(*distributed_utils.all_gather_list(([logging_outputs] + list(extra_stats_to_sum)), max_size=getattr(self.cfg.common, 'all_gather_list_size', 16384), group=self.data_parallel_process_group)))
(logging_outputs, extra_stats_to_sum) = (results[0], results[1:])
logging_outputs = list(chain.from_iterable(logging_outputs))
extra_stats_to_sum = [sum(s) for s in extra_stats_to_sum]
return (logging_outputs, extra_stats_to_sum)
def _fast_stat_sync_sum(self, logging_outputs: List[Dict[(str, Any)]], *extra_stats_to_sum, ignore=False):
data = {}
for (i, stat) in enumerate(extra_stats_to_sum):
data[('extra_stats_' + str(i))] = stat
if (len(logging_outputs) > 0):
log_keys = list(logging_outputs[0].keys())
for k in log_keys:
if (not ignore):
v = sum((log[k] for log in logging_outputs if (k in log)))
else:
v = logging_outputs[0][k]
v = (torch.zeros_like(v) if torch.is_tensor(v) else 0)
data[('logging_outputs_' + k)] = v
else:
log_keys = None
data = distributed_utils.all_reduce_dict(data, device=self.device, group=self.data_parallel_process_group)
extra_stats_to_sum = [data[('extra_stats_' + str(i))] for i in range(len(extra_stats_to_sum))]
if (log_keys is not None):
logging_outputs = [{k: data[('logging_outputs_' + k)] for k in log_keys}]
else:
logging_outputs = []
return (logging_outputs, extra_stats_to_sum)
def _check_grad_norms(self, grad_norm):
if (self._grad_norm_buf is not None):
self._grad_norm_buf.zero_()
self._grad_norm_buf[self.data_parallel_rank] = grad_norm
distributed_utils.all_reduce(self._grad_norm_buf, group=self.data_parallel_process_group)
def is_consistent(tensor):
max_abs_diff = torch.max(torch.abs((tensor - tensor[0])))
return ((torch.isfinite(tensor).all() and ((max_abs_diff / (tensor[0] + 1e-06)) < 1e-06).all()) or (self.cfg.common.amp and (not torch.isfinite(tensor).all())))
if (not is_consistent(self._grad_norm_buf)):
pretty_detail = '\n'.join(('rank {:3d} = {:.8f}'.format(r, n) for (r, n) in enumerate(self._grad_norm_buf.tolist())))
error_detail = 'grad_norm across the workers:\n{}\n'.format(pretty_detail)
raise FloatingPointError((((('Fatal error: gradients are inconsistent between workers. Try --ddp-backend=legacy_ddp. Or are you mixing up different generation of GPUs in training?' + '\n') + ('-' * 80)) + '\n{}\n'.format(error_detail)) + ('-' * 80)))
def _reduce_and_log_stats(self, logging_outputs, sample_size, grad_norm=None):
if ((grad_norm is not None) and ((not torch.is_tensor(grad_norm)) or torch.isfinite(grad_norm))):
metrics.log_speed('ups', 1.0, priority=100, round=2)
metrics.log_scalar('gnorm', grad_norm, priority=400, round=3)
if (self.cfg.optimization.clip_norm > 0):
metrics.log_scalar('clip', torch.where((grad_norm > self.cfg.optimization.clip_norm), grad_norm.new_tensor(100), grad_norm.new_tensor(0)), priority=500, round=1)
with metrics.aggregate() as agg:
if (logging_outputs is not None):
self.task.reduce_metrics(logging_outputs, self.get_criterion())
del logging_outputs
if ('loss' not in agg):
if ('loss' not in self._warn_once):
self._warn_once.add('loss')
logger.warning("Criterion.reduce_metrics did not log a 'loss' value, which may break some functionality")
metrics.log_scalar('loss', (- 1))
if self.tpu:
logging_output = {}
else:
logging_output = agg.get_smoothed_values()
logging_output['sample_size'] = sample_size
for key_to_delete in ['ppl', 'wps', 'wpb', 'bsz']:
if (key_to_delete in logging_output):
del logging_output[key_to_delete]
return logging_output
def _check_xla_compilation(self):
import torch_xla.debug.metrics as met
compile_stats = met.metric_data('CompileTime')
if (compile_stats is None):
return
num_xla_compiles = compile_stats[0]
if (num_xla_compiles > self._num_xla_compiles):
logger.warning('XLA compilation detected on device #{}; too many of these can lead to slow training, but we expect a few in the beginning'.format(self.cfg.distributed_training.distributed_rank))
self._num_xla_compiles = num_xla_compiles
def _xla_markstep_and_send_to_cpu(self, data=None):
import torch_xla.core.xla_model as xm
xm.mark_step()
if (data is not None):
from fairseq.utils import xla_device_to_cpu
return xla_device_to_cpu(data) |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--config', dest='config', default='', type=str, help='3R Scan configuration file name')
parser.add_argument('--split', dest='split', default='', type=str, help='split to run on')
parser.add_argument('--visualise', dest='visualise', action='store_true', help='visualisation of subscene generation - camera trajectory')
parser.add_argument('--scan_id', dest='scan_id', default='', type=str, help='3RScan scan Id to run subscan generation (only visualisation) on')
args = parser.parse_args()
return (parser, args) |
def hook_debug(module, input, output):
print(('Hooking ' + module.__class__.__name__))
print('output size:', output.data.size())
return output |
class TestOptions():
def __init__(self):
self.parser = argparse.ArgumentParser()
self.initialized = False
def initialize(self):
self.parser.add_argument('--dataset', type=str, default='paris_streetview', help='The dataset of the experiment.')
self.parser.add_argument('--data_file', type=str, default='./imgs/paris-streetview_256x256', help='the file storing testing file paths')
self.parser.add_argument('--test_dir', type=str, default='./test_results', help='models are saved here')
self.parser.add_argument('--load_model_dir', type=str, default='./checkpoints', help='pretrained models are given here')
self.parser.add_argument('--model_prefix', type=str, default='snap')
self.parser.add_argument('--seed', type=int, default=1, help='random seed')
self.parser.add_argument('--use_noise', type=int, default=0)
self.parser.add_argument('--data_noise', type=str, default='')
self.parser.add_argument('--data_noise_aux', type=str, default='')
self.parser.add_argument('--use_blend', type=int, default=1)
self.parser.add_argument('--embrace', type=int, default=0, help='use the all data or not, default is not')
self.parser.add_argument('--rho', type=float, default=0.5, help='control ratio in context normalization')
self.parser.add_argument('--model', type=str, default='vcn')
self.parser.add_argument('--random_mask', type=int, default=0, help='using random mask')
self.parser.add_argument('--use_cn', type=int, default=1)
self.parser.add_argument('--cn_type', type=str, default='v1', choices=['v1', 'se', 'old'], help='[v1|se|old]')
self.parser.add_argument('--use_mrf', type=int, default=0)
self.parser.add_argument('--phase', type=str, default='tune')
self.parser.add_argument('--img_shapes', type=str, default='256,256,3', help='given shape parameters: h,w,c or h,w')
self.parser.add_argument('--mask_shapes', type=str, default='128,128', help='given mask parameters: h,w')
self.parser.add_argument('--mask_type', type=str, default='stroke')
self.parser.add_argument('--test_num', type=int, default=(- 1))
self.parser.add_argument('--mode', type=str, default='save')
self.parser.add_argument('--save_intermediate', type=int, default=0)
self.parser.add_argument('--g_cnum', type=int, default=32, help='# of generator filters in first conv layer')
self.parser.add_argument('--d_cnum', type=int, default=64, help='# of discriminator filters in first conv layer')
def parse(self):
if (not self.initialized):
self.initialize()
self.opt = self.parser.parse_args()
if (self.opt.data_file != ''):
self.opt.dataset_path = self.opt.data_file
if (os.path.exists(self.opt.test_dir) is False):
os.mkdir(self.opt.test_dir)
assert (self.opt.random_mask in [0, 1])
self.opt.random_mask = (True if (self.opt.random_mask == 1) else False)
assert (self.opt.use_cn in [0, 1])
self.opt.use_cn = (True if (self.opt.use_cn == 1) else False)
assert (self.opt.use_mrf in [0, 1])
self.opt.use_mrf = (True if (self.opt.use_mrf == 1) else False)
assert (self.opt.use_noise in [0, 1])
self.opt.use_noise = (True if (self.opt.use_noise == 1) else False)
assert (self.opt.use_blend in [0, 1])
self.opt.use_blend = (True if (self.opt.use_blend == 1) else False)
assert (self.opt.save_intermediate in [0, 1])
self.opt.save_intermediate = (True if (self.opt.save_intermediate == 1) else False)
assert (self.opt.embrace in [0, 1])
self.opt.embrace = (True if (self.opt.embrace == 1) else False)
assert (self.opt.mask_type in ['rect', 'stroke'])
str_img_shapes = self.opt.img_shapes.split(',')
self.opt.img_shapes = [int(x) for x in str_img_shapes]
str_mask_shapes = self.opt.mask_shapes.split(',')
self.opt.mask_shapes = [int(x) for x in str_mask_shapes]
self.opt.date_str = ('test_' + time.strftime('%Y%m%d-%H%M%S'))
self.opt.model_folder = ((((self.opt.date_str + '_') + self.opt.dataset) + '_') + self.opt.model)
self.opt.model_folder += ((('_s' + str(self.opt.img_shapes[0])) + 'x') + str(self.opt.img_shapes[1]))
self.opt.model_folder += ('_gc' + str(self.opt.g_cnum))
self.opt.model_folder += ('_r' + str((10 * self.opt.rho)))
self.opt.model_folder += (('_randmask-' + self.opt.mask_type) if self.opt.random_mask else '')
self.opt.model_folder += ('_RM' if self.opt.embrace else '')
if self.opt.random_mask:
self.opt.model_folder += ('_seed-' + str(self.opt.seed))
self.opt.saving_path = os.path.join(self.opt.test_dir, self.opt.model_folder)
if ((os.path.exists(self.opt.saving_path) is False) and (self.opt.mode == 'save')):
os.mkdir(self.opt.saving_path)
return self.opt
def __string__(self):
args = vars(self.opt)
doc = ' Options \n'
for (k, v) in sorted(args.items()):
doc += f'''{str(k)}: {str(v)}
'''
doc += ' End ' |
class _FSMTapeCacheDetectEpsilon_(_FSMTapeCache_):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._visited_states_ = set()
def __deepcopy__(self, memo):
new = super().__deepcopy__(memo)
new._visited_states_ = copy(self._visited_states_)
return new
def _transition_possible_test_(self, word_in):
return self._transition_possible_epsilon_(word_in) |
def get_global_config(*, raise_exception: bool=True, auto_create: bool=False, return_empty_if_none: bool=False):
config = _get_or_set_config_via_tf_default_graph()
if config:
return config
if _global_config:
return _global_config
import sys
main_mod = sys.modules['__main__']
if (hasattr(main_mod, 'config') and isinstance(main_mod.config, Config)):
return main_mod.config
import returnn.__main__ as rnn
if isinstance(rnn.config, Config):
return rnn.config
if auto_create:
config = Config()
set_global_config(config)
return config
if return_empty_if_none:
return Config()
if raise_exception:
raise Exception('No global config found.')
return None |
def validate_fi_hetu(df: Union[(str, pd.Series, dd.Series, pd.DataFrame, dd.DataFrame)], column: str='') -> Union[(bool, pd.Series, pd.DataFrame)]:
if isinstance(df, (pd.Series, dd.Series)):
return df.apply(hetu.is_valid)
elif isinstance(df, (pd.DataFrame, dd.DataFrame)):
if (column != ''):
return df[column].apply(hetu.is_valid)
else:
return df.applymap(hetu.is_valid)
return hetu.is_valid(df) |
def log_item(tag: str, val: (((((float | int) | bool) | list) | np.ndarray) | torch.Tensor), writer: SummaryWriter, step: Optional[int]=None, nchains: Optional[int]=None) -> None:
if (step is not None):
log_step(tag, step, writer)
tag = check_tag(tag)
if isinstance(val, (Tensor, Array)):
if ((nchains is not None) and (len(val.shape) > 0)):
val = val[:nchains]
if ((isinstance(val, Tensor) and torch.is_complex(val)) or (isinstance(val, Array) and np.iscomplexobj(val))):
log_item(tag=f'{tag}/real', val=val.real, writer=writer, step=step)
log_item(tag=f'{tag}/imag', val=val.imag, writer=writer, step=step)
elif (len(val.shape) > 0):
writer.add_scalar(f'{tag}/avg', val.mean(), global_step=step)
val = (val[:nchains] if ((len(val.shape) > 0) and (nchains is not None)) else val)
if (len(val.shape) > 0):
if (nchains is not None):
val = val[:nchains]
try:
writer.add_histogram(tag=tag, values=val, global_step=step)
except ValueError:
log.error(f'Error adding histogram for: {tag}')
else:
writer.add_scalar(tag, val, global_step=step)
elif isinstance(val, list):
log_list(writer=writer, x=val, step=step, prefix=tag)
elif (isinstance(val, (float, int, bool, np.floating)) or (len(val.shape) == 0)):
writer.add_scalar(tag=tag, scalar_value=val, global_step=step)
else:
log.warning(f'Unexpected type encountered for: {tag}')
log.warning(f'{tag}.type: {type(val)}') |
def spherical_plot3d(f, urange, vrange, **kwds):
return plot3d(f, urange, vrange, transformation=Spherical('radius', ['azimuth', 'inclination']), **kwds) |
def try_get_nn_module_compiled_mod_and_inputs(*args, **kwargs):
name = get_nn_module_name_from_kwargs(**kwargs)
if (('desc' in kwargs) and ('eval' in kwargs['desc'])):
return
test_name = name
if ('desc' in kwargs):
test_name = '{}_{}'.format(test_name, kwargs['desc'])
test_name = get_nn_mod_test_name(**kwargs)
if (test_name in EXCLUDE_SCRIPT_MODULES):
return
if ('constructor' in kwargs):
nn_module = kwargs['constructor']
else:
nn_module = getattr(torch.nn, name)
if ('FunctionalModule' in str(nn_module)):
return
if ('constructor_args_fn' in kwargs):
constructor_args = kwargs['constructor_args_fn']()
else:
constructor_args = kwargs.get('constructor_args', ())
if ('input_fn' in kwargs):
input = kwargs['input_fn']()
else:
input = (kwargs['input_size'],)
if ('extra_args' in kwargs):
input = (input + kwargs['extra_args'])
if ('target_size' in kwargs):
input = (input + (kwargs['target_size'],))
elif ('target_fn' in kwargs):
if torch.is_tensor(input):
input = (input,)
input = (input + (kwargs['target_fn'](),))
(args_variable, kwargs_variable) = create_input(input)
f_args_variable = deepcopy(unpack_variables(args_variable))
out_var = deepcopy(f_args_variable)
(args, mod) = (f_args_variable, create_script_module(None, nn_module, constructor_args, *f_args_variable)(*f_args_variable))
return (mod, out_var) |
def train(train_loader, train_table, model, model_bert, opt, bert_config, tokenizer, max_seq_length, num_target_layers, accumulate_gradients=1, check_grad=False, st_pos=0, opt_bert=None, path_db=None, dset_name='train', col_pool_type='start_tok', aug=False):
model.train()
model_bert.train()
ave_loss = 0
cnt = 0
cnt_sc = 0
cnt_sa = 0
cnt_wn = 0
cnt_wc = 0
cnt_wo = 0
cnt_wv = 0
cnt_wvi = 0
cnt_lx = 0
cnt_x = 0
engine = DBEngine(os.path.join(path_db, f'{dset_name}.db'))
for (iB, t) in enumerate(train_loader):
cnt += len(t)
if (cnt < st_pos):
continue
(nlu, nlu_t, sql_i, sql_q, sql_t, tb, hs_t, hds) = get_fields(t, train_table, no_hs_t=True, no_sql_t=True)
(g_sc, g_sa, g_wn, g_wc, g_wo, g_wv) = get_g(sql_i)
g_wvi_corenlp = get_g_wvi_corenlp(t)
(all_encoder_layer, pooled_output, tokens, i_nlu, i_hds, l_n, l_hpu, l_hs, nlu_tt, t_to_tt_idx, tt_to_t_idx) = get_bert_output(model_bert, tokenizer, nlu_t, hds, max_seq_length)
try:
g_wvi = get_g_wvi_bert_from_g_wvi_corenlp(t_to_tt_idx, g_wvi_corenlp)
except:
continue
wemb_n = get_wemb_n(i_nlu, l_n, bert_config.hidden_size, bert_config.num_hidden_layers, all_encoder_layer, 1)
wemb_h = get_wemb_h_FT_Scalar_1(i_hds, l_hs, bert_config.hidden_size, all_encoder_layer, col_pool_type=col_pool_type)
cls_vec = pooled_output
(s_sc, s_sa, s_wn, s_wc, s_wo, s_wv) = model(wemb_n, l_n, wemb_h, l_hs, cls_vec, g_sc=g_sc, g_sa=g_sa, g_wn=g_wn, g_wc=g_wc, g_wo=g_wo, g_wvi=g_wvi)
loss = Loss_sw_se(s_sc, s_sa, s_wn, s_wc, s_wo, s_wv, g_sc, g_sa, g_wn, g_wc, g_wo, g_wvi)
if ((iB % accumulate_gradients) == 0):
opt.zero_grad()
if opt_bert:
opt_bert.zero_grad()
loss.backward()
if (accumulate_gradients == 1):
opt.step()
if opt_bert:
opt_bert.step()
elif ((iB % accumulate_gradients) == (accumulate_gradients - 1)):
loss.backward()
opt.step()
if opt_bert:
opt_bert.step()
else:
loss.backward()
if check_grad:
named_parameters = model.named_parameters()
(mu_list, sig_list) = get_mean_grad(named_parameters)
grad_abs_mean_mean = mean(mu_list)
grad_abs_mean_sig = std(mu_list)
grad_abs_sig_mean = mean(sig_list)
else:
grad_abs_mean_mean = 1
grad_abs_mean_sig = 1
grad_abs_sig_mean = 1
(pr_sc, pr_sa, pr_wn, pr_wc, pr_wo, pr_wvi) = pred_sw_se(s_sc, s_sa, s_wn, s_wc, s_wo, s_wv)
(pr_wv_str, pr_wv_str_wp) = convert_pr_wvi_to_string(pr_wvi, nlu_t, nlu_tt, tt_to_t_idx, nlu)
pr_sql_i = generate_sql_i(pr_sc, pr_sa, pr_wn, pr_wc, pr_wo, pr_wv_str, nlu)
(cnt_sc1_list, cnt_sa1_list, cnt_wn1_list, cnt_wc1_list, cnt_wo1_list, cnt_wvi1_list, cnt_wv1_list) = get_cnt_sw_list(g_sc, g_sa, g_wn, g_wc, g_wo, g_wvi, pr_sc, pr_sa, pr_wn, pr_wc, pr_wo, pr_wvi, sql_i, pr_sql_i, mode='train')
cnt_lx1_list = get_cnt_lx_list(cnt_sc1_list, cnt_sa1_list, cnt_wn1_list, cnt_wc1_list, cnt_wo1_list, cnt_wv1_list)
if (not aug):
(cnt_x1_list, g_ans, pr_ans) = get_cnt_x_list(engine, tb, g_sc, g_sa, sql_i, pr_sc, pr_sa, pr_sql_i)
else:
cnt_x1_list = ([0] * len(t))
g_ans = (['N/A (data augmented'] * len(t))
pr_ans = (['N/A (data augmented'] * len(t))
ave_loss += loss.item()
cnt_sc += sum(cnt_sc1_list)
cnt_sa += sum(cnt_sa1_list)
cnt_wn += sum(cnt_wn1_list)
cnt_wc += sum(cnt_wc1_list)
cnt_wo += sum(cnt_wo1_list)
cnt_wvi += sum(cnt_wvi1_list)
cnt_wv += sum(cnt_wv1_list)
cnt_lx += sum(cnt_lx1_list)
cnt_x += sum(cnt_x1_list)
ave_loss /= cnt
acc_sc = (cnt_sc / cnt)
acc_sa = (cnt_sa / cnt)
acc_wn = (cnt_wn / cnt)
acc_wc = (cnt_wc / cnt)
acc_wo = (cnt_wo / cnt)
acc_wvi = (cnt_wv / cnt)
acc_wv = (cnt_wv / cnt)
acc_lx = (cnt_lx / cnt)
acc_x = (cnt_x / cnt)
acc = [ave_loss, acc_sc, acc_sa, acc_wn, acc_wc, acc_wo, acc_wvi, acc_wv, acc_lx, acc_x]
aux_out = [grad_abs_mean_mean, grad_abs_mean_sig, grad_abs_sig_mean]
return (acc, aux_out) |
class TestRoIDataLoader(unittest.TestCase):
('roi_data.loader.get_minibatch_blob_names', return_value=[u'data'])
('roi_data.loader.get_minibatch', side_effect=get_roidb_blobs)
def test_two_parallel_loaders(self, _1, _2):
train_data = np.random.rand(2, 3, 3).astype(np.float32)
(train_loader, train_net) = create_loader_and_network(train_data, 'dequeue_net_train')
test_data = np.random.rand(2, 4, 4).astype(np.float32)
(test_loader, test_net) = create_loader_and_network(test_data, 'dequeue_net_test')
for _ in range(5):
data = run_net(train_net)
self.assertEqual(data[0].tolist(), train_data.tolist())
data = run_net(test_net)
self.assertEqual(data[0].tolist(), test_data.tolist())
test_loader.shutdown()
train_loader.shutdown() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.