code
stringlengths
17
6.64M
def run(args, input=None): 'run subproc' args = list(args) print('run:', args) p = Popen(args, stdout=PIPE, stderr=STDOUT, stdin=PIPE, env=build_env()) (out, _) = p.communicate(input=input) print(('Return code is %i' % p.returncode)) print(('std out/err:\n---\n%s\n---\n' % out.decode('utf8...
def filter_out(ls): '\n :param list[str] ls:\n :rtype: list[str]\n ' if (not isinstance(ls, list)): ls = list(ls) res = [] i = 0 while (i < len(ls)): s = ls[i] if (('tensorflow/core/' in s) or ('tensorflow/stream_executor/' in s)): i += 1 co...
def count_start_with(ls, s): '\n :param list[str] ls:\n :param str s:\n :rtype: int\n ' c = 0 for l in ls: if l.startswith(s): c += 1 return c
def test_filter_out(): s = '\n/home/travis/virtualenv/python2.7.14/lib/python2.7/site-packages/scipy/special/__init__.py:640: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88\n from ._ufuncs import *\n/home/travis/virtualenv/python2.7.14/lib/python2.7/site-packag...
def test_returnn_startup(): out = run([py, __main_entry__, '-x', 'nop', '++use_tensorflow', '1']) ls = out.splitlines() ls = filter_out(ls) if (not (3 <= len(ls) <= 10)): print(('output:\n%s\n\nNum lines: %i' % ('\n'.join(ls), len(ls)))) raise Exception('unexpected output number of lin...
def test_returnn_startup_verbose(): out = run([py, __main_entry__, '-x', 'nop', '++use_tensorflow', '1', '++log_verbosity', '5']) ls = out.splitlines() ls = filter_out(ls) if (not (3 <= len(ls) <= 15)): print(('output:\n%s\n\nNum lines: %i' % ('\n'.join(ls), len(ls)))) raise Exception(...
def test_simple_log(): code = '\nfrom __future__ import annotations\nprint("hello stdout 1")\nfrom returnn.log import log\nlog.initialize(verbosity=[], logs=[], formatter=[])\nprint("hello stdout 2")\nprint("hello log 1", file=log.v3)\nprint("hello log 2", file=log.v3)\n ' out = run([py], input=code.encode('...
def test_StreamIO(): import io buf = io.StringIO() assert_equal(buf.getvalue(), '') print(('buf: %r' % buf.getvalue())) buf.write('hello') print(('buf: %r' % buf.getvalue())) assert_equal(buf.getvalue(), 'hello') buf.truncate(0) print(('buf: %r' % buf.getvalue())) assert_equal(...
def _sig_alarm_handler(signum, frame): raise Exception(f'Alarm (timeout) signal handler')
@contextlib.contextmanager def timeout(seconds=10): '\n :param seconds: when the context is not closed within this time, an exception will be raised\n ' signal.alarm(seconds) try: (yield) finally: signal.alarm(0)
def test_MultiProcDataset_n1_b1_default(): hdf_fn = generate_hdf_from_other({'class': 'Task12AXDataset', 'num_seqs': 23}) hdf_dataset_dict = {'class': 'HDFDataset', 'files': [hdf_fn]} hdf_dataset = init_dataset(hdf_dataset_dict) hdf_dataset_seqs = dummy_iter_dataset(hdf_dataset) with timeout(): ...
def test_MultiProcDataset_n3_b5_shuffle(): hdf_fn = generate_hdf_from_other({'class': 'Task12AXDataset', 'num_seqs': 23}) hdf_dataset_dict = {'class': 'HDFDataset', 'files': [hdf_fn], 'seq_ordering': 'random'} hdf_dataset = init_dataset(hdf_dataset_dict) hdf_dataset_seqs = dummy_iter_dataset(hdf_datas...
def test_MultiProcDataset_meta(): hdf_fn = generate_hdf_from_other({'class': 'Task12AXDataset', 'num_seqs': 23}) meta_dataset_dict = {'class': 'MetaDataset', 'data_map': {'classes': ('hdf', 'classes'), 'data': ('hdf', 'data')}, 'datasets': {'hdf': {'class': 'HDFDataset', 'files': [hdf_fn]}}} meta_dataset ...
def test_MultiProcDataset_via_config(): from io import StringIO import textwrap from returnn.config import Config, global_config_ctx config = Config() config.load_file(StringIO(textwrap.dedent(' #!returnn.py\n\n import numpy\n from returnn.datasets.map ...
class _MyCustomMapDatasetException(Exception): pass
class _MyCustomMapDatasetThrowingExceptionAtInit(MapDatasetBase): def __init__(self): super().__init__() raise _MyCustomMapDatasetException('test exception at init')
class _MyCustomMapDatasetThrowingExceptionAtItem(MapDatasetBase): def __init__(self): super().__init__(data_types={'data': {'shape': (None, 3)}}) def __len__(self): return 2 def __getitem__(self, item): if (item == 0): return {'data': numpy.zeros((5, 3))} rai...
def test_MultiProcDataset_exception_at_init(): with timeout(): mp_dataset = MultiProcDataset(dataset={'class': 'MapDatasetWrapper', 'map_dataset': _MyCustomMapDatasetThrowingExceptionAtInit}, num_workers=1, buffer_size=1) try: mp_dataset.initialize() except Exception as exc: ...
def test_MultiProcDataset_exception_at_item(): with timeout(): mp_dataset = MultiProcDataset(dataset={'class': 'MapDatasetWrapper', 'map_dataset': _MyCustomMapDatasetThrowingExceptionAtItem}, num_workers=1, buffer_size=1) mp_dataset.initialize() try: dummy_iter_dataset(mp_datas...
class _MyCustomDummyMapDataset(MapDatasetBase): def __init__(self): super().__init__(data_types={'data': {'shape': (None, 3)}}) def __len__(self): return 2 def __getitem__(self, item): return {'data': numpy.zeros((((item * 2) + 5), 3))}
def test_MultiProcDataset_pickle(): import pickle with timeout(): mp_dataset = MultiProcDataset(dataset={'class': 'MapDatasetWrapper', 'map_dataset': _MyCustomDummyMapDataset}, num_workers=1, buffer_size=1) mp_dataset.initialize() mp_dataset_seqs = dummy_iter_dataset(mp_dataset) ...
def test_config_net_dict1(): config = Config() config.update(config_dict) config.typed_dict['network'] = net_dict pretrain = pretrain_from_config(config) assert_equal(pretrain.get_train_num_epochs(), 2) net1_json = pretrain.get_network_json_for_epoch(1) net2_json = pretrain.get_network_jso...
def test_config_net_dict2(): config = Config() config.update(config_dict) config.typed_dict['network'] = net_dict2 pretrain = pretrain_from_config(config) assert_equal(pretrain.get_train_num_epochs(), 3)
@contextlib.contextmanager def make_scope(): with tf.Graph().as_default() as graph: with tf_compat.v1.Session(graph=graph) as session: (yield session)
def build_resnet(conv_time_dim): dropout = 0 L2 = 0.1 filter_size = (3, 3) context_window = 1 window = 1 feature_dim = 64 channel_num = 3 num_inputs = ((feature_dim * channel_num) * window) num_outputs = 9001 EpochSplit = 6 cur_feat_dim = feature_dim global _last, netwo...
def test_ResNet(): 'Test to compare Resnet convolving (window x frequency) vs (time x frequency).\n Batch_norm layers are turned off in oder to compare, since the statistics over the\n windowed input data is a bit different from the plain input (when convolving directing\n over the time dim).\n ' ...
def generate_batch(seq_idx, dataset): batch = Batch() batch.add_frames(seq_idx=seq_idx, seq_start_frame=0, length=dataset.get_seq_length(seq_idx)) return batch
def test_read_all(): config = Config() config.update(dummyconfig_dict) print('Create ExternSprintDataset') python_exec = util.which('python') if (python_exec is None): raise unittest.SkipTest('python not found') num_seqs = 4 dataset = ExternSprintDataset([python_exec, sprintExecPat...
def test_assign_dev_data(): config = Config() config.update(dummyconfig_dict) print('Create ExternSprintDataset') dataset = ExternSprintDataset([sys.executable, sprintExecPath], '--*.feature-dimension=2 --*.trainer-output-dimension=3 --*.crnn-dataset=DummyDataset(2,3,num_seqs=4,seq_len=10)') datas...
def test_window(): input_dim = 2 output_dim = 3 num_seqs = 2 seq_len = 5 window = 3 dataset_kwargs = dict(sprintTrainerExecPath=[sys.executable, sprintExecPath], sprintConfigStr=' '.join([('--*.feature-dimension=%i' % input_dim), ('--*.trainer-output-dimension=%i' % output_dim), ('--*.crnn-dat...
def install_sigint_handler(): import signal def signal_handler(signal, frame): print('\nSIGINT at:') better_exchook.print_tb(tb=frame, file=sys.stdout) print('') if (getattr(sys, 'exited_frame', None) is not None): print('interrupt_main via:') better_ex...
def test_forward(): tmpdir = mkdtemp('returnn-test-sprint') olddir = os.getcwd() os.chdir(tmpdir) from returnn.datasets.generating import DummyDataset seq_len = 5 n_data_dim = 2 n_classes_dim = 3 train_data = DummyDataset(input_dim=n_data_dim, output_dim=n_classes_dim, num_seqs=4, seq_...
@contextlib.contextmanager def make_scope(): with tf.Graph().as_default() as graph: with tf_compat.v1.Session(graph=graph) as session: (yield session)
class DummyLoss(Loss): need_target = False def get_value(self): assert (self.layer and isinstance(self.layer, DummyLayer)) return self.layer._get_loss_value() def get_error(self): return None
class DummyLayer(LayerBase): def __init__(self, initial_value=0.0, loss_value_factor=1.0, **kwargs): super(DummyLayer, self).__init__(**kwargs) self.loss_value_factor = loss_value_factor self.x = self.add_param(tf.Variable(initial_value)) self.output.placeholder = self.x def ...
def test_Updater_GradientDescent(): with make_scope() as session: from returnn.tf.network import TFNetwork, ExternData from returnn.config import Config config = Config() network = TFNetwork(extern_data=ExternData(), train_flag=True) network.add_layer(name='output', layer_c...
def test_Updater_CustomUpdate(): with make_scope() as session: from returnn.tf.network import TFNetwork, ExternData from returnn.config import Config from returnn.tf.util.basic import CustomUpdate config = Config() network = TFNetwork(extern_data=ExternData(), train_flag=Tr...
def test_add_check_numerics_ops(): with make_scope() as session: x = tf.constant(3.0, name='x') y = tf_compat.v1.log((x * 3), name='y') assert isinstance(y, tf.Tensor) assert_almost_equal(session.run(y), numpy.log(9.0)) check = add_check_numerics_ops([y]) session.ru...
def test_grad_add_check_numerics_ops(): with make_scope() as session: x = tf.Variable(initial_value=0.0, name='x') session.run(x.initializer) y = (1.0 / x) grad_x = tf.gradients(y, x)[0] print('grad_x:', grad_x.eval()) assert_equal(str(float('-inf')), '-inf') ...
def test_Updater_add_check_numerics_ops(): class _Layer(DummyLayer): def _get_loss_value(self): return tf_compat.v1.log(self.x) from returnn.tf.network import TFNetwork, ExternData from returnn.config import Config with make_scope() as session: config = Config() c...
def test_Updater_simple_batch(): with make_scope() as session: from returnn.tf.network import TFNetwork, ExternData from returnn.config import Config from returnn.datasets.generating import Task12AXDataset dataset = Task12AXDataset() dataset.init_seq_order(epoch=1) ...
def test_Updater_decouple_constraints(): with make_scope() as session: from returnn.tf.network import TFNetwork, ExternData from returnn.config import Config from returnn.datasets.generating import Task12AXDataset dataset = Task12AXDataset() dataset.init_seq_order(epoch=1) ...
def test_Updater_decouple_constraints_simple_graph(): with make_scope() as session: from returnn.tf.network import TFNetwork, ExternData from returnn.config import Config config = Config({'decouple_constraints': True, 'decouple_constraints_factor': 1.0}) extern_data = ExternData({'...
def test_Updater_decouple_constraints_simple_graph_grad_accum(): with make_scope() as session: from returnn.tf.network import TFNetwork, ExternData from returnn.config import Config config = Config({'decouple_constraints': True, 'decouple_constraints_factor': 1.0, 'accum_grad_multiple_step...
def test_Updater_multiple_optimizers(): with make_scope() as session: from returnn.tf.network import TFNetwork, ExternData from returnn.config import Config from returnn.datasets.generating import Task12AXDataset dataset = Task12AXDataset() dataset.init_seq_order(epoch=1) ...
def test_Updater_multiple_optimizers_and_opts(): with make_scope() as session: from returnn.tf.network import TFNetwork, ExternData from returnn.config import Config from returnn.datasets.generating import Task12AXDataset dataset = Task12AXDataset() dataset.init_seq_order(e...
def load_data(): from returnn.__main__ import load_data (dev_data, _) = load_data(config, 0, 'dev', chunking=config.value('chunking', ''), seq_ordering='sorted', shuffle_frames_of_nseqs=0) (eval_data, _) = load_data(config, 0, 'eval', chunking=config.value('chunking', ''), seq_ordering='sorted', shuffle_f...
def test_determinism_of_vanillalstm(): def create_engine(): (dev_data, eval_data, train_data) = load_data() engine = Engine() engine.init_train_from_config(config, train_data, dev_data, eval_data) engine.init_train_epoch() engine.train_batches = engine.train_data.generate_...
def pickle_dumps(obj): sio = BytesIO() p = Pickler(sio) p.dump(obj) return sio.getvalue()
def pickle_loads(s): p = Unpickler(BytesIO(s)) return p.load()
def test_pickle_anon_new_class(): class Foo(object): a = 'class' b = 'foo' def __init__(self): self.a = 'hello' def f(self, a): return a s = pickle_dumps(Foo) Foo2 = pickle_loads(s) assert inspect.isclass(Foo2) assert (Foo is not Foo2) ...
def test_pickle_anon_old_class(): class Foo(): a = 'class' b = 'foo' def __init__(self): self.a = 'hello' def f(self, a): return a s = pickle_dumps(Foo) Foo2 = pickle_loads(s) assert inspect.isclass(Foo2) assert (Foo is not Foo2) asser...
def test_pickle_inst_anon_class(): class Foo(object): a = 'class' b = 'foo' def __init__(self): self.a = 'hello' def f(self, a): return a s = pickle_dumps(Foo()) inst = pickle_loads(s) assert (inst.a == 'hello') assert (inst.b == 'foo') ...
class DemoClass(): def method(self): return 42
def test_pickle(): obj = DemoClass() s = pickle_dumps(obj.method) inst = pickle_loads(s) assert_equal(inst(), 42)
def pickle_dumps(obj): sio = BytesIO() p = Pickler(sio) p.dump(obj) return sio.getvalue()
def pickle_loads(s): p = Unpickler(BytesIO(s)) return p.load()
def find_numpy_shared_by_shmid(shmid): for sh in SharedNumpyArray.ServerInstances: assert isinstance(sh, SharedNumpyArray) assert (sh.mem is not None) assert (sh.mem.shmid > 0) if (sh.mem.shmid == shmid): return sh return None
def have_working_shmget(): global _have_working_shmget if (_have_working_shmget is None): _have_working_shmget = SharedMem.is_shmget_functioning() print('shmget functioning:', _have_working_shmget) return _have_working_shmget
@unittest.skipIf((not have_working_shmget()), 'shmget does not work') def test_shmget_functioning(): assert SharedMem.is_shmget_functioning()
@unittest.skipIf((not have_working_shmget()), 'shmget does not work') def test_pickle_numpy(): m = numpy.random.randn(10, 10) p = pickle_dumps(m) m2 = pickle_loads(p) assert isinstance(m2, numpy.ndarray) assert numpy.allclose(m, m2) assert isinstance(m2.base, SharedNumpyArray) shared_clien...
@unittest.skipIf((not have_working_shmget()), 'shmget does not work') def test_pickle_numpy_scalar(): m = numpy.array([numpy.random.randn()]) assert isinstance(m, numpy.ndarray) assert (m.shape == (1,)) assert (m.nbytes >= 1) p = pickle_dumps(m) m2 = pickle_loads(p) assert isinstance(m2, n...
@unittest.skipIf((not have_working_shmget()), 'shmget does not work') def test_pickle_gc_aggressive(): m = numpy.random.randn(10, 10) p = pickle_dumps(m) m2 = pickle_loads(p) assert isinstance(m2, numpy.ndarray) assert numpy.allclose(m, m2) assert isinstance(m2.base, SharedNumpyArray) prin...
@unittest.skipIf((not have_working_shmget()), 'shmget does not work') def test_pickle_multiple(): for i in range(20): ms = [numpy.random.randn(10, 10) for i in range(((i % 3) + 1))] p = pickle_dumps(ms) ms2 = pickle_loads(p) assert (len(ms) == len(ms2)) for (m, m2) in zip(m...
@unittest.skipIf((not have_working_shmget()), 'shmget does not work') def test_pickle_unpickle_auto_unused(): old_num_servers = None for i in range(10): m = numpy.random.randn(((i * 2) + 1), ((i * 3) + 2)) p = pickle_dumps((m, m, m)) new_num_servers = len(SharedNumpyArray.ServerInstanc...
def create_vocabulary(text): '\n :param str text: any natural text\n :return: mapping of words in the text to ids, as well as the inverse mapping\n :rtype: (dict[str, int], dict[int, str])\n ' vocabulary = {word: index for (index, word) in enumerate(set(text.strip().split()))} inverse_vocabula...
def word_ids_to_sentence(word_ids, vocabulary): '\n :param list[int] word_ids:\n :param dict[int, str] vocabulary: mapping from word ids to words\n :return: concatenation of all words\n :rtype: str\n ' words = [vocabulary[word_id] for word_id in word_ids] return ' '.join(words)
def test_translation_dataset(): '\n Checks whether a dummy translation dataset can be read and whether the returned word indices are correct.\n We create the necessary corpus and vocabulary files on the fly.\n ' dummy_dataset = tempfile.mkdtemp() source_file_name = os.path.join(dummy_dataset, 'so...
def test_translation_factors_dataset(): '\n Similar to test_translation_dataset(), but using translation factors.\n ' source_text_per_factor = [dummy_source_text_factor_0, dummy_source_text_factor_1] target_text_per_factor = [dummy_target_text_factor_0, dummy_target_text_factor_1, dummy_target_text_...
def build_env(env_update=None): '\n :param dict[str,str]|None env_update:\n :return: env dict for Popen\n :rtype: dict[str,str]\n ' env_update_ = os.environ.copy() if env_update: env_update_.update(env_update) return env_update_
def run(*args, env_update=None, print_stdout=False): args = list(args) print('run:', args) p = Popen(args, stdout=PIPE, stderr=STDOUT, env=build_env(env_update=env_update)) (out, _) = p.communicate() out = out.decode('utf8') if (p.returncode != 0): print(('Return code is %i' % p.return...
def parse_last_fer(out: str) -> float: '\n :param out:\n :return: FER\n ' parsed_fer = None for line in out.splitlines(): m = re.match('epoch [0-9]+ score: .* dev: .* error ([0-9.]+)\\s?', line) if (not m): m = re.match('dev: score .* error ([0-9.]+)\\s?', line) ...
def run_and_parse_last_fer(*args, **kwargs): out = run(*args, **kwargs) return parse_last_fer(out)
def run_config_get_fer(config_filename, *args, env_update=None, log_verbosity=5, print_stdout=False, pre_cleanup=True, post_cleanup=True): if pre_cleanup: cleanup_tmp_models(config_filename) fer = run_and_parse_last_fer(py, 'rnn.py', config_filename, '++log_verbosity', str(log_verbosity), *args, env_u...
def get_model_filename(config_filename: str) -> str: assert os.path.exists(config_filename) from returnn.config import Config config = Config() config.load_file(config_filename) model_filename = config.value('model', '') assert model_filename assert model_filename.startswith('/tmp/') r...
def cleanup_tmp_models(config_filename: str): model_filename = get_model_filename(config_filename) for f in glob((model_filename + '.*')): os.remove(f)
@unittest.skipIf((not tf), 'no TF') def test_demo_tf_task12ax(): fer = run_config_get_fer('demos/demo-tf-native-lstm.12ax.config', print_stdout=True) assert_less(fer, 0.015)
@unittest.skipIf((not tf), 'no TF') def test_demo_tf_task12ax_eval(): cfg_filename = 'demos/demo-tf-native-lstm.12ax.config' train_dataset_repr = '{"class": "Task12AXDataset", "num_seqs": 10}' dev_dataset_repr = '{"class": "Task12AXDataset", "num_seqs": 10}' fer1 = run_config_get_fer(cfg_filename, '++...
@unittest.skipIf((not torch), 'no PyTorch') def test_demo_torch_task12ax(): cleanup_tmp_models('demos/demo-torch.config') out = run(py, 'rnn.py', 'demos/demo-torch.config', print_stdout=True) fer = parse_last_fer(out) assert_less(fer, 0.02)
def _test_torch_export_to_onnx(cfg_filename: str) -> str: '\n Executes the demo passed as a parameter and returns the ONNX exported model as a filename.\n\n :param cfg_filename: Demo filename, either "demos/demo-rf.config" or "demos/demo-torch.config".\n :return: Filename representing the ONNX model loca...
def _test_torch_onnx_inference_no_seq_lens(out_onnx_model: str): '\n Tests the inference of the torch demo with an ONNX model passed as parameter.\n ' import onnxruntime as ort torch.manual_seed(42) dummy_data = torch.randn([3, 50, 9]) session = ort.InferenceSession(out_onnx_model) outpu...
def _test_torch_onnx_inference_seq_lens_in_out(out_onnx_model: str): '\n Tests the inference of the torch demo with an ONNX model passed as parameter.\n ' print(out_onnx_model) import onnxruntime as ort torch.manual_seed(42) dummy_data = torch.randn([3, 50, 9]) dummy_seq_lens = torch.ten...
@unittest.skipIf((not torch), 'no PyTorch') def test_demo_torch_export_to_onnx(): out_onnx_model = _test_torch_export_to_onnx('demos/demo-torch.config') _test_torch_onnx_inference_seq_lens_in_out(out_onnx_model)
@unittest.skipIf((not torch), 'no PyTorch') def test_demo_rf_export_to_onnx(): out_onnx_model = _test_torch_export_to_onnx('demos/demo-rf.config') _test_torch_onnx_inference_seq_lens_in_out(out_onnx_model)
@unittest.skipIf((not torch), 'no PyTorch') def test_demo_rf_torch_task12ax(): cleanup_tmp_models('demos/demo-rf.config') out = run(py, 'rnn.py', 'demos/demo-rf.config', print_stdout=True) fer = parse_last_fer(out) assert_less(fer, 0.02)
@unittest.skipIf((not tf), 'no TF') def test_demo_rf_tf_task12ax(): cleanup_tmp_models('demos/demo-rf.config') out = run(py, 'rnn.py', 'demos/demo-rf.config', '++backend', 'tensorflow-net-dict', print_stdout=True) fer = parse_last_fer(out) assert_less(fer, 0.02)
def test_demo_iter_dataset_task12ax(): cleanup_tmp_models('demos/demo-tf-vanilla-lstm.12ax.config') out = run(py, 'demos/demo-iter-dataset.py', 'demos/demo-tf-vanilla-lstm.12ax.config') assert_in('Epoch 5.', out.splitlines())
@unittest.skipIf((not tf), 'no TF') def test_demo_returnn_as_framework(): print('Prepare.') import subprocess import shutil from glob import glob from returnn.util.basic import get_login_username subprocess.check_call(['echo', 'travis_fold:start:test_demo_returnn_as_framework']) assert os....
@unittest.skipIf((not tf), 'no TF') def test_demo_sprint_interface(): import subprocess subprocess.check_call(['echo', 'travis_fold:start:test_demo_sprint_interface']) subprocess.check_call([py, os.path.abspath('demos/demo-sprint-interface.py')], cwd='/') subprocess.check_call(['echo', 'travis_fold:en...
def test_returnn_as_framework_TaskSystem(): import subprocess subprocess.check_call(['echo', 'travis_fold:start:test_returnn_as_framework_TaskSystem']) subprocess.check_call([py, os.path.abspath('tests/returnn-as-framework.py'), 'test_TaskSystem_Pickler()'], cwd='/') subprocess.check_call(['echo', 'tr...
@unittest.skipIf((not tf), 'no TF') def test_returnn_as_framework_old_style_crnn_TFUtil(): "\n Check that old-style `import crnn.TFUtil` works.\n\n It's not so much about TFUtil, it also could be some other module.\n It's about the old-style module names.\n This is the logic in __old_mod_loader__.\n ...
@unittest.skipIf((not tf), 'no TF') def test_returnn_as_framework_old_style_TFUtil(): '\n Check that old-style `import TFUtil` works.\n See also :func:`test_returnn_as_framework_old_style_crnn_TFUtil`.\n ' import subprocess subprocess.check_call(['echo', 'travis_fold:start:test_returnn_as_framewo...
class CLibAtForkDemo(): def __init__(self): self._load_lib() def _load_lib(self): from returnn.util.basic import NativeCodeCompiler native = NativeCodeCompiler(base_name='test_fork_exec', code_version=1, code=c_code_at_fork_demo, is_cpp=False, ld_flags=['-lpthread']) self._li...
def demo_hello_from_fork(): print('Hello.') sys.stdout.flush() clib_at_fork_demo.set_magic_number(3) clib_at_fork_demo.register_hello_from_child() clib_at_fork_demo.register_hello_from_fork_prepare() pid = os.fork() if (pid == 0): print('Hello from child after fork.') sys.e...
def demo_start_subprocess(): print('Hello.') sys.stdout.flush() clib_at_fork_demo.set_magic_number(5) clib_at_fork_demo.register_hello_from_child() clib_at_fork_demo.register_hello_from_fork_prepare() from subprocess import check_call check_call('echo Hello from subprocess.', shell=True) ...
def run_demo_check_output(name): '\n :param str name: e.g. "demo_hello_from_fork"\n :return: lines of stdout of the demo\n :rtype: list[str]\n ' from subprocess import check_output output = check_output([sys.executable, __file__, name]) return output.decode('utf8').splitlines()
def filter_demo_output(ls): '\n :param list[str] ls:\n :rtype: list[str]\n ' ls = [l for l in ls if (not l.startswith('Executing: '))] ls = [l for l in ls if (not l.startswith('Compiler call: '))] ls = [l for l in ls if (not l.startswith('loaded lib: '))] ls = [l for l in ls if (not l.sta...
def test_demo_hello_from_fork(): ls = run_demo_check_output('demo_hello_from_fork') pprint(ls) ls = filter_demo_output(ls) pprint(ls) assert_equal(set(ls), {'Hello from child after fork.', 'Hello from child atfork, magic number 3.', 'Hello from atfork prepare, magic number 3.', 'Hello from parent ...
def test_demo_start_subprocess(): ls = run_demo_check_output('demo_start_subprocess') pprint(ls) ls = filter_demo_output(ls) pprint(ls) assert ('Hello from subprocess.' in ls) import platform print('Python impl:', platform.python_implementation()) print('Python version:', sys.version_i...
def patched_check_demo_start_subprocess(): '\n Just like test_demo_start_subprocess(), but here we assert that no atfork handlers are executed.\n ' assert_equal(os.environ.get('__RETURNN_ATFORK_PATCHED'), '1') ls = run_demo_check_output('demo_start_subprocess') pprint(ls) ls = filter_demo_ou...