code stringlengths 17 6.64M |
|---|
def rf_module_to_pt_module(rf_module: rf.Module, *, aux_params_as_buffers: bool=True) -> torch.nn.Module:
"\n :param rf_module: RF module\n :param aux_params_as_buffers: whether to map RF auxiliary parameters to PyTorch buffers,\n otherwise to normal parameters, i.e. they occur in model.named_paramet... |
class _PTModuleAsRFModule(rf.Module):
def __init__(self, pt_module: torch.nn.Module):
super().__init__()
self._pt_module = pt_module
for (name, pt_param) in pt_module.named_parameters(recurse=False):
rf_param = rf.Parameter(raw_tensor=pt_param, dims=[Dim(d) for d in pt_param.s... |
class _RFModuleAsPTModule(torch.nn.Module):
def __init__(self, rf_module: rf.Module, *, aux_params_as_buffers: bool=True):
super().__init__()
self._rf_module = rf_module
self._aux_params_as_buffers = aux_params_as_buffers
self._is_initializing = True
for (name, rf_param) i... |
def squared_difference(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
'\n :param a:\n :param b:\n :return: (a - b) ** 2\n '
return torch.square((a - b))
|
def _init_optimizer_classes_dict():
'\n Initializes a global dictionary with all optimizers available in PyTorch.\n '
global _OptimizerClassesDictInitialized
if _OptimizerClassesDictInitialized:
return
_OptimizerClassesDictInitialized = True
for (name, cls) in list(vars(torch.optim).... |
def get_optimizer_class(class_name) -> Type[torch.optim.Optimizer]:
'\n :param str|()->torch.optim.Optimizer|type[torch.optim.Optimizer] class_name:\n Optimizer data, e.g. "adam", torch.optim.Adam...\n :return: Optimizer class\n '
_init_optimizer_classes_dict()
if isinstance(class_name, ty... |
def _get_class_init_kwargs(optim_class):
'\n Obtains the keyword arguments of the class provided as parameter that the user can add to their optimizer.\n\n :param type[torch.optim.Optimizer] optim_class: Optimizer class.\n :return: Keyword arguments of the provided class.\n :rtype: List[str]\n '
... |
class Updater(object):
'\n Wraps a torch.optim.Optimizer, and extends it by some further functionality.\n '
def __init__(self, *, config, network, device, initial_learning_rate=1.0):
'\n :param returnn.config.Config config: config defining the training conditions.\n :param torch.n... |
def _wrap_user_blacklist_wd_modules(mods: Sequence[Union[(str, Type[rf.Module], Type[torch.nn.Module])]]) -> Tuple[(type, ...)]:
assert isinstance(mods, (list, tuple)), f'invalid blacklist_weight_decay_modules {mods!r}'
res = []
for mod in mods:
if isinstance(mod, str):
assert (mod.sta... |
def gradient_noise_(params: Iterable[torch.nn.Parameter], std: float):
'\n Add gradient noise to parameters, using a truncated normal distribution.\n '
(a, b) = (((- 2) * std), (2 * std))
for param in params:
if (param.requires_grad and (param.grad is not None)):
noise = torch.em... |
def print_available_devices(*, file: Optional[TextIO]=None):
'\n Print available devices, GPU (CUDA or other), etc.\n\n :param file: where to print to. stdout by default\n '
if (file is None):
file = sys.stdout
cuda_visible_devs = None
if ('CUDA_VISIBLE_DEVICES' in os.environ):
... |
def print_using_cuda_device_report(dev: Union[(str, torch.device)], *, file: Optional[TextIO]=None):
'\n Theano and TensorFlow print sth like: Using gpu device 2: GeForce GTX 980 (...)\n Print in a similar format so that some scripts which grep our stdout work just as before.\n '
if (file is None):
... |
def diagnose_no_gpu() -> List[str]:
'\n Diagnose why we have no GPU.\n Print to stdout, but also prepare summary strings.\n\n :return: summary strings\n '
res = []
print('CUDA_VISIBLE_DEVICES:', os.environ.get('CUDA_VISIBLE_DEVICES', None))
print('LD_LIBRARY_PATH:', os.environ.get('LD_LIBR... |
class _ScaledGradient(torch.autograd.Function):
@staticmethod
def forward(ctx, x: torch.Tensor, scale: float) -> torch.Tensor:
ctx.scale = scale
return x
@staticmethod
def backward(ctx, grad_output):
return ((grad_output * ctx.scale), None)
|
def scaled_gradient(x: torch.Tensor, scale: float) -> torch.Tensor:
'\n :param x:\n :param scale:\n :return: just x, however, in backward pass, the gradient is scaled by the given factor\n '
return _ScaledGradient.apply(x, scale)
|
class _ScaledGradientExt(torch.autograd.Function):
@staticmethod
def forward(ctx, x: torch.Tensor, scale: Union[(float, torch.Tensor)]=1.0, shift: Optional[Union[(float, torch.Tensor)]]=None, scale_shift_by_sum_over_axis: Optional[int]=None):
ctx.scale = scale
ctx.shift = shift
ctx.sc... |
def scaled_gradient_ext(x: torch.Tensor, *, scale: Union[(float, torch.Tensor)]=1.0, shift: Optional[Union[(float, torch.Tensor)]]=None, scale_shift_by_sum_over_axis: Optional[int]=None):
'\n :param x:\n :param scale: will scale gradient by this value\n :param shift: will shift gradient by this value\n ... |
def parse_py_statement(line):
'\n Parse Python statement into tokens.\n Note that this is incomplete.\n It should be simple and fast and just barely enough for what we need here.\n\n Reference:\n https://docs.python.org/3/reference/lexical_analysis.html\n\n :param str line:\n :return: yields ... |
def parse_py_statements(source_code):
'\n :param str source_code:\n :return: via :func:`parse_py_statement`\n :rtype: typing.Iterator[typing.Tuple[str,str]]\n '
for line in source_code.splitlines():
for t in parse_py_statement(line):
(yield t)
|
def grep_full_py_identifiers(tokens):
'\n :param typing.Iterable[(str,str)] tokens:\n :rtype: typing.Iterator[str]\n '
global py_keywords
tokens = list(tokens)
i = 0
while (i < len(tokens)):
(token_type, token) = tokens[i]
i += 1
if (token_type != 'id'):
... |
def set_linecache(filename, source):
'\n The :mod:`linecache` module has some cache of the source code for the current source.\n Sometimes it fails to find the source of some files.\n We can explicitly set the source for some filename.\n\n :param str filename:\n :param str source:\n :return: not... |
def simple_debug_shell(globals, locals):
'\n :param dict[str] globals:\n :param dict[str] locals:\n :return: nothing\n '
try:
import readline
except ImportError:
pass
compile_string_fn = '<simple_debug_shell input>'
while True:
try:
s = raw_input('> ... |
def debug_shell(user_ns, user_global_ns, traceback=None, execWrapper=None):
'\n Spawns some interactive shell. Tries to use IPython if available.\n Falls back to :func:`pdb.post_mortem` or :func:`simple_debug_shell`.\n\n :param dict[str] user_ns:\n :param dict[str] user_global_ns:\n :param tracebac... |
def output_limit():
'\n :return: num chars\n :rtype: int\n '
return 300
|
def fallback_findfile(filename):
'\n :param str filename:\n :return: try to find the full filename, e.g. in modules, etc\n :rtype: str|None\n '
mods = [m for m in list(sys.modules.values()) if (m and getattr(m, '__file__', None) and (filename in m.__file__))]
if (len(mods) == 0):
retur... |
def is_source_code_missing_brackets(source_code, prioritize_missing_open=False):
'\n We check whether this source code snippet (e.g. one line) is complete/even w.r.t. opening/closing brackets.\n\n :param str source_code:\n :param bool prioritize_missing_open: once we found any missing open bracket, direc... |
def is_source_code_missing_open_brackets(source_code):
'\n We check whether this source code snippet (e.g. one line) is complete/even w.r.t. opening/closing brackets.\n\n :param str source_code:\n :return: whether there are missing open brackets.\n E.g. this would mean that you might want to inclu... |
def get_source_code(filename, lineno, module_globals=None):
'\n :param str filename:\n :param int lineno:\n :param dict[str]|None module_globals:\n :return: source code of that line (including newline)\n :rtype: str\n '
import linecache
linecache.checkcache(filename)
source_code = li... |
def str_visible_len(s):
'\n :param str s:\n :return: len without escape chars\n :rtype: int\n '
import re
s = re.sub('[\x1b\x9b][\\[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-PRZcf-nqry=><]', '', s)
return len(s)
|
def add_indent_lines(prefix, s):
'\n :param str prefix:\n :param str s:\n :return: s with prefix indent added to all lines\n :rtype: str\n '
if (not s):
return prefix
prefix_len = str_visible_len(prefix)
lines = s.splitlines(True)
return ''.join(([(prefix + lines[0])] + [(('... |
def get_indent_prefix(s):
'\n :param str s:\n :return: the indent spaces of s\n :rtype: str\n '
return s[:(len(s) - len(s.lstrip()))]
|
def get_same_indent_prefix(lines):
'\n :param list[] lines:\n :rtype: str|None\n '
if (not lines):
return ''
prefix = get_indent_prefix(lines[0])
if (not prefix):
return ''
if all([line.startswith(prefix) for line in lines]):
return prefix
return None
|
def remove_indent_lines(s):
'\n :param str s:\n :return: remove as much indentation as possible\n :rtype: str\n '
if (not s):
return ''
lines = s.splitlines(True)
prefix = get_same_indent_prefix(lines)
if (prefix is None):
return ''.join([line.lstrip() for line in lines... |
def replace_tab_indent(s, replace=' '):
'\n :param str s: string with tabs\n :param str replace: e.g. 4 spaces\n :rtype: str\n '
prefix = get_indent_prefix(s)
return (prefix.replace('\t', replace) + s[len(prefix):])
|
def replace_tab_indents(s, replace=' '):
'\n :param str s: multi-line string with tabs\n :param str replace: e.g. 4 spaces\n :rtype: str\n '
lines = s.splitlines(True)
return ''.join([replace_tab_indent(line, replace) for line in lines])
|
def to_bool(s, fallback=None):
'\n :param str s: str to be converted to bool, e.g. "1", "0", "true", "false"\n :param T fallback: if s is not recognized as a bool\n :return: boolean value, or fallback\n :rtype: bool|T\n '
if (not s):
return fallback
s = s.lower()
if (s in ['1', ... |
class Color():
'\n Helper functions provided to perform terminal coloring.\n '
ColorIdxTable = {k: i for (i, k) in enumerate(['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'])}
@classmethod
def get_global_color_enabled(cls):
'\n :rtype: bool\n '
... |
class DomTerm():
'\n DomTerm (https://github.com/PerBothner/DomTerm/) is a terminal emulator\n with many extended escape codes, such as folding text away, or even generic HTML.\n We can make use of some of these features (currently just folding text).\n '
_is_domterm = None
@classmethod
d... |
def is_at_exit():
'\n Some heuristics to figure out whether this is called at a stage where the Python interpreter is shutting down.\n\n :return: whether the Python interpreter is currently in the process of shutting down\n :rtype: bool\n '
if (_threading_main_thread is not None):
if (not ... |
class _OutputLinesCollector():
def __init__(self, color):
'\n :param Color color:\n '
self.color = color
self.lines = []
self.dom_term = (DomTerm() if DomTerm.is_domterm() else None)
def __call__(self, s1, s2=None, **kwargs):
'\n Adds to self.line... |
def format_tb(tb=None, limit=None, allLocals=None, allGlobals=None, withTitle=False, with_color=None, with_vars=None):
'\n :param types.TracebackType|types.FrameType|StackSummary tb: traceback. if None, will use sys._getframe\n :param int|None limit: limit the traceback to this number of frames. by default,... |
def print_tb(tb, file=None, **kwargs):
'\n :param types.TracebackType|types.FrameType|StackSummary tb:\n :param io.TextIOBase|io.StringIO|typing.TextIO|None file: stderr by default\n :return: nothing, prints to ``file``\n '
if (file is None):
file = sys.stderr
for line in format_tb(tb=... |
def better_exchook(etype, value, tb, debugshell=False, autodebugshell=True, file=None, with_color=None, with_preamble=True):
'\n Replacement for sys.excepthook.\n\n :param etype: exception type\n :param value: exception value\n :param tb: traceback\n :param bool debugshell: spawn a debug shell at t... |
def dump_all_thread_tracebacks(exclude_thread_ids=None, file=None):
'\n Prints the traceback of all threads.\n\n :param set[int]|list[int]|None exclude_thread_ids: threads to exclude\n :param io.TextIOBase|io.StringIO|typing.TextIO|None file: output stream\n '
if (exclude_thread_ids is None):
... |
def get_current_frame():
'\n :return: current frame object (excluding this function call)\n :rtype: types.FrameType\n\n Uses sys._getframe if available, otherwise some trickery with sys.exc_info and a dummy exception.\n '
if hasattr(sys, '_getframe'):
return sys._getframe(1)
try:
... |
def get_func_str_from_code_object(co, frame=None):
'\n :param types.CodeType co:\n :param types.FrameType|None frame: if given, might provide a faster way to get the function name\n :return: co.co_name as fallback, but maybe sth better like the full func name if possible\n :rtype: str\n '
f = g... |
def get_func_from_code_object(co, frame=None):
'\n :param types.CodeType co:\n :param types.FrameType|None frame: if given, might provide a faster way to get the function name\n :return: function, such that ``func.__code__ is co``, or None\n :rtype: types.FunctionType\n\n This is CPython specific (... |
def _get_loaded_module_from_filename(filename):
'\n Like inspect.getmodule but faster.\n\n :param str filename:\n :rtype: types.ModuleType|Any|None\n '
if (filename.endswith('.pyc') or filename.endswith('.pyo')):
filename = filename[:(- 1)]
if (filename in _loaded_module_from_filename_... |
def iter_traceback(tb=None, enforce_most_recent_call_first=False):
'\n Iterates a traceback of various formats:\n - traceback (types.TracebackType)\n - frame object (types.FrameType)\n - stack summary (traceback.StackSummary)\n\n :param types.TracebackType|types.FrameType|StackSummary|None tb... |
class ExtendedFrameSummary(FrameSummary):
'\n Extends :class:`FrameSummary` by ``self.tb_frame``.\n '
def __init__(self, frame, **kwargs):
super(ExtendedFrameSummary, self).__init__(**kwargs)
self.tb_frame = frame
|
class DummyFrame():
'\n This class has the same attributes as a code and a frame object\n and is intended to be used as a dummy replacement.\n '
@classmethod
def from_frame_summary(cls, f):
'\n :param FrameSummary f:\n :rtype: DummyFrame\n '
return cls(filena... |
def _StackSummary_extract(frame_gen, limit=None, lookup_lines=True, capture_locals=False):
'\n Replacement for :func:`StackSummary.extract`.\n\n Create a StackSummary from a traceback or stack object.\n Very simplified copy of the original StackSummary.extract().\n We want always to capture locals, th... |
def install():
'\n Replaces sys.excepthook by our better_exchook.\n '
sys.excepthook = better_exchook
|
def replace_traceback_format_tb():
'\n Replaces these functions from the traceback module by our own:\n\n - traceback.format_tb\n - traceback.StackSummary.format\n - traceback.StackSummary.extract\n\n Note that this kind of monkey patching might not be safe under all circumstances\n and is not o... |
class StandardBytePairEncoder():
'\n Code is partly taken from subword-nmt/apply_bpe.py.\n Author: Rico Sennrich, code under MIT license.\n\n Use operations learned with learn_bpe.py to encode a new text.\n The text will not be smaller, but use only a fixed vocabulary, with rare words\n encoded as ... |
class PrefixTree():
'\n Prefix tree / trie.\n This class represents both a single node and the tree.\n '
def __init__(self, prefix='', root=None):
'\n :param str prefix:\n :param PrefixTree|None root:\n '
self.prefix = prefix
self.arcs = {}
self.f... |
class Hyp():
'\n Represents a hypothesis in the search.\n '
def __init__(self, bpe_sym_history, cur_node):
'\n :param list[str] bpe_sym_history:\n :param PrefixTree cur_node:\n '
self.bpe_sym_history = bpe_sym_history
self.cur_node = cur_node
|
class CharSyncSearch():
'\n Covers the search hyps and the search itself.\n '
def __init__(self, bpe, word, word_pos=0):
'\n :param PrefixTree bpe:\n :param str word:\n :param int word_pos:\n '
self.bpe = bpe
self.word = word
self.word_pos = w... |
class HypInPos():
'\n Represents a hypothesis in the search.\n '
def __init__(self, bpe_sym_history, cur_node, pos):
'\n :param list[str] bpe_sym_history:\n :param PrefixTree cur_node:\n :param int pos:\n '
self.bpe_sym_history = bpe_sym_history
self.... |
class DepthFirstSearch():
'\n Depth-first search.\n '
def __init__(self, bpe, word, sampler=None):
'\n :param PrefixTree bpe:\n :param str word:\n :param (()->bool)|None sampler:\n '
self.bpe = bpe
self.word = word
self.sampler = sampler
... |
class SamplingBytePairEncoder():
'\n Will randomly sample from any possible BPE split.\n '
def __init__(self, labels, breadth_prob, rnd, unknown_label=None):
'\n :param list[str] labels: vocab\n :param float breadth_prob: 1.0 will lead to breadth-first search, 0.0 to depth-first s... |
def _demo():
import sys
import os
my_dir = os.path.dirname(os.path.abspath(__file__))
root_dir = os.path.dirname(os.path.dirname(my_dir))
assert os.path.exists(('%s/returnn/__init__.py' % root_dir))
sys.path.insert(0, root_dir)
from returnn.util import better_exchook
better_exchook.ins... |
def auto_exclude_all_new_threads(func):
'\n :param T func:\n :return: func wrapped\n :rtype: T\n '
def wrapped(*args, **kwargs):
'\n :param args:\n :param kwargs:\n :return:\n '
old_threads = set(sys._current_frames().keys())
res = func(*args, *... |
def dump_all_thread_tracebacks(exclude_thread_ids=None, exclude_self=False):
'\n :param set[int] exclude_thread_ids:\n :param bool exclude_self:\n '
if (exclude_thread_ids is None):
exclude_thread_ids = set()
from returnn.util.better_exchook import print_tb
import threading
if exc... |
def setup_warn_with_traceback():
'\n Installs some hook for ``warnings.showwarning``.\n '
import warnings
from returnn.util.better_exchook import print_tb
def warn_with_traceback(message, category, filename, lineno, file=None, line=None):
'\n :param message:\n :param categ... |
def init_better_exchook():
'\n Installs our own ``sys.excepthook``, which uses :mod:`better_exchook`,\n but adds some special handling for the main thread.\n '
from returnn.util.better_exchook import better_exchook
def excepthook(exc_type, exc_obj, exc_tb):
'\n :param exc_type:\n ... |
def format_signum(signum):
'\n :param int signum:\n :return: string "signum (signame)"\n :rtype: str\n '
return ('%s (%s)' % (signum, signum_to_signame.get(signum, 'unknown')))
|
def signal_handler(signum, frame):
'\n Prints a message on stdout and dump all thread stacks.\n\n :param int signum: e.g. signal.SIGUSR1\n :param frame: ignored, will dump all threads\n '
print(('Signal handler: got signal %s' % format_signum(signum)))
dump_all_thread_tracebacks()
|
def install_signal_handler_if_default(signum, exceptions_are_fatal=False):
'\n :param int signum: e.g. signal.SIGUSR1\n :param bool exceptions_are_fatal: if True, will reraise any exceptions. if False, will just print a message\n :return: True iff no exception, False otherwise. not necessarily that we re... |
def _get_native_signal_handler_lib_filename() -> str:
'\n :return: path to our native_signal_handler lib. see :func:`install_native_signal_handler`\n '
global _native_signal_handler_lib_filename
if _native_signal_handler_lib_filename:
return _native_signal_handler_lib_filename
from retur... |
def install_native_signal_handler(*, reraise_exceptions: bool=False):
'\n Installs some own custom C signal handler.\n '
try:
import ctypes
lib = ctypes.CDLL(_get_native_signal_handler_lib_filename())
lib.install_signal_handler.return_type = None
lib.install_signal_handle... |
def install_lib_sig_segfault():
'\n Installs libSegFault (common on Unix/Linux).\n '
try:
os.environ.setdefault('SEGFAULT_SIGNALS', 'all')
import ctypes
import ctypes.util
libfn = ctypes.util.find_library('SegFault')
assert libfn, 'libSegFault not found'
c... |
def init_faulthandler(sigusr1_chain=False):
'\n Maybe installs signal handlers, SIGUSR1 and SIGUSR2 and others.\n If no signals handlers are installed yet for SIGUSR1/2, we try to install our own Python handler.\n This also tries to install the handler from the fauldhandler module,\n esp for SIGSEGV a... |
@auto_exclude_all_new_threads
def init_ipython_kernel():
'\n Runs IPython in some background kernel, where you can connect to.\n '
try:
import IPython.kernel.zmq.ipkernel
from IPython.kernel.zmq.ipkernel import Kernel
from IPython.kernel.zmq.heartbeat import Heartbeat
fro... |
def init_cuda_not_in_main_proc_check():
'\n Installs some hook to Theano which checks that CUDA is only used in the main proc.\n '
import theano.sandbox.cuda as cuda
if (cuda.use.device_number is not None):
print(('CUDA already initialized in proc %i' % os.getpid()))
return
use_o... |
def debug_shell(user_ns: Optional[Dict[(str, Any)]]=None, user_global_ns: Optional[Dict[(str, Any)]]=None, exit_afterwards: bool=True):
'\n Provides some interactive Python shell.\n Uses IPython if possible.\n Wraps to ``better_exchook.debug_shell``.\n\n :param user_ns:\n :param user_global_ns:\n ... |
def literal_eval(s):
'\n This can be used as an alternative to ``ast.literal_eval``.\n In contrast to ``ast.literal_eval``, it also accepts bytes,\n and it should be ~5x faster.\n\n :param str|bytes s:\n :return: any object\n '
raw_pickle = py_to_pickle(s)
return pickle.loads(raw_pickle)... |
def py_to_pickle(s):
'\n :param str|bytes s:\n :rtype: bytes\n '
if isinstance(s, bytes):
in_bytes = s
else:
assert isinstance(s, str)
in_bytes = s.encode('utf8')
in_ = ctypes.create_string_buffer(in_bytes)
in_len = len(in_bytes)
out_len = (in_len + 1000)
o... |
def _get_native_lib_filename():
'\n :return: path to our patch_atfork lib. see :func:`maybe_restart_returnn_with_atfork_patch`\n :rtype: str\n '
global _native_lib_filename
if _native_lib_filename:
return _native_lib_filename
native = NativeCodeCompiler(base_name='pytopickle', code_ve... |
def next_power_of_two(n: int) -> int:
'next power of two, >= n'
return (2 ** int((n - 1)).bit_length())
|
class NativeCodeCompiler(object):
'\n Helper class to compile native C/C++ code on-the-fly.\n '
CacheDirName = 'returnn_native'
CollectedCompilers = None
def __init__(self, base_name, code_version, code, is_cpp=True, c_macro_defines=None, ld_flags=None, include_paths=(), include_deps=None, stat... |
def pprint(obj: Any, *, file=None, prefix='', postfix='', line_prefix='', line_postfix='\n') -> None:
'\n Pretty-print a Python object.\n '
if (file is None):
file = sys.stdout
if (('\n' in line_postfix) and (_type_simplicity_score(obj) <= _type_simplicity_limit)):
prefix = f'{line_p... |
def pformat(obj: Any) -> str:
'\n Pretty-format a Python object.\n '
import io
s = io.StringIO()
pprint(obj, file=s)
return s.getvalue()
|
def _type_simplicity_score(obj: Any, _offset=0.0) -> float:
'\n :param Any obj:\n :param float _offset:\n :return: a score, which is a very rough estimate of len(repr(o)), calculated efficiently\n '
_spacing = 2.0
if isinstance(obj, bool):
return (4.0 + _offset)
if isinstance(obj, ... |
class PyExtModCompiler(NativeCodeCompiler):
'\n Python extension module compiler\n '
CacheDirName = 'returnn_py_ext_mod_cache'
def __init__(self, include_paths=(), **kwargs):
py_compile_vars = sysconfig.get_config_vars()
include_paths = (list(include_paths) + [py_compile_vars['INCLU... |
@dataclass
class ResultWithReason(Generic[T]):
'\n This is a wrapper class for a result value, which can also have a reason.\n '
result: T
reason: Optional[str] = None
|
class SharedMem():
class ShmException(Exception):
pass
class CCallException(ShmException):
pass
if (sys.platform != 'win32'):
import ctypes
import ctypes.util
libc_so = ctypes.util.find_library('c')
libc = ctypes.CDLL(libc_so, use_errno=True)
shm_k... |
def next_power_of_two(n):
return (2 ** int((n - 1)).bit_length())
|
class SharedNumpyArray():
'\n This class provides a way to create Numpy arrays in shared memory.\n It adds some logic to mark whether some shared memory segment can be reused\n - that is when the client marks it as unused.\n\n Note that there are a few similar Python modules:\n https://pypi.pytho... |
def attrChain(base, *attribs, **kwargs):
default = kwargs.get('default', None)
obj = base
for attr in attribs:
if (obj is None):
return default
obj = getattr(obj, attr, None)
if (obj is None):
return default
return obj
|
def funcCall(attrChainArgs, args=()):
f = attrChain(*attrChainArgs)
return f(*args)
|
def get_func_closure(f):
return f.__closure__
|
def get_func_tuple(f):
return (f.__code__, f.__globals__, f.__name__, f.__defaults__, f.__closure__)
|
def makeFuncCell(value):
return get_func_closure((lambda : value))[0]
|
def getModuleDict(modname, path=None):
'\n :param str modname: such that "import <modname>" would work\n :param list[str] path: sys.path\n :return: the dict of the mod\n :rtype: dict[str]\n '
try:
mod = import_module(modname)
except ImportError:
assert path
for p in ... |
def getModNameForModDict(obj):
"\n :type obj: dict\n :rtype: str | None\n :returns The module name or None. It will not return '__main__' in any case\n because that likely will not be the same in the unpickling environment.\n Also see: https://stackoverflow.com/questions/56171796/\n "
if ('_... |
def getNormalDict(d):
'\n :type d: dict[str] | dictproxy\n :rtype: dict[str]\n It also removes getset_descriptor. New-style classes have those.\n '
r = {}
for (k, v) in d.items():
if isinstance(v, types.GetSetDescriptorType):
continue
r[k] = v
return r
|
def assign_obj_attribs(obj, d: Dict[(str, Any)]):
'\n :param obj:\n :param d:\n :return: obj\n\n Note that obj.__dict__.update(d) does not always work,\n e.g. when obj is a type (then obj.__dict__ is a readonly mappingproxy).\n '
for (k, v) in d.items():
setattr(obj, k, v)
return... |
def make_numpy_ndarray_fromstring(s, dtype, shape):
return numpy.fromstring(s, dtype=dtype).reshape(shape)
|
def use_shared_mem_for_numpy_array(obj):
assert isinstance(obj, numpy.ndarray)
if (obj.shape == ()):
return False
if isinstance(obj.base, SharedNumpyArray):
assert obj.base.is_in_use()
return True
if (not SharedMemNumpyConfig['enabled']):
return False
return (obj.nb... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.