code stringlengths 17 6.64M |
|---|
def get_loader_from_returnn_dataset(dataset: Dataset, mp_manager: torch.multiprocessing.Manager) -> DataLoader:
epoch_mp_shared = mp_manager.Value('i', 0)
epoch_mp_shared.value = 1
reset_callback = returnn_dataset_wrapper.ReturnnDatasetResetMpSharedEpochCallback(dataset=dataset, epoch_mp_shared=epoch_mp_s... |
def test_pipeline_serialization():
dataset = Task12AXDataset(num_seqs=1000)
mp_manager = torch.multiprocessing.Manager()
loader = get_loader_from_returnn_dataset(dataset, mp_manager)
c = 0
n = 3
for batch in loader:
print(batch)
c += 1
if (c >= n):
break
... |
def test_HDFDataset():
from test_HDFDataset import generate_hdf_from_other, HDFDataset
hdf_fn = generate_hdf_from_other({'class': 'Task12AXDataset', 'num_seqs': 23})
hdf_dataset = HDFDataset(files=[hdf_fn], cache_byte_size=0)
mp_manager = torch.multiprocessing.Manager()
loader = get_loader_from_re... |
def test_MultiProcDataset_HDFDataset():
from test_HDFDataset import generate_hdf_from_other
from test_MultiProcDataset import timeout
from returnn.datasets.multi_proc import MultiProcDataset
hdf_fn = generate_hdf_from_other({'class': 'Task12AXDataset', 'num_seqs': 23})
with timeout(10):
mp... |
def test_torch_engine_train():
class _Model(torch.nn.Module):
def __init__(self, **_kwargs):
super(_Model, self).__init__()
self.lin = torch.nn.Linear(9, 2)
def __call__(self, x: torch.Tensor) -> torch.Tensor:
"\n :param x: [B,T,D]\n :re... |
def test_torch_engine_forward_simple():
def _get_model(**_kwargs):
return torch.nn.Module()
def _forward_step(*, extern_data: TensorDict, **_kwargs):
rf.get_run_ctx().mark_as_default_output(extern_data['data'])
config = Config(dict(task='forward', extern_data={'data': {'dim': 9}}, batch_... |
def test_torch_engine_forward():
def _get_model(**_kwargs):
return torch.nn.Module()
def _forward_step(*, extern_data: TensorDict, **_kwargs):
rf.get_run_ctx().mark_as_default_output(extern_data['data'])
class _ForwardCallback(ForwardCallbackIface):
def __init__(self):
... |
def test_torch_engine_forward_pure_torch_no_model_out():
def _get_model(**_kwargs):
return torch.nn.Module()
def _forward_step(*, extern_data: TensorDict, **_kwargs):
rf.get_run_ctx().mark_as_default_output(extern_data['data'].raw_tensor)
config = Config(dict(task='forward', extern_data=... |
def test_torch_forward_raw_strings():
from test_Dataset import create_ogg_zip_txt_only_dataset
def _get_model(**_kwargs):
return torch.nn.Module()
def _forward_step(*, extern_data: TensorDict, **_kwargs):
for (key, value) in extern_data.data.items():
rf.get_run_ctx().mark_as_... |
def test_forward_beam_seq_lens():
from returnn.tensor import Dim, batch_dim
def _get_model(**_kwargs):
return torch.nn.Module()
def _forward_step(*, extern_data: TensorDict, **_kwargs):
data = extern_data['data']
assert (data.dims[0] == batch_dim)
time_dim = data.dims[1]
... |
def test_min_seq_len():
from returnn.datasets.generating import DummyDataset
config = Config({'min_seq_length': 2, 'batch_size': 3})
dataset = DummyDataset(input_dim=1, output_dim=4, num_seqs=1, seq_len=1)
dataset.initialize()
dataset.init_seq_order(epoch=1)
engine = Engine(config=config)
... |
def test_max_seq_len():
from returnn.datasets.generating import DummyDataset
config = Config({'max_seq_length': 4, 'batch_size': 3})
dataset = DummyDataset(input_dim=1, output_dim=4, num_seqs=1, seq_len=5)
dataset.initialize()
dataset.init_seq_order(epoch=1)
engine = Engine(config=config)
... |
def test_data_loader_oggzip():
from test_Dataset import create_ogg_zip_txt_only_dataset_mult_seqs
ds_num_seqs = 23
ds_max_seq_len = 11
max_seqs = 3
config = Config({'max_seqs': max_seqs, 'batch_size': (max_seqs * ds_max_seq_len)})
with create_ogg_zip_txt_only_dataset_mult_seqs(num_seqs=ds_num_... |
def test_load_optimizer_old_format():
config = Config(dict(optimizer={'class': 'adamw', 'weight_decay': 0.001}))
model = torch.nn.Linear(7, 5)
updater = Updater(config=config, network=model, device=torch.device('cpu'))
updater.create_optimizer()
with tempfile.TemporaryDirectory(prefix='returnn_tes... |
def test_optimizer_convert_aux_param():
from returnn.torch.frontend.bridge import rf_module_to_pt_module
config = Config(dict(optimizer={'class': 'adamw', 'weight_decay': 0.001}))
rf.select_backend_torch()
class _Model(rf.Module):
def __init__(self):
super().__init__()
... |
class _DemoException(Exception):
pass
|
class _TestTorchSubModelRaisingException(torch.nn.Module):
def __init__(self, in_features: int, out_features: int):
super().__init__()
self.lin = torch.nn.Linear(in_features, out_features)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"\n :param x: [B,T,D]\n :retu... |
def test_torch_engine_train_exception():
class _Model(torch.nn.Module):
def __init__(self, **_kwargs):
super(_Model, self).__init__()
self.sub = _TestTorchSubModelRaisingException(9, 2)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"\n :param... |
def test_dot_scalar_multiplication():
a_raw = torch.tensor(2.0)
b_raw = torch.tensor(3.0)
a = Tensor(name='a', dims=[], dtype='float32', raw_tensor=a_raw)
b = Tensor(name='b', dims=[], dtype='float32', raw_tensor=b_raw)
result = rf.matmul(a, b, reduce=[])
assert (pytest.approx(result.raw_tenso... |
def test_dot_scalar_product():
a_raw = torch.tensor([1.0, 2.0, 3.0])
b_raw = torch.tensor([4.0, 5.0, 6.0])
feature_dim = Dim(dimension=3)
a = Tensor(name='a', dims=[feature_dim], dtype='float32', raw_tensor=a_raw)
b = Tensor(name='b', dims=[feature_dim], dtype='float32', raw_tensor=b_raw)
resu... |
def test_dot_outer_product():
a_raw = torch.tensor([1.0, 2.0, 3.0])
b_raw = torch.tensor([4.0, 5.0, 6.0])
a_feature_dim = Dim(dimension=3)
b_feature_dim = Dim(dimension=3)
a = Tensor(name='a', dims=[a_feature_dim], dtype='float32', raw_tensor=a_raw)
b = Tensor(name='b', dims=[b_feature_dim], d... |
def test_dot_matrix_vector_product():
a_raw = torch.tensor([[1.0, 2.0, 3.0], [(- 1.0), (- 2.0), (- 3.0)]])
b_raw = torch.tensor([4.0, 5.0])
a_feature_dim = Dim(dimension=3)
reduce_dim = Dim(dimension=2)
a = Tensor(name='a', dims=[reduce_dim, a_feature_dim], dtype='float32', raw_tensor=a_raw)
b... |
def test_dot_matrix_matrix_product():
a_raw = torch.tensor([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
b_raw = torch.tensor([[1.0, (- 2.0)], [2.0, (- 4.0)]])
a_feature_dim = Dim(dimension=3)
b_feature_dim = Dim(dimension=2)
reduce_dim = Dim(dimension=2)
a = Tensor(name='a', dims=[a_feature_dim, redu... |
def test_dot_scale_matrix():
a_raw = torch.tensor([[1.0, 2.0, 3.0], [(- 1.0), (- 2.0), (- 3.0)]])
b_raw = torch.tensor(2.0)
a_feature_dim1 = Dim(dimension=2)
a_feature_dim2 = Dim(dimension=3)
a = Tensor(name='a', dims=[a_feature_dim1, a_feature_dim2], dtype='float32', raw_tensor=a_raw)
b = Ten... |
def test_dot_batched_scalar_multiplication():
a_raw = torch.tensor([1.0, 2.0, 3.0])
b_raw = torch.tensor([4.0, 5.0, 6.0])
batch_dim = Dim(dimension=3)
a = Tensor(name='a', dims=[batch_dim], dtype='float32', raw_tensor=a_raw)
b = Tensor(name='b', dims=[batch_dim], dtype='float32', raw_tensor=b_raw)... |
def test_dot_batched_scalar_product():
a_raw = torch.tensor([[1.0, 2.0, 3.0], [(- 1.0), (- 2.0), (- 3.0)]])
b_raw = torch.tensor([[4.0, 5.0, 6.0], [4.0, 5.0, 6.0]])
batch_dim = Dim(dimension=2)
feature_dim = Dim(dimension=3)
a = Tensor(name='a', dims=[batch_dim, feature_dim], dtype='float32', raw_... |
def test_dot_batched_outer_product():
a_raw = torch.tensor([[1.0, 2.0, 3.0], [(- 1.0), (- 2.0), (- 3.0)]])
b_raw = torch.tensor([[4.0, 5.0, 6.0], [4.0, 5.0, 6.0]])
batch_dim = Dim(dimension=2)
a_feature_dim = Dim(dimension=3)
b_feature_dim = Dim(dimension=3)
a = Tensor(name='a', dims=[batch_di... |
def test_dot_batched_matrix_vector_product():
a_raw = torch.tensor([[[1.0, (- 1.0)], [2.0, (- 2.0)]], [[3.0, (- 3.0)], [4.0, (- 4.0)]], [[5.0, (- 5.0)], [6.0, (- 6.0)]]])
b_raw = torch.tensor([[1.0, 2.0], [2.0, 4.0]])
batch_dim = Dim(dimension=2)
a_feature_dim = Dim(dimension=3)
reduce_dim = Dim(d... |
def test_dot_batched_matrix_matrix_product():
a_raw = torch.tensor([[[1.0, 2.0], [(- 1.0), (- 2.0)]], [[3.0, 4.0], [(- 3.0), (- 4.0)]], [[5.0, 6.0], [(- 5.0), (- 6.0)]]])
b_raw = torch.tensor([[[1.0, 1.0], [2.0, 2.0]], [[3.0, 3.0], [4.0, 4.0]], [[5.0, 5.0], [6.0, 6.0]]])
batch_dim = Dim(dimension=2)
a... |
def test_dot_batched_scale_matrix():
a_raw = torch.tensor([2.0, 3.0])
b_raw = torch.tensor([[[1.0, 2.0, 3.0], [(- 1.0), (- 2.0), (- 3.0)]], [[2.0, 3.0, 4.0], [(- 2.0), (- 3.0), (- 4.0)]]])
batch_dim = Dim(dimension=2)
b_feature_dim1 = Dim(dimension=2)
b_feature_dim2 = Dim(dimension=3)
a = Tens... |
def test_dot_multiple_dims():
a_raw = torch.rand(size=(2, 4, 6, 9, 5, 3, 8, 1))
b_raw = torch.rand(size=(7, 2, 6, 8, 3, 1, 5, 4))
reduce_dim_1 = Dim(dimension=3)
reduce_dim_2 = Dim(dimension=6)
reduce_dim_3 = Dim(dimension=1)
common_dim_1 = Dim(dimension=2)
common_dim_2 = Dim(dimension=8)
... |
def test_cross_entropy_no_batch_dim():
logits_raw = torch.tensor([0.0, 0.0, math.log(10.0), 0.0, 0.0, 0.0])
target_raw = torch.tensor(2, dtype=torch.int64)
classes_dim = Dim(dimension=6)
logits = Tensor(name='logits', dims=[classes_dim], dtype='float32', raw_tensor=logits_raw)
target = Tensor(name... |
def test_cross_entropy_no_batch_dim_dense_target():
logits_raw = torch.tensor([0.0, 0.0, math.log(10.0), 0.0, 0.0, 0.0])
target_raw = torch.tensor([0.0, 0.0, 0.5, 0.0, 0.0, 0.5])
classes_dim = Dim(dimension=6)
logits = Tensor(name='logits', dims=[classes_dim], dtype='float32', raw_tensor=logits_raw)
... |
def test_cross_entropy():
logits_raw = torch.tensor([[0.0, 0.0, math.log(3.0)], [math.log(5.0), 0.0, 0.0], [0.0, math.log(2.0), 0.0]])
target_raw = torch.tensor([2, 0, 1], dtype=torch.int64)
batch_dim = Dim(dimension=3)
classes_dim = Dim(dimension=3)
logits = Tensor(name='logits', dims=[batch_dim,... |
def test_cross_entropy_dense_target():
logits_raw = torch.tensor([[0.0, math.log(5.0)], [0.0, 0.0], [math.log(3.0), 0.0]])
target_raw = torch.tensor([[0.0, 0.4, 0.6], [0.3, 0.7, 0.0]])
batch_dim = Dim(dimension=2)
classes_dim = Dim(dimension=3)
logits = Tensor(name='logits', dims=[classes_dim, bat... |
def test_pack_padded():
def _loss_rf_packed(logits: Tensor, targets: Tensor) -> torch.Tensor:
(logits_packed, pack_dim) = rf.pack_padded(logits, dims=(batch_dim, time_dim), enforce_sorted=False)
(targets_packed, _) = rf.pack_padded(targets, dims=(batch_dim, time_dim), enforce_sorted=False, out_di... |
def test_Data_copy_compatible_to_match_priority():
feat_dim = Dim(2, name='feature')
in_dim = feat_dim.copy(match_priority=1)
assert ((in_dim == feat_dim) and (in_dim.match_priority > feat_dim.match_priority) and (in_dim is not feat_dim))
raw_np = numpy.arange(0, (2 * 2), dtype=numpy.float32).reshape(... |
def test_Data_copy_compatible_to_dims_match_priority():
feat_dim = Dim(2, name='feature')
in_dim = feat_dim.copy(match_priority=1)
assert ((in_dim == feat_dim) and (in_dim.match_priority > feat_dim.match_priority) and (in_dim is not feat_dim))
raw_np = numpy.arange(0, (2 * 2), dtype=numpy.float32).res... |
def test_Data_copy_tranpose_match_priority():
feat_dim = Dim(2, name='feature')
in_dim = feat_dim.copy(match_priority=1)
assert ((in_dim == feat_dim) and (in_dim.match_priority > feat_dim.match_priority) and (in_dim is not feat_dim))
raw_np = numpy.arange(0, (2 * 2), dtype=numpy.float32).reshape((2, 2... |
def test_compare_eq():
a_raw = torch.tensor([2.0, 2.0, 2.0])
b_raw = torch.tensor([1.0, 2.0, 3.0])
feature_dim = Dim(3)
a = Tensor(name='a', raw_tensor=a_raw, dims=[feature_dim], dtype='float32')
b = Tensor(name='b', raw_tensor=b_raw, dims=[feature_dim], dtype='float32')
result = (a == b)
... |
def test_compare_ne():
a_raw = torch.tensor([2.0, 2.0, 2.0])
b_raw = torch.tensor([1.0, 2.0, 3.0])
feature_dim = Dim(3)
a = Tensor(name='a', raw_tensor=a_raw, dims=[feature_dim], dtype='float32')
b = Tensor(name='b', raw_tensor=b_raw, dims=[feature_dim], dtype='float32')
result = (a != b)
... |
def test_compare_lt():
a_raw = torch.tensor([2.0, 2.0, 2.0])
b_raw = torch.tensor([1.0, 2.0, 3.0])
feature_dim = Dim(3)
a = Tensor(name='a', raw_tensor=a_raw, dims=[feature_dim], dtype='float32')
b = Tensor(name='b', raw_tensor=b_raw, dims=[feature_dim], dtype='float32')
result = (a < b)
r... |
def test_compare_le():
a_raw = torch.tensor([2.0, 2.0, 2.0])
b_raw = torch.tensor([1.0, 2.0, 3.0])
feature_dim = Dim(3)
a = Tensor(name='a', raw_tensor=a_raw, dims=[feature_dim], dtype='float32')
b = Tensor(name='b', raw_tensor=b_raw, dims=[feature_dim], dtype='float32')
result = (a <= b)
... |
def test_compare_gt():
a_raw = torch.tensor([2.0, 2.0, 2.0])
b_raw = torch.tensor([1.0, 2.0, 3.0])
feature_dim = Dim(3)
a = Tensor(name='a', raw_tensor=a_raw, dims=[feature_dim], dtype='float32')
b = Tensor(name='b', raw_tensor=b_raw, dims=[feature_dim], dtype='float32')
result = (a > b)
r... |
def test_compare_ge():
a_raw = torch.tensor([2.0, 2.0, 2.0])
b_raw = torch.tensor([1.0, 2.0, 3.0])
feature_dim = Dim(3)
a = Tensor(name='a', raw_tensor=a_raw, dims=[feature_dim], dtype='float32')
b = Tensor(name='b', raw_tensor=b_raw, dims=[feature_dim], dtype='float32')
result = (a >= b)
... |
def test_combine_add_int_tensors():
a_raw = torch.tensor([2, 2, 2])
b_raw = torch.tensor([1, 2, 3])
feature_dim = Dim(3)
a = Tensor(name='a', raw_tensor=a_raw, dims=[feature_dim], dtype='int64')
b = Tensor(name='b', raw_tensor=b_raw, dims=[feature_dim], dtype='int64')
result = (a + b)
resu... |
def test_combine_add_float_tensors():
a_raw = torch.tensor([2.0, 2.0, 2.0])
b_raw = torch.tensor([1.0, 2.0, 3.0])
feature_dim = Dim(3)
a = Tensor(name='a', raw_tensor=a_raw, dims=[feature_dim], dtype='float32')
b = Tensor(name='b', raw_tensor=b_raw, dims=[feature_dim], dtype='float32')
result ... |
def test_combine_add_number_to_tensor():
a_raw = torch.tensor([2.0, 2.0, 2.0])
b_raw = torch.tensor(3.0)
feature_dim = Dim(3)
a = Tensor(name='a', raw_tensor=a_raw, dims=[feature_dim], dtype='float32')
b = Tensor(name='b', raw_tensor=b_raw, dims=[], dtype='float32')
result = (a + b)
result... |
def test_combine_sub_int_tensors():
a_raw = torch.tensor([2, 2, 2])
b_raw = torch.tensor([1, 2, 3])
feature_dim = Dim(3)
a = Tensor(name='a', raw_tensor=a_raw, dims=[feature_dim], dtype='int64')
b = Tensor(name='b', raw_tensor=b_raw, dims=[feature_dim], dtype='int64')
result = (a - b)
resu... |
def test_combine_sub_float_tensors():
a_raw = torch.tensor([2.0, 2.0, 2.0])
b_raw = torch.tensor([1.0, 2.0, 3.0])
feature_dim = Dim(3)
a = Tensor(name='a', raw_tensor=a_raw, dims=[feature_dim], dtype='float32')
b = Tensor(name='b', raw_tensor=b_raw, dims=[feature_dim], dtype='float32')
result ... |
def test_combine_mul_int_tensors():
a_raw = torch.tensor([2, 2, 2])
b_raw = torch.tensor([1, 2, 3])
feature_dim = Dim(3)
a = Tensor(name='a', raw_tensor=a_raw, dims=[feature_dim], dtype='int64')
b = Tensor(name='b', raw_tensor=b_raw, dims=[feature_dim], dtype='int64')
result = (a * b)
resu... |
def test_combine_mul_float_tensors():
a_raw = torch.tensor([2.0, 2.0, 2.0])
b_raw = torch.tensor([1.0, 2.0, 3.0])
feature_dim = Dim(3)
a = Tensor(name='a', raw_tensor=a_raw, dims=[feature_dim], dtype='float32')
b = Tensor(name='b', raw_tensor=b_raw, dims=[feature_dim], dtype='float32')
result ... |
def test_combine_truediv_float_tensors():
a_raw = torch.tensor([2.0, 2.0, 2.0])
b_raw = torch.tensor([1.0, 2.0, 3.0])
feature_dim = Dim(3)
a = Tensor(name='a', raw_tensor=a_raw, dims=[feature_dim], dtype='float32')
b = Tensor(name='b', raw_tensor=b_raw, dims=[feature_dim], dtype='float32')
res... |
def test_combine_floordiv_int_tensors():
a_raw = torch.tensor([2, 2, 2])
b_raw = torch.tensor([1, 2, 3])
feature_dim = Dim(3)
a = Tensor(name='a', raw_tensor=a_raw, dims=[feature_dim], dtype='int64')
b = Tensor(name='b', raw_tensor=b_raw, dims=[feature_dim], dtype='int64')
result = (a // b)
... |
def test_combine_floordiv_float_tensors():
a_raw = torch.tensor([2.0, 2.0, 2.0])
b_raw = torch.tensor([1.0, 2.0, 3.0])
feature_dim = Dim(3)
a = Tensor(name='a', raw_tensor=a_raw, dims=[feature_dim], dtype='float32')
b = Tensor(name='b', raw_tensor=b_raw, dims=[feature_dim], dtype='float32')
re... |
def test_combine_mod_int_tensors():
a_raw = torch.tensor([2, 2, 2, 17])
b_raw = torch.tensor([1, 2, 3, 4])
feature_dim = Dim(4)
a = Tensor(name='a', raw_tensor=a_raw, dims=[feature_dim], dtype='int64')
b = Tensor(name='b', raw_tensor=b_raw, dims=[feature_dim], dtype='int64')
result = (a % b)
... |
def test_combine_mod_float_tensors():
a_raw = torch.tensor([2.0, 2.0, 2.0, 17.0])
b_raw = torch.tensor([1.0, 2.0, 3.0, 4.0])
feature_dim = Dim(4)
a = Tensor(name='a', raw_tensor=a_raw, dims=[feature_dim], dtype='float32')
b = Tensor(name='b', raw_tensor=b_raw, dims=[feature_dim], dtype='float32')
... |
def test_combine_pow_int_tensors():
a_raw = torch.tensor([2, 2, 2])
b_raw = torch.tensor([1, 2, 3])
feature_dim = Dim(3)
a = Tensor(name='a', raw_tensor=a_raw, dims=[feature_dim], dtype='int64')
b = Tensor(name='b', raw_tensor=b_raw, dims=[feature_dim], dtype='int64')
result = (a ** b)
res... |
def test_combine_pow_float_tensors():
a_raw = torch.tensor([2.0, 2.0, 2.0])
b_raw = torch.tensor([1.0, 2.0, 3.0])
feature_dim = Dim(3)
a = Tensor(name='a', raw_tensor=a_raw, dims=[feature_dim], dtype='float32')
b = Tensor(name='b', raw_tensor=b_raw, dims=[feature_dim], dtype='float32')
result ... |
def test_combine_max():
a_raw = torch.tensor([2.0, 2.0, 2.0])
b_raw = torch.tensor([1.0, 2.0, 3.0])
feature_dim = Dim(3)
a = Tensor(name='a', raw_tensor=a_raw, dims=[feature_dim], dtype='float32')
b = Tensor(name='b', raw_tensor=b_raw, dims=[feature_dim], dtype='float32')
result = rf.combine(a... |
def test_combine_min():
a_raw = torch.tensor([2.0, 2.0, 2.0])
b_raw = torch.tensor([1.0, 2.0, 3.0])
feature_dim = Dim(3)
a = Tensor(name='a', raw_tensor=a_raw, dims=[feature_dim], dtype='float32')
b = Tensor(name='b', raw_tensor=b_raw, dims=[feature_dim], dtype='float32')
result = rf.combine(a... |
class _CheckNoPythonCalls():
'\n Check that there is no Python code executed via sys.settrace.\n '
def __init__(self):
self.num_calls = 0
self.old_tracefunc = None
def _tracefunc(self, frame, event, arg):
print('*** trace:', frame, event, arg)
if (frame.f_globals is... |
def test_native_is_raw_torch_tensor_type():
raw_tensor = torch.zeros(2, 3)
raw_parameter = torch.nn.Parameter(torch.zeros(2, 3))
numpy_tensor = numpy.zeros((2, 3))
from returnn.frontend import _native
mod = _native.get_module()
with _CheckNoPythonCalls():
assert (mod.is_raw_torch_tenso... |
def test_native_get_out_permutation_to_dims():
batch_dim = Dim(2, name='batch_dim')
time_dim = Dim(3, name='time_dim')
feature_dim = Dim(5, name='feature_dim')
tensor_f = Tensor(name='x', dims=[feature_dim], dtype='float32')
tensor_bf = Tensor(name='x', dims=[batch_dim, feature_dim], dtype='float3... |
def test_torch_native_setup():
tensor = Tensor(name='x', raw_tensor=torch.tensor([1.0, 2.0, 3.0]), dims=[Dim(3)], dtype='float32')
from returnn.frontend._backend import global_backend
from returnn.torch.frontend import TorchBackend
assert isinstance(global_backend, TorchBackend)
assert global_back... |
def test_native_torch_raw_backend():
tensor = Tensor(name='a', raw_tensor=torch.tensor([1.0, 2.0, 3.0]), dims=[Dim(3)], dtype='float32')
backend1 = tensor._raw_backend
import returnn.frontend._backend as _backend_api
backend2 = _backend_api.get_backend_by_raw_tensor_type(type(tensor.raw_tensor))
f... |
def test_native_torch_raw_backend_raw_dtype():
raw = torch.tensor([1.0, 2.0, 3.0], dtype=torch.float32)
from returnn.frontend import _native
mod = _native.get_module()
with _CheckNoPythonCalls():
dtype = mod.raw_torch_tensor_get_dtype(raw)
assert (isinstance(dtype, str) and (dtype == 'floa... |
def test_native_torch_tensor_eq():
batch_dim = Dim(2, name='batch_dim')
feature_dim = Dim(3, name='feature_dim')
tensor_bf = Tensor('tensor', dims=[batch_dim, feature_dim], dtype='float32', raw_tensor=torch.zeros(2, 3))
tensor_f = Tensor('tensor', dims=[feature_dim], dtype='float32', raw_tensor=torch.... |
def test_native_torch_tensor_eq_op():
batch_dim = Dim(2, name='batch_dim')
feature_dim = Dim(3, name='feature_dim')
tensor_bf = Tensor('tensor', dims=[batch_dim, feature_dim], dtype='float32', raw_tensor=torch.zeros(2, 3))
tensor_f = Tensor('tensor', dims=[feature_dim], dtype='float32', raw_tensor=tor... |
def test_native_torch_tensor_neg():
batch_dim = Dim(2, name='batch_dim')
feature_dim = Dim(3, name='feature_dim')
tensor = Tensor('tensor', dims=[batch_dim, feature_dim], dtype='float32', raw_tensor=torch.ones(2, 3))
from returnn.frontend import _native
mod = _native.get_module()
with _CheckNo... |
def test_native_torch_tensor_sub():
batch_dim = Dim(2, name='batch_dim')
feature_dim = Dim(3, name='feature_dim')
tensor_bf = Tensor('tensor', dims=[batch_dim, feature_dim], dtype='float32', raw_tensor=torch.ones(2, 3))
tensor_f = Tensor('tensor', dims=[feature_dim], dtype='float32', raw_tensor=torch.... |
def test_native_torch_tensor_sub_permute_more_dims():
batch_dim = Dim(2, name='batch_dim')
time_dim = Dim(3, name='time_dim')
feature_dim = Dim(5, name='feature_dim')
tensor_bft = Tensor('tensor', dims=[batch_dim, feature_dim, time_dim], dtype='int32', raw_tensor=torch.arange(1, (1 + ((2 * 3) * 5)), d... |
def analyze_dataset(options):
'\n :param options: argparse.Namespace\n '
print(('Epoch: %i' % options.epoch), file=log.v3)
print('Dataset keys:', dataset.get_data_keys(), file=log.v3)
print('Dataset target keys:', dataset.get_target_list(), file=log.v3)
assert (options.key in dataset.get_dat... |
def init(config_str, config_dataset, use_pretrain, epoch, verbosity):
'\n :param str config_str: either filename to config-file, or dict for dataset\n :param str|None config_dataset:\n :param bool use_pretrain: might overwrite config options, or even the dataset\n :param int epoch:\n :param int ver... |
def main():
'\n Main entry.\n '
arg_parser = argparse.ArgumentParser(description='Anaylize dataset batches.')
arg_parser.add_argument('returnn_config', help='either filename to config-file, or dict for dataset')
arg_parser.add_argument('--dataset', help="if given the config, specifies the datase... |
class BlissItem():
'\n Represents one entry in the Bliss XML.\n '
def __init__(self, segment_name, recording_filename, start_time, end_time, orth):
'\n :param str segment_name:\n :param str recording_filename:\n :param float start_time:\n :param float end_time:\n ... |
def iter_bliss(filename):
'\n :param str filename:\n :return: yields BlissItem\n :rtype: list[BlissItem]\n '
corpus_file = open(filename, 'rb')
if filename.endswith('.gz'):
corpus_file = gzip.GzipFile(fileobj=corpus_file)
context = iter(ElementTree.iterparse(corpus_file, events=('s... |
def main():
'\n Main entry.\n '
arg_parser = ArgumentParser()
arg_parser.add_argument('bliss_filename', nargs='+')
arg_parser.add_argument('--output', default='/dev/stdout')
args = arg_parser.parse_args()
if args.output.endswith('.gz'):
out = gzip.GzipFile(args.output, mode='wb')... |
def main():
'\n Main entry.\n '
parser = ArgumentParser(description='dump orth from Bliss XML file as-is')
parser.add_argument('xml')
args = parser.parse_args()
corpus_filename = args.xml
def callback(orth):
'\n :param str orth:\n '
print(orth)
_iter_bl... |
class BlissItem():
'\n Bliss item.\n '
def __init__(self, segment_name, recording_filename, start_time, end_time, orth):
'\n :param str segment_name:\n :param str recording_filename:\n :param float start_time:\n :param float end_time:\n :param str orth:\n ... |
def iter_bliss(filename):
'\n :param str filename:\n :return: yields BlissItem\n :rtype: list[BlissItem]\n '
corpus_file = open(filename, 'rb')
if filename.endswith('.gz'):
corpus_file = gzip.GzipFile(fileobj=corpus_file)
context = iter(ElementTree.iterparse(corpus_file, events=('s... |
def main():
'\n Main entry.\n '
arg_parser = ArgumentParser()
arg_parser.add_argument('bliss_filename')
arg_parser.add_argument('--subset_segment_file')
arg_parser.add_argument('--output_type', default='', help='e.g. segment_name')
arg_parser.add_argument('--merge_swb_ab', action='store_... |
class BlissItem():
'\n Bliss item.\n '
def __init__(self, segment_name, recording_filename, start_time, end_time, orth, speaker_name=None):
'\n :param str segment_name:\n :param str recording_filename:\n :param Decimal start_time:\n :param Decimal end_time:\n ... |
def iter_bliss(filename):
'\n :param str filename:\n :return: yields BlissItem\n :rtype: list[BlissItem]\n '
corpus_file = open(filename, 'rb')
if filename.endswith('.gz'):
corpus_file = gzip.GzipFile(fileobj=corpus_file)
parser = ElementTree.XMLParser(target=ElementTree.TreeBuilde... |
class SprintCacheHandler():
'\n This is just to apply the same silence trimming on the raw audio samples\n which was applied on the features in the Sprint cache.\n We can reconstruct this information because the Sprint cache also has the exact timing information.\n '
def __init__(self, opt, bliss... |
def longest_common_prefix(strings):
'\n :param list[str]|set[str] strings:\n :rtype: str\n '
if (not strings):
return ''
min_s = min(strings)
max_s = max(strings)
if (not min_s):
return ''
for i in range(len(min_s)):
if (max_s[i] != min_s[i]):
retur... |
def longest_common_postfix(strings):
'\n :param list[str]|set[str] strings:\n :rtype: str\n '
strings = [''.join(reversed(s)) for s in strings]
res = longest_common_prefix(strings)
return ''.join(reversed(res))
|
def hms(s):
'\n :param float|int s: seconds\n :return: e.g. "1:23:45" (hs:ms:secs). see hms_fraction if you want to get fractional seconds\n :rtype: str\n '
(m, s) = divmod(s, 60)
(h, m) = divmod(m, 60)
return ('%d:%02d:%02d' % (h, m, s))
|
def main():
'\n Main entry.\n '
arg_parser = ArgumentParser()
arg_parser.add_argument('bliss_filename')
arg_parser.add_argument('--subset_segment_file')
arg_parser.add_argument('--no_ogg', help='skip generating ogg files', action='store_true')
arg_parser.add_argument('--no_conversion', h... |
def parse_vocab(filename):
'\n Can be either pure text file, line-based, or lexicon XML file, or Python vocab dict.\n\n :param str filename:\n :rtype: list[str]\n '
if filename.endswith('.gz'):
import gzip
raw = gzip.open(filename, 'r').read().decode('utf8')
else:
raw =... |
def xml_prettify(element, indent=' '):
'\n https://stackoverflow.com/a/38574067/133374 (deleted StackOverflow answer)\n\n :param ElementTree.Element element:\n :param str indent:\n '
queue = [(0, element)]
while queue:
(level, element) = queue.pop(0)
children = [((level + 1), ... |
def main():
'\n Main entry.\n '
arg_parser = ArgumentParser()
arg_parser.add_argument('--bpe_vocab', required=True)
arg_parser.add_argument('--word_vocab', required=True)
arg_parser.add_argument('--unk')
arg_parser.add_argument('--skip_special', action='store_true')
arg_parser.add_ar... |
class WerComputeGraph():
'\n Creates TF computation graph to calculate the WER.\n We accumulate the absolute number of edits and normalize by the accumulated seq lens.\n '
def __init__(self):
self.hyps = tf_compat.v1.placeholder(tf.string, [None])
self.refs = tf_compat.v1.placeholder... |
def calc_wer_on_dataset(dataset, refs, options, hyps):
'\n :param Dataset|None dataset:\n :param dict[str,str]|None refs: seq tag -> ref string (words delimited by space)\n :param options: argparse.Namespace\n :param dict[str,str] hyps: seq tag -> hyp string (words delimited by space)\n :return: WE... |
def init(config_filename, log_verbosity):
'\n :param str config_filename: filename to config-file\n :param int log_verbosity:\n '
rnn.init_better_exchook()
rnn.init_thread_join_hack()
if config_filename:
print(('Using config file %r.' % config_filename))
assert os.path.exists(... |
def load_hyps_refs(filename):
'\n :param str filename:\n :return: dict of seq_tag -> ref\n :rtype: dict[str,str]\n '
if filename.endswith('.gz'):
import gzip
content_str = gzip.open(filename, 'rt').read()
else:
content_str = open(filename).read()
content = eval(cont... |
def main(argv):
'\n Main entry.\n '
arg_parser = argparse.ArgumentParser(description='Dump something from dataset.')
arg_parser.add_argument('--config', help="filename to config-file. will use dataset 'eval' from it")
arg_parser.add_argument('--dataset', help='dataset, overwriting config')
a... |
def main():
'\n Main entry.\n '
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('--config')
arg_parser.add_argument('--cwd', help='will change to this dir')
arg_parser.add_argument('--model', help='model filenames (default: take from config)')
arg_parser.add_argument('--sc... |
def found_sub_seq(sub_seq, seq):
'\n :param list[str] sub_seq:\n :param list[str] seq:\n :rtype: bool\n '
for i in range(len(seq)):
if (seq[i:(i + len(sub_seq))] == sub_seq):
return True
return False
|
def iter_dataset(dataset, options, callback):
'\n :type dataset: Dataset.Dataset\n '
dataset.init_seq_order(epoch=1)
assert ('orth' in dataset.get_target_list())
seq_idx = 0
while dataset.is_less_than_num_seqs(seq_idx):
dataset.load_seqs(seq_idx, seq_idx)
frame_len = dataset.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.